alfresco custom action for secure timestamp - error using BouncyCastle - java

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.

Related

Caused by: java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts

i am using jjwt-0.9.1.jar and runtime gives this exception for jersey reset API call.
When i use this code using java main() method, its works perfectly but when i call from servlet to that class, the method throws exception.
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.UUID;
public String createJWTToken() {
String id = UUID.randomUUID().toString().replace("-", "");
//The JWT signature algorithm we will be using to sign the token
// SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
//Let's set the JWT Claims
JwtBuilder builder = null;
try {
builder = Jwts.builder().setId(id).setHeaderParam("typ", "JWT")
.setIssuedAt(now)
.setSubject("")
.setIssuer(API_KEY)
.signWith(SignatureAlgorithm.HS256,SECRET_KEY.getBytes("UTF-8"));
//if it has been specified, let's add the expiration
if (ttlMillis >= 0) {
long expMillis = nowMillis + ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.compact();//Builds the JWT and serializes it to a compact, URL-safe string
}
When call servlet to java class method i.e.createJWTToken() gives following exception in tomcat.
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:328)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.test.lms.servlets.GlobalFilter.doFilter(GlobalFilter.java:204)
at com.test.lms.servlets.GlobalFilter.doFilter(GlobalFilter.java:48)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at com.general.FilterDemo.doFilter(FilterDemo.java:312)
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:224)
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.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts
at com.zoom.JWTTokenGeneration.createJWTToken(JWTTokenGeneration.java:31)
at com.zoom.Utilities.setMeeting(Utilities.java:571)
at com.general.InsertController.doPost(InsertController.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) ... 22 more Caused by: java.lang.ClassNotFoundException: io.jsonwebtoken.Jwts
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1701)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1546) ... 28 more
The exception is java.lang.NoClassDefFoundError: io/jsonwebtoken/Jwts
Check the Jar file(jwt) is packaged in the build or not?

java.io.FileNotFoundException uploading image with apache.commons

I'm developing a Spring-MVC project that requires uploading images by the users of the app. I'm using apache.commons, Eclipse Mars2 and Java1.8. Everytime I test the upload, eclipse console throws this:
EDIT: it seems the problem is to find the path to the project independently of the OS. At this moment we are using:
File localFile = new File(System.getProperty("user.home")+File. separator+ "workspace"+File. separator+"ProyectoSpring"+File. separator + "WebContent" + File. separator+"usr"+File. separator+imagen.getNombreImagen());
The problem is the workspace is hardcoded and the app is being developed by more people. Any way to find the path to the project? user.dir returns the eclipe path, not the project or workspace.
Original question:
java.io.FileNotFoundException: C:\Users\UserName\workspace\ApacheTomcat7\ProyectoSpring\WebContent\usr\back.jpg (El sistema no puede encontrar la ruta especificada)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at controller.ImagenController.grabarFicheroALocal(ImagenController.java:84)
at controller.ImagenController.processAddSubmit(ImagenController.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:919)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
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(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Controller methods:
#RequestMapping(value="/uploadImagen" , method=RequestMethod.GET)
public String addImagen(Model model) {
model.addAttribute("imagen", new Imagen());
return "imagen/uploadImagen";
}
#RequestMapping(value="/uploadImagen", method=RequestMethod.POST)
public String processAddSubmit(#ModelAttribute("imagen") Imagen imagen,
BindingResult bindingResult) {
//if (bindingResult.hasErrors())
// return "imagen/uploadImagen";
//
try {
String aux = imagen.getFichero().getOriginalFilename();
imagen.setImageName(System.getProperty("catalina.home")+ File. separator +"ProyectoSpring"+ File. separator +"WebContent"+ File. separator +"usr"+ File. separator + aux);
grabarFicheroALocal(imagen);
} catch (Exception e) {
e.printStackTrace();
return "user/error";
}
return "redirect:../index.jsp";
}
private void grabarFicheroALocal(Imagen imagen) throws Exception {
CommonsMultipartFile uploaded = imagen.getFichero();
File localFile = new File(imagen.getImageName());
FileOutputStream os = null;
try {
os = new FileOutputStream(localFile);
os.write(uploaded.getBytes());
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
An extract from the object:
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class Imagen {
private String imageName;
private CommonsMultipartFile fichero;
public Imagen(){
super();
}
//GETTERS AND SETTERS
public CommonsMultipartFile getFichero() {
return fichero;
}
public void setFichero(CommonsMultipartFile fichero) {
this.fichero = fichero;
}
...
Of course, the image is not uploaded. In other pc with Linux (I'm using W7-64) the code works, so I suspect it may be a permissions problem, but all folders in the path have write permissions. Any ideas? Thx.

Java exception in openConnection method (fetching data from html)

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

java.lang.IllegalStateException content - disposition

I am trying to use content - disposition to save something from server to client computer. When I click on button in jsp, dialog opens and I choose to save file. File is saved but I get this exception. I have read on other similar topics something like "Somewhere, your application is calling getOutputStream or getWriter more than once." but I don't know/understand where?
#Controller
public class ExportPhonebook2 {
#Autowired
private PhoneBookService phoneBookSer;
private void setResponseHeader(HttpServletResponse response, String imenikTXT, File file){
response.setHeader("Content-Length", "" + file.length());
response.setContentType("application/txt; charset=UTF-8");
response.setHeader("content-disposition", "attachement; filename=imenik.txt" );
response.setHeader("Content-Transfer-Encoding", "binary");
}
#RequestMapping(value = "/exportPhonebook.html", method = RequestMethod.POST)
public String exportPhonebook(Model model, HttpServletResponse response) {
List<User> listOfAllUsers = phoneBookSer.fetchAllUsers();
String imenik = "";
for (User user : listOfAllUsers) {
imenik = imenik + user.getPrezime() + " " + user.getIme() + ", Telefon: " + user.getTelefon() + ";\r\n" ;
}
try {
File file = new File("c:\\imenik.txt");
setResponseHeader(response, "imenik.txt", file);
FileInputStream fileIn;
fileIn = new FileInputStream(file);
OutputStream outTXT = response.getOutputStream();
byte[] outputByte = new byte[8192];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, 8192) != -1){
outTXT.write(outputByte, 0, 8192);
}
fileIn.close();
outTXT.flush();
outTXT.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "homepage";
}
}
stacktrace:
Exception initializing page context
java.lang.IllegalStateException: Cannot create a session after the response has been committed
at org.apache.catalina.connector.Request.doGetSession(Request.java:2705)
at org.apache.catalina.connector.Request.getSession(Request.java:2231)
at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:899)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:229)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:572)
at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:517)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:238)
at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:238)
at org.apache.jasper.runtime.PageContextImpl._initialize(PageContextImpl.java:146)
at org.apache.jasper.runtime.PageContextImpl.initialize(PageContextImpl.java:125)
at org.apache.jasper.runtime.JspFactoryImpl.internalGetPageContext(JspFactoryImpl.java:112)
at org.apache.jasper.runtime.JspFactoryImpl.getPageContext(JspFactoryImpl.java:65)
at org.apache.jsp.WEB_002dINF.jsp.homepage_jsp._jspService(homepage_jsp.java:58)
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:419)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
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:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:593)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:530)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:229)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:328)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:95)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:340)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:175)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
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:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
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)
This particular exception is caused because Spring MVC apparently needs to create a session during rendering of the view, but couldn't because the response is already committed with the file download. But your real problem is bigger, Spring MVC should not be rendering a view at all.
You need to tell Spring MVC to not render a view after having taken over the control of the HTTP response from Spring MVC. It is otherwise trying to append the rendered view to the end of the HTTP response which would only corrupt the file download.
I don't do Spring MVC, so I can't answer from top of head, but it appears that just returning void instead of String from the controller's action method should be sufficient in order to tell Spring MVC to not render a view.
java.lang.IllegalStateException: Cannot create a session after the response has been committed
Session creation requires a session cookie to be written to the HTTP header, before the body. Something is trying to create a session after you've flushed and closed your response.
Consider creating the session prior to writing the response.

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