How do I invoke the following method JsonParser:
/**
* Converts a JSON document to XML.
* #param io input
* #param options parser options
* #return parser
* #throws IOException I/O exception
*/
private static IOContent toXML(final IO io, final JsonParserOptions options) throws IOException {
final JsonConverter conv = JsonConverter.get(options);
final IOContent xml = new IOContent(conv.convert(io).serialize().finish());
xml.name(io.name());
return xml;
}
yet I'm certainly not seeing this method from the IDE:
The method is in the JavaDocs:
Method Detail
toXML
public static IOContent toXML(IO io,
JsonParserOptions options)
throws java.io.IOException
Converts a JSON document to XML.
Parameters:
io - input
options - parser options
Returns:
parser
Throws:
java.io.IOException - I/O exception
The build file is using:
compile group: 'org.basex', name: 'basex', version: '9.2.4'
which is the most recent version I see on the repository:
maven { url "https://mvnrepository.com/" }
I went so far as to assemble the project and extracted the .class file from the JAR from the resulting BaseX but didn't go futher to find if this method is there or not.
Perhaps I'm just not invoking the method properly?
whoops:
package basex;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.logging.Logger;
import org.basex.build.json.JsonParser;
import org.basex.build.xml.SAXWrapper;
import org.basex.core.MainOptions;
import org.basex.io.IOFile;
public class JsonToXmlTransformer {
private static final Logger log = Logger.getLogger(JsonToXmlTransformer.class.getName());
public JsonToXmlTransformer() {
}
private void baseXparseJsonFile(String fileName) throws IOException {
org.basex.build.json.JsonParser jsonParser = new org.basex.build.json.JsonParser(new IOFile(fileName), new MainOptions());
SAXWrapper foo = org.basex.build.json.JsonParser.xmlParser(new IOFile(fileName));
foo.parse();
String bar = foo.toString();
log.info(bar);
}
public void transform(String fileName) throws IOException {
String content = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);
org.json.JSONObject json = new org.json.JSONObject(content);
log.info(org.json.XML.toString(json));
}
}
had the wrong package...
Related
My code is like:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet;
import org.dom4j;
import org.jaxen.JaxenException;
/**
* Servlet implementation class Search
*/
//#WebServlet("/Search")
public class Search extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String xmlName = "rows.xml";
private static Document document;
/**
* #throws DocumentException
* #see HttpServlet#HttpServlet()
*/
public Search() throws DocumentException {
super();
XmlReader xmlReader = new XmlReader();
document = xmlReader.readXml();
searcher();
}
The code that occured the unexpected output:
public void searcher()
{
List nodelist = document.selectNodes("rows");
System.out.println(nodelist.size());
}
}
My XML reader:
package web.app;
import org.xml.sax.helpers.DefaultHandler;
import org.dom4j;
public class XmlReader extends DefaultHandler{
public static String filename =
"D:\\JavaWorkplace\\DataCuration\\WebContent\\rows.xml";
public Document readXml() throws DocumentException {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(filename);
System.out.println(document.content());
return document;
}
}
The XML file: https://data.oregon.gov/api/views/j8eb-8um2/rows.xml?accessType=DOWNLOAD
However, the output is:
[org.dom4j.tree.DefaultElement#50e96ea1 [Element: <response attributes: []/>]]
0
So what's wrong with that?
All right, I got the reason.
I confused the root element in the XML file.
It is "response", not "rows".
Thanks anyway :)
I am generating java source code using JCodeModel. I would to add copyright information to the generated code. Is this possible currently?
I tried using javadoc()in JDefinedClass , it adds the information only above the class definition.
com.sun.codemodel.writer.PrologCodeWriter is exactly what you are looking for
You can create a CodeWriter that writes the copyright header. This CodeWriter can delegate to another one - namely, to the one that you would usually pass to the CodeModel#build method.
A complete example:
import java.io.IOException;
import java.io.OutputStream;
import com.sun.codemodel.CodeWriter;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.writer.SingleStreamCodeWriter;
public class HeaderInCodeModel
{
public static void main(String[] args) throws Exception
{
JCodeModel codeModel = new JCodeModel();
codeModel._class("com.example.Example");
CodeWriter codeWriter = new SingleStreamCodeWriter(System.out);
String header = "// Copyright 2017 - example.com\n";
CodeWriter codeWriterWithHeader =
createCodeWriterWithHeader(header, codeWriter);
codeModel.build(codeWriterWithHeader);
}
private static CodeWriter createCodeWriterWithHeader(
String header, CodeWriter delegate)
{
CodeWriter codeWriter = new CodeWriter()
{
#Override
public OutputStream openBinary(JPackage pkg, String fileName)
throws IOException
{
OutputStream result = delegate.openBinary(pkg, fileName);
if (header != null)
{
result.write(header.getBytes());
}
return result;
}
#Override
public void close() throws IOException
{
delegate.close();
}
};
return codeWriter;
}
}
The resulting class will be
// Copyright 2017 - example.com
package com.example;
public class Example {
}
In my application I have a method which I cant execute without main method. It only runs inside the main method. When I call that method inside my servlet class. It show an exception
My class with Main Method
package com.books.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
// download
public void download(String url, File destination) throws IOException, Exception {
URL website = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
public static Set<String> nounPhrases = new HashSet<>();
private static String line = "The Moon is a barren, rocky world ";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP")
|| p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
}
}
public void parserAction() throws Exception {
// InputStream is = new FileInputStream("en-parser-chunking.bin");
File modelFile = new File("en-parser-chunking.bin");
if (!modelFile.exists()) {
System.out.println("Downloading model.");
download("https://drive.google.com/uc?export=download&id=0B4uQtYVPbChrY2ZIWmpRQ1FSVVk", modelFile);
}
ParserModel model = new ParserModel(modelFile);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses) {
// p.show();
getNounPhrases(p);
}
}
public static void main(String[] args) throws Exception {
new ParserTest().parserAction();
System.out.println("List of Noun Parse : " + nounPhrases);
}
}
It gives me below output
List of Noun Parse : [barren,, world, Moon]
Then I commented the main method and. Called the ParserAction() method in my servlet class
if (name.equals("bkDescription")) {
bookDes = value;
try {
new ParserTest().parserAction();
System.out.println("Nouns Are"+ParserTest.nounPhrases);
} catch (Exception e) {
}
It gives me the below exceptions
And below error in my Browser
Why is this happening ? I can run this with main method. But when I remove main method and called in my servlet. it gives an exception. Is there any way to fix this issue ?
NOTE - I have read below instructions in OpenNLP documentation , but I have no clear idea about it. Please help me to fix his issue.
Unlike the other components to instantiate the Parser a factory method
should be used instead of creating the Parser via the new operator.
The parser model is either trained for the chunking parser or the tree
insert parser the parser implementation must be chosen correctly. The
factory method will read a type parameter from the model and create an
instance of the corresponding parser implementation.
Either create an object of ParserTest class or remove new keyword in this line new ParserTest().parserAction();
I am currently having trouble creating a folder and a file if not present. I keep getting and error about it not being specified and I don't really know how to fix it.
this is my main
import java.io.IOException;
public class main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException{
timeKeepHome ja = new timeKeepHome();
//ja.setVisible(true);
fileTimeLog log = new fileTimeLog();
log.checkFile();
}
}
and this is my class to create the file/ folder.
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Formatter;
public class fileTimeLog
{
File log = new File("log/sixWeek.dat");
File folder = new File("log");
PrintWriter logW = new PrintWriter("log/sixWeek.dat");
public fileTimeLog() throws IOException
{
System.out.println("successful");
checkFile();
}
public void checkFile() throws IOException
{
if(!(log.exists()))
{
createFile();
}
}
public void saveTime() throws IOException
{
}
public void saveDate()
{
}
public void createFile() throws IOException
{
folder.mkdir();
logW = new PrintWriter(log);
logW.println("DONT MODIFY THIS FILE IF UNLESS YOU KNOW WHAT YOUR ARE DOING ");
logW.close();
}
}
and the error i'm getting
Exception in thread "main" java.io.FileNotFoundException: log\sixWeek.dat (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at java.io.PrintWriter.<init>(PrintWriter.java:184)
at fileTimeLog.<init>(fileTimeLog.java:17)
at main.main(main.java:18)
I would make everything look nicer and neater but I'm just really frustrated and I've done research but don't really understand.
The Printwriter will try and create a file, so when you do this
PrintWriter logW = new PrintWriter("log/sixWeek.dat");
in your class defintion, then it will try to create it, but the folder does not exist until you do createFile
As you re-initialize logW in createFile anyway, you do not need to initialize it in your class defintion
I am creating a sample program using protocol buffer and protobuf-java-format.My proto file is
package com.sample;
option java_package = "com.sample";
option java_outer_classname = "PersonProtos";
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
My Sample program is
package com.sample;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import com.google.protobuf.Message;
import com.googlecode.protobuf.format.XmlFormat;
import com.sample.PersonProtos.Person;
/**
* This class generate XML out put from Object and vice-versa
*
* #author mcapatna
*
*/
public class Demo
{
public static void main(String[] args) throws IOException
{
// get the message type from protocol buffer generated class.set the
// required property
Message personProto = Person.newBuilder().setEmail("a").setId(1).setName("as").build();
// use protobuf-java-format to generate XMl from Object.
String toXml = XmlFormat.printToString(personProto);
System.out.println(toXml);
// Create the Object from XML
Message.Builder builder = Person.newBuilder();
String fileContent = "";
Person person = Person.parseFrom(new FileInputStream("C:\\file3.xml"));
System.out.println(XmlFormat.printToString(person));
System.out.println("-Done-");
}
}
XmlFormat.printToString() is working fine.but creating object from XML not working
I also tried XmlFormat.merge(toXml, builder); .but since merge() return void.so how can we get the object of Person class.
Both the above method merge() and parseFrom() giving the same exception
com.google.protobuf.InvalidProtocolBufferException: Protocol message end-group tag did not match expected tag.
NOTE: "C:\\file3.xml" have the same content as toXml.
After a lots of effort,I found the solution...Here is the answer
package com.sample;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.protobuf.Message;
import com.googlecode.protobuf.format.XmlFormat;
import com.sample.PersonProtos.Person;
/**
* This class generate XML output from Object and vice-versa
*
* #author mcapatna
*
*/
public class Demo
{
public static void main(String[] args) throws IOException
{
long startDate=System.currentTimeMillis();
// get the message type from protocol buffer generated class.set the
// required property
Message personProto = Person.newBuilder().setEmail("a").setId(1).setName("as").build();
// use protobuf-java-format to generate XMl from Object.
String toXml = XmlFormat.printToString(personProto);
System.out.println("toXMl "+toXml);
// Create the Object from XML
Message.Builder builder = Person.newBuilder();
String fileContent = "";
// file3 contents same XML String as toXml
fileContent = readFileAsString("C:\\file3.xml");
// call protobuf-java-format method to generate Object
XmlFormat.merge(fileContent, builder);
Message msg= builder.build();
System.out.println("From XML"+XmlFormat.printToString(msg));
long endDate=System.currentTimeMillis();
System.out.println("Time Taken: "+(endDate-startDate));
System.out.println("-Done-");
}
private static String readFileAsString(String filePath) throws IOException
{
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
}
Here is the Output of program:
toXMl <Person><name>as</name><id>1</id><email>a</email></Person>
From XML<Person><name>Deepak</name><id>1</id><email>a</email></Person>
Time Taken: 745
-Done-
Hope it will be useful for other members.