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:org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreTextWriter.java

@Override
public ExtractedText getText(String propertyPath, Blob blob) throws IOException {
    String blobId = blob.getContentIdentity();
    if (blobId == null) {
        log.debug("No id found for blob at path {}", propertyPath);
        return null;
    }/*from ww w.ja  v a 2 s. c om*/

    blobId = stripLength(blobId);
    ExtractedText result = null;
    if (getEmptyBlobs().contains(blobId)) {
        result = ExtractedText.EMPTY;
    } else if (getErrorBlobs().contains(blobId)) {
        result = ExtractedText.ERROR;
    } else {
        File textFile = getFile(blobId);
        if (textFile.exists()) {
            String text = Files.toString(textFile, Charsets.UTF_8);
            result = new ExtractedText(ExtractionResult.SUCCESS, text);
        }
    }

    if (log.isDebugEnabled()) {
        String extractionResult = result != null ? result.getExtractionResult().toString() : null;
        log.debug("Extraction result for [{}] at path [{}] is [{}]", blobId, propertyPath, extractionResult);
    }
    return result;
}

From source file:net.oneandone.troilus.CassandraDB.java

/**
 * executes a CQL file. CQL processing errors will be ignored 
 * /*from   w w w .  j av  a  2 s .co m*/
 * @param cqlFile    the CQL file name 
 * @throws IOException  if the file could not be found
 */
public void tryExecuteCqlFile(String cqlFile) {
    try {
        File file = new File(cqlFile);
        if (file.exists()) {
            tryExecuteCqls(Splitter.on(";").split(Files.toString(new File(cqlFile), Charsets.UTF_8)));
        } else {
            tryExecuteCqls(
                    Splitter.on(";").split(Resources.toString(Resources.getResource(cqlFile), Charsets.UTF_8)));
        }
    } catch (IOException ioe) {
        throw new RuntimeException(cqlFile + " not found");
    }
}

From source file:com.indeed.lsmtree.recordlog.GenericRecordLogAppender.java

private static Map<String, String> readMetadata(File metadataPath, ObjectMapper mapper) throws IOException {
    if (metadataPath.exists()) {
        Map<String, String> ret = Maps.newLinkedHashMap();
        JsonNode node = mapper.readTree(Files.toString(metadataPath, Charsets.UTF_8));
        Iterator<Map.Entry<String, JsonNode>> iterator = node.getFields();
        while (iterator.hasNext()) {
            Map.Entry<String, JsonNode> entry = iterator.next();
            ret.put(entry.getKey(), entry.getValue().getTextValue());
        }//  www. ja  v  a2 s .co m
        return ret;
    }
    return null;
}

From source file:com.splout.db.hadoop.DeployerCMD.java

@SuppressWarnings("deprecation")
@Override//from  w  w w  .j  a v a 2  s.c  o m
public int run(String[] args) throws Exception {
    JCommander jComm = new JCommander(this);
    jComm.setProgramName("Tablespaces Deployer");
    try {
        jComm.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jComm.usage();
        return -1;
    } catch (Throwable t) {
        t.printStackTrace();
        jComm.usage();
        return -1;
    }

    StoreDeployerTool deployer = new StoreDeployerTool(qnode, getConf());

    ArrayList<TablespaceDepSpec> deployments = new ArrayList<TablespaceDepSpec>();
    if (configFile != null) {
        deployments = JSONSerDe.deSer(Files.toString(new File(configFile), Charset.forName("UTF-8")),
                new TypeReference<ArrayList<TablespaceDepSpec>>() {
                });
    } else {
        Path rootPath = new Path(root);
        if (tablespaceName == null && tablespaces.size() == 0) {
            System.err.println(
                    "Tablespace name for root folder or tablespaces contained in them is lacking. Either use tablespacename or tablespaces option.");
            jComm.usage();
            return -1;
        }
        if (tablespaceName != null && tablespaces.size() > 0) {
            System.err.println(
                    "Can't use tablespacename and tablespaces at the same time. Root is to be either a generated tablespace or a folder with multiple generated tablespaces.");
            jComm.usage();
            return -1;
        }
        if (tablespaceName != null) {
            deployments.add(new TablespaceDepSpec(tablespaceName, rootPath.toString(), replicationFactor,
                    initStatements));
        }
        for (String tb : tablespaces) {
            Path tablespacePath = new Path(rootPath, tb);
            deployments.add(
                    new TablespaceDepSpec(tb, tablespacePath.toString(), replicationFactor, initStatements));
        }
    }

    // Checking for file existence
    for (TablespaceDepSpec spec : deployments) {
        Path tablespacePath = new Path(spec.getSourcePath());
        FileSystem fs = tablespacePath.getFileSystem(getConf());
        if (!fs.exists(tablespacePath)) {
            System.out.println("ERROR: Path [" + tablespacePath.makeQualified(fs) + "] not found.");
            return 1;
        }
    }

    deployer.deploy(deployments);
    return 0;
}

From source file:pl.iz.cubicrl.controller.dao.DaoXStream.java

private String readStringFromFile(String path) throws IOException {
    return Files.toString(new File(path), Charset.forName("UTF-8"));
}

From source file:com.axelor.tool.template.TemplateMaker.java

public void setTemplate(File file) throws FileNotFoundException {
    if (!file.isFile()) {
        throw new FileNotFoundException(I18n.get(IExceptionMessage.TEMPLATE_MAKER_1) + ": " + file.getName());
    }/*from  w  w  w .j  a v a 2 s  .  c o m*/

    String text;
    try {
        text = Files.toString(file, Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }

    this.setTemplate(text);
}

From source file:org.ctoolkit.maven.plugins.optimizer.CssOptimizer.java

/**
 * Process css optimization//from  w  ww.  ja  v a  2  s .  c o  m
 *
 * @param pathToXml     path to css configuration xml
 * @param cssOutputPath css output path
 */
public static void process(String pathToXml, String cssOutputPath, String baseDir) {
    if (pathToXml == null || pathToXml.trim().isEmpty()) {
        log.info("Css path to xml is not set. Skipping css optimization.");
        return;
    }

    if (!new File(pathToXml).exists()) {
        throw new IllegalArgumentException("Css path to xml does not exists: " + pathToXml);
    }

    log.info("Starting to optimize css...");

    try {
        for (CSSConfig cssConfig : getCssConfigList(pathToXml, baseDir)) {
            String cssOutputFileName = cssConfig.getCssOutputName();
            List<String> cssPaths = new ArrayList<>();

            // create external css files
            for (String externalCssContent : cssConfig.getExternalCssList()) {
                String externalCssFileName = FileHelper
                        .writeToFile(File.createTempFile("externalCssFile", ".css"), externalCssContent);
                cssPaths.add(externalCssFileName);
            }

            // encode images in css
            for (String cssCustomInputFileName : cssConfig.getCssList()) {
                File cssCustomFile = new File(cssCustomInputFileName);

                if (cssCustomFile.exists()) {
                    String cssCustomString = encodeImages(cssCustomFile);
                    String encodedCssFileName = FileHelper
                            .writeToFile(File.createTempFile("encodedCssFile", ".css"), cssCustomString);

                    cssPaths.add(encodedCssFileName);
                }
            }

            // minify css
            String cssOutputString;
            if (cssConfig.getMinfy()) {
                cssPaths.add("-o"); // set output file parameter as temp file (we will load its content into cssOutputString
                File cssMinifiedFile = File.createTempFile("minifiedCssFile", "css");
                cssPaths.add(cssMinifiedFile.getAbsolutePath());
                ClosureCommandLineCompiler.main(cssPaths.toArray(new String[cssPaths.size()]));

                cssOutputString = Files.toString(cssMinifiedFile, Charsets.UTF_8);

                log.info("CSS minified output:\n===\n" + cssOutputString + "\n===\n");
            } else {
                StringBuilder output = new StringBuilder();
                for (String cssPath : cssPaths) {
                    output.append(Files.toString(new File(cssPath), Charsets.UTF_8));
                }

                cssOutputString = output.toString();
            }

            // create final css file
            String optimizedCss = FileHelper.createOutputFile(cssOutputPath, cssOutputFileName,
                    cssOutputString);

            log.info(">>> Css optimization finished successfully. Optimized css file can be found at: "
                    + optimizedCss);
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error occurred during processing css: ", e);
    }
}

From source file:com.facebook.presto.cli.Console.java

@Override
public void run() {
    ClientSession session = clientOptions.toClientSession();
    KerberosConfig kerberosConfig = clientOptions.toKerberosConfig();
    boolean hasQuery = !Strings.isNullOrEmpty(clientOptions.execute);
    boolean isFromFile = !Strings.isNullOrEmpty(clientOptions.file);

    if (!hasQuery || !isFromFile) {
        AnsiConsole.systemInstall();//from w ww  . j  a v a2s  .  co  m
    }

    initializeLogging(clientOptions.logLevelsFile);

    String query = clientOptions.execute;
    if (hasQuery) {
        query += ";";
    }

    if (isFromFile) {
        if (hasQuery) {
            throw new RuntimeException("both --execute and --file specified");
        }
        try {
            query = Files.toString(new File(clientOptions.file), UTF_8);
            hasQuery = true;
        } catch (IOException e) {
            throw new RuntimeException(
                    format("Error reading from file %s: %s", clientOptions.file, e.getMessage()));
        }
    }

    try (QueryRunner queryRunner = QueryRunner.create(session, Optional.ofNullable(clientOptions.socksProxy),
            Optional.ofNullable(clientOptions.keystorePath),
            Optional.ofNullable(clientOptions.keystorePassword),
            Optional.ofNullable(clientOptions.krb5Principal),
            Optional.ofNullable(clientOptions.krb5RemoteServiceName), clientOptions.authenticationEnabled,
            kerberosConfig)) {
        if (hasQuery) {
            executeCommand(queryRunner, query, clientOptions.outputFormat);
        } else {
            runConsole(queryRunner, session);
        }
    }
}

From source file:me.lucko.luckperms.api.sponge.simple.persisted.SubjectStorage.java

public Map.Entry<String, SimpleSubjectDataHolder> loadFromFile(File file) throws IOException {
    if (!file.exists()) {
        return null;
    }/*w  w  w.  j  a v  a 2s . c  o  m*/

    String s = Files.toString(file, Charset.defaultCharset());
    return new AbstractMap.SimpleEntry<>(file.getName().substring(file.getName().length() - 5).toLowerCase(),
            loadFromString(s));
}

From source file:com.google.template.soy.msgs.SoyMsgBundleHandler.java

/**
 * Reads a translated messages file and creates a SoyMsgBundle.
 *
 * @param inputFile The input file to read from.
 * @return The message bundle created from the messages file.
 * @throws IOException If there's an error while accessing the file.
 * @throws SoyMsgException If there's an error while processing the messages.
 *//*from w  ww. ja  va2 s  . c  o  m*/
public SoyMsgBundle createFromFile(File inputFile) throws IOException, SoyMsgException {

    // TODO: This is for backwards-compatibility. Figure out how to get rid of this.
    // We special-case English locales because they often don't have translated files and falling
    // back to the Soy source should be fine.
    if (!inputFile.exists() && FIRST_WORD_IS_EN_PATTERN.matcher(inputFile.getName()).matches()) {
        return SoyMsgBundle.EMPTY;
    }

    try {
        String inputFileContent = Files.toString(inputFile, UTF_8);
        return msgPlugin.parseTranslatedMsgsFile(inputFileContent);

    } catch (SoyMsgException sme) {
        sme.setFileOrResourceName(inputFile.toString());
        throw sme;
    }
}