List of usage examples for org.apache.commons.io.input XmlStreamReader XmlStreamReader
public XmlStreamReader(URL url) throws IOException
From source file:org.apache.maven.doxia.DefaultConverter.java
/** * @param f not null file/*from w w w. ja v a 2 s. c om*/ * @return the detected encoding for f or <code>null</code> if not able to detect it. * @throws IllegalArgumentException if f is not a file. * @throws UnsupportedOperationException if could not detect the file encoding. * @see {@link XmlStreamReader#getEncoding()} for xml files * @see {@link CharsetDetector#detect()} for text files */ private static String autoDetectEncoding(File f) { if (!f.isFile()) { throw new IllegalArgumentException( "The file '" + f.getAbsolutePath() + "' is not a file, could not detect encoding."); } Reader reader = null; InputStream is = null; try { if (XmlUtil.isXml(f)) { reader = new XmlStreamReader(f); return ((XmlStreamReader) reader).getEncoding(); } is = new BufferedInputStream(new FileInputStream(f)); CharsetDetector detector = new CharsetDetector(); detector.setText(is); CharsetMatch match = detector.detect(); return match.getName().toUpperCase(Locale.ENGLISH); } catch (IOException e) { // nop } finally { IOUtil.close(reader); IOUtil.close(is); } StringBuilder msg = new StringBuilder(); msg.append("Could not detect the encoding for file: "); msg.append(f.getAbsolutePath()); msg.append("\n Specify explicitly the encoding."); throw new UnsupportedOperationException(msg.toString()); }
From source file:org.apache.maven.plugin.acr.AcrMojo.java
/** * Get the encoding from an XML-file./*from ww w .j a v a 2 s .c o m*/ * * @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); return xmlReader.getEncoding(); } finally { IOUtils.closeQuietly(xmlReader); } }
From source file:org.apache.maven.plugin.changes.ChangesMojo.java
/** * 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 */// w w w.j a va 2 s. com 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.EMPTY_LIST, false, encoding, session, additionalProperties); mavenFileFilter.copyFile(mavenFileFilterRequest); changesXml = resultFile; } 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 { if (xmlStreamReader != null) { IOUtil.close(xmlStreamReader); } } } return new ChangesXML(changesXml, getLog()); }
From source file:org.apache.maven.plugin.changes.schema.DefaultChangesSchemaValidator.java
public XmlValidationHandler validateXmlWithSchema(File file, String schemaVersion, boolean failOnValidationError) throws SchemaValidatorException { Reader reader = null;//w ww. j a v a2 s .co m try { String schemaPath = CHANGES_SCHEMA_PATH + "changes-" + schemaVersion + ".xsd"; Schema schema = getSchema(schemaPath); Validator validator = schema.newValidator(); XmlValidationHandler baseHandler = new XmlValidationHandler(failOnValidationError); validator.setErrorHandler(baseHandler); reader = new XmlStreamReader(file); validator.validate(new StreamSource(reader)); return baseHandler; } catch (IOException e) { throw new SchemaValidatorException("IOException : " + e.getMessage(), e); } catch (SAXException e) { throw new SchemaValidatorException("SAXException : " + e.getMessage(), e); } catch (Exception e) { throw new SchemaValidatorException("Exception : " + e.getMessage(), e); } finally { IOUtil.close(reader); } }
From source file:org.apache.maven.plugin.invoker.AbstractInvokerMojo.java
/** * Runs the specified build jobs./*from w ww. ja v a 2 s. c om*/ * * @param projectsDir The base directory of all projects, must not be <code>null</code>. * @param buildJobs The build jobs to run must not be <code>null</code> nor contain <code>null</code> elements. * @throws org.apache.maven.plugin.MojoExecutionException * If any build could not be launched. */ private void runBuilds(final File projectsDir, BuildJob[] buildJobs) throws MojoExecutionException { if (!localRepositoryPath.exists()) { localRepositoryPath.mkdirs(); } //----------------------------------------------- // interpolate settings file //----------------------------------------------- File interpolatedSettingsFile = null; if (settingsFile != null) { if (cloneProjectsTo != null) { interpolatedSettingsFile = new File(cloneProjectsTo, "interpolated-" + settingsFile.getName()); } else { interpolatedSettingsFile = new File(settingsFile.getParentFile(), "interpolated-" + settingsFile.getName()); } buildInterpolatedFile(settingsFile, interpolatedSettingsFile); } //----------------------------------------------- // merge settings file //----------------------------------------------- SettingsXpp3Writer settingsWriter = new SettingsXpp3Writer(); File mergedSettingsFile; Settings mergedSettings = this.settings; if (mergeUserSettings) { if (interpolatedSettingsFile != null) { // Have to merge the specified settings file (dominant) and the one of the invoking Maven process Reader reader = null; try { reader = new XmlStreamReader(interpolatedSettingsFile); SettingsXpp3Reader settingsReader = new SettingsXpp3Reader(); Settings dominantSettings = settingsReader.read(reader); // MINVOKER-137: NPE on dominantSettings.getRuntimeInfo() // DefaultMavenSettingsBuilder does the same trick if (dominantSettings.getRuntimeInfo() == null) { RuntimeInfo rtInfo = new RuntimeInfo(dominantSettings); rtInfo.setFile(interpolatedSettingsFile); dominantSettings.setRuntimeInfo(rtInfo); } Settings recessiveSettings = cloneSettings(); SettingsUtils.merge(dominantSettings, recessiveSettings, TrackableBase.USER_LEVEL); mergedSettings = dominantSettings; getLog().debug("Merged specified settings file with settings of invoking process"); } catch (XmlPullParserException e) { throw new MojoExecutionException("Could not read specified settings file", e); } catch (IOException e) { throw new MojoExecutionException("Could not read specified settings file", e); } finally { IOUtil.close(reader); } } } if (this.settingsFile != null && !mergeUserSettings) { mergedSettingsFile = interpolatedSettingsFile; } else { try { mergedSettingsFile = File.createTempFile("invoker-settings", ".xml"); FileWriter fileWriter = null; try { fileWriter = new FileWriter(mergedSettingsFile); settingsWriter.write(fileWriter, mergedSettings); } finally { IOUtil.close(fileWriter); } if (getLog().isDebugEnabled()) { getLog().debug("Created temporary file for invoker settings.xml: " + mergedSettingsFile.getAbsolutePath()); } } catch (IOException e) { throw new MojoExecutionException("Could not create temporary file for invoker settings.xml", e); } } final File finalSettingsFile = mergedSettingsFile; if (mavenHome != null) { actualMavenVersion = SelectorUtils.getMavenVersion(mavenHome); } else { actualMavenVersion = SelectorUtils.getMavenVersion(); } scriptRunner.setGlobalVariable("mavenVersion", actualMavenVersion); if (javaHome != null) { resolveExternalJreVersion(); } else { actualJreVersion = SelectorUtils.getJreVersion(); } try { if (isParallelRun()) { getLog().info("use parallelThreads " + parallelThreads); ExecutorService executorService = Executors.newFixedThreadPool(parallelThreads); for (final BuildJob job : buildJobs) { executorService.execute(new Runnable() { public void run() { try { runBuild(projectsDir, job, finalSettingsFile); } catch (MojoExecutionException e) { throw new RuntimeException(e.getMessage(), e); } } }); } try { executorService.shutdown(); // TODO add a configurable time out executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new MojoExecutionException(e.getMessage(), e); } } else { for (BuildJob job : buildJobs) { runBuild(projectsDir, job, finalSettingsFile); } } } finally { if (interpolatedSettingsFile != null && cloneProjectsTo == null) { interpolatedSettingsFile.delete(); } if (mergedSettingsFile != null && mergedSettingsFile.exists()) { mergedSettingsFile.delete(); } } }
From source file:org.apache.maven.plugin.testing.AbstractMojoTestCase.java
protected void setUp() throws Exception { configurator = getContainer().lookup(ComponentConfigurator.class, "basic"); InputStream is = getClass().getResourceAsStream("/" + getPluginDescriptorLocation()); XmlStreamReader reader = new XmlStreamReader(is); InterpolationFilterReader interpolationFilterReader = new InterpolationFilterReader( new BufferedReader(reader), container.getContext().getContextData()); PluginDescriptor pluginDescriptor = new PluginDescriptorBuilder().build(interpolationFilterReader); Artifact artifact = lookup(RepositorySystem.class).createArtifact(pluginDescriptor.getGroupId(), pluginDescriptor.getArtifactId(), pluginDescriptor.getVersion(), ".jar"); artifact.setFile(new File(getBasedir()).getCanonicalFile()); pluginDescriptor.setPluginArtifact(artifact); pluginDescriptor.setArtifacts(Arrays.asList(artifact)); for (ComponentDescriptor<?> desc : pluginDescriptor.getComponents()) { getContainer().addComponentDescriptor(desc); }/*ww w . j a v a 2 s. c o m*/ mojoDescriptors = new HashMap<String, MojoDescriptor>(); for (MojoDescriptor mojoDescriptor : pluginDescriptor.getMojos()) { mojoDescriptors.put(mojoDescriptor.getGoal(), mojoDescriptor); } }
From source file:org.apache.maven.plugins.pdf.DocumentModelBuilder.java
/** * Extract the encoding./* ww w. j a va2 s . c om*/ * * @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; }
From source file:org.apache.maven.plugins.pdf.PdfMojo.java
/** * @return the DecorationModel instance from <code>site.xml</code> * @throws MojoExecutionException if any */// w w w . j a v a2 s .co m private DecorationModel getDefaultDecorationModel() throws MojoExecutionException { if (this.defaultDecorationModel == null) { final Locale locale = getDefaultLocale(); final File basedir = project.getBasedir(); final String relativePath = siteTool.getRelativePath(siteDirectory.getAbsolutePath(), basedir.getAbsolutePath()); final File descriptorFile = siteTool.getSiteDescriptorFromBasedir(relativePath, basedir, locale); DecorationModel decoration = null; if (descriptorFile.exists()) { XmlStreamReader reader = null; try { reader = new XmlStreamReader(descriptorFile); String enc = reader.getEncoding(); String siteDescriptorContent = IOUtil.toString(reader); siteDescriptorContent = siteTool.getInterpolatedSiteDescriptorContent( new HashMap<String, String>(2), project, siteDescriptorContent, enc, enc); 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:org.apache.maven.plugins.pdf.stubs.ModelBuilderMavenProjectStub.java
/** * Stub to test the DocumentModelBuilder. *//*from w w w . j a va 2 s.c o m*/ public ModelBuilderMavenProjectStub() { XmlStreamReader reader = null; try { reader = new XmlStreamReader(getFile()); final Model model = new MavenXpp3Reader().read(reader); setModel(model); reader.close(); reader = null; setGroupId(model.getGroupId()); setArtifactId(model.getArtifactId()); setVersion(model.getVersion()); setName(model.getName()); setDescription(model.getDescription()); setDevelopers(model.getDevelopers()); setOrganization(model.getOrganization()); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtil.close(reader); } }
From source file:org.omegat.util.TMXReader2.java
/** * Detects charset of XML file.//from w w w .j av a 2s. c om */ public static String detectCharset(File file) throws IOException { try (XmlStreamReader rd = new XmlStreamReader(file)) { return rd.getEncoding(); } }