I've seen the answers provided [here] (Formatting XML file using StAX) and [here] (merge XML using STAX XMLStreamWriter)
In both cases it did not work. In both cases it was because my IDE, netbeans, doesn't recognize the methods as valid. This is driving me crazy. thanks in advance for your help.
Here's the code that doesn't work, I'm simply trying to wrap my writer in an IndentingWriter.
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
XMLEventWriter writer = null;
try {
writer = outputFactory
.createXMLEventWriter(new FileOutputStream(args[1]), "UTF-8");
writer = new IndentingXMLEventWriter(writer);
} catch (XMLStreamException ex) {
Logger.getLogger(XMLReader.class.getName()).log(Level.SEVERE, null, ex);
}
Here is a list of my imports:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.StringTokenizer;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
XMLOutputFactory.createXMLEventWriter has another signature, where it accepts a Writer instead of an OutputStream. If you use that, you can use the append method to add a newline wherever you want (shown here with a StringWriter, but should work for other types of Writers as well):
StringWriter outputXml = new StringWriter();
XMLEventWriter eventWriter = factory.createXMLEventWriter(outputXml);
XMLEvent event = eventFactory.createStartDocument();
eventWriter.add(event);
eventWriter.flush(); // important!
outputXml.append("\n"); // add newline after XML declaration
You can even output stuff inside XML elements, not just necessarily in between elements. This can come handy if you need to emit some legacy or non-standard XML format.
Related
I am developing a project which needs a docx file to be converted to pdf. I found same question already posted and used the code which was provided by "Kishan C S". It uses docx4J2.8.1
The code is working fine , pdf is generated but only problem I am facing is that the docx file contains logo.jpg (images header part) which are not converted. Only textual format is converted to pdf.
I am posting the code which I have used. Please let me know what how can I solve the problem
P.S: link I referred Convert docx file into PDF with Java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFont;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
public class DocxConverter {
public static void main(String[] args) throws FileNotFoundException, Docx4JException, Exception {
InputStream is = new FileInputStream(new File("D:\\Test\\C_IN0004_AppointmentLetter.docx"));
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);
List sections = wordMLPackage.getDocumentModel().getSections();
for (int i = 0; i < sections.size(); i++) {
wordMLPackage.getDocumentModel().getSections().get(i).getPageDimensions();
}
Mapper fontMapper = new IdentityPlusMapper();
PhysicalFont font = PhysicalFonts.getPhysicalFonts().get("Comic Sans MS");//set your desired font
fontMapper.getFontMappings().put("Algerian", font);
wordMLPackage.setFontMapper(fontMapper);
PdfSettings pdfSettings = new PdfSettings();
org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);
//To turn off logger
List<Logger> loggers = Collections.<Logger> list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for (Logger logger : loggers) {
logger.setLevel(Level.OFF);
}
OutputStream out = new FileOutputStream(new File("D:\\Test\\C_IN0004_AppointmentLetter.pdf"));
conversion.output(out, pdfSettings);
System.out.println("DONE!!");
}
}
I'm in a part of an application where I have an access to the XmlStreamReader which is representing the XML file needed to be fully read into a String.
Is there a way to obtain the XML content without building another XmlStreamReader or using another stream on the file?
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
private String getOuterXml(XMLStreamReader xmlr) throws TransformerConfigurationException,
TransformerFactoryConfigurationError, TransformerException
{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringWriter stringWriter = new StringWriter();
transformer.transform(new StAXSource(xmlr), new StreamResult(stringWriter));
return stringWriter.toString();
}
I have a code that parses through XML files, edits them and saves them (using dom for this). Now, I have a few files which have the .ftl extension. I have managed to process the ftl file with given answers (using freemarker template configuration) , However, I am unable to save the edited xml back as an FTL.
All of this is in Java. Any suggestions on how I can achieve the saving aspect of the problem?
Again, I want to process, edit and then save an FTL file in Java.
I am appending the code that I have for processing the ftl file.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FTLReader {
public static void main(String[] args) {
//Freemarker configuration object
Configuration cfg = new Configuration();
try {
//Load template from source folder
Template template = cfg.getTemplate(filename);
// Build the data-model
Map<String,Object> data = new HashMap<String,Object>();
JsonParser parser = new JsonParser();
//write code to get answers
Object obj = parser.parse(new FileReader("src/answers.txt"));
JsonObject jsonObject = (JsonObject) obj;
data.put("element1", jsonObject.get("element1"));
// Console output
Writer out = new OutputStreamWriter(System.out);
template.process(data, out);
out.flush();
/*write code to edit and save the ftl file
*
*
*
*
* */
// File output (the processed FTL file)
Writer file = new FileWriter (new File("C:\\FTL_helloworld.txt"));
template.process(data, file);
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}
After reading your question and comments few times, I am probably finally getting to grasp what you are aiming to. So, you have to "patch" the file behind the filename variable from the start of your code (Template template = cfg.getTemplate(filename);). FTL file is basically a text file, so you can process it line by line. Then you must re-initialize your template with the new file content, i.e. do template = cfg.getTemplate(filename); again.
Am trying to read the qrcode from a image file uploaded from a jsp file. To read QRcode i have used zxing jars.
code from
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class GenerateQRCode {
public String readQRCode(String filePath, String charset)
throws FileNotFoundException, IOException, NotFoundException {
Hashtable hintMap = new Hashtable();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
new BufferedImageLuminanceSource( ImageIO.read(new FileInputStream(filePath)))));
**Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap, hintMap);**
return qrCodeResult.getText();
}
}
This is the method where am trying to get the qrcode value in the string "result".
String result = rr.readQRCode(tmpFile.getCanonicalPath(), "UTF-8");
the following error is thrown in the above called method at the bold line.
com.google.zxing.NotFoundException
already i find the repetition of the same question in stackoverflow.
http://stackoverflow.com/questions/27770665/error-when-decoding-qr-code
but no proper response for it. Will this code work. or should i look for alternative. I have completed the code for generating a qrcode. reading the code from a file is the issue with zxing.
I had similar problem and I found this https://github.com/zxing/zxing/issues/216
You should put PURE_BARCODE hints. So, your code should be
// ...
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.put(DecodeHintType.PURE_BARCODE, true);
Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap, hints);
return qrCodeResult.getText();
// ...
I am trying to train en-ner-location.bin file using opennlp in java The thing is i got the training text file in the following format
<START:location> Fontana <END>
<START:location> Palo Verde <END>
<START:location> Picacho <END>
and i trained the file using the following code
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Collections;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.NameSample;
import opennlp.tools.namefind.NameSampleDataStream;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.tokenize.Tokenizer;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.Span;
public class TrainNames {
#SuppressWarnings("deprecation")
public void TrainNames() throws IOException{
File fileTrainer=new File("citytrain.txt");
File output=new File("en-ner-location.bin");
ObjectStream<String> lineStream = new PlainTextByLineStream(new FileInputStream(fileTrainer), "UTF-8");
ObjectStream<NameSample> sampleStream = new NameSampleDataStream(lineStream);
System.out.println("lineStream = " + lineStream);
TokenNameFinderModel model = NameFinderME.train("en", "location", sampleStream, Collections.<String, Object>emptyMap(), 1, 0);
BufferedOutputStream modelOut = null;
try {
modelOut = new BufferedOutputStream(new FileOutputStream(output));
model.serialize(modelOut);
} finally {
if (modelOut != null)
modelOut.close();
}
}
}
I got no errors or warnings but when i try to get a city name from a string like this cnt="John is planning to specialize in Electrical Engineering in UC Fontana and pursue a career with IBM."; It returns the whole string
anybody could tell me why...??
Welcome to SO! Looks like you need more context around each location annotation. I believe right now openNLP thinks you are training it to find words (any word) because your training data has only one word. You need to annotate locations within whole sentences and you will need at least a few hundred samples to start seeing good results.
See this answer as well:
How I train an Named Entity Recognizer identifier in OpenNLP?