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

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

Introduction

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

Prototype

public static String toString(File file, Charset charset) throws IOException 

Source Link

Usage

From source file:com.netflix.iep.config.ConfigFile.java

public static Map<String, String> load(Map<String, String> vars, File file) {
    try {/* ww  w  . j  a va2  s . com*/
        return load(vars, Files.toString(file, Charsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.numberfour.n4js.antlr.compressor.ParserCompressorFragment.java

@Override
public void generate(org.eclipse.xtext.Grammar grammar, org.eclipse.xpand2.XpandExecutionContext ctx) {
    for (String fileName : grammarFiles) {
        File file = new File(fileName);
        String javaSource = null;
        try {//from w  ww . jav  a 2  s. c  o  m
            javaSource = Files.toString(file, Charsets.UTF_8);
        } catch (Exception ex) {
            log.error("Error reading file " + fileName + ": " + ex.getMessage());
        }
        if (javaSource != null) {
            String compressed = process(javaSource, file);
            log.info("File " + readableFileName(file) + " compressed: " + javaSource.length() + " --> "
                    + compressed.length() + " (" + 100 * compressed.length() / javaSource.length() + "%)");

            if (backup) {
                try {
                    Files.copy(file, new File(file.getParentFile(), file.getName() + ".bak"));
                } catch (IOException e) {
                    log.error("Error creating backup of " + readableFileName(file) + ": " + e.getMessage());
                    return;
                }
            }

            try {
                Files.write(compressed, file, Charsets.UTF_8);
            } catch (IOException e) {
                log.error("Error writing compressed file " + readableFileName(file) + ": " + e.getMessage());
            }
        }
    }
}

From source file:com.parallax.server.blocklyprop.servlets.HelpServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String filePath = req.getParameter("f");

    if (filePath == null) {
        filePath = "index";
    }/*  w w w  .ja v a  2 s. co  m*/

    File file = new File(destinationDirectoryFile, filePath);
    if (!filePath.contains(".")) {
        file = new File(destinationDirectoryFile, filePath + ".xml");

        String fileName = Files.getNameWithoutExtension(file.getName());
        String extension = Files.getFileExtension(file.getName());

        File localeFile = new File(destinationDirectoryFile, fileName + "_" + getLocale(req) + "." + extension);
        if (localeFile.exists() && localeFile.isFile()) {
            file = localeFile;
        }

        if (isSubDirectory(destinationDirectoryFile, file)) {
            if (file.exists() && file.isFile()) {
                req.setAttribute("html", Files.toString(file, Charset.forName("UTF-8")));
                req.getRequestDispatcher("/WEB-INF/servlet/help/help.jsp").forward(req, resp);
            } else {
                req.setAttribute("help-not-found", true);
                req.getRequestDispatcher("/WEB-INF/servlet/help/help-error.jsp").forward(req, resp);
                ;
            }
        } else {

        }
    } else {
        String fileName = Files.getNameWithoutExtension(file.getName());
        String extension = Files.getFileExtension(file.getName());

        File localeFile = new File(destinationDirectoryFile, fileName + "_" + getLocale(req) + "." + extension);
        if (localeFile.exists() && localeFile.isFile()) {
            file = localeFile;
        }

        if (isSubDirectory(destinationDirectoryFile, file)) {
            if (file.exists() && file.isFile()) {
                resp.setContentType(java.nio.file.Files.probeContentType(file.toPath()));
                Files.copy(file, resp.getOutputStream());
            } else {
                req.setAttribute("help-not-found", true);
                req.getRequestDispatcher("/WEB-INF/servlet/help/help-error.jsp").forward(req, resp);
                ;
            }
        } else {
            req.setAttribute("help-invalid-path", true);
            req.getRequestDispatcher("/WEB-INF/servlet/help/help-error.jsp").forward(req, resp);
        }
    }
}

From source file:datamine.mojo.storage.AbstractCodeGenerationMojo.java

protected void validateArguments() throws MojoFailureException {
    if (packageName == null || schemaPath == null || schemaPath.length() == 0) {

        StringBuilder sb = new StringBuilder().append("An invalid package name or schema path occurs! \n")
                .append("Package Name is : ").append(packageName).append("\n").append("Schema Path is: ")
                .append(schemaPath);/*from  w  ww  .  ja  v  a 2  s . com*/

        throw new MojoFailureException(sb.toString());
    }
    //
    try {
        // validate the new schema
        Schema nextSchema = new JsonSchemaConvertor().apply(Files.toString(schemaPath, Charsets.UTF_8));
        new SchemaValidation().check(nextSchema);

        // check its compatibility with the old one
        Schema currentSchema = new MetadataPackageToSchema().apply(packageName);
        if (currentSchema != null) {
            new SchemaEvolutionValidation(currentSchema).check(nextSchema);
        }
    } catch (AbstractValidationException e) {
        throw new MojoFailureException(e.getMessage());
    } catch (IOException e) {
        throw new MojoFailureException("Cannot read the schema from " + schemaPath, e);
    }
}

From source file:de.monticore.mojo.ReportRenderer.java

@Override
protected void renderBody() {
    startSection(title);//from   w  ww .j a v  a2  s.c  om
    linkPatternedText(createLinkPatternedText("Back to parent", "./" + this.parent + ".html"));

    try {
        verbatimText(Files.toString(inputFile, Charset.defaultCharset()));
    } catch (IOException iOE) {
        log.warn("0xA4071 Unable to read input file " + inputFile.getAbsolutePath(), iOE);
    }
    linkPatternedText(createLinkPatternedText("Back to parent", "./" + this.parent + ".html"));
    endSection();
}

From source file:org.apache.flume.channel.file.encryption.JCEFileKeyProvider.java

@Override
public Key getKey(String alias) {
    String passwordFile = keyStorePasswordFile.getAbsolutePath();
    try {//from w w  w. jav a2 s. c o m
        char[] keyPassword = keyStorePassword;
        if (aliasPasswordFileMap.containsKey(alias)) {
            File keyPasswordFile = aliasPasswordFileMap.get(alias);
            keyPassword = Files.toString(keyPasswordFile, Charsets.UTF_8).trim().toCharArray();
            passwordFile = keyPasswordFile.getAbsolutePath();
        }
        Key key = ks.getKey(alias, keyPassword);
        if (key == null) {
            throw new IllegalStateException("KeyStore returned null for " + alias);
        }
        return key;
    } catch (Exception e) {
        String msg = e.getClass().getName() + ": " + e.getMessage() + ". " + "Key = " + alias
                + ", passwordFile = " + passwordFile;
        throw new RuntimeException(msg, e);
    }
}

From source file:Contextual.Stemmer.StemmerFactory.java

protected String[] getWordsFromFile() {
    String pwd = Paths.get(".").toAbsolutePath().normalize().toString();
    String dictionaryFile = pwd + "/../../" + DICT_FILENAME;
    String contents = new String();
    String[] split;/*from  w ww.jav  a  2 s.c o m*/
    File dictFile;

    try { //Try to read dictionary files to be exploded in string split
        dictFile = new File(dictionaryFile);
        if (!dictFile.canRead()) {
            System.out.println("Missing or incorrect permission for dictionary file");
            System.exit(ErrorDescriptorsEnum.DICTIONARY_FILE_ERROR.getErrCode());
        }
        try {
            contents = Files.toString(dictFile, Charset.defaultCharset());
        } catch (IOException e) {
            System.out.println(e.getStackTrace());
        }
    } catch (Exception e) {
        System.out.println(e.getStackTrace());
    }

    if (contents.isEmpty()) {
        System.out.println("Dictionary file is empty, exiting...\n");
        System.exit(ErrorDescriptorsEnum.DICTIONARY_CONTENTS_ERROR.getErrCode());
    }
    split = StringUtils.explode("\n", contents);
    return split;
}

From source file:com.mapr.storm.SpoutState.java

public static DirectoryScanner restoreState(Queue<PendingMessage> pendingReplays, File statusFile)
        throws IOException {
    Preconditions.checkState(statusFile.exists(), "Status file not found %s", statusFile);
    SpoutState s = SpoutState.fromString(Files.toString(statusFile, Charsets.UTF_8));
    DirectoryScanner scanner = new DirectoryScanner(new File(s.inputDirectory), Pattern.compile(s.filePattern));

    // we always reset all of the old replays.  Even in reliable = false cases,
    // there will be one of these entries for the live file.
    scanner.setOldFiles(s.oldFiles);/*w  w w.ja v  a  2s. c  o m*/
    for (File file : s.offsets.keySet()) {
        pendingReplays.add(new PendingMessage(file, s.offsets.get(file), null));
    }
    return scanner;
}

From source file:org.apache.aurora.scheduler.events.WebhookModule.java

@VisibleForTesting
static String readWebhookFile() {
    try {/*from ww w .j  a va 2  s  . c  o m*/
        return WEBHOOK_CONFIG_FILE.hasAppliedValue()
                ? Files.toString(WEBHOOK_CONFIG_FILE.get(), StandardCharsets.UTF_8)
                : Resources.toString(Webhook.class.getClassLoader().getResource(WEBHOOK_CONFIG_PATH),
                        StandardCharsets.UTF_8);
    } catch (IOException e) {
        LOG.error("Error loading webhook configuration file.");
        throw new RuntimeException(e);
    }
}

From source file:org.cretz.sbnstat.scrape.Cache.java

public String load(String url) throws IOException {
    String uuid = urls.getProperty(url);
    //if it's not there, screw it...return null
    if (uuid == null) {
        return null;
    }//from   w ww. j  a  va2 s. c  o m
    File file = new File(directory, uuid + ".html");
    if (!file.exists()) {
        return null;
    }
    //load it
    return Files.toString(file, Charset.forName("UTF8"));
}