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

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

Introduction

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

Prototype

public static String toString(URL url, Charset charset) throws IOException 

Source Link

Document

Reads all characters from a URL into a String , using the given character set.

Usage

From source file:org.sonar.api.internal.ApiVersion.java

public static Version load(System2 system) {
    try {/* w  w w. j av  a 2 s  .  c  om*/
        URL url = system.getResource(FILE_PATH);
        String versionInFile = Resources.toString(url, StandardCharsets.UTF_8);
        return Version.parse(versionInFile);
    } catch (IOException e) {
        throw new IllegalStateException("Can not load " + FILE_PATH + " from classpath", e);
    }
}

From source file:ratpack.util.RatpackVersion.java

/**
 * The version of Ratpack./*from   w  w w .  j  a  v  a 2 s.  c o  m*/
 *
 * @return The version of Ratpack
 */
public static String getVersion() {
    ClassLoader classLoader = RatpackVersion.class.getClassLoader();
    URL resource = classLoader.getResource(RESOURCE_PATH);
    if (resource == null) {
        throw new RuntimeException("Could not find " + RESOURCE_PATH + " on classpath");
    }

    try {
        return Resources.toString(resource, CharsetUtil.UTF_8).trim();
    } catch (Exception e) {
        throw uncheck(e);
    }
}

From source file:org.apache.isis.viewer.restfulobjects.applib.JsonFixture.java

public static JsonNode readJson(final String resourceName)
        throws JsonParseException, JsonMappingException, IOException {
    return JsonMapper.instance().read(
            Resources.toString(Resources.getResource(JsonFixture.class, resourceName), Charsets.UTF_8),
            JsonNode.class);
}

From source file:com.github.lukaszkusek.assertj.xml.ResourceReader.java

public static String getFileContent(String fileName) throws IOException {
    return Resources.toString(getURL(fileName), Charsets.UTF_8);
}

From source file:com.openlattice.mail.utils.TemplateUtils.java

public static String loadTemplate(String templatePath) throws IOException {
    URL templateResource = Resources.getResource(templatePath);
    return Resources.toString(templateResource, Charsets.UTF_8);
}

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

public static void load(String propFile, Map<String, String> subs, Map<String, String> overrides)
        throws IOException {
    URL propUrl = Resources.getResource(propFile);
    String propData = Resources.toString(propUrl, Charsets.UTF_8);
    for (Map.Entry e : subs.entrySet()) {
        propData = propData.replaceAll("\\{" + e.getKey() + "\\}", (String) e.getValue());
    }/*from  w  w  w .  j a va  2  s. c o  m*/
    final Properties props = new Properties();
    props.load(new ByteArrayInputStream(propData.getBytes()));
    for (Map.Entry e : overrides.entrySet()) {
        props.setProperty((String) e.getKey(), (String) e.getValue());
    }
    Configuration.setBackingStore(new IConfiguration() {
        @Override
        public String get(String key) {
            return (String) props.getProperty(key);
        }
    });
}

From source file:org.openqa.selenium.atoms.JavaScriptLoader.java

static String loadResource(String resourcePath, String resourceTask) throws IOException {
    URL resourceUrl = JavaScriptLoader.class.getResource(resourcePath);
    if (resourceUrl != null) {
        return Resources.toString(resourceUrl, Charsets.UTF_8);
    } else {//from  w w w  .j a v a  2s  .c o m
        new Build().of(resourceTask).go();

        File topDir = InProject.locate("Rakefile").getParentFile();
        File builtFile = new File(topDir, taskToBuildOutput(resourceTask));
        return Files.toString(builtFile, Charsets.UTF_8);
    }
}

From source file:org.litecoinj.tools.WalletTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("force");
    parser.accepts("debuglog");
    OptionSpec<String> walletFileName = parser.accepts("wallet").withRequiredArg().defaultsTo("wallet");
    seedFlag = parser.accepts("seed").withRequiredArg();
    watchFlag = parser.accepts("watchkey").withRequiredArg();
    OptionSpec<NetworkEnum> netFlag = parser.accepts("net").withRequiredArg().ofType(NetworkEnum.class)
            .defaultsTo(NetworkEnum.MAIN);
    dateFlag = parser.accepts("date").withRequiredArg().ofType(Date.class)
            .withValuesConvertedBy(DateConverter.datePattern("yyyy/MM/dd"));
    OptionSpec<WaitForEnum> waitForFlag = parser.accepts("waitfor").withRequiredArg().ofType(WaitForEnum.class);
    OptionSpec<ValidationMode> modeFlag = parser.accepts("mode").withRequiredArg().ofType(ValidationMode.class)
            .defaultsTo(ValidationMode.SPV);
    OptionSpec<String> chainFlag = parser.accepts("chain").withRequiredArg();
    // For addkey/delkey.
    parser.accepts("pubkey").withRequiredArg();
    parser.accepts("privkey").withRequiredArg();
    parser.accepts("addr").withRequiredArg();
    parser.accepts("peers").withRequiredArg();
    xpubkeysFlag = parser.accepts("xpubkeys").withRequiredArg();
    OptionSpec<String> outputFlag = parser.accepts("output").withRequiredArg();
    parser.accepts("value").withRequiredArg();
    OptionSpec<String> feePerKbOption = parser.accepts("fee-per-kb").withRequiredArg();
    unixtimeFlag = parser.accepts("unixtime").withRequiredArg().ofType(Long.class);
    OptionSpec<String> conditionFlag = parser.accepts("condition").withRequiredArg();
    parser.accepts("locktime").withRequiredArg();
    parser.accepts("allow-unconfirmed");
    parser.accepts("offline");
    parser.accepts("ignore-mandatory-extensions");
    lookaheadSize = parser.accepts("lookahead-size").withRequiredArg().ofType(Integer.class);
    OptionSpec<String> passwordFlag = parser.accepts("password").withRequiredArg();
    OptionSpec<String> paymentRequestLocation = parser.accepts("payment-request").withRequiredArg();
    parser.accepts("no-pki");
    parser.accepts("dump-privkeys");
    OptionSpec<String> refundFlag = parser.accepts("refund-to").withRequiredArg();
    OptionSpec<String> txHashFlag = parser.accepts("txhash").withRequiredArg();
    options = parser.parse(args);//from  w  w w .j  av a  2 s .  c  om

    if (args.length == 0 || options.has("help") || options.nonOptionArguments().size() < 1
            || options.nonOptionArguments().contains("help")) {
        System.out.println(
                Resources.toString(WalletTool.class.getResource("wallet-tool-help.txt"), Charsets.UTF_8));
        return;
    }

    ActionEnum action;
    try {
        String actionStr = options.nonOptionArguments().get(0);
        actionStr = actionStr.toUpperCase().replace("-", "_");
        action = ActionEnum.valueOf(actionStr);
    } catch (IllegalArgumentException e) {
        System.err.println("Could not understand action name " + options.nonOptionArguments().get(0));
        return;
    }

    if (options.has("debuglog")) {
        BriefLogFormatter.init();
        log.info("Starting up ...");
    } else {
        // Disable logspam unless there is a flag.
        java.util.logging.Logger logger = LogManager.getLogManager().getLogger("");
        logger.setLevel(Level.SEVERE);
    }
    switch (netFlag.value(options)) {
    case MAIN:
    case PROD:
        params = MainNetParams.get();
        chainFileName = new File("mainnet.chain");
        break;
    case TEST:
        params = TestNet3Params.get();
        chainFileName = new File("testnet.chain");
        break;
    case REGTEST:
        params = RegTestParams.get();
        chainFileName = new File("regtest.chain");
        break;
    default:
        throw new RuntimeException("Unreachable.");
    }
    Context.propagate(new Context(params));

    mode = modeFlag.value(options);

    // Allow the user to override the name of the chain used.
    if (options.has(chainFlag)) {
        chainFileName = new File(chainFlag.value(options));
    }

    if (options.has("condition")) {
        condition = new Condition(conditionFlag.value(options));
    }

    if (options.has(passwordFlag)) {
        password = passwordFlag.value(options);
    }

    walletFile = new File(walletFileName.value(options));
    if (action == ActionEnum.CREATE) {
        createWallet(options, params, walletFile);
        return; // We're done.
    }
    if (!walletFile.exists()) {
        System.err.println("Specified wallet file " + walletFile + " does not exist. Try wallet-tool --wallet="
                + walletFile + " create");
        return;
    }

    if (action == ActionEnum.RAW_DUMP) {
        // Just parse the protobuf and print, then bail out. Don't try and do a real deserialization. This is
        // useful mostly for investigating corrupted wallets.
        FileInputStream stream = new FileInputStream(walletFile);
        try {
            Protos.Wallet proto = WalletProtobufSerializer.parseToProto(stream);
            proto = attemptHexConversion(proto);
            System.out.println(proto.toString());
            return;
        } finally {
            stream.close();
        }
    }

    InputStream walletInputStream = null;
    try {
        boolean forceReset = action == ActionEnum.RESET || (action == ActionEnum.SYNC && options.has("force"));
        WalletProtobufSerializer loader = new WalletProtobufSerializer();
        if (options.has("ignore-mandatory-extensions"))
            loader.setRequireMandatoryExtensions(false);
        walletInputStream = new BufferedInputStream(new FileInputStream(walletFile));
        wallet = loader.readWallet(walletInputStream, forceReset, (WalletExtension[]) (null));
        if (!wallet.getParams().equals(params)) {
            System.err.println("Wallet does not match requested network parameters: "
                    + wallet.getParams().getId() + " vs " + params.getId());
            return;
        }
    } catch (Exception e) {
        System.err.println("Failed to load wallet '" + walletFile + "': " + e.getMessage());
        e.printStackTrace();
        return;
    } finally {
        if (walletInputStream != null) {
            walletInputStream.close();
        }
    }

    // What should we do?
    switch (action) {
    case DUMP:
        dumpWallet();
        break;
    case ADD_KEY:
        addKey();
        break;
    case ADD_ADDR:
        addAddr();
        break;
    case DELETE_KEY:
        deleteKey();
        break;
    case CURRENT_RECEIVE_ADDR:
        currentReceiveAddr();
        break;
    case RESET:
        reset();
        break;
    case SYNC:
        syncChain();
        break;
    case SEND:
        if (options.has(paymentRequestLocation) && options.has(outputFlag)) {
            System.err.println("--payment-request and --output cannot be used together.");
            return;
        } else if (options.has(outputFlag)) {
            Coin feePerKb = null;
            if (options.has(feePerKbOption))
                feePerKb = parseCoin((String) options.valueOf(feePerKbOption));
            String lockTime = null;
            if (options.has("locktime")) {
                lockTime = (String) options.valueOf("locktime");
            }
            boolean allowUnconfirmed = options.has("allow-unconfirmed");
            send(outputFlag.values(options), feePerKb, lockTime, allowUnconfirmed);
        } else if (options.has(paymentRequestLocation)) {
            sendPaymentRequest(paymentRequestLocation.value(options), !options.has("no-pki"));
        } else {
            System.err.println("You must specify a --payment-request or at least one --output=addr:value.");
            return;
        }
        break;
    case SEND_CLTVPAYMENTCHANNEL: {
        if (!options.has(outputFlag)) {
            System.err.println("You must specify a --output=addr:value");
            return;
        }
        Coin feePerKb = null;
        if (options.has(feePerKbOption))
            feePerKb = parseCoin((String) options.valueOf(feePerKbOption));
        if (!options.has("locktime")) {
            System.err.println("You must specify a --locktime");
            return;
        }
        String lockTime = (String) options.valueOf("locktime");
        boolean allowUnconfirmed = options.has("allow-unconfirmed");
        if (!options.has(refundFlag)) {
            System.err.println("You must specify an address to refund money to after expiry: --refund-to=addr");
            return;
        }
        sendCLTVPaymentChannel(refundFlag.value(options), outputFlag.value(options), feePerKb, lockTime,
                allowUnconfirmed);
    }
        break;
    case SETTLE_CLTVPAYMENTCHANNEL: {
        if (!options.has(outputFlag)) {
            System.err.println("You must specify a --output=addr:value");
            return;
        }
        Coin feePerKb = null;
        if (options.has(feePerKbOption))
            feePerKb = parseCoin((String) options.valueOf(feePerKbOption));
        boolean allowUnconfirmed = options.has("allow-unconfirmed");
        if (!options.has(txHashFlag)) {
            System.err.println("You must specify the transaction to spend: --txhash=tx-hash");
            return;
        }
        settleCLTVPaymentChannel(txHashFlag.value(options), outputFlag.value(options), feePerKb,
                allowUnconfirmed);
    }
        break;
    case REFUND_CLTVPAYMENTCHANNEL: {
        if (!options.has(outputFlag)) {
            System.err.println("You must specify a --output=addr:value");
            return;
        }
        Coin feePerKb = null;
        if (options.has(feePerKbOption))
            feePerKb = parseCoin((String) options.valueOf(feePerKbOption));
        boolean allowUnconfirmed = options.has("allow-unconfirmed");
        if (!options.has(txHashFlag)) {
            System.err.println("You must specify the transaction to spend: --txhash=tx-hash");
            return;
        }
        refundCLTVPaymentChannel(txHashFlag.value(options), outputFlag.value(options), feePerKb,
                allowUnconfirmed);
    }
        break;
    case ENCRYPT:
        encrypt();
        break;
    case DECRYPT:
        decrypt();
        break;
    case MARRY:
        marry();
        break;
    case ROTATE:
        rotate();
        break;
    case SET_CREATION_TIME:
        setCreationTime();
        break;
    }

    if (!wallet.isConsistent()) {
        System.err.println("************** WALLET IS INCONSISTENT *****************");
        return;
    }

    saveWallet(walletFile);

    if (options.has(waitForFlag)) {
        WaitForEnum value;
        try {
            value = waitForFlag.value(options);
        } catch (Exception e) {
            System.err.println("Could not understand the --waitfor flag: Valid options are WALLET_TX, BLOCK, "
                    + "BALANCE and EVER");
            return;
        }
        wait(value);
        if (!wallet.isConsistent()) {
            System.err.println("************** WALLET IS INCONSISTENT *****************");
            return;
        }
        saveWallet(walletFile);
    }
    shutdown();
}

From source file:org.sonar.api.internal.SonarQubeVersionFactory.java

public static SonarQubeVersion create(System2 system) {
    try {/*from  w w  w  .ja  v  a 2 s . c  om*/
        URL url = system.getResource(FILE_PATH);
        String versionInFile = Resources.toString(url, StandardCharsets.UTF_8);
        return new SonarQubeVersion(Version.parse(versionInFile));
    } catch (IOException e) {
        throw new IllegalStateException("Can not load " + FILE_PATH + " from classpath", e);
    }
}

From source file:org.arkhamnetwork.playersync.managers.SQLManager.java

private static void setupSQLTables() throws IOException, SQLException {
    URL resource = Resources.getResource(PlayerSync.class, "/tables.sql");
    String[] databaseStructure = Resources.toString(resource, Charsets.UTF_8).split(";");

    if (databaseStructure.length == 0) {
        return;//  ww  w .  j  a v a  2s.c  o m
    }
    Statement statement = null;
    try {
        C.setAutoCommit(false);
        statement = C.createStatement();

        for (String query : databaseStructure) {
            query = query.trim();

            if (query.isEmpty()) {
                continue;
            }

            statement.execute(query);
        }
        C.commit();
    } finally {
        C.setAutoCommit(true);
        if (statement != null && !statement.isClosed()) {
            statement.close();
        }
    }
}