After reading xml file trying to send mail - java

I am trying to read the xml file and trying to send the mail.
here is the xml code
<?xml version="1.0" encoding="UTF-8"?><xml>
<u_incident_task>
<description>messafe</description>
<priority>1</priority>
<number>12345</number>
<u_task_incident_service_ci>A</u_task_incident_service_ci>
</u_incident_task>
<u_incident_task>
<description>messafe</description>
<priority>3</priority>
<number>123456</number>
<u_task_incident_service_ci>A</u_task_incident_service_ci>
</u_incident_task>
</xml>
so when ever Priority is 1 i need to send mail. currently my below code is working and able to send.
But when ever Priority is updated from 3 to 1 mail is not able to send. may be the reason i am storing all the number in array since i dont want to send mail repeatedly. so i stored the numbers in array so that i can be sent only once. so while i am storing the numbers if any Priority is updated to 1 mail is not working.
But when record is created with 1 mail i sent but if we updated the existing priority from 3 to 1 it not workin. complete working code is here. can any one help what i missed in logic pls?
complete code here.
Incidentreport2000.java
package com.asn.model;
import java.awt.Desktop;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.asn.model.incident200;
import com.asn.model.incident1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.mail.Message;
import javax.mail.MessagingException;import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
public class incidentreport2000 implements Runnable {
List<String> number1 = new ArrayList<String>();
public incidentreport2000(){
}
public void run(){
for(int i=1;i>0;i++){
try{
Thread.sleep(9600);
List<incident1> incident1List = new ArrayList<incident1>();
List<incident200> incident200List = new ArrayList<incident200>();
FileWriter fw =null;
BufferedWriter bw=null;
String Path = "C:\\Users";
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
InputStream input = null;
String address ="C:\\Users" ;
String localFileName = "\\file.xml";
try {
File fXmlFile = new File(Path + "\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList incident1NodeList = doc.getElementsByTagName("u_incident_task");
for (int temp = 0; temp < incident1NodeList.getLength(); temp++) {
Node varNode = incident1NodeList.item(temp);
if (varNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) varNode;
NodeList u_task_incident_service_ciList = eElement.getElementsByTagName
("u_task_incident_service_ci");
NodeList varsionList = eElement.getElementsByTagName("priority");
NodeList numberList = eElement.getElementsByTagName("number");
NodeList descriptionList = eElement.getElementsByTagName("description");
/* Node u_task_incident_service_ciNode =
u_task_incident_service_ciList.item(0);
Node priorityNode = varsionList.item(0);*/
Node u_task_incident_service_ciNode =
u_task_incident_service_ciList.item(0);
Node priorityNode = varsionList.item(0);
Node numberNode = numberList.item(0);
Node descriptionNode = descriptionList.item(0);
if (u_task_incident_service_ciNode.getNodeType() == Node.ELEMENT_NODE
&& priorityNode.getNodeType() ==
Node.ELEMENT_NODE) {
Element u_task_incident_service_ciElement = (Element)
u_task_incident_service_ciNode;
Element priorityElement = (Element) priorityNode;
Element numberElement = (Element) numberNode;
Element descriptionElement = (Element) descriptionNode;
incident1 incident1 = new incident1(
u_task_incident_service_ciElement.getTextContent(),
priorityElement.getTextContent());
incident1List.add(incident1);
incident200 incident200 = new incident200(
u_task_incident_service_ciElement.getTextContent(),
priorityElement.getTextContent(),numberElement.getTextContent (),descriptionElement.getTextContent());
incident200List.add(incident200);
}
}
// fw = new FileWriter(file.getAbsoluteFile());
// bw = new BufferedWriter(fw);
}
} catch (Exception e) {
e.printStackTrace();
}
Map<incident1, Integer> count = new HashMap<incident1, Integer>();
for (incident1 c : incident1List)
if (!count.containsKey(c))
count.put(c, Collections.frequency(incident1List, c));
List<String> prioritys = getprioritys(count);
List<String> u_task_incident_service_cis = getu_task_incident_service_cis(count);
Map<incident200, Integer> count1 = new HashMap<incident200, Integer>();
for (incident200 c1 : incident200List)
if (!count1.containsKey(c1))
count1.put(c1, Collections.frequency(incident200List, c1));
List<String> number = getnumber(count1);
List<String> description = getdescription(count1);
List<String> prioritys1 = getprioritys1(count1);
List<String> u_task_incident_service_cis1 = getu_task_incident_service_cis1(count1);
for (String v2 : prioritys1 ) {
if (v2 =="P1" ){
for (String n2 : number ) {
System.out.println(number);
if (!number1.contains(n2)) {
for (String d : description){
for (String m3 : u_task_incident_service_cis1){
if (m3 == "A"){
getCountu_task_incident_service_cis1( m3,prioritys1,n2,d, count1);
}
if (m3 == "B"){
getCountu_task_incident_service_cis1( m3,prioritys1,n2,d, count1);
}
}} number1.add(n2);
}}
}}
}catch(Exception e){}
}
}
private static List<String> getu_task_incident_service_cis(Map<incident1, Integer>
count) {
List<String> u_task_incident_service_cis = new ArrayList<String>();
for (Map.Entry<incident1, Integer> ent : count.entrySet())
if (!u_task_incident_service_cis.contains(ent.getKey
().getu_task_incident_service_ci()))
u_task_incident_service_cis.add(ent.getKey().getu_task_incident_service_ci
());
System.out.println(u_task_incident_service_cis);
if(!u_task_incident_service_cis.contains("A"))
u_task_incident_service_cis.add("A");
return u_task_incident_service_cis;
}
private static List<String> getu_task_incident_service_cis1(Map<incident200, Integer>
count) {
List<String> u_task_incident_service_cis1 = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!u_task_incident_service_cis1.contains(ent.getKey
().getu_task_incident_service_ci()))
u_task_incident_service_cis1.add(ent.getKey().getu_task_incident_service_ci
());
System.out.println(u_task_incident_service_cis1+"NewCIS");
if(!u_task_incident_service_cis1.contains("BIRSD"))
u_task_incident_service_cis1.add("BIRSD");
return u_task_incident_service_cis1;
}
private static String getNumOfu_task_incident_service_cis(String
u_task_incident_service_ci, List<String> prioritys,
Map<incident1, Integer>
count) {
StringBuilder builder = new StringBuilder();
for (String v : prioritys) {
Integer cnt = count.get(new incident1(u_task_incident_service_ci, v));
if (cnt == null) {
cnt = 0;
}
}
return builder.toString();
}
private static String getCountu_task_incident_service_cis1(String
u_task_incident_service_ci, List<String> prioritys1, String number,String description,
Map<incident200, Integer>
count1) {
StringBuilder builder1 = new StringBuilder();
List<String> ARRAY = new ArrayList<>();
for (String v : prioritys1) {
if ( v == "P1") {
Integer cnt1 = count1.get(new incident200(u_task_incident_service_ci, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
if (!ARRAY.contains(number)) {
mail1 (u_task_incident_service_ci,v,number,description);
ARRAY.add(number);
}
}}
else
if ( v == "P2") {
Integer cnt1 = count1.get(new incident200(u_task_incident_service_ci, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
if (!ARRAY.contains(number)) {
mail1(u_task_incident_service_ci,v,number,description);
ARRAY.add(number);
}}
}}
return number;
}
private static List<String> getprioritys(Map<incident1, Integer> count) {
List<String> prioritys = new ArrayList<String>();
for (Map.Entry<incident1, Integer> ent : count.entrySet())
if (!prioritys.contains(ent.getKey().getpriority()))
prioritys.add(ent.getKey().getpriority());
Collections.sort(prioritys);
return prioritys;
}
private static List<String> getprioritys1(Map<incident200, Integer> count) {
List<String> prioritys1 = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!prioritys1.contains(ent.getKey().getpriority()))
prioritys1.add(ent.getKey().getpriority());
;
//Collections.sort(prioritys);
System.out.println("check1");
return prioritys1;
}
private static List<String> getnumber(Map<incident200, Integer> count) {
List<String> number = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!number.contains(ent.getKey().getnumber()))
number.add(ent.getKey().getnumber());
return number;
}
private static List<String> getdescription(Map<incident200, Integer> count) {
List<String> description = new ArrayList<String>();
for (Map.Entry<incident200, Integer> ent : count.entrySet())
if (!description.contains(ent.getKey().getdescription()))
description.add(ent.getKey().getdescription());
return description;
}
public static void mail1(String Email,String v,String n, String d) {
System.out.println(Email);
System.out.println(v);
final String username = "mailid";
final String password = "password";
//w2011.kpnnl.local
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
//props.put("mail.transport.protocol","smtp");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse
("toaddress"));
message.setSubject("Priority:"+v+": "+n+"Incident has bee raised for the team"+Email);
message.setText("messager,"
);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws IOException {
incidentreport2000 mrt = new incidentreport2000();
Thread t = new Thread(mrt);
t.start();
String Path = "C:\\Users";
List<String> number1 = new ArrayList<String>();
}
}
incident200.java
package com.asn.model;
public class incident200 {
private String u_task_incident_service_ci;
private String priority;
private String number;
private String description;
public incident200(String u_task_incident_service_ci, String priority, String number,String description ) {
super();
if (u_task_incident_service_ci.equals("A"))
{ String Team= "A";
this.u_task_incident_service_ci = Team;}
else
this.u_task_incident_service_ci = u_task_incident_service_ci;
if (priority.equals("1"))
{ String priority1 = "P1";
this.priority = priority1;}
else
if (priority.equals("3"))
{ String priority3 = "P3";
this.priority = priority3;}
else
if (priority.equals("4"))
{ String priority4 = "P3";
this.priority = priority4;}
else
if (priority.equals("5"))
{ String priority5 = "P3";
this.priority = priority5;}
else
if (priority.equals("2"))
{ String priority2 = "P2";
this.priority = priority2;}
else
this.priority = priority;
this.number = number;
this.description = description;
}
public String getu_task_incident_service_ci() {
return u_task_incident_service_ci;
}
public void setu_task_incident_service_ci(String u_task_incident_service_ci) {
this.u_task_incident_service_ci = u_task_incident_service_ci;
}
public String getpriority() {
return priority;
}
public void setpriority(String priority) {
this.priority = priority;
}
public String getnumber() {
return number;
}
public void setnumber(String number) {
this.number = number;
}
public String getdescription() {
return description;
}
public void setdescription(String description) {
this.description = description;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((u_task_incident_service_ci == null) ? 0 : u_task_incident_service_ci.hashCode());
result = prime * result + ((priority == null) ? 0 : priority.hashCode());
result = prime * result + ((number == null) ? 0 : number.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
incident200 other = (incident200) obj;
if (u_task_incident_service_ci == null) {
if (other.u_task_incident_service_ci != null)
return false;
} else if (!u_task_incident_service_ci.equals(other.u_task_incident_service_ci))
return false;
if (priority == null) {
if (other.priority != null)
return false;
} else if (!priority.equals(other.priority))
return false;
if (number == null) {
if (other.number != null)
return false;
} else if (!number.equals(other.number))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("incident99 [u_task_incident_service_ci=");
builder.append(u_task_incident_service_ci);
builder.append(", priority1=");
builder.append(priority);
builder.append(", number=");
builder.append(number);
builder.append(", description=");
builder.append(description);
builder.append("]");
return builder.toString();
}
}
Incident1.java
package com.asn.model;
public class incident1 {
private String u_task_incident_service_ci;
private String priority;
public incident1(String u_task_incident_service_ci, String priority) {
super();
if (u_task_incident_service_ci.equals("A"))
{ String Team= "A";
this.u_task_incident_service_ci = Team;}
else
this.u_task_incident_service_ci = u_task_incident_service_ci;
if (priority.equals("1"))
{ String priority1 = "P1";
this.priority = priority1;}
else
if (priority.equals("3"))
{ String priority3 = "P3";
this.priority = priority3;}
else
this.priority = priority;
}
public String getu_task_incident_service_ci() {
return u_task_incident_service_ci;
}
public void setu_task_incident_service_ci(String u_task_incident_service_ci) {
this.u_task_incident_service_ci = u_task_incident_service_ci;
}
public String getpriority() {
return priority;
}
public void setpriority(String priority) {
this.priority = priority;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((u_task_incident_service_ci == null) ? 0 : u_task_incident_service_ci.hashCode());
result = prime * result + ((priority == null) ? 0 : priority.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
incident1 other = (incident1) obj;
if (u_task_incident_service_ci == null) {
if (other.u_task_incident_service_ci != null)
return false;
} else if (!u_task_incident_service_ci.equals(other.u_task_incident_service_ci))
return false;
if (priority == null) {
if (other.priority != null)
return false;
} else if (!priority.equals(other.priority))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("incident1 [u_task_incident_service_ci=");
builder.append(u_task_incident_service_ci);
builder.append(", priority=");
builder.append(priority);
builder.append("]");
return builder.toString();
}
}

This code is rather ... peculiar. Looking at one method:
private static String
getNumOfu_task_incident_service_cis(String u_task_incident_service_ci,
List<String> prioritys,
Map<incident1, Integer> count) {
StringBuilder builder = new StringBuilder();
for (String v : prioritys) {
Integer cnt = count.get(new incident1(u_task_incident_service_ci, v));
if (cnt == null) {
cnt = 0;
}
}
return builder.toString();
}
Several "count" values are obtained from the Map, but the StringBuilder happily remains unchanged; the method always returns "".
Another method:
private static String
getCountu_task_incident_service_cis1( ..., String number,... ){
//...
if ( v == "P1") {
Integer cnt1 = count1.get(new incident200(u_task_incident_service_ci, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
} else
if (cnt1 != 0){
cnt1 = 1;
//...
return number;
}
Here, cnt1 is set to 0 or 1, but not used later on within the same if statement. And the return value is number, a String parameter. So - what's the point?
public incident200(String u_task_incident_service_ci,
String priority, String number,String description ) {
super();
if (u_task_incident_service_ci.equals("A")){
String Team= "A";
this.u_task_incident_service_ci = Team;}
else
this.u_task_incident_service_ci = u_task_incident_service_ci;
What's the purpose of this complication? A single statement would be sufficient:
this.u_task_incident_service_ci = u_task_incident_service_ci;
I regret that I can only point out why this code may be difficult to understand. Cleaning up the code might be a good start towards finding the bug.
Later
If method getCountu_task_incident_service_cis1 should send emails, it does so for priorities P1 and P2 only:
for (String v : prioritys1) {
if ( v == "P1") {
// ...
} else
if ( v == "P2") {
//...
}
}
Moreover, method run contains
for (String v2 : prioritys1 )
if (v2 =="P1" ){
// some code...
}
}
Do you expect that any other priority is ever sent?

Related

Inspiring from GENERATED TALEND CLASS and Reuse in JAVA

I would like to get the value of from context in a new [java simple class] by inspiring from the seconde generated [talend class] :
I couldn't get filepath value because TALEND CLASS seems a little bit difficult to me ^^
My new java class
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import sapphire.util.DataSet;
public class LHCM_FX {
public static void main(String[] args) {
// Trying to get filepath here from context as TALEND JAVA GENERATED CLASS DO
String filepath = "C:/Users/Administrator/Desktop/Test/";
System.out.println("xmldataset=" + parseFXFile(filepath+"0.txt").toXML());
}
public static DataSet parseFXFile(String filepath) {
// Something Codes Here
}
TALEND GENERATED CLASS where filepath is declared
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import routines.LHCM_FX_ROUTINE;
import routines.TalendString;
import routines.system.IPersistableRow;
import routines.system.ResumeUtil;
import routines.system.TDieException;
import sapphire.util.DataSet;
public class LHCM_FX {
public final Object obj = new Object();
private Object valueObject = null;
private static final String defaultCharset = Charset.defaultCharset().name();
private static final String utf8Charset = "UTF-8";
private Properties defaultProps = new Properties();
private LHCM_FX.ContextProperties context = new LHCM_FX.ContextProperties();
private final String jobVersion = "0.1";
private final String jobName = "LHCM_FX";
private final String projectName = "CETEMCO";
public Integer errorCode = null;
private String currentComponent = "";
private final Map<String, Long> start_Hash = new HashMap();
private final Map<String, Long> end_Hash = new HashMap();
private final Map<String, Boolean> ok_Hash = new HashMap();
private final Map<String, Object> globalMap = new HashMap();
public final List<String[]> globalBuffer = new ArrayList();
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
private final PrintStream errorMessagePS;
private Exception exception;
public String resuming_logs_dir_path;
public String resuming_checkpoint_path;
public String parent_part_launcher;
private String resumeEntryMethodName;
private boolean globalResumeTicket;
public boolean watch;
public Integer portStats;
public int portTraces;
public String clientHost;
public String defaultClientHost;
public String contextStr;
public String pid;
public String rootPid;
public String fatherPid;
public String fatherNode;
public long startTime;
public boolean isChildJob;
private boolean execStat;
private ThreadLocal threadLocal;
private Properties context_param;
public Map<String, Object> parentContextMap;
public String status;
ResumeUtil resumeUtil;
public LHCM_FX() {
this.errorMessagePS = new PrintStream(new BufferedOutputStream(this.baos));
this.exception = null;
this.resuming_logs_dir_path = null;
this.resuming_checkpoint_path = null;
this.parent_part_launcher = null;
this.resumeEntryMethodName = null;
this.globalResumeTicket = false;
this.watch = false;
this.portStats = null;
this.portTraces = 4334;
this.defaultClientHost = "localhost";
this.contextStr = "Default";
this.pid = "0";
this.rootPid = null;
this.fatherPid = null;
this.fatherNode = null;
this.startTime = 0L;
this.isChildJob = false;
this.execStat = true;
this.threadLocal = new ThreadLocal();
Map threadRunResultMap = new HashMap();
threadRunResultMap.put("errorCode", (Object)null);
threadRunResultMap.put("status", "");
this.threadLocal.set(threadRunResultMap);
this.context_param = new Properties();
this.parentContextMap = new HashMap();
this.status = "";
this.resumeUtil = null;
}
public Object getValueObject() {
return this.valueObject;
}
public void setValueObject(Object valueObject) {
this.valueObject = valueObject;
}
public LHCM_FX.ContextProperties getContext() {
return this.context;
}
public String getExceptionStackTrace() {
if ("failure".equals(this.getStatus())) {
this.errorMessagePS.flush();
return this.baos.toString();
} else {
return null;
}
}
public Exception getException() {
return "failure".equals(this.getStatus()) ? this.exception : null;
}
public void tJavaFlex_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tJavaFlex_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tLogRow_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tLogRow_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tLabVantageLIMSCIPostData_1_error(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.end_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
this.tJavaFlex_1_onSubJobError(exception, errorComponent, globalMap);
}
public void tJavaFlex_1_onSubJobError(Exception exception, String errorComponent, Map<String, Object> globalMap) throws LHCM_FX.TalendException {
this.resumeUtil.addLog("SYSTEM_LOG", "NODE:" + errorComponent, "", String.valueOf(Thread.currentThread().getId()), "FATAL", "", exception.getMessage(), ResumeUtil.getExceptionStackTrace(exception), "");
}
public void tJavaFlex_1Process(Map<String, Object> globalMap) throws LHCM_FX.TalendException {
globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", 0);
boolean execStat = this.execStat;
String iterateId = "";
String currentComponent = "";
try {
String currentMethodName = (new Exception()).getStackTrace()[0].getMethodName();
boolean resumeIt = currentMethodName.equals(this.resumeEntryMethodName);
if (this.resumeEntryMethodName == null || resumeIt || this.globalResumeTicket) {
this.globalResumeTicket = true;
LHCM_FX.row1Struct row1 = new LHCM_FX.row1Struct();
this.ok_Hash.put("tLabVantageLIMSCIPostData_1", false);
this.start_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
currentComponent = "tLabVantageLIMSCIPostData_1";
int tos_count_tLabVantageLIMSCIPostData_1 = 0;
DataSet dsData_tLabVantageLIMSCIPostData_1 = new DataSet();
dsData_tLabVantageLIMSCIPostData_1.addColumn("sdcid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("keyid1", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("paramlistid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("variantid", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("paramtype", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("instrumentfield", 0);
dsData_tLabVantageLIMSCIPostData_1.addColumn("value", 0);
this.ok_Hash.put("tLogRow_1", false);
this.start_Hash.put("tLogRow_1", System.currentTimeMillis());
currentComponent = "tLogRow_1";
int tos_count_tLogRow_1 = 0;
this.ok_Hash.put("tJavaFlex_1", false);
this.start_Hash.put("tJavaFlex_1", System.currentTimeMillis());
currentComponent = "tJavaFlex_1";
int tos_count_tJavaFlex_1 = 0;
DataSet ds = LHCM_FX_ROUTINE.parseFXFile(this.context.filepath);
int i_tLabVantageLIMSCIPostData_1;
String keyid1;
String instrumentfield;
for(int i = 0; i < ds.getRowCount(); ++i) {
currentComponent = "tJavaFlex_1";
row1.sdcid = ds.getValue(i, "sdcid", "");
row1.keyid1 = ds.getValue(i, "keyid1", "");
row1.paramlistid = ds.getValue(i, "paramlistid", "");
row1.variantid = ds.getValue(i, "variantid", "");
row1.paramtype = ds.getValue(i, "paramtype", "");
row1.instrumentfield = ds.getValue(i, "instrumentfield", "");
row1.value = ds.getValue(i, "value", "");
++tos_count_tJavaFlex_1;
currentComponent = "tLogRow_1";
++tos_count_tLogRow_1;
currentComponent = "tLabVantageLIMSCIPostData_1";
i_tLabVantageLIMSCIPostData_1 = dsData_tLabVantageLIMSCIPostData_1.addRow();
keyid1 = "";
instrumentfield = "";
keyid1 = "sdcid";
instrumentfield = row1.sdcid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "keyid1";
instrumentfield = row1.keyid1;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "paramlistid";
instrumentfield = row1.paramlistid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "variantid";
instrumentfield = row1.variantid;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "paramtype";
instrumentfield = row1.paramtype;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "instrumentfield";
instrumentfield = row1.instrumentfield;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
keyid1 = "value";
instrumentfield = row1.value;
instrumentfield = instrumentfield == null ? "" : instrumentfield;
dsData_tLabVantageLIMSCIPostData_1.setValue(i_tLabVantageLIMSCIPostData_1, keyid1, instrumentfield);
++tos_count_tLabVantageLIMSCIPostData_1;
currentComponent = "tJavaFlex_1";
}
this.ok_Hash.put("tJavaFlex_1", true);
this.end_Hash.put("tJavaFlex_1", System.currentTimeMillis());
currentComponent = "tLogRow_1";
this.ok_Hash.put("tLogRow_1", true);
this.end_Hash.put("tLogRow_1", System.currentTimeMillis());
currentComponent = "tLabVantageLIMSCIPostData_1";
String sWarningMessages_tLabVantageLIMSCIPostData_1 = "";
if ("LIMS CI".equals("LIMS CI") && (!dsData_tLabVantageLIMSCIPostData_1.isValidColumn("sdcid") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("keyid1") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("instrumentfield") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("value"))) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + "Error : In 'LIMS CI' case, the columns sdcid, keyid1, instrumentfield and value are mandatory. Please change the component schema.";
}
if ("LIMS CI".equals("Protocol Provider") && (!dsData_tLabVantageLIMSCIPostData_1.isValidColumn("instrumentfield") || !dsData_tLabVantageLIMSCIPostData_1.isValidColumn("value"))) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + "Error : In 'Protocol Provider' case, the columns instrumentfield and value are mandatory. Please change the component schema.";
}
if (sWarningMessages_tLabVantageLIMSCIPostData_1.equals("")) {
for(i_tLabVantageLIMSCIPostData_1 = 0; i_tLabVantageLIMSCIPostData_1 < dsData_tLabVantageLIMSCIPostData_1.getRowCount(); ++i_tLabVantageLIMSCIPostData_1) {
keyid1 = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, "keyid1", "null");
instrumentfield = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, "instrumentfield", "null");
if ((!"LIMS CI".equals("LIMS CI") || !keyid1.equals("null")) && !instrumentfield.equals("null")) {
for(int j_tLabVantageLIMSCIPostData_1 = 0; j_tLabVantageLIMSCIPostData_1 < dsData_tLabVantageLIMSCIPostData_1.getColumnCount(); ++j_tLabVantageLIMSCIPostData_1) {
String columnid = dsData_tLabVantageLIMSCIPostData_1.getColumnId(j_tLabVantageLIMSCIPostData_1);
String value = dsData_tLabVantageLIMSCIPostData_1.getValue(i_tLabVantageLIMSCIPostData_1, columnid, "nullvalue");
String message = "";
if ("LIMS CI".equals("LIMS CI") && (columnid.equals("sdcid") || columnid.equals("keyid1") || columnid.equals("instrumentfield")) && (value == null || value.equals("") || value.equals("nullvalue"))) {
message = "Error : Invalid value : The column '" + columnid + "' can not be empty or null.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
}
if ("LIMS CI".equals("Protocol Provider")) {
if (!columnid.equals("instrumentfield") && !columnid.equals("value")) {
message = "Error : Invalid column '" + columnid + "'. In 'Protocol Provider' case, only 'instrumentfield' and 'value' columns are accepted.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
} else if (columnid.equals("instrumentfield") && (value == null || value.equals("") || value.equals("nullvalue"))) {
message = "Error : Invalid value : The column '" + columnid + "' can not be empty or null.\n";
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.contains(message)) {
sWarningMessages_tLabVantageLIMSCIPostData_1 = sWarningMessages_tLabVantageLIMSCIPostData_1 + message;
}
}
}
}
} else {
dsData_tLabVantageLIMSCIPostData_1.deleteRow(i_tLabVantageLIMSCIPostData_1);
--i_tLabVantageLIMSCIPostData_1;
}
}
}
if (!sWarningMessages_tLabVantageLIMSCIPostData_1.equals("")) {
System.out.println("Invalid data ! You must solve the following problems : ");
System.out.println(sWarningMessages_tLabVantageLIMSCIPostData_1);
}
System.out.println("xmldataset=" + dsData_tLabVantageLIMSCIPostData_1.toXML());
globalMap.put("tLabVantageLIMSCIPostData_1_NB_LINE", dsData_tLabVantageLIMSCIPostData_1.getRowCount());
this.ok_Hash.put("tLabVantageLIMSCIPostData_1", true);
this.end_Hash.put("tLabVantageLIMSCIPostData_1", System.currentTimeMillis());
}
} catch (Exception var22) {
throw new LHCM_FX.TalendException(var22, currentComponent, globalMap, (LHCM_FX.TalendException)null);
} catch (Error var23) {
throw new Error(var23);
}
globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", 1);
}
public static void main(String[] args) {
LHCM_FX LHCM_FXClass = new LHCM_FX();
int exitCode = LHCM_FXClass.runJobInTOS(args);
System.exit(exitCode);
}
public String[][] runJob(String[] args) {
int exitCode = this.runJobInTOS(args);
String[][] bufferValue = new String[][]{{Integer.toString(exitCode)}};
return bufferValue;
}
public int runJobInTOS(String[] args) {
String lastStr = "";
boolean hasContextArg = false;
String[] var7 = args;
int var6 = args.length;
for(int var5 = 0; var5 < var6; ++var5) {
String arg = var7[var5];
if (arg.toLowerCase().contains("--context=")) {
hasContextArg = true;
} else if (arg.equalsIgnoreCase("--context_param")) {
lastStr = arg;
} else if (lastStr.equals("")) {
this.evalParam(arg);
} else {
this.evalParam(lastStr + " " + arg);
lastStr = "";
}
}
if (this.clientHost == null) {
this.clientHost = this.defaultClientHost;
}
if (this.pid == null || "0".equals(this.pid)) {
this.pid = TalendString.getAsciiRandomString(6);
}
if (this.rootPid == null) {
this.rootPid = this.pid;
}
if (this.fatherPid == null) {
this.fatherPid = this.pid;
} else {
this.isChildJob = true;
}
try {
InputStream inContext = LHCM_FX.class.getClassLoader().getResourceAsStream("cetemco/lhcm_fx_0_1/contexts/" + this.contextStr + ".properties");
if (inContext != null) {
this.defaultProps.load(inContext);
inContext.close();
this.context = new LHCM_FX.ContextProperties(this.defaultProps);
} else if (hasContextArg) {
System.err.println("Could not find the context " + this.contextStr);
}
if (!this.context_param.isEmpty()) {
this.context.putAll(this.context_param);
}
this.context.filepath = this.context.getProperty("filepath");
} catch (IOException var12) {
System.err.println("Could not load context " + this.contextStr);
var12.printStackTrace();
}
if (this.parentContextMap != null && !this.parentContextMap.isEmpty() && this.parentContextMap.containsKey("filepath")) {
this.context.filepath = (String)this.parentContextMap.get("filepath");
}
this.resumeEntryMethodName = ResumeUtil.getResumeEntryMethodName(this.resuming_checkpoint_path);
this.resumeUtil = new ResumeUtil(this.resuming_logs_dir_path, this.isChildJob, this.rootPid);
this.resumeUtil.initCommonInfo(this.pid, this.rootPid, this.fatherPid, "CETEMCO", "LHCM_FX", this.contextStr, "0.1");
this.resumeUtil.addLog("JOB_STARTED", "JOB:LHCM_FX", this.parent_part_launcher, String.valueOf(Thread.currentThread().getId()), "", "", "", "", ResumeUtil.convertToJsonText(this.context));
long startUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long endUsedMemory = 0L;
long end = 0L;
this.startTime = System.currentTimeMillis();
this.globalResumeTicket = true;
this.globalResumeTicket = false;
try {
this.errorCode = null;
this.tJavaFlex_1Process(this.globalMap);
this.status = "end";
} catch (LHCM_FX.TalendException var11) {
this.status = "failure";
var11.printStackTrace();
this.globalMap.put("tJavaFlex_1_SUBPROCESS_STATE", -1);
}
this.globalResumeTicket = true;
end = System.currentTimeMillis();
if (this.watch) {
System.out.println(end - this.startTime + " milliseconds");
}
endUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
int returnCode = false;
int returnCode;
if (this.errorCode == null) {
returnCode = this.status != null && this.status.equals("failure") ? 1 : 0;
} else {
returnCode = this.errorCode;
}
this.resumeUtil.addLog("JOB_ENDED", "JOB:LHCM_FX", this.parent_part_launcher, String.valueOf(Thread.currentThread().getId()), "", "" + returnCode, "", "", "");
return returnCode;
}
private void evalParam(String arg) {
if (arg.startsWith("--resuming_logs_dir_path")) {
this.resuming_logs_dir_path = arg.substring(25);
} else if (arg.startsWith("--resuming_checkpoint_path")) {
this.resuming_checkpoint_path = arg.substring(27);
} else if (arg.startsWith("--parent_part_launcher")) {
this.parent_part_launcher = arg.substring(23);
} else if (arg.startsWith("--watch")) {
this.watch = true;
} else {
String keyValue;
if (arg.startsWith("--stat_port=")) {
keyValue = arg.substring(12);
if (keyValue != null && !keyValue.equals("null")) {
this.portStats = Integer.parseInt(keyValue);
}
} else if (arg.startsWith("--trace_port=")) {
this.portTraces = Integer.parseInt(arg.substring(13));
} else if (arg.startsWith("--client_host=")) {
this.clientHost = arg.substring(14);
} else if (arg.startsWith("--context=")) {
this.contextStr = arg.substring(10);
} else if (arg.startsWith("--father_pid=")) {
this.fatherPid = arg.substring(13);
} else if (arg.startsWith("--root_pid=")) {
this.rootPid = arg.substring(11);
} else if (arg.startsWith("--father_node=")) {
this.fatherNode = arg.substring(14);
} else if (arg.startsWith("--pid=")) {
this.pid = arg.substring(6);
} else if (arg.startsWith("--context_param")) {
keyValue = arg.substring(16);
int index = true;
int index;
if (keyValue != null && (index = keyValue.indexOf(61)) > -1) {
this.context_param.put(keyValue.substring(0, index), keyValue.substring(index + 1));
}
}
}
}
public Integer getErrorCode() {
return this.errorCode;
}
public String getStatus() {
return this.status;
}
public class ContextProperties extends Properties {
public String filepath;
public ContextProperties(Properties properties) {
super(properties);
}
public ContextProperties() {
}
public void synchronizeContext() {
if (this.filepath != null) {
this.setProperty("filepath", this.filepath.toString());
}
}
public String getFilepath() {
return this.filepath;
}
}
private class TalendException extends Exception {
private Map<String, Object> globalMap;
private Exception e;
private String currentComponent;
private TalendException(Exception e, String errorComponent, Map<String, Object> globalMap) {
this.globalMap = null;
this.e = null;
this.currentComponent = null;
this.currentComponent = errorComponent;
this.globalMap = globalMap;
this.e = e;
}
public void printStackTrace() {
if (!(this.e instanceof LHCM_FX.TalendException) && !(this.e instanceof TDieException)) {
this.globalMap.put(this.currentComponent + "_ERROR_MESSAGE", this.e.getMessage());
System.err.println("Exception in component " + this.currentComponent);
}
if (!(this.e instanceof TDieException)) {
if (this.e instanceof LHCM_FX.TalendException) {
this.e.printStackTrace();
} else {
this.e.printStackTrace();
this.e.printStackTrace(LHCM_FX.this.errorMessagePS);
LHCM_FX.this.exception = this.e;
}
}
if (!(this.e instanceof LHCM_FX.TalendException)) {
try {
Method[] var4;
int var3 = (var4 = this.getClass().getEnclosingClass().getMethods()).length;
for(int var2 = 0; var2 < var3; ++var2) {
Method m = var4[var2];
if (m.getName().compareTo(this.currentComponent + "_error") == 0) {
m.invoke(LHCM_FX.this, this.e, this.currentComponent, this.globalMap);
break;
}
}
boolean var10000 = this.e instanceof TDieException;
} catch (SecurityException var5) {
this.e.printStackTrace();
} catch (IllegalArgumentException var6) {
this.e.printStackTrace();
} catch (IllegalAccessException var7) {
this.e.printStackTrace();
} catch (InvocationTargetException var8) {
this.e.printStackTrace();
}
}
}
// ............. More More code
}
}
Thank you in advance,
My bad!
I have the parameter filepath inside args of my : MAIN (String[] args)
so filepath = args[4]
Im sorry and thanks anyway :)

Get metadata from shoutcast stream

I'm developing a radio app with multiple radios, the stream is playing fine. But I'm struggling to show artist and music playing at the moment.
This is the class I'm using to get metadata from shoutcast stream:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IcyStreamMeta<Message> {
protected URL streamUrl;
private Map<String, String> metadata;
private boolean isError;
public IcyStreamMeta(URL streamUrl) {
setStreamUrl(streamUrl);
isError = false;
}
/**
* Get artist using stream's title
*
* #return String
* #throws IOException
*/
public String getArtist() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String title = streamTitle.substring(0, streamTitle.indexOf("-"));
return title.trim();
}
/**
* Get title using stream's title
*
* #return String
* #throws IOException
*/
public String getTitle() throws IOException {
Map<String, String> data = getMetadata();
if (!data.containsKey("StreamTitle"))
return "";
String streamTitle = data.get("StreamTitle");
String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
return artist.trim();
}
public Map<String, String> getMetadata() throws IOException {
if (metadata == null) {
refreshMeta();
}
return metadata;
}
public void refreshMeta() throws IOException {
retreiveMetadata();
}
private void retreiveMetadata() throws IOException {
URLConnection con = streamUrl.openConnection();
con.setRequestProperty("Icy-MetaData", "1");
con.setRequestProperty("Connection", "close");
con.setRequestProperty("Accept", null);
con.connect();
int metaDataOffset = 0;
Map<String, List<String>> headers = con.getHeaderFields();
InputStream stream = con.getInputStream();
if (headers.containsKey("icy-metaint")) {
// Headers are sent via HTTP
metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
} else {
// Headers are sent within a stream
StringBuilder strHeaders = new StringBuilder();
char c;
while ((c = (char)stream.read()) != -1) {
strHeaders.append(c);
if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
// end of headers
break;
}
}
// Match headers to get metadata offset within a stream
Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
Matcher m = p.matcher(strHeaders.toString());
if (m.find()) {
metaDataOffset = Integer.parseInt(m.group(2));
}
}
// In case no data was sent
if (metaDataOffset == 0) {
isError = true;
return;
}
// Read metadata
int b;
int count = 0;
int metaDataLength = 4080; // 4080 is the max length
boolean inData = false;
StringBuilder metaData = new StringBuilder();
// Stream position should be either at the beginning or right after headers
while ((b = stream.read()) != -1) {
count++;
// Length of the metadata
if (count == metaDataOffset + 1) {
metaDataLength = b * 16;
}
if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
inData = true;
} else {
inData = false;
}
if (inData) {
if (b != 0) {
metaData.append((char)b);
}
}
if (count > (metaDataOffset + metaDataLength)) {
break;
}
}
// Set the data
metadata = IcyStreamMeta.parseMetadata(metaData.toString());
// Close
stream.close();
}
public boolean isError() {
return isError;
}
public URL getStreamUrl() {
return streamUrl;
}
public void setStreamUrl(URL streamUrl) {
this.metadata = null;
this.streamUrl = streamUrl;
this.isError = false;
}
public static Map<String, String> parseMetadata(String metaString) {
Map<String, String> metadata = new HashMap();
String[] metaParts = metaString.split(";");
Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
Matcher m;
for (int i = 0; i < metaParts.length; i++) {
m = p.matcher(metaParts[i]);
if (m.find()) {
metadata.put(m.group(1), m.group(2));
}
}
return metadata;
}
}
And the method on MainActivity to get the metadata every 10 seconds
private void getMeta()
{
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
try {
IcyStreamMeta icy = new IcyStreamMeta(new URL(RadiophonyService.getRadioURL()));
final String data = icy.getArtist() + " - " + icy.getTitle();
final TextView meta = (TextView) findViewById(R.id.now_playing);
runOnUiThread(new Runnable() {
public void run() {
meta.setText(data);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 10000);
}
Initially, when I select one station, it plays but does not show metadata and when I select another station the app crashes with this runtime error:
E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: com.example.app, PID: 23597
java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=-1
at java.lang.String.startEndAndLength(String.java:504)
at java.lang.String.substring(String.java:1333)
at com.example.app.utilities.IcyStreamMeta.getArtist(IcyStreamMeta.java:41)
at com.example.app.activities.MainActivity$8.run(MainActivity.java:306)
at java.util.Timer$TimerImpl.run(Timer.java:284)
I'm stuck at this for days, and I tried other solutions but nothing works!
Looks like this line
String title = streamTitle.substring(0, streamTitle.indexOf("-"));
is the culprit.
If streamTitle does not have a dash in its title, indexOf() will return a -1, and substring() is choking because you can't have an end index less than the start index.
Maybe you need something like this:
int pos = streamTitle.indexOf("-");
String title = (pos == -1) ? streamTitle : streamTitle.substring(0, pos);

Found some code for serialization of an ItemStack in Bukkit, how to deserialize it?

I've dug up the following code for serializing an ItemStack in bukkit (Minecraft). I've been able to serialize an item in hand with the following:
itemString = ItemStackUtils.deserialize(player.getInventory().getItemInHand());
I can't figure out how to utilize the deserial call however. What I am trying to do is to pull an item from the players hand, serialize it, stick it into a config file, then when the player runs another command... deserialize it and slap it into their inventory. I am fairly certain this class will meet my needs if I just can get the last part working.
public final class ItemStackUtils {
public static String getEnchants(ItemStack i){
List<String> e = new ArrayList<String>();
Map<Enchantment, Integer> en = i.getEnchantments();
for(Enchantment t : en.keySet()) {
e.add(t.getName() + ":" + en.get(t));
}
return StringUtils.join(e, ",");
}
public static String deserialize(ItemStack i){
String[] parts = new String[6];
parts[0] = i.getType().name();
parts[1] = Integer.toString(i.getAmount());
parts[2] = String.valueOf(i.getDurability());
parts[3] = i.getItemMeta().getDisplayName();
parts[4] = String.valueOf(i.getData().getData());
parts[5] = getEnchants(i);
return StringUtils.join(parts, ";");
}
public ItemStack deserial(String p){
String[] a = p.split(";");
ItemStack i = new ItemStack(Material.getMaterial(a[0]), Integer.parseInt(a[1]));
i.setDurability((short) Integer.parseInt(a[2]));
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(a[3]);
i.setItemMeta(meta);
MaterialData data = i.getData();
data.setData((byte) Integer.parseInt(a[4]));
i.setData(data);
if (a.length > 5) {
String[] parts = a[5].split(",");
for (String s : parts) {
String label = s.split(":")[0];
String amplifier = s.split(":")[1];
Enchantment type = Enchantment.getByName(label);
if (type == null)
continue;
int f;
try {
f = Integer.parseInt(amplifier);
} catch(Exception ex) {
continue;
}
i.addEnchantment(type, f);
}
}
return i;
}
}
here it saves & loads the whole NBT
package XXXXXXXXX
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_8_R3.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.material.MaterialData;
import net.minecraft.server.v1_8_R3.MojangsonParseException;
import net.minecraft.server.v1_8_R3.MojangsonParser;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
public class ItemSerialize {
public ItemSerialize() {
}
public static String serialize(ItemStack i) {
String[] parts = new String[7];
parts[0] = i.getType().name();
parts[1] = Integer.toString(i.getAmount());
parts[2] = String.valueOf(i.getDurability());
parts[3] = i.getItemMeta().getDisplayName();
parts[4] = String.valueOf(i.getData().getData());
parts[5] = getEnchants(i);
parts[6] = getNBT(i);
return StringUtils.join(parts, ";");
}
public static String getEnchants(ItemStack i) {
List<String> e = new ArrayList<String>();
Map<Enchantment, Integer> en = i.getEnchantments();
for (Enchantment t : en.keySet()) {
e.add(t.getName() + ":" + en.get(t));
}
return StringUtils.join(e, ",");
}
public static String getLore(ItemStack i) {
List<String> e = i.getItemMeta().getLore();
return StringUtils.join(e, ",");
}
public static String getNBT(ItemStack i) {
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(i);
NBTTagCompound compound = nmsStack.hasTag() ? nmsStack.getTag() : new NBTTagCompound();
return compound.toString();
}
public static ItemStack setNBT(ItemStack i, String NBT) {
net.minecraft.server.v1_8_R3.ItemStack nmsStack = CraftItemStack.asNMSCopy(i);
try {
NBTTagCompound compound = MojangsonParser.parse(NBT);
nmsStack.setTag(compound);
} catch (MojangsonParseException e1) {
e1.printStackTrace();
}
return CraftItemStack.asBukkitCopy(nmsStack);
}
#SuppressWarnings("deprecation")
public static ItemStack deserial(String p) {
String[] a = p.split(";");
ItemStack i = new ItemStack(Material.getMaterial(a[0]), Integer.parseInt(a[1]));
i.setDurability((short) Integer.parseInt(a[2]));
ItemMeta meta = i.getItemMeta();
meta.setDisplayName(a[3]);
i.setItemMeta(meta);
MaterialData data = i.getData();
data.setData((byte) Integer.parseInt(a[4]));
i.setData(data);
if (!a[6].isEmpty()) {
i = setNBT(i, a[6]);
}
if (!a[5].isEmpty()) {
String[] parts = a[5].split(",");
for (String s : parts) {
String label = s.split(":")[0];
String amplifier = s.split(":")[1];
Enchantment type = Enchantment.getByName(label);
if (type == null)
continue;
int f;
try {
f = Integer.parseInt(amplifier);
} catch (Exception ex) {
continue;
}
i.addUnsafeEnchantment(type, f);
}
}
return i;
}
}
ItemStack rItem = ItemStackUtils.deserial(itemString);

counting the values in xml

I am Having an XML file
<?xml version="1.0"?>
<ticket>
<team>A</team>
<imp>I1</imp>
</ticket>
<ticket>
<team>A</team>
<imp>I2</imp>
</ticket>
<ticket>
<team>b</team>
<imp>I2</imp>
</ticket>
<ticket>
<team>A</team>
<imp>I1</imp>
</ticket>
<ticket>
<team>B</team>
<imp>I2</imp>
</ticket>
<ticket>
<team>c</team>
<imp>I1</imp>
</ticket>
out put to like :-
Team I1 I2 I3
A 2 1 0
B 1 1 0
C 1 0 0
Here currently I3 is not there in XML. is it Possible to take I1,I2 and I3 into Hash and check if I1 is there then to get count accorind to team and display like above.
ticket.java
package com.asn.ticket;
public class ticket {
private String team;
private String imp;
public ticket(String team, String imp) {
super();
this.team = team;
this.imp = imp;
}
public String getteam() {
return team;
}
public void setteam(String team) {
this.team = team;
}
public String getimp() {
return imp;
}
public void setimp(String imp) {
this.imp = imp;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((team == null) ? 0 : team.hashCode());
result = prime * result + ((imp == null) ? 0 : imp.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ticket other = (ticket) obj;
if (team == null) {
if (other.team != null)
return false;
} else if (!team.equals(other.team))
return false;
if (imp == null) {
if (other.imp != null)
return false;
} else if (!imp.equals(other.imp))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ticket [team=");
builder.append(team);
builder.append(", imp=");
builder.append(imp);
builder.append("]");
return builder.toString();
}
}
ticketcounts.java
package com.asn.team;
import com.asn.team.ticket;
public class ticketsCount {
public static void main(String[] args) {
List<ticket> ticketList = new ArrayList<ticket>();
try {
String Path = "C:\\Users";
File fXmlFile = new File(Path+"\\tickets.xml");
// File fXmlFile = new File(App.class.getClassLoader().getResource("C:\\Users\// \\tickets.xml").getFile());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList ticketNodeList = doc.getElementsByTagName("ticket");
for (int temp = 0; temp < ticketNodeList.getLength(); temp++) {
Node varNode = ticketNodeList.item(temp);
if (varNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) varNode;
NodeList teamList = eElement.getElementsByTagName("team");
NodeList varsionList = eElement.getElementsByTagName("imp");
Node teamNode = teamList.item(0);
Node impNode = varsionList.item(0);
if(teamNode.getNodeType() == Node.ELEMENT_NODE && impNode.getNodeType() == Node.ELEMENT_NODE){
Element teamElement = (Element)teamNode;
Element impElement = (Element)impNode;
ticket ticket = new ticket(teamElement.getTextContent(), impElement.getTextContent());
ticketList.add(ticket);
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
Map<ticket,Integer> count = new HashMap<ticket, Integer>();
for(ticket c: ticketList)
if(!count.containsKey(c))
count.put(c, Collections.frequency(ticketList, c));
List<String> imps = getimps(count);
List<String> teams = getteams(count);
StringBuilder heading = new StringBuilder("ticket \t| ");
for(String s : imps){
heading.append(s);
heading.append("\t| ");
}
System.out.println(heading);
System.out.println("---------------------------------");
for(String m : teams){
System.out.println(m+"\t| "+getNumOfteams(m, imps, count));
}
}
/**
* #param count
* #return
*/
private static List<String> getteams(Map<ticket, Integer> count) {
List<String> teams = new ArrayList<String>();
for(Map.Entry<ticket, Integer> ent : count.entrySet())
if(!teams.contains(ent.getKey().getteam()))
teams.add(ent.getKey().getteam());
return teams;
}
private static String getNumOfteams(String team, List<String> imps, Map<ticket, Integer> count) {
StringBuilder builder = new StringBuilder();
for(String v : imps){
for(Map.Entry<ticket, Integer> ent : count.entrySet())
if(team.equals(ent.getKey().getteam()) && ent.getKey().getimp().equals(v)){
int cnt = ent.getValue();
builder.append((cnt==0)?" ": cnt);
builder.append("\t| ");
}
}
return builder.toString();
}
private static List<String> getimps(Map<ticket, Integer> count) {
List<String> imps = new ArrayList<String>();
for(Map.Entry<ticket, Integer> ent : count.entrySet())
if(!imps.contains(ent.getKey().getimp()))
imps.add(ent.getKey().getimp());
return imps;
}
}
I haven't executed your code, but if I understand correctly, it works fine except you don't have any column for I3, because no ticket in the XML file has I3 as its imp. So you simply need to do as if there was I3 in the file:
private static List<String> getimps(Map<ticket, Integer> count) {
List<String> imps = new ArrayList<String>();
for(Map.Entry<ticket, Integer> ent : count.entrySet())
if (!imps.contains(ent.getKey().getimp())) {
imps.add(ent.getKey().getimp());
}
}
// make sure I3 is listed as imp as well:
if (!imps.contains("I3")) {
imps.add("I3");
}
return imps;
}
And in the getNumOfTeams() method, you shouldn't assume that at least one ticket has the current imp. So I would rewrite it as:
private static String getNumOfteams(String team, List<String> imps, Map<ticket, Integer> count) {
StringBuilder builder = new StringBuilder();
for (String v : imps){
Integer cnt = count.get(new ticket(team, v));
if (cnt == null) {
cnt = 0;
}
builder.append(cnt + "\t");
}
return builder.toString();
}
Side note: you should really learn and apply naming conventions. Don't abuse abbreviations. Name your getters and setters getTeam() and setTeam() rather than getteam() and setteam(), classes start with an uppercase letter.

Read text line and put in to the JTable

hey
i have text file shown as below.
11/2/2010 cat 6
11/2/2010 cat 3
11/2/2010 dog 4
11/2/2010 cat 11
11/3/2010 cat 1
11/3/2010 dog 3
11/3/2010 cat 8
i have in every month this kind of text file. Above figure shows the part of the text file. so then i want to read this text using java to Jtable.
i Have used StringTokanizer And Arreaylist to ceate this. Unfotunately i couldn't done it. SO PLS HELP ME........
So i want below result to jTable using java program.
date animal total count
11/2/2010 cat 20 3
11/3/2010 cat 9 2
You don't need a StringTokenizer (in fact, it's not recommended). Just get the input line by line using BufferedReader, and do a String split:
List<Array> data = new ArrayList<Array>();
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String line;
// Read input and put into ArrayList of Arrays
while ((line = in.readLine) != null) {
data.add(line.split("\\s+"));
}
// Now create JTable with Array of Arrays
JTable table = new JTable(data.toArray(), new String[] {
"date", "animal", "total", "count"});
test with : http://crysol.org/es/node/819
or
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
public class Reader {
public Reader() {
// TODO Auto-generated constructor stub
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("sample.txt")));
Map<String, Object[]> result = new LinkedHashMap<String, Object[]>();
while (reader.ready()) {
String line = reader.readLine();
String[] values = line.split("\\s+");
String key = values[0] + "\t" + values[1];
String label = values[0];
String date = values[1];
Integer sum = 0;
Integer count = 0;
if (result.containsKey(key)) {
sum = (Integer) ((Object[]) result.get(key))[2];
count = (Integer) ((Object[]) result.get(key))[3];
} else {
}
result.put(key, new Object[]{label, date,
sum + Integer.parseInt(values[2]), count + 1});
}
ArrayList arrayList = new ArrayList(result.values());
/* interate and print new output */
/*
* for (String key : result.keySet()) { Integer sum =
* result.get(key); Integer count = result2.get(key);
* System.out.println(key + " " + sum + "\t" + count); }
*/
JTable table = new JTable(new AnimalTableModel(arrayList));
panel.add(new JScrollPane(table));
reader.close();
frame.setContentPane(panel);
frame.setVisible(true);
frame.pack();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Reader();
}
public class AnimalTableModel implements TableModel {
final Class[] columnClass = new Class[]{String.class, String.class,
Integer.class, Integer.class};
final String[] columnName = new String[]{"Date", "Animal", "Sum",
"Count"};
List values = null;
public AnimalTableModel(List values) {
this.values = values;
// initilize values
}
#Override
public void addTableModelListener(TableModelListener l) {
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return columnClass[columnIndex];
}
#Override
public int getColumnCount() {
return columnClass.length;
}
#Override
public String getColumnName(int columnIndex) {
return columnName[columnIndex];
}
#Override
public int getRowCount() {
return values.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return ((Object[]) values.get(rowIndex))[columnIndex];
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
#Override
public void removeTableModelListener(TableModelListener l) {
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// TODO FOR EDITABLE DT
}
}
}
You will have to populate the data to a map from the given file.I will give you an example as to how to populate the data.
public class AnimalMapping {
public static void main(String[] args) {
Object[][] data = { { "11/2/2010", "cat", 6 },
{ "11/2/2010", "cat", 3 }, { "11/2/2010", "dog", 4 },
{ "11/2/2010", "cat", 11 }, { "11/3/2010", "cat", 1 },
{ "11/3/2010", "dog", 3 }, { "11/3/2010", "cat", 8 } };
HashMap<String, Map<String, AnimalValCnt>> animalMap = new HashMap<String, Map<String, AnimalValCnt>>();
for (Object[] record : data) {
Map<String, AnimalValCnt> innerMap = null;
if ((innerMap = animalMap.get(record[0])) == null) {
innerMap = new HashMap<String, AnimalValCnt>();
animalMap.put((String) record[0], innerMap);
}
AnimalValCnt obj = null;
if ((obj = innerMap.get(record[1])) == null) {
obj = new AnimalValCnt();
innerMap.put((String) record[1], obj);
}
obj.Sumval += (Integer) record[2];
obj.cnt++;
}
System.out.println(animalMap);
}
}
class AnimalValCnt {
int Sumval;
int cnt;
#Override
public String toString() {
return "(" + Sumval + "," + cnt + ")";
}
}
Once you have got the data in a map then it's easy to populate these data to a table.You can use a tablemodel for this purpose.Have a look at this code to understand how data from a map can be loaded into a table using TableModel.
UPDATE:
public class AnimalMapping {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String line;
String[] record;
HashMap<String, Map<String, AnimalValCnt>> animalMap = new HashMap<String, Map<String, AnimalValCnt>>();
while(((line = in.readLine()) != null)) {
record=line.split("\\s+");
Map<String, AnimalValCnt> innerMap = null;
if ((innerMap = animalMap.get(record[0])) == null) {
innerMap = new HashMap<String, AnimalValCnt>();
animalMap.put(record[0], innerMap);
}
AnimalValCnt obj = null;
if ((obj = innerMap.get(record[1])) == null) {
obj = new AnimalValCnt();
innerMap.put(record[1], obj);
}
obj.Sumval += Integer.valueOf(record[2]);
obj.cnt++;
}
System.out.println(animalMap);
}
}
class AnimalValCnt {
int Sumval;
int cnt;
#Override
public String toString() {
return "(" + Sumval + "," + cnt + ")";
}
}
#Dilantha Chamal: Reading from file was already given by Box9.I just included it in my code.You should be putting some effort here.Maybe you are a beginner that's why I wrote the code.Now try to implement the TableModel by yourself.Just a friendly advice:unless you do it you are never going to learn.
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
public class AnimalSummaryBuilder
{
private static final Splitter SPLITTER = Splitter.on(CharMatcher.anyOf(","));
private static final Joiner JOINER = Joiner.on("\t");
#SuppressWarnings("unchecked")
public static void main(final String[] args) throws Exception
{
#SuppressWarnings("rawtypes")
Map<Animal, Summary> result = Files.readLines(new File("c:/1.txt"), Charsets.ISO_8859_1, new LineProcessor() {
private final Map<Animal, Summary> result = Maps.newHashMap();
public Object getResult()
{
return result;
}
public boolean processLine(final String line) throws IOException
{
Iterator<String> columns = SPLITTER.split(line).iterator();
String date = columns.next();
String name = columns.next();
int value = Integer.valueOf(columns.next()).intValue();
Animal currentRow = new Animal(date, name);
if (result.containsKey(currentRow))
{
Summary summary = result.get(currentRow);
summary.increaseCount();
summary.addToTotal(value);
}
else
{
Summary initialSummary = new Summary();
initialSummary.setCount(1);
initialSummary.setTotal(value);
result.put(currentRow, initialSummary);
}
return true;
}
});
for (Map.Entry<Animal, Summary> entry : result.entrySet())
{
Animal animal = entry.getKey();
Summary summary = entry.getValue();
System.out.println(JOINER.join(animal.date, animal.name, summary.total, summary.count));
}
}
final static class Animal
{
String date;
String name;
public Animal(final String date, final String n)
{
this.date = date;
this.name = n;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof Animal))
{
return false;
}
Animal other = (Animal) obj;
if (date == null)
{
if (other.date != null)
{
return false;
}
}
else if (!date.equals(other.date))
{
return false;
}
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
return true;
}
}
final static class Summary
{
private int total;
private int count;
void setTotal(int value)
{
total = value;
}
void setCount(int i)
{
count = i;
}
void increaseCount()
{
count++;
}
void addToTotal(int valueToAdd)
{
total += valueToAdd;
}
}
}

Categories

Resources