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.opendaylight.controller.config.persist.storage.file.FileStorageAdapter.java

@Override
public void persistConfig(ConfigSnapshotHolder holder) throws IOException {
    Preconditions.checkNotNull(storage, "Storage file is null");

    String content = Files.toString(storage, ENCODING);
    if (numberOfStoredBackups == Integer.MAX_VALUE) {
        resetLastConfig(content);//from   w  ww  . j  ava 2 s .  co  m
        persistLastConfig(holder);
    } else {
        if (numberOfStoredBackups == 1) {
            Files.write("", storage, ENCODING);
            persistLastConfig(holder);
        } else {
            int count = StringUtils.countMatches(content, SEPARATOR_S);
            if ((count + 1) < numberOfStoredBackups) {
                resetLastConfig(content);
                persistLastConfig(holder);
            } else {
                String contentSubString = StringUtils.substringBefore(content, SEPARATOR_E);
                contentSubString = contentSubString.concat(SEPARATOR_E_PURE);
                content = StringUtils.substringAfter(content, contentSubString);
                resetLastConfig(content);
                persistLastConfig(holder);
            }
        }
    }
}

From source file:com.mgmtp.perfload.agent.AgentModule.java

@Provides
@Singleton/*  w ww.  j a  v  a 2  s .  c om*/
@SuppressWarnings("unchecked")
Config provideConfig(@ConfigFile final File configFile) throws IOException {
    String json = Files.toString(configFile, Charsets.UTF_8);
    JSONObject jsonObject = JSONObject.fromObject(json);

    JsonConfig entryPointsConfig = new JsonConfig();
    entryPointsConfig.setArrayMode(JsonConfig.MODE_LIST);
    entryPointsConfig.setRootClass(String.class);

    JSONObject entryPointsObject = jsonObject.getJSONObject("entryPoints");
    List<String> servlets = (List<String>) JSONSerializer.toJava(entryPointsObject.getJSONArray("servlets"),
            entryPointsConfig);
    List<String> filters = (List<String>) JSONSerializer.toJava(entryPointsObject.getJSONArray("filters"),
            entryPointsConfig);

    JSONObject instrumentationsObject = jsonObject.getJSONObject("instrumentations");
    Set<String> keySet = instrumentationsObject.keySet();

    // instrumentations by class
    Map<String, Map<String, MethodInstrumentations>> classInstrumentationsMap = newHashMapWithExpectedSize(
            keySet.size());

    for (String className : keySet) {
        JSONObject classConfig = instrumentationsObject.getJSONObject(className);
        Set<String> methodEntryKeySet = classConfig.keySet();

        // instrumentations by method
        Map<String, MethodInstrumentations> methodInstrumentationsMap = newHashMapWithExpectedSize(
                methodEntryKeySet.size());

        for (String methodName : methodEntryKeySet) {
            JSONArray methodConfig = classConfig.getJSONArray(methodName);
            List<List<String>> methodArgsLists = newArrayListWithCapacity(methodConfig.size());
            for (Object obj : methodConfig) {
                JSONArray paramsArray = (JSONArray) obj;
                List<String> params = (List<String>) JSONSerializer.toJava(paramsArray, entryPointsConfig);
                methodArgsLists.add(params);
            }
            methodInstrumentationsMap.put(methodName, new MethodInstrumentations(methodName, methodArgsLists));
        }

        classInstrumentationsMap.put(className, methodInstrumentationsMap);
    }

    EntryPoints entryPoints = new EntryPoints(servlets, filters);
    return new Config(entryPoints, classInstrumentationsMap);
}

From source file:com.splout.db.engine.EmbeddedMySQL.java

/**
 * TODO MySQL Hangs if port is busy, we should perform a timeout in a separate thred.
 *///from  ww w . j  a v  a  2  s .com
@SuppressWarnings({ "unchecked", "rawtypes" })
public void start(boolean deleteFilesIfExist) throws IOException, InterruptedException {
    if (deleteFilesIfExist && config.residentFolder.exists()) {
        File pidFile = new File(config.residentFolder, "data/MysqldResource.pid");
        if (pidFile.exists()) {
            // Issue "kill -9" if process is still alive
            String pid = Files.toString(pidFile, Charset.defaultCharset());
            log.info("Killing existing process: " + pid);
            Runtime.getRuntime().exec("kill -9 " + pid).waitFor();
        }
        log.info("Deleting contents of: " + config.residentFolder);
        FileUtils.deleteDirectory(config.residentFolder);
    }
    log.info("Using config: " + config);
    MysqldResource mysqldResource = new MysqldResource(config.residentFolder);
    Map<String, String> database_options = new HashMap();
    database_options.put(MysqldResourceI.PORT, Integer.toString(config.port));
    database_options.put(MysqldResourceI.INITIALIZE_USER, "true");
    database_options.put(MysqldResourceI.INITIALIZE_USER_NAME, config.user);
    database_options.put(MysqldResourceI.INITIALIZE_PASSWORD, config.pass);
    database_options.put("innodb-file-per-table", "true");

    if (config.customConfig != null) {
        for (Map.Entry<String, Object> entry : config.customConfig.entrySet()) {
            database_options.put(entry.getKey(), entry.getValue().toString());
        }
    }

    log.info("Using the following MySQL Configuration:");
    for (Map.Entry<String, String> entry : database_options.entrySet()) {
        log.info("MySQLConf: " + entry.getKey() + " -> " + entry.getValue());
    }
    // I have to do this checking myself, otherwise in some cases mysqldResource will block undefinitely...
    try {
        ServerSocket serverSocket = new ServerSocket(config.port);
        serverSocket.close();
    } catch (IOException e) {
        throw new RuntimeException("Port already in use: " + config.port);
    }
    if (mysqldResource.isRunning()) {
        throw new RuntimeException("MySQL already running!");
    }
    mysqldResource.start("test-mysqld-thread", database_options);
    if (!mysqldResource.isRunning()) {
        throw new RuntimeException("MySQL did not start successfully!");
    }
    log.info("MySQL is running.");
    resource = mysqldResource;
}

From source file:com.theoryinpractise.coffeescript.CoffeeScriptCompilerMojo.java

public void execute() throws MojoExecutionException {

    if (compileIndividualFiles && map) {
        throw new MojoExecutionException("Unable to generate source maps when compiling joinsets individually");
    }//  w  w  w  . j av a 2 s  . c o  m

    if (map && !version.equals("1.6.1")) {
        throw new MojoExecutionException("CoffeeScript 1.6.1 is required for using source maps");
    }

    if (!acceptableVersions.contains(version)) {

        String error = String.format(
                "Unsupported version of coffee-script specified (%s) - supported versions: %s", version,
                Joiner.on(", ").join(acceptableVersions));

        throw new MojoExecutionException(error);
    }

    getLog().info(String.format("coffee-maven-plugin using coffee script version %s", version));
    CoffeeScriptCompiler coffeeScriptCompiler = new CoffeeScriptCompiler(version);

    try {
        if (compileIndividualFiles) {
            getLog().info("Starting individual compilations of files");

            for (JoinSet joinSet : findJoinSets()) {
                StringBuilder compiled = new StringBuilder();
                for (File file : joinSet.getFiles()) {
                    getLog().info("Compiling File " + file.getName() + " in JoinSet:" + joinSet.getId());
                    compiled.append(
                            coffeeScriptCompiler
                                    .compile(Files.toString(file, Charsets.UTF_8), file.getName(), bare,
                                            getSourceMapType(), header, file.getName().endsWith(".litcoffee"))
                                    .getJs())
                            .append("\n");
                }
                write(joinSet.getCoffeeOutputDirectory(), joinSet.getId(),
                        new CompileResult(compiled.toString(), null));
            }
        } else {
            for (JoinSet joinSet : findJoinSets()) {
                getLog().info(
                        "Compiling JoinSet: " + joinSet.getId() + " with files:  " + joinSet.getFileNames());

                String sourceName = joinSet.getId() + (joinSet.isLiterate() ? ".litcoffee" : ".coffee");
                CompileResult compiled = coffeeScriptCompiler.compile(joinSet.getConcatenatedStringOfFiles(),
                        sourceName, bare, getSourceMapType(), header, joinSet.isLiterate());

                write(joinSet.getCoffeeOutputDirectory(), joinSet.getId(), compiled);
            }
        }

    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.glowroot.config.ConfigFile.java

Config loadConfig() throws IOException {
    if (!file.exists()) {
        Config config = getDefaultConfig();
        write(config);/* w ww. jav a  2  s .  c  o m*/
        return config;
    }
    String content = Files.toString(file, Charsets.UTF_8);
    Config config;
    String warningMessage = null;
    try {
        config = readValue(content);
    } catch (Exception e) {
        // immutables json processing wraps IOExceptions inside RuntimeExceptions so can't rely
        // on just catching IOException here
        logger.warn("error processing config file: {}", file.getAbsolutePath(), e);
        File backupFile = new File(file.getParentFile(), file.getName() + ".invalid-orig");
        config = getDefaultConfig();
        try {
            Files.copy(file, backupFile);
            warningMessage = "due to an error in the config file, it has been backed up to"
                    + " extension '.invalid-orig' and overwritten with the default config";
        } catch (IOException f) {
            logger.warn("error making a copy of the invalid config file before overwriting it", f);
            warningMessage = "due to an error in the config file, it has been overwritten with"
                    + " the default config";
        }
    }
    // it's nice to update config.json on startup if it is missing some/all config
    // properties so that the file contents can be reviewed/updated/copied if desired
    writeToFileIfNeeded(config, content);
    if (warningMessage != null) {
        logger.warn(warningMessage);
    }
    return config;
}

From source file:org.spongepowered.common.util.SpongeUsernameCache.java

/**
 * Load the cache from file//w  w  w. ja v  a  2s . c  o  m
 */
public static void load() {
    loaded = true;
    if (!saveFile.exists())
        return;

    try {

        String json = Files.toString(saveFile, charset);
        Type type = new TypeToken<Map<UUID, String>>() {
            private static final long serialVersionUID = 1L;
        }.getType();

        map = gson.fromJson(json, type);
    } catch (JsonSyntaxException e) {
        SpongeImpl.getLogger().error("Could not parse username cache file as valid json, deleting file", e);
        saveFile.delete();
    } catch (IOException e) {
        SpongeImpl.getLogger().error("Failed to read username cache file from disk, deleting file", e);
        saveFile.delete();
    } finally {
        // Can sometimes occur when the json file is malformed
        if (map == null) {
            map = Maps.newHashMap();
        }
    }
}

From source file:org.moe.designer.ddms.screenshot.DeviceArtDescriptor.java

public static List<DeviceArtDescriptor> getDescriptors(@Nullable File[] folders) {
    List<File> files = getDescriptorFiles(folders);
    List<DeviceArtDescriptor> result = Lists.newArrayList();

    for (File file : files)
        try {/*from   w  w w .jav a2s . c o m*/
            String xml = Files.toString(file, Charsets.UTF_8);
            Document document = XmlUtils.parseDocumentSilently(xml, false);
            if (document != null) {
                File baseFolder = file.getParentFile();
                addDescriptors(result, document, baseFolder);
            } else {
                Logger.getInstance(DeviceArtDescriptor.class).error("Couldn't parse " + file);
            }
        } catch (IOException e) {
            Logger.getInstance(DeviceArtDescriptor.class).error(e);
        }

    return result;
}

From source file:com.android.builder.png.VectorDrawableRenderer.java

@Override
public void generateFile(File toBeGenerated, File original) throws IOException {
    Files.createParentDirs(toBeGenerated);

    if (isXml(toBeGenerated)) {
        Files.copy(original, toBeGenerated);
    } else {//  w w w .  j  av  a  2 s  .  c  o m
        mLogger.info("Generating PNG: [%s] from [%s]", toBeGenerated.getAbsolutePath(),
                original.getAbsolutePath());

        FolderConfiguration folderConfiguration = getFolderConfiguration(toBeGenerated);
        checkState(folderConfiguration.getDensityQualifier() != null);
        Density density = folderConfiguration.getDensityQualifier().getValue();

        String xmlContent = Files.toString(original, Charsets.UTF_8);
        float scaleFactor = density.getDpiValue() / (float) Density.MEDIUM.getDpiValue();
        if (scaleFactor <= 0) {
            scaleFactor = 1.0f;
        }

        final VdPreview.TargetSize imageSize = VdPreview.TargetSize.createSizeFromScale(scaleFactor);
        BufferedImage image = VdPreview.getPreviewFromVectorXml(imageSize, xmlContent, null);
        checkState(image != null, "Generating the image failed.");
        ImageIO.write(image, "png", toBeGenerated);
    }
}

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

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

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

From source file:com.splout.db.hazelcast.TablespaceVersionStore.java

protected Map<String, Long> readValues(File file) throws JSONSerDeException, IOException {
    if (file.exists()) {
        return JSONSerDe.deSer(Files.toString(file, UTF8), MAP_STRING_LONG_TYPE_REF);
    } else {/*from   w w  w  . ja  v  a2 s  .co  m*/
        return null;
    }
}