Java Code Examples for org.jdom.output.Format

The following are top voted examples for showing how to use org.jdom.output.Format. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: My-Javaweb-Homework   File: XMLOutputUtil.java   Source Code and License 8 votes vote down vote up
public void doOutput(List<StudentEntity> students){
	  	Element root = new Element("students");  
        Document document = new Document(root);  
        Iterator<StudentEntity> iter = students.iterator();
        while(iter.hasNext()){
        	StudentEntity student = iter.next();
        	Element studentEl = new Element("student");
        	studentEl.addContent(new Element("studentnumber").setText(student.getStudentNumber()));
        	studentEl.addContent(new Element("studentname").setText(student.getStudentName()));
        	studentEl.addContent(new Element("major").setText(student.getMajor()));
        	studentEl.addContent(new Element("grade").setText(student.getGrade()));
        	studentEl.addContent(new Element("classname").setText(student.getClassName()));
        	studentEl.addContent(new Element("gender").setText(student.getGender()));
        	root.addContent(studentEl);
        }
        try {
	        XMLOutputter out = new XMLOutputter();  
            Format f = Format.getPrettyFormat();  
            f.setEncoding("UTF-8");
            out.setFormat(f);  
            out.output(document, new FileOutputStream(outputFile)); 
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
}
 
Example 2
Project: pathvisio   File: GpmlFormat2010a.java   Source Code and License 7 votes vote down vote up
/**
 * Writes the JDOM document to the outputstream specified
 * @param out	the outputstream to which the JDOM document should be writed
 * @param validate if true, validate the dom structure before writing. If there is a validation error,
 * 		or the xsd is not in the classpath, an exception will be thrown.
 * @throws ConverterException
 */
public void writeToXml(Pathway pwy, OutputStream out, boolean validate) throws ConverterException {
	Document doc = createJdom(pwy);
	
	//Validate the JDOM document
	if (validate) validateDocument(doc);
	//			Get the XML code
	XMLOutputter xmlcode = new XMLOutputter(Format.getPrettyFormat());
	Format f = xmlcode.getFormat();
	f.setEncoding("UTF-8");
	f.setTextMode(Format.TextMode.PRESERVE);
	xmlcode.setFormat(f);

	try
	{
		//Send XML code to the outputstream
		xmlcode.output(doc, out);
	}
	catch (IOException ie)
	{
		throw new ConverterException(ie);
	}
}
 
Example 3
Project: pathvisio   File: GpmlFormat2013a.java   Source Code and License 7 votes vote down vote up
/**
 * Writes the JDOM document to the outputstream specified
 * @param out	the outputstream to which the JDOM document should be writed
 * @param validate if true, validate the dom structure before writing. If there is a validation error,
 * 		or the xsd is not in the classpath, an exception will be thrown.
 * @throws ConverterException
 */
public void writeToXml(Pathway pwy, OutputStream out, boolean validate) throws ConverterException {
	Document doc = createJdom(pwy);
	
	//Validate the JDOM document
	if (validate) validateDocument(doc);
	//			Get the XML code
	XMLOutputter xmlcode = new XMLOutputter(Format.getPrettyFormat());
	Format f = xmlcode.getFormat();
	f.setEncoding("UTF-8");
	f.setTextMode(Format.TextMode.PRESERVE);
	xmlcode.setFormat(f);

	try
	{
		//Send XML code to the outputstream
		xmlcode.output(doc, out);
	}
	catch (IOException ie)
	{
		throw new ConverterException(ie);
	}
}
 
Example 4
Project: tibco-bwmaven   File: IncludeDependenciesInEARMojo.java   Source Code and License 7 votes vote down vote up
private void updateAlias(String includeOrigin, String includeDestination, File ear) throws JDOMException, IOException, JDOMException {
	TFile xmlTIBCO = new TFile(ear.getAbsolutePath() + File.separator + "TIBCO.xml");
	String tempPath = ear.getParentFile().getAbsolutePath() + File.separator + "TIBCO.xml";
	TFile xmlTIBCOTemp = new TFile(tempPath);

	truezip.copyFile(xmlTIBCO, xmlTIBCOTemp);

	File xmlTIBCOFile = new File(tempPath);

	SAXBuilder sxb = new SAXBuilder();
	Document document = sxb.build(xmlTIBCOFile);

	XPath xpa = XPath.newInstance("//dd:NameValuePairs/dd:NameValuePair[starts-with(dd:name, 'tibco.alias') and dd:value='" + includeOrigin + "']/dd:value");
	xpa.addNamespace("dd", "http://www.tibco.com/xmlns/dd");

	Element singleNode = (Element) xpa.selectSingleNode(document);
	if (singleNode != null) {
		singleNode.setText(includeDestination);
		XMLOutputter xmlOutput = new XMLOutputter();
		xmlOutput.setFormat(Format.getPrettyFormat().setIndent("    "));
		xmlOutput.output(document, new FileWriter(xmlTIBCOFile));

		truezip.copyFile(xmlTIBCOTemp, xmlTIBCO);
	}

	updateAliasInPARs(includeOrigin, includeDestination, ear);
}
 
Example 5
Project: eurocarbdb   File: GeneratorDefault.java   Source Code and License 7 votes vote down vote up
/**
 * @param t_objdb
 * @param string
 * @throws IOException 
 * @throws SQLException 
 */
public void export(DBInterface a_objDB, String a_strFileName) throws IOException, SQLException 
{
    this.m_objDB = a_objDB;
    // Erzeugung eines XML-Dokuments
    Document t_objDocument = new Document();
    // Erzeugung des Root-XML-Elements 
    Element t_objRoot = new Element("defaults");
    Namespace xsiNS = Namespace.getNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");        
    t_objRoot.addNamespaceDeclaration(xsiNS);
    this.exportResidues(t_objRoot);
    this.exportPersubstitutions(t_objRoot);
    this.exportIons(t_objRoot);
    this.exportDericatisation(t_objRoot);
    this.exportMolecules(t_objRoot);
    // Und jetzt haengen wir noch das Root-Element an das Dokument
    t_objDocument.setRootElement(t_objRoot);
    // Damit das XML-Dokument schoen formattiert wird holen wir uns ein Format
    Format t_objFormat = Format.getPrettyFormat();
    t_objFormat.setEncoding("iso-8859-1");
    // Erzeugung eines XMLOutputters dem wir gleich unser Format mitgeben
    XMLOutputter t_objExportXML = new XMLOutputter(t_objFormat);
    // Schreiben der XML-Datei in einen String
    FileWriter t_objWriter = new FileWriter(a_strFileName);
    t_objExportXML.output(t_objDocument, t_objWriter );
}
 
Example 6
Project: crystalvc   File: XMLTools.java   Source Code and License 7 votes vote down vote up
public static boolean writeXMLDocument(Document doc, String fName) throws FileNotFoundException {
	// Assert.assertNotNull(doc);
	if (doc == null)
	    _log.error("null document");
	else {
	    final long start = System.currentTimeMillis();
	    FileOutputStream fos = new FileOutputStream(fName);
	    try {
	        XMLOutputter outputter = new XMLOutputter();
	        outputter.setFormat(Format.getPrettyFormat());
	        outputter.output(doc, fos);
	        return true;
	    } catch (IOException ioe) {
	        _log.error(ioe);
	    }
	    _log.trace("Document written to " + fName + " in: " + TimeUtility.msToHumanReadableDelta(start));
	}
	return false;
}
 
Example 7
Project: THINK-VPL   File: SaveFileIO.java   Source Code and License 7 votes vote down vote up
static void write(File file) throws FileNotFoundException, IOException{
	Document document = new Document();
	Element root = new Element("document");
	root.setAttribute("version", Main.VERSION_ID);
	for(Blueprint bp : Main.blueprints){
		
		Element blueprint = writeGraphEditor(bp);
		
		for(VFunction f : bp.getFunctions()){
			blueprint.addContent(writeGraphEditor(f.getEditor()));
		}
		
		root.addContent(blueprint);
	}
	document.setRootElement(root);
	XMLOutputter output = new XMLOutputter();
	Format format = Format.getPrettyFormat();//getRawFormat();
	format.setOmitDeclaration(true);
	format.setOmitEncoding(true);
	format.setTextMode(TextMode.PRESERVE);
	output.setFormat(format);
	output.output(document, new FileOutputStream(file));
}
 
Example 8
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 7 votes vote down vote up
/**
 *
 * @param message
 *            the String to extract the list of collections from and assumes
 *            that you are passing in a single invocation message.
 * @return an array of Strings representing all of the fully 'wrapped'
 *         collections in the message.
 * @throws MobyException
 *             if the the element contains an invalid BioMOBY message
 */
public static String[] getListOfCollections(String message)
		throws MobyException {
	Element element = getDOMDocument(message).getRootElement();
	Element[] elements = getListOfCollections(element);
	String[] strings = new String[elements.length];
	XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));
	for (int count = 0; count < elements.length; count++) {
		try {
			strings[count] = outputter.outputString(elements[count]);
		} catch (Exception e) {
			throw new MobyException(newline
					+ "Unexpected error occured while creating String[]:"
					+ newline + Utils.format(e.getLocalizedMessage(), 3));
		}
	}
	return strings;
}
 
Example 9
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 7 votes vote down vote up
/**
 * This method assumes a single invocation was passed to it
 * <p>
 *
 * @param name
 *            the article name of the simple that you are looking for
 * @param xml
 *            the xml that you want to query
 * @return a String object that represent the simple found.
 * @throws MobyException
 *             if no simple was found given the article name and/or data
 *             type or if the xml was not valid moby xml or if an unexpected
 *             error occurs.
 */
public static String getSimple(String name, String xml)
		throws MobyException {
	Element element = getDOMDocument(xml).getRootElement();
	XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));
	Element simples = getSimple(name, element);
	if (simples != null) {
		try {
			return outputter.outputString(simples);
		} catch (Exception e) {
			throw new MobyException(newline
					+ "Unexpected error occured while creating String[]:"
					+ newline + Utils.format(e.getLocalizedMessage(), 3));
		}
	}
	throw new MobyException(newline + "The simple named '" + name
			+ "' was not found in the xml:" + newline + xml + newline);
}
 
Example 10
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 7 votes vote down vote up
/**
 *
 * @param name
 *            the name of the collection to extract the simples from.
 * @param xml
 *            the XML to extract from
 * @return an array of String objects that represent the simples
 * @throws MobyException
 */
public static String[] getSimplesFromCollection(String name, String xml)
		throws MobyException {
	Element[] elements = getSimplesFromCollection(name, getDOMDocument(xml)
			.getRootElement());
	String[] strings = new String[elements.length];
	XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));
	for (int i = 0; i < elements.length; i++) {
		try {
			strings[i] = output.outputString(elements[i]);
		} catch (Exception e) {
			throw new MobyException(newline
					+ "Unknown error occured while creating String[]."
					+ newline + Utils.format(e.getLocalizedMessage(), 3));
		}
	}
	return strings;
}
 
Example 11
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 7 votes vote down vote up
/**
 *
 * @param name
 *            the name of the collection to extract the simples from.
 * @param xml
 *            the XML to extract from
 * @return an array of String objects that represent the simples, with the
 *         name of the collection
 * @throws MobyException
 *             if the collection doesnt exist or the xml is invalid
 */
public static String[] getWrappedSimplesFromCollection(String name,
		String xml) throws MobyException {
	Element[] elements = getWrappedSimplesFromCollection(name,
			getDOMDocument(xml).getRootElement());
	String[] strings = new String[elements.length];
	XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));
	for (int i = 0; i < elements.length; i++) {
		try {
			strings[i] = output.outputString(elements[i]);
		} catch (Exception e) {
			throw new MobyException(newline
					+ "Unknown error occured while creating String[]."
					+ newline + Utils.format(e.getLocalizedMessage(), 3));
		}
	}
	return strings;
}
 
Example 12
Project: itsimple   File: XMLUtilities.java   Source Code and License 7 votes vote down vote up
public static void printXML(Element element){
	Format format = Format.getPrettyFormat();
	format.setIndent("\t");
	XMLOutputter op = new XMLOutputter(format);
	if(element == null){
		System.err.println("Null element");
	}
	else{
		try {
			op.output(element, System.out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println();
	}
}
 
Example 13
Project: itsimple   File: XMLUtilities.java   Source Code and License 7 votes vote down vote up
public static void printXML(Document doc){
	Format format = Format.getPrettyFormat();
	format.setIndent("\t");
	XMLOutputter op = new XMLOutputter(format);
	if(doc == null){
		System.err.println("Null document");
	}
	else{
		try {
			op.output(doc, System.out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println();
	}
}
 
Example 14
Project: incubator-netbeans   File: NetbeansBuildActionJDOMWriterTest.java   Source Code and License 6 votes vote down vote up
public void testInsertAtPreferredLocation() throws Exception {
    NetbeansBuildActionJDOMWriter writer = new NetbeansBuildActionJDOMWriter();
    XMLOutputter xmlout = new XMLOutputter();
    xmlout.setFormat(Format.getRawFormat().setLineSeparator("\n"));
    Element p = new Element("p");
    NetbeansBuildActionJDOMWriter.Counter c = writer.new Counter(1);
    writer.insertAtPreferredLocation(p, new Element("one"), c);
    assertEquals("<p>\n    <one />\n</p>", xmlout.outputString(p));
    c.increaseCount();
    writer.insertAtPreferredLocation(p, new Element("two"), c);
    assertEquals("<p>\n    <one />\n    <two />\n</p>", xmlout.outputString(p));
    c = writer.new Counter(1);
    writer.insertAtPreferredLocation(p, new Element("zero"), c);
    assertEquals("<p>\n    <zero />\n    <one />\n    <two />\n</p>", xmlout.outputString(p));
    c.increaseCount();
    writer.insertAtPreferredLocation(p, new Element("hemi"), c);
    assertEquals("<p>\n    <zero />\n    <hemi />\n    <one />\n    <two />\n</p>", xmlout.outputString(p));
    c.increaseCount();
    c.increaseCount();
    writer.insertAtPreferredLocation(p, new Element("sesqui"), c);
    assertEquals("<p>\n    <zero />\n    <hemi />\n    <one />\n    <sesqui />\n    <two />\n</p>", xmlout.outputString(p));
    c.increaseCount();
    c.increaseCount();
    writer.insertAtPreferredLocation(p, new Element("ultimate"), c);
    assertEquals("<p>\n    <zero />\n    <hemi />\n    <one />\n    <sesqui />\n    <two />\n    <ultimate />\n</p>", xmlout.outputString(p));
    c = writer.new Counter(1);
    writer.insertAtPreferredLocation(p, new Element("initial"), c);
    assertEquals("<p>\n    <initial />\n    <zero />\n    <hemi />\n    <one />\n    <sesqui />\n    <two />\n    <ultimate />\n</p>", xmlout.outputString(p));
    // XXX indentation still not right; better to black-box test write(ActionToGoalMapping...)
}
 
Example 15
Project: gate-core   File: CreoleRegisterImpl.java   Source Code and License 6 votes vote down vote up
private void processFullCreoleXmlTree(Plugin plugin,
    Document jdomDoc, CreoleAnnotationHandler annotationHandler)
    throws GateException, IOException, JDOMException {
  // now we can process any annotations on the new classes
  // and augment the XML definition
  annotationHandler.processAnnotations(jdomDoc);

  // debugging
  if(DEBUG) {
    XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
    xmlOut.output(jdomDoc, System.out);
  }

  // finally, parse the augmented definition with the normal parser
  DefaultHandler handler =
      new CreoleXmlHandler(this, plugin);
  SAXOutputter outputter =
      new SAXOutputter(handler, handler, handler, handler);
  outputter.output(jdomDoc);
  if(DEBUG) {
    Out.prln("done parsing " + plugin);
  }
}
 
Example 16
Project: apache-maven-shade-plugin   File: PomWriter.java   Source Code and License 6 votes vote down vote up
public static void write( Writer w, Model newModel, boolean namespaceDeclaration )
    throws IOException
{
    Element root = new Element( "project" );

    if ( namespaceDeclaration )
    {
        String modelVersion = newModel.getModelVersion();

        Namespace pomNamespace = Namespace.getNamespace( "", "http://maven.apache.org/POM/" + modelVersion );

        root.setNamespace( pomNamespace );

        Namespace xsiNamespace = Namespace.getNamespace( "xsi", "http://www.w3.org/2001/XMLSchema-instance" );

        root.addNamespaceDeclaration( xsiNamespace );

        if ( root.getAttribute( "schemaLocation", xsiNamespace ) == null )
        {
            root.setAttribute( "schemaLocation",
                               "http://maven.apache.org/POM/" + modelVersion + " http://maven.apache.org/maven-v"
                                   + modelVersion.replace( '.', '_' ) + ".xsd", xsiNamespace );
        }
    }

    Document doc = new Document( root );

    MavenJDOMWriter writer = new MavenJDOMWriter();

    String encoding = newModel.getModelEncoding() != null ? newModel.getModelEncoding() : "UTF-8";

    Format format = Format.getPrettyFormat().setEncoding( encoding );

    writer.write( newModel, doc, w, format );
}
 
Example 17
Project: apache-maven-shade-plugin   File: MavenJDOMWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Method write
 *
 * @param project
 * @param stream
 * @param document
 * @deprecated
 */
public void write( Model project, Document document, OutputStream stream )
    throws java.io.IOException
{
    updateModel( project, "project", new Counter( 0 ), document.getRootElement() );
    XMLOutputter outputter = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    format.setIndent( "    " ).setLineSeparator( System.getProperty( "line.separator" ) );
    outputter.setFormat( format );
    outputter.output( document, stream );
}
 
Example 18
Project: apache-maven-shade-plugin   File: MavenJDOMWriter.java   Source Code and License 6 votes vote down vote up
/**
 * Method write
 *
 * @param project
 * @param jdomFormat
 * @param writer
 * @param document
 */
public void write( Model project, Document document, Writer writer, Format jdomFormat )
    throws java.io.IOException
{
    updateModel( project, "project", new Counter( 0 ), document.getRootElement() );
    XMLOutputter outputter = new XMLOutputter();
    outputter.setFormat( jdomFormat );
    outputter.output( document, writer );
}
 
Example 19
Project: lvm4j   File: File.java   Source Code and License 6 votes vote down vote up
/**
 * Write the HMM parameters to a xml file.
 *
 * @param hmm the markovmodel of which should be written
 * @param file  the output file
 */
public static void writeXML(HMM hmm, String file)
{
    try
    {
        _LOGGER.info("Writing markovmodel to xml.");
        Element hmmxml = new Element("markovmodel");
        Document doc = new Document(hmmxml);
        doc.setRootElement(hmmxml);

        Element meta = new Element("meta");
        hmmxml.addContent(meta);
        addMeta(hmm, meta);
        if (hmm.isTrained())
        {
            Element ortho = new Element("ortho");
            hmmxml.addContent(ortho);
            addOrtho(hmm, ortho);
        }
        XMLOutputter xmlOutput = new XMLOutputter();
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, new FileWriter(file));
    }
    catch (IOException e)
    {
        _LOGGER.error("Error when writing xmlFile: " + e.getMessage());
    }
}
 
Example 20
Project: OSCAR-ConCert   File: ExportMeasurementType.java   Source Code and License 6 votes vote down vote up
public String export (EctMeasurementTypesBean mtb){
    Element measurement = createXMLMeasurement(mtb.getType(),mtb.getTypeDesc(),mtb.getTypeDisplayName(),mtb.getMeasuringInstrc());
    
    EctValidationsBeanHandler valBeanHandler = new EctValidationsBeanHandler();
    EctValidationsBean v = valBeanHandler.getValidation(mtb.getValidationName());//(EctValidationsBean) validationRules.get(i);
    measurement.addContent(createXMLValidation(v.getName(),v.getMaxValue(),v.getMinValue(),v.getIsDate(),v.getIsNumeric(),v.getRegularExp(),v.getMaxLength(),v.getMinLength()));
    
    XMLOutputter outp = new XMLOutputter();
    outp.setFormat(Format.getPrettyFormat());
    
    return outp.outputString(measurement);      
}
 
Example 21
Project: OSCAR-ConCert   File: RuleBaseCreator.java   Source Code and License 6 votes vote down vote up
public RuleBase getRuleBase(String rulesetName, List<Element> elementRules) throws Exception {
	long timer = System.currentTimeMillis();
	try {
		Element va = new Element("rule-set");

		addAttributeifValueNotNull(va, "name", rulesetName);

		va.setNamespace(namespace);
		va.addNamespaceDeclaration(javaNamespace);
		va.addNamespaceDeclaration(xsNs);
		va.setAttribute("schemaLocation", "http://drools.org/rules rules.xsd http://drools.org/semantics/java java.xsd", xsNs);

		for (Element ele : elementRules) {
			va.addContent(ele);
		}

		XMLOutputter outp = new XMLOutputter();
		outp.setFormat(Format.getPrettyFormat());
		String ooo = outp.outputString(va);

		log.debug(ooo);
		
		RuleBase ruleBase=RuleBaseFactory.getRuleBase("RuleBaseCreator:"+ooo);
		if (ruleBase!=null) return(ruleBase);
		
		ruleBase = RuleBaseLoader.loadFromInputStream(new ByteArrayInputStream(ooo.getBytes()));
		RuleBaseFactory.putRuleBase("RuleBaseCreator:"+ooo, ruleBase);
		return ruleBase;
	} finally {
		log.debug("generateRuleBase TimeMs : " + (System.currentTimeMillis() - timer));
	}
}
 
Example 22
Project: LAS   File: Container.java   Source Code and License 6 votes vote down vote up
public String toString(Format format) {
    StringWriter xmlout = new StringWriter();
    try {
        format.setLineSeparator(System.getProperty("line.separator"));
        XMLOutputter outputter = new XMLOutputter(format);
        outputter.output(this.element, xmlout);
        // Close the FileWriter
        xmlout.close();
    } catch (java.io.IOException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    return xmlout.toString();
}
 
Example 23
Project: LAS   File: LASDocument.java   Source Code and License 6 votes vote down vote up
public String write() {
	String xml = null;
	try {
		StringWriter xmlout = new StringWriter();
		org.jdom.output.Format format = org.jdom.output.Format.getPrettyFormat();
		format.setLineSeparator(System.getProperty("line.separator"));
		XMLOutputter outputter = new XMLOutputter(format);
		outputter.output(this, xmlout);
		xml = xmlout.toString();
		xmlout.close();
		return xml;
	} catch (Exception e) {
		return null;
	}
}
 
Example 24
Project: LAS   File: IOSPDocument.java   Source Code and License 6 votes vote down vote up
/**
 * Return a pretty printed string formatted according to the JDOM Format 
 * @param format the Format object that controls the pretty printing.
 * @return the pretty printed string.
 */
public String toString(Format format) {
    StringWriter xmlout = new StringWriter();
    try {
        format.setLineSeparator(System.getProperty("line.separator"));
        XMLOutputter outputter = new XMLOutputter(format);
        outputter.output(this, xmlout);
        // Close the FileWriter
        xmlout.close();
    } catch (java.io.IOException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    return xmlout.toString();
}
 
Example 25
Project: TalkAndPlay   File: XMLConfigurationHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Write the new data to the xml file
 */
private void writeToXmlFile() throws Exception {
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());
    xmlOutput.output(configurationXmlDocument, new OutputStreamWriter(
            new FileOutputStream(new File(configurationFilePath)), "UTF-8"));
}
 
Example 26
Project: Rearranger   File: RearrangerSettings.java   Source Code and License 6 votes vote down vote up
public void writeSettingsToFile(File f)
{
    Element component = new Element("component");
    component.setAttribute("name", Rearranger.COMPONENT_NAME);
    Element r = new Element(Rearranger.COMPONENT_NAME);
    component.getChildren().add(r);
    writeExternal(r);
    Format format = Format.getPrettyFormat();
    XMLOutputter outputter = new XMLOutputter(format);
    try
    {
        final FileOutputStream fileOutputStream = new FileOutputStream(f);
        outputter.output(component, fileOutputStream);
        fileOutputStream.close();
    }
    catch (IOException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example 27
Project: zap-maven-plugin   File: AlertsFile.java   Source Code and License 6 votes vote down vote up
private static void writeAlertsToFile(File outputFile, Document doc) {

        XMLOutputter xmlOutput = new XMLOutputter();

        xmlOutput.setFormat(Format.getPrettyFormat());
        try {
            xmlOutput.output(doc, new FileWriter(outputFile));
            System.out.println("alert xml report saved to: "+outputFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 28
Project: pathvisio   File: VisualizationManager.java   Source Code and License 6 votes vote down vote up
public void saveXML() throws IOException
{
	if(!gexManager.isConnected()) return;
	
	File finalFile = getFileForDb();
	if (finalFile.exists()) finalFile.delete();
	finalFile.createNewFile();
	
	OutputStream out = new FileOutputStream(finalFile);

	Document xmlDoc = new Document();
	Element root = new Element(ROOT_XML_ELEMENT);
	xmlDoc.setRootElement(root);

	root.addContent(colorSetMgr.getXML());

	Element vis = new Element(XML_ELEMENT);
	for(Visualization v : getVisualizations()) {
		vis.addContent(v.toXML());
	}
	root.addContent(vis);

	XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
	xmlOut.output(xmlDoc, out);
	out.close();

	Logger.log.info("Saved visualizations and color sets to xml: " + finalFile);
}
 
Example 29
Project: pathvisio   File: DgpmlOutputter.java   Source Code and License 6 votes vote down vote up
public void flush() throws IOException
{
	XMLOutputter xmlcode = new XMLOutputter(Format.getPrettyFormat());
	Format f = xmlcode.getFormat();
	f.setEncoding("ISO-8859-1");
	f.setTextMode(Format.TextMode.PRESERVE);
	f.setLineSeparator(System.getProperty("line.separator"));
	xmlcode.setFormat(f);

	//Open a filewriter
	PrintWriter writer = new PrintWriter(out);
	xmlcode.output(doc, writer);
	out.flush();
}
 
Example 30
Project: intellij-ce-playground   File: JDOMUtil.java   Source Code and License 6 votes vote down vote up
@NotNull
public static XMLOutputter createOutputter(String lineSeparator) {
  XMLOutputter xmlOutputter = new MyXMLOutputter();
  Format format = Format.getCompactFormat().
    setIndent("  ").
    setTextMode(Format.TextMode.TRIM).
    setEncoding(CharsetToolkit.UTF8).
    setOmitEncoding(false).
    setOmitDeclaration(false).
    setLineSeparator(lineSeparator);
  xmlOutputter.setFormat(format);
  return xmlOutputter;
}
 
Example 31
Project: intellij-ce-playground   File: XMLOutputterTest.java   Source Code and License 6 votes vote down vote up
private String printElement(Element root) throws IOException {
  XMLOutputter xmlOutputter = JDOMUtil.createOutputter("\n");
  final Format format = xmlOutputter.getFormat().setOmitDeclaration(true).setOmitEncoding(true).setExpandEmptyElements(true);
  xmlOutputter.setFormat(format);

  CharArrayWriter writer = new CharArrayWriter();

  xmlOutputter.output(root, writer);
  String res = new String(writer.toCharArray());
  return res;
}
 
Example 32
Project: intellij   File: BlazeAndroidBinaryRunConfigurationStateTest.java   Source Code and License 6 votes vote down vote up
@Test
public void repeatedWriteShouldNotChangeElement() throws WriteExternalException {
  final XMLOutputter xmlOutputter = new XMLOutputter(Format.getCompactFormat());

  BlazeAndroidRunConfigurationCommonState commonState = state.getCommonState();
  commonState.getBlazeFlagsState().setRawFlags(ImmutableList.of("--flag1", "--flag2"));
  commonState.setNativeDebuggingEnabled(true);

  state.setActivityClass("com.example.TestActivity");
  state.setMode(BlazeAndroidBinaryRunConfigurationState.LAUNCH_SPECIFIC_ACTIVITY);
  state.setLaunchMethod(AndroidBinaryLaunchMethod.MOBILE_INSTALL);
  state.setUseSplitApksIfPossible(false);
  state.setUseWorkProfileIfPresent(true);
  state.setUserId(2);
  state.setDeepLink("http://deeplink");

  Element firstWrite = new Element("test");
  state.writeExternal(firstWrite);
  Element secondWrite = firstWrite.clone();
  state.writeExternal(secondWrite);

  assertThat(xmlOutputter.outputString(secondWrite))
      .isEqualTo(xmlOutputter.outputString(firstWrite));
}
 
Example 33
Project: intellij   File: BlazeAndroidTestRunConfigurationStateTest.java   Source Code and License 6 votes vote down vote up
@Test
public void repeatedWriteShouldNotChangeElement() throws WriteExternalException {
  final XMLOutputter xmlOutputter = new XMLOutputter(Format.getCompactFormat());

  BlazeAndroidRunConfigurationCommonState commonState = state.getCommonState();
  commonState.getBlazeFlagsState().setRawFlags(ImmutableList.of("--flag1", "--flag2"));
  commonState.setNativeDebuggingEnabled(true);

  state.setTestingType(BlazeAndroidTestRunConfigurationState.TEST_METHOD);
  state.setInstrumentationRunnerClass("com.example.TestRunner");
  state.setMethodName("fooMethod");
  state.setClassName("BarClass");
  state.setPackageName("com.test.package.name");
  state.setLaunchMethod(AndroidTestLaunchMethod.MOBILE_INSTALL);
  state.setExtraOptions("--option");

  Element firstWrite = new Element("test");
  state.writeExternal(firstWrite);
  Element secondWrite = firstWrite.clone();
  state.writeExternal(secondWrite);

  assertThat(xmlOutputter.outputString(secondWrite))
      .isEqualTo(xmlOutputter.outputString(firstWrite));
}
 
Example 34
Project: intellij   File: BlazeAndroidRunConfigurationCommonStateTest.java   Source Code and License 6 votes vote down vote up
@Test
public void repeatedWriteShouldNotChangeElement() throws WriteExternalException {
  final XMLOutputter xmlOutputter = new XMLOutputter(Format.getCompactFormat());

  state.getBlazeFlagsState().setRawFlags(ImmutableList.of("--flag1", "--flag2"));
  state.getExeFlagsState().setRawFlags(ImmutableList.of("--exe1", "--exe2"));
  state.setNativeDebuggingEnabled(true);

  Element firstWrite = new Element("test");
  state.writeExternal(firstWrite);
  Element secondWrite = firstWrite.clone();
  state.writeExternal(secondWrite);

  assertThat(xmlOutputter.outputString(secondWrite))
      .isEqualTo(xmlOutputter.outputString(firstWrite));
}
 
Example 35
Project: intellij   File: ExportRunConfigurationDialog.java   Source Code and License 6 votes vote down vote up
private static void writeConfiguration(RunConfiguration configuration, File outputFile) {
  try (FileOutputStream writer = new FileOutputStream(outputFile, false)) {
    XMLOutputter xmlOutputter = new XMLOutputter(Format.getCompactFormat());
    xmlOutputter.output(RunConfigurationSerializer.writeToXml(configuration), writer);
  } catch (IOException e) {
    throw new RuntimeException("Error exporting run configuration to file: " + outputFile);
  }
}
 
Example 36
Project: intellij   File: BlazeCommandRunConfigurationCommonStateTest.java   Source Code and License 6 votes vote down vote up
@Test
public void repeatedWriteShouldNotChangeElement() throws Exception {
  final XMLOutputter xmlOutputter = new XMLOutputter(Format.getCompactFormat());

  state.getCommandState().setCommand(COMMAND);
  state.getBlazeFlagsState().setRawFlags(ImmutableList.of("--flag1", "--flag2"));
  state.getExeFlagsState().setRawFlags(ImmutableList.of("--exeFlag1"));
  state.getBlazeBinaryState().setBlazeBinary("/usr/bin/blaze");

  Element firstWrite = new Element("test");
  state.writeExternal(firstWrite);
  Element secondWrite = firstWrite.clone();
  state.writeExternal(secondWrite);

  assertThat(xmlOutputter.outputString(secondWrite))
      .isEqualTo(xmlOutputter.outputString(firstWrite));
}
 
Example 37
Project: intellij   File: BlazeCommandRunConfigurationRunManagerImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void loadStateAndGetStateElementShouldMatchAfterChangeAndRevert() {
  final XMLOutputter xmlOutputter = new XMLOutputter(Format.getCompactFormat());
  final Label label = Label.create("//package:rule");
  configuration.setTarget(label);

  final Element initialElement = runManager.getState();
  runManager.loadState(initialElement);
  final BlazeCommandRunConfiguration modifiedConfiguration =
      (BlazeCommandRunConfiguration) runManager.getAllConfigurations()[0];
  modifiedConfiguration.setTarget(Label.create("//new:label"));

  final Element modifiedElement = runManager.getState();
  assertThat(xmlOutputter.outputString(modifiedElement))
      .isNotEqualTo(xmlOutputter.outputString(initialElement));
  runManager.loadState(modifiedElement);
  final BlazeCommandRunConfiguration revertedConfiguration =
      (BlazeCommandRunConfiguration) runManager.getAllConfigurations()[0];
  revertedConfiguration.setTarget(label);

  final Element revertedElement = runManager.getState();
  assertThat(xmlOutputter.outputString(revertedElement))
      .isEqualTo(xmlOutputter.outputString(initialElement));
}
 
Example 38
Project: intellij   File: BlazeCommandRunConfigurationRunManagerImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void getStateElementShouldMatchAfterEditorApplyToAndResetFrom()
    throws ConfigurationException {
  final XMLOutputter xmlOutputter = new XMLOutputter(Format.getCompactFormat());
  final BlazeCommandRunConfigurationSettingsEditor editor =
      new BlazeCommandRunConfigurationSettingsEditor(configuration);
  configuration.setTarget(Label.create("//package:rule"));

  final Element initialElement = runManager.getState();
  editor.resetFrom(configuration);
  editor.applyEditorTo(configuration);
  final Element newElement = runManager.getState();

  assertThat(xmlOutputter.outputString(newElement))
      .isEqualTo(xmlOutputter.outputString(initialElement));

  Disposer.dispose(editor);
}
 
Example 39
Project: intellij   File: RunConfigurationSerializerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRunConfigurationUnalteredBySerializationRoundTrip() throws InvalidDataException {
  configuration.setTarget(Label.create("//package:rule"));
  configuration.setKeepInSync(true);

  final Element initialElement = runManager.getState();

  Element element = RunConfigurationSerializer.writeToXml(configuration);
  assertThat(RunConfigurationSerializer.findExisting(getProject(), element)).isNotNull();

  clearRunManager(); // remove configuration from project
  RunConfigurationSerializer.loadFromXmlElementIgnoreExisting(getProject(), element);

  final Element newElement = runManager.getState();
  final XMLOutputter xmlOutputter = new XMLOutputter(Format.getCompactFormat());
  assertThat(xmlOutputter.outputString(newElement))
      .isEqualTo(xmlOutputter.outputString(initialElement));
}
 
Example 40
Project: tibco-bwmaven   File: IncludeDependenciesInEARMojo.java   Source Code and License 6 votes vote down vote up
private void updateAliasInPARs(String includeOrigin, String includeDestination, File ear) throws IOException, JDOMException {
	TrueZipFileSet pars = new TrueZipFileSet();
	pars.setDirectory(ear.getAbsolutePath());
	pars.addInclude("*.par");
	List<TFile> parsXML = truezip.list(pars);
	for (TFile parXML : parsXML) {
		TFile xmlTIBCO = new TFile(parXML, "TIBCO.xml");

		String tempPath = ear.getParentFile().getAbsolutePath() + File.separator + "TIBCO.xml";
		TFile xmlTIBCOTemp = new TFile(tempPath);

		truezip.copyFile(xmlTIBCO, xmlTIBCOTemp);

		File xmlTIBCOFile = new File(tempPath);

		SAXBuilder sxb = new SAXBuilder();
		Document document = sxb.build(xmlTIBCOFile);

		XPath xpa = XPath.newInstance("//dd:NameValuePairs/dd:NameValuePair[dd:name='EXTERNAL_JAR_DEPENDENCY']/dd:value");
		xpa.addNamespace("dd", "http://www.tibco.com/xmlns/dd");

		Element singleNode = (Element) xpa.selectSingleNode(document);
		if (singleNode != null) {
			String value = singleNode.getText().replace(includeOrigin, includeDestination);
			singleNode.setText(value);
			XMLOutputter xmlOutput = new XMLOutputter();
			xmlOutput.setFormat(Format.getPrettyFormat().setIndent("    "));
			xmlOutput.output(document, new FileWriter(xmlTIBCOFile));

			truezip.copyFile(xmlTIBCOTemp, xmlTIBCO);
		}
	}
}
 
Example 41
Project: kc-rice   File: TravelAccountTypeExporter.java   Source Code and License 6 votes vote down vote up
@Override
public void export(Class<?> dataObjectClass, List<? extends Object> dataObjects, String exportFormat,
        OutputStream outputStream) throws IOException, ExportNotSupportedException {
    Document document = new Document(new Element("travelAccountTypes"));

    for (Object dataObject : dataObjects) {
        Element travelAccountTypeElement = new Element("travelAccountType");
        TravelAccountType travelAccountType = (TravelAccountType) dataObject;

        Element accountTypeCodeElement = new Element("accountTypeCode");
        accountTypeCodeElement.setText(travelAccountType.getAccountTypeCode());
        travelAccountTypeElement.addContent(accountTypeCodeElement);

        Element nameElement = new Element("name");
        nameElement.setText(travelAccountType.getName());
        travelAccountTypeElement.addContent(nameElement);

        Element activeElement = new Element("active");
        activeElement.setText(Boolean.toString(travelAccountType.isActive()));
        travelAccountTypeElement.addContent(activeElement);

        document.getRootElement().addContent(travelAccountTypeElement);
    }

    XMLOutputter outputer = new XMLOutputter(Format.getPrettyFormat());
    try {
        outputer.output(document, outputStream);
    } catch (IOException e) {
        throw new RuntimeException("Could not write XML data export.", e);
    }
}
 
Example 42
Project: kc-rice   File: XmlExporterServiceImpl.java   Source Code and License 6 votes vote down vote up
public byte[] export(ExportDataSet dataSet) {
    if (dataSet == null) {
        throw new IllegalArgumentException("Xml Exporter cannot handle NULL data.");
    }
    Element rootElement = new Element(DATA_ELEMENT, WORKFLOW_NAMESPACE);
    rootElement.addNamespaceDeclaration(SCHEMA_NAMESPACE);
    rootElement.setAttribute(SCHEMA_LOCATION_ATTR, WORKFLOW_SCHEMA_LOCATION, SCHEMA_NAMESPACE);
    Document document = new Document(rootElement);
    boolean shouldPrettyPrint = true;
    for (XmlExporter exporter : xmlImpexRegistry.getExporters()) {
    	Element exportedElement = exporter.export(dataSet);
    	if (exportedElement != null) {
    		if (!exporter.supportPrettyPrint()) {
    			shouldPrettyPrint = false;
    		}
    		appendIfNotEmpty(rootElement, exportedElement);
    	}
    }

    // TODO: KULRICE-4420 - this needs cleanup
    Format f;
    if (!shouldPrettyPrint) {
        f = Format.getRawFormat();
        f.setExpandEmptyElements(false);
        f.setTextMode(Format.TextMode.PRESERVE);
    } else {
        f = Format.getPrettyFormat();
    }
    XMLOutputter outputer = new XMLOutputter(f);
    StringWriter writer = new StringWriter();
    try {
        outputer.output(document, writer);
    } catch (IOException e) {
        throw new WorkflowRuntimeException("Could not write XML data export.", e);
    }
    return writer.toString().getBytes();
}
 
Example 43
Project: eurocarbdb   File: SugarExporterGlycoCT.java   Source Code and License 6 votes vote down vote up
public String getXMLCode() throws IOException
{
    Format t_objFormat = Format.getPrettyFormat();
    XMLOutputter t_objExportXML = new XMLOutputter(t_objFormat);
    StringWriter t_objWriter = new StringWriter();
    t_objExportXML.output(this.m_objDocument, t_objWriter );
    return t_objWriter.toString();
}
 
Example 44
Project: eurocarbdb   File: GeneratorFragment.java   Source Code and License 6 votes vote down vote up
/**
 * @param t_objdb
 * @param string
 * @throws IOException 
 * @throws SQLException 
 */
public void export(DBInterface a_objDB, String a_strFileName) throws IOException, SQLException 
{
    this.m_objDB = a_objDB;
    // Erzeugung eines XML-Dokuments
    Document t_objDocument = new Document();
    // Erzeugung des Root-XML-Elements 
    Element t_objRoot = new Element("fragments");
    Namespace xsiNS = Namespace.getNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");        
    t_objRoot.addNamespaceDeclaration(xsiNS);
    this.exportAX(t_objRoot);
    this.exportOthers(t_objRoot);
    // Und jetzt haengen wir noch das Root-Element an das Dokument
    t_objDocument.setRootElement(t_objRoot);
    // Damit das XML-Dokument schoen formattiert wird holen wir uns ein Format
    Format t_objFormat = Format.getPrettyFormat();
    t_objFormat.setEncoding("iso-8859-1");
    // Erzeugung eines XMLOutputters dem wir gleich unser Format mitgeben
    XMLOutputter t_objExportXML = new XMLOutputter(t_objFormat);
    // Schreiben der XML-Datei in einen String
    FileWriter t_objWriter = new FileWriter(a_strFileName);
    t_objExportXML.output(t_objDocument, t_objWriter );
}
 
Example 45
Project: eurocarbdb   File: CalcParameterXml.java   Source Code and License 6 votes vote down vote up
/** 
 * Exports a parameter object to an XML string
 * 
 * @param t_objSetting
 * @return XML-string
 * @throws IOException
 */
public String exportParameter(CalculationParameter t_objSetting) throws IOException
{
    // Erzeugung eines XML-Dokuments
    Document t_objDocument = new Document();
    // Erzeugung des Root-XML-Elements 
    Element t_objRoot = new Element("glycopeakfinder_calculation");
    Namespace xsiNS = Namespace.getNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");        
    t_objRoot.addNamespaceDeclaration(xsiNS);
    t_objRoot.setAttribute(new Attribute("noNamespaceSchemaLocation",this.m_strFile, xsiNS));
    // write Settings to element
    this.exportParameter(t_objRoot, t_objSetting);
    // Und jetzt haengen wir noch das Root-Element an das Dokument
    t_objDocument.setRootElement(t_objRoot);
    // Damit das XML-Dokument schoen formattiert wird holen wir uns ein Format
    Format t_objFormat = Format.getPrettyFormat();
    t_objFormat.setEncoding("iso-8859-1");
    // Erzeugung eines XMLOutputters dem wir gleich unser Format mitgeben
    XMLOutputter t_objExportXML = new XMLOutputter(t_objFormat);
    // Schreiben der XML-Datei in einen String
    StringWriter t_objWriter = new StringWriter();
    t_objExportXML.output(t_objDocument, t_objWriter );
    return t_objWriter.toString();
}
 
Example 46
Project: gitdep-maven-plugin   File: PomHandler.java   Source Code and License 6 votes vote down vote up
public void write() throws IOException {
	final XMLOutputter xml = new XMLOutputter(Format.getPrettyFormat());
	final OutputStream output = new FileOutputStream(pom.getFile());

	try {
		xml.output(pom.getDocument(), output);
	} finally {
		output.close();
	}
}
 
Example 47
Project: fosstrak-fc   File: SerializerUtil.java   Source Code and License 6 votes vote down vote up
/**
 * ORANGE: This method serializes a ADD_ROSPEC to an xml and writes it into a file.
 * @param addRoSpec containing the ADD_ROSPEC to be written into a file
 * @param pathName the file where to store
 * @throws IOException whenever an io problem occurs
 */
public static void serializeAddROSpec(ADD_ROSPEC addRoSpec, String pathName) throws IOException {
	try {
		Document document = addRoSpec.encodeXML();
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
		outputter.output(document, new FileOutputStream(pathName));
	} catch (InvalidLLRPMessageException e) {
		log.error("could not serialize AddROSpec:", e);
	}
}
 
Example 48
Project: fosstrak-fc   File: SerializerUtil.java   Source Code and License 6 votes vote down vote up
/**
 * ORANGE: This method serializes a ADD_ROSPEC to an xml and writes it into a file.
 * @param roSpec containing the ADD_ROSPEC to be written into a file
 * @param writer to write the xml into
 * @throws IOException whenever an io problem occurs
 */
public static void serializeAddROSpec(ADD_ROSPEC addRoSpec, Writer writer) throws IOException {
	try {
		Document document = addRoSpec.encodeXML();
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
		outputter.output(document, writer);
	} catch (InvalidLLRPMessageException e) {
		log.error("could not serialize AddROSpec:", e);
	}
}
 
Example 49
Project: petablox   File: XMLFactory.java   Source Code and License 6 votes vote down vote up
/**
 * Dumps the given element as an XML document to the given writer.
 * 
 * @param out  output writer
 * @param e  element to write
 */
public static void dumpXML(Writer out, Element e) throws IOException {
    Document d = new Document(e);
    XMLOutputter serializer = new XMLOutputter();
    serializer.setFormat(Format.getPrettyFormat());
    serializer.output(d, out);
}
 
Example 50
Project: BART   File: SaveEGTask.java   Source Code and License 6 votes vote down vote up
private void saveDOM(Document doc,File file) throws IOException  {
    BufferedWriter out = null;
    FileWriter fw = null;
    try{
        fw = new FileWriter(file);
        out = new BufferedWriter(fw);
        XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
        xmlOut.output(doc, out);
    }catch(IOException ioex)   {
        log.log(Level.SEVERE, "saveDOM", ioex);
        throw ioex;
    }finally{
        if(fw != null)   {
            fw.close();
        }
        if(out != null)   {
            out.close();
        }         
        log.fine("SaveDOM close resource");
    }
}
 
Example 51
Project: tellervo   File: XMLBody.java   Source Code and License 6 votes vote down vote up
@Override
public void writeTo(OutputStream out) throws IOException {
       if (out == null) {
           throw new IllegalArgumentException("Output stream may not be null");
       }
      	XMLOutputter outp = new XMLOutputter();
      	outp.setFormat(pretty ? Format.getPrettyFormat() : Format.getCompactFormat());
       	
      	outp.output(in, out);        	
       out.flush();
	
}
 
Example 52
Project: tellervo   File: XMLDebug.java   Source Code and License 6 votes vote down vote up
public static void dumpDocument(Document d) {
	XMLOutputter xmlo = new XMLOutputter();
	xmlo.setFormat(Format.getPrettyFormat());
	
	try {
		xmlo.output(d, System.out);
	} catch(Exception e) {}
}
 
Example 53
Project: tellervo   File: XMLDebug.java   Source Code and License 6 votes vote down vote up
public static void dumpElement(Element d) {
	XMLOutputter xmlo = new XMLOutputter();
	xmlo.setFormat(Format.getPrettyFormat());
	
	try {
		xmlo.output(d, System.out);
	} catch(Exception e) {}
}
 
Example 54
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param message
 *            the String of xml to extract the list of simples from. This
 *            method assumes that you are passing in a single invokation and
 *            that you wish to extract the Simples not contained in any
 *            collections. This method also maintains any past queryIDs.
 * @return an array of Strings that represent fully 'wrapped' simples.
 * @throws MobyException
 *             if the String doesnt contain a structurally valid Moby
 *             message structure or if an unexpected error occurs
 */
public static String[] getListOfSimples(String message)
		throws MobyException {
	Element element = getDOMDocument(message).getRootElement();
	Element[] elements = getListOfSimples(element);
	String[] strings = new String[elements.length];
	XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));
	for (int count = 0; count < elements.length; count++) {
		try {
			strings[count] = outputter.outputString(elements[count]);
		} catch (Exception e) {
			throw new MobyException(newline
					+ "Unexpected error occured while creating String[]:"
					+ newline + Utils.format(e.getLocalizedMessage(), 3));
		}
	}
	return strings;
}
 
Example 55
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param name
 * @param xml
 * @return
 * @throws MobyException
 */
public static String getCollection(String name, String xml)
		throws MobyException {
	Element element = getDOMDocument(xml).getRootElement();
	XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));
	Element collection = getCollection(name, element);
	if (collection != null)
		return outputter.outputString(collection);
	return null;
}
 
Example 56
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param name
 * @param xml
 * @return
 * @throws MobyException
 */
public static String getWrappedCollection(String name, String xml)
		throws MobyException {
	Element element = getWrappedCollection(name, getDOMDocument(xml)
			.getRootElement());
	XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));
	return outputter.outputString(element);
}
 
Example 57
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param name
 *            the name of the simples that you would like to extract. The
 *            name can be collection name as well. This method extracts
 *            simples from all invocation messages.
 * @param xml
 *            the xml to extract the simples from
 * @return a String[] of Simples that you are looking for, taken from
 *         collections with your search name as well as simple elements with
 *         the search name
 * @throws MobyException
 *             if there is a problem with the BioMOBY message
 */
public static String[] getAllSimplesByArticleName(String name, String xml)
		throws MobyException {
	Element[] elements = getAllSimplesByArticleName(name, getDOMDocument(
			xml).getRootElement());
	String[] strings = new String[elements.length];
	XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));
	for (int i = 0; i < elements.length; i++) {
		try {
			strings[i] = output.outputString(elements[i]);
		} catch (Exception e) {
			throw new MobyException(newline
					+ "Unknown error occured while creating String[]."
					+ newline + Utils.format(e.getLocalizedMessage(), 3));
		}
	}
	return strings;
}
 
Example 58
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param xml
 *            the XML to extract from
 * @return an array of String objects that represent the simples
 * @throws MobyException
 */
public static String[] getSimplesFromCollection(String xml)
		throws MobyException {
	Element[] elements = getSimplesFromCollection(getDOMDocument(xml)
			.getRootElement());
	String[] strings = new String[elements.length];
	XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));
	for (int i = 0; i < elements.length; i++) {
		try {
			strings[i] = output.outputString(elements[i]);
		} catch (Exception e) {
			throw new MobyException(newline
					+ "Unknown error occured while creating String[]."
					+ newline + Utils.format(e.getLocalizedMessage(), 3));
		}
	}
	return strings;
}
 
Example 59
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param xml
 *            the message to extract the invocation messages from
 * @return an array of String objects each representing a distinct BioMOBY
 *         invocation message.
 * @throws MobyException
 *             if the moby message is invalid or if the xml is syntatically
 *             invalid.
 */
public static String[] getSingleInvokationsFromMultipleInvokations(
		String xml) throws MobyException {
	Element[] elements = getSingleInvokationsFromMultipleInvokations(getDOMDocument(
			xml).getRootElement());
	String[] strings = new String[elements.length];
	XMLOutputter output = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));

	for (int i = 0; i < elements.length; i++) {
		strings[i] = output.outputString(new Document(elements[i]));
	}
	return strings;
}
 
Example 60
Project: incubator-taverna-plugin-bioinformatics   File: XMLUtilities.java   Source Code and License 6 votes vote down vote up
public static String createMobyDataElementWrapper(String xml,
		String queryID, Element serviceNotes) throws MobyException {
	if (xml == null)
		return null;
	Element element = createMobyDataElementWrapper(getDOMDocument(xml)
			.getRootElement(), queryID, serviceNotes);
	XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()
			.setOmitDeclaration(false));
	return (element == null ? null : outputter.outputString(element));
}