Example usage for org.apache.commons.io FileUtils openInputStream

List of usage examples for org.apache.commons.io FileUtils openInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils openInputStream.

Prototype

public static FileInputStream openInputStream(File file) throws IOException 

Source Link

Document

Opens a FileInputStream for the specified file, providing better error messages than simply calling new FileInputStream(file).

Usage

From source file:org.jdev.emg.sonar.cci.CCIXmlMetricsDecorator.java

@Override
public void decorate(Resource resource, DecoratorContext context) {
    if (!Qualifiers.isFile(resource)) {
        return;//from  w  w  w.  ja  v a 2s. co  m
    }
    ProjectFileSystem fileSystem = context.getProject().getFileSystem();
    File file = lookup(resource, fileSystem);

    try {
        if (readFirstByte(file) != '<') {
            return;
        }
    } catch (IOException e) {
        throw new SonarException(e);
    }

    int numCommentLines;
    CCICountCommentParser commentCounter = new CCICountCommentParser();
    try {
        numCommentLines = commentCounter.countLinesOfComment(FileUtils.openInputStream(file));
        if (numCommentLines == -1) {
            return;
        }
    } catch (IOException e) {
        throw new SonarException(e);
    }

    LineIterator iterator = null;
    int numLines = 0;
    int numBlankLines = 0;
    try {
        Charset charset = fileSystem.getSourceCharset();
        iterator = charset == null ? FileUtils.lineIterator(file)
                : FileUtils.lineIterator(file, charset.name());
        while (iterator.hasNext()) {
            String line = iterator.nextLine();
            numLines++;
            if (line.trim().isEmpty()) {
                numBlankLines++;
            }
        }
    } catch (IOException e) {
        LOG.warn("error reading " + file + " to collect metrics", e);
    } finally {
        LineIterator.closeQuietly(iterator);
    }

    context.saveMeasure(CoreMetrics.LINES, (double) numLines); // Lines
    context.saveMeasure(CoreMetrics.COMMENT_LINES, (double) numCommentLines); // Non Commenting Lines of Code
    context.saveMeasure(CoreMetrics.NCLOC, (double) numLines - numBlankLines - numCommentLines); // Comment Lines
}

From source file:org.jenkinsci.plugins.pipeline.modeldefinition.DeclarativeLinterCommandTest.java

@Test
public void validJenkinsfile() throws Exception {
    File testPath = writeJenkinsfileToTmpFile("simplePipeline");
    j.jenkins.disableSecurity();/* w w  w  .ja v  a  2s .c o  m*/

    final CLICommandInvoker.Result result = command.withStdin(FileUtils.openInputStream(testPath)).invoke();

    assertThat(result, succeeded());
    assertThat(result, hasNoErrorOutput());
    assertThat(result.stdout(), containsString("Jenkinsfile successfully validated."));
}

From source file:org.jenkinsci.plugins.pipeline.modeldefinition.DeclarativeLinterCommandTest.java

@Test
public void invalidJenkinsfile() throws Exception {
    File testPath = writeJenkinsfileToTmpFile("errors", "emptyAgent");
    j.jenkins.disableSecurity();//from  w ww.  j a  va 2 s  . c  o  m

    final CLICommandInvoker.Result result = command.withStdin(FileUtils.openInputStream(testPath)).invoke();

    assertThat(result, failedWith(1));
    assertThat(result, hasNoErrorOutput());
    assertThat(result.stdout(), containsString("Errors encountered validating Jenkinsfile:"));
    assertThat(result.stdout(),
            containsString("Not a valid section definition: \"agent\". Some extra configuration is required"));
}

From source file:org.jenkinsci.plugins.pipeline.modeldefinition.DeclarativeLinterCommandTest.java

@Test
public void invalidUser() throws Exception {
    File testPath = writeJenkinsfileToTmpFile("simplePipeline");

    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy().grant(Jenkins.ADMINISTER).everywhere()
            .to("bob").grant(Jenkins.READ, Item.READ, Item.EXTENDED_READ).everywhere().to("alice"));

    final CLICommandInvoker.Result result = command.withStdin(FileUtils.openInputStream(testPath)).invoke();

    assertThat(result, not(succeeded()));
    assertThat(result.stderr(), containsString("ERROR: anonymous is missing the Overall/Read permission"));
}

From source file:org.jfrog.teamcity.server.runner.ArtifactoryBuildStartContextProcessor.java

private void readAndAddFileProps(SRunnerContext runnerContext, String... propTypes) {
    Map<String, String> buildParams = runnerContext.getBuildParameters();
    for (String propType : propTypes) {
        String propFilePropKey = propType + BuildInfoConfigProperties.PROP_PROPS_FILE;
        String propertyFilePath = buildParams.get(propFilePropKey);
        if (StringUtils.isNotBlank(propertyFilePath)) {
            File propertiesFile = new File(propertyFilePath);

            if (!propertiesFile.exists()) {
                Loggers.SERVER.error("Ignoring build info properties file at '" + propertyFilePath
                        + "' given from property '" + propFilePropKey + "': file does not exist.");
                return;
            }//from ww  w.  j a  v a 2  s  .co  m

            if (!propertiesFile.canRead()) {
                Loggers.SERVER.error("Ignoring build info properties file at '" + propertyFilePath
                        + "' given from property '" + propFilePropKey + "': lacking read permissions.");
                return;
            }

            FileInputStream inputStream = null;
            try {
                inputStream = FileUtils.openInputStream(propertiesFile);
                Properties properties = new Properties();
                properties.load(inputStream);
                Map<Object, Object> filteredProperties = Maps.filterKeys(properties, new Predicate<Object>() {
                    public boolean apply(Object input) {
                        String key = (String) input;
                        return key.startsWith(BuildInfoProperties.BUILD_INFO_PROP_PREFIX)
                                || key.startsWith(ClientProperties.PROP_DEPLOY_PARAM_PROP_PREFIX);
                    }
                });
                for (Map.Entry<Object, Object> entry : filteredProperties.entrySet()) {
                    runnerContext.addBuildParameter(propType + entry.getKey(), (String) entry.getValue());
                }
            } catch (IOException ioe) {
                Loggers.SERVER.error("Error while reading build info properties file at '" + propertyFilePath
                        + "' given from property '" + propFilePropKey + "': " + ioe.getMessage());
                Loggers.SERVER.error(ioe);
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    }
}

From source file:org.jumpmind.properties.DefaultParameterParser.java

public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        System.err.println("Usage: <input_properties_file> <output_docbook_file> [true|false]");
    }// ww w.ja  v  a  2s. co  m
    DefaultParameterParser parmParser = null;
    if (args[0].startsWith("classpath:")) {
        parmParser = new DefaultParameterParser(args[0].replaceAll("classpath:", ""));
    } else {
        parmParser = new DefaultParameterParser(FileUtils.openInputStream(new File(args[0])));
    }
    new File(args[1]).getParentFile().mkdirs();

    FileWriter writer = new FileWriter(args[1]);
    boolean isDatabaseOverridable = Boolean.parseBoolean(args[2]);
    boolean isAsciiDocFormat = args.length > 3 && "asciidoc".equals(args[3]);

    Map<String, ParameterMetaData> map = parmParser.parse();
    if (!isAsciiDocFormat) {
        writer.write("<variablelist>\n");
    }

    for (ParameterMetaData parm : map.values()) {
        if ((isDatabaseOverridable && parm.isDatabaseOverridable())
                || (!isDatabaseOverridable && !parm.isDatabaseOverridable())) {
            if (!isAsciiDocFormat) {
                writer.write("<varlistentry>\n<term><command>" + parm.getKey() + "</command></term>\n");
                writer.write("<listitem><para>" + parm.getDescription() + " [ Default: "
                        + (parm.isXmlType() ? StringEscapeUtils.escapeXml(parm.getDefaultValue())
                                : parm.getDefaultValue())
                        + " ]</para></listitem>\n</varlistentry>\n");
            } else {
                writer.write(parm.getKey() + ":: " + parm.getDescription() + "\n\n_Default:_ "
                        + (parm.isXmlType()
                                ? "\n\n[source, xml]\n----\n" + parm.getDefaultValue() + "\n----\n\n"
                                : (isBlank(parm.getDefaultValue()) ? "" : "_" + parm.getDefaultValue() + "_")
                                        + "\n\n"));
            }
        }
    }

    if (!isAsciiDocFormat) {
        writer.write("</variablelist>\n");
    }
    writer.close();
}

From source file:org.localmatters.lesscss4j.parser.FileStyleSheetResource.java

public InputStream getInputStream() throws IOException {
    return FileUtils.openInputStream(getFile());
}

From source file:org.mitre.mpf.wfm.camel.operations.mediainspection.MediaInspectionProcessor.java

private Metadata generateFFMPEGMetadata(File fileName) throws IOException, TikaException, SAXException {
    Tika tika = new Tika();
    Metadata metadata = new Metadata();
    ContentHandler handler = new DefaultHandler();
    URL url = this.getClass().getClassLoader().getResource("tika-external-parsers.xml");
    Parser parser = org.apache.tika.parser.external.ExternalParsersConfigReader.read(url.openStream()).get(0);

    ParseContext context = new ParseContext();
    String mimeType = null;/*from w  w  w . jav  a2 s  .com*/
    try (InputStream stream = Preconditions.checkNotNull(
            IOUtils.toBufferedInputStream(FileUtils.openInputStream(fileName)), "Cannot open file '%s'",
            fileName)) {
        mimeType = tika.detect(stream);
        metadata.set(Metadata.CONTENT_TYPE, mimeType);
    }
    try (InputStream stream = Preconditions.checkNotNull(
            IOUtils.toBufferedInputStream(FileUtils.openInputStream(fileName)), "Cannot open file '%s'",
            fileName)) {
        parser.parse(stream, handler, metadata, context);
    }
    return metadata;
}

From source file:org.mitre.mpf.wfm.camel.operations.mediainspection.MediaInspectionProcessor.java

private Metadata generateExifMetadata(File fileName) throws IOException, TikaException, SAXException {
    Tika tika = new Tika();
    Metadata metadata = new Metadata();
    ContentHandler handler = new DefaultHandler();
    Parser parser = new AutoDetectParser();
    ParseContext context = new ParseContext();
    String mimeType = null;//from  ww w .j a v  a 2  s .c o  m
    try (InputStream stream = Preconditions.checkNotNull(
            IOUtils.toBufferedInputStream(FileUtils.openInputStream(fileName)), "Cannot open file '%s'",
            fileName)) {
        mimeType = tika.detect(stream);
        metadata.set(Metadata.CONTENT_TYPE, mimeType);
    }
    try (InputStream stream = Preconditions.checkNotNull(
            IOUtils.toBufferedInputStream(FileUtils.openInputStream(fileName)), "Cannot open file '%s'",
            fileName)) {
        parser.parse(stream, handler, metadata, context);
    }
    return metadata;
}

From source file:org.n52.sos.XmlToExiConverter.java

protected void encode(String fileName) {
    try (InputStream exiIS = FileUtils.openInputStream(getFile(fileName, XML_EXTENSION));
            OutputStream exiOS = FileUtils.openOutputStream(getFile(fileName, EXI_EXTENSION))) {
        EXIResult exiResult = new EXIResult();
        exiResult.setOutputStream(exiOS);
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setContentHandler(exiResult.getHandler());
        xmlReader.parse(new InputSource(exiIS));
    } catch (Exception e) {
        // TODO: handle exception
    }/*  w  ww .  j a  va 2s  . com*/
}