I'm beginner for using JPOS with ISO8583. At this time, I try my application using Spring to build the request using JPOS where I want to send it to BASE24.
Here my code for build :
public class BuildISO {
public void sentISOMsg(String hostname, int portNumber) {
// Create Packager based on XML that contain DE type
GenericPackager packager;
ASCIIChannel channel;
try {
packager = new GenericPackager("packager/iso93ascii.xml");
channel = new ASCIIChannel(hostname, portNumber, packager);
ISOMUX isoMux = new ISOMUX(channel) {
#Override
protected String getKey(ISOMsg m) throws ISOException {
return super.getKey(m);
}
};
new Thread(isoMux).start();
// Create ISO Message
ISOMsg isoRequest = new ISOMsg();
isoRequest.setMTI("1800");
isoRequest.set(3, "123456");
isoRequest.set(7, new SimpleDateFormat("yyyyMMdd").format(new Date()));
isoRequest.set(11, "000001");
isoRequest.set(12, new SimpleDateFormat("HHmmss").format(new Date()));
isoRequest.set(13, new SimpleDateFormat("MMdd").format(new Date()));
isoRequest.set(48, "Tutorial ISO 8583 Dengan Java");
isoRequest.set(70, "001");
ISORequest req = new ISORequest(isoRequest);
isoMux.queue(req);
ISOMsg isoReply = req.getResponse(50*1000);
if (isoReply != null) {
System.out.println("Req ["+new String(isoRequest.pack()) + "]");
System.out.println("Res ["+new String(isoReply.pack()) + "]");
}
// print the DE list
logISOMsg(isoRequest);
// Get and print the output result
byte[] data = isoRequest.pack();
System.out.println("RESULT : " + new String(data));
} catch (ISOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void logISOMsg(ISOMsg msg) {
System.out.println("----ISO MESSAGE-----");
try {
System.out.println(" MTI : " + msg.getMTI());
for (int i=1;i<=msg.getMaxField();i++) {
if (msg.hasField(i)) {
System.out.println(" Field-"+i+" : "+msg.getString(i));
}
}
} catch (ISOException e) {
e.printStackTrace();
} finally {
System.out.println("--------------------");
}
}
}
and next, while I want to call that class in here :
public #ResponseBody ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String hostname = request.getParameter("hostname");
int portNumber = Integer.parseInt(request.getParameter("portNumber"));
System.out.println("handleRequest... : " + hostname + " : " + portNumber);
BuildISO buildISO = new BuildISO();
buildISO.sentISOMsg(hostname, portNumber);
return null;
}
I got error like this :
SEVERE: Servlet.service() for servlet spring threw exception
java.lang.ClassNotFoundException: org.jpos.iso.ISOException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
at org.sprint.controller.HandleController.handleRequest(HandleController.java:28)
at org.sprint.controller.HandleController$$FastClassByCGLIB$$fc3d18c.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:256)
at org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at org.sprint.controller.HandleController$$EnhancerByCGLIB$$fbdc3830.handleRequest(<generated>)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:722)
I have searched through StackOverflow's already asked questions, but have not found any of the situations in which the changes to the project were NONE. So I am feeling quite frustrated now because I have actually changed NOTHING and my project has stopped working. Help me please, any ideas would be grateful.
You should be sure that you have all jars in the CLASSPATH. In your case it is jpos.jar. And they all (with Spring) should be loaded withing the same classloader.
And one more advice: add -verbose option to the java (I guess Tomcat) to see from where your classes are loaded.
Please add the maven jpos dependency to you project.
<dependency>
<groupId>org.jpos</groupId>
<artifactId>jpos</artifactId>
<version>1.9.4</version>
</dependency>
Choose any one of the repository available from maven Maven Repository Link
Related
i have an unmanaged extension for my neo4j server.
and the code like the following.
#Path("/helloworld")
public class HelloWorldResource {
private final GraphDatabaseService database;
public HelloWorldResource(#Context GraphDatabaseService database) {
this.database = database;
}
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/{nodeId}")
public Response hello(#PathParam("nodeId") long nodeId) {
String res = "";
try ( Transaction ignored = database.beginTx();)
{
//##problem
Result result = database.execute( "MATCH (n:KISI) where id(n)=1 return n" );
} catch (Exception e) {
res = "Error = " + e.getMessage();
}
return Response
.status(Status.OK)
.entity(("nodeId =" + nodeId + " " + res).getBytes(Charset
.forName("UTF-8"))).build();
}
}
When i deploy the code i got 500 internal error.
if i remove the code
Result result = database.execute( "MATCH (n:KISI) where id(n)=1 return
n" );
then everything is fine.
i checked the log file and the error is the following
Aug 13, 2015 3:34:36 AM com.sun.jersey.spi.container.ContainerResponse
mapMappableContainerException SEVERE: The exception contained within
MappableContainerException could not be mapped to a response,
re-throwing to the HTTP container
java.lang.NoSuchMethodError:
org.neo4j.graphdb.GraphDatabaseService.execute(Ljava/lang/String;)Lorg/neo4j/graphdb/Result;
at
org.neo4j.examples.server.unmanaged.HelloWorldResource.hello(HelloWorldResource.java:55)
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:606) at
com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
at
com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at
org.neo4j.server.rest.transactional.TransactionalRequestDispatcher.dispatch(TransactionalRequestDispatcher.java:139)
at
com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288)
at
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at
com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at
com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469)
at
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400)
at
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) at
org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:698)
at
org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:505)
at
org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:211)
at
org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1096)
at
org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:432)
at
org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:175)
at
org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1030)
at
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at
org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:52)
at
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:445) at
org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:268) at
org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:229)
at
org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:358)
at
org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:601)
at
org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:532)
at java.lang.Thread.run(Thread.java:745)
so whats wrong with my code?
I guess that your Neo4j distribution version and maven dependency version in pom.xml are not same.
But there are several things to check:
1) You should always close Result object.
Example:
try(Result result = database.execute( "MATCH (n:KISI) where id(n)=1 return n" )) {
// do stuff here
}
```
2) Exception occurs not in try-catch but later. You should change your code to this:
try ( Transaction tx = database.beginTx()) {
String query = "MATCH (n:KISI) where id(n)=1 return n";
// use result with try-with-resource to ensure that it will be closed
try(Result result = database.execute(query)) {
// do stuff you need with result here
return Response.ok("nodeId =" + nodeId).build();
}
tx.success(); // mark transaction as successful
} catch (Exception e) {
// If exception occurs - send exception message with 500 status code
// It's good idea to write Exception stacktrace to log there
return Response.serverError().entity(e.getMessage()).build()
}
3) You should check how unmanaged extension .jar file is build.
All Neo4j dependencies should be provided in pom.xml (there are already there in Neo4j distribution).
Check that your database version and your dependency version in pom.xml are same. GraphDatabaseService::execute method is invented recently (2.2.3 if I remember correctly). Probably your database distribution is older than your maven dependencies.
I'm facing a problem using Spring with Drools. My main problem is that in the unit tests do not occur the error. Follows below the exception
java.lang.RuntimeException: Unexpected global [premioService]
This error occurs when I try to set a global variable in KieSession
Seeing the method StatefulKnowledgeSessionImpl#setGlobal(String, Object) seems that I should set the
globals before create a newInstance. Follows the StatefulKnowledgeSessionImpl#setGlobal code:
public void setGlobal(final String identifier,
final Object value) {
// Cannot set null values
if ( value == null ) {
return;
}
try {
this.kBase.readLock();
startOperation();
// Make sure the global has been declared in the RuleBase
final Map globalDefintions = this.kBase.getGlobals();
final Class type = (Class) globalDefintions.get( identifier );
if ( (type == null) ) {
throw new RuntimeException( "Unexpected global [" + identifier + "]" );
} else if ( !type.isInstance( value ) ) {
throw new RuntimeException( "Illegal class for global. " + "Expected [" + type.getName() + "], " + "found [" + value.getClass().getName() + "]." );
} else {
this.globalResolver.setGlobal( identifier,
value );
}
} finally {
endOperation();
this.kBase.readUnlock();
}
}
Follows my code:
#Inject
protected PremioVisaoService premioVisaoService;
protected final KieSession createSession() {
return this.kieBase.newKieSession();
}
protected final int process() {
final KieSession kieSession = this.createSession();
Object rulesFired = 0;
try {
//here occurs the error
kieSession.execute(CommandFactory.newSetGlobal(PREMIO_SERVICE_GLOBAL_ID, premioVisaoService));
} catch(Exception e) {
e.printStackTrace();
}
}
package br.com.company.brms.model.rules;
import br.com.company.brms.model.*;
import br.com.company.brms.model.premios.*;
import br.com.company.brms.model.tarifas.*;
import function br.com.company.brms.helpers.DomainUtils.getPais;
import function br.com.company.brms.helpers.DomainUtils.getUF;
import function br.com.company.brms.helpers.PremioFactory.novoPremioVisaoPercursoPadrao;
import function br.com.company.brms.helpers.CalculoTarifaHelper.calculaTaxaBasica;
global br.com.company.brms.services.PremioVisaoService premioService;
rule "Rule Example"
ruleflow-group "calculo"
salience -1
when
$averbacao : Averbacao( indicadorAvaria == Constantes.STATUS_SIM )
$taxa : TarifaPercursoVigencia( tipoTarifa == TipoTarifa.AVARIA)
then
PremioVisaoPercursoPadrao premio = novoPremioVisaoPercursoPadrao($taxa, $averbacao);
premio.setValor( calculaTaxaBasica($taxa, $averbacao) );
//insert ( premio );
premioService.inserirPremioCalculado( premio );
//System.out.println( $averbacao + " calculada com o premio: " + premio );
end
Follows below the stacktrace:
java.lang.RuntimeException: Unexpected global [premioService]
at org.drools.core.impl.StatefulKnowledgeSessionImpl.setGlobal(StatefulKnowledgeSessionImpl.java:1124)
at org.drools.core.command.runtime.SetGlobalCommand.execute(SetGlobalCommand.java:65)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.execute(StatefulKnowledgeSessionImpl.java:665)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.execute(StatefulKnowledgeSessionImpl.java:648)
at br.com.company.brms.services.impl.BilhetagemBpmnRunnerServiceImpl.processar(BilhetagemBpmnRunnerServiceImpl.java:87)
at br.com.company.brms.services.impl.BilhetagemBpmnRunnerServiceImpl.processarRegrasMercado(BilhetagemBpmnRunnerServiceImpl.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
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.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 $Proxy68.processarRegrasMercado(Unknown Source)
at br.com.company.brms.services.impl.BilhetagemProcessManagerServiceImpl.processar(BilhetagemProcessManagerServiceImpl.java:111)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
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.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 $Proxy69.processar(Unknown Source)
at br.com.company.brms.spi.impl.BilhetagemServiceAsyncImpl.processarPorCliente(BilhetagemServiceAsyncImpl.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
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.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:95)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Tks in advance
My problem was that I were looking for the DRL files in different jars. I don't know yet how I'll do this in the right way. But the problem definitely was solved.
I finally tracked down what the root cause of this is:
If you have a rule and you want to setGlobal for that rule, you must have the global defined in that rule (the .drl file), such as;
global net.mikeski.ProviderImpl provider
Then, kSession.setGlobal("provider", myProviderImpl); will work.
I discovered this by looking at the Drools setGlobal method in StatefulKnowledgeSessionImpl.java:
...
final Class type = (Class) globalDefintions.get( identifier );
if ( (type == null) ) {
throw new RuntimeException( "Unexpected global [" + identifier + "]" );
} else if ( !type.isInstance( value ) ) {
throw new RuntimeException( "Illegal class for global. " + "Expected [" + type.getName() + "], " + "found [" + value.getClass().getName() + "]." );
} else {
this.globalResolver.setGlobal( identifier,
value );
}
...
Based on the example mentioned in - https://gist.github.com/canthony/3655917 I have created a new Vaadin example to upload an Excel/CSV file.
Based on the comments mentioned, I even downloaded opencsv-3.0 from the http://opencsv.sourceforge.net and added them into the project.
Below is how I added them
Right Click on Vaadin project created --> Properties --> Java Build Path --> Add Library (Created new User Library) --> New User Library --> User Libraries --> New (In User Libraries page) --> Created New Library with name CSV --> Included the OpenCSV3.0-jar
Finally this is how my setup looks like:
No errors or warnings are present, but when I publish on tomcat I get below error. This error comes up when I Browse a file and click on Upload button. Can some one please help?
SEVERE:
java.lang.NoClassDefFoundError: au/com/bytecode/opencsv/CSVReader
at com.example.uploadexcel.UploadexcelUI.buildContainerFromCSV(UploadexcelUI.java:101)
at com.example.uploadexcel.UploadexcelUI$2.uploadFinished(UploadexcelUI.java:63)
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 com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:198)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:161)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:979)
at com.vaadin.ui.Upload.fireUploadInterrupted(Upload.java:875)
at com.vaadin.ui.Upload$2.streamingFailed(Upload.java:1166)
at com.vaadin.server.communication.FileUploadHandler.streamToReceiver(FileUploadHandler.java:615)
at com.vaadin.server.communication.FileUploadHandler.handleFileUploadValidationAndData(FileUploadHandler.java:447)
at com.vaadin.server.communication.FileUploadHandler.doHandleSimpleMultipartFileUpload(FileUploadHandler.java:397)
at com.vaadin.server.communication.FileUploadHandler.handleRequest(FileUploadHandler.java:282)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1402)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:305)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
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)
I don't understand why I get java.lang.NoClassDefFoundError when I have added the required jar into the Java build path.
Full code:
public class UploadexcelUI extends UI {
protected File tempFile;
protected Table table;
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = UploadexcelUI.class)
public static class Servlet extends VaadinServlet {
}
#SuppressWarnings("deprecation")
#Override
protected void init(VaadinRequest request) {
Upload upload = new Upload("Upload CSV File", new Upload.Receiver() {
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
try {
/* Here, we'll stored the uploaded file as a temporary file. No doubt there's
a way to use a ByteArrayOutputStream, a reader around it, use ProgressListener (and
a progress bar) and a separate reader thread to populate a container *during*
the update.
This is quick and easy example, though.
*/
tempFile = File.createTempFile("temp", ".csv");
return new FileOutputStream(tempFile);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
});
upload.addListener(new Upload.FinishedListener() {
#Override
public void uploadFinished(Upload.FinishedEvent finishedEvent) {
try {
/* Let's build a container from the CSV File */
FileReader reader = new FileReader(tempFile);
IndexedContainer indexedContainer = buildContainerFromCSV(reader);
reader.close();
tempFile.delete();
/* Finally, let's update the table with the container */
table.setCaption(finishedEvent.getFilename());
table.setContainerDataSource(indexedContainer);
table.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
});
/* Table to show the contents of the file */
table = new Table();
table.setVisible(false);
/* Main layout */
VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
layout.setSpacing(true);
layout.addComponent(table);
layout.addComponent(upload);
setContent(layout);
}
/**
* Uses http://opencsv.sourceforge.net/ to read the entire contents of a CSV
* file, and creates an IndexedContainer from it
*
* #param reader
* #return
* #throws IOException
*/
#SuppressWarnings("resource")
protected IndexedContainer buildContainerFromCSV(Reader reader) throws IOException {
IndexedContainer container = new IndexedContainer();
CSVReader csvReader = new CSVReader(reader);
String[] columnHeaders = null;
String[] record;
while ((record = csvReader.readNext()) != null) {
if (columnHeaders == null) {
columnHeaders = record;
addItemProperties(container, columnHeaders);
} else {
addItem(container, columnHeaders, record);
}
}
return container;
}
/**
* Set's up the item property ids for the container. Each is a String (of course,
* you can create whatever data type you like, but I guess you need to parse the whole file
* to work it out)
*
* #param container The container to set
* #param columnHeaders The column headers, i.e. the first row from the CSV file
*/
private static void addItemProperties(IndexedContainer container, String[] columnHeaders) {
for (String propertyName : columnHeaders) {
container.addContainerProperty(propertyName, String.class, null);
}
}
/**
* Adds an item to the given container, assuming each field maps to it's corresponding property id.
* Again, note that I am assuming that the field is a string.
*
* #param container
* #param propertyIds
* #param fields
*/
#SuppressWarnings("unchecked")
private static void addItem(IndexedContainer container, String[] propertyIds, String[] fields) {
if (propertyIds.length != fields.length) {
throw new IllegalArgumentException("Hmmm - Different number of columns to fields in the record");
}
Object itemId = container.addItem();
Item item = container.getItem(itemId);
for (int i = 0; i < fields.length; i++) {
String propertyId = propertyIds[i];
String field = fields[i];
item.getItemProperty(propertyId).setValue(field);
}
}
}
Probably, it is a dependency issue. You need to add commons-lang3 as dependency.
You can find the required .jar file here.
Check this answer.
P.S.- May be I should have put this in comment but as my reputation is quite low, I can't.
Here are the satisfactory enough dependencies of net.sf.opencsv:opencsv:2.3:
$HOME/.m2/repository/net/sf/opencsv/opencsv/2.3/opencsv-2.3.jar,$HOME/.m2/repository/org/apache/commons/commons-lang3/3.1/commons-lang3-3.1.jar,$HOME/.m2/repository/commons-beanutils/commons-beanutils/1.7.0/commons-beanutils-1.7.0.jar,$HOME/.m2/repository/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar
I've requirement where in my input request I'm getting parameters which are password thats needs to be masked Since I've kept logging level as debug, the input xml is getting logged with password fields. I fixed this problem by overriding LogginginInterceptors and LoggingOutInterceptor.
However on further analysis, found that Abstract invoker is printing method invoked along with parameters for the method invoked. Hence password field is again getting printed. I can override the method which prints parameter. But where and how I need to register my my custom abstractmethod invoker.
2014-04-03 20:16:54,827 [http-8443-1] DEBUG o.a.c.s.invoker.AbstractInvoker - Invoking method public com.kp.schema.CredResObject com.kp.CredentialsImpl.updateCredentials(com.kp.schema.CredReqObject) throws com.kp.FaultResponse on object com.kp.CredentialsImpl#2ee4e8 with params [CredReqObject [clientID=kpid, host=asda, userName=u1, passWord=sssss]].
Custom Invoker
public class NMSCustomInvoker extends AbstractInvoker {
static final ResourceBundle BUNDLE = BundleUtils
.getBundle(FactoryInvoker.class);
private Factory factory;
public NMSCustomInvoker(Factory factory) {
this.factory = factory;
}
public NMSCustomInvoker() {
}
public void setFactory(Factory f) {
this.factory = f;
}
#Override
public Object getServiceObject(Exchange ex) {
try {
return factory.create(ex);
} catch (Fault e) {
throw e;
} catch (Throwable e) {
throw new Fault(new Message("CREATE_SERVICE_OBJECT_EXC", BUNDLE), e);
}
}
public void releaseServiceObject(final Exchange ex, Object obj) {
factory.release(ex, obj);
}
#Override
protected Object performInvocation(Exchange exchange,
final Object serviceObject, Method m, Object[] paramArray)
throws Exception {
paramArray = insertExchange(m, paramArray, exchange);
return m.invoke(serviceObject, paramArray);
}
}
I'm getinng null pointer error since factory object is null.
Updated StackTrace
org.apache.cxf.interceptor.Fault: Could not instantiate service object.
at mypackage.NMSCustomInvoker.getServiceObject(NMSCustomInvoker.java:45) ~[NMSCustomInvoker.class:na]
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:50) ~[cxf-api-2.7.8.jar:2.7.8]
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58) ~[cxf-api-2.7.8.jar:2.7.8]
at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:94) ~[cxf-api-2.7.8.jar:2.7.8]
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:272) ~[cxf-api-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121) [cxf-api-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:239) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:248) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:222) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:153) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:167) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:286) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:211) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) [servlet-api-3.0-alpha-1.jar:3.0-alpha-1]
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:262) [cxf-rt-transports-http-2.7.8.jar:2.7.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) [catalina.jar:6.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:6.0.37]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) [catalina.jar:6.0.37]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) [catalina.jar:6.0.37]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) [catalina.jar:6.0.37]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) [catalina.jar:6.0.37]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [catalina.jar:6.0.37]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) [catalina.jar:6.0.37]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861) [tomcat-coyote.jar:6.0.37]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606) [tomcat-coyote.jar:6.0.37]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) [tomcat-coyote.jar:6.0.37]
at java.lang.Thread.run(Thread.java:662) [na:1.6.0_32]
Caused by: java.lang.NullPointerException: null
at mypackage.NMSCustomInvoker.getServiceObject(NMSCustomInvoker.java:41) ~[NMSCustomInvoker.class:na]
... 26 common frames omitted
You can set the invoker yourself if you are using cxf-jaxws or cxf-jaxrs front end API, just like this
ServerFactoryBean.setInvoker(new MyInvoker());
If you are using spring configuration, you can set your custom invoker just like this
<jaxws:endpoint id="simpleWithBinding"
implementor="#greeter"
address="http://localhost:8080/simpleWithAddress">
<jaxws:invoker>
<bean id="myInvoker" class="com.example.MyInvoker"/>
</jaxws:invoker>
</jaxws:endpoint>
Does anybody know how can I send an object, to be more specific a List, a result from a query in Database, to my servlet, which is another Java application and is not in Google App Engine.
Update: My servlet in GAE, is working fine, it serialize my List<Video> result:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
String titulo = req.getParameter("titulo");
String json = "";
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery("select from "+Video.class.getName()+ " where titulo.startsWith('"+titulo+"')");
List<Video> video = (List<Video>) pm.newQuery(query).execute();
json = new Gson().toJson(video);
System.out.println("SERIALIZED >> " + json);
res.setContentType("application/json");
res.setCharacterEncoding("UTF-8");
res.getWriter().write(json);
}
My calling servlet has this method:
public void receberMetaDados(String titulo) throws IOException, Exception{
InputStream input = new URL("http://localhost:8888/serve?titulo="+titulo).openStream();
Reader reader = new InputStreamReader(input, "UTF-8");
List<Video> results = new Gson().fromJson(reader, new TypeToken<List<Video>>(){}.getType());
}
I get the following exception:
com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter#2d7440 failed to deserialized json object [{"id":"30102010113847691504","titulo":"CIty of Angel","descricao":"Um belo filme","date":"30/11/2010 13:38:47"},{"id":"30102010115514196289","titulo":"CIty of Angel","descricao":"Um belo filme","date":"30/11/2010 13:55:14"},{"id":"3010201011561620697","titulo":"CIty of Angel","descricao":"Um belo filme","date":"30/11/2010 13:56:01"},{"id":"3010201012829669834","titulo":"CIty of Angel","descricao":"Um belo filme","date":"30/11/2010 14:08:29"},{"id":"3010201012849669427","titulo":"CIty of Angel","descricao":"Um belo filme","date":"30/11/2010 14:08:49"},{"id":"3010201012919920893","titulo":"CIty of Angel","descricao":"Um belo filme","date":"30/11/2010 14:09:19"}] given the type java.util.List
at com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDeserializerExceptionWrapper.java:63)
at com.google.gson.JsonDeserializationVisitor.invokeCustomDeserializer(JsonDeserializationVisitor.java:88)
at com.google.gson.JsonDeserializationVisitor.visitUsingCustomHandler(JsonDeserializationVisitor.java:76)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:106)
at com.google.gson.JsonDeserializationContextDefault.fromJsonArray(JsonDeserializationContextDefault.java:64)
at com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDeserializationContextDefault.java:49)
at com.google.gson.Gson.fromJson(Gson.java:568)
at com.google.gson.Gson.fromJson(Gson.java:515)
at com.google.gson.Gson.fromJson(Gson.java:484)
at classes.Manip.receberMetaDados(Manip.java:64)
at servlet.OurTube_Servlet.buscar(OurTube_Servlet.java:105)
at servlet.OurTube_Servlet.doPost(OurTube_Servlet.java:55)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.RuntimeException: No-args constructor for class classes.Video does not exist. Register an InstanceCreator with Gson for this type to fix this problem.
at com.google.gson.MappedObjectConstructor.constructWithNoArgConstructor(MappedObjectConstructor.java:64)
at com.google.gson.MappedObjectConstructor.construct(MappedObjectConstructor.java:53)
at com.google.gson.JsonObjectDeserializationVisitor.constructTarget(JsonObjectDeserializationVisitor.java:40)
at com.google.gson.JsonDeserializationVisitor.getTarget(JsonDeserializationVisitor.java:56)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:109)
at com.google.gson.JsonDeserializationContextDefault.fromJsonObject(JsonDeserializationContextDefault.java:73)
at com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDeserializationContextDefault.java:51)
at com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter.deserialize(DefaultTypeAdapters.java:548)
at com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter.deserialize(DefaultTypeAdapters.java:510)
at com.google.gson.JsonDeserializerExceptionWrapper.deserialize(JsonDeserializerExceptionWrapper.java:50)
... 25 more
I don't know what is wrong, thank you by your assist.
That depends. If it is to be returned as a HTTP response on a HTTP request, then you need to convert it to a string following a specific format. The popular ones are XML and JSON. The other end has just to read the XML or JSON string in and then recreate the list based on this information.
Here's an example with JSON and Google Gson which is able to convert Java objects to JSON and vice versa.
The called servlet:
List<Result> results = someDAO.list();
String json = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
The calling servlet:
InputStream input = new URL("http://example.com/servleturl").openStream();
Reader reader = new InputStreamReader(input, "UTF-8");
List<Result> results = new Gson().fromJson(reader, new TypeToken<List<Result>>(){}.getType());
Update: as per the exception:
Caused by: java.lang.RuntimeException: No-args constructor for class classes.Video does not exist.
This is pretty self-explaining. Supply a default constructor.
public class Video {
public Video() {
// Always keep default c'tor alive whenever you
// supply another c'tor in a Javabean class.
}
}