Java Code Examples for javax.xml.transform.sax.SAXTransformerFactory#newInstance()

The following examples show how to use javax.xml.transform.sax.SAXTransformerFactory#newInstance() . 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: Bug5072946.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test3() throws Exception {
    SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    Transformer t = sf.newTransformer();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document dom = parser.parse(Bug5072946.class.getResourceAsStream("Bug5072946.xml"));

    DOMResult r = new DOMResult();

    t.transform(new DOMSource(dom), r);
    Assert.assertNotNull(r.getNode());

    Node n = r.getNode().getFirstChild();
    r.setNode(n);
    t.transform(new DOMSource(dom), r);
    Assert.assertNotNull(r.getNode());
    Assert.assertSame(r.getNode(), n);

    r.setNextSibling(r.getNode().getFirstChild());
    t.transform(new DOMSource(dom), r);
    Assert.assertNotNull(r.getNode());
    Assert.assertSame(r.getNode(), n);
}
 
Example 2
Source File: XSLTTransformer.java    From syncope with Apache License 2.0 5 votes vote down vote up
/**
 * Utility method to create a new transformer factory.
 *
 * @return a new transformer factory
 */
private static SAXTransformerFactory createNewSAXTransformerFactory() {
    SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    transformerFactory.setURIResolver((href, base) -> null);
    try {
        transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    } catch (TransformerConfigurationException e) {
        LOG.error("Could not enable secure XML processing", e);
    }
    return transformerFactory;
}
 
Example 3
Source File: JdkXmlUtils.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static SAXTransformerFactory getSAXTransformFactory(boolean overrideDefaultParser) {
    SAXTransformerFactory tf = overrideDefaultParser
            ? (SAXTransformerFactory) SAXTransformerFactory.newInstance()
            : (SAXTransformerFactory) new TransformerFactoryImpl();
    try {
        tf.setFeature(OVERRIDE_PARSER, overrideDefaultParser);
    } catch (TransformerConfigurationException ex) {
        // ignore since it'd never happen with the JDK impl.
    }
    return tf;
}
 
Example 4
Source File: SAXTransformerFactoryTest.java    From learnjavabug with MIT License 5 votes vote down vote up
public static void main(String[] args) throws TransformerConfigurationException {
    SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

    //todo 修复方式
//    sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
//    sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Payloads.NO_FEEDBACK_SINGLE_LINE
        .getBytes());
    StreamSource source = new StreamSource(byteArrayInputStream);
    sf.newTransformerHandler(source);
  }
 
Example 5
Source File: Bug5072946.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests if the identity transformer correctly sets the output node.
 */
@Test
public void test2() throws Exception {
    SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler th = sf.newTransformerHandler();
    DOMResult r = new DOMResult();
    th.setResult(r);

    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(th);
    reader.parse(new InputSource(Bug5072946.class.getResourceAsStream("Bug5072946.xml")));

    Assert.assertNotNull(r.getNode());
}
 
Example 6
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 7
Source File: JdkXmlUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static SAXTransformerFactory getSAXTransformFactory(boolean overrideDefaultParser) {
    SAXTransformerFactory tf = overrideDefaultParser
            ? (SAXTransformerFactory) SAXTransformerFactory.newInstance()
            : (SAXTransformerFactory) new TransformerFactoryImpl();
    try {
        tf.setFeature(OVERRIDE_PARSER, overrideDefaultParser);
    } catch (TransformerConfigurationException ex) {
        // ignore since it'd never happen with the JDK impl.
    }
    return tf;
}
 
Example 8
Source File: TikaLambdaHandler.java    From tika-lambda with Apache License 2.0 5 votes vote down vote up
private String doTikaStuff(String bucket, String key, InputStream objectData) throws IOException, TransformerConfigurationException, SAXException {
  _logger.log("Extracting text with Tika");
  String extractedText = "";

  SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
  TransformerHandler handler = factory.newTransformerHandler();
  handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "text");
  handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
  StringWriter sw = new StringWriter();
  handler.setResult(new StreamResult(sw));
  AutoDetectParser parser = new AutoDetectParser();
  ParseContext parseContext = new ParseContext();
  parseContext.set(Parser.class, parser);

  Tika tika = new Tika();
  Metadata tikaMetadata = new Metadata();
  try {
    // for synthetic transactions
    if( key.toLowerCase().endsWith("tika.exception.testing.pdf")) {
      throw new TikaException("Test Tika Exception");
    }
    parser.parse(objectData, handler, tikaMetadata, parseContext);
    extractedText = sw.toString();
  } catch( TikaException e) {
    _logger.log("TikaException thrown while parsing: " + e.getLocalizedMessage());
    return assembleExceptionResult(bucket, key, e);
  }
  _logger.log("Tika parsing success");
  return assembleExtractionResult(bucket, key, extractedText, tikaMetadata);
}
 
Example 9
Source File: JdkXmlUtils.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public static SAXTransformerFactory getSAXTransformFactory(boolean overrideDefaultParser) {
    SAXTransformerFactory tf = overrideDefaultParser
            ? (SAXTransformerFactory) SAXTransformerFactory.newInstance()
            : (SAXTransformerFactory) new TransformerFactoryImpl();
    try {
        tf.setFeature(OVERRIDE_PARSER, overrideDefaultParser);
    } catch (TransformerConfigurationException ex) {
        // ignore since it'd never happen with the JDK impl.
    }
    return tf;
}
 
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: DomAnnotationParserFactory.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected SAXTransformerFactory initialValue() throws Exception {
    return (SAXTransformerFactory) SAXTransformerFactory.newInstance();
}
 
Example 12
Source File: DomAnnotationParserFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected SAXTransformerFactory initialValue() throws Exception {
    return (SAXTransformerFactory) SAXTransformerFactory.newInstance();
}
 
Example 13
Source File: TableToXML.java    From ramus with GNU General Public License v3.0 4 votes vote down vote up
public void store() throws IOException, TransformerConfigurationException,
        SAXException {
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
            .newInstance();
    th = tf.newTransformerHandler();
    StreamResult result = new StreamResult(stream);
    th.setResult(result);
    th.startDocument();
    attrs.addAttribute("", "", "generate-from-table", "CDATA", tableName);
    attrs.addAttribute("", "", "generate-time", "CDATA", new Date()
            .toString());
    attrs.addAttribute("", "", "prefix", "CDATA", prefix);
    startElement("table");
    attrs.clear();

    template.execute(new JDBCCallback() {
        @Override
        public Object execute(Connection connection) throws SQLException {
            Statement st = connection.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM " + prefix
                    + tableName);
            ResultSetMetaData meta = rs.getMetaData();
            startElement("fields");
            int cc = meta.getColumnCount();
            Converter[] converters = new Converter[cc];
            for (int i = 0; i < cc; i++) {
                attrs.addAttribute("", "", "id", "CDATA", Integer
                        .toString(i));
                attrs.addAttribute("", "", "name", "CDATA", meta
                        .getColumnName(i + 1));
                attrs.addAttribute("", "", "type", "CDATA", meta
                        .getColumnTypeName(i + 1));
                startElement("field");
                attrs.clear();
                endElement("field");
                if ((meta.getColumnType(i + 1) == Types.BLOB)
                        || (meta.getColumnType(i + 1) == Types.VARBINARY)
                        || (meta.getColumnTypeName(i + 1)
                        .equalsIgnoreCase("bytea"))) {
                    converters[i] = new ByteAConverter();
                } else if (meta.getColumnType(i + 1) == Types.CLOB) {
                    converters[i] = new ToStringConverter();
                } else if (meta.getColumnTypeName(i + 1).equalsIgnoreCase(
                        "bool")) {
                    converters[i] = new BoolConverter();
                } else if (meta.getColumnTypeName(i + 1).equalsIgnoreCase(
                        "timestamp")) {
                    converters[i] = new DateConverter();
                } else {
                    converters[i] = new ToStringConverter();
                }
            }
            endElement("fields");
            startElement("data");
            while (resultSetNext(rs)) {
                startElement("row");
                for (int i = 0; i < cc; i++) {
                    Object object;
                    if (converters[i] instanceof BoolConverter)
                        object = rs.getBoolean(i + 1);
                    else if (converters[i] instanceof ToStringConverter)
                        object = rs.getString(i + 1);
                    else if (converters[i] instanceof ByteAConverter)
                        object = rs.getBytes(i + 1);
                    else
                        object = rs.getObject(i + 1);
                    if (object != null) {
                        attrs.addAttribute("", "", "id", "CDATA", Integer
                                .toString(i));
                        startElement("f");
                        attrs.clear();
                        characters(converters[i].toString(object));
                        endElement("f");
                    }
                }
                endElement("row");
            }
            endElement("data");
            rs.close();
            st.close();
            return null;
        }

    });

    endElement("table");
    th.endDocument();
}
 
Example 14
Source File: SafeXml.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
public static SAXTransformerFactory newSaxTransformerFactory() {
  SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
  factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
  factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
  return factory;
}
 
Example 15
Source File: DomAnnotationParserFactory.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected SAXTransformerFactory initialValue() throws Exception {
    return (SAXTransformerFactory) SAXTransformerFactory.newInstance();
}
 
Example 16
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 17
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 18
Source File: DomAnnotationParserFactory.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected SAXTransformerFactory initialValue() throws Exception {
    return (SAXTransformerFactory) SAXTransformerFactory.newInstance();
}
 
Example 19
Source File: HtmlContentExtractor.java    From flink-crawler with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a transformer handler that serializes incoming SAX events to XHTML or HTML (depending the given method)
 * using the given output encoding.
 *
 * @param method
 *            "xml" or "html"
 * @param encoding
 *            output encoding, or <code>null</code> for the platform default
 * @return {@link System#out} transformer handler
 * @throws TransformerConfigurationException
 *             if the transformer can not be created
 */
private static TransformerHandler getTransformerHandler(String method, String encoding)
        throws TransformerConfigurationException {
    SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    if (encoding != null) {
        handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, encoding);
    }
    return handler;
}
 
Example 20
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();

}