Keep getting null pointer exception - java

here is my program: basically i have an xml file and from that file i have to decode a base64 string but i keep getting NullPointerException..please help! code is as follows...
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.apache.commons.codec.binary.Base64;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Arrays;
public class main {
public static void main(String[] args) throws Exception {
SAXParserFactory parserFactor = SAXParserFactory.newInstance();
SAXParser parser = parserFactor.newSAXParser();
SAXHandler handler = new SAXHandler();
//parser.parse(ClassLoader.getSystemResourceAsStream("ATMSPopulateDMSData.xml"),
// handler);
parser.parse(new FileInputStream("C:\\Users\\qta6754\\workspace\\Java_Dev\\XML64_Decoded\\ATMSMessageData.xml"), handler);
for (NeededInfo emp : handler.empList) {
System.out.println(emp);
}
}
}
class SAXHandler extends DefaultHandler {
List<NeededInfo> empList = new ArrayList<>();
NeededInfo emp = null;
String content = null;
String did = null;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch (qName) {
case "dMSDeviceStatus":
emp = new NeededInfo();
emp.id = attributes.getValue("id");
emp.Read();
break;
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
content = String.copyValueOf(ch, start, length).trim();
}
}
class NeededInfo {
String id;
String firstName;
String lastName;
String location;
String organization_id;
String operator_id;
String device_id;
String dms_device_status;
String dms_current_message;
String last_comm_time;
String date;
String time;
public String toString() {
//return firstName + " " + lastName + "(" + id + ")" + location+date+time+device_name;
return "Organization id: " + organization_id + "\n" + "Operator id: " + operator_id + "\n" + "Device id: " + device_id + "\n"
+ "Dms Device Status: " + dms_device_status + "\n" + "Dms Current Message: " + dms_current_message + "\n" + "Last Comm Time" + "\n"
+ "Time: " + time + "\n" + "Date: " + date + "\n" + "decoded string is: " + "\n" + "-------------------------------------";
}
public void Read() {
byte[] byteArray = Base64.decodeBase64(dms_current_message.getBytes());
String decodedString = new String(byteArray);
System.out.print("The decoded message is: " + decodedString);
// return decodedString;
}
}

It's hard to guess where you're getting your error, but I'm assuming here:
byte[] byteArray = Base64.decodeBase64(dms_current_message.getBytes());
I don't see dms_current_message being initialized ever, yet you're calling a method on it, which would definitely result in the null pointer exception.

Your Read method accesses the dms_current_message which is never initialized in all the code you included in your question.
byte[] byteArray = Base64.decodeBase64(dms_current_message.getBytes());

Related

parse Json data with array using java

i use gson to get parese json data.but i have some problems
here is my json url data https://api.kcg.gov.tw/api/service/get/2c1d9959-d038-4918-bae3-409680f8193a
you can see that the json data have structure.
here is my code first
package iii_project;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class GsonFetchNetworkJson2 {
public class ItemType {
int seq;
String 資料年度;
String 統計項目;
String 稅目別;
String 資料單位;
String 值;
// public String toString() {
// return Arrays.toString(seq);
// }
}
public class Item {
String isImage;
String success;
String id;
ItemType[] data;
#Override
public String toString() {
return "Item [isImage=" + isImage + ", success=" + success + ", data=" + Arrays.toString(data) + "]";
}
}
public static void main(String[] ignored) throws Exception {
// Type listType = new TypeToken<List<Item>>() {}.getType();
URL url = new URL("https://api.kcg.gov.tw/api/service/get/2c1d9959-d038-4918-bae3-409680f8193a");
InputStreamReader reader = new InputStreamReader(url.openStream());
Item dto = new Gson().fromJson(reader, Item.class);
System.out.println(dto);
// System.out.println(dto.isImage);
// System.out.println(dto.id);
// System.out.println(dto.success);
// System.out.println(dto.types);
// System.out.println(dto.data.toString());
// System.out.println(dto.toString());
// System.out.println(Arrays.toString(dto.date));
// Detail abd = new Gson().fromJson(reader, Detail.class);
// System.out.println(Arrays.toString(abd.值));
// System.out.println(abd.資料單位);
// System.out.println(Arrays.toString(dto.data));
}
}
but the result of
System.out.println(dto);
i haved override it but still can not work
i want the data like this:
here is the answer!!!!
package iii_project;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class GsonFetchNetworkJson2 {
public class ItemType {
private int seq;
private String 資料年度;
private String 統計項目;
private String 稅目別;
private String 資料單位;
private String 值;
//getter and setter
#Override
public String toString() {
return "ItemType [seq=" + seq + ", 資料年度=" + 資料年度 + ", 統計項目=" + 統計項目 + ", 稅目別=" + 稅目別 + ", 資料單位=" + 資料單位
+ ", 值=" + 值 + "]";
}
}
public class Item {
String isImage;
String success;
String id;
ItemType[] data;
#Override
public String toString() {
return "Item [isImage=" + isImage + ", success=" + success + ", id=" + id + ", data="
+ Arrays.toString(data) + "]";
}
}
public static void main(String[] ignored) throws Exception {
// Type listType = new TypeToken<List<Item>>() {}.getType();
URL url = new URL("https://api.kcg.gov.tw/api/service/get/2c1d9959-d038-4918-bae3-409680f8193a");
InputStreamReader reader = new InputStreamReader(url.openStream());
Item dto = new Gson().fromJson(reader, Item.class);
// System.out.println(dto);
// System.out.println(Arrays.toString(dto.data));
System.out.println(dto.isImage);
System.out.println(dto);
// for(ItemType element : dto.data) {
// System.out.println(element);
// }
// System.out.println(dto.data);
// System.out.println(dto.id);
// System.out.println(dto.success);
// System.out.println(dto.types);
// System.out.println(dto.data.toString());
// System.out.println(dto.toString());
// System.out.println(Arrays.toString(dto.date));
// Detail abd = new Gson().fromJson(reader, Detail.class);
// System.out.println(Arrays.toString(abd.值));
// System.out.println(abd.資料單位);
// System.out.println(Arrays.toString(dto.data));
}
}
Your dto.data is array, so your current output is the address of that array.
Replace your System.out.println(dto.data) by System.out.println(Arrays.toString(array)); to print your data array
Check out this to have more details: What's the simplest way to print a Java array?
You need to override the toString function in your Detail class, otherwise it will only print out its address for the object.
but still can not work
It works exactly as you've written it to!
I want the data like this (shows image of some JSON object)
You need to explicitly write the indentation in your toString function, then
For example
public String toString() {
StringBuilder sb = new StringBuilder("{\n");
sb.append(" \"isImage\":" + isImage).append(",\n");
sb.append(" \"data\":");
if (data.length == 0) {
// add empty array string "[]"
} else {
sb.append("[");
for (ItemType it : data) {
// create object string
// append to outer builder
// add a comma, but not for the very last object in the array
}
sb.append("]");
}
// TODO: close off remaining end brackets
return sb.toString();
}
And your ItemType class still needs it's own toString...
If you really just want to print indented JSON without much code, then don't try to print an Item class
Pretty-Print JSON in Java

How to generate custom jvm-cucumber HTML, send it through Jenkins and also ftp the json results?

How to generate custom jvm-cucumber HTML, send it through Jenkins and also ftp the JSON results? This results generation should happen after the entire mvn cucumber suite execution so that I can capture passed / failed results from the json that will be generated after test execution is complete.
I used extended cucumber to achieve this -
Here is the extended cucumber code and create this class in your library -
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import com.github.mkolisnyk.cucumber.runner.AfterSuite;
import com.github.mkolisnyk.cucumber.runner.BeforeSuite;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import cucumber.api.junit.Cucumber;
public class ExtendedCucumberRunner extends Runner {
private Class clazz;
private Cucumber cucumber;
public ExtendedCucumberRunner(Class clazzValue) throws Exception {
clazz = clazzValue;
cucumber = new Cucumber(clazzValue);
}
#Override
public Description getDescription() {
return cucumber.getDescription();
}
private void runPredefinedMethods(Class annotation) throws Exception {
if (!annotation.isAnnotation()) {
return;
}
Method[] methodList = this.clazz.getMethods();
for (Method method : methodList) {
Annotation[] annotations = method.getAnnotations();
for (Annotation item : annotations) {
if (item.annotationType().equals(annotation)) {
method.invoke(null);
break;
}
}
}
}
#Override
public void run(RunNotifier notifier) {
try {
runPredefinedMethods(BeforeSuite.class);
} catch (Exception e) {
e.printStackTrace();
}
cucumber.run(notifier);
try {
runPredefinedMethods(AfterSuite.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is runner class code that will be used to start with the mvn command and this will capture the summary based on the cucumber tags starting with #SUMMARY-
import libs.ExtendedCucumberRunner;
import libs.FTP;
import libs.RemoteSSH;
import com.github.mkolisnyk.cucumber.reporting.CucumberResultsOverview;
import com.github.mkolisnyk.cucumber.runner.AfterSuite;
import com.github.mkolisnyk.cucumber.runner.BeforeSuite;
import com.github.mkolisnyk.cucumber.runner.ExtendedCucumberOptions;
import cucumber.api.CucumberOptions;
import org.apache.commons.io.FileUtils;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import static libs.BaseTest.tagCounts;
import static com.automation.steps.Common.failedCount;
#RunWith(ExtendedCucumberRunner.class)
#ExtendedCucumberOptions(jsonReport = "target/Destination/cucumber.json",
overviewReport = true,
outputFolder = "target/ext-cucumber-results"
,retryCount = 0)
#CucumberOptions(
plugin = {"pretty","html:target/Destination","json:target/Destination/cucumber.json"},
strict = true,
monochrome = true
)
public class Runner {
#BeforeSuite
public static void manageResults() throws IOException {
String directory=System.getProperty("user.dir");
if (new File("target/Destination/cucumber.json").exists()) {
String contents = new String(Files.readAllBytes(Paths.get("target/Destination/cucumber.json"))).toString().trim();
if (!contents.equals("")) {
long timestamp = System.currentTimeMillis() / 1000;
FileUtils.copyFile(new File("target/Destination/cucumber.json"), new File("target/Destination/cucumber_" + timestamp + ".json"));
}
}
}
#AfterSuite
public static void copy_json_generate_report() throws Exception {
String directory=System.getProperty("user.dir");
CucumberResultsOverview results = new CucumberResultsOverview();
results.setOutputDirectory("target/ext-cucumber-results");
results.setOutputName("cucumber-results");
results.setSourceFile(directory+"/target/Destination/cucumber.json");
results.execute();
String format_tag_name="";
if(System.getenv("TAG_NAME")==null){
format_tag_name="Local--";
}else {
format_tag_name = System.getenv("TAG_NAME").
replaceAll("#", "").replaceAll(",", "-")
.replaceAll("\\[", "")
.replaceAll("]", "");
}
String destination_path = "";
Date today = Calendar.getInstance().getTime();
SimpleDateFormat unix_format = new SimpleDateFormat("yyyyMMdd");
long timestamp = System.currentTimeMillis() / 1000;
if (failedCount==0) {
destination_path ="/tmp/QA_RESULTS/"+unix_format.format(today)+"/"+format_tag_name+"_" + timestamp + ".json";
}else{
destination_path ="/tmp/QA_RESULTS/"+unix_format.format(today)+"/"+format_tag_name+"_" + timestamp + "--F.json";
}
System.out.println("After class is being run now- to copy json files!!!");
if (new File(directory+"/target/Destination/cucumber.json").exists()) {
System.out.println(directory+"/target/Destination/cucumber.json --exits!");
// CommonUtils.createFile(GenerateHTMLReport(),"Destination/CucumberSummaryReport.html");
String contents = new String(Files.readAllBytes(Paths.get(directory+"/target/Destination/cucumber.json"))).toString().trim();
if (!contents.equals("")) {
RemoteSSH ssh = new RemoteSSH();
List<String> check_file_commands = Arrays.asList("mkdir -p /tmp/QA_RESULTS/"+unix_format.format(today) );
List<String> check_file_logs = ssh.SSHClient(check_file_commands);
String local_path = directory+"/target/Destination/cucumber.json";
System.out.println(local_path);
FTP ftp = new FTP();
ftp.SCPUpload(local_path,destination_path);
}else{
System.out.println("File is empty!");
}
}
try {
Runtime.getRuntime().exec("TASKKILL /F /IM xxx.exe");
} catch (IOException e) {
System.out.println("Killing xxxx.exe error out");
}
}
public static String GenerateHTMLReport(){
String html_string = "<!-- CSS Code: Place this code in the document's head (between the 'head' tags) -->\n" +
"<style>\n" +
"table.GeneratedTable {\n" +
" width: 100%;\n" +
" background-color: #ffffff;\n" +
" border-collapse: collapse;\n" +
" border-width: 2px;\n" +
" border-color: #ffcc00;\n" +
" border-style: solid;\n" +
" color: #000000;\n" +
"}\n" +
"\n" +
"table.GeneratedTable td, table.GeneratedTable th {\n" +
" border-width: 2px;\n" +
" border-color: #ffcc00;\n" +
" border-style: solid;\n" +
" padding: 3px;\n" +
"}\n" +
"\n" +
"table.GeneratedTable thead {\n" +
" background-color: #ffcc00;\n" +
"}\n" +
"</style>\n" +
"\n" +
"<!-- HTML Code: Place this code in the document's body (between the 'body' tags) where the table should appear -->\n" +
"<table class=\"GeneratedTable\">\n" +
" <thead>\n" +
" <tr>\n" +
" <th>Functionality Group</th>\n" +
" <th>Passed</th>\n" +
" <th>Passed With Warning</th>\n" +
" <th>Failed</th>\n" +
" <th>Script Issue</th>\n" +
" <th>Env Issue</th>\n" +
" <th>Warning</th>\n" +
" </tr>\n" +
" </thead>\n" +
" <tbody>\n" +
" <tr>\n";
System.out.println(tagCounts.size());
for (Map.Entry<String,List<Integer>> entry : tagCounts.entrySet()) {
html_string = html_string +
" <tr><td>" + entry.getKey() + "</td>\n" +
" <td>" + entry.getValue().get(0) + "</td>\n" +
" <td>" + entry.getValue().get(1) + "</td>\n" +
" <td>" + "Script Issue Value" + "</td>\n" +
" <td>" + "Env Issue Value" + "</td></tr>\n";
}
html_string = html_string +
" </tr>\n" +
" </tbody>\n" +
"</table>\n" +
"\n";
return html_string;
}
}
Now in the Jenkins configure, add the following to the content section of editable email configuration add-in-
<html>
<body>
<p>Pls refer the below results-</p>
${BUILD_URL}/cucumber-html-reports/overview-features.html
<p>Note: Copy and paste the above link in chrome or Firefox. The report won't work in IE.</p>
</body>
</html>
${FILE,path="target/CucumberSummaryReport.html"}
${FILE,path="target/ext-cucumber-results/cucumber-results-feature-overview.html"}

How to read XML to a list of POJOs in Java?

I'm new to XML and im trying to read in an XML page and store its contents in an arraylist.
So far i seem to have been able to get the arraylist filled with the first content, as when i tried an isEmpty, it returned false. so there is definitely containing something.
However, when i try to call the overided tostring method, or even try to call any individual category for that matter, it just returns empty?
can anyone help?
heres the code im working with:
package test;
import java.io.File;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class xmlmx {
public static void main(String[] args) {
ArrayList<Anime> list = new ArrayList<Anime>();
try {
File inputFile = new File("c:\\code\\ad\\XMLDB.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Anime");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
list.add(new Anime(eElement.getAttribute("ID"),
eElement.getAttribute("name"),
eElement.getAttribute("altname"),
eElement.getAttribute("seasons"),
eElement.getAttribute("episodes"),
eElement.getAttribute("status"),
eElement.getAttribute("DS"),
eElement.getAttribute("have"),
eElement.getAttribute("left"),
eElement.getAttribute("plot"),
eElement.getAttribute("connect"),
eElement.getAttribute("image")));
System.out.println(list.get(0).toString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
the arraylist is of type anime, a class here:
package test;
class Anime{
private String ID;
private String name;
private String altname;
private String seasons;
private String episodes;
private String status;
private String DS;
private String have;
private String left;
private String plot;
private String connect;
private String image;
public Anime(String ID,
String name,
String altname,
String seasons,
String episodes,
String status,
String DS,
String have,
String left,
String plot,
String connect,
String image) {
this.ID = ID;
this.name = name;
this.altname = altname;
this.seasons = seasons;
this.episodes = episodes;
this.status = status;
this.DS = DS;
this.have = have;
this.left = left;
this.plot = plot;
this.connect = connect;
this.image = image;
}
/*
getters and setters here...
*/
#Override
public String toString() {
return "Anime [ID=" + ID +
", name=" + name +
", altname=" + altname +
", seasons=" + seasons +
", episodes=" + episodes +
", status=" + status +
", DS=" + DS +
", have=" + have +
", left=" + left +
", plot=" + plot +
", connect=" + connect +
", image=" + image + "]";
}
}
finally, heres the xml:
<?xml version="1.0" encoding="UTF-8"?>
<Anime>
<record ID="BL1">
<name>Bleach</name>
<altname>Burichi</altname>
<seasons>16</seasons>
<episodes>366</episodes>
<status>Finished</status>
<sound>Dubbed</sound>
<have>All</have>
<left>-/-</left>
<plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
<connect>Bleach movies</connect>
<image>images/bleach.jpg</image>
</record>
</Anime>
any help would be greatly appreciated, thank you
Hi basically your understanding about the w3c dom xml element is wrong. "name:, "altname" etc are not attributes of "Animie" element. those are "child nodes" of "record" node. So first you have to fetch "record" node by iterating child nodes of "Animie" element. Then you can iterate through the child nodes of "record" element so that you can populate your Anime object.
Here's a simple implementation of your "xmlmx class that works. I had to use a map because you have ommitted the setter methods, this can be improved just trying to fix the xml concepts in your head.
Just replace your class with this.
package test;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import com.sun.org.apache.xerces.internal.dom.DeferredElementImpl;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class xmlmx {
public static void main(String[] args) {
ArrayList<Anime> list = new ArrayList<Anime>();
try {
File inputFile = new File("test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
Node recordNode = null;
NodeList childNodes = doc.getFirstChild().getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
if (childNodes.item(i).getNodeName().equals("record")) {
recordNode = childNodes.item(i);
break;
}
}
System.out.println("----------------------------");
Map<String, String> map = new HashMap<>();
if (recordNode != null) {
NodeList subNodes = recordNode.getChildNodes();
for (int i = 0; i < subNodes.getLength(); i++) {
if (subNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
map.put(subNodes.item(i).getNodeName(), subNodes.item(i).getTextContent());
}
}
}
String id = ((DeferredElementImpl) recordNode).getAttribute("ID");
list.add(new Anime(id,
map.get("name"),
map.get("altname"),
map.get("seasons"),
map.get("episodes"),
map.get("status"),
map.get("DS"),
map.get("have"),
map.get("left"),
map.get("plot"),
map.get("connect"),
map.get("image")));
System.out.println(list.get(0));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Use an ObjectMapper like Jackson FasterXML!
new XmlMapper().readValue(yourDataAsInputStream, Anime.class);
or for a list
new XmlMapper().readValue(yourDataAsInputStream, new TypeReference<List<Anime>>(){});
Full Example:
package stack47711679;
import java.util.List;
import org.junit.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class HowToReadXmlToAPojoIn2017 {
#Test
public void readXmlToPojo() throws Exception {
ObjectMapper mapper = new XmlMapper();
Anime pojo = mapper.readValue(Thread.currentThread().getContextClassLoader().getResourceAsStream("47711679.xml"), Anime.class);
System.out.println(pojo+"");
}
#Test
public void readXmlToListOfPojo() throws Exception {
ObjectMapper mapper = new XmlMapper();
List<Anime> pojos = mapper.readValue(Thread.currentThread().getContextClassLoader().getResourceAsStream("47711679_v2.xml"), new TypeReference<List<Anime>>(){});
System.out.println(pojos+"");
}
}
Your POJO Anime.java
package stack47711679;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
public class Anime{
#JacksonXmlProperty(isAttribute = true)
public String id;
public String name;
public String altname;
public String seasons;
public String episodes;
public String status;
public String DS;
public String have;
public String left;
public String plot;
public String connect;
public String image;
public String sound;
public Anime(){
}
#Override
public String toString() {
return "Anime [ID=" + id +
", name=" + name +
", altname=" + altname +
", seasons=" + seasons +
", episodes=" + episodes +
", status=" + status +
", DS=" + DS +
", have=" + have +
", left=" + left +
", plot=" + plot +
", connect=" + connect +
", sound=" + sound +
", image=" + image + "]";
}
}
With Testdata:
47711679.xml
<?xml version="1.0" encoding="UTF-8"?>
<Anime id="1">
<name>Bleach</name>
<altname>Burichi</altname>
<seasons>16</seasons>
<episodes>366</episodes>
<status>Finished</status>
<sound>Dubbed</sound>
<have>All</have>
<left>-/-</left>
<plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
<connect>Bleach movies</connect>
<image>images/bleach.jpg</image>
</Anime>
47711679_v2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Animes>
<Anime id="1">
<name>Bleach</name>
<altname>Burichi</altname>
<seasons>16</seasons>
<episodes>366</episodes>
<status>Finished</status>
<sound>Dubbed</sound>
<have>All</have>
<left>-/-</left>
<plot>Ichigo gets grim reaper powers, fights reapers, hollows and everything in between</plot>
<connect>Bleach movies</connect>
<image>images/bleach.jpg</image>
</Anime>
<Anime id="2">
<name>Something</name>
<altname>else</altname>
<seasons>21</seasons>
<episodes>34</episodes>
<status>to be continued</status>
<sound>Dubbed</sound>
<have>All</have>
<left>-/-</left>
<plot>Yes it has one</plot>
<connect>Bleach movies</connect>
<image>images/bleach.jpg</image>
</Anime>
</Animes>
Prints:
For the list in 47711679_v2.xml:
[Anime [ID=1, name=Bleach, altname=Burichi, seasons=16, episodes=366, status=Finished, DS=null, have=All, left=-/-, plot=Ichigo gets grim reaper powers, fights reapers, hollows and everything in between, connect=Bleach movies, sound=Dubbed, image=images/bleach.jpg], Anime [ID=2, name=Something, altname=else, seasons=21, episodes=34, status=to be continued, DS=null, have=All, left=-/-, plot=Yes it has one, connect=Bleach movies, sound=Dubbed, image=images/bleach.jpg]]
And for the single entry 47711679.xml:
Anime [ID=1, name=Bleach, altname=Burichi, seasons=16, episodes=366, status=Finished, DS=null, have=All, left=-/-, plot=Ichigo gets grim reaper powers, fights reapers, hollows and everything in between, connect=Bleach movies, sound=Dubbed, image=images/bleach.jpg]
I used jackson 2.8.6.
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.8.6</version>
</dependency>

how to solve The import com.atlassian cannot be resolved?

Hello I am trying to develop my web application using jsp. I have 6 jsp pages in it. Pages are registration.jsp, login.jsp, r1.jsp, welcome.jsp, createroom.jsp and showroom.jsp respectivly. My goal is that when i login in login page, page should redirect in openmeeting server. For that i have created webservice like omRestService. For calling this Service i have created two java class omGateWay and OmPluginSettings respectivly. Everything works fine but error occurs in ompluginSetting class.error mention below.
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
(The import com.atlassian cannot be resolved)
Here I am Providing you my OmPluginSeeting.java file which has error. There are many errors occur at PluginSettingsFactory.
package restService;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OmPluginSettings
{
private static final Logger log = (Logger) LoggerFactory.getLogger(OmPluginSettings.class);
final PluginSettingsFactory pluginSettingsFactory;
public OmPluginSettings(PluginSettingsFactory pluginSettingsFactory)
{
this.pluginSettingsFactory = pluginSettingsFactory;
}
public void storeSomeInfo(String key, String value)
{
this.pluginSettingsFactory.createGlobalSettings().put("openmeetings:" + key, value);
}
public Object getSomeInfo(String key)
{
return this.pluginSettingsFactory.createGlobalSettings().get("openmeetings:" + key);
}
public void storeSomeInfo(String projectKey, String key, String value)
{
this.pluginSettingsFactory.createSettingsForKey(projectKey).put("openmeetings:" + key,
value);
}
public Object getSomeInfo(String projectKey, String key) {
return this.pluginSettingsFactory.createSettingsForKey(projectKey).get("openmeetings:"
+ key);
}
}
I also provide my restservice which is Given Below and totally error free.
package restService;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashMap;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class omRestService
{
private static final Logger log = (Logger)
LoggerFactory.getLogger(omRestService.class);
private URI getURI(String url) {
return UriBuilder.fromUri(
url).build(new Object[0]);
}
private String getEncodetURI(String url) throws MalformedURLException
{
return new URL(url).toString().replaceAll(" ", "%20");
}
public LinkedHashMap<String, Element> call(String request, Object param)
throws Exception
{
HttpClient client = new HttpClient();
GetMethod method = null;
try
{
method = new GetMethod(getEncodetURI(request).toString());
}
catch (MalformedURLException e) {
e.printStackTrace();
}
int statusCode = 0;
try {
statusCode = client.executeMethod(method);
}
catch (HttpException e)
{
throw new Exception("Connection to OpenMeetings refused. Please check your
OpenMeetings configuration.");
}
catch (IOException e)
{
throw new Exception("Connection to OpenMeetings refused. Please check your
OpenMeetings configuration.");
}
switch (statusCode)
{
case 200:
break;
case 400:
throw new Exception("Bad request. The parameters passed to the service did
not match
as expected. The Message should tell you what was missing or incorrect.");
case 403:
throw new Exception("Forbidden. You do not have permission to access this
resource, or
are over your rate limit.");
case 503:
throw new Exception("Service unavailable. An internal problem prevented us
from
returning data to you.");
default:
throw new Exception("Your call to OpenMeetings! Web Services returned an
unexpected
HTTP status of: " + statusCode);
}
InputStream rstream = null;
try
{
rstream = method.getResponseBodyAsStream();
}
catch (IOException e) {
e.printStackTrace();
throw new Exception("No Response Body");
}
BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
SAXReader reader = new SAXReader();
Document document = null;
String line;
try
{
// String line;
while ((line = br.readLine()) != null)
{
// String line;
document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
throw new Exception("UnsupportedEncodingException by SAXReader");
}
catch (IOException e) {
e.printStackTrace();
throw new Exception("IOException by SAXReader in REST Service");
}
catch (DocumentException e) {
e.printStackTrace();
throw new Exception("DocumentException by SAXReader in REST Service");
} finally {
br.close();
}
Element root = document.getRootElement();
LinkedHashMap elementMap = new LinkedHashMap();
for (Iterator i = root.elementIterator(); i.hasNext(); )
{
Element item = (Element)i.next();
if (item.getNamespacePrefix() == "soapenv") {
throw new Exception(item.getData().toString());
}
String nodeVal = item.getName();
elementMap.put(nodeVal, item);
}
return elementMap;
}
}
After This RestService i have make OmGateWay class which has many method for integrate with openmeetings. which is given below:
package org.openmeetings.jira.plugin.gateway;
import java.util.LinkedHashMap;
import org.dom j.Element;
import org.openmeetings.jira.plugin.ao.adminconfiguration.OmPluginSettings;
import org.slf j.Logger;
import org.slf j.LoggerFactory;
public class OmGateway
{
private static final Logger log =
LoggerFactory.getLogger(OmGateway.class);
private OmRestService omRestService;
private OmPluginSettings omPluginSettings;
private String sessionId;
public OmGateway(OmRestService omRestService, OmPluginSettings omPluginSettings)
{
this.omRestService = omRestService;
this.omPluginSettings = omPluginSettings;
}
public Boolean loginUser() throws Exception
{
LinkedHashMap result = null;
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String userpass = (String)this.omPluginSettings.getSomeInfo("userpass");
String omusername =
(String)this.omPluginSettings.getSomeInfo("username");
String sessionURL = "http://" + url + ":" + port + "/openmeetings
/services/
UserService/getSession";
LinkedHashMap elementMap = this.omRestService.call(sessionURL, null);
Element item = (Element)elementMap.get("return");
setSessionId(item.elementText("session_id"));
log.info(item.elementText("session_id"));
result = this.omRestService.call("http://" + url + ":" + port +
"/openmeetings/
services/UserService/loginUser?SID=" + getSessionId() + "&username=" +
omusername
+ "&userpass=" + userpass, null);
if
(Integer.valueOf(((Element)result.get("return")).getStringValue()).intValue() >
) {
return Boolean.valueOf(true);
}
return Boolean.valueOf(false);
}
public Long addRoomWithModerationExternalTypeAndTopBarOption(Boolean
isAllowedRecording,
Boolean isAudioOnly, Boolean isModeratedRoom, String name, Long
numberOfParticipent, Long
roomType, String externalRoomType)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String roomId = "";
String restURL = "http://" + url + ":" + port + "/openmeetings/services/
RoomService/addRoomWithModerationExternalTypeAndTopBarOption?" +
"SID=" + getSessionId() +
"&name=" + name +
"&roomtypes_id=" + roomType.toString() +
"&comment=jira" +
"&numberOfPartizipants=" + numberOfParticipent.toString() +
"&ispublic=false" +
"&appointment=false" +
"&isDemoRoom=false" +
"&demoTime=" +
"&isModeratedRoom=" + isModeratedRoom.toString() +
"&externalRoomType=" + externalRoomType +
"&allowUserQuestions=" +
"&isAudioOnly=" + isAudioOnly.toString() +
"&waitForRecording=false" +
"&allowRecording=" + isAllowedRecording.toString() +
"&hideTopBar=false";
LinkedHashMap result = this.omRestService.call(restURL, null);
roomId = ((Element)result.get("return")).getStringValue();
return Long.valueOf(roomId);
}
public Long updateRoomWithModerationAndQuestions(Boolean isAllowedRecording,
Boolean
isAudioOnly, Boolean isModeratedRoom, String roomname, Long
numberOfParticipent, Long
roomType, Long roomId)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String updateRoomId = "";
String restURL = "http://" + url + ":" + port + "/openmeetings/services
/RoomService/
updateRoomWithModerationAndQuestions?" +
"SID=" + getSessionId() +
"&room_id=" + roomId.toString() +
"&name=" + roomname.toString() +
"&roomtypes_id=" + roomType.toString() +
"&comment=" +
"&numberOfPartizipants=" + numberOfParticipent.toString() +
"&ispublic=false" +
"&appointment=false" +
"&isDemoRoom=false" +
"&demoTime=" +
"&isModeratedRoom=" + isModeratedRoom.toString() +
"&allowUserQuestions=";
LinkedHashMap result = this.omRestService.call(restURL, null);
log.info("addRoomWithModerationExternalTypeAndTopBarOption with ID: ",
((Element)result.get("return")).getStringValue());
updateRoomId = ((Element)result.get("return")).getStringValue();
return Long.valueOf(updateRoomId);
}
public String setUserObjectAndGenerateRoomHash(String username, String
firstname, String
lastname, String profilePictureUrl, String email, String externalUserId, String
externalUserType, Long room_id, int becomeModeratorAsInt, int
showAudioVideoTestAsInt)
throws Exception
{
String url = (String)this.omPluginSettings.getSomeInfo("url");
String port = (String)this.omPluginSettings.getSomeInfo("port");
String roomHash = null;
String restURL = "http://" + url + ":" + port + "/openmeetings/services
/UserService/
setUserObjectAndGenerateRoomHash?" +
"SID=" + getSessionId() +
"&username=" + username +
"&firstname=" + firstname +
"&lastname=" + lastname +
"&profilePictureUrl=" + profilePictureUrl +
"&email=" + email +
"&externalUserId=" + externalUserId +
"&externalUserType=" + externalUserType +
"&room_id=" + room_id +
"&becomeModeratorAsInt=" + becomeModeratorAsInt +
"&showAudioVideoTestAsInt=" + showAudioVideoTestAsInt;
LinkedHashMap result = this.omRestService.call(restURL, null);
roomHash = ((Element)result.get("return")).getStringValue();
return roomHash;
}
public String getSessionId() {
return this.sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}
I want to call loginuser method from OmGateway class on Jsp Button Click Event. Kindly help me to solve this Error. And Help To Redirect and Integrate to openmeetings. Thank you In Advance.
Visit Atlassian Developers for help
Have you ever tried the Jira Plugin from the website:
http://openmeetings.apache.org/JiraPlugin.html
or is this actually the plugin code that you are posting here?

JAXM soap message parsing

I am getting the following XML back from a .net service:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<validateCredentialsResponse
xmlns="http://www.paragon.com/positionmonitor/PositionMonitor">
<validateCredentialsResult>
<ResultData xsi:type="ValidateCredentialsResultData">
<validated>true</validated>
<alreadyLoggedIn>false</alreadyLoggedIn>
</ResultData>
<Status>
<Condition xmlns="">SUCCESS</Condition>
<ErrorCode xmlns="">BO.00000</ErrorCode>
<ErrorDesc xmlns="">OK</ErrorDesc>
</Status>
</validateCredentialsResult>
</validateCredentialsResponse>
</soap:Body>
</soap:Envelope>
...and I'm trying to parse it using JAXM, however the following always evaluates to null:
SOAPEnvelope env = reply.getSOAPPart().getEnvelope();
Can anyone help me out here?
I got nice results using the following code (needs at least Java 1.5):
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Jaxm {
private static List<Element> elements(NodeList nodes) {
List<Element> result = new ArrayList<Element>(nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node instanceof Element)
result.add((Element)node);
}
return result;
}
private static Element named(Element elem, String name) {
if (!elem.getNodeName().equals(name))
throw new IllegalArgumentException("Expected " + name + ", got " + elem.getNodeName());
return elem;
}
#SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException, SOAPException {
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" \r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \r\n" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n" +
" <soap:Body>\r\n" +
" <validateCredentialsResponse \r\n" +
" xmlns=\"http://www.paragon.com/positionmonitor/PositionMonitor\">\r\n" +
" <validateCredentialsResult>\r\n" +
" <ResultData xsi:type=\"ValidateCredentialsResultData\">\r\n" +
" <validated>true</validated>\r\n" +
" <alreadyLoggedIn>false</alreadyLoggedIn>\r\n" +
" </ResultData>\r\n" +
" <Status>\r\n" +
" <Condition xmlns=\"\">SUCCESS</Condition>\r\n" +
" <ErrorCode xmlns=\"\">BO.00000</ErrorCode>\r\n" +
" <ErrorDesc xmlns=\"\">OK</ErrorDesc>\r\n" +
" </Status>\r\n" +
" </validateCredentialsResult>\r\n" +
" </validateCredentialsResponse>\r\n" +
" </soap:Body>\r\n" +
"</soap:Envelope>\r\n" +
"";
MessageFactory factory = MessageFactory.newInstance();
SOAPMessage msg = factory.createMessage(new MimeHeaders(), new ByteArrayInputStream(xml.getBytes(Charset.forName("UTF-8"))));
msg.saveChanges();
SOAPBody soapBody = msg.getSOAPBody();
for (Element response : elements(soapBody.getElementsByTagName("validateCredentialsResponse"))) {
for (Element result : elements(response.getElementsByTagName("validateCredentialsResult"))) {
List<Element> children = elements(result.getChildNodes());
Element resultData = named(children.get(0), "ResultData");
List<Element> resultDataChildren = elements(resultData.getChildNodes());
boolean validated = Boolean.getBoolean(named(resultDataChildren.get(0), "validated").getTextContent());
boolean alreadyLoggedIn = Boolean.getBoolean(named(resultDataChildren.get(1), "alreadyLoggedIn").getTextContent());
Element status = named(children.get(1), "Status");
List<Element> statusChildren = elements(status.getChildNodes());
String condition = named(statusChildren.get(0), "Condition").getTextContent();
String errorCode = named(statusChildren.get(1), "ErrorCode").getTextContent();
String errorDesc = named(statusChildren.get(2), "ErrorDesc").getTextContent();
System.out.printf("validated=%s alreadyLoggedIn=%s condition=%s errorCode=%s errorDesc=%s\n", validated, alreadyLoggedIn, condition, errorCode, errorDesc);
}
}
}
}

Categories

Resources