Java reference inner class attributes through outer class object - java

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.

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.

Parse JSON into a java object

Hello I have the following task:
A URL that has a JSON Object:
- Write a program to read/write URL
- Parse data in URL using JSON to JAVA Object
- display 3 variables to user from the object
- Find entity/list of object = Find object that has ‘name’
- Find Object that has ‘author’
- Find Object that has ‘item’
*Define through annotation how to define JSON into Java list and find Object that has ‘name’ in it.
I think the question is asking to parse the JSON without using any java library. So far I have developed the following code:
class JSONObject {
HashMap map = new HashMap();
}
public class SYW {
public static String sampleUrl = "https://api.github.com/users/mralexgray/repos";
public static Integer index = 1;
public static void main(String[] args) {
//String sampleJSON = fetchJSON(sampleUrl);
JSONObject json = getJSONObject("{\"login\": \"mralexgray\",\"id\": 262517,\"avatar_url\": \"https://avatars.githubusercontent.com/u/262517?v=3\"}");
// suppose there is a owner class
populateJavaObject(json, Owner.class);
}
public static void populateJavaObject(JSONObject json, Class class1) {
// TODO Auto-generated method stub
Object obj = null;
try {
obj = class1.newInstance();
Iterator it = json.map.keySet().iterator();
while (it.hasNext()) {
String key = (String)it.next();
Object value = json.map.get(key);
Field field = class1.getDeclaredField(key);
field.setAccessible(true);
if (value instanceof Integer) {
field.setInt(obj, (Integer)value);
} else if (value instanceof String) {
field.setString(obj, (String)value);
}
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getString(String jsonStr) {
int i = index;
StringBuffer buf = new StringBuffer();
while (jsonStr.charAt(i) != '\"') {
jsonStr.charAt(i);
buf.append(jsonStr.charAt(i));
i++;
}
index = i;
return buf.toString();
}
public static JSONObject getJSONObject (String jsonStr) {
StringBuffer buf = new StringBuffer();
boolean isKey = true;
String currentKey = "";
Object currentValue = "";
JSONObject json = new JSONObject();
while (jsonStr.charAt(index) != '}') {
if (jsonStr.charAt(index) == '\"') {
index++;
String token = getString(jsonStr);
if (isKey) {
currentKey = token;
} else {
currentValue = token;
}
} else if (Character.isDigit(jsonStr.charAt(index))) {
Integer token = getNumber(jsonStr);
currentValue = token;
} else if (jsonStr.charAt(index) == '{') {
currentValue = getJSONObject(jsonStr);
} else if (jsonStr.charAt(index) == '[') {
currentValue = getArray(jsonStr);
} else if (jsonStr.charAt(index) == ':') {
isKey = false;
} else if (jsonStr.charAt(index) == ',' || jsonStr.charAt(index) == '}') {
isKey = true;
json.map.put(currentKey, currentValue);
}
index++;
}
return json;
}
private static ArrayList getArray(String jsonStr) {
ArrayList list = new ArrayList();
while (jsonStr.charAt(index) != ']') {
index++;
}
return null;
}
private static Integer getNumber(String jsonStr) {
// TODO Auto-generated method stub
Integer num = 0;
while (Character.isDigit(jsonStr.charAt(index))) {
num = num * 10 + Integer.parseInt(jsonStr.charAt(index)+"");
index++;
}
index--;
return num;
}
public static Object parseJSON(String jsonStr) {
Owner owner = new Owner();
while (index <= jsonStr.length()) {
if (jsonStr.charAt(index) == '{') {
return getJSONObject(jsonStr);
} else if (jsonStr.charAt(index) == '[') {
return getArray(jsonStr);
}
}
return null;
}
public static String fetchJSON(String url) {
String nextLine = "";
try {
URL sywURL = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(sywURL.openStream()));
StringBuffer buf = new StringBuffer();
while ((nextLine = reader.readLine()) != null) {
buf.append(nextLine);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return nextLine;
}
}
What I am doing here is I have a JSONObject class which stores the JSON attributes in a map then I want to use reflection to populate any class.
For parsing the JSON, I am trying to create a mini FSM ( :) ), which parses the string using a for loop and based on the character it either parses the string or number or array token. I am using a non-generic map so that I can store object of any type.
I was thinking may be I can use template or something pattern where each node will have a recursive structure or will be a leaf node. But I am really confused how to represent that because each leaf node can have one attribute and value. How can I represent that? Besides Is this the only way to represent that or whatever I have done so far is in the right direction?
Secondly, if I parse the objects, then how can I store them? Obviously the task is to find elements based on different attribute values. So I can create probably a hashmap based on one key to serve the one such query. But then how can I create an efficient data structure that will allow me efficiently query based on different attributes?
Thirdly, I am not sure what this means "Define through annotation how to define JSON into Java list and find Object that has ‘name’ in it."
Please help.
Thanks
'I think the question is asking to parse the JSON without using any java library' - personally I take it as being the complete opposite.
Software engineering principle number 1 is 'Don't reinvent the wheel'.
I think 'Define through annotation how to define JSON into Java list and find Object that has ‘name’ in it.' is a strong hint to use the annotations with the Jackson parser - which would be the standard way to attack this problem. Jackson annotations

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);

marshalling a log file into an xml file - 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
}

How to modify values of JsonObject / JsonArray directly?

Once i have parsed a JSON String into a GSON provided JsonObject class, (assume that i do not wish to parse it into any meaningful data objects, but strictly want to use JsonObject), how am i able to modify a field / value of a key directly?
I don't see an API that may help me.
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
This works for modifying childkey value using JSONObject.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
Since 2.3 version of Gson library the JsonArray class have a 'set' method.
Here's an simple example:
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
Another approach would be to deserialize into a java.util.Map, and then just modify the Java Map as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).
Here's an simple example:
public class BasicDB {
private JSONObject jData = new JSONObject;
public BasicDB(String username, String tagline) {
try {
jData.put("username", username);
jData.put("tagline" , tagline);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername () {
String ret = null;
try {
ret = jData.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void setUsername (String username) {
try {
jData.remove("username");
jData.put("username" , username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTagline () {
String ret = null;
try {
ret = jData.getString("tagline");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
JSONObject json = new JSONObject();
String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
json = new JSONObject(jsonStr);
System.out.println(json);
JSONArray jsonArray = json.getJSONArray("users");
JSONArray finalJsonArray = new JSONArray();
/**
* Get User form setNewUser method
*/
//finalJsonArray.put(setNewUserPreference());
boolean has = true;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
finalJsonArray.put(jsonObject);
String username2 = jsonObject.getString("userName");
if (username2.equals(username)) {
has = true;
}
System.out.println("user name are :" + username2);
JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
String eng = jsonObject2.getString("Eng");
String fin = jsonObject2.getString("Fin");
String ger = jsonObject2.getString("Ger");
jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
System.out.println(" Eng : " + eng + " Fin " + fin + " ger : " + ger);
}
System.out.println("Final JSON Array \n" + json);
jsonArray.put(setNewUserPreference());
return json;
}

Categories