Example usage for org.apache.commons.io IOUtils closeQuietly

List of usage examples for org.apache.commons.io IOUtils closeQuietly

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils closeQuietly.

Prototype

public static void closeQuietly(OutputStream output) 

Source Link

Document

Unconditionally close an OutputStream.

Usage

From source file:com.revo.deployr.client.example.data.io.auth.stateful.preload.MultipleDataInMultipleDataOut.java

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

    RClient rClient = null;/*from   w ww. jav a  2  s .c  o  m*/
    RProject rProject = null;

    try {

        /*
         * Determine DeployR server endpoint.
         */
        String endpoint = System.getProperty("endpoint");
        log.info("[ CONFIGURATION  ] Using endpoint=" + endpoint);

        /*
         * Establish RClient connection to DeployR server.
         *
         * An RClient connection is the mandatory starting
         * point for any application using the client library.
         */
        rClient = RClientFactory.createClient(endpoint);

        log.info("[   CONNECTION   ] Established anonymous " + "connection [ RClient ].");

        /*
         * Build a basic authentication token.
         */
        RAuthentication rAuth = new RBasicAuthentication(System.getProperty("username"),
                System.getProperty("password"));

        /*
         * Establish an authenticated handle with the DeployR
         * server, rUser. Following this call the rClient 
         * connection is operating as an authenticated connection
         * and all calls on rClient inherit the access permissions
         * of the authenticated user, rUser.
         */
        RUser rUser = rClient.login(rAuth);
        log.info("[ AUTHENTICATION ] Upgraded to authenticated " + "connection [ RUser ].");

        /*
         * Create a ProjectCreationOptions instance
         * to specify data inputs that "pre-heat" the R session
         * workspace or working directory for your project.
         */
        ProjectCreationOptions creationOpts = new ProjectCreationOptions();

        /*
         * MultipleDataInMultipleDataOut Example Note:
         * 
         * The preload inputs sent on this example are
         * contrived and superfluous as the hipStar.rData
         * binary R object input and the hipStarUrl input
         * perform the exact same purpose...to load the Hip STAR
         * dataset into the workspace at project initialization.
         * 
         * The example is provided to simply demonstrate
         * the mechanism of specifying multiple preload inputs.
         */

        /* 
         * Preload from the DeployR repository the following
         * binary R object input file:
         * /testuser/example-data-io/hipStar.rData
         */
        ProjectPreloadOptions preloadWorkspace = new ProjectPreloadOptions();
        preloadWorkspace.filename = "hipStar.rData";
        preloadWorkspace.directory = "example-data-io";
        preloadWorkspace.author = "testuser";
        creationOpts.preloadWorkspace = preloadWorkspace;

        log.info("[ PRELOAD INPUT  ] Repository binary file input "
                + "set on project creation, [ ProjectCreationOptions.preloadWorkspace ].");

        /* 
         * Load an R object literal "hipStarUrl" into the
         * workspace on project initialization.
         *
         * The R script execution that follows will check for
         * the existence of "hipStarUrl" in the workspace and if
         * present uses the URL path to load the Hipparcos star
         * dataset from the DAT file at that location.
         */
        RData hipStarUrl = RDataFactory.createString("hipStarUrl", HIP_DAT_URL);
        List<RData> rinputs = Arrays.asList(hipStarUrl);
        creationOpts.rinputs = rinputs;

        log.info("[ PRELOAD INPUT  ] External data source input "
                + "set on project creation, [ ProjectCreationOptions.rinputs ].");

        /*
         * Create a temporary project (R session) passing a 
         * ProjectCreationOptions to "pre-heat" data into the
         * workspace and/or working directory.
         */
        rProject = rUser.createProject(creationOpts);

        log.info("[  GO STATEFUL   ] Created stateful temporary " + "R session [ RProject ].");

        /*
         * Create a ProjectExecutionOptions instance
         * to specify data inputs and output to the
         * execution of the repository-managed R script.
         *
         * This options object can be used to pass standard
         * execution model parameters on execution calls. All
         * fields are optional.
         *
         * See the Standard Execution Model chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        ProjectExecutionOptions execOpts = new ProjectExecutionOptions();

        /*
         * Request the retrieval of the "hip" data.frame and
         * two vector objects from the workspace following the
         * execution. The corresponding R objects are named as
         * follows:
         * 'hip', hipDim', 'hipNames'.
         */
        execOpts.routputs = Arrays.asList("hip", "hipDim", "hipNames");

        log.info("[  EXEC OPTION   ] DeployR-encoded R object request "
                + "set on execution [ ProjectExecutionOptions.routputs ].");

        /*
         * Execute a public analytics Web service as an authenticated
         * user based on a repository-managed R script:
         * /testuser/example-data-io/dataIO.R
         */
        RProjectExecution exec = rProject.executeScript("dataIO.R", "example-data-io", "testuser", null,
                execOpts);

        log.info("[   EXECUTION    ] Stateful R script " + "execution completed [ RProjectExecution ].");

        /*
         * Retrieve multiple outputs following the execution:
         *
         * 1. R console output.
         * 2. R console output.
         * 3. R console output.
         * 4. R console output.
         * 5. R console output.
         */

        String console = exec.about().console;
        log.info("[  DATA OUTPUT   ] Retrieved R console " + "output [ String ].");

        /*
         * Retrieve the requested R object data encodings from
         * the workspace follwing the script execution. 
         *
         * See the R Object Data Decoding chapter in the
         * Client Library Tutorial on the DeployR website for
         * further details.
         */
        List<RData> objects = exec.about().workspaceObjects;

        for (RData rData : objects) {
            if (rData instanceof RDataFrame) {
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object output " + rData.getName()
                        + " [ RDataFrame ].");
                List<RData> hipSubsetVal = ((RDataFrame) rData).getValue();
            } else if (rData instanceof RNumericVector) {
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object output " + rData.getName()
                        + " [ RNumericVector ].");
                List<Double> hipDimVal = ((RNumericVector) rData).getValue();
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object " + rData.getName()
                        + " value=" + hipDimVal);
            } else if (rData instanceof RStringVector) {
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object output " + rData.getName()
                        + " [ RStringVector ].");
                List<String> hipNamesVal = ((RStringVector) rData).getValue();
                log.info("[  DATA OUTPUT   ] Retrieved DeployR-encoded R " + "object " + rData.getName()
                        + " value=" + hipNamesVal);
            } else {
                log.info("Unexpected DeployR-encoded R object returned, " + "object name=" + rData.getName()
                        + ", encoding=" + rData.getClass());
            }
        }

        /*
         * Retrieve the working directory files (artifact)
         * was generated by the execution.
         */
        List<RProjectFile> wdFiles = exec.about().artifacts;

        for (RProjectFile wdFile : wdFiles) {
            log.info("[  DATA OUTPUT   ] Retrieved working directory " + "file output "
                    + wdFile.about().filename + " [ RProjectFile ].");
            InputStream fis = null;
            try {
                fis = wdFile.download();
            } catch (Exception ex) {
                log.warn("Working directory binary file download " + ex);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }

        /*
         * Retrieve R graphics device plots (results) called
         * unnamedplot*.png that was generated by the execution.
         */
        List<RProjectResult> results = exec.about().results;

        for (RProjectResult result : results) {
            log.info("[  DATA OUTPUT   ] Retrieved graphics device " + "plot output " + result.about().filename
                    + " [ RProjectResult ].");
            InputStream fis = null;
            try {
                fis = result.download();
            } catch (Exception ex) {
                log.warn("Graphics device plot download " + ex);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }

    } catch (Exception ex) {
        log.warn("Unexpected runtime exception=" + ex);
    } finally {
        try {
            if (rProject != null) {
                /*
                 * Close rProject before application exits.
                 */
                rProject.close();
            }
        } catch (Exception fex) {
        }
        try {
            if (rClient != null) {
                /*
                 * Release rClient connection before application exits.
                 */
                rClient.release();
            }
        } catch (Exception fex) {
        }
    }

}

From source file:com.wfd.util.FileUtil.java

public static void writeToFile(InputStream in, String filePath) {
    try {/*from  w ww . j a  va2s  .com*/
        byte[] data = IOUtils.toByteArray(in);
        FileUtils.writeByteArrayToFile(new File(filePath), data);
        IOUtils.closeQuietly(in);
    } catch (Exception e) {
        System.out.println("Failed to conver inputstream to an image in server.");
        e.printStackTrace();
    }
}

From source file:com.mayalogy.mayu.io.FileAppender.java

public static void appendToFile(final InputStream in, final File f) throws IOException {
    OutputStream stream = null;//w  w w .  ja va2s  .c o m
    try {
        stream = outStream(f);
        IOUtils.copy(in, stream);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:gov.nih.nci.caintegrator.application.study.ExternalLinksLoader.java

static void loadLinks(ExternalLinkList externalLinkList) throws ValidationException, IOException {
    CSVReader reader = new CSVReader(new FileReader(externalLinkList.getFile()));
    try {/*w  w  w.  ja va 2s.  c  o m*/
        loadLinks(externalLinkList, reader);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.mayalogy.mayu.io.FileAppender.java

public static void appendToFile(final String in, final File f) throws IOException {
    InputStream stream = null;//  w ww. j  a va  2s  .  c o m
    try {
        stream = IOUtils.toInputStream(in);
        appendToFile(stream, f);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:bookstore.BookUnmarshaller.java

public static Book[] BooksFromCsv(String url) {
    InputStream in = null;//  ww  w . jav  a 2s  .c o  m
    Book[] books;
    try {
        in = new URL(url).openStream();
        books = BooksFromString(IOUtils.toString(in, Charset.forName("utf-8")));
    } catch (IOException | ParseException | NumberFormatException e) {
        return null;
    } finally {
        IOUtils.closeQuietly(in);
    }
    return books;
}

From source file:net.bpelunit.util.FileUtil.java

public static byte[] readFile(File f) throws IOException {
    FileInputStream bprInputStream = null;
    try {/*from   ww  w  .java  2s.co  m*/
        bprInputStream = new FileInputStream(f);
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream((int) f.length());
        IOUtils.copy(bprInputStream, bytesOut);

        return bytesOut.toByteArray();
    } finally {
        IOUtils.closeQuietly(bprInputStream);
    }
}

From source file:gaffer.example.gettingstarted.util.DataUtils.java

public static List<String> loadData(final InputStream dataStream) {
    List<String> lines = null;
    try {/*from   w w w  .ja va 2  s.  c  o m*/
        lines = IOUtils.readLines(dataStream);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(dataStream);
    }
    return lines;
}

From source file:com.google.gwt.site.markdown.Util.java

public static String getStringFromFile(File file) throws IOException {
    FileInputStream fileInputStream = null;
    try {//ww w. j av  a  2s .c  o  m
        fileInputStream = new FileInputStream(file);
        return IOUtils.toString(fileInputStream, "UTF-8");
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:net.javacrumbs.mocksocket.util.Utils.java

public static final byte[] toByteArray(InputStream stream) {
    try {//  w  ww .  j  a v  a 2s.c  o m
        return IOUtils.toByteArray(stream);
    } catch (IOException e) {
        throw new MockSocketException("Can not read data.", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}