Search in sources :

Example 1 with XmlStreamReader

use of org.apache.commons.io.input.XmlStreamReader in project maven-archetype by apache.

the class DefaultOldArchetype method createArchetype.

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());
    // ---------------------------------------------------------------------
    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);
        }
    }
    // ----------------------------------------------------------------------
    // 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);
            }
        }
    }
    // ----------------------------------------------------------------------
    if (getLogger().isInfoEnabled()) {
        getLogger().info("project created from Old (1.x) Archetype in dir: " + outputDirectory);
    }
}
Also used : HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) SAXReader(org.dom4j.io.SAXReader) XmlStreamReader(org.apache.commons.io.input.XmlStreamReader) Reader(java.io.Reader) MavenXpp3Reader(org.apache.maven.model.io.xpp3.MavenXpp3Reader) URL(java.net.URL) StringWriter(java.io.StringWriter) ArchetypeDescriptorBuilder(org.apache.maven.archetype.old.descriptor.ArchetypeDescriptorBuilder) DocumentException(org.dom4j.DocumentException) URLClassLoader(java.net.URLClassLoader) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) Context(org.apache.velocity.context.Context) VelocityContext(org.apache.velocity.VelocityContext) InputStream(java.io.InputStream) XmlStreamReader(org.apache.commons.io.input.XmlStreamReader) MavenXpp3Reader(org.apache.maven.model.io.xpp3.MavenXpp3Reader) IOException(java.io.IOException) ArchetypeDescriptor(org.apache.maven.archetype.old.descriptor.ArchetypeDescriptor) URLClassLoader(java.net.URLClassLoader) Model(org.apache.maven.model.Model) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) XMLWriter(org.dom4j.io.XMLWriter) OutputStreamWriter(java.io.OutputStreamWriter) StringWriter(java.io.StringWriter) MavenXpp3Writer(org.apache.maven.model.io.xpp3.MavenXpp3Writer) Writer(java.io.Writer)

Example 2 with XmlStreamReader

use of org.apache.commons.io.input.XmlStreamReader in project maven-plugins by apache.

the class ChangesMojo method getChangesFromFile.

/* --------------------------------------------------------------------- */
/* Private methods */
/* --------------------------------------------------------------------- */
/**
 * Parses specified changes.xml file. It also makes filtering if needed. If specified file doesn't exist it will log
 * warning and return <code>null</code>.
 *
 * @param changesXml changes xml file to parse
 * @param project maven project to parse changes for
 * @param additionalProperties additional properties used for filtering
 * @return parsed <code>ChangesXML</code> instance or null if file doesn't exist
 * @throws MavenReportException if any errors occurs while parsing
 */
private ChangesXML getChangesFromFile(File changesXml, MavenProject project, Properties additionalProperties) throws MavenReportException {
    if (!changesXml.exists()) {
        getLog().warn("changes.xml file " + changesXml.getAbsolutePath() + " does not exist.");
        return null;
    }
    if (filteringChanges) {
        if (!filteredOutputDirectory.exists()) {
            filteredOutputDirectory.mkdirs();
        }
        XmlStreamReader xmlStreamReader = null;
        try {
            // so we get encoding from the file itself
            xmlStreamReader = new XmlStreamReader(changesXml);
            String encoding = xmlStreamReader.getEncoding();
            File resultFile = new File(filteredOutputDirectory, project.getGroupId() + "." + project.getArtifactId() + "-changes.xml");
            final MavenFileFilterRequest mavenFileFilterRequest = new MavenFileFilterRequest(changesXml, resultFile, true, project, Collections.<String>emptyList(), false, encoding, session, additionalProperties);
            mavenFileFilter.copyFile(mavenFileFilterRequest);
            changesXml = resultFile;
            xmlStreamReader.close();
            xmlStreamReader = null;
        } catch (IOException e) {
            throw new MavenReportException("Exception during filtering changes file : " + e.getMessage(), e);
        } catch (MavenFilteringException e) {
            throw new MavenReportException("Exception during filtering changes file : " + e.getMessage(), e);
        } finally {
            IOUtil.close(xmlStreamReader);
        }
    }
    return new ChangesXML(changesXml, getLog());
}
Also used : MavenFilteringException(org.apache.maven.shared.filtering.MavenFilteringException) MavenFileFilterRequest(org.apache.maven.shared.filtering.MavenFileFilterRequest) XmlStreamReader(org.apache.commons.io.input.XmlStreamReader) IOException(java.io.IOException) File(java.io.File) MavenReportException(org.apache.maven.reporting.MavenReportException)

Example 3 with XmlStreamReader

use of org.apache.commons.io.input.XmlStreamReader in project maven-plugins by apache.

the class AcrMojo method getEncoding.

/**
 * Get the encoding from an XML-file.
 *
 * @param xmlFile the XML-file
 * @return The encoding of the XML-file, or UTF-8 if it's not specified in the file
 * @throws IOException if an error occurred while reading the file
 */
private String getEncoding(File xmlFile) throws IOException {
    XmlStreamReader xmlReader = null;
    try {
        xmlReader = new XmlStreamReader(xmlFile);
        final String encoding = xmlReader.getEncoding();
        xmlReader.close();
        xmlReader = null;
        return encoding;
    } finally {
        IOUtils.closeQuietly(xmlReader);
    }
}
Also used : XmlStreamReader(org.apache.commons.io.input.XmlStreamReader)

Example 4 with XmlStreamReader

use of org.apache.commons.io.input.XmlStreamReader in project maven-plugins by apache.

the class DocumentModelBuilder method getProjectModelEncoding.

/**
 * Extract the encoding.
 *
 * @param project the MavenProject to extract the encoding name from.
 * @return the project encoding if defined, or UTF-8 otherwise, or null if project is null.
 */
private static String getProjectModelEncoding(MavenProject project) {
    if (project == null) {
        return null;
    }
    String encoding = project.getModel().getModelEncoding();
    // Workaround for MNG-4289
    XmlStreamReader reader = null;
    try {
        reader = new XmlStreamReader(project.getFile());
        encoding = reader.getEncoding();
    } catch (IOException e) {
    // nop
    } finally {
        IOUtil.close(reader);
    }
    if (StringUtils.isEmpty(encoding)) {
        return "UTF-8";
    }
    return encoding;
}
Also used : XmlStreamReader(org.apache.commons.io.input.XmlStreamReader) IOException(java.io.IOException)

Example 5 with XmlStreamReader

use of org.apache.commons.io.input.XmlStreamReader in project AntennaPod by AntennaPod.

the class FeedHandler method parseFeed.

public FeedHandlerResult parseFeed(Feed feed) throws SAXException, IOException, ParserConfigurationException, UnsupportedFeedtypeException {
    TypeGetter tg = new TypeGetter();
    TypeGetter.Type type = tg.getType(feed);
    SyndHandler handler = new SyndHandler(feed, type);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    SAXParser saxParser = factory.newSAXParser();
    File file = new File(feed.getFile_url());
    Reader inputStreamReader = new XmlStreamReader(file);
    InputSource inputSource = new InputSource(inputStreamReader);
    saxParser.parse(inputSource, handler);
    inputStreamReader.close();
    return new FeedHandlerResult(handler.state.feed, handler.state.alternateUrls);
}
Also used : InputSource(org.xml.sax.InputSource) SAXParser(javax.xml.parsers.SAXParser) XmlStreamReader(org.apache.commons.io.input.XmlStreamReader) Reader(java.io.Reader) XmlStreamReader(org.apache.commons.io.input.XmlStreamReader) File(java.io.File) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

XmlStreamReader (org.apache.commons.io.input.XmlStreamReader)9 File (java.io.File)5 IOException (java.io.IOException)5 Reader (java.io.Reader)4 HashMap (java.util.HashMap)2 SAXParser (javax.xml.parsers.SAXParser)2 SAXParserFactory (javax.xml.parsers.SAXParserFactory)2 XmlPullParserException (org.codehaus.plexus.util.xml.pull.XmlPullParserException)2 InputSource (org.xml.sax.InputSource)2 TypeGetter (de.danoeh.antennapod.parser.feed.util.TypeGetter)1 InputStream (java.io.InputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 StringReader (java.io.StringReader)1 StringWriter (java.io.StringWriter)1 Writer (java.io.Writer)1 URL (java.net.URL)1 URLClassLoader (java.net.URLClassLoader)1 Locale (java.util.Locale)1 Map (java.util.Map)1 StreamSource (javax.xml.transform.stream.StreamSource)1