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

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

Introduction

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

Prototype

public static String toString(byte[] input) throws IOException 

Source Link

Document

Get the contents of a byte[] as a String using the default character encoding of the platform.

Usage

From source file:com.tek271.reverseProxy.utils.FileTools.java

static String toString(InputStream stream) {
    try {//from   w  ww.  j  a v a  2  s.  co  m
        return IOUtils.toString(stream);
    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot read stream", e);
    }
}

From source file:com.denimgroup.threadfix.service.defects.util.HttpTrafficFileLoader.java

public static String getResponse(String fileName) {
    try {//from w ww.j  a v a2  s. c o m
        String filePath = "httptraffic/" + fileName + ".txt";

        InputStream stream = HttpTrafficFileLoader.class.getClassLoader().getResourceAsStream(filePath);

        assertFalse("Stream was null for " + filePath, stream == null);

        return IOUtils.toString(stream);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.callidusrobotics.object.ItemFactory.java

@SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel")
public static synchronized void initializeFactory(final String xmlFile) throws IOException {
    final XmlMarshaller xmlMarshaller = new XmlMarshaller(ItemList.class);
    final ItemList itemList = (ItemList) xmlMarshaller
            .unMarshal(IOUtils.toString(ItemFactory.class.getResourceAsStream(xmlFile)));

    for (final ItemData itemData : itemList.items) {
        if (ITEM_MAP.containsKey(itemData.getId())) {
            throw new AssertionError(
                    "Encountered duplicate ItemData ID (" + itemData.getId() + ") in " + xmlFile);
        }//w w w .  ja v  a 2 s . c  o  m

        ITEM_MAP.put(itemData.getId(), itemData);
    }
}

From source file:de.shadowhunt.subversion.internal.AbstractRepositoryDownloadIT.java

public static void assertEquals(final String message, final InputStream expected, final InputStream actual)
        throws Exception {
    try {// w  w w.  j  a v  a  2  s .c  o  m
        Assert.assertEquals(message, IOUtils.toString(expected).trim(), IOUtils.toString(actual).trim());
    } finally {
        IOUtils.closeQuietly(expected);
        IOUtils.closeQuietly(actual);
    }
}

From source file:com.fluke.parser.YahooIntradayParserTest.java

@Test
public void testParseData() throws FileNotFoundException, IOException {
    String data = IOUtils
            .toString(YahooIntradayParser.class.getClassLoader().getResourceAsStream("intraday_data"));
    IntradayDetails details = (IntradayDetails) new YahooIntradayParser().parseData(data);
    assertNotNull(details);//from   w  w  w  . j a  v a 2s.c  o m
}

From source file:launcher.workflow.update.UpdateWorkflow.java

public static void begin(final Settings launcherCfg, final String license) {
    WorkflowStep prepare = new WorkflowStep("Preparing to launch the game", new WorkflowAction() {
        @Override/*from w ww .  ja va 2  s .com*/
        public boolean act() {
            return true;
        }
    });
    WorkflowStep checkLicense = new WorkflowStep("Checking to see if a license has been entered.",
            new WorkflowAction() {
                @Override
                public boolean act() throws Exception {
                    if (license == null || license.isEmpty()) {
                        LaunchLogger.error(LaunchLogger.Tab + "No valid license found.");
                        return false;
                    }

                    WorkflowWindowManager.setProgressVisible(true);
                    URL licenseCheckUrl = new URL(launcherCfg.licenseCall(license));
                    String response = IOUtils.toString(licenseCheckUrl.openStream());
                    WorkflowWindowManager.setProgressVisible(false);
                    if (response.contains("true")) {
                        LaunchLogger.info(LaunchLogger.Tab + "License is valid.");
                        return true;
                    } else {
                        if (License.isCached()) {
                            LaunchLogger
                                    .info("Invalid license was found. Deleting the locally cached license.");
                            License.deleteCache();
                            return false;
                        }
                    }
                    return false;
                }
            });

    WorkflowStep checkVersion = new WorkflowStep("Checking for updates.", new WorkflowAction() {
        @Override
        public boolean act() throws Exception {
            File versionPath = new File("assets/data/version.dat");
            String myVersion = "0.0.0";
            if (versionPath.exists()) {
                myVersion = FileUtils.readFileToString(versionPath);
                LaunchLogger.info("Detected version: " + myVersion);
            }
            WorkflowWindowManager.setProgressVisible(true);
            URL versionCheckUrl = new URL(launcherCfg.versionCall(myVersion));

            String result = IOUtils.toString(versionCheckUrl.openStream());
            WorkflowWindowManager.setProgressVisible(false);
            if (result.contains("true")) {
                LaunchLogger.info(LaunchLogger.Tab + "Local copy of the game is out of date.");
                return true;
            }
            LaunchLogger.info(LaunchLogger.Tab + "Local copy of the game is up to date. No update required.");
            return false;
        }
    });

    WorkflowStep downloadUpdate = new WorkflowStep("Preparing the update location", new WorkflowAction() {
        @Override
        public boolean act() throws Exception {
            if (UpdateWorkflowData.UpdateArchive.exists()) {
                FileUtils.forceDelete(UpdateWorkflowData.UpdateArchive);
            }

            int responseTimeoutMs = launcherCfg.responseTimeoutMilliseconds;
            int downloadTimeoutMs = launcherCfg.downloadTimeoutMilliseconds;
            LaunchLogger.info("Attempting to download an update using license: [" + license + "]");

            WorkflowWindowManager.setProgressVisible(true);
            String downloadUrl = launcherCfg.downloadCall(license, "update");
            LaunchLogger.info("Downloading latest stable edition");
            FileUtils.copyURLToFile(new URL(downloadUrl), UpdateWorkflowData.UpdateArchive, responseTimeoutMs,
                    downloadTimeoutMs);
            WorkflowWindowManager.setProgressVisible(false);

            LaunchLogger.info(LaunchLogger.Tab + "Update downloaded successfully.");
            return true;
        }
    });

    WorkflowStep applyUpdate = new WorkflowStep("Unpacking update archive", new WorkflowAction() {
        @Override
        public boolean act() throws IOException {
            WorkflowWindowManager.setProgressVisible(true);
            Archive.unzip(UpdateWorkflowData.UpdateArchive, UpdateWorkflowData.UpdateWorkingDirectory);
            LaunchLogger.info("Replacing old content");
            File game = new File(UpdateWorkflowData.UpdateWorkingDirectory + "/game.jar");
            File gameTarget = new File("./");
            LaunchLogger.info("Attempting to copy: " + game + " to " + gameTarget);
            FileUtils.copyFileToDirectory(game, gameTarget);

            File assets = new File(UpdateWorkflowData.UpdateWorkingDirectory + "/assets");
            File assetsTarget = new File("./assets");
            LaunchLogger.info("Attempting to copy: " + assets + " to " + assetsTarget);
            FileUtils.copyDirectory(assets, assetsTarget);
            WorkflowWindowManager.setProgressVisible(false);

            LaunchLogger.info(LaunchLogger.Tab + "Update applied successfully.");
            return true;
        }
    });

    WorkflowStep clean = new WorkflowStep("Cleaning up temporary files", new WorkflowAction() {
        @Override
        public boolean act() throws IOException {
            if (UpdateWorkflowData.UpdateArchive.exists()) {
                FileUtils.forceDelete(UpdateWorkflowData.UpdateArchive);
            }
            if (UpdateWorkflowData.UpdateWorkingDirectory.exists()) {
                FileUtils.deleteDirectory(UpdateWorkflowData.UpdateWorkingDirectory);
            }
            return true;
        }
    });

    prepare.setOnSuccess(checkLicense);
    checkLicense.setOnSuccess(checkVersion);
    checkVersion.setOnSuccess(downloadUpdate);
    downloadUpdate.setOnSuccess(applyUpdate);
    applyUpdate.setOnSuccess(clean);

    prepare.setOnFailure(clean);
    checkLicense.setOnFailure(clean);
    checkVersion.setOnFailure(clean);
    downloadUpdate.setOnFailure(clean);
    applyUpdate.setOnFailure(clean);

    prepare.execute();
}

From source file:com.github.jdk7.Chapter1.java

public static void test1() {
    InputStream inputStream = Chapter1.class.getResourceAsStream("/dkj/a.txt");
    try {//  w ww. ja va 2  s.  c o  m
        String allLines = IOUtils.toString(inputStream);
    } catch (Throwable e) {

        System.err.println(" error ");
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    System.out.println("now");

    System.out.println("close");

}

From source file:cc.pinel.mangue.util.MangaSearch.java

/**
 * Searches mangas remotely using the query.
 * //from  w  ww  .j  a  v a2  s  . c  o  m
 * @param query the query to be searched
 * @return the list of mangas filtered
 * @throws MalformedURLException
 * @throws IOException
 */
public static Collection search(String query) throws MalformedURLException, IOException {
    Collection mangas = new ArrayList();

    InputStream is = new URL("http://www.mangapanda.com/actions/search/?q=" + query + "&limit=20").openStream();

    String lines[] = StringUtils.split(IOUtils.toString(is), '\n');

    for (int i = 0, length = lines.length; i < length && i < 20; i++) {
        String tokens[] = StringUtils.splitPreserveAllTokens(lines[i], '|');

        if (tokens.length >= MIN_TOKEN_LENGHT)
            mangas.add(new Manga(tokens[5], tokens[2], convertOldPath(tokens[4])));
    }

    return mangas;
}

From source file:hudson.init.InitScriptsExecutor.java

@Initializer(after = JOB_LOADED)
public static void init(Hudson hudson) throws IOException {
    URL bundledInitScript = hudson.servletContext.getResource("/WEB-INF/init.groovy");
    if (bundledInitScript != null) {
        logger.info("Executing bundled init script: " + bundledInitScript);
        InputStream in = bundledInitScript.openStream();
        try {/* w w w.j  av  a  2 s  .  c om*/
            String script = IOUtils.toString(in);
            logger.info(new Script(script).execute());
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    File initScript = new File(hudson.getRootDir(), "init.groovy");
    if (initScript.exists()) {
        execute(initScript);
    }

    File initScriptD = new File(hudson.getRootDir(), "init.groovy.d");
    if (initScriptD.isDirectory()) {
        File[] scripts = initScriptD.listFiles(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.getName().endsWith(".groovy");
            }
        });
        if (scripts != null) {
            // sort to run them in a deterministic order
            Arrays.sort(scripts);
            for (File f : scripts) {
                execute(f);
            }
        }
    }
}

From source file:com.yattatech.gcm.gui.GCMSender.java

public static void send(String channel, String message, String classKey) throws Exception {

    loadProperties();/*from   w w  w .j  av a 2s . c o m*/
    final HttpClient httpClient = new DefaultHttpClient();
    final HttpPost httpPost = new HttpPost("https://android.googleapis.com/gcm/send");
    final Class<?> formatClass = Class.forName(PROPERTIES.getProperty(classKey));
    final RequestFormat format = (RequestFormat) formatClass.newInstance();
    //HttpHost proxy    = new HttpHost(PROPERTIES.getProperty("proxy.host"), Integer.parseInt(PROPERTIES.getProperty("proxy.port")));                  
    //httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);      
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Authorization", PROPERTIES.getProperty("auth.key"));
    httpPost.setEntity(format.getRequest(channel, message));
    HttpResponse response = httpClient.execute(httpPost);
    final String content = IOUtils.toString(response.getEntity().getContent());
    System.out.println("Response status " + response.getStatusLine().getStatusCode());
    if (logCallback != null) {
        logCallback.message(content);
    }
    System.out.println("Response " + content);
}