I have created a Dataservice in WSO2 to execute SQL Query TRUNCATE TABLE Student and expose it as an API , but i got this error
[2022-12-07 16:33:57,222] ERROR {DBInOnlyMessageReceiver} - Error in
in-only message receiver DS Fault Message: Error in DS non result
invoke. DS Code: DATABASE_ERROR Nested Exception:-
javax.xml.stream.XMLStreamException: DS Fault Message: Error in
'SQLQuery.processStoredProcQuery': DS Fault Message: Error in
'createProcessedPreparedStatement' DS Code: UNKNOWN_ERROR Nested
Exception:- java.sql.SQLException: Unable to retrieve metadata for
procedure.
DS Code: DATABASE_ERROR Source Data Service:- Name: RADMINDataService
Location:
/home/master/Downloads/IntegrationStudio/runtime/microesb/tmp/carbonapps/-1234/1670427210936TestCompositeApplication_1.0.0.car/RADMINDataService_1.0.0/RADMINDataService-1.0.0.dbs
Description: Exposing the radmin data service as a REST service
Default Namespace: http://ws.wso2.org/dataservice/samples/json_sample
Current Request Name: _gettruncatenumseq Current Params: {} Nested
Exception:- DS Fault Message: Error in
'createProcessedPreparedStatement' DS Code: UNKNOWN_ERROR Nested
Exception:- java.sql.SQLException: Unable to retrieve metadata for
procedure.
at
org.wso2.micro.integrator.dataservices.core.dispatch.SingleDataServiceRequest.processSingleRequest(SingleDataServiceRequest.java:117)
at
org.wso2.micro.integrator.dataservices.core.dispatch.SingleDataServiceRequest.processRequest(SingleDataServiceRequest.java:66)
at
org.wso2.micro.integrator.dataservices.core.dispatch.DataServiceRequest.dispatch(DataServiceRequest.java:358)
at
org.wso2.micro.integrator.dataservices.core.DataServiceProcessor.dispatch(DataServiceProcessor.java:40)
at
org.wso2.micro.integrator.dataservices.core.DBInOnlyMessageReceiver.invokeBusinessLogic(DBInOnlyMessageReceiver.java:52)
at
org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:110)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
at
org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:376)
at
org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:190)
at
org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
at
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834) Caused by:
javax.xml.stream.XMLStreamException: DS Fault Message: Error in
'SQLQuery.processStoredProcQuery': DS Fault Message: Error in
'createProcessedPreparedStatement' DS Code: UNKNOWN_ERROR Nested
Exception:- java.sql.SQLException: Unable to retrieve metadata for
procedure.
This is my configuration file
<query id="truncatenum" useConfig="mysql">
<sql><![CDATA[TRUNCATE TABLE Student]]></sql>
</query>
<resource method="GET" path="truncatenum">
<description />
<call-query href="truncatenum"/>
</resource>
I don't think the error is caused by the code snippet you shared. The following seems correct.
<query id="truncatenum" useConfig="mysql">
<sql><![CDATA[TRUNCATE TABLE Student]]></sql>
</query>
<resource method="GET" path="truncatenum">
<description />
<call-query href="truncatenum"/>
</resource>
Probably one of the queries you have doesn't match the input parameters you are providing. Hence double check all the other queries you have.
Update
You are correct the TRUNCATE query is executed as a STOREDPROC. I had a closer look at the source-code and it seems if the QUERY String doesn't start with one of the following it's inferred as a STOREDPROC. This is definitely a bug in WSO2.
The weird thing is, in my case the TRUNCATE query is executed as a Stored Procedure successfully. So I assume there is a difference in your Dataeervice from the one I'm trying. Can you create the following Dataservice as it is and try it out? (Just change the connection parameters)
Dataservice
<data name="RESTDataService" serviceNamespace="http://ws.wso2.org/dataservice/samples/json_sample" transports="http https">
<description>Exposing the data service as a REST service.</description>
<config id="default">
<property name="driverClassName">com.mysql.jdbc.Driver</property>
<property name="url">jdbc:mysql://localhost:3306/school_db</property>
<property name="org.wso2.ws.dataservice.user">root</property>
<property name="org.wso2.ws.dataservice.password">root123456</property>
</config>
<resource method="GET" path="truncatenum">
<description />
<call-query href="truncatenum" />
</resource>
<query id="truncatenum" useConfig="default">
<sql><![CDATA[TRUNCATE TABLE students]]></sql>
</query>
</data>
Request
curl --location --request GET 'http://localhost:8290/services/RESTDataService/truncatenum'
If you still get the error. Please enable DEBUG logs for the package org.wso2.micro.integrator.dataservices and share the logs.
Related
I use WSO2 EI 6.6.0 and Micro Integrator 4.0.0. I have an api to get data, but for this I need to authenticate and get a token to use in a further request. for authentication I use separately created api and call it from first flow. For authentication I need to create a payload and send it in the request body to the server, but I get an error. The problem is repeated on different servers and I do not understand what is the reason.
My Auth API looks like this:
<api context="/auth" name="AuthGateway" xmlns="http://ws.apache.org/ns/synapse">
<resource methods="GET" uri-template="/gateway">
<inSequence>
<payloadFactory media-type="json">
<format>{"username": "adm", "password": "admin"}</format>
<args/>
</payloadFactory>
<call>
<endpoint>
<http method="post" uri-template="https://1537-212-90-188-166.ngrok.io/auth/login">
<suspendOnFailure>
<initialDuration>-1</initialDuration>
<progressionFactor>-1</progressionFactor>
<maximumDuration>0</maximumDuration>
</suspendOnFailure>
<markForSuspension>
<retriesBeforeSuspension>0</retriesBeforeSuspension>
</markForSuspension>
</http>
</endpoint>
</call>
<log separator="
">
<property expression="json-eval($)" name="log_auth"/>
</log>
<respond/>
</inSequence>
<outSequence/>
<faultSequence/>
</resource>
My Data API looks like this:
<resource methods="GET" uri-template="/fieldCard?*">
<inSequence>
<propertyGroup>
<property name="uri.var.version" expression="$url:version" scope="default" type="STRING"/>
<property name="uri.var.size" expression="$url:size" scope="default" type="STRING"/>
<property name="uri.var.page" expression="$url:page" scope="default" type="STRING"/>
</propertyGroup>
<log level="full" separator="
">
<property name="version" expression="$ctx:uri.var.version"/>
<property name="size" expression="$ctx:uri.var.size"/>
<property name="page" expression="$ctx:uri.var.page"/>
</log>
<call>
<endpoint>
<http method="GET" uri-template="http://localhost:8290/auth/gateway"/>
</endpoint>
</call> .......
In the console I get messages:
[2022-05-02 19:16:12,962] ERROR {JsonStreamBuilder} - Error occurred while processing document for application/json java.lang.reflect.InvocationTargetException
Caused by: org.apache.axis2.AxisFault: #Can not parse stream. MessageID: urn:uuid:7ac6a4c9-0ed1-4973-87d4-69dad6d4a950. Error>>> #getNewJsonPayload. Could not save JSON payload. Invalid input stream found. Payload is not a JSON string.
org.apache.synapse.commons.json.JsonStreamBuilder.processDocument(JsonStreamBuilder.java:43)
... 21 more
Caused by: org.apache.axis2.AxisFault: #getNewJsonPayload. Could not save JSON payload. Invalid input stream found. Payload is not a JSON string.
[2022-05-02 19:16:12,963] ERROR {DeferredMessageBuilder} - Error building message org.apache.axis2.AxisFault
[2022-05-02 19:16:12,964] ERROR {RelayUtils} - Error while building Passthrough stream org.apache.axis2.AxisFault
[2022-05-02 19:16:12,964] ERROR {SequenceMediator} - {api:AuthGateway} Error while building message. Error while building Passthrough stream org.apache.axis2.AxisFault: Error while building Passthrough stream
I removed the detailed stack trace. If it is needed to understand the problem - I can add it.
P.S. When calling the auth API directly I get the token and the response is correct.
[2022-05-02 19:20:17,560] INFO {org.apache.synapse.mediators.builtin.LogMediator} - To: http://www.w3.org/2005/08/addressing/anonymous
WSAction:
SOAPAction:
MessageID: urn:uuid:817185a7-39a4-4418-a696-72473672997d
Direction: request
log_auth = {"access_token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMyIsInVzZXJfbmFtZSI6Im...
Payload: {"access_token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMyIsInVzZXJfbmFtZSI6Im...
Please help me understand the problem.
UPD: I reinstalled the server because I thought the error might be there or I broke the config files. created a new project and wrote a new same thread, but the error still repeats.
Good. The problem was that Postman has a Header Accept-Encoding option. When this parameter was disabled, the request became correct and the response began to come without errors!
I have an Apache Camel route which invokes restlet component and would like to use the redelivery mechanism from the exception handler which performs some processing on every failure to update my database record which should be done on generic route. So, I'm trying to continue the exception in one route and handle the same exception in another route through direct component. But exception is not continuing to generic route.
1st route:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:cxf="http://camel.apache.org/schema/cxf"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd">
<!-- CXF Rest Endpoint Declaration -->
<cxf:rsServer address="http://localhost:9092/rest/corp"
id="FetchCDFRestRequest" serviceClass="com.tcl.Service.Service" />
<bean class="com.tcl.ExceptionOccurredRefProcessor" id="exProc" />
<bean class="org.apache.camel.builder.DeadLetterChannelBuilder"
id="DLCErrorHandler">
<property name="deadLetterUri"
value="activemq:queue:DMS.FAILURES.DLQ" />
<property name="redeliveryPolicy" ref="redeliveryPolicy" />
</bean>
<bean class="org.apache.camel.processor.RedeliveryPolicy"
id="redeliveryPolicy">
<property name="maximumRedeliveries"
value="3" />
<property name="maximumRedeliveryDelay" value="2000" />
<property name="retryAttemptedLogLevel" value="WARN" />
</bean>
<camelContext id="Corp"
xmlns="http://camel.apache.org/schema/spring">
<errorHandler id="eh" onExceptionOccurredRef="exProc">
<redeliveryPolicy id="redeliveryPolicy" />
</errorHandler>
<route id="MainRouteOppIDFolder" streamCache="true">
<from id="_CreateOppIDFolder"
uri="restlet:http://localhost:9092/rest/corp/createOppIDFolder?restletMethod=POST" />
----------
<to uri="restlet:http://localhost:9902/CreateOppIDFolder?restletMethod=POST" />
------------
<onException id="_onException1" useOriginalMessage="true">
<exception>java.lang.Exception</exception>
<handled>
<simple>false</simple>
</handled>
<log id="_log1" message="Cont... ex >>>>> ${exception.message} "/>
<to uri="direct:ExceptionHandle"/>
</onException>
</route>
</camelContext>
</beans>
2nd route:
<route errorHandlerRef="DLCErrorHandler" >
<from id="_from2" uri="direct:ExceptionHandle"/>
<log id="_log4" message="Req>>>>> ${body}"/>
<onException id="_onException2"
onExceptionOccurredRef="exProc" redeliveryPolicyRef="redeliveryPolicy">
<exception>java.lang.Exception</exception>
<handled>
<simple>true</simple>
</handled>
<log id="_log3" loggingLevel="INFO" message="Handled ex >>>>> ${exception.message} "/>
<choice id="_choice1">
<when id="_when1">
<simple>${header.errorMessage} contains 'Could not send Message' || ${header.errorMessage} contains 'Connection timed out'</simple>
<to id="_to1" pattern="OutOnly" uri="activemq:queue:DMS.FAILURES"/>
</when>
<otherwise id="_otherwise1">
<log id="_log5" loggingLevel="ERROR" message="Exception occured in otherwise block >>>>>> ${exception.stacktrace} "/>
</otherwise>
</choice>
</onException>
</route>
12:11:24.384 [Restlet-781390346] WARN o.a.c.processor.DeadLetterChannel - Failed delivery for (MessageId: ID-DESKTOP-P2DBOO5-1580280046927-0-8 on ExchangeId: ID-DESKTOP-P2DBOO5-1580280046927-0-7).On delivery attempt: 0 caught: org.apache.camel.component.restlet.RestletOperationException: Restlet operation failed invoking http://localhost:9902/CreateOppIDFolder with statusCode: 500 /n responseBody:org.apache.cxf.interceptor.Fault: Could not send Message.
Caused by: java.net.ConnectException: ConnectException invoking http://172.16.18.113:7001/services/TCLDMSSFDCService/TCLDMSSFDCService: Connection timed out: connect
Caused by: java.net.ConnectException: Connection timed out: connect
12:11:24.392 [Restlet-781390346] INFO MainRouteOppIDFolder - Cont... ex >>>>> Restlet operation failed invoking http://localhost:9902/CreateOppIDFolder with statusCode: 500 /n responseBody:org.apache.cxf.interceptor.Fault: Could not send Message.
Caused by: java.net.ConnectException: ConnectException invoking http://172.16.18.113:7001/services/TCLDMSSFDCService/TCLDMSSFDCService: Connection timed out: connect
Caused by: java.net.ConnectException: Connection timed out: connect
12:11:24.396 [Restlet-781390346] INFO _route1 - Req>>>>> {
"oppID" : "10268216",
"salesOrganization" : "Commerical Finance",
"salesVertical" : "CEQ",
"productName" : "Construction Equipment Finance",
"applicantName" : "SGS INFRASTRUCTURE",
"docName" : null,
"appNature" : null,
"docType" : null,
"base64Content" : null
}
12:11:24.405 [Restlet-781390346] ERROR o.a.c.processor.DeadLetterChannel - Failed delivery for (MessageId: ID-DESKTOP-P2DBOO5-1580280046927-0-8 on ExchangeId: ID-DESKTOP-P2DBOO5-1580280046927-0-7). Exhausted after delivery attempt: 1 caught: org.apache.camel.component.restlet.RestletOperationException: Restlet operation failed invoking http://localhost:9902/CreateOppIDFolder with statusCode: 500 /n responseBody:org.apache.cxf.interceptor.Fault: Could not send Message.
Caused by: java.net.ConnectException: ConnectException invoking http://172.16.18.113:7001/services/TCLDMSSFDCService/TCLDMSSFDCService: Connection timed out: connect
Caused by: java.net.ConnectException: Connection timed out: connect
. Processed by failure processor: FatalFallbackErrorHandler[Pipeline[[Channel[Log(MainRouteOppIDFolder)[Cont... ex >>>>> ${exception.message} ]], Channel[sendTo(direct://ExceptionHandle)], Channel[Log(MainRouteOppIDFolder)]]]]
Message History
RouteId ProcessorId Processor Elapsed (ms)
[MainRouteOppIDFold] [MainRouteOppIDFold] [restlet://http://localhost:9092/rest/corp/createOppIDFolder?restletMethod=POST] [ 21608]
[MainRouteOppIDFold] [_CreateOppIDFolder] [restlet:http://localhost:9902/CreateOppIDFolder?restletMethod=POST ] [ 21319]
[MainRouteOppIDFold] [_to2 ] [direct:ExceptionHandle ] [ 1]
[_route1 ] [_log4 ] [log ] [ 1]
Stacktrace
org.apache.camel.component.restlet.RestletOperationException: Restlet operation failed invoking http://localhost:9902/CreateOppIDFolder with statusCode: 500 /n responseBody:org.apache.cxf.interceptor.Fault: Could not send Message.
Caused by: java.net.ConnectException: ConnectException invoking http://172.16.18.113:7001/services/TCLDMSSFDCService/TCLDMSSFDCService: Connection timed out: connect
Caused by: java.net.ConnectException: Connection timed out: connect```
**Any suggestions please?**
To be honest: I don't see your problem.
Your exception block does
<log id="_log1" message="Cont... ex >>>>> ${exception.message} "/>
<to uri="direct:ExceptionHandle"/>
The direct route does
<log id="_log4" message="Req>>>>> ${body}"/>
And your log shows
Cont... ex >>>>> [error message]
Req>>>>> [message body]
So everything works as you expect. Am I missing something?
Update due to comment
The onException block of the second route is NOT called as long as no Exception occurs in the second route. The second route normally receives a message and processes it.
You can still access the exception information on the message with ${exception}.
I've seen all sorts of posts on using Spring and MyBatis with transactions, but I'm facing a problem with rollbacks not working with plain old JDBC.
My ( test / throwaway) code is pretty simple : I open a session, insert a rec, throw an error on purpose and rollback the transaction. However, it always commits.
public static void main (String[] args){
//-- omitted for brevity
try {
org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sess = sqlSessionFactory.openSession(false);
BillsMapper mapper = sess.getMapper(BillsMapper.class);
BillState billState = new BillState();
billState.setBillId(-1);
billState.setLastName("TESTER");
billState.setFirstName("TESTER");
mapper.insert(billState);
logger.info("Post insert: key = {}", billState.getBillId());
if(1 == 1)
throw new RuntimeException("Error Thrown on purpose...testing rollback ");
sess.commit();
}catch(Exception e){
logger.error("Error: {}", e);
sess.rollback();
}finally{
sess.close();
logger.info("Finito!");
}
}
The logs show:
DEBUG | (BaseJdbcLogger.java:145) - ==> Preparing: insert into bills (users_userId, refId, firstName, ...
DEBUG | (BaseJdbcLogger.java:145) - ==> Parameters: 67(Integer), 67-120530180328(String), TESTER(String), ...
DEBUG | (BaseJdbcLogger.java:145) - <== Updates: 1
INFO | (TestAction.java:50) - Post insert: key = 2478
ERROR | (TestAction.java:56) - Error: {} java.lang.RuntimeException: Error Thrown on purpose...testing rollback at com.s2stest.TestAction.main(TestAction.java:53)
DEBUG | (JdbcTransaction.java:79) - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (JdbcTransaction.java:122) - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (JdbcTransaction.java:90) - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (PooledDataSource.java:344) - Returned connection 924748027 to pool.
Note the resetting of autocommit before closing the connection.... Would resetting autcommit before closing the SqlSession cause my rolled-back transaction to be committed? If so, is this a bug? Has anyone gotten JDBC working with transactions? I need it for testing, and I'd value some help. Right now, no transactions can be rolled back.
I've looked at the MyBatis source, and it indeed calls resetAutocommit before closing the connection. I'm using MySQL 5.6 and mysql-connector-java-5.1.36.jar for the driver if someone has a workaround that they've found.
--- UPDATE ---
mybatis-config.xml is as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="SLF4J" />
</settings>
<typeAliases>
<package name="com.ship2storage.domain" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mytestDb?zeroDateTimeBehavior=convertToNull" />
<property name="username" value="--shhh!!--" />
<property name="password" value="--shhh!!--" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ship2storage/db/maps/BillsMapper.xml" />
</mappers>
</configuration>
OK, I've found the answer by digging deeper into my setup. It seems that the MySQL storage engine I installed for my test DB is ISAM. ISAM does not support transactions. I switched to InnoDB using the following SQL tidbit, and transactions now work with JDBC:
ALTER TABLE bills ENGINE=InnoDB;
I haven't tried this, but it looks like you can also do this temporarily too:
SET default_storage_engine=InnoDB;
Hopefully this will help someone. The code/config posted above works.
When I'm trying to create a new EntityManager to persist my data, i get the following Error:
javax.persistence.PersistenceException: Unable to build entity manager factory
I using the JPA-Persistence Provider of Hibernate...
unluckily I couldn't find any helpful post in stackoverflow / with googling...
Does anybody have an idea where the cause of the error could lie?
Thank you for your help!
code-snippets:
creation of entitymanager
EntityManager em;
EntityManagerFactory fact = Persistence.createEntityManagerFactory("bachelordebug"); // Here it crashes
em = fact.createEntityManager();
stacktrace
javax.persistence.PersistenceException: Unable to build entity manager factory
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:81)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at com.uzh.platform.api.util.AssignmentUtil.findAll(AssignmentUtil.java:20)
at com.uzh.platform.api.services.GetAssignments.getAssignments(GetAssignments.java:22)
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 org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:402)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:349)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:106)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:259)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1010)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1221)
at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:156)
at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:233)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1212)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:399)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="bachelordebug" transaction-type="RESOURCE_LOCAL">
<!-- <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> -->
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.uzh.platform.data.dao.Assignment</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://127.0.0.1:5432/bachelor"/>
<property name="javax.persistence.jdbc.user" value="bachelor"/>
<property name="javax.persistence.jdbc.password" value="bachelor14"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.release_mode" value="after_statement"/>
<property name="connection.pool_size" value="1"/>
<property name="dialect" value="org.postgresql.Driver"/>
<property name="current_session_context_class" value="thread"/>
<property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="show_sql" value="true"/>
</properties>
</persistence-unit>
(Question answered in comments and edits. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
SOLVED
I finally found my error!
In my JPA-Entity class, I misspelled my Named-Query Annotation (even though I don't use it)
#NamedQuery(name="Assignment.findAll", query ="SELECT * FROM assignment")
of course one has to write that in capital Letters, i.e. "Assignment" (i.e. all terms like they appear in the service-class!)
3 days wasted with this stupid error - but now I learned how to do it! :-)
Thanks anyway for your help!
Since the error can indicate a lot of different causes it seems best to get to the cause examining the Hibernate DEBUG log statements (we use logback, but it should work in any other logging framework similarly):
With this you get a lot of output, but can determine the actually interesting classes (it is very likely you will spot the cause here already):
// (logback.groovy)
logger( "org.hibernate", DEBUG )
Which for us showed something like the following (where Mapping collection: foo.Bar.field -> some_tab_x was the info we needed to spot the faulty mapping):
07:32:43.720 D~ [main ~ main] [ : ] CollectionSecondPass:SecondPass: 67|
Second pass for collection: foo.Bar.field
07:32:43.720 D~ [main ~ main] [ : ] c.a.CollectionBinder:SecondPass: 823|
Binding a OneToMany: foo.Bar.field through a foreign key
07:32:43.720 D~ [main ~ main] [ : ] c.a.CollectionBinder:SecondPass: 861|
Mapping collection: foo.Bar.field -> some_tab_x
07:32:43.727 D~ [main ~ main] [ : ] ePersistenceProvider:gerFactory: 82|
Unable to build entity manager factory
07:32:43.743 E~ [main ~ main] [ : ] .l.f.m.m.MgFooTstJu:AndRethrow: 74|
MyException: unit test error loading Foo with id: 4342153208-2:
<java.lang.NullPointerException> =>
<javax.persistence.PersistenceException: Unable to build entity manager factory>
To restrict the logging again (if there are multiple places to fix your JPA mapping), we then used something like the following:
// (logback.groovy)
//logger( "org.hibernate", DEBUG ) // log everything
// infos on annotation mappping, e.g. getting NullPointerExceptions with
// javax.persistence.PersistenceException: Unable to build entity manager factory
logger( "org.hibernate.cfg.annotations.CollectionBinder", DEBUG )
(E.g. in Eclipse just use CTRL+SHIFT+T to search for the type you like to debug, if the log output does not show the complete classname)
I encountered the same error, and unfortunately the above answer didn't help me a lot. So I looked to other errors reported in my case where I found this error:
com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value 'EEST' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
I solved it as specified the this answer and it's comments, by replacing my connection url with : "jdbc:mysql://localhost:3306/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"
That solved all errors including the one noted in this question:
javax.persistence.PersistenceException: Unable to build entity manager factory
I hope this helps others coming across the same issue I faced.
add the id annotation in your entity class
#Entity
public class yourClass{
#Id
private Long id;
...
}
Am trying to call a service running in tomcat through remote objects from flex, when i call the remote object it throws flex invalid session error
Channel.Ping.Failed error There was an unhandled failure on the server. The FlexSession is invalid. url: 'http://localhost:8080/Server/messagebroker/amf/'
[RemoteObject destination="reinforcementService" channelSet="[ChannelSet null ]"]
Send failed
Code
<s:CallResponder id="getReinforcementsResult"/>
<services:ReinforcementService id="reinforcementService" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/>
<s:RemoteObject id="ro2" destination="reinforcementService" endpoint="{parentApplication.serviceURL}" result="ro2_resultHandler(event)" fault="ro2_faultHandler(event)"/>
and i call the method using
ro2.getReinforcements();
and i disconnect the remote object in result handler to avoid DuplicateFlexSessions error
ro2.disconnect();
and the channel definition in services-config.xml is as follows
<channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
<endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/>
<properties>
<polling-enabled>true</polling-enabled>
<add-no-cache-headers>true</add-no-cache-headers>
<!-- <invalidate-session-on-disconnect>true</invalidate-session-on-disconnect> -->
<invalidate-session-on-disconnect>true</invalidate-session-on-disconnect>
</properties>
</channel-definition>
how to solve this problem?