Java exception in openConnection method (fetching data from html) - java

I have a problem getting the input stream using 'getInputStream' method for few URLs (most of the URLs works fine) although the URL seems to work via web browser.
I am using the following code:
public static String getContents(String uri, String encoding) {
StringBuffer sb = new StringBuffer();
URL url;
try {
url = new URL(uri);
URLConnection con = url.openConnection();
con.setReadTimeout(90000);
System.out.println("--------2.1:");//////////////////////////////////////////////////////////////
InputStream is = con.getInputStream();
System.out.println("--------2.2:"+is);/////////////////////////////////////////////////////////
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// read lines from HTML
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
System.out.println("--------2.6:");//////////////////////////////////////////////////////
return null;
}
return sb.toString();
}
output:
--------2.1:http://infoscience.epfl.ch/oai2d?verb=ListIdentifiers&metadataPrefix=oai_dc
--------2.6:
Exception:
java.io.IOException: Server returned HTTP response code: 503 for URL: http://infoscience.epfl.ch/oai2d?verb=ListIdentifiers&metadataPrefix=oai_dc
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.irWizard.common.util.FileUtils.getContents(FileUtils.java:29)
at com.irWizard.web.controller.WizardController.getActualTotalOfRecords(WizardController.java:500)
at com.irWizard.web.controller.WizardController.validateSets(WizardController.java:419)
at com.irWizard.web.controller.WizardController.onSubmit(WizardController.java:242)
at com.irWizard.web.controller.BaseController.onSubmit(BaseController.java:127)
at org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:258)
at org.springframework.web.servlet.mvc.AbstractFormController.handleInvalidSubmit(AbstractFormController.java:652)
at org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:257)
at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:45)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:728)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:350)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
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:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
It seems that it's code 503.
Does anyone know how it can be solved? (it works fine via browser).
Mike

Related

java.lang.NullPointerException occurs when i update?

I got Null pointer exception
"java.lang.NullPointerException"
refer below code for reference
Everything should be fine but not able to update data to the database(mySql)
<% try{
//reading request parameters
String projectName=request.getParameter("projectName").trim();
String status=request.getParameter("status").trim();
//String user = session.getAttribute("user").toString();
Connection connection = DAO.getConnection();
PreparedStatement pstmt = connection.prepareStatement("update project set status=? where projectName=?");
pstmt.setString(1,status);
pstmt.executeUpdate();
out.println("<h2 style='color:green'>Project Status has been updated</h2>");
}
catch(Exception ex)
{
ex.printStackTrace();
out.println("<h2 style='color:red'>Please login to update your Status</h2>");
}
%>
Not able to update because of exception
refer below
Please anyone suggest me how to solve this exception...
java.lang.NullPointerException at org.apache.jsp.MyWorkPanelAction_jsp._jspService(MyWorkPanelAction_jsp.java:93)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) 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:222)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
You missed the projectName...Try the code below
try{
//reading request parameters
String projectName=request.getParameter("projectName").trim();
String status=request.getParameter("status").trim();
//String user = session.getAttribute("user").toString();
Connection connection = DAO.getConnection();
PreparedStatement pstmt = connection.prepareStatement("update project set status=? where projectName=?");
pstmt.setString(1,status);
pstmt.setString(2,projectName); //Try this
pstmt.executeUpdate();
out.println("<h2 style='color:green'>Project Status has been updated</h2>");
}
catch(Exception ex)
{
ex.printStackTrace();
out.println("<h2 style='color:red'>Please login to update your Status</h2>");
}

FlexJson Error : ClassCastException: java.util.HashMap cannot be cast to class

This is the error I get while I try to cast my LONGTEXT object from mysql back to my ProcessInputs java object using FlexJSON.
java.lang.ClassCastException: java.util.HashMap cannot be cast to org.juzzy.server.ProcessInputs
at org.juzzy.server.FLSDAO.RetrieveFLSFromDatabase(FLSDAO.java:68)
at org.juzzy.client.CreateFLS.doPost(CreateFLS.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
This is what my ProcessInput class looks like
public class ProcessInputs {
//inputs contain names of all the inputs and their objects
Map<String,Input> inputs= new LinkedHashMap<String,Input>();
Map<String,Output> outputs= new HashMap<String,Output>();
Map<String,Object> fuzzyTerms=new HashMap<String,Object>();
Map<String,String> fuzzyTermMapper=new HashMap<String,String>();
ArrayList<T1_Antecedent> antecedentArrayList;
String outputxml;
T1_Rulebase rulebase = new T1_Rulebase(1);
//getters,setters, constructor and functions
}
My retrieval code in FLEXJSON:
while(rs.next()){
String jsonInString= rs.getString("fls");
JSONDeserializer<ProcessInputs> der = new JSONDeserializer<ProcessInputs>();
ProcessInputs fls = der.deserialize(jsonInString);
}
This is how the serialization happens:
public boolean InsertFLStoDatabase(ProcessInputs object, String xml) throws IOException {
Connection connection = DatabaseConnect.getConnection();
String query = "insert into fls_systems (fls, xml) values (?,?)";
try {
JSONSerializer ser = new JSONSerializer();
String jsonInString = ser.deepSerialize(object);
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, jsonInString);
From your exception this should work (i guess...):
while(rs.next()){
String jsonInString= rs.getString("fls");
JSONDeserializer<ProcessInputs> der = new JSONDeserializer<ProcessInputs>();
// exception is here, right? der.deserialize(String) is giving you a Map!!
Map<String,Input> fls = der.deserialize(jsonInString);
}
Don't have a deep knowledge of flexjson, but I'm not casting like
Map<String,Input> fls = (Map<String,Input>) der.deserialize(jsonInString);
Because of the message:
java.util.HashMap cannot be cast to org.juzzy.server.ProcessInputs
And because API:
Deserialize the given json formatted input into a Java object.
But may be a possibility if first option does not work.

alfresco custom action for secure timestamp - error using BouncyCastle

I'm a newbie to developing to alfresco so here is my question. I'm developing a custom action in alfresco wich goal is to create a detached Secure Time Stamp of a document.
Here's my code:
String tsaUrl = "http://ts.cartaodecidadao.pt/tsa/server";
OutputStream out = null;
HttpURLConnection con = null;
MessageDigest hash;
InputStream is = null;
try{
hash = MessageDigest.getInstance("SHA1");
try{
is = new BufferedInputStream(new FileInputStream(file));
final byte[] buffer = new byte[1024];
for (int i = 0; is.read(buffer) != -1;){
hash.update(buffer, 0, i);
}
} catch (FileNotFoundException e){
e.printStackTrace();
}
TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
/*FIXME */
ASN1ObjectIdentifier algorithm = TSPAlgorithms.SHA1;
TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(algorithm, hash.digest());
byte request[] = timeStampRequest.getEncoded();
URL url = new URL(tsaUrl);
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-type",
"application/timestamp-query");
con.setRequestProperty("Content-length",
String.valueOf(request.length));
out = con.getOutputStream();
out.write(request);
out.flush();
out.close();
if (con.getResponseCode() != HttpURLConnection.HTTP_OK)
{
System.out.println("---------- != HttpURLConnection.HTTP_OK");
throw new IOException("Received HTTP error: "
+ con.getResponseCode() + " - "
+ con.getResponseMessage());
}
InputStream in = con.getInputStream();
TimeStampResp resp = TimeStampResp
.getInstance(new ASN1InputStream(in).readObject());
TimeStampResponse response = new TimeStampResponse(resp);
It builds successfully but when trying the action, it throws an error the line after where is the comment "FIXME". The stack-trace of the error is
2015-07-09 00:58:32,598 ERROR [extensions.webscripts.AbstractRuntime] [http-bio-8080-exec-8] Exception from executeScript - redirecting to status template error: 06090002 Wrapped Exception (with status template): 06090015 The action failed to execute due to an error.
org.springframework.extensions.webscripts.WebScriptException: 06090002 Wrapped Exception (with status template): 06090015 The action failed to execute due to an error.
at org.springframework.extensions.webscripts.AbstractWebScript.createStatusException(AbstractWebScript.java:1126)
at org.springframework.extensions.webscripts.DeclarativeWebScript.execute(DeclarativeWebScript.java:171)
at org.alfresco.repo.web.scripts.RepositoryContainer$3.execute(RepositoryContainer.java:470)
at org.alfresco.repo.transaction.RetryingTransactionHelper.doInTransaction(RetryingTransactionHelper.java:454)
at org.alfresco.repo.web.scripts.RepositoryContainer.transactionedExecute(RepositoryContainer.java:532)
at org.alfresco.repo.web.scripts.RepositoryContainer.transactionedExecuteAs(RepositoryContainer.java:600)
at org.alfresco.repo.web.scripts.RepositoryContainer.executeScriptInternal(RepositoryContainer.java:380)
at org.alfresco.repo.web.scripts.RepositoryContainer.executeScript(RepositoryContainer.java:261)
at org.springframework.extensions.webscripts.AbstractRuntime.executeScript(AbstractRuntime.java:378)
at org.springframework.extensions.webscripts.AbstractRuntime.executeScript(AbstractRuntime.java:209)
at org.springframework.extensions.webscripts.servlet.WebScriptServlet.service(WebScriptServlet.java:132)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.alfresco.web.app.servlet.GlobalLocalizationFilter.doFilter(GlobalLocalizationFilter.java:61)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.alfresco.service.cmr.action.ActionServiceException: 06090015 The action failed to execute due to an error.
at org.alfresco.repo.action.ActionServiceImpl.executeActionImpl(ActionServiceImpl.java:816)
at org.alfresco.repo.action.ActionServiceImpl.executeAction(ActionServiceImpl.java:573)
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:483)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.alfresco.repo.security.permissions.impl.AlwaysProceedMethodInterceptor.invoke(AlwaysProceedMethodInterceptor.java:34)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.alfresco.repo.security.permissions.impl.ExceptionTranslatorMethodInterceptor.invoke(ExceptionTranslatorMethodInterceptor.java:46)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.alfresco.repo.audit.AuditMethodInterceptor.invoke(AuditMethodInterceptor.java:159)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy53.executeAction(Unknown Source)
at org.alfresco.repo.web.scripts.rule.ActionQueuePost.executeImpl(ActionQueuePost.java:85)
at org.springframework.extensions.webscripts.DeclarativeWebScript.execute(DeclarativeWebScript.java:64)
... 32 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.bouncycastle.tsp.TSPAlgorithms
at pt.ubi.release.SecureTimeStamp_repo.action.StampAction.executeImpl(StampAction.java:233)
at org.alfresco.repo.action.executer.ActionExecuterAbstractBase.execute(ActionExecuterAbstractBase.java:265)
at org.alfresco.repo.action.ActionServiceImpl.directActionExecution(ActionServiceImpl.java:839)
at org.alfresco.repo.action.ActionServiceImpl.executeActionImpl(ActionServiceImpl.java:739)
Did anyone knows why it says it could not initializa class org.bouncycastle.tsp.TSPAlgorithms? Btw, i'm using version 1.52 of bouncycastle libraries.
Sorry about my english but it's not my native language.
NoClassDefFoundError indicates that the classloader, which is responsible for dynamically loading classes, cannot find the .class file for the class that you're trying to use. So, probably jar is not added to class path for class org.bouncycastle.tsp.TSPAlgorithms
You probably need to add that bouncycastle jar in alfresco/Web-INF/lib if you are trying to run this action within Alfresco.

java.lang.IllegalArgumentException: java.text.ParseException: End of header

I encounter IllegalArgumentException while sending a post request to the restful web-service.
If i comment the method for post request(getEmplByPostReqParam()) then, code works fine for get request but with getEmplByPostReqParam(), all request throws IllegalArgumentException.
Can you please help in identifying the problem.
Web service code:
#Path("/employee")
public class EmployeeInfoService {
// This method is called if TEXT_PLAIN is request
#GET
#Path("/get/{id}")
#Produces(MediaType.APPLICATION_ATOM_XML)
public Employee getEmplById(#PathParam("id") String id) {
System.out.println("sayPlainTextHello");
EmployeeDAO dbHandler = new EmployeeDAOImpl();
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
return fetchedEmployee;
}
#GET
#Path("/get")
#Produces(MediaType.APPLICATION_ATOM_XML)
public Employee getEmplByGetReqParam(#QueryParam("param1") String id) {
System.out.println("getEmplByGetReqParam");
EmployeeDAO dbHandler = new EmployeeDAOImpl();
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
return fetchedEmployee;
}
#POST
#Path("/get")
#Produces("MediaType.TEXT_PLAIN")
public String getEmplByPostReqParam(#FormParam("param1") String id) {
System.out.println("getEmplByPostReqParam");
EmployeeDAO dbHandler = new EmployeeDAOImpl();
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
return fetchedEmployee.toString();
}
}
I used two client to test the service:
1. Google chrome's Advance Rest client
url - http://myhost:14443/de.vogella.jersey.first/rest/employee/get
payload - [param1: 1]
method type - [post]
core java code
String url = "http://myhost:14443/de.vogella.jersey.first/rest/employee/get";
String charset = "UTF-8";
String param1 = "1";
String query = String.format("param1=%s",
URLEncoder.encode(param1, charset));
URL service = new URL(url);
URLConnection connection = service.openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
OutputStream output = connection.getOutputStream();
try {
output.write(query.getBytes(charset));
} catch (Exception e) {
// TODO: handle exception
}
Stacktrace:
</pre></p><p><b>root cause</b> <pre>java.lang.IllegalArgumentException: java.text.ParseException: End of header
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:289)
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:274)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.addProduces(IntrospectionModeller.java:171)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.workOutSubResourceMethodsList(IntrospectionModeller.java:342)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.createResource(IntrospectionModeller.java:126)
com.sun.jersey.server.impl.application.WebApplicationImpl.getAbstractResource(WebApplicationImpl.java:744)
com.sun.jersey.server.impl.application.WebApplicationImpl.createAbstractResourceModelStructures(WebApplicationImpl.java:1564)
com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1328)
com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:168)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:774)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:770)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:770)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
</pre></p><p><b>root cause</b> <pre>java.text.ParseException: End of header
com.sun.jersey.core.header.reader.HttpHeaderReaderImpl.getNextCharacter(HttpHeaderReaderImpl.java:168)
com.sun.jersey.core.header.reader.HttpHeaderReaderImpl.next(HttpHeaderReaderImpl.java:129)
com.sun.jersey.core.header.reader.HttpHeaderListAdapter.next(HttpHeaderListAdapter.java:111)
com.sun.jersey.core.header.reader.HttpHeaderListAdapter.next(HttpHeaderListAdapter.java:98)
com.sun.jersey.core.header.reader.HttpHeaderReader.nextSeparator(HttpHeaderReader.java:116)
com.sun.jersey.core.header.QualitySourceMediaType.valueOf(QualitySourceMediaType.java:85)
com.sun.jersey.core.header.reader.HttpHeaderReader$5.create(HttpHeaderReader.java:360)
com.sun.jersey.core.header.reader.HttpHeaderReader$5.create(HttpHeaderReader.java:358)
com.sun.jersey.core.header.reader.HttpHeaderReader.readList(HttpHeaderReader.java:481)
com.sun.jersey.core.header.reader.HttpHeaderReader.readList(HttpHeaderReader.java:473)
com.sun.jersey.core.header.reader.HttpHeaderReader.readAcceptableList(HttpHeaderReader.java:461)
com.sun.jersey.core.header.reader.HttpHeaderReader.readQualitySourceMediaType(HttpHeaderReader.java:365)
com.sun.jersey.core.header.reader.HttpHeaderReader.readQualitySourceMediaType(HttpHeaderReader.java:373)
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:287)
com.sun.jersey.core.header.MediaTypes.createQualitySourceMediaTypes(MediaTypes.java:274)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.addProduces(IntrospectionModeller.java:171)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.workOutSubResourceMethodsList(IntrospectionModeller.java:342)
com.sun.jersey.server.impl.modelapi.annotation.IntrospectionModeller.createResource(IntrospectionModeller.java:126)
com.sun.jersey.server.impl.application.WebApplicationImpl.getAbstractResource(WebApplicationImpl.java:744)
com.sun.jersey.server.impl.application.WebApplicationImpl.createAbstractResourceModelStructures(WebApplicationImpl.java:1564)
com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1328)
com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:168)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:774)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:770)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:770)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:765)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:489)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:319)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
If you notice your annotation (#Produces) argument is passed in double quotes. remove the double quotes and it should work
#Produces("MediaType.TEXT_PLAIN")
should look like below
#Produces(MediaType.TEXT_PLAIN)
I resolved the issue by changing the getEmplByPostReqParam() as follows:
#POST
#Path("/get")
public Response getEmplByPostReqParam(#FormParam("param1") String id) {
EmployeeDAO dbHandler = new EmployeeDAOImpl();
System.out.println("getEmplByPostReqParam");
Employee fetchedEmployee = dbHandler.findEmployee(Integer.parseInt(id));
ResponseBuilder rb = new ResponseBuilderImpl();
rb.type(MediaType.APPLICATION_ATOM_XML);
rb.entity(fetchedEmployee);
return rb.build();
}
This is working fine for me, if there is some better approach or there is something wrong with this approach, please post a comment.

Unable to connect to database based on property file

Hi I'm new in java/jsp developing.
I'm trying to connect to database depending on parameter that jsp file receives from previous page.
My program works if i connect to single DB like
try {
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/db.properties");
properties.load(in);
connString = properties.getProperty("db_conn").toString();
connUser = properties.getProperty("db_user").toString();
connPass = properties.getProperty("db_pass").toString();
bPath = properties.getProperty("exec_path").toString();
in.close();
} catch (IOException ex) {
System.out.println(ex);
}
and db.properties file contains
db_conn=jdbc:oracle:thin:#33.333.3.33:3333:DKSE1
db_user=guest
db_pass=guestpw
My attempt:
String userinfo = request.getParameter("userinfo");
try {
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/db.properties");
properties.load(in);
db_conn = userinfo + "_conn";
db_user = userinfo + "_user";
db_pass = userinfo + "_pass";
connString = properties.getProperty(db_conn).toString();
connUser = properties.getProperty(db_user).toString();
connPass = properties.getProperty(db_pass).toString();
bPath = properties.getProperty("exec_path").toString();
in.close();
} catch (IOException ex) {
System.out.println(ex);
}
try {
// --- Required database stuff ---
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection conn = DriverManager.getConnection(connString, connUser, connPass);
Statement stmt = conn.createStatement();
More codes....
}
db.properties
guest_conn=jdbc:oracle:thin:#33.333.3.33:3333:DKSE1
guest_user=guest
guest_pass=guestpw
user_conn=jdbc:oracle:thin#11.222.3.33:4444:ESMZ1
user_user=user
user_pass=upw1
user1_conn=jdbc:oracle:thin#11.11.1.11:1111:GEPD1
user1_user=user1
user1_pass=upw1
batch_exec_path = ${SERVER_DIR}
Stacktrace
Nov 30, 2012 9:03:55 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/dashboard] threw exception [An exception occurred processing JSP page /alpharunBatch.jsp at line 106
103: db_conn = userinfo + "_conn";
104: db_user = userinfo + "_user";
105: db_pass = userinfo + "_pass";
106: connString = properties.getProperty(db_conn).toString();
107: connUser = properties.getProperty(db_user).toString();
108: connPass = properties.getProperty(db_pass).toString();
109: bPath = properties.getProperty("exec_path").toString();
Stacktrace:] with root cause
java.lang.NullPointerException
at org.apache.jsp.alpharunBatch_jsp._jspService(alpharun_jsp.java:192)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
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)
Am i doing something fundamentally wrong?
Thanks for your help!
try following for test:
change that
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/db.properties");
to
InputStream in = getServletContext().getResourceAsStream("db.properties");
and put your properties in the classpath folder(src)
Furthermore change
properties.getProperty("exec_path").toString();
to
properties.getProperty("batch_exec_path").toString();

Categories