I am migrating from jboss 6 to jboss 8.2. Earlier it was working without any exception but now when I try to download a file , I get below exception
Caused by: org.xnio.channels.FixedLengthUnderflowException: 8088 bytes remaining
at io.undertow.conduits.AbstractFixedLengthStreamSinkConduit.terminateWrites(AbstractFixedLengthStreamSinkConduit.java:255) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at org.xnio.conduits.Conduits.writeFinalBasic(Conduits.java:134)
at io.undertow.conduits.AbstractFixedLengthStreamSinkConduit.writeFinal(AbstractFixedLengthStreamSinkConduit.java:175) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at org.xnio.conduits.ConduitStreamSinkChannel.writeFinal(ConduitStreamSinkChannel.java:104)
at io.undertow.channels.DetachableStreamSinkChannel.writeFinal(DetachableStreamSinkChannel.java:194) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.server.HttpServerExchange$WriteDispatchChannel.writeFinal(HttpServerExchange.java:1829) [undertow-core-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.spec.ServletOutputStreamImpl.writeBufferBlocking(ServletOutputStreamImpl.java:565) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.spec.ServletOutputStreamImpl.close(ServletOutputStreamImpl.java:600) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.spec.ServletOutputStreamImpl.updateWritten(ServletOutputStreamImpl.java:364) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at io.undertow.servlet.spec.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:223) [undertow-servlet-1.1.0.Final.jar:1.1.0.Final]
at java.io.BufferedOutputStream.flushBuffer(Unknown Source) [rt.jar:1.7.0_71]
at java.io.BufferedOutputStream.write(Unknown Source) [rt.jar:1.7.0_71]
Code snippet
ContentType = "application/octet-stream";
BufInput = new BufferedInputStream(new FileInputStream(File), 5000);
Response.reset();
Response.setIntHeader("Expires", 0);
Response.setContentType(contentType);
Response.setHeader("Content-Disposition", header);
Response.setIntHeader("Content-length", (int) File.length());
Response.setContentLength((int)File.length());
OutStream = new BufferedOutputStream(Response.getOutputStream(), 5000);
int Byte;
while ((Byte = BufInput.read()) != -1)
OutStream.write(Byte);
OutStream.flush();
OutStream.close();
BufInput.close();
This was fixed in 8.2.1 and 9.0.x
So solution for you is to upgrade.
Related
I get an NPE using NULL in a fairly simple JPQL query, see stack trace below:
15:25:46,724 ERROR [net.bbstats.framework.cdi.BaseCdiBean] (default task-1) CompetitionProvider.loadEntities() threw RetrieveException: net.bbstats.framework.exception.RetrieveException: java.lang.IllegalArgumentException: Exception [EclipseLink-6168] (Eclipse Persistence Services - 2.7.5.v20191016-ea124dd158): org.eclipse.persistence.exceptions.QueryException
Exception Description: Query failed to prepare, unexpected error occurred: [java.lang.NullPointerException].
Internal Exception: java.lang.NullPointerException
Query: ReportQuery(name="Competition.findDtosBySeason" referenceClass=Group jpql="
SELECT NEW net.bbstats.dto.CompetitionListDto(
gr,
gl.name,
se.startYear,
NULL, <--
SIZE(rd.groups),
sc.level,
scl.code,
scl.name,
tt.code,
tt.ageGroup,
tt.gender,
cm.type,
cm.name,
gc,
CASE WHEN COUNT(pa.roster.id) > 0 THEN TRUE ELSE FALSE END
)
FROM Group gr
LEFT JOIN gr.groupLabel gl
LEFT JOIN gr.participations pa
JOIN gr.round rd
JOIN rd.season se
JOIN rd.subCompetition sc
JOIN sc.subCompetitionLabels scl
JOIN sc.teamType tt
JOIN sc.competition cm
JOIN cm.geoContext gc
WHERE se.startYear = :seasonStartYear
")
at net.bbstats.view.domain.CompetitionProvider.loadEntities(CompetitionProvider.java:32)
at net.bbstats.framework.management.BaseProvider.getEntities(BaseProvider.java:77)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:241)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:180)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:208)
at com.sun.el.parser.AstValue.getValue(AstValue.java:139)
at com.sun.el.parser.AstValue.getValue(AstValue.java:203)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
at org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:115)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:200)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:187)
at javax.faces.component.UIData.getValue(UIData.java:766)
at org.primefaces.component.api.UIData.getDataModel(UIData.java:824)
at javax.faces.component.UIData.getRowCount(UIData.java:371)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:1187)
at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:1166)
at org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:452)
at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:383)
at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:96)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:949)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1912)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:918)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1905)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1908)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1908)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:491)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:194)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:151)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:151)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:151)
at org.omnifaces.viewhandler.OmniViewHandler.renderView(OmniViewHandler.java:121)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:126)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:223)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:671)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:55)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:360)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1378)
at java.lang.Thread.run(Thread.java:748)
Replacing the NULL with the actual identifier/value gets rids of the NPE.
EDIT:
2nd example:
Caused by: Exception [EclipseLink-6168] (Eclipse Persistence Services - 2.7.5.v20191016-ea124dd158): org.eclipse.persistence.exceptions.QueryException
Exception Description: Query failed to prepare, unexpected error occurred: [java.lang.NullPointerException].
Internal Exception: java.lang.NullPointerException
Query: ReportQuery(name="Competition.findDtosBySeason" referenceClass=Group jpql="
SELECT NEW net.bbstats.dto.TestDto(
NULL
)
FROM Group gr
")
at org.eclipse.persistence.exceptions.QueryException.prepareFailed(QueryException.java:1598)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:692)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:968)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:622)
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:346)
... 96 more
Caused by: java.lang.NullPointerException
at org.eclipse.persistence.queries.ConstructorReportItem.initialize(ConstructorReportItem.java:187)
at org.eclipse.persistence.queries.ReportQuery.prepare(ReportQuery.java:1105)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:673)
... 99 more
DTO:
import java.io.Serializable;
public class TestDto implements Serializable
{
private static final long serialVersionUID = 1L;
public TestDto( String test )
{
}
}
EDIT #2:
Caused by: Exception [EclipseLink-6168] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.QueryException
Exception Description: Query failed to prepare, unexpected error occurred: [java.lang.NullPointerException].
Internal Exception: java.lang.NullPointerException
Query: ReportQuery(name="Competition.findDtosBySeason" referenceClass=Group jpql="
SELECT NEW net.bbstats.dto.TestDto(
NULL
)
FROM Group gr
")
at org.eclipse.persistence.exceptions.QueryException.prepareFailed(QueryException.java:1590)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:680)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:901)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:613)
at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:341)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:1124)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:1144)
at org.jboss.as.jpa.container.AbstractEntityManager.createNamedQuery(AbstractEntityManager.java:99)
at net.bbstats.framework.service.Repository.findByNamedQuery(Repository.java:173)
at net.bbstats.framework.service.Repository.findByNamedQuery(Repository.java:166)
at net.bbstats.framework.service.Repository.findByNamedQuery(Repository.java:159)
at net.bbstats.framework.service.Repository.findByNamedQuery(Repository.java:140)
at net.bbstats.view.domain.CompetitionProvider.loadEntities(CompetitionProvider.java:28)
... 88 more
Caused by: java.lang.NullPointerException
at org.eclipse.persistence.queries.ConstructorReportItem.initialize(ConstructorReportItem.java:167)
at org.eclipse.persistence.queries.ReportQuery.prepare(ReportQuery.java:1059)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:661)
... 99 more
QUESTION:
Is this a bug?
Using EclipseLink 2.7.5
EDIT #2: EclipseLink version 2.5.2 fails as well.
It is not a bug. According BNF (for example JPA 2.1 Specification page 210 - 215) sole usage of NULL (as an addition to IS [NOT] NULL) is in new_value, which is then used only in update statements.
new_value ::= scalar_expression | simple_entity_expression |NULL
Without this limitation it would be unclear which constructor to call in case of multiple constructors with same number of parameters.
Easiest workaround is to introduce new constructor without this value.
Mikko Maunu is right in his answer, the grammar does not allow using NULL literals except in IS NULL, IS NOT NULL or as an assigned value in a UPDATE statement, so it is better not to depend on your particular JPA provider allowing that in some circumstances.
But disallowing NULL does not mean that you cannot generate a null value of the correct type and avoid implementing multiple constructors as he suggests (when you have multiple constructors with huge argument lists it can be hard to tell which constructor is called for a particular query)
You can use:
NULLIF(<literal>, <literal>)
where <literal> is an arbitrary (non-null) literal of the desired type. <literal> will fix the type of the NULLIF expression to the type you desire, so that your JPA provider can find the matching constructor via reflection.
So, in your test query the following should work:
SELECT NEW net.bbstats.dto.TestDto(
NULLIF('dummy_string', 'dummy_string')
)
FROM Group gr
In your actual query, modify the literal value according to the typed null you want to generate. For example, if you want a number you could use NULLIF(0, 0).
Similarly, you should be able to use a more general CASE expression, but NULLIF is in my opinion shorter and less confusing. Use a comment to document this workaround, anyway.
Recently we migrated from weblogic 10 to weblogic12c. The application was working fine until we migrated to the new weblogic12c server. My web application is using JPA and eclipselink to fetch some information from the database. All other named query seems to be working fine, expect the Native Named query. I'm getting a classcastException. Below is the code. Any help is greatly appreciated.
This is my Named Native Query
#NamedNativeQueries({
#NamedNativeQuery(name="Channel.findValue",
query="SELECT ID, APP_ID , APPLICATION_TYPE_ID, CHANNEL_ID, VALUE, EFFECTIVE_DATE FROM TABLENAME "+
" WHERE APP_ID = ? AND STATUS= ? AND APPLICATION_TYPE_ID = ? AND CHANNEL_ID = ? AND EXPIRY_DATE >= ? AND EFFECTIVE_DATE <= ? "
,resultSetMapping="findFeeByAppTypeAndChannel")
})
#SqlResultSetMappings({
#SqlResultSetMapping(name="findValue",
entities={#EntityResult(entityClass=Channel.class)}
)
})
Code that's calling that's calling query:
List<Channel> channels = em.createNamedQuery("channel.findVale").setParameter(1, app.getId())
.setParameter(2, ConstStatus.ACTIVE)
.setParameter(3, appType.getId())
.setParameter(4, channelId)
.setParameter(5, effectiveDate)
.setParameter(6, effectiveDate).setHint("eclipselink.refresh", "true").getResultList();
Error that I am getting:
java.lang.ClassCastException: org.eclipse.persistence.queries.ResultSetMappingQuery cannot be cast to org.eclipse.persistence.queries.ObjectLevelReadQuery
Full Stack trace:
SEVERE: Value Service Response:EJB Exception: : java.lang.ClassCastException: org.eclipse.persistence.queries.ResultSetMappingQuery cannot be cast to org.eclipse.persistence.queries.ObjectLevelReadQuery
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRowInternal(ForeignReferenceMapping.java:2073)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:1987)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.readFromRowIntoObject(ForeignReferenceMapping.java:1353)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:445)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.refreshObjectIfRequired(ObjectBuilder.java:3591)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:826)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:715)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:668)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:601)
at org.eclipse.persistence.queries.EntityResult.getValueFromRecord(EntityResult.java:192)
at org.eclipse.persistence.queries.ResultSetMappingQuery.buildObjectsFromRecords(ResultSetMappingQuery.java:144)
at org.eclipse.persistence.queries.ResultSetMappingQuery.executeDatabaseQuery(ResultSetMappingQuery.java:195)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1463)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:485)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:742)
at weblogic.persistence.QueryProxyImpl.getResultList(QueryProxyImpl.java:140)
at com.database.service.app.app.service.appServiceBean.getFeeByAppTypeAndChannel(appServiceBean.java:413)
at com.database.service.app.app.service.appServiceBean_7omfhq_appServiceLocalImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:33)
at com.database.service.app.app.service.appServiceBean_7omfhq_appServiceLocalImpl.getFeeByAppTypeAndChannel(Unknown Source)
at com.database.service.app.ws.service.FeeService.getFeeInfo(FeeService.java:89)
at com.database.service.app.ws.service.FeeService.getFee(FeeService.java:191)
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 weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker.invoke(WLSInstanceResolver.java:117)
at weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker.invoke(WLSInstanceResolver.java:91)
at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149)
at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:88)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:419)
at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:868)
at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:422)
at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:169)
at weblogic.wsee.jaxws.WLSServletAdapter.handle(WLSServletAdapter.java:199)
at weblogic.wsee.jaxws.HttpServletAdapter$AuthorizedInvoke.run(HttpServletAdapter.java:640)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.wsee.util.ServerSecurityHelper.authenticatedInvoke(ServerSecurityHelper.java:108)
at weblogic.wsee.jaxws.HttpServletAdapter$3.run(HttpServletAdapter.java:284)
at weblogic.wsee.jaxws.HttpServletAdapter.post(HttpServletAdapter.java:293)
at weblogic.wsee.jaxws.JAXWSServlet.doRequest(JAXWSServlet.java:128)
at weblogic.servlet.http.AbstractAsyncServlet.service(AbstractAsyncServlet.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:346)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:243)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3432)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3402)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2285)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2201)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1572)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)>
<31-Mar-2016 11:26:58 o'clock AM ADT> <Error> <com.database.service.app.ws.service.FeeService> <BEA-000000> <Value Service Response:EJB Exception: : java.lang.ClassCastException: org.eclipse.persistence.queries.ResultSetMappingQuery cannot be cast to org.eclipse.persistence.queries.ObjectLevelReadQuery
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRowInternal(ForeignReferenceMapping.java:2073)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.valueFromRow(ForeignReferenceMapping.java:1987)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.readFromRowIntoObject(ForeignReferenceMapping.java:1353)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildAttributesIntoObject(ObjectBuilder.java:445)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.refreshObjectIfRequired(ObjectBuilder.java:3591)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:826)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:715)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:668)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:601)
at org.eclipse.persistence.queries.EntityResult.getValueFromRecord(EntityResult.java:192)
at org.eclipse.persistence.queries.ResultSetMappingQuery.buildObjectsFromRecords(ResultSetMappingQuery.java:144)
at org.eclipse.persistence.queries.ResultSetMappingQuery.executeDatabaseQuery(ResultSetMappingQuery.java:195)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:844)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:743)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2871)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1516)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1498)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1463)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:485)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:742)
at weblogic.persistence.QueryProxyImpl.getResultList(QueryProxyImpl.java:140)
at com.database.service.app.app.service.appServiceBean.getFeeByAppTypeAndChannel(appServiceBean.java:413)
at com.database.service.app.app.service.appServiceBean_7omfhq_appServiceLocalImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionLocalMethodInvoker.invoke(SessionLocalMethodInvoker.java:33)
at com.database.service.app.app.service.appServiceBean_7omfhq_appServiceLocalImpl.getFeeByAppTypeAndChannel(Unknown Source)
at com.database.service.app.ws.service.FeeService.getFeeInfo(FeeService.java:89)
at com.database.service.app.ws.service.FeeService.getFee(FeeService.java:191)
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 weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker.invoke(WLSInstanceResolver.java:117)
at weblogic.wsee.jaxws.WLSInstanceResolver$WLSInvoker.invoke(WLSInstanceResolver.java:91)
at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149)
at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:88)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877)
at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:419)
at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:868)
at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:422)
at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:169)
at weblogic.wsee.jaxws.WLSServletAdapter.handle(WLSServletAdapter.java:199)
at weblogic.wsee.jaxws.HttpServletAdapter$AuthorizedInvoke.run(HttpServletAdapter.java:640)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.wsee.util.ServerSecurityHelper.authenticatedInvoke(ServerSecurityHelper.java:108)
at weblogic.wsee.jaxws.HttpServletAdapter$3.run(HttpServletAdapter.java:284)
at weblogic.wsee.jaxws.HttpServletAdapter.post(HttpServletAdapter.java:293)
at weblogic.wsee.jaxws.JAXWSServlet.doRequest(JAXWSServlet.java:128)
at weblogic.servlet.http.AbstractAsyncServlet.service(AbstractAsyncServlet.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:346)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:243)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3432)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3402)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2285)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2201)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1572)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:311)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:263)
Error got resolved when I removed the
setHint("eclipselink.refresh", "true")
from
List<Channel> channels = em.createNamedQuery("channel.findVale")
.setParameter(1, app.getId())
.setParameter(2, ConstStatus.ACTIVE)
.setParameter(3, appType.getId())
.setParameter(4, channelId) .setParameter(5, effectiveDate)
.setParameter(6, effectiveDate)
.setHint("eclipselink.refresh", "true").getResultList();
Mail service configuration in standalone-full-ha.xml.
<subsystem xmlns="urn:jboss:domain:mail:2.0">
<mail-session name="default" jndi-name="java:jboss/mail/Default" from="sender#gmail.com">
<smtp-server outbound-socket-binding-ref="mail-smtp" ssl="true" username="User" password="password"/>
</mail-session>
</subsystem>
The mail Session in turn references an SMTP host bound at localhost at port 465.
<outbound-socket-binding name="mail-smtp">
<remote-destination host="smtp.gmail.com" port="465"/>
</outbound-socket-binding>
The actual password used in the configuration is an application specific password generated during "2-Step Verification" at https://security.google.com/settings/security/apppasswords
After this configuration has been made, an attempted to send an email using the following code causes an exception to be thrown.
#Resource(mappedName = "java:jboss/mail/Default")
private Session mailSession;
public void init() throws AddressException, MessagingException {
MimeMessage m = new MimeMessage(mailSession);
Address from = new InternetAddress("sender#gmail.com");
Address[] to = new InternetAddress[]{new InternetAddress("receiver#gmail.com")};
m.setFrom(from);
m.setRecipients(Message.RecipientType.TO, to);
m.setSubject("Message Subject");
m.setSentDate(new Date());
m.setContent("Mail sent from app", "text/html");
Transport.send(m);
}
The following exception is thrown.
07:48:36,906 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (default task-9) #{countryManagedBean.init}: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/answer/14257 t70sm5413631pfi.8 - gsmtp
: javax.faces.FacesException: #{countryManagedBean.init}: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/answer/14257 t70sm5413631pfi.8 - gsmtp
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UIViewAction.broadcast(UIViewAction.java:562)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:86)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:130)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:78)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132)
at io.undertow.websockets.jsr.JsrWebSocketFilter.doFilter(JsrWebSocketFilter.java:151)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132)
at org.omnifaces.facesviews.FacesViewsForwardingFilter.filterExtensionLess(FacesViewsForwardingFilter.java:128)
at org.omnifaces.facesviews.FacesViewsForwardingFilter.doFilter(FacesViewsForwardingFilter.java:89)
at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:108)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132)
at filter.NoCacheFilter.doFilter(NoCacheFilter.java:33)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132)
at org.omnifaces.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:122)
at org.omnifaces.filter.HttpFilter.doFilter(HttpFilter.java:108)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:60)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:132)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.DisableCacheHandler.handleRequest(DisableCacheHandler.java:33)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AuthenticationConstraintHandler.handleRequest(AuthenticationConstraintHandler.java:51)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.servlet.handlers.security.ServletSecurityConstraintHandler.handleRequest(ServletSecurityConstraintHandler.java:56)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:58)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:72)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.SecurityInitialHandler.handleRequest(SecurityInitialHandler.java:76)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:282)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:261)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:80)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:172)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:199)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:774)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/answer/14257 t70sm5413631pfi.8 - gsmtp
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 57 more
Caused by: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/answer/14257 t70sm5413631pfi.8 - gsmtp
at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:892)
at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:814)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:728)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at admin.bean.CountryManagedBean.init(CountryManagedBean.java:81)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.sun.el.parser.AstValue.invoke(AstValue.java:292)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 58 more
Using WildFly 9.0.2 final (the application using a self-signed SSL certificate should not be an issue here).
There is a configuration mistake made in an incorrect assumption. The XML attribute username expects the actual email address where the screen name of the corresponding sender's account was given hence, the exception. It works fine after it has been corrected as follows.
<mail-session name="default" jndi-name="java:jboss/mail/Default" from="sender#gmail.com">
<smtp-server outbound-socket-binding-ref="mail-smtp" ssl="true" username="sender#gmail.com" password="password"/>
</mail-session>
The actual password to be used in the configuration is an application specific password generated during "2-Step Verification" at https://security.google.com/settings/security/apppasswords as already stated in the question.
The mail session javax.mail.Session can then be injected into any Java EE artifact like Servlets, Servlet filters, managed beans, EJBs, Message Driven Beans (MDB) etc using the javax.annotation.Resource annotation.
One thing which does not happen for some unknown reasons is the sender's name (label) as specified with the from XML attribute. It always sends the sender's email address as the sender name which is unexpected. Even doing,
Address from = new InternetAddress("admin#server.domain");
mimeMessage.setFrom(from);
does not help. I followed some patterns as suggested in this answer but it did not help either. It however, works in Java SE environment. It is nevertheless a different thing than the current question. Perhaps, I will ask a separate question later on.
Additional :
I prefer JMS queues to send mails asynchronously as a background process, since sending a mail may be delayed significantly for many reasons. The actual message along with the recipient's email address is sent through a JMS queue and the actual mail is delivered to a target mail server from within the receiving terminal of the corresponding queue like the following.
#MessageDriven(activationConfig = {
#ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
#ActivationConfigProperty(propertyName = "useJNDI", propertyValue = "true"),
#ActivationConfigProperty(propertyName = "destination", propertyValue = "java:jboss/exported/jms/emailQueue"),
#ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge")})
#RunAs("ROLE_ADMIN")
public class MailBean implements MessageListener {
#Resource(lookup = "java:jboss/mail/Default")
private Session mailSession; // javax.jms.Session
#Override
#PermitAll
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void onMessage(Message message) {
try {
if (message instanceof ObjectMessage) {
ObjectMessage objectMessage = (ObjectMessage) message;
EmailUtil emailUtil = (EmailUtil) objectMessage.getObject();
String receiver = emailUtil.getReceiver();
String textMessage = emailUtil.getMessage();
if (StringUtils.isNotBlank(receiver) && StringUtils.isNotBlank(textMessage)) {
MimeMessage mimeMessage = new MimeMessage(mailSession);
Address[] to = new InternetAddress[]{new InternetAddress(receiver)};
mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, to);
mimeMessage.setSubject(emailUtil.getSubject(), "UTF-8");
mimeMessage.setSentDate(new Date());
mimeMessage.setText(textMessage, "UTF-8", "html");
Transport.send(mimeMessage);
} else {
System.out.println("No message found.");
}
} else {
System.out.println("Message is of wrong type : " + message.getClass().getName());
}
} catch (JMSException | MessagingException e) {
Logger.getLogger(MailBean.class.getName()).log(Level.SEVERE, null, e);
}
}
}
EmailUtil is a utility Java class holding necessary properties and implementing the java.io.Serializable interface (which is mandatory for sending serializable Java objects).
public final class EmailUtil implements Serializable {
private String message;
private String subject;
private String receiver;
private static final long serialVersionUID = 1L;
// Constructor(s) + getters + setters + hashCode() + equals() + toString().
}
In order to inject a Queue, I use an application scoped CDI managed bean for better reusability on the front side.
#ApplicationScoped
public class EmailQueueBean {
#Resource(lookup = "java:jboss/exported/jms/emailQueue")
private Queue queue;
#Resource(lookup = "java:jboss/exported/jms/emailFactory")
private ConnectionFactory connectionFactory;
public EmailQueueBean() {}
public void send(EmailUtil emailUtil) throws JMSException {
try (Connection connection = connectionFactory.createConnection("admin#gmail.com", "admin_password");
javax.jms.Session session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue)) {
ObjectMessage objectMessage = session.createObjectMessage(emailUtil);
producer.send(objectMessage);
}
}
}
Inject this bean anywhere in any Java EE artifact, construct an instance of EmailUtil manually using new and invoke the send() method on behalf of the injected proxy instance of the managed bean passing through the instance of EmailUtil constructed.
The authentication using username / password as specified with the createConnection() method is not needed (nor #RunAs("ROLE_ADMIN") before the MDB), in case the security is disabled / not used in the hornetq server in the configuration.
See also :
JAAS authentication in JMS using WildFly : javax.jms.JMSSecurityException: HQ119032: User: null doesnt have permission=SEND on address {2}
I am using rest easy for getting and posting the data from a third party URL, When I am calling the get service using the below code I am getting the ClassNotFoundException "javax.net.ssl.SSLSocketFactory"
final ClientRequest request = createRequest(url,acceptType,consumesType,body);
final byte[] encodedCredentials = (userName + ":" + password)
.getBytes();
final String encodedAuto = Base64.encodeBytes(encodedCredentials);
request.header("Authorization", "Basic " + encodedAuto);
try {
request.addAuthenticationHeaders(request, userName,
password);
response = request.get(String.class);
if (response != null) {
logger.info("Status of the REST Call:"
+ response.getStatus());
}
} catch (final Exception e) {
e.printStackTrace();
logger.error("Failed the get the data from PM", e);
}
And the createRequest method is as below
public ClientRequest createRequest(final String urlString,
final String acceptType, final String consumesType,
final String body) {
final ClientRequest request = new ClientRequest(urlString);
request.accept(acceptType);
if (body != null) {
request.body(consumesType, body);
}
request.header("Content-Type", consumesType);
// request.header("Accept", acceptType);
return request;
}
When it is executing response = request.get(request); it is throwing SSLSocketFactory ClassNotFoundException, as per my analysis this class is available on rt.jar which is not required to add to the WildFly server or deployments lib folder.
Caused by: java.lang.NoClassDefFoundError: javax/net/ssl/SSLSocketFactory
at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:82) [commons-httpclient-3.1.jar:]
at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:127) [commons-httpclient-3.1.jar:]
at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707) [commons-httpclient-3.1.jar:]
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387) [commons-httpclient-3.1.jar:]
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) [commons-httpclient-3.1.jar:]
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) [commons-httpclient-3.1.jar:]
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323) [commons-httpclient-3.1.jar:]
at org.jboss.resteasy.client.core.executors.ApacheHttpClientExecutor.execute(ApacheHttpClientExecutor.java:81) [resteasy-jaxrs-2.2.1.GA.jar:]
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:39) [resteasy-jaxrs-2.2.1.GA.jar:]
at org.jboss.resteasy.security.doseta.DigitalSigningInterceptor.execute(DigitalSigningInterceptor.java:107) [resteasy-crypto-3.0.10.Final.jar:]
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:45) [resteasy-jaxrs-2.2.1.GA.jar:]
at org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPInterceptor.execute(AcceptEncodingGZIPInterceptor.java:40) [resteasy-jaxrs-2.2.1.GA.jar:]
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:45) [resteasy-jaxrs-2.2.1.GA.jar:]
at org.jboss.resteasy.client.ClientRequest.execute(ClientRequest.java:473) [resteasy-jaxrs-2.2.1.GA.jar:]
at org.jboss.resteasy.client.ClientRequest.httpMethod(ClientRequest.java:704) [resteasy-jaxrs-2.2.1.GA.jar:]
at org.jboss.resteasy.client.ClientRequest.get(ClientRequest.java:509) [resteasy-jaxrs-2.2.1.GA.jar:]
at org.jboss.resteasy.client.ClientRequest.get(ClientRequest.java:537) [resteasy-jaxrs-2.2.1.GA.jar:]
at com.example.main.framework.service.RestClientService.get(RestClientService.java:46) [main-ejb.jar:]
at com.example.main.entity.validator.EntityValidator.getPMAccountDetails(EntityValidator.java:2866) [main-ejb.jar:]
at com.example.main.entity.validator.EntityValidator.validateCompanySettingPortfolioMgr(EntityValidator.java:2633) [main-ejb.jar:]
at com.example.main.action.codegen.CompanySettingPortfolioMgrHome.persist(CompanySettingPortfolioMgrHome.java:329) [main-ejb.jar:]
... 99 more
Caused by: java.lang.ClassNotFoundException: javax.net.ssl.SSLSocketFactory from [Module "org.apache.commons.httpclient:main" from local module loader #6043cd28 (finder: local module finder #cb51256 (roots: D:\wildfly-8.2.0.Final\modules,D:\wildfly-8.2.0.Final\modules\system\layers\base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:213) [jboss-modules.jar:1.3.3.Final]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:459) [jboss-modules.jar:1.3.3.Final]
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:408) [jboss-modules.jar:1.3.3.Final]
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:389) [jboss-modules.jar:1.3.3.Final]
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:134) [jboss-modules.jar:1.3.3.Final]
... 120 more
If we add rt.jar to the wildfly module then it throws ClassNotFoundException related to classes in jsse.jar which is as part of JDK 1.8 lib. Then I realized that we should not add these jars to neither httpclient module nor deployment lib folder.
Please let me know if any one has solution for this issue.
The issue got resolved after adding the "javax.api" dependency to the module.xml for the module org.apache.commons.httpclient.
<module ...>
<resources>
...
</resources>
<dependencies>
....
<module name="javax.api"/>
</dependencies>
</module>
I want to get a JasperReport from a jasper file path. My jasper file path is C:/project/report/reportTemplate_20110420000035982.jasper
public static JasperReport getJasperReportByTemplateName(String templateFullName) throws JRException{
JasperReport jasperReport;
jasperReport = (JasperReport)JRLoader.loadObjectFromLocation(templateFullName);
return jasperReport;
}
and an exception occurs at this line:
jasperReport = (JasperReport)JRLoader.loadObjectFromLocation(templateFullName);
I tried to find the reason, but it looks like everything is ok. I guess may be the path is not
valid in Windows (C:/project/report/reportTemplate_20110420000035982.jasper)
Anyone who can help me, thanks a lot. I've pasted the exception info below. Thanks.
net.sf.jasperreports.engine.JRException: Could not load object from location : C:/project/report/reportTemplate_20110420000035982.jasper
at net.sf.jasperreports.engine.util.JRLoader.loadObjectFromLocation(JRLoader.java:262)
at net.sf.jasperreports.engine.util.JRLoader.loadObjectFromLocation(JRLoader.java:221)
at com.hp.proctool.reportmgt.customizer.IReportFactory.getJasperReportByTemplateName(IReportFactory.java:68)
at com.hp.proctool.reportmgt.service.ReportManager.getParametersByTemplateName(ReportManager.java:410)
at com.hp.proctool.reportmgt.service.ReportManager.getFieldJs(ReportManager.java:360)
at com.hp.proctool.reportmgt.service.ReportManager.generateReportDownloadForm(ReportManager.java:345)
at com.hp.proctool.reportmgt.service.ReportManager$$FastClassByCGLIB$$c444a9f1.invoke()
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:700)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:635)
at com.hp.proctool.reportmgt.service.ReportManager$$EnhancerByCGLIB$$1ab1a55e.generateReportDownloadForm()
at com.hp.proctool.reportmgt.web.ReportController.generateDownloadForm(ReportController.java:148)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:421)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:136)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:326)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:313)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:807)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:511)
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 com.hp.common.orm.RightFilter.doFilter(RightFilter.java:73)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
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:859)
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(Unknown Source)
Looking at the source code of JRLoader at http://jasperreports.sourcearchive.com/documentation/3.6.0plus-pdfsg/JRLoader_8java-source.html, it looks like this line is returning null for your file.
File file = JRResourcesUtil.resolveFile(location, fileResolver);
which seems to suggest the file is either missing or not a file (i.e. a directory).
If you call:
new File("C:/project/report/reportTemplate_20110420000035982.jasper").exists()
do you get true or false?
Could you try calling JRLoader#loadObject() passing in a FileInputStream that you create yourself?
I use the technique like this to make sure of the path
String subReportDir = ((HashMap<String, String>) dispatcher.getServletContext().getAttribute("local")).get("SUBREPORT_DIR");
String reportPath = dispatcher.getServletContext().getRealPath(subReportDir) + "\\";
String reportNamePath = dispatcher.getServletContext().getRealPath(subReportDir + reportName);
HashMap map = new HashMap();
map.put("SUBREPORT_DIR", reportPath);//this is a parameter in the report in the subreport only put the report name.jasper
String dbConnection = (String) dispatcher.getServletContext().getInitParameter("dbConnectionString");
String dbUserName = (String) dispatcher.getServletContext().getInitParameter("dbUserName");
String dbPassword = (String) dispatcher.getServletContext().getInitParameter("dbPassword");
ReportGenerator reportGenerator;
reportGenerator = new ReportGenerator(reportNamePath, map, dbConnection, dbUserName, dbPassword);//
byte[] reportSteam = null;
SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy");
String fileName = "Issue Statistics" + dt.format(new Date());
reportSteam = reportGenerator.generateRTFReport();
dispatcher.getRequest().setAttribute("mimeType", "application/msword");
dispatcher.getRequest().setAttribute("fileName", fileName + ".doc");
dispatcher.getRequest().setAttribute("fileBytes", reportSteam);
public ReportGenerator(String reportPath, HashMap map, String dbConnection, String dbUserName, String dbPassword) {
this.reportPath = reportPath;
this.map = map;
this.dbConnection = dbConnection;
this.dbUserName = dbUserName;
this.dbPassword = dbPassword;
}
public byte[] generateRTFReport()
{
try
{
jasperReport = (JasperReport) JRLoader.loadObject(reportPath);
jasperPrint = JasperFillManager.fillReport(jasperReport, map, connectDB(dbConnection, dbUserName, dbPassword));
rtfExporter = new JRRtfExporter();
reportSteam = new ByteArrayOutputStream();
rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, reportSteam);
rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
rtfExporter.exportReport();
System.out.println("jasper loaded");
return reportSteam.toByteArray();
}
catch(Exception ex)
{
ex.printStackTrace();
return null;
}
finally
{
try
{
reportSteam.close();
}
catch(IOException io)
{
io.printStackTrace();
}
}
}