I am facing strange issue "Premature end of file." exception for last few days on one of our azure application. Its a spring boot application. I am using spring boot version 2.6.3 (embedded tomcat). This code has been working for past 8 months but its not working anymore. Only changes I did for Java 8 to Java 11 version update on the azure app service.
We are using "Java 11 on JAVA SE linux stack" in app service.
We are getting an exception on below line (setting new schema),
Schema schema = sf.newSchema(file);
Here is the Java code which was working before.
public static <T> String marshal(Class<T> beanClass, Object object, String xsdSchemaPath)
throws JAXBException, SAXException{
JAXBContext jaxbContext = JAXBContext.newInstance(beanClass);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
File file = new File(xsdSchemaPath);
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaPath);
try {
FileUtils.copyInputStreamToFile(in, file);
} catch (IOException e) {
logger.error("Error occured in Marshalling the object", e.getMessage());
throw new SriException(xsdSchemaPath + " not found ");
}
Schema schema = sf.newSchema(file);
jaxbMarshaller.setSchema(schema);
I have already verified xsd and its valid.
Please let me know if there are any leads.
the only thing I can think about it's a max size issue or timeout. Take a look in the following and try changing the parameters:
In conf\server.xml
<Connector port="80" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxPostSize="67589953" />
In webapps\manager\WEB-INF\web.xml
<multipart-config>
<!-- 52MB max -->
<max-file-size>52428800</max-file-size>
<max-request-size>52428800</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
HttpRequest maximum allowable size in tomcat?
Related
I am very new to Spring Integration and my project is using File Support to read a file and load into data base.
I have XML config , trying to understand it's content.
<int-file:inbound-channel-adapter auto-startup= true channel="channelOne" directory="${xx}" filename-regex="${xx}" id="id" prevent-duplicates="false">
<int:poller fixed-delay="1000" receive-timeout="5000"/>
</int-file:inbound-channel-adapter>
<int:channel id="channelOne"/>
From the above piece, my understanding is :
We define a channel and
Then define inbound-channel-adapter - this will look into directory for the file and create a message with file as a payload.
I was able to convert this in JavaConfig as below :
#Bean
public MessageChannel fileInputChannel() {
return new DirectChannel();
}
#Bean
#InboundChannelAdapter(value = "fileInputChannel", poller = #Poller(fixedDelay = "1000"))
public MessageSource<File> fileReadingMessageSource() {
FileReadingMessageSource sourceReader= new FileReadingMessageSource();
RegexPatternFileListFilter regexPatternFileListFilter = new RegexPatternFileListFilter(
file-regex);
//List<FileListFilter<File>> fileListFilter = new ArrayList<FileListFilter<File>>();
fileListFilter.add(regexPatternFileListFilter);
//CompositeFileListFilter compositeFileListFilter = new CompositeFileListFilter<File>(
fileListFilter);
sourceReader.setDirectory(new File(inputDirectorywhereFileComes));
sourceReader.setFilter(regexPatternFileListFilter );
return sourceReader;
}
Then the next piece of code , which literally I am struggling to understand and moreover to convert to JavaConfig.
Here is the next piece:
<int-file:outbound-gateway
delete-source-files="true"
directory="file:${pp}"
id="id"
reply-channel="channelTwo"
request-channel="channelOne"
temporary-file-suffix=".tmp"/>
<int:channel id="channelTwo"/>
<int:outbound-channel-adapter channel="channelTwo" id="id" method="load" ref="beanClass"/>
So from this piece , my understanding :
1: Define an output channel.
2: Define an outbound-gateway, which will write that message as a file again in directory(other one), also remove file from source directory. And finally it will call the method Load of Bean Class. This is our class and has load method which takes file as input and load it to DB.
I tried to covert it into Java Config. Here is my code:
#Bean
#ServiceActivator(inputChannel= "fileInputChannel")
public MessageHandler fileWritingMessageHandler() throws IOException, ParseException {
FileWritingMessageHandler handler = new FileWritingMessageHandler(new File(path to output directory));
handler.setFileExistsMode(FileExistsMode.REPLACE);
beaObject.load(new File(path to output directory or input directory:: Nothing Worked));
handler.setDeleteSourceFiles(true);
handler.setOutputChannel(fileOutputChannel());
return handler;
}
I am able to write this file to output folder also was able to delete from source. After that I am totally lost. I have to call method Load of my BeanClass(ref=class in XML ).
I tried a lot, but not able to get it. Read multiple times the integration File Support doc, but couldn't make it.
Note: When I tried , I got one error saying , the File Not Found Exception. I believe , I am able to call my method , but can not get the file.
This XML config is working perfectly fine.
Spring Integration with DSL also anyone can suggest, if possible.
Please help me to understand the basic flow and get this thing done. Any help and comments is really appreciable.
Thanks in advance.
First of all you need to understand that #Bean method is exactly for configuration and components definitions which are going to be used later at runtime. You definitely must not call a business logic in the #Bean. I mean that your beaObject.load() is totally wrong.
So, please, go first to Spring Framework Docs to understand what is #Bean and its parent #Configuration: https://docs.spring.io/spring/docs/5.1.2.RELEASE/spring-framework-reference/core.html#beans-java
Your #ServiceActivator for the FileWritingMessageHandler is really correct (when you remove that beaObject.load()). What you just need is to declare one more #ServiceActivator for calling your beaObject.load() at runtime when message appears in the fileOutputChannel:
#ServiceActivator(inputChannel= "fileOutputChannel")
public void loadFileIntoDb(File payload) {
this.beaObject.load(payload);
}
See https://docs.spring.io/spring-integration/docs/5.1.1.BUILD-SNAPSHOT/reference/html/configuration.html#annotations for more info.
Is there mongodb mapping converter for generic message.
No argument constructor not available for generic message.
.11:47:30.937 [http-nio-9080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.messaging.MessageHandlingException: error occurred in message handler [messageHandler]; nested exception is org.springframework.data.mapping.model.MappingInstantiationException: Failed to instantiate org.springframework.messaging.support.GenericMessage using constructor NO_CONSTRUCTOR with arguments ] with root cause
java.lang.NoSuchMethodException: org.springframework.messaging.support.GenericMessage.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getDeclaredConstructor(Class.java:2178)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:104)
at org.springframework.data.convert.ReflectionEntityInstantiator.createInstance(ReflectionEntityInstantiator.java:61)
at org.springframework.data.convert.ClassGeneratingEntityInstantiator.createInstance(ClassGeneratingEntityInstantiator.java:83)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:251)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:231)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readValue(MappingMongoConverter.java:1186)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.access$200(MappingMongoConverter.java:78)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1134)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$MongoDbPropertyValueProvider.getPropertyValue(MappingMongoConverter.java:1097)
Also I am trying following config of mongotemplate
Please advise if correct
public MongoTemplate messagingMongoTemplate() throws Exception {
MongoTemplate mongoTemplate=null;
try {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
MappingContext mappingContext = new MongoMappingContext();
MappingMongoConverter mappingMongoConverter = new MappingMongoConverter(dbRefResolver,mappingContext);
CustomConversions customConversions = new CustomConversions(Arrays.asList(new MongoDbMessageBytesConverter()));
mappingMongoConverter.setCustomConversions(customConversions);
mongoTemplate=new MongoTemplate(mongoDbFactory,mappingMongoConverter);
Starting with version 3.0 it is recommended to use ConfigurableMongoDbMessageStore as that provides more options for customization, including a Converter for Message.
Out-of-the-box Spring Integration provides MongoDbMessageBytesConverter, which has become public since 4.2.10 and is used by default if there is no any external customization for the ConfigurableMongoDbMessageStore.
EDIT #1: I used JAXB RI 2.2.6 (latest as of today 12/06/12), and I
observe the same behavior :-(
I am using JAXB for unmarshalling XML payloads.
When I pass an invalid payload for the first time via Unmarshaller, I get the following type of error:
javax.xml.bind.UnmarshalException: Unable to create an instance of foo.bar.FooBarType
- with linked exception:
[java.lang.InstantiationException]
On the next line in my code (in the catch() block), I try the same Unmarshaller instance and give a valid payload, where I get following type of error:
java.lang.ClassCastException: foo.bar.SomeAType cannot be cast to foo.bar.SomeBType
On the next line (again in the subsequent catch()), I try the same Unmarshaller instance and again give the same valid payload, which unmarshals fine!
Has anyone experienced this kind of behavior with JAXB? Am I hitting a bug here? Where to look/dig?
Here are the details of the manifest of JAXB jar that I am using:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.0
Created-By: 1.5.0_12-b04 (Sun Microsystems Inc.)
Specification-Title: Java Architecture for XML Binding
Specification-Version: 2.1
Specification-Vendor: Sun Microsystems, Inc.
Implementation-Title: JAXB Reference Implementation
Implementation-Version: 2.1.12
Implementation-Vendor: Sun Microsystems, Inc.
Implementation-Vendor-Id: com.sun
Extension-Name: com.sun.xml.bind
Build-Id: hudson-jaxb-ri-2.1-833
Class-Path: jaxb-api.jar activation.jar jsr173_1.0_api.jar jaxb1-impl.jar
Name: com.sun.xml.bind.v2.runtime
Implementation-Version: hudson-jaxb-ri-2.1-833
Thank you much in advance!
EDIT #2: It's not possible to paste everything, but here's the gist of what it is looking like:
final JAXBContext jaxbContext = JAXBContext.newInstance(FooRequestType.class);
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<FooRequestType> result = null;
try {
//try unmarshalling invalid payload.
result = unmarshaller.unmarshal(invalidPayload.getDocumentElement(), FooRequestType.class);
}catch(Exception e1){
try {
//now try unmarshalling valid payload . ##NOTE: If you try unmarshalling Invalid Payload here, it will fail again.
result = unmarshaller.unmarshal(validPayload.getDocumentElement(), FooRequestType.class);
} catch(Exception e2){
//try again unmarshalling valid payload
result = unmarshaller.unmarshal(validPayload.getDocumentElement(), FooRequestType.class);
System.out.println("Result:=" + result.getValue());
System.out.println("Successfully unmarshalled. Exiting with (0)");
System.exit(0);
}
}
System.out.println("Not expecting to reach here.Exiting with (1)");
System.exit(1);
EDIT #3: Ran the same piece of code by using EclipseLink MOXy as the JAXB Impl; and it behaves correctly.
I opened a bug on Sun/Oracle JAXB RI: http://java.net/jira/browse/JAXB-931
JAXB unmarshallling fails when runnin on WAS 7 (succeed on a standalone test)
[21/11/12 16:47:55:690 CET] 00000025 DefaultMessag W org.springframework.jms.listener.AbstractMessageListenerContainer invokeErrorHandler Execution of JMS message listener failed, and no ErrorHandler has been set.
java.lang.VerifyError: javax/xml/bind/JAXBElement.<init>(Ljavax/xml/namespace/QName;Ljava/lang/Class;Ljava/lang/Class;Ljava/lang/Object;)V
at com.ca.cib.zba.message.mt101.ObjectFactory.createMatherUnmarshaller(ObjectFactory.java:23)
at com.ibm.xml.xlxp2.jaxb.unmarshal.JAXB_Deserialization_Root_Stub.write(com.ibm.xml.xlxp2.jaxb.unmarshal.JAXB_Deserialization_Root_Stub.java)
at com.ibm.xml.xlxp2.jaxb.unmarshal.impl.DeserializationStub.end(DeserializationStub.java:151)
at com.ibm.xml.xlxp2.jaxb.unmarshal.impl.DeserializationContext.endComplexType(DeserializationContext.java:673)
at com.ibm.xml.xlxp2.jaxb.unmarshal.impl.DeserializationContext.handleEndElementEvent(DeserializationContext.java:384)
at com.ibm.xml.xlxp2.jaxb.unmarshal.impl.JAXBDocumentScanner.produceEndElementEvent(JAXBDocumentScanner.java:234)
at com.ibm.xml.xlxp2.scan.DocumentScanner.scanEndElement(DocumentScanner.java:2590)
at com.ibm.xml.xlxp2.scan.DocumentScanner.nextEvent(DocumentScanner.java:1289)
at com.ibm.xml.xlxp2.scan.DocumentScanner.parseDocumentEntity(DocumentScanner.java:1168)
at com.ibm.xml.xlxp2.jaxb.unmarshal.impl.JAXBDocumentScanner.unmarshal(JAXBDocumentScanner.java:147)
at com.ibm.xml.xlxp2.jaxb.unmarshal.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:158)
at com.ca.cib.zba.message.mt101.ZBAProcessingResultXMLTool.getZBAProcessingResult(ZBAProcessingResultXMLTool.java:52)
at com.ca.cib.zba.message.mt101.listener.ListenerMT101.processMessage(ListenerMT101.java:80)
at com.ca.cib.zba.message.mt101.listener.ListenerMT101.onMessage(ListenerMT101.java:65)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:562)
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:500)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:468)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:326)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:264)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1071)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1063)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:960)
at java.lang.Thread.run(Thread.java:735)
It is ObjectFactory.createMatherUnmarshaller that fails when running on Websphere application server while it works fine on stand alone test
#XmlElementDecl(namespace = "", name = "ZBAProcessingResult")
public JAXBElement<ZBAProcessingResult> createMatherUnmarshaller(ZBAProcessingResult zbaProcessingResult){
return new JAXBElement<ZBAProcessingResult>(ZBAProcessingResult_QNAME, ZBAProcessingResult.class,null,zbaProcessingResult);
}
A solution as been found I used a ObjectFactory.java and it was apparently the evil origin (in the Websphere Application Server’s world). So I switch to using a jaxb.index containing my serialized classes’ name. And I changed my code to not use JAXBElement :
I created an unit test case for displaying error messages in a different language than English but it doesn't seem to work and I don't know what I am missing.
Here are the details:
I am using attributes.
app.config (I excluded the nhibernate cfg):
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
<section name="nhv-configuration" type="NHibernate.Validator.Cfg.ConfigurationSectionHandler, NHibernate.Validator" />
</configSections>
<nhv-configuration xmlns="urn:nhv-configuration-1.0">
<property name='apply_to_ddl'>false</property>
<property name='autoregister_listeners'>true</property>
<property name='default_validator_mode'>OverrideExternalWithAttribute</property>
</nhv-configuration>
Initialization of the validator:
private void InitializeValidator()
{
var provider = new NHibernateSharedEngineProvider();
provider.GetEngine().Configure();
NHibernate.Validator.Cfg.Environment.SharedEngineProvider = provider;
}
The test function (EntityDescription is my entity class and the Repository follows the sharp architecture design with Repository classes):
[Test]
public void TestNhValidationSp()
{
CultureInfo ci = CultureInfo.GetCultureInfo("fr");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
TestNhValidation();
}
private void TestNhValidation()
{
IEntityDescriptionRepository repository = GetObject<IEntityDescriptionRepository>();
ISession session = NHibernateSession.Current;
EntityDescription entityDescription=
(from kpad in session.Query<EntityDescription>()
select kpad).FirstOrDefault();
entityDescription.Title = "012345678901234567890123456789012345678901234567890123456789";
try
{
repository.SaveOrUpdateWithTransaction(entityDescription);
Assert.IsTrue(false);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Assert.IsTrue(ex is InvalidStateException);
InvalidStateException isex = (InvalidStateException) ex;
foreach (InvalidValue invalidValue in isex.GetInvalidValues())
{
Console.WriteLine("PropertyName={0} Message={1}", invalidValue.PropertyName, invalidValue.Message);
}
}
}
Setting
entityDescription.Title = "012345678901234567890123456789012345678901234567890123456789";
will trigger a validation error because the title can have up to 50 chars.
The problem is that the message always comes in English. Any thoughts?
One thing I want to add is that my test project has a dependency on the SharpArchitecture project (1.9.5). I wonder if somehow this screws up my nhibernate validator cnfiguration.
Found this message: NHibernate Validation Localization with S#arp Architecture that reports a similar problem.
I think it was my own fault due to a dll versions mix-up.
SharpArchitecture 1.9.5 uses NHV 1.2.0 which in turn has been compiled with NH 2.1.0.
My test above used NHV 1.3.1 (I wanted to upgrade to the latest version of NHV) and it didn't work, the messages didn't show in the right language.
I recompiled NHV 1.2.0 to use NH 3.1.0, I switched to NHV 1.2.0 and now the test works fine.