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:me.lazerka.gae.jersey.oauth2.OauthModule.java

/**
 * Reads whole file as a string.//from   w  w w. jav a  2 s .  com
 */
static String readKey(File file) {
    logger.trace("Reading {}", file.getAbsolutePath());

    try {
        String result = Files.toString(file, UTF_8).trim();
        if (result.isEmpty()) {
            throw new RuntimeException("File is empty: " + file.getAbsolutePath());
        }

        return result;
    } catch (FileNotFoundException e) {
        throw new RuntimeException("File " + file.getAbsolutePath() + " not found.");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.hadoop.ha.HAZKUtil.java

/**
 * Because ZK ACLs and authentication information may be secret,
 * allow the configuration values to be indirected through a file
 * by specifying the configuration as "@/path/to/file". If this
 * syntax is used, this function will return the contents of the file
 * as a String.//from  w w  w  . java2 s .c  om
 * 
 * @param valInConf the value from the Configuration 
 * @return either the same value, or the contents of the referenced
 * file if the configured value starts with "@"
 * @throws IOException if the file cannot be read
 */
public static String resolveConfIndirection(String valInConf) throws IOException {
    if (valInConf == null)
        return null;
    if (!valInConf.startsWith("@")) {
        return valInConf;
    }
    String path = valInConf.substring(1).trim();
    return Files.toString(new File(path), Charsets.UTF_8).trim();
}

From source file:org.jclouds.vagrant.strategy.VagrantDefaultImageCredentials.java

private LoginCredentials parseSshBoxCredentials(Image image) {
    BoxConfig parser = boxConfigFactory.newInstance(image);
    String username = parser.getStringKey(VagrantConstants.KEY_SSH_USERNAME)
            .or(VagrantConstants.DEFAULT_USERNAME);
    Builder credBuilder = LoginCredentials.builder().user(username);
    Optional<String> password = parser.getStringKey(VagrantConstants.KEY_SSH_PASSWORD);
    if (password.isPresent()) {
        credBuilder.password(password.get());
    }/*from  ww  w . ja va 2s.  c  om*/
    Optional<String> privateKeyPath = parser.getStringKey(VagrantConstants.KEY_SSH_PRIVATE_KEY_PATH);
    if (privateKeyPath.isPresent()) {
        File privateKey = new File(parser.getFolder(), privateKeyPath.get());
        if (privateKey.exists()) {
            try {
                credBuilder.privateKey(Files.toString(privateKey, Charsets.UTF_8));
            } catch (IOException e) {
                throw new IllegalStateException("Failure reading private key file "
                        + privateKey.getAbsolutePath() + " for box " + parser.getFolder().getAbsolutePath());
            }
        } else {
            logger.warn(
                    "Private key " + privateKeyPath.get() + " for box " + parser.getFolder().getAbsolutePath()
                            + " not found at " + privateKey.getAbsolutePath() + ". Ignoring.");
        }
    }
    return credBuilder.build();
}

From source file:hihex.cs.PidEntry.java

public String getThreadName(final int tid) {
    final String cachedThreadName = mThreadNames.get(tid);
    if (cachedThreadName != null) {
        return cachedThreadName;
    }//  ww  w  .  j  av a 2s.  com

    final File threadNameFile = new File("/proc/" + pid + "/task/" + tid + "/comm");
    String threadName;
    try {
        threadName = Files.toString(threadNameFile, Charsets.UTF_8);
    } catch (final IOException e) {
        threadName = "TID:" + tid;
    }
    mThreadNames.append(tid, threadName);

    return threadName;
}

From source file:net.sf.maven.plugin.autotools.FileUtils.java

/**
 * Replace all occurences, in <code>files</code>, of <code>regex</code> with <code>replace</code>
 * @param regex    the original text to replace
 * @param replace    the placeholder/*from  ww w  . j av a2  s.c om*/
 * @param files   the files
 */
public static void replace(Log log, @Nonnull String regex, @Nullable String replace, File... files)
        throws IOException {
    if (files == null)
        return;
    Preconditions.checkArgument(!Strings.isNullOrEmpty(regex), "regex is empty");
    replace = Strings.nullToEmpty(replace);
    for (File file : files) {
        log.debug(String.format("Replacing [%s] with [%s] in [%s]", regex, replace, file.getAbsolutePath()));
        String text = Files.toString(file, Charset.defaultCharset());
        Files.write(text.replaceAll(regex, replace), file, Charset.defaultCharset());
    }
}

From source file:org.eclipse.andmore.ddms.systrace.SystraceOutputParser.java

private static String getHtmlTemplate(File assetsFolder, String htmlFileName) {
    try {//from   ww  w . j a  va  2s . c  o  m
        return Files.toString(new File(assetsFolder, htmlFileName), Charsets.UTF_8);
    } catch (IOException e) {
        return "";
    }
}

From source file:com.proofpoint.zookeeper.ConnectionState.java

private ZookeeperSessionID readSessionId() {
    if (config.getSessionStorePath() != null) {
        File sessionIdFile = new File(config.getSessionStorePath());
        if (sessionIdFile.exists()) {
            try {
                String sessionSpec = Files.toString(sessionIdFile, Charsets.UTF_8);
                ObjectMapper mapper = new ObjectMapper();
                return mapper.readValue(sessionSpec, ZookeeperSessionID.class);
            } catch (IOException e) {
                log.warn(e, "Could not read session file: %s", config.getSessionStorePath());
            }//from  w  w w  . j  a va 2 s . c  om
        }
    }
    return null;
}

From source file:org.apache.jackrabbit.oak.run.osgi.ConfigTracker.java

@SuppressWarnings("unchecked")
private Map<String, Map<String, Object>> parseJSONConfig(String jsonFilePath) throws IOException {
    Map<String, Map<String, Object>> configs = Maps.newHashMap();
    if (jsonFilePath == null) {
        return configs;
    }// ww w.  ja  v  a  2 s .  c  o m

    List<String> files = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(jsonFilePath);
    for (String filePath : files) {
        File jsonFile = new File(filePath);
        if (!jsonFile.exists()) {
            log.warn("No file found at path {}. Ignoring the file entry", jsonFile.getAbsolutePath());
            continue;
        }

        String content = Files.toString(jsonFile, Charsets.UTF_8);
        JSONObject json = (JSONObject) JSONValue.parse(content);
        configs.putAll(json);
    }

    return configs;
}

From source file:org.plista.kornakapi.web.servlets.BigBangServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    try {/*w  w w. j a  v a2s  .  com*/
        log.info("Try started");
        String configFileLocation = System.getProperty(CONFIG_PROPERTY);
        Preconditions.checkState(configFileLocation != null, "configuration file not set!");

        File configFile = new File(configFileLocation);
        Preconditions.checkState(configFile.exists() && configFile.canRead(),
                "configuration file not found or not readable");

        conf = Configuration.fromXML(Files.toString(configFile, Charsets.UTF_8));

        Preconditions.checkState(conf.getNumProcessorsForTraining() > 0,
                "need at least one processor for training!");
        domainIndependetStorage = null;
        labels = null;

        dataSource = new BasicDataSource();
        storages = new HashMap<String, CandidateCacheStorageDecorator>();
        if (conf.getMaxPersistence()) {
            domainIndependetStorage = new CandidateCacheStorageDecorator(
                    new MySqlMaxPersistentStorage(conf.getStorageConfiguration(), "", dataSource));
            labels = domainIndependetStorage.getAllLabels();
            for (String label : labels) {
                storages.put(label, new CandidateCacheStorageDecorator(
                        new MySqlMaxPersistentStorage(conf.getStorageConfiguration(), label, dataSource)));
            }
        } else {
            domainIndependetStorage = new CandidateCacheStorageDecorator(
                    new MySqlStorage(conf.getStorageConfiguration(), "", dataSource));
            labels = domainIndependetStorage.getAllLabels();
            for (String label : labels) {
                storages.put(label, new CandidateCacheStorageDecorator(
                        new MySqlStorage(conf.getStorageConfiguration(), label, dataSource)));
            }
        }
        persitentDatas = new HashMap<String, DataModel>();
        for (String label : labels) {
            persitentDatas.put(label, storages.get(label).recommenderData());
        }

        scheduler = new TaskScheduler();

        String purgePreferencesCronExpression = conf.getStorageConfiguration()
                .getPurgePreferencesCronExpression();

        scheduler.setPurgeOldPreferences(purgePreferencesCronExpression);

        recommenders = Maps.newHashMap();
        trainers = Maps.newHashMap();

        preferenceChangeListener = new DelegatingPreferenceChangeListenerForLabel();

        setupRecommenders();

    } catch (Exception e) {
        log.info("Something bad happend: {}", e.getMessage());
        throw new RuntimeException(e);
    }
}

From source file:com.facebook.buck.doctor.DoctorReportHelper.java

public DoctorEndpointRequest generateEndpointRequest(BuildLogEntry entry, DefectSubmitResult rageResult)
        throws IOException {
    Optional<String> machineLog;

    if (entry.getMachineReadableLogFile().isPresent()) {
        machineLog = Optional.of(Files.toString(
                filesystem.resolve(entry.getMachineReadableLogFile().get()).toFile(), Charsets.UTF_8));
    } else {//  w  w  w  .j a  v  a 2s. c  om
        LOG.warn(String.format(WARNING_FILE_TEMPLATE, entry.toString(), "machine readable log"));
        machineLog = Optional.empty();
    }

    return DoctorEndpointRequest.of(entry.getBuildId(), entry.getRelativePath().toString(), machineLog,
            rageResult.getReportSubmitMessage(), rageResult.getReportSubmitLocation());
}