this is my code, it seems right to me! i don't know why it keeps saying this:
"Cannot instantiate the type Iterator"
this is the servlet:
package uges.servlets;
import jess.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Iterator;
public class Catalog extends BaseServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
checkInitialized();
try {
String customerId =
(String) request.getParameter("customerId");
if (customerId == null || customerId.length() == 0) {
dispatch(request, response, "/index.html");
return;
}
request.getSession().invalidate();
HttpSession session = request.getSession();
session.setAttribute("customerId", customerId);
session.setAttribute("orderNumber",
String.valueOf(getNewOrderNumber()));
ServletContext servletContext = getServletContext();
Rete engine = (Rete) servletContext.getAttribute("engine");
Iterator result =
engine.runQuery("all-products", new ValueVector());
request.setAttribute("queryResult", result);
} catch (JessException je) {
throw new ServletException(je);
}
dispatch(request, response, "/catalog.jsp");
}
this is the dispatch method, it 's in a servlet called BaseServlet:
protected void dispatch(HttpServletRequest request,
HttpServletResponse response,
String page)
throws IOException, ServletException {
ServletContext servletContext = getServletContext();
RequestDispatcher dispatcher =
servletContext.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
and this the JSP code:
<HTML>
<%# page import="jess.*" %>
<jsp:useBean id="queryResult" class="java.util.Iterator" scope="request"/>
the error is about the java.util.Iterator in the class type of useBean tag!
the exception says : The value for the useBean class attribute java.util.Iterator is invalid
any help please ..
Thanks in advance!
java.util.Iterator is an Interface, not a Class. You want
<jsp:useBean id="queryResult" type="java.util.Iterator" scope="request"/>
To confirm this I used the following test code:
package org.apache.markt.so;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Q001Servlet")
public class Q001Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
request.setAttribute("list", list.iterator());
RequestDispatcher rd = request.getRequestDispatcher("/so/q001.jsp");
rd.forward(request, response);
}
}
With the following /so/q001.jsp
<html>
<jsp:useBean id="list" type="java.util.Iterator" scope="request" />
<body>
<p><%=list.next()%></p>
</body>
</html>
This was using HEAD from the latest development branch but you'll see the same results with the latest Tomcat 7 release.
Here is a JSP that demonstrates my idea.
<%# page import="java.util.*" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
//for testing
List<String> engineList = new ArrayList<String>();
engineList.add("zero");
engineList.add("one");
engineList.add("two");
engineList.add("three");
Iterator<String> result = engineList.iterator();
// create a list from engine result
List<String> list = new ArrayList<String>();
while(result.hasNext())list.add(result.next());
request.setAttribute("list", list);
%>
<html>
<body>
Complete list is${list}
The first item is ${list[0]}.
The second item is ${list[1]}.
If you don't know how many items there are in result, then use JSTL
<c:forEach var="item" items="${list}" >
${item}
</c:forEach>
</body>
</html>
Related
I am trying a simple movie recommender by referring a short video here- https://www.youtube.com/watch?v=63k560Livmg . What I am trying diff is instead of console , I want recommendations to be displayed on browser so I am using servlets. But the problem is when i input a value(user id ) in my form, blank screen is shown . Please help what I am doing wrong. Dataset from here- https://mahout.apache.org/users/recommender/userbased-5-minutes.html. Refer screenshot attached for web.xml and hierarchy.
index.jsp
<html>
<body>
<h2>Hello World!</h2>
<form action="demo" method="post">
loginID:<input type="text" name="name"/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
demo.java- servlet for collecting user value and display result.
package com.issac;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
/**
* Servlet implementation class demo
*/
public class demo extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public demo() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #throws IOException
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
// TODO Auto-generated method stub
String n = request.getParameter("name");
int k = Integer.parseInt(n);
PrintWriter out = response.getWriter();
List<RecommendedItem> recommendations = new ArrayList<RecommendedItem> ();
try {
recommendations = App.getRecommend(k);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (RecommendedItem recommendation : recommendations) {
out.println(recommendation);
}
}}
app.java - logic for generating recommendations
package com.issac;
import java.io.File;
import java.util.List;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.ThresholdUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.UserBasedRecommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
public class App
{
public static List<RecommendedItem> getRecommend(int k) throws Exception
{
DataModel model = new FileDataModel(new File("data/dataset.csv"));
UserSimilarity similarity = new PearsonCorrelationSimilarity(model);
UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, similarity, model);
UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity);
List<RecommendedItem> recommendations = recommender.recommend(k, 3);
return recommendations;
}
}
stack trace of eclipse console-
INFO: Server startup in 15288 ms
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
java.io.FileNotFoundException: data\dataset.csv
at org.apache.mahout.cf.taste.impl.model.file.FileDataModel.<init> (FileDataModel.java:182)
at org.apache.mahout.cf.taste.impl.model.file.FileDataModel.<init>(FileDataModel.java:169)
at org.apache.mahout.cf.taste.impl.model.file.FileDataModel.<init>(FileDataModel.java:149)
at com.issac.App.getRecommend(App.java:24)
at com.issac.demo.doPost(demo.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilt erChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Within a JEE application, files should be read through the getResourceAsStream method:
try(InputStream input=getClass().getClassLoader().getResourceAsStream("data/dataset.csv")){
...
}
And data folder should be placed immediately within src/main/resources.
In your case, one more complication exists: Due to the lack of a constructor of DataModel from an InputStream, we need to save first the contents of the inputStream to a (temporary) file:
try(InputStream input=getClass().getClassLoader().getResourceAsStream("data/dataset.csv")){
// Copy the contents of the inputStream to a File, to fix the constructor FileDataModel(file):
File tmp=File.createTempFile("model-", "");
tmp.deleteOnExit();
InputStream input=new ByteArrayInputStream("enero".getBytes("ISO-8859-1"));
Files.copy(input, tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
DataModel model = new FileDataModel(new File("data/dataset.csv"));
...
}
So this is how it worked out for me. After getting FileNotFound exception,I tried this->
ClassLoader classLoader = App.class.getClassLoader();
DataModel model = new FileDataModel(new File(classLoader.getResource("data/dataset.csv").getFile()));
instead of
DataModel model = new FileDataModel(new File("data/dataset.csv"));
I don't have thorough knowledge about why it worked just found it on internet, has something to do with class FileDataModel's parameters. Anyone who can give explanation is welcome.
My code opens a index.html file in a webView but failed to open the css and js files, the errors I am getting are:
E/SysUtils: ApplicationContext is null in ApplicationStatus
E/chromium: [ERROR:browser_gpu_channel_host_factory.cc(258)] Failed to init browser shader disk cache.
E/libEGL: validate_display:255 error 3008 (EGL_BAD_DISPLAY)
all the files referenced to in the <head> of the index.html are located in the assets folder as siblings of index.html
package au.com.totalcareauto.webappandroid1;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
WebView wv = (WebView) findViewById(R.id.wv);
wv.setWebViewClient(new WebViewClient());
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
ws.setAllowFileAccess(true);
String summary = null;
String path = "file:///assets/";
try {
summary = getStringFromFile("index.html");
} catch (Exception e) {
e.printStackTrace();
}
wv.loadDataWithBaseURL(path ,summary,"text/html","utf-8",null);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
}
public String getStringFromFile(String filePath) throws Exception {
File fl = new File(filePath);
String ret = convertStreamToString(this.getAssets().open(filePath));
return ret;
}
}
<head>
<meta charset="UTF-8">
<title>RRR</title>
<link type="text/css" rel="stylesheet" href="jquery.mobile-1.4.5.css"/>
<link type="text/css" rel="stylesheet" href="index.css"/>
<script type="text/javascript" src="jquery-1.11.3.js"></script>
<script type="text/javascript" src="jquery.mobile-1.4.5.js"></script>
<meta name="viewport" content="width=device-width"/>
</head>
The log does not reflect the cause the loading failure.
The issue is you have wrong path:
String path = "file:///assets/";
Which should be:
String path = "file:///android_asset/";
The question is basically the title of the post.
Is there a possibility to hide the hidden files that appear on the CRXDE Lite?
I have a mac and in my CRXDE Lite i can see the .DS_Store files and i don't want to see them.
Why hide them when you can delete them? This simple example is a Servlet. you could run this nightly with an OSGi scheduler.
package com.foo.bar;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import javax.jcr.query.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#SlingServlet(paths={"/bin/deletedsstore"})
public class DeleteDSStoreServlet extends SlingSafeMethodsServlet {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(DeleteDSStoreServlet.class);
private static final String SQL2_QUERY = "SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE([/content]) and NAME() = '.DS_Store'";
private static final int SAVE_THRESHOLD = 100;
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
ResourceResolver resolver = request.getResourceResolver();
Iterator<Resource> resources = resolver.findResources(SQL2_QUERY, Query.JCR_SQL2);
int deleted = 0;
while (resources.hasNext()) {
Resource resource = resources.next();
String path = resource.getPath();
resolver.delete(resource);
log.info("Deleted node: " + path);
deleted++;
if (deleted % SAVE_THRESHOLD == 0) {
resolver.commit();
}
}
if (resolver.hasChanges()) {
resolver.commit();
}
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.write("Deleted " + deleted + " .DS_Store nodes");
}
}
I'm having a web-application that is secured with HTTP-Basic auth.
I also implemented a filter using the ServletRequestListener interface. Now when the filter calls the requestInitialized method, the getUserPrincipal-Method of the request returns null. But when I check the request headers, the authorization-header is set with the encrypted value. Here's the code:
#Override
public void requestInitialized(ServletRequestEvent e) {
HttpServletRequest request = (HttpServletRequest) e.getServletRequest();
//p is null
Principal p = request.getUserPrincipal();
Enumeration<String> enH = request.getHeaders("Authorization");
while (enH.hasMoreElements()) {
String s = enH.nextElement();
System.out.println(s);
//prints.
//Basic c3RhY2tvdmVyZmxvdzpteXBhc3N3b3Jk
}
}
Why is the userprincipal not initialized?
You are likely not setting up the needed security layers for embedded-jetty.
Here's an example found in the Jetty embedded examples source tree.
package org.eclipse.jetty.embedded;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.security.Constraint;
public class SecuredHelloHandler
{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
server.addBean(loginService);
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate( true );
constraint.setRoles(new String[]{"user", "admin"});
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec( "/*" );
mapping.setConstraint( constraint );
Set<String> knownRoles = new HashSet<String>();
knownRoles.add("user");
knownRoles.add("admin");
security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
security.setStrict(false);
// Your Handler (or Servlet) that should be secured
HelloHandler hh = new HelloHandler();
security.setHandler(hh);
server.start();
server.join();
}
}
I solved it by using a Filter instead of a Listener..
#WebFilter(urlPatterns = { "/*" })
public class RequestFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain fChain) throws IOException, ServletException {
HttpServletRequest hReq = (HttpServletRequest) req;
//p is not null anymore
Principal p = hReq.getUserPrincipal();
fChain.doFilter(hReq, res);
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig config) throws ServletException {
}
}
In the below program, the last line in the code is showing an error. df and d cannot be resolved. I used the same logic in a normal Java program and I got the output. Can somebody explain the problem in this.
package com.first;
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AgeCalc extends HttpServlet {
private static final long serialVersionUID = 1L;
public AgeCalc() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//request parameters
String name1=request.getParameter("name1");
try {
DateFormat df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
Date d=df.parse(dob);
}
catch(Exception e){}
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
}
}
d and df variables are defined inside try block and are not visible outside of it. Either declare them outside:
DateFormat df = null;
Date d = null;
try {
df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
d=df.parse(dob);
} catch(Exception e){
}
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
or better, wrap everything in one huge try block:
try {
DateFormat df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
Date d=df.parse(dob);
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
} catch(Exception e){
}
This is basic Java, not really related to servlets. Also you please do something with the exception, at least:
} catch(Exception e){
e.printStackTrace();
}