maven in eclipse giving filenotfound exception for data.csv file - eclipse

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.

Related

InvalidInputException when running a jar exported from Eclipse

I have installed Hadoop 2.6 in centos7 and it's running fine. But when I run a jar exported from Eclipse, it gives the following error:
[root#myspark ~]# hadoop jar fengcount.jar intput output1
17/05/26 21:24:51 INFO client.RMProxy: Connecting to ResourceManager
at myspark/192.168.44.100:8032 17/05/26 21:24:53 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/root/.staging/job_1495765615548_0004 Exception in thread "main" org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://myspark:54310/user/root/intput
at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:321)
at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:264)
at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:385)
at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:302)
at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:319)
at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:197)
at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1297)
at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1294)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1692)
at org.apache.hadoop.mapreduce.Job.submit(Job.java:1294)
at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1315)
at hdfs.hadoop_hdfs.fengcount.main(fengcount.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
The file input/test1.txt actually exists:
[root#myspark ~]# hdfs dfs -ls -R
drwxr-xr-x - root supergroup 0 2017-05-26 21:02 input
-rw-r--r-- 1 root supergroup 16 2017-05-24 01:57 input/test1.txt
My code:
package hdfs.hadoop_hdfs;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class fengcount {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
// TODO Auto-generated method stub
Configuration conf=new Configuration();
String[] otherargs=new GenericOptionsParser(conf,args).getRemainingArgs();
if (otherargs.length!=2) {
System.err.println("Usage:fengcount<int><out>");
System.exit(2);
}
#SuppressWarnings("deprecation")
Job job=new Job(conf, "fengcount");
job.setJarByClass(fengcount.class);
job.setMapperClass(TokerizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherargs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherargs[1]));
System.exit(job.waitForCompletion(true)?0:1);
}
// mapper class
public static class TokerizerMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
#Override
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
// TODO Auto-generated method stub
System.out.println("key=" + key.toString());
System.out.println("value=" + value.toString());
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
//reduce process
public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
#Override
public void reduce(Text key, Iterable<IntWritable> values,
Reducer<Text, IntWritable, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
// TODO Auto-generated method stub
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
//mapreduce process
}
From the error log, I could see hdfs://myspark:54310/user/root/intput, I suspect its incorrect. I guess the path ends with input.
Good luck!

How to change the default folder for uploading file in jboss

I am trying to upload a file, I am trying to change the default location of the uploaded file. How to change this please suggest ?
package Controller;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import requests.Connect;
import display.DisplayLog;
/** * Servlet implementation class ControlServlet
*/
public class ControlServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
boolean result;
private boolean isMultipart;
private String filePath;
private int maxFileSize = 1000 * 1024;
private int maxMemSize = 1000 * 1024;
private File file ;
public ControlServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session=request.getSession();
String userName = request.getParameter("username");
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("audio/mpeg3;audio/x-mpeg-3;video/mpeg;video/x-mpeg;text/xml");
PrintWriter out = response.getWriter( );
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
if (fileName != null) {
fileName = FilenameUtils.getName(fileName);
}
String root = getServletContext().getRealPath("/");
root = "F/images";
File path = new File(root + "/uploads");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(" Prashant File Upload Location is ");
// System.out.println(uploadedFile.getAbsolutePath());
System.out.println("fileName is " +fileName);
System.out.println("root is " + root);
System.out.println("path is " + path);
if(fileName!="")
{
item.write(uploadedFile);
System.out.println(" Prashant File Upload Location 2 is ");
System.out.println(uploadedFile.getAbsolutePath());
out.println("<h1>File Uploaded Successfully....:-)</h1>");
}
else
{
out.println(uploadedFile.getAbsolutePath());
out.println("<h1>File Uploaded Successfully....:-)</h1>");
System.out.println("file not found");
}
}
else
{
String abc = item.getString();
}
}
} catch (FileUploadException e) {
out.println(e);
} catch (Exception e) {
out.println(e);
}
}
else
{
out.println("Not Multipart");
}
System.out.println("print this Prashant" + userName);
session.setAttribute("username",userName);
request.setAttribute("username","prashant");
// RequestDispatcher myDispatch = request.getRequestDispatcher("Index.jsp");
//myDispatch.forward(request, response);
}
}
I am getting this as default folder F:\jboss-4.2.3.GA-jdk6\jboss-4.2.3.GA\bin\ please help i am new to this
Your problem is here:
String root = getServletContext().getRealPath("/");
you are setting the upload path to the containers path, not a default path but the place where the server started from. You can make the upload path anything you want it to be, it depends on your needs and configuration.
You could create a system property with the directory of your choice, you could set it as a dynamic property in a JBoss configuration file (not sure what that would be for JBoss4).

Servlet.service() for servlet [FitbitApiAuthExampleServlet] in context with path [/Webfit]

I'm having a problem.
I'm developing web application in Eclipse IDE and using Tomcat 7.
Everything was working fine, when suddenly my debugger doesn't work anymore as it should and everything collapsed to pieces. I was looking for same errors, but I haven't found soulution yet. Please help me.
I'm getting this error:
SEVERE: Servlet.service() for servlet [FitbitApiAuthExampleServlet] in context with path [/Webfit] threw exception
java.lang.NullPointerException
at java.net.URLEncoder.encode(Unknown Source)
at com.fitbit.api.client.http.OAuth.encode(OAuth.java:254)
at com.fitbit.api.client.http.OAuth.encodeParameters(OAuth.java:233)
at com.fitbit.api.client.http.OAuth.encodeParameters(OAuth.java:217)
at com.fitbit.api.client.http.OAuth.normalizeRequestParameters(OAuth.java:196)
at com.fitbit.api.client.http.OAuth.generateAuthorizationHeader(OAuth.java:85)
at com.fitbit.api.client.http.OAuth.generateAuthorizationHeader(OAuth.java:129)
at com.fitbit.api.client.http.HttpClient.setHeaders(HttpClient.java:522)
at com.fitbit.api.client.http.HttpClient.httpRequest(HttpClient.java:422)
at com.fitbit.api.client.http.HttpClient.get(HttpClient.java:398)
at com.fitbit.api.client.FitbitApiClientAgent.httpGet(FitbitApiClientAgent.java:2563)
at com.fitbit.api.client.FitbitApiClientAgent.httpGet(FitbitApiClientAgent.java:2513)
at com.fitbit.api.client.FitbitApiClientAgent.getLoggedHeartRate(FitbitApiClientAgent.java:1779)
at com.fitbit.web.FitbitApiAuthExampleServlet.doGet(FitbitApiAuthExampleServlet.java:108)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Servlet code:
package com.fitbit.web;
import com.fitbit.api.FitbitAPIException;
import com.fitbit.api.client.*;
import com.fitbit.api.client.service.FitbitAPIClientService;
import com.fitbit.api.common.model.body.Body;
import com.fitbit.api.common.model.body.BodyWithGoals;
import com.fitbit.api.common.model.bp.Bp;
import com.fitbit.api.common.model.heart.Heart;
import com.fitbit.api.common.model.user.UserInfo;
import com.fitbit.api.model.APIResourceCredentials;
import com.fitbit.api.model.FitbitUser;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.joda.time.LocalDate;
import java.io.IOException;
import java.util.Properties;
/**
* Created by IntelliJ IDEA.
* User: Kiryl
* Date: 6/22/11
* Time: 7:05 AM
*/
public class FitbitApiAuthExampleServlet extends HttpServlet {
public static final String OAUTH_TOKEN = "oauth_token";
public static final String OAUTH_VERIFIER = "oauth_verifier";
private FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
private FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
private FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
private String apiBaseUrl;
private String fitbitSiteBaseUrl;
private String exampleBaseUrl;
private String clientConsumerKey;
private String clientSecret;
private FitbitUser fitbitUser = new FitbitUser("-");
private int year = 2012;
private int month = 5;
private int day = 5;
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
Properties properties = new Properties();
properties.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
apiBaseUrl = properties.getProperty("apiBaseUrl");
fitbitSiteBaseUrl = properties.getProperty("fitbitSiteBaseUrl");
exampleBaseUrl = properties.getProperty("exampleBaseUrl").replace("/app", "");
clientConsumerKey = properties.getProperty("clientConsumerKey");
clientSecret = properties.getProperty("clientSecret");
} catch (IOException e) {
throw new ServletException("Exception during loading properties", e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
clientConsumerKey,
clientSecret,
credentialsCache,
entityCache,
subscriptionStore
);
if (request.getParameter("completeAuthorization") != null) {
// Get temporary token and verifier returned by Fitbit from query string
String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
// Fetch user credentials from cache by temporary token from query string
APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);
/*Handle error when there is no record of credentials in cache for the temporary token provided
As implementation of the credentials cache in this example is not persistant,
this error will popup if you restart application, while user's browser will be on Fitbit*/
if (resourceCredentials == null) {
throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
}
// Call method of Fitbit4J to get token credentials only if necessary (they haven't been cached yet)
if (!resourceCredentials.isAuthorized()) {
resourceCredentials.setTempTokenVerifier(tempTokenVerifier); // The verifier token is required in the request to get token credentials
try {
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId())); // get token credentials for user
} catch (FitbitAPIException e) {
throw new ServletException("Unable to finish authorization with Fitbit.", e);
}
}
try {
// get UserInfo
UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
request.setAttribute("userInfo", userInfo);
//get HeartRate
Heart heartInfo = apiClientService.getClient().getLoggedHeartRate(new LocalUserDetail(resourceCredentials.getLocalUserId()), fitbitUser, new LocalDate(year,month,day));
//HeartRate heartAverage = new HeartRate(heartInfo.getTrackerAverage());
request.setAttribute("heartRate", heartInfo);
/*double weight = apiClientService.getClient().getWeight(new LocalUserDetail(resourceCredentials.getLocalUserId()), new FitbitUser("-"), new LocalDate(2012,5,5));
request.setAttribute("weight", weight);*/
// get BodyInfo (weight, fat, bmi)
Body bodyInfo = apiClientService.getClient().getBody(new LocalUserDetail(resourceCredentials.getLocalUserId()), fitbitUser, new LocalDate(year,month,day));
//BodyWithGoals bodyGoals = apiClientService.getClient().getBodyWithGoals(new LocalUserDetail(resourceCredentials.getLocalUserId()), new FitbitUser("-"), new LocalDate(year,month,day));
request.setAttribute("bodyInfo", bodyInfo);
// get BloodPressure (BP) Info
Bp bloodPressureInfo = apiClientService.getClient().getLoggedBp(new LocalUserDetail(resourceCredentials.getLocalUserId()), fitbitUser, new LocalDate(year,month,day));
request.setAttribute("bloodPressureInfo", bloodPressureInfo);
// forward result to .jsp page
request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
} catch (FitbitAPIException e) {
throw new ServletException("Exception during getting user info", e);
}
} else {
try {
response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
} catch (FitbitAPIException e) {
throw new ServletException("Exception during performing authorization", e);
}
}
}
}

Cannot instantiate the type Iterator in JSP (Exception: The value for the useBean class attribute ... is invalid)

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>

CompileError in File uploading

List<?> items =upload.parseRequest(request);
The method parseRequest(HttpServletRequest, int, long, String) in the type DiskFileUpload is not applicable for the arguments (HttpServletRequest)
When i Run as Server...it gives error on console
May 13, 2012 7:47:49 PM org.apache.tomcat.util.digester.Digester startElement
SEVERE: Begin event threw error
java.lang.NoSuchMethodError: org.apache.tomcat.util.ExceptionUtils.unwrapInvocationTargetException(Ljava/lang/Throwable;)Ljava/lang/Throwable;
at org.apache.catalina.core.AprLifecycleListener.init(AprLifecycleListener.java:185)
at org.apache.catalina.core.AprLifecycleListener.isAprAvailable(AprLifecycleListener.java:84)
at org.apache.catalina.connector.Connector.setProtocol(Connector.java:577)
at org.apache.catalina.connector.Connector.(Connector.java:69)
at org.apache.catalina.startup.ConnectorCreateRule.begin(ConnectorCreateRule.java:62)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:506)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1302)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
at org.apache.catalina.startup.Catalina.load(Catalina.java:619)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:449)
java.lang.NoSuchMethodError: org.apache.tomcat.util.ExceptionUtils.unwrapInvocationTargetException(Ljava/lang/Throwable;)Ljava/lang/Throwable;
at org.apache.catalina.core.AprLifecycleListener.init(AprLifecycleListener.java:185)
at org.apache.catalina.core.AprLifecycleListener.isAprAvailable(AprLifecycleListener.java:84)
at org.apache.catalina.connector.Connector.setProtocol(Connector.java:577)
at org.apache.catalina.connector.Connector.(Connector.java:69)
at org.apache.catalina.startup.ConnectorCreateRule.begin(ConnectorCreateRule.java:62)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:506)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1302)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
at org.apache.catalina.startup.Catalina.load(Catalina.java:619)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:449)
This is my code in this code
List<?> items =upload.parseRequest(request); Got error as The method parseRequest(HttpServletRequest, int, long, String) in the type DiskFileUpload is not applicable for the arguments
(HttpServletRequest)
package br.com.ecommerce.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
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.tomcat.util.http.fileupload.disk.*;
import org.apache.tomcat.util.http.fileupload.servlet.*;
import org.apache.tomcat.util.http.fileupload.util.*;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import br.com.ecommerce.bean.Produtos;
import br.com.ecommerce.controller.ExceptionController;
import br.com.ecommerce.dao.CategoriasDao;
import br.com.ecommerce.dao.ProdutosDao;
class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
Produtos produto = new Produtos();
String caminhoTemp = new String("C:\\Users\\vaio\\workspace\\ecommerce\\WebContent\\images\\upload");
String pasta = new String("C:\\Users\\vaio\\workspace\\ecommerce\\WebContent\\images\\upload");
String caminho = new String("images\\upload\\");
if (ServletFileUpload.isMultipartContent( request)){
DiskFileUpload upload = new DiskFileUpload();
upload.setRepositoryPath(caminhoTemp);
try{
List<?> items =upload.parseRequest(request);//In this line i got error..why?..Pls help
Iterator<?> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.isFormField()){
if(item.getFieldName().equals("nome")){
produto.setProdNome(item.getString().toUpperCase());
}
else if (item.getFieldName().equals("categoria")){
produto.setCategorias(new CategoriasDao().findByPK(Integer.valueOf(item.getString())));
}
else if (item.getFieldName().equals("preco")){
produto.setPreco(Double.valueOf(item.getString()));
Double preco = 0d;
preco = Double.valueOf(item.getString());
preco += 10.00;
System.out.println(preco);
}
else if (item.getFieldName().equals("descp")){
produto.setDescPeq(item.getString());
}
else if (item.getFieldName().equals("descg")){
produto.setDescGd(item.getString());
}
else if (item.getFieldName().equals("espec")){
produto.setEspecificacoes(item.getString());
}
else if (item.getFieldName().equals("itens")){
produto.setItensInclusos(item.getString());
}
produto.setPromocao(0);
produto.setDestaque(0);
}
if (!item.isFormField()) {
String nome = item.getName().toString();
String nomeArquivo = nome.substring(nome.lastIndexOf("\\")+1);
File arquivo = new File(pasta + "\\" + nomeArquivo);
produto.setImagem(caminho + nomeArquivo);
item.write(arquivo);
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
new ProdutosDao().insert(produto);
} catch (ExceptionController e) {
e.printStackTrace();
}
response.sendRedirect("/ecommerce/admin/gerenciarProdutos.jsp");
}
}
enter code here
Are you trying to use the DiskFileUpload class from Commons FileUpload? If so, make sure your class is importing org.apache.commons.fileupload.DiskFileUpload, and not some other class called DiskFileUpload.