marshalling a log file into an xml file - Java - java

I have a log file with the following output:
2226:org.powertac.common.TariffSpecification::6::new::1::CONSUMPTION
2231:org.powertac.common.Rate::7::new
2231:org.powertac.common.Rate::7::withValue::-0.5
2232:org.powertac.common.Rate::7::setTariffId::6
2232:org.powertac.common.TariffSpecification::6::addRate::7
2233:org.powertac.common.Tariff::6::new::6
2234:org.powertac.common.TariffSpecification::8::new::1::INTERRUPTIBLE_CONSUMPTION
2234:org.powertac.common.Rate::9::new
2234:org.powertac.common.Rate::9::withValue::-0.5
2235:org.powertac.common.Rate::9::setTariffId::8
After I parse the file, have the following pattern:
<id>:<full_classname>::<order_of_execution>::<new_or_method>::<params>
The parser works nicely, and does what I expect. Now, my goal is to marshalling that same instruction into a XML file. I'm totally unfamiliar with this kind of task.
So, the XML would have to contain both new objects and methods call.
I know using the Reflection API I would use the <full_classname> to create an object of that class:
Class<?> cl = Class.forName( className );
How could I generate such XML file from that Class object? Do I have to have a data-structure or a way to take all the methods and fields of the object and write them to the xml file? I know the Reflection API has such methods, but I would need a more general / sample idea of how could I accomplish my task.
I started to write down this method, but I'm not sure how would it work:
// would send in the object to be marshalled.
public void toXML(Object obj){
try {
JAXBContext context = JAXBContext.newInstance(Object.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here is a sample of the parsed file:
171269 org.powertac.common.Order 171417 new 4
171270 org.powertac.common.Order 171418 new 4
171271 org.powertac.common.Order 171419 new 4
The parse method looks like:
public void parse() throws ClassNotFoundException{
try{
//
// assure file exists before parsing
//
FileReader fr = new FileReader( this.filename );
BufferedReader textReader = new BufferedReader( fr );
String line;
File input = new File("test.xml");
//Integer id = 1;
while(( line = textReader.readLine()) != null ){
Pattern p = Pattern.compile("([^:]+):([^:]+)::([\\d]+)::([^:]+)::(.+)");
Matcher m = p.matcher( line );
if (m.find()) {
int id = Integer.parseInt(m.group(1));
String className = m.group(2);
int orderOfExecution = Integer.valueOf( m.group( 3 ));
String methodNameOrNew = m.group(4);
String[] arguments = m.group(5).split("::");
//
// there is the need to create a new object
//
if( methodNameOrNew.compareTo( "new" ) == 0 ){
//
// inner class
//
if( className.contains("$") == true){
continue;
}
else if( className.contains("genco")){
continue;
}
System.out.println("Loading class: " + className);
LogEntry le = new LogEntry(id, className, orderOfExecution, methodNameOrNew, arguments.toString());
Serializer ser = new Persister();
ser.write(le, input);
id++;
System.out.printf("%s %s %d %s %d\n", id, className, orderOfExecution, methodNameOrNew, arguments.length);
}
}
}
textReader.close();
}
catch( IOException ex ){
ex.printStackTrace();
}
catch( ArrayIndexOutOfBoundsException ex){
ex.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void write() throws Exception{
File file = new File("test.xml");
Serializer ser = new Persister();
for(LogEntry entry : entries){
ser.write(entry, file);
}
}

Here is a first try using Simple XML library:
#Default()
public class LogEntry
{
private int id;
private Object classInstance;
private String orderOfExecution;
private String newOrMethod;
private String params;
// throws 'Exception' only for testing
public LogEntry(int id, String className, String orderOfExecution, String newOrMethod, String params) throws Exception
{
this.id = id;
this.classInstance = Class.forName(className).newInstance();
this.orderOfExecution = orderOfExecution;
this.newOrMethod = newOrMethod;
this.params = params;
}
// getter / setter
}
And how do make XML out of the class LogEntry:
// Here is an example of an entry
LogEntry le = new LogEntry(3, "com.example.MyClass", "abc", "def", "ghi");
Serializer ser = new Persister();
ser.write(le, new File("test.xml"));
Simple XML is very easy to use, see here for tutorials and examples.
You can custumize the whole XML with the Annotations in the LogEntry Class, however you can also let #Default() do everything for you :-)

LogEntry:
#Default()
public class LogEntry
{
private int id;
private Object classInstance;
private int orderOfExecution;
private String newOrMethod;
private List<Object> args;
public LogEntry(int id, Object classInstance, int orderOfExecution, String newOrMethod, List<Object> args)
{
this.id = id;
this.classInstance = classInstance;
this.orderOfExecution = orderOfExecution;
this.newOrMethod = newOrMethod;
this.args = args;
}
public LogEntry() { }
// getter / setter / toString / ... here
}
parse Method:
// Here all entries are saved
private List<LogEntry> entries = new ArrayList<>();
// ...
public void parse() throws Exception
{
// Don't compile this in a loop!
Pattern p = Pattern.compile("([^:]+):([^:]+)::([\\d]+)::([^:]+)::(.+)");
FileReader fr = new FileReader(this.filename);
BufferedReader textReader = new BufferedReader(fr);
String line;
while( (line = textReader.readLine()) != null )
{
Matcher m = p.matcher(line);
if( m.find() )
{
LogEntry entry = new LogEntry();
entry.setId(Integer.valueOf(m.group(1)));
String className = m.group(2);
entry.setOrderOfExecution(Integer.valueOf(m.group(3)));
String methodNameOrNew = m.group(4);
entry.setNewOrMethod(methodNameOrNew); // required in LogEntry?
Object[] arguments = m.group(5).split("::");
entry.setArgs(Arrays.asList(arguments));
if( methodNameOrNew.equals("new") )
{
if( className.contains("$") == true || className.contains("genco") )
continue;
createInstance(className, arguments);
}
else
{
callMethod(className, methodNameOrNew, arguments);
}
// XXX: for testing - set the instance 'not null'
entry.setClassInstance("only for testing");
entries.add(entry);
}
}
textReader.close();
}
Edit:
Lets say your parse()-Method, the List etc are in the Class Example:
#Root
public class Example
{
private File filename = new File("test.txt");
#ElementList
private List<LogEntry> entries = new ArrayList<>();
// ...
// Only 'entries' is annotated as entry -> only it will get serialized
public void storeToXml(File f) throws Exception
{
Serializer ser = new Persister();
ser.write(this, f);
}
public void parse() throws Exception
{
// ...
}
}
Note: For this example i've added entry.setClassInstance("only for testing"); above entries.add(...), else the instance is null.
Edit #2: Helper methods for parse()
private Object createInstance(String className, Object args[])
{
// TODO
return null;
}
private void callMethod(String className, String methodName, Object args[])
{
// TODO
}

Related

NullPointerException while invoking method getInputParameters()

I am doing Parameterized Java Mapping in SAP PI 7.5 with following parameters bound by the tag names specified in the Operation Mapping
(BS_NAME,CHANNEL_NAME,EMAIL).
On testing the below java mapping in the test tab of OM using the payload, it gives the following error:
NullPointerException while trying to invoke the method com.sap.aii.mapping.api.TransformationInput.getInputParameters() of a null object loaded from field of an object loaded from local variable "this**"
I debugged the code but didn't found the issue, any suggestions?
Please find below Java code for XmlNFe_To_Mail Class. BodyText Class is also used to fetch some content. The error is encountered in the XmlNFe_To_Mail Class.
public class XmlNFe_To_Mail extends AbstractTransformation {
private String prefixoSubject = new String();
private String emailFrom = new String();
private String prefixoDocumento = new String();
private String frase = new String();
private String gap = "\n\r";
private AbstractTrace trace = null;
private Map map = null;
private String BSSystem = "";
private String ComChannel = "";
private String Emails = "";
private final String NFE_EMPRESA = "NFE Company: ";
private final String NFe = "NFE";
private final String NFe_Mail = "nfe#company.com";
TransformationInput input = null;
TransformationOutput output = null;
public void execute(InputStream in , OutputStream out) throws StreamTransformationException {
// TODO Auto-generated method stub
{
BSSystem = input.getInputParameters().getString("BS_NAME");
ComChannel = input.getInputParameters().getString("CHANNEL_NAME");
Emails = input.getInputParameters().getString("EMAIL");
try {
configParamEmail();
BufferedReader inpxml = new BufferedReader(new InputStreamReader( in ));
StringBuffer buffer = new StringBuffer();
String line = "";
String quebra = System.getProperty("line.separator");
while ((line = inpxml.readLine()) != null) {
line.replaceAll("\r\n", "");
line.replaceAll(quebra, "");
line.replaceAll(" />", "/>");
line.replaceAll(" />", "/>");
line.replaceAll(" />", "/>");
buffer.append(line);
}
String inptxml = buffer.toString();
inptxml = inptxml.replace("\r\n", "");
inptxml = inptxml.replaceAll(quebra, "");
inptxml = inptxml.replaceAll(" />", "/>");
inptxml = inptxml.replaceAll(" />", "/>");
inptxml = inptxml.replaceAll(" />", "/>");
String idNFe = "";
String numeroNF = "";
String idEvent = "";
idNFe = inptxml.substring(inptxml.indexOf("<chNFe>") + 7, inptxml.indexOf("</chNFe>"));
numeroNF = idNFe.substring(25, 34);
if (inptxml.indexOf("infEvento") > 0) {
idEvent = inptxml.substring(inptxml.indexOf("<tpEvento>") + 10, inptxml.indexOf("</tpEvento>"));
if (idEvent.length() > 0) {
if (idEvent.equals("111111")) {
this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "CancNFe"));
this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE", "NFE CANCELADA"));
} else if (idEvent.equals("100000")) {
this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "CCE"));
this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE", "CCE"));
} else {
this.setPrefixoDocumento(this.getPrefixoDocumento().replaceAll("NFE", "ManDest"));
this.setPrefixoSubject(this.getPrefixoSubject().replaceAll("NFE", "MANIFESTO"));
}
}
}
Channel chn = null;
RfcAccessor rfc = null;
String email = "";
String pdf = "";
chn = LookupService.getChannel(getBSystem(), getCChannel());
rfc = LookupService.getRfcAccessor(chn);
String req = "<ns0:TEST_NFE_MAIL_OPT xmlns:ns0='urn:sap-com:document:sap:rfc:functions'><I_ACCESS_KEY>" +
idNFe + "<I_ACCESS_KEY></ns0:ZOTC_NFE_EMAIL_OUTPUT>";
InputStream inputRFC = new ByteArrayInputStream(req.getBytes("UTF-8"));
XmlPayload rfcPayload = LookupService.getXmlPayload(inputRFC);
XmlPayload result = rfc.call(rfcPayload);
InputStream resp = result.getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(resp);
Node node = (Node) doc.getElementsByTagName("E_EMAIL").item(0);
if (node.hasChildNodes() && !node.getFirstChild().getNodeValue().equals("")) {
email = node.getFirstChild().getNodeValue();
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transform = tf.newTransformer();
Document docout = db.newDocument();
Element root = docout.createElement("ns0:Mail");
root.setAttribute("xmlns:ns0", "http://sap.com/xi/XI/Mail/30");
docout.appendChild(root);
Element subject = docout.createElement("Subject");
root.appendChild(subject);
Text subjectText = docout.createTextNode(getPrefixoSubject() + numeroNF);
subject.appendChild(subjectText);
Element from = docout.createElement("From");
root.appendChild(from);
Text fromText = docout.createTextNode(getEmailFrom());
from.appendChild(fromText);
if (email.length() > 0) {
email += ";";
} else {
email = this.getEmaillist();
}
Element to = docout.createElement("To");
root.appendChild(to);
Text toText = docout.createTextNode(email);
to.appendChild(toText);
Element contentType = docout.createElement("Content_Type");
root.appendChild(contentType);
Text contentTypeText = docout.createTextNode("multipart/mixed;boundary=--AaZz");
contentType.appendChild(contentTypeText);
BodyText texto = new BodyText(idNFe, getFrase(), inptxml, pdf);
Element content = docout.createElement("Content");
root.appendChild(content);
Text contentText = null;
if ("NFE Company: ".equalsIgnoreCase(getPrefixoSubject())) {
contentText = docout.createTextNode(texto.getnfeText());
} else if ("NFE CANCELADA Company: ".equalsIgnoreCase(getPrefixoSubject())) {
contentText = docout.createTextNode(texto.getCnfeText());
} else if ("CCE Company: ".equalsIgnoreCase(getPrefixoSubject())) {
contentText = docout.createTextNode(texto.getcceText());
}
content.appendChild(contentText);
DOMSource domS = new DOMSource(docout);
transform.transform((domS), new StreamResult(out));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// Exception Handling }
}
}
}
public String getGap() {
return gap;
}
public void setGap(String gap) {
this.gap = gap;
}
public String getFrase() {
return frase;
}
public void setFrase(String frase) {
this.frase = frase;
}
public String getBSystem() {
return BSSystem;
}
public String getEmaillist() {
return Emails;
}
public String getCChannel() {
return ComChannel;
}
public String getPrefixoSubject() {
return prefixoSubject;
}
public void setPrefixoSubject(String prefixoSubject) {
this.prefixoSubject = prefixoSubject;
}
public String getEmailFrom() {
return emailFrom;
}
public void setEmailFrom(String emailFrom) {
this.emailFrom = emailFrom;
}
public String getPrefixoDocumento() {
return prefixoDocumento;
}
public void setPrefixoDocumento(String prefixoDocumento) {
this.prefixoDocumento = prefixoDocumento;
}
private void configParamEmail() {
setEmailFrom(NFe_Mail);
setPrefixoDocumento(NFe);
setPrefixoSubject(NFE_EMPRESA);
}
#Override
public void transform(TransformationInput in , TransformationOutput out) throws StreamTransformationException {
this.execute( in .getInputPayload().getInputStream(), out.getOutputPayload().getOutputStream());
}
/*public void setParameter(Map arg0) {
// TODO Auto-generated method stub
}*/
}
Kindly let me know what changes should be done.
Thanks.
It's missing instance from the TransformationInput/TransformationOutput classes because their variables are null,
TransformationInput input = null;
TransformationOutput output = null;
So you need to instance them or pass them as reference on some setter.

Creating stub for dependence class's under test

Good day, everyone! I have a little question about testing and generating a stub for dependence through reflection. So let's assume I have a class named UnderTest:
class UnderTest{
/*field*/
SomeLogic someLogic;
/*method, that i testing*/
List<MyObject> getCalculatedObjects(params) {/*logic,based on result getSomeStuff of someLogic*/ }
}
class SomeLogic {
List<String> getSomeStuff(String param) { /*Some complex and slow code, actually don't want test this code, and want to use some reflection invocation handler*/ }
}
For me it's important to not change legacy code, which doesn't design for testing. And i don't have any reason, except testing to make SomeLogic as an interface and so on.
I can't remember how to handle method invocation of someLogic using reflection. But google search isn't helping me.
Class MainAPI is... main api of my module. NetworkProvider long open stream operation, that's why i want to stub it, on my local files. But don't using directly reference on NetworkProvider. Again sorry for my English.
public class MainAPI {
private final XPath xPath;
private final ItemParser itemParser;
private final ListItemsParser listItemsParser;
private final DateParser dateParser;
private final HtmlCleanUp htmlCleanUp;
private final NetworkProvider networkProvider;
public MainAPI(XPath xPath, ItemParser itemParser, ListItemsParser listItemsParser, DateParser dateParser, HtmlCleanUp htmlCleanUp, NetworkProvider networkProvider) {
this.xPath = xPath;
this.itemParser = itemParser;
this.listItemsParser = listItemsParser;
this.dateParser = dateParser;
this.htmlCleanUp = htmlCleanUp;
this.networkProvider = networkProvider;
}
public MainAPI() throws XPathExpressionException, IOException {
dateParser = new DateParser();
xPath = XPathFactory.newInstance().newXPath();
networkProvider = new NetworkProvider();
listItemsParser = new ListItemsParser(xPath, dateParser, item -> true);
itemParser = new ItemParser(xPath, dateParser, networkProvider);
htmlCleanUp = new HtmlCleanUpByCleaner();
}
public List<Item> getItemsFromSessionParsing(SessionParsing sessionParsing) {
listItemsParser.setCondition(sessionParsing.getFilter());
List<Item> result = new ArrayList<>();
Document cleanDocument;
InputStream inputStream;
for (int currentPage = sessionParsing.getStartPage(); currentPage <= sessionParsing.getLastPage(); currentPage++) {
try {
inputStream = networkProvider.openStream(sessionParsing.getUrlAddressByPageNumber(currentPage));
} catch (MalformedURLException e) {
e.printStackTrace();
break;
}
cleanDocument = htmlCleanUp.getCleanDocument(inputStream);
List<Item> list = null;
try {
list = listItemsParser.getList(cleanDocument);
} catch (XPathExpressionException e) {
e.printStackTrace();
break;
}
for (Item item : list) {
inputStream = null;
try {
inputStream = networkProvider.openStream("http://www.avito.ru" + item.getUrl());
} catch (MalformedURLException e) {
e.printStackTrace();
break;
}
cleanDocument = htmlCleanUp.getCleanDocument(inputStream);
try {
item.setDescription(itemParser.getDescription(cleanDocument));
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
result.addAll(list);
}
return result;
}
}
public class NetworkProvider {
private final ListCycleWrapper<Proxy> proxyList;
public NetworkProvider(List<Proxy> proxyList) {
this.proxyList = new ListCycleWrapper<>(proxyList);
}
public NetworkProvider() throws XPathExpressionException, IOException {
this(new ProxySiteParser().getProxyList(new HtmlCleanUpByCleaner().getCleanDocument(new URL("http://www.google-proxy.net").openStream())));
}
public int getSizeOfProxy() {
return proxyList.size();
}
public InputStream openStream(String urlAddress) throws MalformedURLException {
URL url = new URL(urlAddress);
while (!proxyList.isEmpty()) {
URLConnection con = null;
try {
con = url.openConnection(proxyList.getNext());
con.setConnectTimeout(6000);
con.setReadTimeout(6000);
return con.getInputStream();
} catch (IOException e) {
proxyList.remove();
}
}
return null;
}
}
All the dependencies of your class to tests are injectable using its constructor, so there shouldn't be any problem to stub these dependencies and injecting the stubs. You don't even need reflection. For example, using Mockito:
NetworkProvider stubbedNetworkProvider = mock(NetworkProvider.class);
MainAPI mainApi = new MainAPI(..., stubbedNetworkProvider);
You can also write a stub by yourself if you want:
NetworkProvider stubbedNetworkProvider = new NetworkProvider(Collections.emptyList()) {
// TODO override the methods to stub
};
MainAPI mainApi = new MainAPI(..., stubbedNetworkProvider);

BeanSerializer/BeanDeserializer Axis Generated Object

I have a large number of axis generated objects from several WSDLs, I need a generic solution to store the objects in xml format in the database, but also load them back in java when needed.
This is what I've made so far:
private String serializeAxisObject(Object obj) throws Exception {
if (obj == null) {
return null;
}
StringWriter outStr = new StringWriter();
TypeDesc typeDesc = getAxisTypeDesc(obj);
QName qname = typeDesc.getXmlType();
String lname = qname.getLocalPart();
if (lname.startsWith(">") && lname.length() > 1)
lname = lname.substring(1);
qname = new QName(qname.getNamespaceURI(), lname);
AxisServer server = new AxisServer();
BeanSerializer ser = new BeanSerializer(obj.getClass(), qname, typeDesc);
SerializationContext ctx = new SerializationContext(outStr,
new MessageContext(server));
ctx.setSendDecl(false);
ctx.setDoMultiRefs(false);
ctx.setPretty(true);
try {
ser.serialize(qname, new AttributesImpl(), obj, ctx);
} catch (final Exception e) {
throw new Exception("Unable to serialize object "
+ obj.getClass().getName(), e);
}
String xml = outStr.toString();
return xml;
}
private Object deserializeAxisObject(Class<?> cls, String xml)
throws Exception {
final String SOAP_START = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><soapenv:Header /><soapenv:Body>";
final String SOAP_START_XSI = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Header /><soapenv:Body>";
final String SOAP_END = "</soapenv:Body></soapenv:Envelope>";
Object result = null;
try {
Message message = new Message(SOAP_START + xml + SOAP_END);
result = message.getSOAPEnvelope().getFirstBody()
.getObjectValue(cls);
} catch (Exception e) {
try {
Message message = new Message(SOAP_START_XSI + xml + SOAP_END);
result = message.getSOAPEnvelope().getFirstBody()
.getObjectValue(cls);
} catch (Exception e1) {
throw new Exception(e1);
}
}
return result;
}
private TypeDesc getAxisTypeDesc(Object obj) throws Exception {
final Class<? extends Object> objClass = obj.getClass();
try {
final Method methodGetTypeDesc = objClass.getMethod("getTypeDesc",
new Class[] {});
final TypeDesc typeDesc = (TypeDesc) methodGetTypeDesc.invoke(obj,
new Object[] {});
return (typeDesc);
} catch (final Exception e) {
throw new Exception("Unable to get Axis TypeDesc for "
+ objClass.getName(), e);
}
}
I have fixed it, I will leave this here if anyone else needs to use it
Have fun.
I have fixed it, I will leave this here if anyone else needs to use it. See the updated version.
Thank you

Java reference inner class attributes through outer class object

I'm having the problem my title describes. I have an outer class called GAINEntities with an inner class in it called Entities. My goal is to reference the attributes of the inner class through objects of the outer class. I have a function readGainEntities(String inputUrl) which returns a Vector. Thus, in my method i call readGainEntities method and set its content to a new Vector
Example Code:
protected static Vector<LinkedHashTreeMap> getGainEntities(String inputUrl) {
URL url = null;
try {
url = new URL(inputUrl);
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
URLConnection yc = null;
try {
yc = url.openConnection();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String userpass = "" + ":" + "";
String basicAuth = "Basic "
+ new String(new Base64().encode(userpass.getBytes()));
yc.setRequestProperty("Authorization", basicAuth);
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Gson gson = new Gson();
List<LinkedHashTreeMap> items = null;
try {
items = gson.fromJson(in.readLine(),
new TypeToken<List<LinkedHashTreeMap>>() {
}.getType());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Vector<LinkedHashTreeMap> sessions = new Vector<LinkedHashTreeMap>();
for (int i = 0; i < items.size(); i++) {
sessions.add(items.get(i));
}
return sessions;
}
public static Vector<GAINEntities> readGainentities(String inputUrl) {
Vector<GAINEntities> exp = new Vector<GAINEntities>();
Vector<LinkedHashTreeMap> sessions = getGainEntities(inputUrl);
Iterator it = sessions.iterator();
while (it.hasNext()) {
LinkedHashTreeMap next = (LinkedHashTreeMap) it.next();
GAINEntities input = new GAINEntities();
input.setObjectID((String) next.get("objectId"));
input.setSubobjectID((String) next.get("subobjectId"));
LinkedHashTreeMap<String, String> lhmt = (LinkedHashTreeMap<String, String>) next
.get("attributes");
data.GAINEntities.Attributes atts = input.new Attributes();
atts.setAttributeStart(Double.parseDouble(String.valueOf(lhmt
.get("start"))));
atts.setAttributeEnd(Double.parseDouble(String.valueOf(lhmt
.get("end"))));
input.setAttributes(atts);
input.setAccountID((String) next.get("accountId"));
input.setID((String) next.get("_id"));
input.setV(Double.parseDouble(String.valueOf(next.get("__v"))));
ArrayList<LinkedHashTreeMap<String, String>> al = (ArrayList<LinkedHashTreeMap<String, String>>) next
.get("entities");
ArrayList<Entities> ents = new ArrayList<Entities>();
for (int i = 0; i < al.size(); i++) {
ents.add(input.new Entities(al.get(i).get("ntype"), al.get(i)
.get("source"), al.get(i).get("lod"), al.get(i).get(
"type"), al.get(i).get("label"), Double
.parseDouble(String
.valueOf(al.get(i).get("confidence"))),
Double.parseDouble(String.valueOf(al.get(i).get(
"relevance")))));
}
input.setEntities(ents);
exp.add(input);
// System.out.println(input);
// System.out.println(input);
}
return exp;
}
Then in my Translate method:
public static String translateGAINEntities(String url) {
LogicFactory.initialize();
Vector<GAINEntities> exp = readGainEntities.readGainentities(url);
for (int i = 0; i < exp.size(); i++) {
LogicFactory.initialize();
GAINEntities gexp = exp.get(i);
System.out.println("HEREEE \t" + gexp.getEntities()); <-- returns empty.
So,is there something wrong with my code as im still unsure how to reference the Entities attributes through the GAINEntities objects which readGainEntities returns
Generally you can reference the attributes of the Inner class outside the Outer class only when you have an Object of the Outer class:
new Outer().new Inner().doStuff();
provided that the doStuff() method is public.
If the Inner class is static then you can reference it as:
new Outer.Inner().doStuff();
In your example you do not show the classes involved.

Marshalling list of elements in REST

I have a problem with sending ArrayList from server to my client using JAX-rs. I've got 4 classes:
Demo - there is starting REST server
FileDetails - there are 3 fields storing data
ConfigFiles - it has few methods for files and there is a list of FileDetails objects
RestServer - there is method GET
I've got the following code:
#XmlRootElement(name="FileDetails")
#Path("/easy")
public class RestSerwer {
#GET
#Path("/temporary")
#Produces("text/temporary")
public String methodGet() {
ConfigFiles cf = ConfigFiles.getInstance();
List<FileDetails> files = cf.getList();
try {
JAXBContext ctx = JAXBContext.newInstance(ArrayList.class, FileDetails.class);
Marshaller m = ctx.createMarshaller();
StringWriter sw = new StringWriter();
m.marshal(files, sw);
return sw.toString();
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
}
At client side I've got GetRest:
public class GetRest{
HttpClient client = null;
GetMethod method = null;
private String url = null;
public GetRest(String url) {
this.url = url;
}
public String getBody(String urlDetail){
client = new HttpClient();
method = new GetMethod(url + urlDetail);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
client.executeMethod(method);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] responseBody = null;
try {
responseBody = method.getResponseBody();
} catch (IOException e) {
e.printStackTrace();
}finally{
method.releaseConnection();
}
String str = new String(responseBody);
return str;
}
public String getFiles(){
return getBody("/easy/temporary");
}
}
When I try:
GetRest getRestClass = new GetRest("http://localhost:8185");
//List<FileDetails> cf = new ArrayList<FileDetails>();
String xxxx = getRestClass.getFiles(); // TODO
It throws:
Caused by: com.sun.istack.internal.SAXException2: unable to marshal type "java.util.ArrayList" as an element because it is missing an #XmlRootElement annotation
At server side.
Anybody can help me?
Thanks
You basically have 2 possibilities: Create you own class which is a wrapper on top of the List or write your own provider and inject it in jersey so that it knows how to marshall/unmarshall the arraylist. Here is a simple code for the first solution:
#XmlRootElement
public class MyListWrapper {
#XmlElement(name = "List")
private List<String> list;
public MyListWrapper() {/*JAXB requires it */
}
public MyListWrapper(List<String> stringList) {
list = stringList;
}
public List<String> getStringList() {
return list;
}
}

Categories