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.
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!!");
}
}
While performing mail merge using Java, new line characters are converted into space in Microsoft Word.So line breaks are lost after merge.Need to retain the line breaks in the text in MicrosoftWord after the merge is done.
Java code to perform mailmerge using IXDocReport:
package sample;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
public class Sample {
public static void main(String[] args) throws Exception{
// 1) Load ODT file and set Velocity template engine and cache it to the registry
InputStream in= new FileInputStream(new File("sample.docx"));
IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
// 2) Create Java model context
IContext context = report.createContext();
context.put("name", "new \n world");
// 3) Generate report by merging Java model with the ODT
OutputStream out = new FileOutputStream(new File("ODTHelloWordWithVelocity_Out.docx"));
report.process(context, out);
}
}
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.
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?
I need to generate SVG from given DXF file. I try to archive that by using kabeja package. This is the code that they gave on their web page.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.xml.sax.ContentHandler;
import org.kabeja.dxf.DXFDocument;
import org.kabeja.parser.DXFParseException;
import org.kabeja.parser.Parser;
import org.kabeja.parser.ParserBuilder;
import org.kabeja.svg.SVGGenerator;
import org.kabeja.xml.SAXGenerator;
public class MyClass{
public MyClass(){
...
}
public void parseFile(String sourceFile) {
Parser parser = ParserBuilder.createDefaultParser();
try {
parser.parse(new FileInputStream(sourceFile));
DXFDocument doc = parser.getDocument();
//the SVG will be emitted as SAX-Events
//see org.xml.sax.ContentHandler for more information
ContentHandler myhandler = new ContentHandlerImpl();
//the output - create first a SAXGenerator (SVG here)
SAXGenerator generator = new SVGGenerator();
//setup properties
generator.setProperties(new HashMap());
//start the output
generator.generate(doc,myhandler);
} catch (DXFParseException e) {
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
Hear is the code that provided by the kabeja development group on sourceforge web site. But in above code I noticed that some of the classes are missing on their new package. for example
ContentHandler myhandler = new ContentHandlerImpl();
In this line it create contentHandlerImpl object but with new kabeja package it dosn't have that class.So because of this it doesn't generate SVG file. So could some one explain me how to archive my target by using this package.
Try to read symbol ContentHandlerImpl not found from kabeja's forum