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.owasp.dependencycheck.analyzer.NspAnalyzer.java

@Override
protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
    engine.removeDependency(dependency);
    final File file = dependency.getActualFile();
    if (!file.isFile() || file.length() == 0 || !shouldProcess(file)) {
        return;/*  w w w. j  a v  a  2s. c  o m*/
    }

    try (JsonReader jsonReader = Json.createReader(FileUtils.openInputStream(file))) {

        // Retrieves the contents of package.json from the Dependency
        final JsonObject packageJson = jsonReader.readObject();

        // Create a sanitized version of the package.json
        final JsonObject sanitizedJson = SanitizePackage.sanitize(packageJson);

        // Create a new 'package' object that acts as a container for the sanitized package.json
        final JsonObjectBuilder builder = Json.createObjectBuilder();
        final JsonObject nspPayload = builder.add("package", sanitizedJson).build();

        // Submits the package payload to the nsp check service
        final List<Advisory> advisories = searcher.submitPackage(nspPayload);

        for (Advisory advisory : advisories) {
            /*
             * Create a new vulnerability out of the advisory returned by nsp.
             */
            final Vulnerability vuln = new Vulnerability();
            vuln.setCvssScore(advisory.getCvssScore());
            vuln.setDescription(advisory.getOverview());
            vuln.setName(String.valueOf(advisory.getId()));
            vuln.setSource(Vulnerability.Source.NSP);
            vuln.addReference("NSP", "Advisory " + advisory.getId() + ": " + advisory.getTitle(),
                    advisory.getAdvisory());

            /*
             * Create a single vulnerable software object - these do not use CPEs unlike the NVD.
             */
            final VulnerableSoftware vs = new VulnerableSoftware();
            //TODO consider changing this to available versions on the dependency
            //  - the update is a part of the version, not versions to update to
            //vs.setUpdate(advisory.getPatchedVersions());

            vs.setName(advisory.getModule() + ":" + advisory.getVulnerableVersions());
            vuln.setVulnerableSoftware(new HashSet<>(Arrays.asList(vs)));

            final Dependency existing = findDependency(engine, advisory.getModule(), advisory.getVersion());
            if (existing == null) {
                final Dependency nodeModule = createDependency(dependency, advisory.getModule(),
                        advisory.getVersion(), "transitive");
                nodeModule.addVulnerability(vuln);
                engine.addDependency(nodeModule);
            } else {
                existing.addVulnerability(vuln);
            }
        }
    } catch (URLConnectionFailureException e) {
        this.setEnabled(false);
        throw new AnalysisException(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.debug("Error reading dependency or connecting to Node Security Platform - check API", e);
        this.setEnabled(false);
        throw new AnalysisException(e.getMessage(), e);
    } catch (JsonException e) {
        throw new AnalysisException(String.format("Failed to parse %s file.", file.getPath()), e);
    }
}

From source file:org.panthercode.arctic.core.settings.Configuration.java

/**
 * Load the configuration from file./*w w  w  .ja v  a 2 s  .  c o  m*/
 *
 * @param path path to file
 * @throws IOException Is thrown if an error occurs while reading file.
 */
public void load(final String path) throws IOException {
    try (FileInputStream stream = FileUtils.openInputStream(new File(path))) {
        load(stream);
    }
}

From source file:org.pentaho.di.trans.steps.terafast.TeraFast.java

/**
 * Invoke loading with control file.//from   www . j  a v a 2s . com
 *
 * @throws KettleException
 *           ...
 */
private void invokeLoadingControlFile() throws KettleException {
    File controlFile = null;
    final InputStream control;
    final String controlContent;
    try {
        controlFile = new File(resolveFileName(this.meta.getControlFile().getValue()));
        control = FileUtils.openInputStream(controlFile);
        controlContent = environmentSubstitute(FileUtils.readFileToString(controlFile));
    } catch (IOException e) {
        throw new KettleException("Cannot open control file [path=" + controlFile + "]", e);
    }
    try {
        IOUtils.write(controlContent, this.fastload);
        this.fastload.flush();
    } catch (IOException e) {
        throw new KettleException("Cannot pipe content of control file to fastload [path=" + controlFile + "]",
                e);
    } finally {
        IOUtils.closeQuietly(control);
        IOUtils.closeQuietly(this.fastload);
    }
}

From source file:org.pentaho.platform.plugin.services.importexport.RepositoryFileBundle.java

public InputStream getInputStream() throws IOException {
    return new BufferedInputStream(FileUtils.openInputStream(tmpFile));
}

From source file:org.pentaho.platform.repository2.unified.webservices.jaxws.SimpleRepositoryFileDataDto.java

/**
 * Converts SimpleRepositoryFileDataDto to SimpleRepositoryFileData.
 *//* w w  w. j a va2  s .  com*/
public static SimpleRepositoryFileData convert(final SimpleRepositoryFileDataDto simpleJaxWsData) {
    FileOutputStream fout = null;
    InputStream in = null;
    DataHandler dh = null;
    boolean foutClosed = false;
    try {
        File tmpFile = File.createTempFile("pentaho", null); //$NON-NLS-1$
        // TODO mlowery this might not delete files soon enough
        tmpFile.deleteOnExit();
        fout = FileUtils.openOutputStream(tmpFile);
        // used to cast to com.sun.xml.ws.developer.StreamingDataHandler here but that stopped working
        dh = simpleJaxWsData.dataHandler;
        // used to call dh.readOnce() (instead of dh.getInputStream()) here
        in = dh.getInputStream();
        IOUtils.copy(in, fout);
        fout.close();
        foutClosed = true;
        InputStream fin = new BufferedInputStream(FileUtils.openInputStream(tmpFile));
        return new SimpleRepositoryFileData(fin, simpleJaxWsData.encoding, simpleJaxWsData.mimeType);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            // close the streams
            if (in != null) {
                in.close();
            }
            // used to have to call dh.close() on the com.sun.xml.ws.developer.StreamingDataHandler here
            if (fout != null && !foutClosed) {
                fout.close();
            }
        } catch (Exception e) {
            // CHECKSTYLES IGNORE
        }
    }
}

From source file:org.pptx4j.samples.SlideNotes.java

public static void main(String[] args) throws Exception {

    // Where will we save our new .ppxt?
    String outputfilepath = System.getProperty("user.dir") + "/sample-docs/OUT_SlideNotes.pptx";

    // Create skeletal package, including a MainPresentationPart and a SlideLayoutPart
    PresentationMLPackage presentationMLPackage = PresentationMLPackage.createPackage();

    // Need references to these parts to create a slide
    // Please note that these parts *already exist* - they are
    // created by createPackage() above.  See that method
    // for instruction on how to create and add a part.
    MainPresentationPart pp = (MainPresentationPart) presentationMLPackage.getParts().getParts()
            .get(new PartName("/ppt/presentation.xml"));
    SlideLayoutPart layoutPart = (SlideLayoutPart) presentationMLPackage.getParts().getParts()
            .get(new PartName("/ppt/slideLayouts/slideLayout1.xml"));

    // OK, now we can create a slide
    SlidePart slidePart = new SlidePart(new PartName("/ppt/slides/slide1.xml"));
    slidePart.setContents(SlidePart.createSld());
    pp.addSlide(0, slidePart);/*w ww  .j  ava 2 s . co  m*/

    // Slide layout part
    slidePart.addTargetPart(layoutPart);

    // Create and add shape
    Shape sample = ((Shape) XmlUtils.unmarshalString(SAMPLE_SHAPE, Context.jcPML));
    slidePart.getJaxbElement().getCSld().getSpTree().getSpOrGrpSpOrGraphicFrame().add(sample);

    // Now add notes slide.
    // 1. Notes master
    NotesMasterPart nmp = new NotesMasterPart();
    NotesMaster notesmaster = (NotesMaster) XmlUtils.unmarshalString(notesMasterXml, Context.jcPML);
    nmp.setJaxbElement(notesmaster);
    // .. connect it to /ppt/presentation.xml
    Relationship ppRelNmp = pp.addTargetPart(nmp);
    /*
     *  <p:notesMasterIdLst>
        <p:notesMasterId r:id="rId3"/>
    </p:notesMasterIdLst>
     */
    pp.getJaxbElement().setNotesMasterIdLst(createNotesMasterIdListPlusEntry(ppRelNmp.getId()));

    // .. NotesMasterPart typically has a rel to a theme 
    // .. can we get away without it? 
    // Nope .. read this in from a file
    ThemePart themePart = new ThemePart(new PartName("/ppt/theme/theme2.xml"));
    // TODO: read it from a string instead
    themePart.unmarshal(FileUtils.openInputStream(new File(System.getProperty("user.dir") + "/theme2.xml")));
    nmp.addTargetPart(themePart);

    // 2. Notes slide
    NotesSlidePart nsp = new NotesSlidePart();
    Notes notes = (Notes) XmlUtils.unmarshalString(notesXML, Context.jcPML);
    nsp.setJaxbElement(notes);
    // .. connect it to the slide
    slidePart.addTargetPart(nsp);
    // .. it also has a rel to the slide
    nsp.addTargetPart(slidePart);
    // .. and the slide master
    nsp.addTargetPart(nmp);

    // All done: save it
    presentationMLPackage.save(new java.io.File(outputfilepath));

    System.out.println("\n\n done .. saved " + outputfilepath);

}

From source file:org.rundeck.api.RundeckClient.java

/**
 * Import the definitions of jobs, from the given input stream, using the given behavior
 *
 * @param rundeckJobsImport import request, see {@link RundeckJobsImportBuilder}
 *
 * @return a {@link RundeckJobsImportResult} instance - won't be null
 *
 * @throws RundeckApiException      in case of error when calling the API
 * @throws RundeckApiLoginException if the login fails (in case of login-based authentication)
 * @throws RundeckApiTokenException if the token is invalid (in case of token-based authentication)
 * @throws IllegalArgumentException if the stream or fileType is null
 * @see #importJobs(RundeckJobsImport)// w  w w  . ja  v  a2 s.  co m
 */
public RundeckJobsImportResult importJobs(final String filename, final RundeckJobsImport rundeckJobsImport)
        throws RundeckApiException, RundeckApiLoginException, RundeckApiTokenException,
        IllegalArgumentException, IOException {
    AssertUtil.notBlank(filename, "filename (of jobs file) is mandatory to import jobs !");
    FileInputStream stream = null;
    try {
        stream = FileUtils.openInputStream(new File(filename));
        return importJobs(RundeckJobsImportBuilder.builder(rundeckJobsImport).setStream(stream).build());
    } finally {

        IOUtils.closeQuietly(stream);
    }
}

From source file:org.rundeck.api.RundeckClient.java

/**
 * Trigger the execution of an ad-hoc script read from a file, and return immediately (without waiting the end of
 * the execution). The script will be dispatched to nodes, accordingly to the nodeFilters parameter.
 *
 * @param script         the RunAdhocScript, see {@link RunAdhocScriptBuilder}
 * @param scriptFilename a file to read as the input script stream
 *
 * @return a {@link RundeckExecution} instance for the newly created (and running) execution - won't be null
 *
 * @throws RundeckApiException      in case of error when calling the API (non-existent project with this name)
 * @throws RundeckApiLoginException if the login fails (in case of login-based authentication)
 * @throws RundeckApiTokenException if the token is invalid (in case of token-based authentication)
 * @throws IllegalArgumentException if the project is blank (null, empty or whitespace) or the script is null
 * @throws IOException              if an error occurs reading the script file
 * @see #triggerAdhocScript(RunAdhocScript)
 * @see #runAdhocScript(RunAdhocScript, long, java.util.concurrent.TimeUnit)
 *///from  w  w  w. j a  v  a 2 s .c  o m
public RundeckExecution triggerAdhocScript(final RunAdhocScript script, final String scriptFilename)
        throws RundeckApiException, RundeckApiLoginException, RundeckApiTokenException,
        IllegalArgumentException, IOException {
    AssertUtil.notBlank(scriptFilename, "scriptFilename is mandatory to trigger an ad-hoc script !");
    FileInputStream stream = null;
    try {
        stream = FileUtils.openInputStream(new File(scriptFilename));
        return triggerAdhocScript(RunAdhocScriptBuilder.builder(script).setScript(stream).build());
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.rundeck.api.RundeckClient.java

/**
 * Run an ad-hoc script read from a file, and wait until its execution is finished (or aborted) to return. We will
 * poll the Rundeck server at regular interval (configured by the poolingInterval/poolingUnit couple) to know if the
 * execution is finished (or aborted) or is still running. The script will be dispatched to nodes, accordingly to
 * the nodeFilters parameter.// w w w . jav a2s.c o m
 *
 * @param script          the RunAdhocScript, see {@link RunAdhocScriptBuilder}
 * @param scriptFilename  filename of a script to read
 * @param poolingInterval for checking the status of the execution. Must be > 0.
 * @param poolingUnit     unit (seconds, milli-seconds, ...) of the interval. Default to seconds.
 *
 * @return a {@link RundeckExecution} instance for the (finished/aborted) execution - won't be null
 *
 * @throws RundeckApiException      in case of error when calling the API (non-existent project with this name)
 * @throws RundeckApiLoginException if the login fails (in case of login-based authentication)
 * @throws RundeckApiTokenException if the token is invalid (in case of token-based authentication)
 * @throws IllegalArgumentException if the project is blank (null, empty or whitespace) or the script is null
 * @throws IOException              if we failed to read the file
 * @see #runAdhocScript(RunAdhocScript)
 * @see #triggerAdhocScript(RunAdhocScript, String)
 */
public RundeckExecution runAdhocScript(final RunAdhocScript script, final String scriptFilename,
        final long poolingInterval, final TimeUnit poolingUnit) throws RundeckApiException,
        RundeckApiLoginException, RundeckApiTokenException, IllegalArgumentException, IOException {
    FileInputStream stream = null;
    try {
        stream = FileUtils.openInputStream(new File(scriptFilename));
        return runAdhocScript(RunAdhocScriptBuilder.builder(script).setScript(stream).build(), poolingInterval,
                poolingUnit);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.saiku.repository.ClassPathRepositoryManager.java

public List<DataSource> getAllDataSources() throws RepositoryException {

    List<DataSource> ds = new ArrayList<>();

    String[] extensions = new String[1];
    extensions[0] = "sds";
    Collection<File> files = FileUtils.listFiles(new File(append), extensions, true);

    for (File file : files) {
        JAXBContext jaxbContext = null;
        Unmarshaller jaxbMarshaller = null;
        try {//from w w  w  .  j  a v  a2  s .  c om
            jaxbContext = JAXBContext.newInstance(DataSource.class);
        } catch (JAXBException e) {
            log.error("Could not read XML", e);
        }
        try {
            jaxbMarshaller = jaxbContext != null ? jaxbContext.createUnmarshaller() : null;
        } catch (JAXBException e) {
            log.error("Could not read XML", e);
        }
        InputStream stream = null;
        try {
            stream = (FileUtils.openInputStream(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        DataSource d = null;
        try {
            d = (DataSource) (jaxbMarshaller != null ? jaxbMarshaller.unmarshal(stream) : null);
        } catch (JAXBException e) {
            log.error("Could not read XML", e);
        }

        if (d != null) {
            d.setPath(file.getPath());
        }
        if (file.getParentFile().isDirectory()) {
            String p = file.getParent();
            p = p.replace("\\", "/");
            String[] s = p.split("/");

            log.debug("p split: " + p);
            String[] t = append.split("/");
            if (!s[s.length - 2].equals(t[t.length - 1])) {
                d.setName(s[s.length - 2] + "_" + (d != null ? d.getName() : ""));
            }
        }

        ds.add(d);
    }
    return ds;
}