Java Code Examples for org.jdom.output.XMLOutputter#output()

The following examples show how to use org.jdom.output.XMLOutputter#output() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LazyGraphGroupSaveableXML.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
/**
 * Overridden to create the {@link Element} to save at the time saving is taking place, 
 * instead of construction time.
 * 
 * @param objStorage The object into which the data will be placed.
 */
public void save(ObjectStorage objStorage) {
	Element groupVertexElement = GroupVertexSerializer.getXMLForGroupedVertices(functionGraph);
	Document document = new Document(groupVertexElement);
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	XMLOutputter xmlOutputter = new GenericXMLOutputter();

	try {
		xmlOutputter.output(document, outputStream);
	}
	catch (IOException ioe) {
		// shouldn't happen, as we are using our output stream
		Msg.error(getClass(), "Unable to save XML data.", ioe);
		return;
	}

	String xmlString = outputStream.toString();
	objStorage.putString(xmlString);
}
 
Example 2
Source File: OvalFileAggregator.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Finalizes processing and builds the aggregated document
 * @param prettyPrint pretty print XML or not
 * @return XML in string form
 * @throws IOException document output failed
 */
public String finish(boolean prettyPrint) throws IOException {
    if (!isFinished && !isEmpty()) {
        buildDocument();
        isFinished = true;
    }
    if (isEmpty()) {
        return "";
    }
    XMLOutputter out = new XMLOutputter();
    if (prettyPrint) {
        out.setFormat(Format.getPrettyFormat());
    }
    else {
        out.setFormat(Format.getCompactFormat());
    }
    StringWriter buffer = new StringWriter();
    out.output(aggregate, buffer);
    String retval = buffer.toString();
    retval = retval.replaceAll(" xmlns:oval=\"removeme\"", "");
    return retval.replaceAll(" xmlns:redhat=\"removeme\"", "");
}
 
Example 3
Source File: VTSubToolManager.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private void saveSubordinateToolConfig(PluginTool t) {
	String toolName = t.getName();
	String toolFileName = toolName + ".tool";
	File toolFile = new File(ToolUtils.getApplicationToolDirPath(), toolFileName);

	try {
		OutputStream os = new FileOutputStream(toolFile);
		Document doc = new Document(t.getToolTemplate(true).saveToXml());
		XMLOutputter xmlOut = new GenericXMLOutputter();
		xmlOut.output(doc, os);
		os.close();
	}
	catch (IOException e) {
		Msg.showError(this, t.getToolFrame(), "Version Tracking",
			"Failed to save source tool configuration\nFile: " + toolName + "\n" +
				e.getMessage());
	}
	t.setConfigChanged(false);
}
 
Example 4
Source File: VTMatchSetTableDBAdapterV0.java    From ghidra with Apache License 2.0 6 votes vote down vote up
private String getOptionsString(VTProgramCorrelator correlator) {
	ToolOptions options = correlator.getOptions();
	if (options.getOptionNames().isEmpty()) {
		return null;
	}
	Element optionsElement = options.getXmlRoot(true);

	XMLOutputter xmlout = new GenericXMLOutputter();
	StringWriter writer = new StringWriter();
	try {
		xmlout.output(optionsElement, writer);
		return writer.toString();
	}
	catch (IOException ioe) {
	}
	return null;
}
 
Example 5
Source File: CreoleRegisterImpl.java    From gate-core with GNU Lesser General Public License v3.0 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 6
Source File: AbstractSamlObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Convert the received jdom doc to a Document element.
 *
 * @param doc the doc
 * @return the org.w3c.dom. document
 */
private org.w3c.dom.Document toDom(final Document doc) {
    try {
        final XMLOutputter xmlOutputter = new XMLOutputter();
        final StringWriter elemStrWriter = new StringWriter();
        xmlOutputter.output(doc, elemStrWriter);
        final byte[] xmlBytes = elemStrWriter.toString().getBytes(Charset.defaultCharset());
        final DocumentBuilderFactory dbf = DocumentBuilderFactory
                .newInstance();
        dbf.setNamespaceAware(true);
        return dbf.newDocumentBuilder().parse(
                new ByteArrayInputStream(xmlBytes));
    } catch (final Exception e) {
        logger.trace(e.getMessage(), e);
        return null;
    }
}
 
Example 7
Source File: ToolServicesImpl.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public File exportTool(ToolTemplate tool) throws FileNotFoundException, IOException {

	File location = chooseToolFile(tool);
	if (location == null) {
		return location; // user cancelled
	}

	String filename = location.getName();
	if (!filename.endsWith(ToolUtils.TOOL_EXTENSION)) {
		filename = filename + ToolUtils.TOOL_EXTENSION;
	}

	try (FileOutputStream f =
		new FileOutputStream(location.getParent() + File.separator + filename)) {
		BufferedOutputStream bf = new BufferedOutputStream(f);
		Document doc = new Document(tool.saveToXml());
		XMLOutputter xmlout = new GenericXMLOutputter();
		xmlout.output(doc, bf);
	}

	return location;
}
 
Example 8
Source File: WriteXMLFile.java    From maven-framework-project with MIT License 5 votes vote down vote up
public static void main(String[] args) {
 
  try {

	Element company = new Element("company");
	Document doc = new Document(company);
	doc.setRootElement(company);

	Element staff = new Element("staff");
	staff.setAttribute(new Attribute("id", "1"));
	staff.addContent(new Element("firstname").setText("yong"));
	staff.addContent(new Element("lastname").setText("mook kim"));
	staff.addContent(new Element("nickname").setText("mkyong"));
	staff.addContent(new Element("salary").setText("199999"));

	doc.getRootElement().addContent(staff);

	Element staff2 = new Element("staff");
	staff2.setAttribute(new Attribute("id", "2"));
	staff2.addContent(new Element("firstname").setText("low"));
	staff2.addContent(new Element("lastname").setText("yin fong"));
	staff2.addContent(new Element("nickname").setText("fong fong"));
	staff2.addContent(new Element("salary").setText("188888"));

	doc.getRootElement().addContent(staff2);

	// new XMLOutputter().output(doc, System.out);
	XMLOutputter xmlOutput = new XMLOutputter();

	// display nice nice
	xmlOutput.setFormat(Format.getPrettyFormat());
	xmlOutput.output(doc, new FileWriter("target/file.xml"));

	System.out.println("File Saved!");
  } catch (IOException io) {
	System.out.println(io.getMessage());
  }
}
 
Example 9
Source File: XMLModelFile.java    From beast-mcmc with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void print(XMLOutputter outputter, OutputStream ostream) {
    try {
        outputter.output(xmlModel.getContent(), ostream);
    }
    catch (IOException e) {
        System.err.println("Error writing model!");
    }
}
 
Example 10
Source File: RenderingFilterManagerImp.java    From jivejdon with Apache License 2.0 5 votes vote down vote up
private String createProperties() {
	StringWriter writer = new StringWriter();
	try {
		logger.debug("enter createProperties ....");
		Document doc = new Document(new Element("jiveFilters"));
		Element filterClasses = new Element("filterClasses");
		doc.getRootElement().addContent(filterClasses);
		// Add in default list of available filter classes.
		for (int i = 0; i < renderingAvailableFilters.getAvailableFilterClassNames().length; i++) {
			Element newClass = new Element("filter" + i);
			newClass.setText(renderingAvailableFilters.getAvailableFilterClassNames()[i]);
			filterClasses.addContent(newClass);
		}

		// Set default global filters -- HTML and Newline
		Element defaultFilters = new Element("global");
		doc.getRootElement().addContent(defaultFilters);
		defaultFilters.addContent(new Element("filterCount").addContent(Integer.toString(DEFAULT_FILTER_CLASSES.length)));
		for (int i = 0; i < DEFAULT_FILTER_CLASSES.length; i++) {
			Element filter = new Element("filter" + i);
			filter.addContent(new Element("className").addContent(DEFAULT_FILTER_CLASSES[i]));
			defaultFilters.addContent(filter);
		}

		// Use JDOM's XMLOutputter to do the writing and formatting.
		XMLOutputter outputter = new XMLOutputter();
		outputter.output(doc, writer);

	} catch (Exception e) {
		logger.error(e);
	}
	return writer.toString();
}
 
Example 11
Source File: JDOMUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static void writeElementToStreamPretty(final Element e, final OutputStream os) {
  try {
    final BufferedOutputStream bos = new BufferedOutputStream(os);

    final Document document = new Document((Element) e.clone());
    final XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());

    outputter.output(document, bos);

    bos.flush();
  } catch (final IOException ioe) {
    LOGGER.info("write error", ioe);
  }
}
 
Example 12
Source File: ExportRunConfigurationDialog.java    From intellij with Apache License 2.0 5 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 13
Source File: XmlJotter.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Retrieves a string representation of a document in either indented or raw format.
 *
 * @param document the document
 * @param indent   whether to use indented or raw format
 * @return document as a string
 */
public static String jotDocument(org.jdom.Document document, boolean indent) {
    XMLOutputter outputer = new XMLOutputter(getJdomFormat(indent));
    StringWriter writer = new StringWriter();
    try {
        outputer.output(document, writer);
    } catch (IOException e) {
        throw new XmlException("Could not write XML data export.", e);
    }
    return writer.toString();
}
 
Example 14
Source File: JDOMUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static String writeElementToString(final Element e) {
  try {
    final StringWriter sw = new StringWriter();
    final Document document = new Document((Element) e.clone());
    final XMLOutputter outputter = new XMLOutputter();

    outputter.output(document, sw);

    return sw.getBuffer().toString();
  } catch (final IOException ioe) {
    LOGGER.info("write error", ioe);
  }

  return null;
}
 
Example 15
Source File: AntigenicPlotter.java    From beast-mcmc with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
     * Discrete KML
     * @param fileName
     * @param labels
     * @param data
     * @param clusterIndices
     * @param clusterSizes
     */
    private void writeKML(String fileName, String[] labels, double[][][] data, int[][] clusterIndices, int[][] clusterSizes) {
        int[] traceOrder = sortTraces(labels);

        Element traceSchema = new Element("Schema");
        traceSchema.setAttribute("id", "Cluster_Schema");
        traceSchema.addContent(new Element("SimpleField")
                .setAttribute("name", "Label")
                .setAttribute("type", "string")
                .addContent(new Element("displayName").addContent("Label")));
        traceSchema.addContent(new Element("SimpleField")
                .setAttribute("name", "Number")
                .setAttribute("type", "double")
                .addContent(new Element("displayName").addContent("Number")));
        traceSchema.addContent(new Element("SimpleField")
                .setAttribute("name", "Year")
                .setAttribute("type", "double")
                .addContent(new Element("displayName").addContent("Year")));
        traceSchema.addContent(new Element("SimpleField")
                .setAttribute("name", "State")
                .setAttribute("type", "double")
                .addContent(new Element("displayName").addContent("State")));

        Element virusSchema = new Element("Schema");
        virusSchema.setAttribute("id", "Virus_Schema");
        virusSchema.addContent(new Element("SimpleField")
                .setAttribute("name", "Label")
                .setAttribute("type", "string")
                .addContent(new Element("displayName").addContent("Label")));
        virusSchema.addContent(new Element("SimpleField")
                .setAttribute("name", "Year")
                .setAttribute("type", "double")
                .addContent(new Element("displayName").addContent("Year")));
        virusSchema.addContent(new Element("SimpleField")
                .setAttribute("name", "Trace")
                .setAttribute("type", "double")
                .addContent(new Element("displayName").addContent("Trace")));

//        final Element contourFolderElement = new Element("Folder");
//        Element contourFolderNameElement = new Element("name");
//        contourFolderNameElement.addContent("HPDs");
//        contourFolderElement.addContent(contourFolderNameElement);

        final Element traceFolderElement = new Element("Folder");
        Element traceFolderNameElement = new Element("name");
        traceFolderNameElement.addContent("traces");
        traceFolderElement.addContent(traceFolderNameElement);

        final Element clustersFolderElement = new Element("Folder");
        Element clustersFolderNameElement = new Element("name");
        clustersFolderNameElement.addContent("clusters");
        clustersFolderElement.addContent(clustersFolderNameElement);

        Element documentNameElement = new Element("name");
        String documentName = fileName;
        if (documentName.endsWith(".kml"))
            documentName = documentName.replace(".kml", "");
        documentNameElement.addContent(documentName);

        final Element documentElement = new Element("Document");
        documentElement.addContent(documentNameElement);
        documentElement.addContent(traceSchema);
        documentElement.addContent(virusSchema);
//        documentElement.addContent(hpdSchema);
        documentElement.addContent(clustersFolderElement);
        documentElement.addContent(traceFolderElement);
//        documentElement.addContent(contourFolderElement);

        final Element rootElement = new Element("kml");
        rootElement.addContent(documentElement);

        Element traceElement = generateTraceElement(labels, data, traceOrder);
        traceFolderElement.addContent(traceElement);

        Element clustersElement = generateClusterElement(labels, data, clusterIndices, clusterSizes, traceOrder);
        clustersFolderElement.addContent(clustersElement);

//        Element contourElement = generateKDEElement(0.95, labels, data, traceOrder);
//        contourFolderElement.addContent(contourElement);

        PrintStream resultsStream;

        try {
            resultsStream = new PrintStream(new File(fileName));
            XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat().setTextMode(Format.TextMode.PRESERVE));
            xmlOutputter.output(rootElement, resultsStream);

        } catch (IOException e) {
            System.err.println("Error opening file: " + fileName);
            System.exit(-1);
        }
    }
 
Example 16
Source File: LibrarySymbolTable.java    From ghidra with Apache License 2.0 4 votes vote down vote up
void write(File output, File input, String lversion) throws IOException {
	Element root = new Element("LIBRARY");

	root.setAttribute("NAME", tableName);
	root.setAttribute("PATH", input.getAbsolutePath());
	long lastModifiedSeconds = (input.lastModified() / 1000) * 1000; // file time in seconds
	root.setAttribute("DATE", TIMESTAMP_FORMAT.format(new Date(lastModifiedSeconds)));
	root.setAttribute("VERSION", lversion);

	Iterator<LibraryExportedSymbol> iter = exportList.iterator();
	while (iter.hasNext()) {
		LibraryExportedSymbol sym = iter.next();

		Element export = new Element("EXPORT");

		export.setAttribute("ORDINAL", sym.getOrdinal() + "");
		export.setAttribute("NAME", sym.getName() == null ? "" : sym.getName());
		export.setAttribute("PURGE", sym.getPurge() + "");
		export.setAttribute("COMMENT", sym.getComment() == null ? "" : sym.getComment());

		if (sym.hasNoReturn()) {
			export.setAttribute("NO_RETURN", "y");
		}

		if (sym.isFowardEntry()) {
			export.setAttribute("FOWARDLIBRARY",
				sym.getFowardLibraryName() == null ? "" : sym.getFowardLibraryName());
			export.setAttribute("FOWARDSYMBOL",
				sym.getFowardSymbolName() == null ? "" : sym.getFowardSymbolName());
		}
		root.addContent(export);
	}

	FileOutputStream fos = new FileOutputStream(output);
	try {
		Document doc = new Document(root);

		XMLOutputter xmlout = new GenericXMLOutputter();
		xmlout.output(doc, fos);
	}
	finally {
		fos.close();
	}

	//StringBuffer buffer = new StringBuffer();
	//Iterator iter = exportList.iterator();
	//while (iter.hasNext()) {
	//    LibraryExportedSymbol sym = (LibraryExportedSymbol) iter.next();
	//
	//    buffer.append(sym.getOrdinal());
	//    buffer.append("\t");
	//    buffer.append(sym.getName());
	//    buffer.append("\t");
	//    buffer.append(sym.getPurge());
	//    buffer.append("\t");
	//    buffer.append(sym.getComment());
	//    buffer.append("\n");
	//}
	//PrintWriter writer = new PrintWriter(new FileOutputStream(file));
	//try {
	//    writer.println(buffer.toString());
	//}
	//finally {
	//    writer.flush();
	//    writer.close();
	//}
}
 
Example 17
Source File: PCodeTestCombinedTestResults.java    From ghidra with Apache License 2.0 4 votes vote down vote up
void saveToXml() throws IOException {

		File dir = xmlFile.getParentFile();
		if (!dir.exists() && !dir.mkdir()) {
			throw new IOException("Failed to created directory: " + dir);
		}

		Element root = new Element("PCODE_TESTS");
		root.setAttribute("VERSION", XML_VERSION);

		for (String name : combinedResults.keySet()) {
			PCodeTestResults testResults = combinedResults.get(name);
			root.addContent(testResults.saveToXml());
		}

		// Store checkout data in temporary file
		File tmpFile = new File(xmlFile.getParentFile(), xmlFile.getName() + ".new");
		tmpFile.delete();
		FileOutputStream ostream = new FileOutputStream(tmpFile);
		BufferedOutputStream bos = new BufferedOutputStream(ostream);

		try {
			Document doc = new Document(root);
			XMLOutputter xmlout = new GenericXMLOutputter();
			xmlout.output(doc, bos);
		}
		finally {
			bos.close();
		}

		// Rename files
		File oldFile = null;
		if (xmlFile.exists()) {
			oldFile = new File(xmlFile.getParentFile(), xmlFile.getName() + ".bak");
			oldFile.delete();
			if (!xmlFile.renameTo(oldFile)) {
				throw new IOException("Failed to update: " + xmlFile.getAbsolutePath());
			}
		}
		if (!tmpFile.renameTo(xmlFile)) {
			if (oldFile != null) {
				oldFile.renameTo(xmlFile);
			}
			throw new IOException("Failed to update: " + xmlFile.getAbsolutePath());
		}

		Msg.info(this, "XML results file updated: " + xmlFile.getAbsolutePath());

		if (oldFile != null) {
			oldFile.delete();
		}
	}
 
Example 18
Source File: CheckoutManager.java    From ghidra with Apache License 2.0 4 votes vote down vote up
/**
 * Write checkout data file.
 * 
 * @throws IOException
 */
private void writeCheckoutsFile() throws IOException {

	// Output checkouts as XML
	Element root = new Element("CHECKOUT_LIST");
	root.setAttribute("NEXT_ID", Long.toString(nextCheckoutId));

	for (ItemCheckoutStatus status : checkouts.values()) {
		// TRANSIENT checkout data must not be persisted - the existence
		// of such checkouts is retained in-memory only
		if (status.getCheckoutType() != CheckoutType.TRANSIENT) {
			root.addContent(getCheckoutElement(status));
		}
	}

	File checkoutsFile = getCheckoutsFile();

	// Store checkout data in temporary file
	File tmpFile = new File(checkoutsFile.getParentFile(), checkoutsFile.getName() + ".new");
	tmpFile.delete();
	FileOutputStream ostream = new FileOutputStream(tmpFile);
	BufferedOutputStream bos = new BufferedOutputStream(ostream);

	try {
		Document doc = new Document(root);
		XMLOutputter xmlout = new GenericXMLOutputter();
		xmlout.output(doc, bos);
	}
	finally {
		bos.close();
	}

	// Rename files
	File oldFile = null;
	if (checkoutsFile.exists()) {
		oldFile = new File(checkoutsFile.getParentFile(), checkoutsFile.getName() + ".bak");
		oldFile.delete();
		if (!checkoutsFile.renameTo(oldFile)) {
			throw new IOException("Failed to update checkouts: " + item.getPathName());
		}
	}
	if (!tmpFile.renameTo(checkoutsFile)) {
		if (oldFile != null) {
			oldFile.renameTo(checkoutsFile);
		}
		throw new IOException("Failed to update checkouts: " + item.getPathName());
	}
	if (oldFile != null) {
		oldFile.delete();
	}
}
 
Example 19
Source File: NetbeansBuildActionJDOMWriter.java    From netbeans with Apache License 2.0 3 votes vote down vote up
/**
 * Method write.
 * 
 * @param actions
 * @param jdomFormat
 * @param writer
 * @param document
 * @throws java.io.IOException
 */
public void write(ActionToGoalMapping actions, Document document, Writer writer, Format jdomFormat)
    throws java.io.IOException
{
    updateActionToGoalMapping(actions, "actions", new Counter(0), document.getRootElement());
    XMLOutputter outputter = new XMLOutputter();
    outputter.setFormat(jdomFormat);
    outputter.output(document, writer);
}
 
Example 20
Source File: XmlUtilities.java    From ghidra with Apache License 2.0 3 votes vote down vote up
/**
 * Writes a JDOM XML {@link Document} to a {@link File}.
 * <p>
 * 
 * @param doc JDOM XML {@link Document} to write.
 * @param dest {@link File} to write to.
 * @throws IOException if error when writing file.
 */
public static void writeDocToFile(Document doc, File dest) throws IOException {
	XMLOutputter outputter = new XMLOutputter();
	try (FileWriter fw = new FileWriter(dest)) {
		outputter.output(doc, fw);
	}
}