Which is the best option to create a JSONObject and JSONArray in Liferay portlet?
You can't do Java simple way:
JSONObject json = new JSONObject();
JSONArray arrayJson = new JSONArray();
Error:
Cannot instantiate the type JSONObject
Cannot instantiate the type JSONArray
Tried with JSONFactoryUtil and it works but its deprecated.
com.liferay.util.json.JSONFactoryUtil
JSONObject json = JSONFactoryUtil.createJSONObject();
JSONArray arrayJson = JSONFactoryUtil.createJSONArray();
JSONFactoryUtil.createJSONObject() and JSONFactoryUtil.createJSONArray() are not deprecated, neither in Liferay 6.x nor in Liferay 7.x.
If you still want to use new JSONObject() and new JSONArray(), you can import org.json.
Maven:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
Gradle:
compileOnly group: 'org.json', name: 'json', version: '20190722'
Try a different version if this version doesnât work for you.
Related
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?
In all examples I see over the internet, need to call "setContext". but this function doesn't exist in JaxbDataFormat . Any idea or alternative way yo convert from xml to Json
// XML Data Format
JaxbDataFormat xmlDataFormat = new JaxbDataFormat();
JAXBContext con = JAXBContext.newInstance(Employee.class);
**xmlDataFormat.setContext(con);**
// JSON Data Format
JacksonDataFormat jsonDataFormat = new JacksonDataFormat(Employee.class);
from("file:C:/inputFolder").doTry().unmarshal(xmlDataFormat).
process(new MyProcessor()).marshal(jsonDataFormat).
to("jms:queue:javainuse").doCatch(Exception.class).process(new Processor() {
public void process(Exchange exchange) throws Exception {
Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
System.out.println(cause);
}
});
Thanks!
You can't find this function because either you aren't importing this package:
import org.apache.camel.converter.jaxb.JaxbDataFormat;
or because you aren't adding this dependency in your pom.xml:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jaxb</artifactId>
<version>${camel-version}</version>
</dependency>
You can check my reference archive here https://metiago.github.io/dev/2017/02/12/java-apache-camel-xml.html?query=camel for a better example.
Im using automapper to object conversion where source is table class and destination is property class.
I'm using .dml to connect database.
App type - Window
Using platform - VS-12 framework 4.5 , automapper version 4.2.1
Issues :- when convert single class object automapper successfully converted but when im using list then it return zero.
In Config class-
public static Initialize();
Mapper.CreateMap<Source, destination>().ReverseMap();
Mapper.CreateMap<List<Source>, List<destination>>().ReverseMap();
In code-
//It run successfully
Mapper.map(result, objdestination);
//It not run work and anot giving any exception
Mapper.map(listresult, listdestination);
Thanks in advance.
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap< Source, destination>().ReverseMap();
});
config.AssertConfigurationIsValid(); // check if configuration valid.
IMapper mapper = config.CreateMapper();
var appProduct = mapper.Map<List<destination>>(sourceObj);
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
I have an issue when using the Binder implementation in MOXy.
Here is the input XML document (input.xml)
<?xml version="1.0" encoding="utf-8"?>
<root>
<unmapped />
</root>
And now, here is the source code used to unmarshal XML into a Binder instance and then update the XML from the corresponding Java object:
JAXBContext context = JAXBContext.newInstance(Input.class);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
Document document = builder.parse(new File("input.xml"));
Binder<Node> binder = context.createBinder(Node.class);
Input input = (Input) binder.unmarshal(document);
binder.updateXML(input);
In the end, the very simple Input class file:
#XmlRootElement(name = "root")
public class Input {
#XmlAnyElement
protected Object[] elements;
}
When the updateXML() method is invoked, the following exception is thrown:
java.lang.NullPointerException
at org.eclipse.persistence.internal.jaxb.DomHandlerConverter.convertObjectValueToDataValue(DomHandlerConverter.java:97)
We have been able to confirm this issue and it looks like it will be a very quick fix. You can use the link below to track our progress on this issue.
http://bugs.eclipse.org/391237
UPDATE
A fix has been checked into the EclipseLink 2.5.0 stream, a nightly download can be obtained from the following location:
http://www.eclipse.org/eclipselink/downloads/nightly.php
We have also checked in a fix to the EclipseLink 2.4.2 stream. A nightly download can be obtained from the above location starting October 12, 2012.