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.cogroo.gc.cmdline.grammarchecker.GrammarCheckerTool.java

public void run(String[] args) {
    Params params = validateAndParseParams(args, Params.class);

    String lang = params.getLang();
    CmdLineUtil.checkLanguageCode(lang);

    String country = params.getCountry();
    if (Strings.isNullOrEmpty(country)) {
        throw new TerminateToolException(1, "Country cannot be empty. Example country: BR");
    }//from  ww w .  j  a v  a 2  s. c o  m

    File rulesFile = params.getRulesFile();
    if (rulesFile != null) {
        CmdLineUtil.checkInputFile("Rules file", rulesFile);
    }

    long start = System.nanoTime();

    ComponentFactory factory;
    try {
        factory = ComponentFactory.create(new Locale(lang, country));
    } catch (InitializationException e) {
        e.printStackTrace();
        throw new TerminateToolException(1, "Could not find configuration for " + lang + ". Only "
                + new Locale("pt", "BR") + " might be supported for now.");
    }
    GrammarChecker cogroo;
    try {
        if (rulesFile == null) {
            cogroo = new GrammarChecker(factory.createPipe());
        } else {
            String serializedRules = Files.toString(rulesFile, Charsets.UTF_8);
            cogroo = new GrammarChecker(factory.createPipe(), serializedRules);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new TerminateToolException(1, "Could not create pipeline!");
    }

    System.out.println("Loading time [" + ((System.nanoTime() - start) / 1000000) + "ms]");

    Scanner kb = new Scanner(System.in);
    System.out.print("Enter the sentence or 'q' to quit: ");
    String input = kb.nextLine();

    while (!input.equals("q")) {

        CheckDocument document = new CheckDocument();
        document.setText(input);
        cogroo.analyze(document);

        if (params.getShowAnalysis()) {
            System.out.println(TextUtils.nicePrint(document));
        }

        System.out.println(document.getMistakesAsString());

        System.out.print("Enter the sentence or 'q' to quit: ");
        input = kb.nextLine();
    }

}

From source file:org.jclouds.karaf.utils.EnvHelper.java

/**
 * Extracts the credential value from the Google Cloud credentials json file.
 * @param credentialValue/*from   w ww.j a v  a  2  s  . co m*/
 * @return
 */
private static String getGoogleCredentialFromJsonFileIfPath(String credentialValue) {
    File credentialsFile = new File(credentialValue);
    if (credentialsFile.exists()) {
        try {
            String fileContents = Files.toString(credentialsFile, Charsets.UTF_8);
            Supplier<Credentials> credentialSupplier = new GoogleCredentialsFromJson(fileContents);
            return credentialSupplier.get().credential;
        } catch (IOException e) {
            return null;
        }
    } else {
        return credentialValue;
    }
}

From source file:org.apache.gora.goraci.chef.ChefSoftwareProvisioning.java

private static void performChefComputeServiceBootstrapping(Properties properties)
        throws IOException, InstantiationException, IllegalAccessException {
    // Get the credentials that will be used to authenticate to the Chef server
    String rsContinent = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_CONTINENT,
            "rackspace-cloudservers-us");
    String rsUser = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_USERNAME,
            "asf-gora");
    String rsApiKey = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_APIKEY, null);
    String rsRegion = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), RS_REGION, "DFW");
    String client = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(), CHEF_CLIENT,
            System.getProperty("user.name"));
    String organization = DataStoreFactory.findProperty(properties, MemStore.class.newInstance(),
            CHEF_ORGANIZATION, null);/*from  w w  w . j  ava2  s. c  om*/
    String pemFile = System.getProperty("user.home") + "/.chef/" + client + ".pem";
    String credential = Files.toString(new File(pemFile), Charsets.UTF_8);

    // Provide the validator information to let the nodes to auto-register themselves
    // in the Chef server during bootstrap
    String validator = organization + "-validator";
    String validatorPemFile = System.getProperty("user.home") + "/.chef/" + validator + ".pem";
    String validatorCredential = Files.toString(new File(validatorPemFile), Charsets.UTF_8);

    Properties chefConfig = new Properties();
    chefConfig.put(ChefProperties.CHEF_VALIDATOR_NAME, validator);
    chefConfig.put(ChefProperties.CHEF_VALIDATOR_CREDENTIAL, validatorCredential);

    // Create the connection to the Chef server
    ChefContext chefContext = ContextBuilder.newBuilder("chef")
            .endpoint("https://api.opscode.com/organizations/" + organization).credentials(client, credential)
            .overrides(chefConfig).buildView(ChefContext.class);

    // Create the connection to the compute provider. Note that ssh will be used to bootstrap chef
    ComputeServiceContext computeContext = ContextBuilder.newBuilder(rsContinent).endpoint(rsRegion)
            .credentials(rsUser, rsApiKey).modules(ImmutableSet.<Module>of(new SshjSshClientModule()))
            .buildView(ComputeServiceContext.class);

    // Group all nodes in both Chef and the compute provider by this group
    String group = "jclouds-chef-goraci";

    // Set the recipe to install and the configuration values to override
    String recipe = "apache2";
    JsonBall attributes = new JsonBall("{\"apache\": {\"listen_ports\": \"8080\"}}");

    // Check to see if the recipe you want exists
    List<String> runlist = null;
    Iterable<? extends CookbookVersion> cookbookVersions = chefContext.getChefService().listCookbookVersions();
    if (any(cookbookVersions, CookbookVersionPredicates.containsRecipe(recipe))) {
        runlist = new RunListBuilder().addRecipe(recipe).build();
    }
    for (Iterator<String> iterator = runlist.iterator(); iterator.hasNext();) {
        String string = (String) iterator.next();
        LOG.info(string);
    }

    // Update the chef service with the run list you wish to apply to all nodes in the group
    // and also provide the json configuration used to customize the desired values
    BootstrapConfig config = BootstrapConfig.builder().runList(runlist).attributes(attributes).build();
    chefContext.getChefService().updateBootstrapConfigForGroup(group, config);

    // Build the script that will bootstrap the node
    Statement bootstrap = chefContext.getChefService().createBootstrapScriptForGroup(group);

    TemplateBuilder templateBuilder = computeContext.getComputeService().templateBuilder();
    templateBuilder.options(runScript(bootstrap));
    // Run a node on the compute provider that bootstraps chef
    try {
        Set<? extends NodeMetadata> nodes = computeContext.getComputeService().createNodesInGroup(group, 1,
                templateBuilder.build());
        for (NodeMetadata nodeMetadata : nodes) {
            LOG.info("<< node %s: %s%n", nodeMetadata.getId(),
                    concat(nodeMetadata.getPrivateAddresses(), nodeMetadata.getPublicAddresses()));
        }
    } catch (RunNodesException e) {
        throw new RuntimeException(e.getMessage());
    }

    // Release resources
    chefContext.close();
    computeContext.close();

}

From source file:org.fcrepo.indexer.system.IndexingIT.java

@Before
public void setUp() throws ClientProtocolException, IOException {
    final PoolingClientConnectionManager connMann = new PoolingClientConnectionManager();
    connMann.setMaxTotal(MAX_VALUE);//from   www.j  av  a 2s  .  c om
    connMann.setDefaultMaxPerRoute(MAX_VALUE);
    client = new DefaultHttpClient(connMann);
    LOGGER.debug("Installing indexing namespace...");
    final String nsSparqlUpdate = "INSERT { <" + INDEXER_NAMESPACE
            + "> <http://purl.org/vocab/vann/preferredNamespacePrefix> \"indexing\"." + "<"
            + INDEXER_TEST_NAMESPACE
            + "> <http://purl.org/vocab/vann/preferredNamespacePrefix> \"indexingtest\"} WHERE { }";
    HttpPost update = new HttpPost(serverAddress + "fcr:namespaces");
    update.setEntity(new StringEntity(nsSparqlUpdate));
    update.setHeader("Content-Type", "application/sparql-update");
    HttpResponse response = client.execute(update);
    assertEquals("Failed to install indexing namespace!", SC_NO_CONTENT,
            response.getStatusLine().getStatusCode());

    LOGGER.debug("Installing indexing type information...");
    update = new HttpPost(serverAddress + "fcr:nodetypes");
    update.setHeader("Content-Type", "text/cnd");
    HttpEntity cnd = new StringEntity(
            Files.toString(new File("target/classes/indexing.cnd"), defaultCharset()));
    update.setEntity(cnd);
    response = client.execute(update);
    assertEquals("Failed to install indexing type information!", SC_NO_CONTENT,
            response.getStatusLine().getStatusCode());

    LOGGER.debug("Installing indexing test type information...");
    update = new HttpPost(serverAddress + "fcr:nodetypes");
    update.setHeader("Content-Type", "text/cnd");
    cnd = new StringEntity(Files.toString(new File("target/test-classes/indexingtest.cnd"), defaultCharset()));
    update.setEntity(cnd);
    response = client.execute(update);
    assertEquals("Failed to install indexing test type information!", SC_NO_CONTENT,
            response.getStatusLine().getStatusCode());
    /*HttpGet nsRequest = new HttpGet(serverAddress + "fcr:namespaces");
    nsRequest.setHeader("Content-Type", WebContent.contentTypeN3Alt1);
    LOGGER.debug("Now registered namespaces include:\n{}", IOUtils
        .toString(client.execute(nsRequest).getEntity().getContent()));
    nsRequest = new HttpGet(serverAddress + "fcr:nodetypes");
    nsRequest.setHeader("Content-Type", WebContent.contentTypeN3Alt1);
    LOGGER.debug("and registered node types:\n{}", IOUtils.toString(client
        .execute(nsRequest).getEntity().getContent()));*/

}

From source file:com.flysystem.core.adapter.local.Local.java

public String read(String path) throws FileNotFoundException {
    try {/*from w  w w  .j  a  v  a2s .  c  o  m*/
        return Files.toString(getExistingFile(path), Charset.defaultCharset());
    } catch (IOException e) {
        throw new FlysystemGenericException(e);
    }
}

From source file:ec.tss.tsproviders.common.xml.XmlProvider.java

@Override
protected wsTsWorkspace loadFromBean(XmlBean bean) throws IOException {
    File file = getRealFile(bean.getFile());
    String content = Files.toString(file, bean.getCharset()).replace("eu/tstoolkit:", "ec/tstoolkit.");
    return Jaxb.Parser.of(wsTsWorkspace.class).parseChars(content);
}

From source file:org.jenkinsci.plugins.periodicbackup.Util.java

/**
 *
 * This test if a given file is a valid serialized BackupObject file
 *
 * @param backupObjectFile File to test/*from w  w  w  .j  a v a 2 s  .  com*/
 * @return true if valid, false otherwise
 * @throws IOException If an IO problem occurs
 */
public static boolean isValidBackupObjectFile(File backupObjectFile) throws IOException {
    if (!backupObjectFile.exists() || !(backupObjectFile.getUsableSpace() > 0))
        return false;
    else {
        String fileAsString = Files.toString(backupObjectFile, Charsets.UTF_8);
        return fileAsString.contains("fileManager class=\"org.jenkinsci.plugins.periodicbackup")
                && fileAsString.contains("storage class=\"org.jenkinsci.plugins.periodicbackup")
                && fileAsString.contains("location class=\"org.jenkinsci.plugins.periodicbackup");
    }
}

From source file:org.jvnet.hudson.plugins.periodicbackup.Util.java

/**
 *
 * This test if a given file is a valid serialized BackupObject file
 *
 * @param backupObjectFile File to test//from ww w . java  2  s.  c o m
 * @return true if valid, false otherwise
 * @throws IOException If an IO problem occurs
 */
public static boolean isValidBackupObjectFile(File backupObjectFile) throws IOException {
    if (!backupObjectFile.exists() || !(backupObjectFile.getUsableSpace() > 0))
        return false;
    else {
        String fileAsString = Files.toString(backupObjectFile, Charsets.UTF_8);
        return fileAsString.contains("fileManager class=\"org.jvnet.hudson.plugins.periodicbackup")
                && fileAsString.contains("storage class=\"org.jvnet.hudson.plugins.periodicbackup")
                && fileAsString.contains("location class=\"org.jvnet.hudson.plugins.periodicbackup");
    }
}

From source file:eu.stratosphere.api.java.tuple.TupleGenerator.java

private static void insertCodeIntoFile(String code, File file) throws IOException {
    String fileContent = Files.toString(file, Charsets.UTF_8);
    Scanner s = new Scanner(fileContent);

    StringBuilder sb = new StringBuilder();
    String line = null;/*ww  w  .  j a  v  a 2  s  .  c  o m*/

    boolean indicatorFound = false;

    // add file beginning
    while (s.hasNextLine() && (line = s.nextLine()) != null) {
        sb.append(line + "\n");
        if (line.contains(BEGIN_INDICATOR)) {
            indicatorFound = true;
            break;
        }
    }

    if (!indicatorFound) {
        System.out.println("No indicator found in '" + file + "'. Will skip code generation.");
        s.close();
        return;
    }

    // add generator signature
    sb.append("\t// GENERATED FROM " + TupleGenerator.class.getName() + ".\n");

    // add tuple dependent code
    sb.append(code + "\n");

    // skip generated code
    while (s.hasNextLine() && (line = s.nextLine()) != null) {
        if (line.contains(END_INDICATOR)) {
            sb.append(line + "\n");
            break;
        }
    }

    // add file ending
    while (s.hasNextLine() && (line = s.nextLine()) != null) {
        sb.append(line + "\n");
    }
    s.close();
    Files.write(sb.toString(), file, Charsets.UTF_8);
}

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

private static List<X509Certificate> readCertificateChain(File certificateChainFile)
        throws IOException, GeneralSecurityException {
    String contents = Files.toString(certificateChainFile, US_ASCII);

    Matcher matcher = CERT_PATTERN.matcher(contents);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    List<X509Certificate> certificates = new ArrayList<>();

    int start = 0;
    while (matcher.find(start)) {
        byte[] buffer = base64Decode(matcher.group(1));
        certificates.add(//from  ww  w.jav a  2s.com
                (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(buffer)));
        start = matcher.end();
    }

    return certificates;
}