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.ftc.opmodes.NetworkAnalyzer.java

@Override
public void init() {
    wifiChannelMap = HashBiMap.create();
    wifiChannelMap.put(2412, "2.4G Ch01");
    wifiChannelMap.put(2417, "2.4G Ch02");
    wifiChannelMap.put(2422, "2.4G Ch03");
    wifiChannelMap.put(2427, "2.4G Ch04");
    wifiChannelMap.put(2432, "2.4G Ch05");
    wifiChannelMap.put(2437, "2.4G Ch06");
    wifiChannelMap.put(2442, "2.4G Ch07");
    wifiChannelMap.put(2447, "2.4G Ch08");
    wifiChannelMap.put(2452, "2.4G Ch09");
    wifiChannelMap.put(2457, "2.4G Ch10");
    wifiChannelMap.put(2462, "2.4G Ch11");
    wifiChannelMap.put(2467, "2.4G Ch12");
    wifiChannelMap.put(2472, "2.4G Ch13");
    wifiChannelMap.put(2484, "2.4G Ch14");

    wifi = (WifiManager) hardwareMap.appContext.getSystemService(Context.WIFI_SERVICE);
    hardwareMap.appContext.registerReceiver(new BroadcastReceiver() {
        @Override//w w w .  j a va  2  s .co m
        public void onReceive(Context context, Intent intent) {
            LinkedList<ScanResult> results = new LinkedList<>(wifi.getScanResults());
            scanResults(results);
        }
    }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

    wifi.startScan();

    try {
        String absolutePath = hardwareMap.appContext.getFilesDir().getAbsolutePath() + "/";
        RunShellCommand cmd = new RunShellCommand();
        String output;
        if ((output = cmd.run(
                String.format("cp /data/misc/wifi/p2p_supplicant.conf %sp2p_supplicant.conf \n", absolutePath)))
                        .length() > 0) {
            RobotLog.e("Cannot copy p2p file" + output);
            operChannel = output;
        }

        String fileData = Files.toString(new File(absolutePath + "p2p_supplicant.conf"),
                Charset.defaultCharset());
        String[] datas = fileData.split("/n");
        for (String data : datas) {
            if (data.contains("p2p_oper_channel")) {
                operChannel = data.substring(data.indexOf("="));
            }
        }
    } catch (IOException ex) {
        if (operChannel.equals("")) {
            operChannel = ex.getMessage();
        }
    }
}

From source file:io.airlift.drift.transport.apache.PemReader.java

private static PKCS8EncodedKeySpec readPrivateKey(File keyFile, Optional<String> keyPassword)
        throws IOException, GeneralSecurityException {
    String content = Files.toString(keyFile, US_ASCII);

    Matcher matcher = KEY_PATTERN.matcher(content);
    if (!matcher.find()) {
        throw new KeyStoreException("found no private key: " + keyFile);
    }//w ww .j  a  v  a  2s . co m
    byte[] encodedKey = base64Decode(matcher.group(1));

    if (!keyPassword.isPresent()) {
        return new PKCS8EncodedKeySpec(encodedKey);
    }

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encodedKey);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
    SecretKey secretKey = keyFactory.generateSecret(new PBEKeySpec(keyPassword.get().toCharArray()));

    Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
    cipher.init(DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters());

    return encryptedPrivateKeyInfo.getKeySpec(cipher);
}

From source file:uk.ac.ebi.fg.annotare2.core.magetab.MageTabFiles.java

/**
 * Substitutes fake values (which were required to build MAGE-TAB graph) to a required values.
 *
 * @param file file to be sanitized// w  w  w .  j a  va  2  s .  com
 */
private static void sanitize(File file, boolean everything) {
    try {
        String str = Files.toString(file, Charsets.UTF_8);
        str = restoreOriginalNameValues(str);

        if (everything) {
            str = restoreAllUnassignedValues(str);
        }
        Files.write(str, file, Charsets.UTF_8);
    } catch (IOException e) {
        log.error("Unable to sanitize MAGE-TAB file" + file.getAbsolutePath(), e);
    }
}

From source file:org.apache.brooklyn.util.core.text.TemplateProcessor.java

/** Processes template contents according to {@link EntityAndMapTemplateModel}. */
public static String processTemplateFile(String templateFileName, EntityDriver driver,
        Map<String, ? extends Object> extraSubstitutions) {
    String templateContents;//from  w  w w. j  a  va 2  s .c  o m
    try {
        templateContents = Files.toString(new File(templateFileName), Charsets.UTF_8);
    } catch (IOException e) {
        log.warn("Error loading file " + templateFileName, e);
        throw Exceptions.propagate(e);
    }
    return processTemplateContents(templateContents, driver, extraSubstitutions);
}

From source file:org.jclouds.snia.cdmi.v1.options.CreateDataObjectOptions.java

/**
 * Create CDMI data object with file value
 * /*from   w w  w .  j  a  v a  2  s .c  om*/
 * @param value
 *           File
 * @param charset
 *           character set of file File is converted to a String value
 * @return CreateDataObjectOptions
 */
public CreateDataObjectOptions value(File value, Charset charset) throws IOException {
    jsonObjectBody.addProperty("value", (value == null) ? "" : Files.toString(value, charset));
    this.payload = jsonObjectBody.toString();
    return this;
}

From source file:org.sonar.java.parser.sslr.ActionParser.java

public Tree parse(File file) {
    try {/*from   w ww  .j a v  a2s . c o  m*/
        return parse(new Input(Files.toString(file, charset).toCharArray(), file.toURI()));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.facebook.buck.java.intellij.CompilerXml.java

/**
 * Writes the {@code compilerXml} file if and only if its content needs to be updated.
 * @return true if {@code compilerXml} was written
 *///from  w  ww.  ja  v a 2  s.c o  m
boolean write(File compilerXml) throws IOException {
    final Charset charset = Charsets.US_ASCII;

    String existingXml = null;
    if (compilerXml.exists()) {
        existingXml = Files.toString(compilerXml, charset);
    }

    String newXml = generateXml();
    boolean compilerXmlNeedsToBeWritten = !newXml.equals(existingXml);

    if (compilerXmlNeedsToBeWritten) {
        Files.write(newXml, compilerXml, charset);
    }

    return compilerXmlNeedsToBeWritten;
}

From source file:net.kyori.blossom.task.SourceReplacementTask.java

/**
 * Perform the source replacement task./*w  w  w . j a  va  2  s. c o m*/
 *
 * @throws IOException
 */
@TaskAction
public void run() throws IOException {
    final PatternSet patternSet = new PatternSet();
    patternSet.setIncludes(this.input.getIncludes());
    patternSet.setExcludes(this.input.getExcludes());

    if (this.output.exists()) {
        // Remove the output directory if it exists to prevent any possible conflicts
        deleteDirectory(this.output);
    }

    this.output.mkdirs();
    this.output = this.output.getCanonicalFile();

    // Resolve global and by-file replacements
    final Map<String, String> globalReplacements = this.resolveReplacementsGlobal();
    final Multimap<String, Map<String, String>> fileReplacements = this.resolveReplacementsByFile();

    for (final DirectoryTree dirTree : this.input.getSrcDirTrees()) {
        File dir = dirTree.getDir();

        // handle non-existent source directories
        if (!dir.exists() || !dir.isDirectory()) {
            continue;
        } else {
            dir = dir.getCanonicalFile();
        }

        // this could be written as .matching(source), but it doesn't actually work
        // because later on gradle casts it directly to PatternSet and crashes
        final FileTree tree = this.getProject().fileTree(dir).matching(this.input.getFilter())
                .matching(patternSet);

        for (final File file : tree) {
            final File destination = getDestination(file, dir, this.output);
            destination.getParentFile().mkdirs();
            destination.createNewFile();

            boolean wasChanged = false;
            String text = Files.toString(file, Charsets.UTF_8);

            if (this.isIncluded(file)) {
                for (final Map.Entry<String, String> entry : globalReplacements.entrySet()) {
                    text = text.replaceAll(entry.getKey(), entry.getValue());
                }

                wasChanged = true;
            }

            final String path = this.getFilePath(file);
            final Collection<Map<String, String>> collection = fileReplacements.get(path);
            if (collection != null && !collection.isEmpty()) {
                for (final Map<String, String> map : collection) {
                    for (final Map.Entry<String, String> entry : map.entrySet()) {
                        text = text.replaceAll(entry.getKey(), entry.getValue());
                    }
                }

                wasChanged = true;
            }

            if (wasChanged) {
                Files.write(text, destination, Charsets.UTF_8);
            } else {
                Files.copy(file, destination);
            }
        }
    }
}

From source file:org.sonar.batch.scan.filesystem.ComponentIndexer.java

@VisibleForTesting
void importSources(FileSystem fs, boolean shouldImportSource, InputFile inputFile, Resource sonarFile) {
    try {/*from   w w w. j av  a2s  .  c om*/
        // TODO this part deserves optimization.
        // No need to read full content in memory when shouldImportSource=false
        // We should try to remove BOM and count lines in a single pass
        String source = Files.toString(inputFile.file(), fs.encoding());
        // SONAR-3860 Remove BOM character from source
        source = CharMatcher.anyOf("\uFEFF").removeFrom(source);
        if (shouldImportSource) {
            sonarIndex.setSource(sonarFile, source);
        }
    } catch (Exception e) {
        throw new SonarException("Unable to read and import the source file : '" + inputFile.absolutePath()
                + "' with the charset : '" + fs.encoding() + "'.", e);
    }
}

From source file:be.iminds.aiolos.cloud.jclouds.CloudManagerImplEC2.java

protected Template getTemplate() {
    Template template = computeService.templateBuilder().imageId(locationId + "/" + imageId)
            .locationId(locationId).hardwareId(instanceType).build();

    template.getOptions().inboundPorts(inboundPorts);

    if (publicKeyFile != null) {
        try {//from  ww w  .  ja va 2s.  c  o  m
            template.getOptions().authorizePublicKey(Files.toString(publicKeyFile, StandardCharsets.UTF_8));
        } catch (IOException e) {
            Activator.logger.log(LogService.LOG_ERROR,
                    String.format("Public ssh key file (%s) does not exist.", publicKeyFile), e);
        }
    }

    ImmutableList.Builder<Statement> bootstrapBuilder = ImmutableList.<Statement>builder();
    if (adminAccess)
        bootstrapBuilder.add(AdminAccess.standard());

    StatementList bootstrap = new StatementList(bootstrapBuilder.build());
    if (!bootstrap.isEmpty())
        template.getOptions().runScript(bootstrap);

    // specify your own keypair for use in creating nodes
    //template.getOptions().as(AWSEC2TemplateOptions.class).keyPair("ec2");

    return template;
}