Example usage for com.google.common.io CharStreams toString

List of usage examples for com.google.common.io CharStreams toString

Introduction

In this page you can find the example usage for com.google.common.io CharStreams toString.

Prototype

public static String toString(Readable r) throws IOException 

Source Link

Document

Reads all characters from a Readable object into a String .

Usage

From source file:org.openehr.designer.repository.AbstractFileBasedArchetypeRepository.java

private String readArchetype(Path adlFile) {
    try {//from w  w w . jav  a 2 s  .  c om
        return CharStreams.toString(new BomSupportingReader(Files.newInputStream(adlFile), Charsets.UTF_8));
    } catch (IOException e) {
        throw new RepositoryException("Could not read archetype from file " + adlFile, e);
    }
}

From source file:hu.balazsbakai.sq.util.RestUtil.java

private static String convertStreamToString(InputStream is) {
    LogUtil.d("RestClient", "convertStreamToString");

    try {/* w ww.  j  a  va2s.co m*/
        return CharStreams.toString(new InputStreamReader(is, "UTF-8"));
    } catch (Exception e) {
        LogUtil.e("convertStreamToString", e);
    }
    return "";

}

From source file:org.lightjason.agentspeak.action.builtin.rest.IBaseRest.java

/**
 * creates a HTTP connection and reads the data
 *
 * @param p_url url//from   w  w  w .  ja  v  a 2s .co  m
 * @return url data
 *
 * @throws IOException is thrown on connection errors
 */
@Nonnull
private static String httpdata(@Nonnull final String p_url) throws IOException {
    final HttpURLConnection l_connection = (HttpURLConnection) new URL(p_url).openConnection();

    // follow HTTP redirects
    l_connection.setInstanceFollowRedirects(true);

    // set a HTTP-User-Agent if not exists
    l_connection.setRequestProperty("User-Agent",
            (System.getProperty("http.agent") == null) || (System.getProperty("http.agent").isEmpty())
                    ? CCommon.PACKAGEROOT + CCommon.configuration().getString("version")
                    : System.getProperty("http.agent"));

    // read stream data
    final InputStream l_stream = l_connection.getInputStream();
    final String l_return = CharStreams.toString(new InputStreamReader(l_stream,
            (l_connection.getContentEncoding() == null) || (l_connection.getContentEncoding().isEmpty())
                    ? Charsets.UTF_8
                    : Charset.forName(l_connection.getContentEncoding())));
    Closeables.closeQuietly(l_stream);

    return l_return;
}

From source file:org.robotframework.red.junit.ProjectProvider.java

public String getFileContent(final IFile file) throws IOException, CoreException {
    try (final InputStream stream = file.getContents()) {
        return CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
    }//from   ww w  .j  av  a2  s.  c om
}

From source file:org.apache.aurora.scheduler.storage.db.MigrationManagerImpl.java

private void saveDowngradeScript(MigrationMapper mapper) {
    for (Change c : migrationLoader.getMigrations()) {
        try {//from www . j a  v a 2s. co m
            String downgradeScript = CharStreams.toString(migrationLoader.getScriptReader(c, true));
            LOG.info("Saving downgrade script for change id " + c.getId() + ": " + downgradeScript);

            mapper.saveDowngradeScript(c.getId(), downgradeScript.getBytes(Charsets.UTF_8));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.fenixedu.academic.ui.struts.action.resourceAllocationManager.ShiftDistributionFirstYearDA.java

public ActionForward uploadAndSimulateFileDistribution(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    ShiftDistributionFileBean fileBean = getRenderedObject();
    String fileContents = CharStreams
            .toString(new InputStreamReader(fileBean.getInputStream(), Charset.defaultCharset()));
    final String[] data = fileContents.split("\n");

    List<ShiftDistributionDTO> shiftDistributionFromFile = new ArrayList<ShiftDistributionDTO>(data.length);

    for (String dataLine : data) {
        ShiftDistributionDTO shiftDistributionDTO = new ShiftDistributionDTO();
        boolean shouldAdd = shiftDistributionDTO.fillWithFileLineData(dataLine);
        if (shouldAdd) {
            shiftDistributionFromFile.add(shiftDistributionDTO);
        }//from  ww w . ja va 2  s .  co  m
    }

    List<String> errorLog = new ArrayList<String>();
    List<String> warningLog = new ArrayList<String>();
    final Map<DegreeCurricularPlan, List<SchoolClassDistributionInformation>> processedInformation = processInformationFrom(
            shiftDistributionFromFile, errorLog);
    final Map<DegreeCurricularPlan, List<Integer>> abstractStudentNumbers = generateAbstractStudentNumbers(
            fileBean.getPhaseNumber(), errorLog);
    final Map<Shift, List<GenericPair<DegreeCurricularPlan, Integer>>> distribution = distributeStudents(
            abstractStudentNumbers, processedInformation, warningLog);

    if (!errorLog.isEmpty()) {
        request.setAttribute("errorLog", errorLog);
        request.setAttribute("allowToWriteDistribution", "false");
        request.setAttribute("allowToGetStatistics", "false");
    } else {
        request.setAttribute("allowToWriteDistribution", "true");
        request.setAttribute("allowToGetStatistics", "true");
        fileBean.setDistribution(distribution);
        fileBean.setAbstractStudentNumbers(abstractStudentNumbers);
        request.setAttribute("fileBeanDistribution", fileBean);
    }

    Collections.sort(warningLog);
    request.setAttribute("warningLog", warningLog);
    return mapping.findForward("shiftDistribution");
}

From source file:com.google.devtools.j2objc.FileProcessor.java

private String getJarEntryOrNull(String jarFile, String path) {
    File f = new File(jarFile);
    if (!f.exists() || !f.isFile()) {
        return null;
    }//from  ww  w  .j  a  v a  2s  .  c om
    try {
        ZipFile zfile = new ZipFile(f);
        try {
            ZipEntry entry = zfile.getEntry(path);
            if (entry != null) {
                Reader in = new InputStreamReader(zfile.getInputStream(entry));
                return CharStreams.toString(in);
            }
        } finally {
            zfile.close(); // Also closes input stream.
        }
    } catch (IOException e) {
        ErrorUtil.warning(e.getMessage());
    }
    return null;
}

From source file:svnserver.repository.git.push.GitPushEmbedded.java

private void runHook(@NotNull Repository repository, @Nullable String hook, @NotNull User userInfo,
        @NotNull HookRunner runner) throws IOException, SVNException {
    if (hook == null || hook.isEmpty()) {
        return;//from w ww .  j a v  a 2 s .c  o m
    }
    final File script = ConfigHelper.joinPath(ConfigHelper.joinPath(repository.getDirectory(), "hooks"), hook);
    if (script.isFile()) {
        try {
            final ProcessBuilder processBuilder = new ProcessBuilder(script.getAbsolutePath())
                    .directory(repository.getDirectory()).redirectErrorStream(true);
            processBuilder.environment().put("LANG", "en_US.utf8");
            userInfo.updateEnvironment(processBuilder.environment());
            context.sure(UserDB.class).updateEnvironment(processBuilder.environment(), userInfo);
            final Process process = runner.exec(processBuilder);
            final String hookMessage = CharStreams
                    .toString(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new SVNException(SVNErrorMessage.create(SVNErrorCode.REPOS_HOOK_FAILURE,
                        "Commit blocked by hook with output:\n" + hookMessage));
            }
        } catch (InterruptedException e) {
            log.error("Hook interrupted: " + script.getAbsolutePath(), e);
            throw new SVNException(SVNErrorMessage.create(SVNErrorCode.IO_WRITE_ERROR, e));
        }
    }
}

From source file:io.macgyver.core.cli.ClientPackager.java

private synchronized File buildCli() throws IOException, net.lingala.zip4j.exception.ZipException {

    File tempDir = Files.createTempDir();

    File f = new File(tempDir, "collected-cli-classes.jar");

    ZipFile z = new ZipFile(f);

    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    for (String packageName : CLI.findPackageNamesToSearch()) {

        logger.info("searching pacakge for CLI commands: {}", packageName);
        ClassPath.from(cl).getTopLevelClasses(packageName).forEach(it -> {

            if (isToBePackaged(it)) {
                logger.info("adding command class: {}", it);
                try (InputStream input = it.url().openStream()) {
                    byte[] b = ByteStreams.toByteArray(input);

                    ZipParameters zp = new ZipParameters();
                    zp.setSourceExternalStream(true);
                    zp.setFileNameInZip(it.getName().replace(".", "/") + ".class");
                    z.addStream(new ByteArrayInputStream(b), zp);
                } catch (IOException | net.lingala.zip4j.exception.ZipException e) {
                    throw new RuntimeException(e);
                }/* w ww  .  j  a v  a  2 s . c  om*/
            }

        });
    }

    File generatedJar = new File(tempDir, "macgyver-capsule-with-extensions.jar");

    try (InputStream in = cl.getResourceAsStream("cli/macgyver-cli-capsule.jar")) {
        Preconditions.checkNotNull(in,
                "resource cli/macgyver-cli-capsule.jar could not be loaded.  Did you run gradle install in macgyver-cli?");
        try (FileOutputStream out = new FileOutputStream(generatedJar)) {

            ByteStreams.copy(in, out);
        }
    }

    ZipFile mj = new ZipFile(generatedJar);
    ZipParameters zp = new ZipParameters();
    zp.setFileNameInZip("collected-cli-classes.jar");

    try {
        mj.removeFile("collected-cli-classes.jar");
    } catch (Exception e) {
    }
    mj.addFile(f, zp);

    targetDir.mkdirs();
    File executable = new File(targetDir, "macgyver");
    executable.delete();

    PrintWriter bw = new PrintWriter(new FileWriter(executable));

    org.springframework.core.io.Resource resource = Kernel.getApplicationContext()
            .getResource("classpath:cli/cli-jar-header.sh");
    try (InputStreamReader isr = new InputStreamReader(resource.getInputStream())) {
        String script = CharStreams.toString(isr);
        bw.println(script);
    }
    // bw.println("#!/bin/bash");
    // bw.println("exec java -Dcli.exe=\"$0\" -Dcli.launch=true -jar $0
    // \"$@\"");

    bw.close();

    try (FileInputStream fis = new FileInputStream(generatedJar)) {
        try (FileOutputStream fos = new FileOutputStream(executable, true)) {
            ByteStreams.copy(fis, fos);
        }
    }
    executable.setExecutable(true);

    return executable;
}

From source file:com.spotify.helios.agent.HostInfoReporter.java

private String exec(final String command) {
    try {//from   w w w .  java 2 s  .c o m
        final Process process = Runtime.getRuntime().exec(command);
        return CharStreams.toString(new InputStreamReader(process.getInputStream(), UTF_8));
    } catch (IOException e) {
        throw propagate(e);
    }
}