Example usage for org.apache.commons.io.input XmlStreamReader XmlStreamReader

List of usage examples for org.apache.commons.io.input XmlStreamReader XmlStreamReader

Introduction

In this page you can find the example usage for org.apache.commons.io.input XmlStreamReader XmlStreamReader.

Prototype

public XmlStreamReader(URL url) throws IOException 

Source Link

Document

Creates a Reader using the InputStream of a URL.

Usage

From source file:com.github.rwitzel.streamflyer.util.ModifyingReaderFactory.java

public ModifyingReader createInvalidXmlCharacterReplacingReader(InputStream xmlStream, String replacement)
        throws IOException {

    // buffer stream
    // (is this really necessary to get optimal performance?)
    if (!(xmlStream instanceof BufferedInputStream)) {
        xmlStream = new BufferedInputStream(xmlStream);
    }/*from  w  w w  .jav  a 2 s.c  o  m*/

    // get the XML version
    XmlStreamReader xmlReader = new XmlStreamReader(xmlStream);
    XmlVersionReader xmlVersionReader = new XmlVersionReader(xmlReader);
    String xmlVersion = xmlVersionReader.getXmlVersion();

    // what kind of replacement?
    boolean dollarZero;
    if (replacement.contains("$0")) {
        dollarZero = true;
    } else {
        dollarZero = false;
    }

    // create the reader that replaces invalid XML characters
    Modifier modifier = new InvalidXmlCharacterModifier(8192, replacement, xmlVersion, dollarZero);
    return new ModifyingReader(xmlVersionReader, modifier);
}

From source file:com.github.rwitzel.streamflyer.util.ModifyingReaderFactory.java

public ModifyingReader createXmlVersionModifyingReader(InputStream xmlStream, String newXmlVersion)
        throws IOException {

    // buffer stream
    // (is this really necessary to get optimal performance?)
    if (!(xmlStream instanceof BufferedInputStream)) {
        xmlStream = new BufferedInputStream(xmlStream);
    }/*  w ww . j  av a 2 s. c o m*/

    XmlStreamReader xmlReader = new XmlStreamReader(xmlStream);
    XmlVersionReader xmlVersionReader = new XmlVersionReader(xmlReader);

    // create the reader that replaces the XML version in prolog
    Modifier modifier = new XmlVersionModifier(newXmlVersion, 8192);
    return new ModifyingReader(xmlVersionReader, modifier);
}

From source file:com.github.rwitzel.streamflyer.xml.XmlVersionModifierTest.java

private void assertXmlVersionInProlog(byte[] input, String newXmlVersion, String expectedProlog)
        throws Exception {

    XmlVersionReader xmlVersionReader = new XmlVersionReader(
            new XmlStreamReader(new ByteArrayInputStream(input)));

    // create the reader that modifies the XML version
    ModifyingReader reader = new ModifyingReader(xmlVersionReader, createModifier(newXmlVersion, 5));

    String actualProlog = IOUtils.toString(reader);

    assertEquals(expectedProlog, actualProlog);
}

From source file:com.github.rwitzel.streamflyer.xml.XmlVersionModifierTest.java

@Test
public void testExampleFromJavadoc() throws Exception {

    byte UTF16LE_BOM_BYTE_1 = (byte) 0xFF;
    byte UTF16LE_BOM_BYTE_2 = (byte) 0xFE;

    // version in prolog is 1.0
    String input = "<?xml version='1.0'>";
    byte[] bytes = input.getBytes("UTF-16LE");
    byte[] bytesWithBom = new byte[bytes.length + 2];
    bytesWithBom[0] = UTF16LE_BOM_BYTE_1;
    bytesWithBom[1] = UTF16LE_BOM_BYTE_2;
    System.arraycopy(bytes, 0, bytesWithBom, 2, bytes.length);

    // choose the input stream to modify
    ByteArrayInputStream inputStream = new ByteArrayInputStream(bytesWithBom);

    // wrap the input stream by BOM skipping reader
    Reader reader = new XmlStreamReader(inputStream);

    // create the reader that changes the XML version to 1.1
    ModifyingReader modifyingReader = new ModifyingReader(reader, new XmlVersionModifier("1.1", 8192));

    // use the modifying reader instead of the original reader
    String xml = IOUtils.toString(modifyingReader);

    assertTrue(xml.startsWith("<?xml version='1.1'"));
}

From source file:com.c4om.jschematronvalidator.JSchematronValidatorMain.java

/**
 * Reads a {@link org.w3c.dom.Document} from a {@link File}. Encoding is automatically 
 * determined as specified by corresponding RFCs.
 * @param file a {@link File} object./*from  w  w  w .j av a2 s .  c o m*/
 * @return the read {@link Document}
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static Document loadW3CDocumentFromInputFile(File file)
        throws ParserConfigurationException, SAXException, IOException {
    Reader xmlStreamReader = new XmlStreamReader(file);
    return loadW3CDocumentFromInputSource(new InputSource(xmlStreamReader));
}

From source file:cn.wanghaomiao.maven.plugin.seimi.packaging.AbstractWarPackagingTask.java

/**
 * Get the encoding from an XML-file./* w  w w.ja  v  a  2  s.  co  m*/
 *
 * @param webXml the XML-file
 * @return The encoding of the XML-file, or UTF-8 if it's not specified in the file
 * @throws java.io.IOException if an error occurred while reading the file
 */
protected String getEncoding(File webXml) throws IOException {
    XmlStreamReader xmlReader = new XmlStreamReader(webXml);
    try {
        return xmlReader.getEncoding();
    } finally {
        IOUtil.close(xmlReader);
    }
}

From source file:com.google.gdt.eclipse.designer.util.Utils.java

/**
 * Reads module definition from given stream.
 *///ww  w.  j a  va2s.c  om
public static ModuleElement readModule(String id, InputStream inputStream) throws Exception {
    // read content, with correct encoding
    String contents;
    {
        Reader reader = new XmlStreamReader(inputStream);
        contents = IOUtils2.readString(reader);
    }
    // check cache
    String key = id + "|" + contents;
    {
        ModuleElement moduleElement = m_readModule.get(key);
        if (moduleElement != null) {
            return moduleElement;
        }
    }
    // parse using GWTDocumentHandler
    GwtDocumentHandler documentHandler = new GwtDocumentHandler();
    try {
        QParser.parse(new StringReader(contents), documentHandler);
    } catch (Throwable e) {
        throw new DesignerException(IExceptionConstants.INVALID_MODULE_FILE, id);
    }
    // prepare module element
    ModuleElement moduleElement = documentHandler.getModuleElement();
    moduleElement.setId(id);
    moduleElement.finalizeLoading();
    // fill cache
    m_readModule.put(key, moduleElement);
    // done
    return moduleElement;
}

From source file:com.github.spyhunter99.pdf.plugin.PdfMojo.java

/**
 * @return the DecorationModel instance from <code>site.xml</code>
 * @throws MojoExecutionException if any
 *///  w  w  w  . j  a v  a2s . co m
private DecorationModel getDefaultDecorationModel() throws MojoExecutionException {
    if (this.defaultDecorationModel == null) {
        final Locale locale = getDefaultLocale();

        final File descriptorFile = siteTool.getSiteDescriptor(siteDirectory, locale);
        DecorationModel decoration = null;

        if (descriptorFile.exists()) {
            XmlStreamReader reader = null;
            try {
                reader = new XmlStreamReader(descriptorFile);

                String siteDescriptorContent = IOUtil.toString(reader);

                reader.close();
                reader = null;

                siteDescriptorContent = siteTool.getInterpolatedSiteDescriptorContent(
                        new HashMap<String, String>(2), project, siteDescriptorContent);

                decoration = new DecorationXpp3Reader().read(new StringReader(siteDescriptorContent));
            } catch (XmlPullParserException e) {
                throw new MojoExecutionException("Error parsing site descriptor", e);
            } catch (IOException e) {
                throw new MojoExecutionException("Error reading site descriptor", e);
            } catch (SiteToolException e) {
                throw new MojoExecutionException("Error when interpoling site descriptor", e);
            } finally {
                IOUtil.close(reader);
            }
        }

        this.defaultDecorationModel = decoration;
    }

    return this.defaultDecorationModel;
}

From source file:nl.armatiek.xslweb.configuration.WebApp.java

public WebApp(File webAppDefinition) throws Exception {
    logger.info(String.format("Loading webapp definition \"%s\" ...", webAppDefinition.getAbsolutePath()));

    Context context = Context.getInstance();
    this.definition = webAppDefinition;
    this.homeDir = webAppDefinition.getParentFile();
    this.name = this.homeDir.getName();

    this.configuration = new XSLWebConfiguration(this);
    this.processor = new Processor(this.configuration.getConfiguration());

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//  ww  w.j a  v a 2s.  c o  m
    dbf.setSchema(context.getWebAppSchema());
    dbf.setXIncludeAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setErrorHandler(this);

    String defXml = IOUtils.toString(new XmlStreamReader(webAppDefinition));
    Properties vars = new Properties(System.getProperties());
    vars.setProperty("webapp-dir", webAppDefinition.getParentFile().getAbsolutePath().replace('\\', '/'));
    String resolvedDefXml = XSLWebUtils.resolveProperties(defXml, vars);
    // Document webAppDoc = db.parse(webAppDefinition);
    InputSource src = new InputSource(new StringReader(resolvedDefXml));
    src.setSystemId(webAppDefinition.getAbsolutePath());
    Document webAppDoc = db.parse(src);

    XPath xpath = new XPathFactoryImpl().newXPath();
    xpath.setNamespaceContext(XMLUtils.getNamespaceContext("webapp", Definitions.NAMESPACEURI_XSLWEB_WEBAPP));
    Node docElem = webAppDoc.getDocumentElement();
    this.title = (String) xpath.evaluate("webapp:title", docElem, XPathConstants.STRING);
    this.description = (String) xpath.evaluate("webapp:description", docElem, XPathConstants.STRING);
    String devModeValue = (String) xpath.evaluate("webapp:development-mode", docElem, XPathConstants.STRING);
    this.developmentMode = XMLUtils.getBooleanValue(devModeValue, false);
    String maxUploadSizeValue = (String) xpath.evaluate("webapp:max-upload-size", docElem,
            XPathConstants.STRING);
    this.maxUploadSize = XMLUtils.getIntegerValue(maxUploadSizeValue, 10);
    String waitForJobsAtCloseValue = (String) xpath.evaluate("webapp:wait-for-jobs-at-close", docElem,
            XPathConstants.STRING);
    this.waitForJobsAtClose = XMLUtils.getBooleanValue(waitForJobsAtCloseValue, true);

    NodeList resourceNodes = (NodeList) xpath.evaluate("webapp:resources/webapp:resource", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < resourceNodes.getLength(); i++) {
        resources.add(new Resource((Element) resourceNodes.item(i)));
    }
    NodeList paramNodes = (NodeList) xpath.evaluate("webapp:parameters/webapp:parameter", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < paramNodes.getLength(); i++) {
        parameters.add(new Parameter(processor, (Element) paramNodes.item(i)));
    }
    NodeList jobNodes = (NodeList) xpath.evaluate("webapp:jobs/webapp:job", docElem, XPathConstants.NODESET);
    if (jobNodes.getLength() > 0) {
        File quartzFile = new File(homeDir, Definitions.FILENAME_QUARTZ);
        quartzFile = (quartzFile.isFile()) ? quartzFile
                : new File(context.getHomeDir(), "config" + File.separatorChar + Definitions.FILENAME_QUARTZ);
        SchedulerFactory sf;
        if (quartzFile.isFile()) {
            logger.info(String.format("Initializing Quartz scheduler using properties file \"%s\" ...",
                    quartzFile.getAbsolutePath()));
            Properties props = XSLWebUtils.readProperties(quartzFile);
            props.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, name);
            sf = new StdSchedulerFactory(props);
        } else {
            logger.info("Initializing Quartz scheduler ...");
            sf = new StdSchedulerFactory();
        }
        scheduler = sf.getScheduler();
        for (int i = 0; i < jobNodes.getLength(); i++) {
            Element jobElem = (Element) jobNodes.item(i);
            String jobName = XMLUtils.getValueOfChildElementByLocalName(jobElem, "name");
            String jobUri = XMLUtils.getValueOfChildElementByLocalName(jobElem, "uri");
            String jobCron = XMLUtils.getValueOfChildElementByLocalName(jobElem, "cron");
            boolean concurrent = XMLUtils
                    .getBooleanValue(XMLUtils.getValueOfChildElementByLocalName(jobElem, "concurrent"), true);
            String jobId = "job_" + name + "_" + jobName;
            JobDetail job = newJob(concurrent ? XSLWebJob.class : NonConcurrentExecutionXSLWebJob.class)
                    .withIdentity(jobId, name).usingJobData("webapp-path", getPath())
                    .usingJobData("uri", jobUri).build();
            Trigger trigger = newTrigger().withIdentity("trigger_" + name + "_" + jobName, name)
                    .withSchedule(cronSchedule(jobCron)).forJob(jobId, name).build();
            logger.info(String.format("Scheduling job \"%s\" of webapp \"%s\" ...", jobName, name));
            scheduler.scheduleJob(job, trigger);
        }
    }

    NodeList dataSourceNodes = (NodeList) xpath.evaluate("webapp:datasources/webapp:datasource", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < dataSourceNodes.getLength(); i++) {
        DataSource dataSource = new DataSource((Element) dataSourceNodes.item(i));
        dataSources.put(dataSource.getName(), dataSource);
    }

    NodeList fopConfigNodes = (NodeList) xpath.evaluate("webapp:fop-configs/webapp:fop-config", docElem,
            XPathConstants.NODESET);
    for (int i = 0; i < fopConfigNodes.getLength(); i++) {
        Element fopConfig = (Element) fopConfigNodes.item(i);
        Element fopElement = XMLUtils.getFirstChildElement(fopConfig);
        fopConfigs.put(fopConfig.getAttribute("name"), XMLUtils.nodeToString(fopElement));
    }

    // initClassLoader();

    initFileAlterationObservers();
}

From source file:org.apache.maven.archetype.old.DefaultOldArchetype.java

public void createArchetype(ArchetypeGenerationRequest request, File archetypeFile)
        throws ArchetypeDescriptorException, ArchetypeTemplateProcessingException {
    Map<String, String> parameters = new HashMap<String, String>();

    parameters.put("basedir", request.getOutputDirectory());

    parameters.put(Constants.PACKAGE, request.getPackage());

    parameters.put("packageName", request.getPackage());

    parameters.put(Constants.GROUP_ID, request.getGroupId());

    parameters.put(Constants.ARTIFACT_ID, request.getArtifactId());

    parameters.put(Constants.VERSION, request.getVersion());

    // ---------------------------------------------------------------------
    // Get Logger and display all parameters used
    // ---------------------------------------------------------------------
    if (getLogger().isInfoEnabled()) {
        getLogger().info("----------------------------------------------------------------------------");

        getLogger().info("Using following parameters for creating project from Old (1.x) Archetype: "
                + request.getArchetypeArtifactId() + ":" + request.getArchetypeVersion());

        getLogger().info("----------------------------------------------------------------------------");

        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String parameterName = entry.getKey();

            String parameterValue = entry.getValue();

            getLogger().info("Parameter: " + parameterName + ", Value: " + parameterValue);
        }//  w  w w .  ja v a 2  s  . com
    }

    // ----------------------------------------------------------------------
    // Load the descriptor
    // ----------------------------------------------------------------------

    ArchetypeDescriptorBuilder builder = new ArchetypeDescriptorBuilder();

    ArchetypeDescriptor descriptor;

    URLClassLoader archetypeJarLoader;

    InputStream is = null;

    try {
        URL[] urls = new URL[1];

        urls[0] = archetypeFile.toURL();

        archetypeJarLoader = new URLClassLoader(urls);

        is = getStream(ARCHETYPE_DESCRIPTOR, archetypeJarLoader);

        if (is == null) {
            is = getStream(ARCHETYPE_OLD_DESCRIPTOR, archetypeJarLoader);
        }

        if (is == null) {
            throw new ArchetypeDescriptorException(
                    "The " + ARCHETYPE_DESCRIPTOR + " descriptor cannot be found.");
        }

        descriptor = builder.build(new XmlStreamReader(is));
    } catch (IOException e) {
        throw new ArchetypeDescriptorException("Error reading the " + ARCHETYPE_DESCRIPTOR + " descriptor.", e);
    } catch (XmlPullParserException e) {
        throw new ArchetypeDescriptorException("Error reading the " + ARCHETYPE_DESCRIPTOR + " descriptor.", e);
    } finally {
        IOUtil.close(is);
    }

    // ----------------------------------------------------------------------
    //
    // ----------------------------------------------------------------------

    String artifactId = request.getArtifactId();

    File parentPomFile = new File(request.getOutputDirectory(), ARCHETYPE_POM);

    File outputDirectoryFile;

    boolean creating;
    File pomFile;
    if (parentPomFile.exists() && descriptor.isAllowPartial() && artifactId == null) {
        outputDirectoryFile = new File(request.getOutputDirectory());
        creating = false;
        pomFile = parentPomFile;
    } else {
        if (artifactId == null) {
            throw new ArchetypeTemplateProcessingException(
                    "Artifact ID must be specified when creating a new project from an archetype.");
        }

        outputDirectoryFile = new File(request.getOutputDirectory(), artifactId);
        creating = true;

        if (outputDirectoryFile.exists()) {
            if (descriptor.isAllowPartial()) {
                creating = false;
            } else {
                throw new ArchetypeTemplateProcessingException("Directory " + outputDirectoryFile.getName()
                        + " already exists - please run from a clean directory");
            }
        }

        pomFile = new File(outputDirectoryFile, ARCHETYPE_POM);
    }

    if (creating) {
        if (request.getGroupId() == null) {
            throw new ArchetypeTemplateProcessingException(
                    "Group ID must be specified when creating a new project from an archetype.");
        }

        if (request.getVersion() == null) {
            throw new ArchetypeTemplateProcessingException(
                    "Version must be specified when creating a new project from an archetype.");
        }
    }

    String outputDirectory = outputDirectoryFile.getAbsolutePath();

    String packageName = request.getPackage();

    // ----------------------------------------------------------------------
    // Set up the Velocity context
    // ----------------------------------------------------------------------

    Context context = new VelocityContext();

    context.put(Constants.PACKAGE, packageName);

    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        context.put(entry.getKey(), entry.getValue());
    }

    // ----------------------------------------------------------------------
    // Process the templates
    // ----------------------------------------------------------------------

    ClassLoader old = Thread.currentThread().getContextClassLoader();

    Thread.currentThread().setContextClassLoader(archetypeJarLoader);

    Model parentModel = null;
    if (creating) {
        if (parentPomFile.exists()) {
            Reader fileReader = null;

            try {
                fileReader = ReaderFactory.newXmlReader(parentPomFile);
                MavenXpp3Reader reader = new MavenXpp3Reader();
                parentModel = reader.read(fileReader);
                if (!"pom".equals(parentModel.getPackaging())) {
                    throw new ArchetypeTemplateProcessingException(
                            "Unable to add module to the current project as it is not of packaging type 'pom'");
                }
            } catch (IOException e) {
                throw new ArchetypeTemplateProcessingException("Unable to read parent POM", e);
            } catch (XmlPullParserException e) {
                throw new ArchetypeTemplateProcessingException("Unable to read parent POM", e);
            } finally {
                IOUtil.close(fileReader);
            }

            parentModel.getModules().add(artifactId);
        }
    }

    try {
        processTemplates(pomFile, outputDirectory, context, descriptor, packageName, parentModel);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }

    if (parentModel != null) {
        /*
                // TODO: would be nice to just write out with the xpp3 writer again, except that it loses a bunch of info and
                // reformats, so the module is just baked in as a string instead.
                    FileWriter fileWriter = null;
                
                    try
                    {
        fileWriter = new FileWriter( parentPomFile );
                
        MavenXpp3Writer writer = new MavenXpp3Writer();
        writer.write( fileWriter, parentModel );
                    }
                    catch ( IOException e )
                    {
        throw new ArchetypeTemplateProcessingException( "Unable to rewrite parent POM", e );
                    }
                    finally
                    {
        IOUtil.close( fileWriter );
                    }
        */
        Reader fileReader = null;
        boolean added;
        StringWriter w = new StringWriter();
        try {
            fileReader = ReaderFactory.newXmlReader(parentPomFile);
            added = addModuleToParentPom(artifactId, fileReader, w);
        } catch (IOException e) {
            throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
        } catch (DocumentException e) {
            throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
        } finally {
            IOUtil.close(fileReader);
        }

        if (added) {
            Writer out = null;
            try {
                out = WriterFactory.newXmlWriter(parentPomFile);
                IOUtil.copy(w.toString(), out);
            } catch (IOException e) {
                throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
            } finally {
                IOUtil.close(out);
            }
        }
    }

    // ----------------------------------------------------------------------
    // Log message on OldArchetype creation
    // ----------------------------------------------------------------------
    if (getLogger().isInfoEnabled()) {
        getLogger().info("project created from Old (1.x) Archetype in dir: " + outputDirectory);
    }

}