Java Code Examples for javax.xml.transform.sax.TransformerHandler#getTransformer()

The following examples show how to use javax.xml.transform.sax.TransformerHandler#getTransformer() . 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: TransformerPool.java    From iaf with Apache License 2.0 5 votes vote down vote up
public TransformerHandler getTransformerHandler() throws TransformerConfigurationException {
      TransformerHandler handler = ((SAXTransformerFactory)tFactory).newTransformerHandler(templates);
      Transformer transformer = handler.getTransformer();
      transformer.setErrorListener(new TransformerErrorListener());
		// Set URIResolver on transformer for Xalan. Setting it on the factory
		// doesn't work for Xalan. See
		// https://www.oxygenxml.com/archives/xsl-list/200306/msg00021.html
      transformer.setURIResolver(classLoaderURIResolver);
      return handler;
}
 
Example 2
Source File: XSLTTransformer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
protected void setSAXConsumer(final SAXConsumer consumer) {
    TransformerHandler transformerHandler;
    try {
        transformerHandler = TRAX_FACTORY.newTransformerHandler(this.templates);
    } catch (Exception e) {
        throw new SetupException("Could not initialize transformer handler.", e);
    }

    if (this.parameters != null) {
        final Transformer transformer = transformerHandler.getTransformer();

        this.parameters.forEach((name, values) -> {
            // is valid XSLT parameter name
            if (XSLT_PARAMETER_NAME_PATTERN.matcher(name).matches()) {
                transformer.setParameter(name, values);
            }
        });
    }

    final SAXResult result = new SAXResult();
    result.setHandler(consumer);
    // According to TrAX specs, all TransformerHandlers are LexicalHandlers
    result.setLexicalHandler(consumer);
    transformerHandler.setResult(result);

    final SAXConsumerAdapter saxConsumerAdapter = new SAXConsumerAdapter();
    saxConsumerAdapter.setContentHandler(transformerHandler);
    super.setSAXConsumer(saxConsumerAdapter);
}
 
Example 3
Source File: AbstractFilterFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TransformerHandler newRAFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException,
        IOException {
    TransformerHandler retval = getTransformerHandler(getRAXsl());
    Transformer xformer = retval.getTransformer();
    xformer.setParameter("ra_min_hr", String.valueOf(min));
    xformer.setParameter("ra_max_hr", String.valueOf(max));
    return retval;
}
 
Example 4
Source File: AbstractFilterFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TransformerHandler newDECFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException,
        IOException {
    TransformerHandler retval = getTransformerHandler(getDECXsl());
    Transformer xformer = retval.getTransformer();
    xformer.setParameter("dec_min_deg", String.valueOf(min));
    xformer.setParameter("dec_max_deg", String.valueOf(max));
    return retval;
}
 
Example 5
Source File: AbstractFilterFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TransformerHandler newRADECFilter(double rmin, double rmax, double dmin, double dmax) throws TransformerConfigurationException, SAXException,
        ParserConfigurationException, IOException {
    TransformerHandler retval = getTransformerHandler(getRADECXsl());
    Transformer xformer = retval.getTransformer();
    xformer.setParameter("ra_min_hr", String.valueOf(rmin));
    xformer.setParameter("ra_max_hr", String.valueOf(rmax));
    xformer.setParameter("dec_min_deg", String.valueOf(dmin));
    xformer.setParameter("dec_max_deg", String.valueOf(dmax));
    return retval;
}
 
Example 6
Source File: AbstractFilterFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TransformerHandler newStellarTypeFilter(String type) throws TransformerConfigurationException, SAXException, ParserConfigurationException,
        IOException {
    TransformerHandler retval = getTransformerHandler(getStellarXsl());
    Transformer xformer = retval.getTransformer();
    xformer.setParameter("type", type);
    return retval;
}
 
Example 7
Source File: MCRXSLTransformer.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
protected LinkedList<TransformerHandler> getTransformHandlerList(MCRParameterCollector parameterCollector)
    throws TransformerConfigurationException, SAXException, ParserConfigurationException {
    checkTemplateUptodate();
    LinkedList<TransformerHandler> xslSteps = new LinkedList<>();
    //every transformhandler shares the same ErrorListener instance
    MCRErrorListener errorListener = MCRErrorListener.getInstance();
    for (Templates template : templates) {
        TransformerHandler handler = tFactory.newTransformerHandler(template);
        parameterCollector.setParametersTo(handler.getTransformer());
        handler.getTransformer().setErrorListener(errorListener);
        if (TRACE_LISTENER_ENABLED) {
            TransformerImpl transformer = (TransformerImpl) handler.getTransformer();
            TraceManager traceManager = transformer.getTraceManager();
            try {
                traceManager.addTraceListener(TRACE_LISTENER);
            } catch (TooManyListenersException e) {
                LOGGER.warn("Could not add MCRTraceListener.", e);
            }
        }
        if (!xslSteps.isEmpty()) {
            Result result = new SAXResult(handler);
            xslSteps.getLast().setResult(result);
        }
        xslSteps.add(handler);
    }
    return xslSteps;
}
 
Example 8
Source File: XmlSerializer.java    From ganttproject with GNU General Public License v3.0 5 votes vote down vote up
protected TransformerHandler createHandler(String xsltPath) throws TransformerConfigurationException {
  TransformerHandler result = getTransformerFactory().newTransformerHandler(new StreamSource(xsltPath));
  Transformer transformer = result.getTransformer();
  transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
  return result;
}
 
Example 9
Source File: SaverBase.java    From ganttproject with GNU General Public License v3.0 5 votes vote down vote up
protected TransformerHandler createHandler(Result result) throws TransformerConfigurationException {
  SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
  TransformerHandler handler = factory.newTransformerHandler();
  Transformer serializer = handler.getTransformer();
  serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.METHOD, "xml");
  serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
  handler.setResult(result);
  return handler;
}
 
Example 10
Source File: RawDataFileSaveHandler.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copy the data points file of the raw data file from the temporary folder to the zip file.
 * Create an XML file which contains the description of the same raw data file an copy it into the
 * same zip file.
 * 
 * @param rawDataFile raw data file to be copied
 * @param rawDataSavedName name of the raw data inside the zip file
 * @throws java.io.IOException
 * @throws TransformerConfigurationException
 * @throws SAXException
 */
void writeRawDataFile(RawDataFileImpl rawDataFile, int number)
    throws IOException, TransformerConfigurationException, SAXException {

  numOfScans = rawDataFile.getNumOfScans();

  // Get the structure of the data points file
  dataPointsOffsets = rawDataFile.getDataPointsOffsets();
  dataPointsLengths = rawDataFile.getDataPointsLengths();
  consolidatedDataPointsOffsets = new TreeMap<Integer, Long>();

  // step 1 - save data file
  logger.info("Saving data points of: " + rawDataFile.getName());

  String rawDataSavedName = "Raw data file #" + number + " " + rawDataFile.getName();

  zipOutputStream.putNextEntry(new ZipEntry(rawDataSavedName + ".scans"));

  // We save only those data points that still have a reference in the
  // dataPointsOffset table. Some deleted mass lists may still be present
  // in the data points file, we don't want to copy those.
  long newOffset = 0;
  byte buffer[] = new byte[1 << 20];
  RandomAccessFile dataPointsFile = rawDataFile.getDataPointsFile();
  for (Integer storageID : dataPointsOffsets.keySet()) {

    if (canceled)
      return;

    final long offset = dataPointsOffsets.get(storageID);
    dataPointsFile.seek(offset);

    final int bytes = dataPointsLengths.get(storageID) * 4 * 2;
    consolidatedDataPointsOffsets.put(storageID, newOffset);
    if (buffer.length < bytes) {
      buffer = new byte[bytes * 2];
    }
    dataPointsFile.read(buffer, 0, bytes);
    zipOutputStream.write(buffer, 0, bytes);
    newOffset += bytes;
    progress = 0.9 * ((double) offset / dataPointsFile.length());
  }

  if (canceled)
    return;

  // step 2 - save raw data description
  logger.info("Saving raw data description of: " + rawDataFile.getName());

  zipOutputStream.putNextEntry(new ZipEntry(rawDataSavedName + ".xml"));
  OutputStream finalStream = zipOutputStream;

  StreamResult streamResult = new StreamResult(finalStream);
  SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

  TransformerHandler hd = tf.newTransformerHandler();
  Transformer serializer = hd.getTransformer();
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

  hd.setResult(streamResult);
  hd.startDocument();
  saveRawDataInformation(rawDataFile, hd);
  hd.endDocument();
}
 
Example 11
Source File: XSLTEntityHandler.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public ContentHandler getOutputHandler(OutputStream out) throws IOException
{
	if (!isAvailable()) return null;

	try
	{
		XSLTTransform xsltTransform = (XSLTTransform) transformerHolder.get();
		if (xsltTransform == null)
		{
			xsltTransform = new XSLTTransform();
			xsltTransform.setXslt(new InputSource(this.getClass()
					.getResourceAsStream(xslt)));
			transformerHolder.set(xsltTransform);
		}
		SAXResult sr = new SAXResult();
		
		TransformerHandler th = xsltTransform.getContentHandler();
		
		Transformer transformer = th.getTransformer();
		if (transformParameters != null) {
			for (Map.Entry<String, String> entry: transformParameters.entrySet()) {
				transformer.setParameter(entry.getKey(), entry.getValue());
			}
		}

		Properties p = OutputPropertiesFactory.getDefaultMethodProperties("xml");
		p.putAll(outputProperties);
		
		/*
		S_KEY_CONTENT_HANDLER:{http://xml.apache.org/xalan}content-handler
			S_KEY_ENTITIES:{http://xml.apache.org/xalan}entities
			S_KEY_INDENT_AMOUNT:{http://xml.apache.org/xalan}indent-amount
			S_OMIT_META_TAG:{http://xml.apache.org/xalan}omit-meta-tag
			S_USE_URL_ESCAPING:{http://xml.apache.org/xalan}use-url-escaping
		*/
		
		Serializer s = SerializerFactory.getSerializer(p);
		s.setOutputStream(out);
		sr.setHandler(s.asContentHandler());
		th.setResult(sr);
		return th;
	}
	catch (Exception ex)
	{
		throw new RuntimeException("Failed to create Content Handler", ex); //$NON-NLS-1$
		/*
		 * String stackTrace = null; try { StringWriter exw = new
		 * StringWriter(); PrintWriter pw = new PrintWriter(exw);
		 * log.error(ex.getMessage(), ex); stackTrace = exw.toString(); } catch
		 * (Exception ex2) { stackTrace =
		 * MessageFormat.format(defaultStackTrace, new Object[] {
		 * ex.getMessage() }); } out.write(MessageFormat.format(errorFormat,
		 * new Object[] { ex.getMessage(), stackTrace }));
		 */
	}
}
 
Example 12
Source File: XmlWriter.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Creates output XML from all read records using SAX.
 * Call this after all records are stored in PortDefinition structures.  
 * @throws TransformerConfigurationException
 * @throws SAXException
 * @throws IOException
 */
/*
private void flushXmlSax() throws TransformerConfigurationException, SAXException, IOException {

	FileOutputStream fos = new FileOutputStream(fileUrl);
	TransformerHandler hd = createHeader(fos);
	PortDefinition portDefinition = rootPortDefinition;
	// for each record of port
	for (Map.Entry<HashKey, TreeRecord> e : portDefinition.dataMap.entrySet()){
		TreeRecord record = e.getValue();
		List<DataRecord> records = new ArrayList<DataRecord>();
		records.add(record.record);
		addRecords(hd, records, portDefinition);
	}// for record

	createFooter(fos, hd);
}*/

private TransformerHandler createHeader(OutputStream os) throws FileNotFoundException, TransformerConfigurationException, SAXException {
	StreamResult streamResult = new StreamResult(os);
	SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
	// SAX2.0 ContentHandler.
	TransformerHandler hd = tf.newTransformerHandler();
	Transformer serializer = hd.getTransformer();
       
	serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
	serializer.setOutputProperty(OutputKeys.ENCODING, this.charset);
	//serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
	if (omitNewLines)
		serializer.setOutputProperty(OutputKeys.INDENT,"no");
	else
		serializer.setOutputProperty(OutputKeys.INDENT,"yes");
	
	hd.setResult(streamResult);
	hd.startDocument();

	String root = (rootElement!=null && rootElement.length()>0) ? rootElement : DEFAULT_ROOT_ELEMENT; 

	if (useRootElement && dtdPublicId != null && dtdPublicId.trim().length()>0 && dtdSystemId != null && dtdSystemId.trim().length()>0){
		hd.startDTD(root, dtdPublicId, dtdSystemId);
		hd.endDTD();
	}
	
	//if (recordsPerFile!=1){
	if (this.useRootElement) {
		AttributesImpl atts = new AttributesImpl();
		if (rootInfoAttributes) {
			atts.addAttribute("", ATTRIBUTE_COMPONENT_ID, ATTRIBUTE_COMPONENT_ID, "CDATA", getId());
			atts.addAttribute("", ATTRIBUTE_GRAPH_NAME, ATTRIBUTE_GRAPH_NAME, "CDATA", this.getGraph().getName());
			atts.addAttribute("", ATTRIBUTE_CREATED, ATTRIBUTE_CREATED, "CDATA", (new Date()).toString());
		}
		if (!StringUtils.isEmpty(xsdSchemaLocation)) {
			atts.addAttribute(XSI_URI, "schemaLocation", "xsi:schemaLocation", "CDATA", this.xsdSchemaLocation);
		}

		for (String prefix : namespaces.keySet()) {
			String uri = namespaces.get(prefix);
			hd.startPrefixMapping(prefix, uri);
		}
		if (!rootDefaultNamespace.isEmpty()) {
			hd.startPrefixMapping("", rootDefaultNamespace);
		}

		hd.startElement(rootDefaultNamespace, getLocalName(root), root, atts);
	}
	return hd;
}
 
Example 13
Source File: XSLTEntityHandler.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public ContentHandler getOutputHandler(OutputStream out) throws IOException
{
	if (!isAvailable()) return null;

	try
	{
		XSLTTransform xsltTransform = (XSLTTransform) transformerHolder.get();
		if (xsltTransform == null)
		{
			xsltTransform = new XSLTTransform();
			xsltTransform.setXslt(new InputSource(this.getClass()
					.getResourceAsStream(xslt)));
			transformerHolder.set(xsltTransform);
		}
		SAXResult sr = new SAXResult();
		
		TransformerHandler th = xsltTransform.getContentHandler();
		
		Transformer transformer = th.getTransformer();
		if (transformParameters != null) {
			for (Map.Entry<String, String> entry: transformParameters.entrySet()) {
				transformer.setParameter(entry.getKey(), entry.getValue());
			}
		}

		Properties p = OutputPropertiesFactory.getDefaultMethodProperties("xml");
		p.putAll(outputProperties);
		
		/*
		S_KEY_CONTENT_HANDLER:{http://xml.apache.org/xalan}content-handler
			S_KEY_ENTITIES:{http://xml.apache.org/xalan}entities
			S_KEY_INDENT_AMOUNT:{http://xml.apache.org/xalan}indent-amount
			S_OMIT_META_TAG:{http://xml.apache.org/xalan}omit-meta-tag
			S_USE_URL_ESCAPING:{http://xml.apache.org/xalan}use-url-escaping
		*/
		
		Serializer s = SerializerFactory.getSerializer(p);
		s.setOutputStream(out);
		sr.setHandler(s.asContentHandler());
		th.setResult(sr);
		return th;
	}
	catch (Exception ex)
	{
		throw new RuntimeException("Failed to create Content Handler", ex); //$NON-NLS-1$
		/*
		 * String stackTrace = null; try { StringWriter exw = new
		 * StringWriter(); PrintWriter pw = new PrintWriter(exw);
		 * log.error(ex.getMessage(), ex); stackTrace = exw.toString(); } catch
		 * (Exception ex2) { stackTrace =
		 * MessageFormat.format(defaultStackTrace, new Object[] {
		 * ex.getMessage() }); } out.write(MessageFormat.format(errorFormat,
		 * new Object[] { ex.getMessage(), stackTrace }));
		 */
	}
}
 
Example 14
Source File: RawDataFileSaveHandler.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copy the data points file of the raw data file from the temporary folder to the zip file.
 * Create an XML file which contains the description of the same raw data file an copy it into the
 * same zip file.
 * 
 * @param rawDataFile raw data file to be copied
 * @param rawDataSavedName name of the raw data inside the zip file
 * @throws java.io.IOException
 * @throws TransformerConfigurationException
 * @throws SAXException
 */
void writeRawDataFile(RawDataFileImpl rawDataFile, int number)
    throws IOException, TransformerConfigurationException, SAXException {

  numOfScans = rawDataFile.getNumOfScans();

  // Get the structure of the data points file
  dataPointsOffsets = rawDataFile.getDataPointsOffsets();
  dataPointsLengths = rawDataFile.getDataPointsLengths();
  consolidatedDataPointsOffsets = new TreeMap<Integer, Long>();

  // step 1 - save data file
  logger.info("Saving data points of: " + rawDataFile.getName());

  String rawDataSavedName = "Raw data file #" + number + " " + rawDataFile.getName();

  zipOutputStream.putNextEntry(new ZipEntry(rawDataSavedName + ".scans"));

  // We save only those data points that still have a reference in the
  // dataPointsOffset table. Some deleted mass lists may still be present
  // in the data points file, we don't want to copy those.
  long newOffset = 0;
  byte buffer[] = new byte[1 << 20];
  RandomAccessFile dataPointsFile = rawDataFile.getDataPointsFile();
  for (Integer storageID : dataPointsOffsets.keySet()) {

    if (canceled)
      return;

    final long offset = dataPointsOffsets.get(storageID);
    dataPointsFile.seek(offset);

    final int bytes = dataPointsLengths.get(storageID) * 4 * 2;
    consolidatedDataPointsOffsets.put(storageID, newOffset);
    if (buffer.length < bytes) {
      buffer = new byte[bytes * 2];
    }
    dataPointsFile.read(buffer, 0, bytes);
    zipOutputStream.write(buffer, 0, bytes);
    newOffset += bytes;
    progress = 0.9 * ((double) offset / dataPointsFile.length());
  }

  if (canceled)
    return;

  // step 2 - save raw data description
  logger.info("Saving raw data description of: " + rawDataFile.getName());

  zipOutputStream.putNextEntry(new ZipEntry(rawDataSavedName + ".xml"));
  OutputStream finalStream = zipOutputStream;

  StreamResult streamResult = new StreamResult(finalStream);
  SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

  TransformerHandler hd = tf.newTransformerHandler();
  Transformer serializer = hd.getTransformer();
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

  hd.setResult(streamResult);
  hd.startDocument();
  saveRawDataInformation(rawDataFile, hd);
  hd.endDocument();
}
 
Example 15
Source File: SAXGenerator.java    From AndroidPixelDimenGenerator with Apache License 2.0 4 votes vote down vote up
public void generate(Values values) throws IOException {
    File dimenFile = values.dimenFile;
    FileOutputStream fos = new FileOutputStream(dimenFile);
    StreamResult result = new StreamResult(fos);
    SAXTransformerFactory sff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler th = null;
    try {
        th = sff.newTransformerHandler();
        Transformer transformer = th.getTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        th.setResult(result);

        th.startDocument();

        AttributesImpl attr = new AttributesImpl();
        char[] space = "\n".toCharArray();
        th.characters(space, 0, space.length);
        th.startElement("", "", "resources", attr);

        List<Dimen> dimens = values.dimens;
        char[] spaceChar = "\n    ".toCharArray();
        for (Dimen dimen : dimens) {
            //white space
            th.characters(spaceChar, 0, spaceChar.length);
            //name attr
            attr.addAttribute("", "", "name", String.class.getName(), dimen.name);
            th.startElement("", "", "dimen", attr);
            char[] valueChars = String.format("%spx", dimen.value).toCharArray();
            th.characters(valueChars, 0, valueChars.length);
            th.endElement("", "", "dimen");
        }

        th.endElement("", "", "resources");
        th.endDocument();

    } catch (TransformerConfigurationException | SAXException e) {
        e.printStackTrace();
    } finally {
        fos.close();
    }
}
 
Example 16
Source File: XmlTools.java    From MyBox with Apache License 2.0 4 votes vote down vote up
public static void iccHeaderXml(LinkedHashMap<String, Object> header, File file) {
    if (header == null || file == null) {
        return;
    }
    try {
        SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler handler = sf.newTransformerHandler();
        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        Result result = new StreamResult(new BufferedOutputStream(new FileOutputStream(file)));
        handler.setResult(result);
        handler.startDocument();
        AttributesImpl attr = new AttributesImpl();
        handler.startElement("", "", "IccProfile", attr);
        handler.startElement("", "", "Header", attr);

        handler.startElement("", "", "PreferredCMMType", attr);
        String stringV = (String) header.get("CMMType");
        handler.characters(stringV.toCharArray(), 0, stringV.length());
        handler.endElement("", "", "PreferredCMMType");

        handler.startElement("", "", "PCSIlluminant", attr);
        attr.clear();
        attr.addAttribute("", "", "X", "", header.get("x") + "");
        attr.addAttribute("", "", "Y", "", header.get("y") + "");
        attr.addAttribute("", "", "Z", "", header.get("z") + "");
        handler.startElement("", "", "XYZNumber", attr);
        handler.endElement("", "", "XYZNumber");
        handler.endElement("", "", "PCSIlluminant");

        handler.endElement("", "", "Header");
        handler.endElement("", "", "IccProfile");

        handler.endDocument();

    } catch (Exception e) {

    }

}
 
Example 17
Source File: UserParameterSaveHandler.java    From mzmine2 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Function which creates an XML file with user parameters
 */
void saveParameters() throws SAXException, IOException, TransformerConfigurationException {

  logger.info("Saving user parameters");

  StreamResult streamResult = new StreamResult(finalStream);
  SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

  TransformerHandler hd = tf.newTransformerHandler();

  Transformer serializer = hd.getTransformer();
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

  hd.setResult(streamResult);
  hd.startDocument();

  UserParameter<?, ?> projectParameters[] = project.getParameters();

  AttributesImpl atts = new AttributesImpl();

  atts.addAttribute("", "", UserParameterElementName.COUNT.getElementName(), "CDATA",
      String.valueOf(projectParameters.length));

  hd.startElement("", "", UserParameterElementName.PARAMETERS.getElementName(), atts);

  atts.clear();

  // <PARAMETER>
  for (UserParameter<?, ?> parameter : project.getParameters()) {

    if (canceled)
      return;

    logger.finest("Saving user parameter " + parameter.getName());

    atts.addAttribute("", "", UserParameterElementName.NAME.getElementName(), "CDATA",
        parameter.getName());

    atts.addAttribute("", "", UserParameterElementName.TYPE.getElementName(), "CDATA",
        parameter.getClass().getSimpleName());

    hd.startElement("", "", UserParameterElementName.PARAMETER.getElementName(), atts);

    atts.clear();

    fillParameterElement(parameter, hd);

    hd.endElement("", "", UserParameterElementName.PARAMETER.getElementName());
    completedParameters++;
  }

  hd.endElement("", "", UserParameterElementName.PARAMETERS.getElementName());

  hd.endDocument();

}
 
Example 18
Source File: UserParameterSaveHandler.java    From mzmine3 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Function which creates an XML file with user parameters
 */
void saveParameters() throws SAXException, IOException, TransformerConfigurationException {

  logger.info("Saving user parameters");

  StreamResult streamResult = new StreamResult(finalStream);
  SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

  TransformerHandler hd = tf.newTransformerHandler();

  Transformer serializer = hd.getTransformer();
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

  hd.setResult(streamResult);
  hd.startDocument();

  UserParameter<?, ?> projectParameters[] = project.getParameters();

  AttributesImpl atts = new AttributesImpl();

  atts.addAttribute("", "", UserParameterElementName.COUNT.getElementName(), "CDATA",
      String.valueOf(projectParameters.length));

  hd.startElement("", "", UserParameterElementName.PARAMETERS.getElementName(), atts);

  atts.clear();

  // <PARAMETER>
  for (UserParameter<?, ?> parameter : project.getParameters()) {

    if (canceled)
      return;

    logger.finest("Saving user parameter " + parameter.getName());

    atts.addAttribute("", "", UserParameterElementName.NAME.getElementName(), "CDATA",
        parameter.getName());

    atts.addAttribute("", "", UserParameterElementName.TYPE.getElementName(), "CDATA",
        parameter.getClass().getSimpleName());

    hd.startElement("", "", UserParameterElementName.PARAMETER.getElementName(), atts);

    atts.clear();

    fillParameterElement(parameter, hd);

    hd.endElement("", "", UserParameterElementName.PARAMETER.getElementName());
    completedParameters++;
  }

  hd.endElement("", "", UserParameterElementName.PARAMETERS.getElementName());

  hd.endDocument();

}