I have an application that i am extending to provide a REST API. Everything works fine in the main site, but I am getting the following in the exception log when I try to hit the REST API:
"Error","ajp-bio-8014-exec-3","12/02/14","12:54:06","table","failed to lazily initialize a collection of role: field, could not initialize proxy - no Session The specific sequence of files included or processed is: service.cfc'' "
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: field, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:137)
at org.hibernate.collection.internal.PersistentBag.size(PersistentBag.java:242)
at coldfusion.runtime.xml.ListIndexAccessor.getSize(ListIndexAccessor.java:44)
at coldfusion.runtime.xml.ArrayHandler.serialize(ArrayHandler.java:69)
at coldfusion.runtime.xml.CFComponentHandler.serialize(CFComponentHandler.java:106)
at coldfusion.runtime.XMLizerUtils.serializeXML(XMLizerUtils.java:83)
at coldfusion.rest.provider.CFObjectProvider.writeTo(CFObjectProvider.java:378)
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:306)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1479)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
at coldfusion.rest.servlet.CFRestServletContainer.service(CFRestServletContainer.java:141)
at coldfusion.rest.servlet.CFRestServletContainer.service(CFRestServletContainer.java:86)
at coldfusion.rest.servlet.CFRestServlet.serviceUsingAlreadyInitializedContainers(CFRestServlet.java:556)
at coldfusion.rest.servlet.CFRestServlet.invoke(CFRestServlet.java:434)
at coldfusion.rest.servlet.RestFilter.invoke(RestFilter.java:58)
at coldfusion.filter.ExceptionFilter.invoke(ExceptionFilter.java:94)
at coldfusion.filter.ClientScopePersistenceFilter.invoke(ClientScopePersistenceFilter.java:28)
at coldfusion.filter.GlobalsFilter.invoke(GlobalsFilter.java:38)
at coldfusion.filter.DatasourceFilter.invoke(DatasourceFilter.java:22)
at coldfusion.rest.servlet.CFRestServlet.invoke(CFRestServlet.java:409)
at coldfusion.rest.servlet.CFRestServlet.service(CFRestServlet.java:400)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at coldfusion.bootstrap.BootstrapServlet.service(BootstrapServlet.java:89)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at coldfusion.monitor.event.MonitoringServletFilter.doFilter(MonitoringServletFilter.java:42)
at coldfusion.bootstrap.BootstrapFilter.doFilter(BootstrapFilter.java:46)
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:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:422)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:198)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Disabling lazy loading will fix this, but results in unacceptable performance (load times from 200ms to 22s). I'm not sure how else to handle this.
I am new to REST in ColdFusion, and it seems to me that the CFC's are being handled in an unusual way. They do not appear to be initialized (init method does not seem to run) and now it seems that ORM is not handled the same either. Am I missing something?
Here is the excerpt of my code producing this error:
component rest="true" restpath="item"
{
import model.beans.*;
remote item function getitem( numeric id restargsource="Path" ) restpath="{id}" httpmethod="GET"
{
var item = entityLoad("item",{ id = id },true);
return item;
}
}
And the bean:
component persistent="true" table="item" output="false" extends="timestampedBean" batchsize="10" cacheuse="read-only"
{
/* properties */
property name="id" column="id" type="numeric" ormtype="int" fieldtype="id" generator="identity";
property name="title" column="title" type="string" ormtype="string";
property name="description" column="description" type="string" ormtype="string";
property name="status" column="status" type="numeric" ormtype="byte" default="0" ;
property name="user" fieldtype="many-to-one" cfc="user" fkcolumn="userid" inversejoincolum="userid" lazy="true" cacheuse="read-only";
property name="field" type="array" fieldtype="many-to-many" cfc="field" fkcolumn="id" linktable="items_fields" inversejoincolumn="fieldid" lazy="extra" batchsize="10" cacheuse="read-only";
}
I also noticed in the stdout log that Hibernate is logging the query, but then it logs the "No session" error:
Hibernate:
select
item0_.id as id0_0_,
item0_.dtcreated as dtcreated0_0_,
item0_.dtmodified as dtmodified0_0_,
item0_.title as title0_0_,
item0_.description as descript6_0_0_,
item0_.status as status0_0_,
item0_.userid as userid0_0_
from
item item0_
where
item0_.id=?
Dec 2, 2014 15:23:00 PM Error [ajp-bio-8014-exec-3] - failed to lazily initialize a collection of role: field, could not initialize proxy - no Session The specific sequence of files included or processed is: service.cfc''
I should probably also add that this "item" table is part of a many-to-many relationship, so "collection of role: field" is referencing the foreign table.
org.hibernate.LazyInitializationException is a popular hibernate problem. The root cause is that you have no hibernate Session opened, because of no transaction available.
There are several approaches to overcome the issue.
Please, read following links:
http://www.javacodegeeks.com/2012/07/four-solutions-to-lazyinitializationexc_05.html
http://javarevisited.blogspot.ru/2014/04/orghibernatelazyinitializationException-Could-not-initialize-proxy-no-session-hibernate-java.html
Or you can use
<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
after 4.1.6 hibernate version. See more at
Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans
set the list to null
example:
iterate the objects and set list every entity to null
entity.setList(null);
Related
I have resource adapter in wildfly-teiid-server with xml
<resource-adapter id="salesforcefour" statistics-enabled="true">
<module slot="main" id="org.jboss.teiid.resource-adapter.salesforce-41"/>
<connection-definitions>
<connection-definition class-name="org.teiid.resource.adapter.salesforce.SalesForceManagedConnectionFactory" jndi-name="java:/sfDS41" enabled="true" connectable="true" use-java-context="true" pool-name="sfDS41">
<config-property name="connectTimeout">30000</config-property>
<config-property name="password"></config-property>
<config-property name="URL">https://test.salesforce.com/services/Soap/u/45.0</config-property>
<config-property name="requestTimeout">120000</config-property>
<config-property name="username"></config-property>
<pool>
<min-pool-size>5</min-pool-size>
<initial-pool-size>5</initial-pool-size>
<prefill>true</prefill>
<use-strict-min>true</use-strict-min>
<flush-strategy>FailingConnectionOnly</flush-strategy>
</pool>
</connection-definition>
</connection-definitions>
</resource-adapter>
For checking that connection pool really get active connections I need get statistics.
I tied to execute jboss-cli.sh and commends
/subsystem=resource-adapters/resource-adapter=salesforcefour:write-attribute(name=statistics-enabled,value=true)
/subsystem=resource-adapters/statistics=statistics/connection-definitions=java\:\/sfDS41:read-resource(include-runtime=true)
But get error
Failed to get the list of the operation properties: "WFLYCTL0030: No resource definition is registered for address [
("subsystem" => "resource-adapters"),
("statistics" => "statistics"),
("connection-definitions" => "java:/sfDS41")
]"
How to check connection pool statistics or just get current active connections count?
Answer from https://github.com/teiid/teiid/pull/1335
For non-jdbc resource adapters it is specified on the pool for the given connection definition:
/subsystem=resource-adapters/resource-adapter=salesforcefour/connection-definitions=sfDS/statistics=pool:write-attribute(name=statistics-enabled, value=true)
You just need to substitute in the name of the connection definition you used - that is the logical name, which is likely not the jndi name. You can auto complete on subsystem=resource-adapters/resource-adapter=salesforcefour/connection-definitions= to see your connection definition names. You should then be able to read the pool statistics against that connection definition name.
I'm using #sap/cloud-sdk-generator 1.6.1 to generate a VDM (YY1_SALESDOCUMENT_CDS), translating it to CSN using edmx2csn to then use it in a .CDS file to exposed as OData service (named CustomSales).
The goal is to enhance the original YY1_SALESDOCUMENT_CDS with an extra field 'foobar', which works as expected. But it has a draw back: CustomSales does not contains the metadata's sap:* attributes, like 'sap:label', that YY1_SALESDOCUMENT_CDS has.
My custom-sales.CDS service file:
using YY1_SALESDOCUMENT_CDS as sales from '../src/external/csn/YY1_SalesDocument.json';
service CustomSales {
#cds.persistence.skip
entity SalesDocument as projection on sales.YY1_SalesDocumentType {
*
} excluding {to_Item}
extend entity sales.YY1_SalesDocumentType with {
foobar: String(25) ;
toItem : Association to many SalesDocumentItem
on toItem.SalesDocument = SalesDocument ;
}
}
YY1_SALESDOCUMENT_CDS Service's metadata:
<EntityType Name="YY1_SalesDocumentType" sap:label="Sales Document" sap:content-version="1">
<Key>
<PropertyRef Name="SalesDocument"/>
</Key>
<Property Name="SalesDocument" Type="Edm.String" Nullable="false" MaxLength="10" sap:display-format="UpperCase" sap:required-in-filter="false" sap:label="Sales Document"/>
<NavigationProperty Name="to_Item"/>
</EntityType>
CustomSales Service's metadata:
<EntityType Name="SalesDocument">
<Key>
<PropertyRef Name="SalesDocument"/>
</Key>
<Property Name="SalesDocument" Type="Edm.String" MaxLength="10" Nullable="false"/>
<Property Name="foobar" Type="Edm.String" MaxLength="25"/>
<NavigationProperty Name="toItem" Type="Collection(CustomSales.SalesDocumentItem)"/>
</EntityType>
I expected all attributes from YY1_SALESDOCUMENT_CDS service to be copied over CustomSales, but that's not the case.
Is there a way to generate OData service from an existing service and also copy it's metadata attributes ?
It's worth mentioning that I'm using JS/TS as handler to custom logic, using the Cloud SDK for JS to call the original backend service.
I am publishing one custom API through rest HTTP endpoint and after publishing API I am subscribing the API. During subscription I am generating the production endpoint URL token and then trying to access the endpoint.I am able to get the api data on dashboard itself.
How can we store the corresponding api payload in database?
You can add a custom sequence and use DB Report mediator within that. Following is a DBreport mediator sample config.
<dbreport description="">
<connection>
<pool>
<password>regadmin</password>
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://localhost:3306/regdb</url>
<user>regadmin</user>
</pool>
</connection>
<statement>
<sql>insert into tracker (`id`, `query`, `tracked`) values (NULL, ?, NOW())</sql>
<parameter expression="get-property('uri.var.id')" type="VARCHAR"/>
</statement>
</dbreport>
You can read about adding custom sequences from here and abount DBLookup mediator from here and DBReport Mediator from here.
I am trying to consume a public service using Mule + apache cxf. The service is available at http://www.html2xml.nl/Services/Calculator/Version1/Calculator.asmx?WSDL
This is a very simple service which does basic arithmetic operations. I am trying to call the operation "Add" here. My mule configuration is as below
<flow name="calculator" doc:name="calculator">
<stdio:inbound-endpoint system="IN" doc:name="STDIO"/>
<custom-transformer class="com.calculator.transformer.CalculatorClient" doc:name="Java"/>
<outbound-endpoint address="http://localhost:28081/service/Calculator?WSDL" exchange-pattern="request-response" doc:name="HTTP">
<cxf:jaxws-client clientClass="com.calculator.wsdl.Calculator" enableMuleSoapHeaders="true" port="CalculatorHttpPost" wsdlLocation="classpath:/wsdl/Calculator.wsdl" operation="Add">
<cxf:inInterceptors>
<spring:bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
</cxf:inInterceptors>
<cxf:outInterceptors>
<spring:bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
</cxf:outInterceptors>
</cxf:jaxws-client>
</outbound-endpoint>
<transformer ref="CalculatorResponse" doc:name="Transformer Reference"/>
<mulexml:jaxb-object-to-xml-transformer name="CalculatortoXML" jaxbContext-ref="myJaxbCal" />
<stdio:outbound-endpoint system="OUT" doc:name="STDIO"/>
</flow>
Before calling the client class i added a transformer as below. This just sets the 2 numbers to add.
Code
package com.calculator.transformer;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
import com.calculator.wsdl.Add;
public class CalculatorClient extends AbstractMessageTransformer {
#Override
public Object transformMessage(MuleMessage message, String outputEncoding)
throws TransformerException {
Add add= new Add();
add.setA(3);
add.setB(3);
return add;
}
}
Once i start mule i receive the error.Not sure what i am doing wrong.
ERROR 2014-01-16 01:09:46,237 [[weatherproject].calculator.stage1.02] org.mule.exception.DefaultMessagingExceptionStrategy:
Message : wrong number of arguments. Failed to route event via endpoint: org.mule.module.cxf.CxfOutboundMessageProcessor. Message payload is of type: Add
Code : MULE_ERROR--2
Exception stack is:
1. wrong number of arguments (java.lang.IllegalArgumentException)
sun.reflect.NativeMethodAccessorImpl:-2 (null)
2. wrong number of arguments. Failed to route event via endpoint: org.mule.module.cxf.CxfOutboundMessageProcessor. Message payload is of type: Add (org.mule.api.transport.DispatchException)
org.mule.module.cxf.CxfOutboundMessageProcessor:148 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transport/DispatchException.html)
Root Exception stack trace:
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
you have mentioned http://localhost:28081/service/Calculator?WSDL as your address and I suppose it should be http://localhost:28081/service/Calculator .
This post helped me to solve the problem
Mule SOAP client wrapper as parameter instead of object array
By using the JAXB bindings as suggested CXF will generate the wrapper objects.
I'm a java beginner. I'm in trouble to configure a persistance unit using JTA transactions.
I need to use a PostgreSQL database that is already defined, configured and populated. Using netbeans, i created the persistance.xml and glassfish-resources.xml as fallows:
<persistence version="2.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_2_0.xsd">
<persistence-unit name="WellWatcherPU" transaction-type="JTA">
<jta-data-source>WellWatcherDB</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.logging.logger" value="org.eclipse.persistence.logging.DefaultSessionLog"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
and
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.postgresql.ds.PGSimpleDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="post-gre-sql_geowellex_geowellexPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="5432"/>
<property name="databaseName" value="DBNAME"/>
<property name="User" value="USER"/>
<property name="Password" value="PASSWORD"/>
<property name="URL" value="jdbc:postgresql://localhost:5432/DBNAME"/>
<property name="driverClass" value="org.postgresql.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="WellWatcherDB" object-type="user" pool-name="post-gre-sql_geowellex_geowellexPool"/>
</resources>
And this is how i get the EntityManagerFactory and EntityManager (as used in the netBeans example)
public class EUserDao {
#Resource
private UserTransaction utx = null;
#PersistenceUnit(unitName = "WellWatcherPU")
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager(); <-------- NullPointerException here
}
public EUser getOne(long userId){
EntityManager em = getEntityManager();
try {
return em.find(EUser.class, userId);
} finally {
em.close();
}
}
EDIT:
And here is my glassfish deploy log:
Informações: [EL Config]: 2012-05-10 12:01:13.534--ServerSession(2017352940)--Connection(1901223982)--Thread(Thread[admin-thread-pool-4848(5),5,grizzly-kernel])--connecting(DatabaseLogin(
platform=>DatabasePlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
Informações: [EL Config]: 2012-05-10 12:01:13.534--ServerSession(2017352940)--Connection(1462281761)--Thread(Thread[admin-thread-pool-4848(5),5,grizzly-kernel])--Connected: jdbc:postgresql://localhost:5432/geowellex?loginTimeout=0&prepareThreshold=0
User: geowellex
Database: PostgreSQL Version: 9.1.3
Driver: PostgreSQL Native Driver Version: PostgreSQL 8.3 JDBC3 with SSL (build 603)
Informações: [EL Config]: 2012-05-10 12:01:13.534--ServerSession(2017352940)--Connection(766700859)--Thread(Thread[admin-thread-pool-4848(5),5,grizzly-kernel])--connecting(DatabaseLogin(
platform=>PostgreSQLPlatform
user name=> ""
connector=>JNDIConnector datasource name=>null
))
What's wrong?
Most likely problem is that your EUserDao is just regular class. Injection works only for container managed classes. Annotations like #PersistenceUnit and #Resource are not processed for normal classes.
Following types of classes are container managed classes (and in those #PersistenceUnit can be used):
Servlet: servlets, servlet filters, event listeners
JSP: tag handlers, tag library event listeners
JSF: scoped managed beans
JAX-WS: service endpoints, handlers
EJB: beans, interceptors
Managed Beans: managed beans
CDI: CDI-style managed beans, decorators
Java EE Platform: main class (static), login callback handler
I see that in your code declare:
private EntityManagerFactory emf = null;
but never create one... like this
emf = Persistence.createEntityManagerFactory("WellWatcherPU");
Thats why you get a Null Pointer Exception when use the object!
public EntityManager getEntityManager() {
return emf.createEntityManager(); <-------- NullPointerException here
}