Example usage for javax.xml.transform.stream StreamSource StreamSource

List of usage examples for javax.xml.transform.stream StreamSource StreamSource

Introduction

In this page you can find the example usage for javax.xml.transform.stream StreamSource StreamSource.

Prototype

public StreamSource(File f) 

Source Link

Document

Construct a StreamSource from a File.

Usage

From source file:de.drv.dsrv.spoc.web.service.impl.SpocResponseHandler.java

@Override
public StreamSource handleResponse(final HttpResponse httpResponse) throws IOException {

    final HttpEntity httpResponseEntity = getAndCheckHttpEntity(httpResponse);

    // Kopiert den InputStream der Response, damit die Connection
    // geschlossen werden kann.
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    IOUtils.copy(httpResponseEntity.getContent(), outputStream);
    EntityUtils.consume(httpResponseEntity);
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

    // Initialisiert die zurueck gegebene Source.
    StreamSource responseSource;//from  ww w.  jav a 2s  .  c  o m
    final Charset charset = getCharsetFromResponse(httpResponseEntity);
    if (charset != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("F\u00fcr die Antwort des Fachverfahrens wird das Charset >" + charset.name()
                    + "< aus dem Content-Type Header verwendet.");
        }
        responseSource = new StreamSource(new InputStreamReader(inputStream, charset));
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Die Antwort des Fachverfahren hat kein Charset im Content-Type Header spezifiziert."
                    + " Der Payload wird dem XML-Parser ohne Charset \u00fcbergeben,"
                    + " dieses sollte aber im XML-Prolog spezifiziert sein.");
        }
        responseSource = new StreamSource(inputStream);
    }

    return responseSource;
}

From source file:io.github.mikesaelim.arxivoaiharvester.xml.XMLParser.java

/**
 * Constructs a new XML parser by initializing the JAXB unmarshaller and setting up the XML validation.
 *
 * @throws HarvesterError if there are any problems
 *///from   w  w  w  .  j  av  a  2 s .  c  o  m
public XMLParser() {
    try {
        unmarshaller = JAXBContext.newInstance("org.openarchives.oai._2:org.arxiv.oai.arxivraw")
                .createUnmarshaller();
    } catch (JAXBException e) {
        throw new HarvesterError("Error creating JAXB unmarshaller", e);
    }

    ClassLoader classLoader = this.getClass().getClassLoader();
    List<Source> schemaSources = Lists.newArrayList(
            new StreamSource(classLoader.getResourceAsStream("OAI-PMH.xsd")),
            new StreamSource(classLoader.getResourceAsStream("arXivRaw.xsd")));
    try {
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(schemaSources.toArray(new Source[schemaSources.size()]));
        unmarshaller.setSchema(schema);
    } catch (SAXException e) {
        throw new HarvesterError("Error creating validation schema", e);
    }
}

From source file:org.web4thejob.orm.TypeSerailizationTest.java

@Test
public void marshallingTest() throws XmlMappingException, IOException {
    final Marshaller marshaller = ContextUtil.getBean(Marshaller.class);
    Assert.assertNotNull(marshaller);/*from ww  w.  jav a 2 s. com*/

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Result result = new StreamResult(out);
    final Detail detail1 = ContextUtil.getDRS().getOne(Detail.class);
    marshaller.marshal(detail1, result);

    final Unmarshaller unmarshaller = ContextUtil.getBean(Unmarshaller.class);
    final Detail detail2 = (Detail) unmarshaller
            .unmarshal(new StreamSource(new ByteArrayInputStream(out.toByteArray())));

    Assert.assertEquals(detail1, detail2);
}

From source file:co.pugo.convert.Transformation.java

/**
 * helper method to setup transformer//from w ww. j  a  v  a  2 s  .  co m
 */
private void setupTransformer() {
    try {
        transformer = transformerFactory.newTransformer(new StreamSource(xsl));
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:de.uzk.hki.da.metadata.XsltGenerator.java

/**
 * Instantiates a new xslt generator.// w  ww .j a  va  2 s.c  o  m
 *
 * @param xsltPath the xslt path to the edm mapping file
 * @param inputStream the input stream of the source metadata file
 * @throws FileNotFoundException 
 * @throws TransformerConfigurationException 
 */
public XsltGenerator(String xsltPath, InputStream inputStream)
        throws FileNotFoundException, TransformerConfigurationException {
    if (!new File(xsltPath).exists())
        throw new FileNotFoundException();

    try {
        String theString = IOUtils.toString(inputStream, "UTF-8");
        this.inputStream = new ByteArrayInputStream(theString.getBytes());

        xsltSource = new StreamSource(new FileInputStream(xsltPath));

        TransformerFactory transFact = TransformerFactory.newInstance(TRANSFORMER_FACTORY_CLASS, null);
        transFact.setErrorListener(new CutomErrorListener());

        transformer = null;
        transformer = transFact.newTransformer(xsltSource);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setErrorListener(new CutomErrorListener());

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.wandrell.example.swss.test.unit.endpoint.encryption.wss4j.TestEntityEndpointRequestEncryptionWss4j.java

@Override
protected final Source getRequestEnvelope() {
    try {//from w w w.  j av  a2 s  .co m
        return new StreamSource(new ClassPathResource(pathValid).getInputStream());
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ch.entwine.weblounge.tools.importer.ResourceImporterCallback.java

/**
 * This method is called if a resource file has been found.
 * // w ww. ja  v  a 2s .  c  o  m
 * @see ch.entwine.weblounge.tools.importer.AbstractImporterCallback#fileImported(java.io.File)
 */
public boolean fileImported(File f) {
    // load collection information
    File collXml = new File(FilenameUtils.getFullPath(f.getPath()) + "repository.xml");
    if (!collXml.exists()) {
        System.err.println("No repository information (repository.xml) found for file: " + f.getName());
        return false;
    }

    // path relative to the src directory
    String relpath = f.getPath().replaceAll(this.srcDir.getAbsolutePath(), "");

    // Check if collXml contains information for this file
    XMLDocument repoXml = new XMLDocument(collXml);
    if (repoXml.getNode("/collection/entry[@id='" + relpath + "']") == null)
        return false;

    UUID uuid = UUID.randomUUID();
    File resourceXml = null;
    ImageInfo imageInfo = null;
    try {
        // create temporary resource descriptor file
        resourceXml = File.createTempFile(uuid.toString(), ".xml");

        // try loading file as image
        imageInfo = Sanselan.getImageInfo(f);
    } catch (IOException e) {
        System.err.println("Error processing file '" + relpath + "': " + e.getMessage());
        return false;
    } catch (ImageReadException e) {
        // file is not an image
    }

    ImporterState.getInstance().putUUID(relpath, uuid);

    String filename = "de.".concat(FilenameUtils.getExtension(f.getName()));

    // check, if file is an image resource
    String subfolder = null;
    if (imageInfo != null) {
        subfolder = "images";
        Source xsl = new StreamSource(this.getClass().getResourceAsStream("/xsl/convert-image.xsl"));
        // set the TransformFactory to use the Saxon TransformerFactoryImpl method
        System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans;
        try {
            trans = transFact.newTransformer(xsl);
            trans.setParameter("fileid", relpath);
            trans.setParameter("uuid", uuid.toString());
            trans.setParameter("path", relpath);
            trans.setParameter("imgwidth", imageInfo.getWidth());
            trans.setParameter("imgheight", imageInfo.getHeight());
            this.transformXml(collXml, resourceXml, trans);
        } catch (TransformerConfigurationException e) {
            System.err.println(e.getMessage());
            return false;
        }
    } else {
        subfolder = "files";
        Source xsl = new StreamSource(this.getClass().getResourceAsStream("/xsl/convert-file.xsl"));
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans;
        try {
            trans = transFact.newTransformer(xsl);
            trans.setParameter("fileid", relpath);
            trans.setParameter("uuid", uuid.toString());
            trans.setParameter("path", relpath);
            this.transformXml(collXml, resourceXml, trans);
        } catch (TransformerConfigurationException e) {
            System.err.println(e.getMessage());
            return false;
        }
    }

    this.storeFile(f, destDir, subfolder, filename, uuid, 0);
    this.storeFile(resourceXml, destDir, subfolder, "index.xml", uuid, 0);
    System.out.println("Imported resource " + f.getName());
    return true;
}

From source file:com.smartitengineering.cms.spi.impl.type.validator.XMLSchemaBasedTypeValidator.java

protected boolean isValid(Document document) throws Exception {
    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final InputStream xsdStream = getClass().getClassLoader().getResourceAsStream(XSD_LOCATION);
    // load a WXS schema, represented by a Schema instance
    Source schemaFile = new StreamSource(xsdStream);
    schemaFile.setSystemId(CONTENT_TYPE_SCHEMA_URI);
    Schema schema = factory.newSchema(schemaFile);
    // create a Validator instance, which can be used to validate an instance document
    Validator validator = schema.newValidator();
    // validate the DOM tree
    try {//  ww w .j  a  va  2s  .  c  o m
        validator.validate(new DOMSource(document));
        return true;
    } catch (SAXException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.globus.crux.messaging.utils.JAXBMessageConverter.java

/**
 * <p>//  w  ww .j  a va2  s.c  om
 * Unmarshal given <code>message</code> into an <code>object</code>.
 * </p>
 *
 * <p>
 * Should we raise an exception if the XML message encoding is not in sync with the underlying TextMessage encoding when the JMS
 * Provider supports MOM message's encoding ?
 * </p>
 *
 * @param message
 *            message to unmarshal, MUST be an instance of {@link TextMessage} or of {@link BytesMessage}.
 * @see org.springframework.jms.support.converter.MessageConverter#fromMessage(javax.jms.Message)
 */
public Object fromMessage(Message message) throws JMSException, MessageConversionException {

    Source source;
    if (message instanceof TextMessage) {
        TextMessage textMessage = (TextMessage) message;
        source = new StreamSource(new StringReader(textMessage.getText()));
    } else if (message instanceof BytesMessage) {
        BytesMessage bytesMessage = (BytesMessage) message;
        byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
        bytesMessage.readBytes(bytes);
        source = new StreamSource(new ByteArrayInputStream(bytes));

    } else {
        throw new MessageConversionException("Unsupported JMS Message type " + message.getClass()
                + ", expected instance of TextMessage or BytesMessage for " + message);
    }
    Object result;
    try {
        result = context.createUnmarshaller().unmarshal(source);
    } catch (JAXBException e) {
        throw new MessageConversionException("Error unmarshalling message", e);
    }

    return result;
}

From source file:com.jaeksoft.searchlib.authentication.AuthManager.java

public AuthManager(Config config, File indexDir)
        throws SAXException, IOException, ParserConfigurationException {
    authFile = new File(indexDir, AUTH_CONFIG_FILENAME);
    if (!authFile.exists())
        return;//w w w .j a  v a  2  s  .c om
    StreamSource streamSource = new StreamSource(authFile);
    Node docNode = DomUtils.readXml(streamSource, false);
    Node authNode = DomUtils.getFirstNode(docNode, AUTH_ITEM_ROOT_NODE);
    if (authNode == null)
        return;
    enabled = DomUtils.getAttributeBoolean(authNode, AUTH_ATTR_ENABLED, false);
    userAllowField = DomUtils.getAttributeText(authNode, AUTH_ATTR_USER_ALLOW_FIELD);
    userDenyField = DomUtils.getAttributeText(authNode, AUTH_ATTR_USER_DENY_FIELD);
    groupAllowField = DomUtils.getAttributeText(authNode, AUTH_ATTR_GROUP_ALLOW_FIELD);
    groupDenyField = DomUtils.getAttributeText(authNode, AUTH_ATTR_GROUP_DENY_FIELD);
    defaultUser = DomUtils.getAttributeText(authNode, AUTH_ATTR_DEFAULT_USER);
    defaultGroup = DomUtils.getAttributeText(authNode, AUTH_ATTR_DEFAULT_GROUP);
}