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.jcruncher.hbs.HbsProcessor.java

@Override
public void process(List<File> sources, File dest, boolean asNeeded) {
    try {/*  www. j a  v  a2  s  .  c om*/
        // --------- Build Item List To Be Compiled --------- //
        List<Item> items = null;
        Item singleItem = null;

        // if the destination is a folder, then, we have a list of Items
        if (dest.isDirectory()) {
            items = new ArrayList<Item>();
        }
        // otherwise, it is just a singleItem (file and the list of the parts)
        else {
            singleItem = new Item(sources, dest);
        }

        // build the Item
        for (File file : sources) {
            String content = Files.toString(file, Charsets.UTF_8);
            String contentName = Files.getNameWithoutExtension(file.getName());
            List<Part> parts = getParts(content, contentName);

            if (items != null) {
                items.add(new Item(file, new File(dest, contentName + ".js"), parts));
            } else {
                singleItem.addParts(parts);
            }
        }

        // in case of a singleItem, we update the items as it is the canonical form.
        if (items == null) {
            items = new ArrayList<Item>();
            items.add(singleItem);
        }
        // --------- /Build Item List To Be Compiled --------- //

        // --------- Save Items --------- //
        for (Item item : items) {
            if (!asNeeded || doesItemNeedRefresh(item)) {
                processItem(item);
            }

        }
        // --------- /Save Items --------- //
    } catch (Exception e) {
        System.out.println("\nERROR: hbs cannot process because: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:org.grycap.gpf4med.cloud.util.CloudUtils.java

/**
 * Loads the RSA SSH private key of the current user from the default location.
 * @return the login credentials of the current user.
 *//*www .  j  a  v a 2  s .  co m*/
public static LoginCredentials currentUser() {
    final String privateKeyFile = System.getProperty("user.home") + "/.ssh/id_rsa";
    final String privateKey;
    try {
        privateKey = Files.toString(new File(privateKeyFile), UTF_8);
    } catch (IOException e) {
        throw propagate(e);
    }
    assert privateKey.startsWith("-----BEGIN RSA PRIVATE KEY-----") : "invalid key:\n" + privateKey;
    return LoginCredentials.builder().user(System.getProperty("user.name")).privateKey(privateKey).build();
}

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

public static String getJs(File assetsFolder) {
    try {/*  w  w  w.j a v  a2  s .  com*/
        return String.format("<script language=\"javascript\">%s</script>",
                Files.toString(new File(assetsFolder, "script.js"), Charsets.UTF_8));
    } catch (IOException e) {
        return "";
    }
}

From source file:org.sonar.sslr.internal.toolkit.ToolkitPresenter.java

public void onSourceCodeOpenButtonClick() {
    File fileToParse = view.pickFileToParse();
    if (fileToParse != null) {
        view.clearConsole();// w ww  . j av a  2  s. com
        try {
            view.displayHighlightedSourceCode(Files.toString(fileToParse, configurationModel.getCharset()));
        } catch (IOException e) {
            Throwables.propagate(e);
        }
        model.setSourceCode(fileToParse, configurationModel.getCharset());
        view.displayHighlightedSourceCode(model.getHighlightedSourceCode());
        view.displayAst(model.getAstNode());
        view.displayXml(model.getXml());
        view.scrollSourceCodeTo(new Point(0, 0));
        view.setFocusOnAbstractSyntaxTreeView();
        view.enableXPathEvaluateButton();
    }
}

From source file:org.sonar.plugins.xml.checks.XmlFile.java

/**
 * Create a temporary file without any character before the prolog and update the following
 * attributes in order to correctly report issues:
 * <ul>/*from w ww.ja va  2  s  . c  o  m*/
 *   <li> lineDeltaForIssue
 *   <li> file
 */
private void processCharBeforePrologInFile(FileSystem fileSystem, int lineDelta) {
    try {
        String content = Files.toString(inputFile.file(), fileSystem.encoding());
        File tempFile = new File(fileSystem.workDir(), inputFile.file().getName());

        int index = content.indexOf(XML_PROLOG_START_TAG);
        Files.write(content.substring(index), tempFile, fileSystem.encoding());

        noCharBeforePrologFile = tempFile;

        if (index != -1) {
            characterDeltaForHighlight += index;
        }

        if (lineDelta > 1) {
            lineDeltaForIssue = lineDelta - 1;
        }

    } catch (IOException e) {
        LOG.warn("Unable to analyse file {}", inputFile.absolutePath(), e);
    }
}

From source file:com.google.dart.java2dart.engine.MainEngine.java

public static void main(String[] args) throws Exception {
    if (args.length != 2 && args.length != 3) {
        System.out.println("Usage: java2dart <target-src-folder> <target-test-folder> [src-package]");
        System.exit(0);/*from   www.j  av a 2  s.c  o m*/
    }
    String targetFolder = args[0];
    String targetTestFolder = args[1];
    if (args.length == 3) {
        System.out.println("Overrriding default src package to: " + src_package);
        src_package = args[2];
    }
    System.out.println("Generating files into " + targetFolder);
    new File(targetFolder).mkdirs();
    //
    engineFolder = new File("../../../tools/plugins/com.google.dart.engine/src");
    engineTestFolder = new File("../../../tools/plugins/com.google.dart.engine_test/src");
    engineFolder2 = new File("src");
    engineFolder = engineFolder.getCanonicalFile();
    // configure Context
    context.addClasspathFile(new File("../../../../third_party/guava/r13/guava-13.0.1.jar"));
    context.addClasspathFile(new File("../../../../third_party/junit/v4_8_2/junit.jar"));
    context.addSourceFolder(engineFolder);
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/utilities/ast"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/utilities/instrumentation"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/sdk"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/sdk"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/source"));
    context.addSourceFile(new File(engineFolder, "com/google/dart/engine/utilities/source/LineInfo.java"));
    context.addSourceFile(new File(engineFolder, "com/google/dart/engine/utilities/source/SourceRange.java"));
    context.addSourceFile(new File(engineFolder, "com/google/dart/engine/utilities/dart/ParameterKind.java"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/ast"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/ast/visitor"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/constant"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/element"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/error"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/html/ast"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/html/ast/visitor"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/html/parser"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/html/scanner"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/parser"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/resolver"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/scanner"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/type"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/builder"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/cache"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/constant"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/element"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/error"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/parser"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/resolver"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/scope"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/type"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/verifier"));
    context.addSourceFile(
            new File(engineFolder2, "com/google/dart/java2dart/util/ToFormattedSourceVisitor.java"));
    context.addSourceFile(new File(engineFolder, "com/google/dart/engine/AnalysisEngine.java"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/utilities/logging"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/context"));
    context.addSourceFiles(new File(engineFolder, "com/google/dart/engine/internal/context"));
    // Tests
    context.addSourceFile(
            new File(engineTestFolder, "com/google/dart/engine/utilities/io/FileUtilities2.java"));
    context.addSourceFile(new File(engineTestFolder, "com/google/dart/engine/EngineTestCase.java"));
    context.addSourceFile(
            new File(engineTestFolder, "com/google/dart/engine/error/GatheringErrorListener.java"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/scanner"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/parser"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/ast"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/element"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/internal/element"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/internal/type"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/resolver"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/internal/resolver"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/internal/scope"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/context"));
    context.addSourceFiles(new File(engineTestFolder, "com/google/dart/engine/internal/context"));
    // configure renames
    context.addRename("Lcom/google/dart/engine/ast/IndexExpression;.(Lcom/google/dart/engine/ast/Expression;"
            + "Lcom/google/dart/engine/scanner/Token;Lcom/google/dart/engine/ast/Expression;"
            + "Lcom/google/dart/engine/scanner/Token;)", "forTarget");
    context.addRename("Lcom/google/dart/engine/ast/IndexExpression;.(Lcom/google/dart/engine/scanner/Token;"
            + "Lcom/google/dart/engine/scanner/Token;Lcom/google/dart/engine/ast/Expression;"
            + "Lcom/google/dart/engine/scanner/Token;)", "forCascade");
    context.addRename(
            "Lcom/google/dart/engine/html/ast/XmlTagNode;.becomeParentOf<T:Lcom/google/dart/engine/html/ast/XmlNode;>(Ljava/util/List<TT;>;Ljava/util/List<TT;>;)",
            "becomeParentOfEmpty");
    // translate into single CompilationUnit
    dartUnit = context.translate();
    // run processors
    {
        List<SemanticProcessor> PROCESSORS = ImmutableList.of(new ConstructorSemanticProcessor(context),
                new ObjectSemanticProcessor(context), new CollectionSemanticProcessor(context),
                new IOSemanticProcessor(context), new PropertySemanticProcessor(context),
                new GuavaSemanticProcessor(context), new JUnitSemanticProcessor(context),
                new BeautifySemanticProcessor(context), new EngineSemanticProcessor(context));
        for (SemanticProcessor processor : PROCESSORS) {
            processor.process(dartUnit);
        }
    }
    // run this again, because we may introduce conflicts when convert methods to getters/setters
    context.ensureUniqueClassMemberNames(dartUnit);
    context.ensureNoVariableNameReferenceFromInitializer(dartUnit);
    context.ensureMethodParameterDoesNotHide(dartUnit);
    // handle reflection
    EngineSemanticProcessor.rewriteReflectionFieldsWithDirect(context, dartUnit);
    // dump as several libraries
    Files.copy(new File("resources/java_core.dart"), new File(targetFolder + "/java_core.dart"));
    Files.copy(new File("resources/java_io.dart"), new File(targetFolder + "/java_io.dart"));
    Files.copy(new File("resources/java_junit.dart"), new File(targetFolder + "/java_junit.dart"));
    Files.copy(new File("resources/java_engine.dart"), new File(targetFolder + "/java_engine.dart"));
    Files.copy(new File("resources/java_engine_io.dart"), new File(targetFolder + "/java_engine_io.dart"));
    Files.copy(new File("resources/all_test.dart"), new File(targetTestFolder + "/all_test.dart"));
    {
        CompilationUnit library = buildInstrumentationLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/instrumentation.dart"),
                Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildSourceLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/source.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildSourceIoLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/source_io.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildErrorLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/error.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildScannerLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/scanner.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildHtmlLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/html.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildUtilitiesDartLibrary();
        File astFile = new File(targetFolder + "/utilities_dart.dart");
        Files.write(getFormattedSource(library), astFile, Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildAstLibrary();
        File astFile = new File(targetFolder + "/ast.dart");
        Files.write(getFormattedSource(library), astFile, Charsets.UTF_8);
        Files.append(Files.toString(new File("resources/ast_include.dart"), Charsets.UTF_8), astFile,
                Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildParserLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/parser.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildSdkLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/sdk.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildSdkIoLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/sdk_io.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildConstantLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/constant.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildElementLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/element.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildResolverLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/resolver.dart"), Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildEngineLibrary();
        Files.write(getFormattedSource(library), new File(targetFolder + "/engine.dart"), Charsets.UTF_8);
    }
    // Tests
    {
        CompilationUnit library = buildTestSupportLibrary();
        File testSupportFile = new File(targetTestFolder + "/test_support.dart");
        Files.write(getFormattedSource(library), testSupportFile, Charsets.UTF_8);
        Files.append(Files.toString(new File("resources/test_support_include.dart"), Charsets.UTF_8),
                testSupportFile, Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildScannerTestLibrary();
        Files.write(getFormattedSource(library), new File(targetTestFolder + "/scanner_test.dart"),
                Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildParserTestLibrary();
        // replace reflection methods
        StringWriter methodWriter = new StringWriter();
        EngineSemanticProcessor.replaceReflectionMethods(context, new PrintWriter(methodWriter), dartUnit);
        // write to file
        File libraryFile = new File(targetTestFolder + "/parser_test.dart");
        Files.write(getFormattedSource(library), libraryFile, Charsets.UTF_8);
        Files.append(methodWriter.toString(), libraryFile, Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildAstTestLibrary();
        File astFile = new File(targetTestFolder + "/ast_test.dart");
        Files.write(getFormattedSource(library), astFile, Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildElementTestLibrary();
        Files.write(getFormattedSource(library), new File(targetTestFolder + "/element_test.dart"),
                Charsets.UTF_8);
    }
    {
        CompilationUnit library = buildResolverTestLibrary();
        Files.write(getFormattedSource(library), new File(targetTestFolder + "/resolver_test.dart"),
                Charsets.UTF_8);
    }
    System.out.println("Translation complete");
}

From source file:ch.hortis.maven.plugins.JsConsoleRemoverMojo.java

/**
 * Remove all console occurences from the file and store it in the outputDirectory
 *
 * @param file the file name containing the path
 *//*from w w  w . jav a  2  s  .c  om*/
private void removeConsole(String file) {
    try {
        String content = Files.toString(new File(sourceDirectory, file), Charsets.UTF_8);
        int numberOfOccurences = countOccurrenceOfPattern(content);
        if (numberOfOccurences > 0) {
            getLog().info("** contains " + numberOfOccurences + " occurences of console");
        }
        Files.write(content.replaceAll(pattern, "").getBytes(), new File(outputDirectory, file));
    } catch (IOException e) {
        getLog().error(e);
    }
}

From source file:org.mayocat.shop.front.resources.ResourceResource.java

@GET
@Path("{path:.+}")
public Response getResource(@PathParam("path") String resource, @Context Request request) throws Exception {
    ThemeResource themeResource = themeFileResolver.getResource(resource, context.getRequest().getBreakpoint());
    if (themeResource == null) {
        logger.debug("Resource [{}] not found", resource);
        throw new WebApplicationException(404);
    }//from ww w.j a v a 2  s  .  c  om

    File file;

    switch (themeResource.getType()) {
    default:
    case FILE:
        file = themeResource.getPath().toFile();
        break;
    case CLASSPATH_RESOURCE:
        URI uri = Resources.getResource(themeResource.getPath().toString()).toURI();

        if (uri.getScheme().equals("jar")) {
            // Not supported for now
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        file = new File(uri);
        break;
    }

    String tag = Files.hash(file, Hashing.murmur3_128()).toString();
    EntityTag eTag = new EntityTag(tag);

    URL url = file.toURI().toURL();
    long lastModified = ResourceURL.getLastModified(url);
    if (lastModified < 1) {
        // Something went wrong trying to get the last modified time: just use the current time
        lastModified = System.currentTimeMillis();
    }
    // zero out the millis since the date we get back from If-Modified-Since will not have them
    lastModified = (lastModified / 1000) * 1000;

    CacheControl cacheControl = new CacheControl();
    cacheControl.setMaxAge(24 * 3600);
    Response.ResponseBuilder builder = request.evaluatePreconditions(new Date(lastModified), eTag);
    String mimeType = guessMimeType(file).or("application/octet-stream");

    if (builder == null) {
        if (mimeType.equals("application/javascript")) {
            // Handle javascript files as a special case. Something (what ?) is serializing them as URIs instead
            // of file contents.
            // FIXME: find out what at in Jersey or Jackson or DW is doing that and disable that behavior
            builder = Response.ok(Files.toString(file, Charsets.UTF_8), mimeType);
        } else {
            builder = Response.ok(file, mimeType);
        }
    }

    return builder.cacheControl(cacheControl).lastModified(new Date(lastModified)).build();
}

From source file:com.proofpoint.event.monitor.MonitorsProvider.java

@Override
public synchronized Set<Monitor> get() {
    if (monitors == null) {
        try {/*  w  ww  . ja v a 2s  .com*/
            String json = Files.toString(new File(monitorRulesFile), Charsets.UTF_8);
            monitors = monitorLoader.load(json);
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }

        for (Monitor monitor : monitors) {
            monitor.start();
        }

        Set<String> eventTypes = newHashSet();
        for (Monitor monitor : monitors) {
            eventTypes.add(monitor.getEventType());
        }

        if (announcer != null) {
            for (String eventType : eventTypes) {
                ServiceAnnouncement announcement = ServiceAnnouncement.serviceAnnouncement("eventTap")
                        .addProperty("http", httpServerInfo.getHttpUri().toString() + "/v1/event")
                        .addProperty("tapId", flowId).addProperty("flowId", flowId)
                        .addProperty("eventType", eventType).build();
                announcer.addServiceAnnouncement(announcement);
                announcements.add(announcement);
            }
        }

        if (exporter != null) {
            for (Monitor monitor : monitors) {
                String name = generatedNameOf(Monitor.class, named(monitor.getName()));
                exporter.export(name, monitor);
                mbeanNames.add(name);
            }
        }
    }

    return monitors;
}

From source file:com.facebook.buck.android.GenerateManifestStep.java

@Override
public int execute(ExecutionContext context) {

    if (skeletonManifestPath.getNameCount() == 0) {
        throw new HumanReadableException("Skeleton manifest filepath is missing");
    }//from   ww w  .ja va  2s  .  c  o m

    if (outManifestPath.getNameCount() == 0) {
        throw new HumanReadableException("Output Manifest filepath is missing");
    }

    if (libraryManifestPaths == null || libraryManifestPaths.isEmpty()) {
        warnUser(context, "No library manifests found. Aborting manifest merge step.");
        return 1;
    }

    try {
        Files.createParentDirs(outManifestPath.toFile());
    } catch (IOException e) {
        e.printStackTrace(context.getStdErr());
        return 1;
    }

    List<File> libraryManifestFiles = Lists.newArrayList();

    for (Path path : libraryManifestPaths) {
        libraryManifestFiles.add(path.toFile());
    }

    File skeletonManifestFile = skeletonManifestPath.toFile();

    ICallback callback = new ICallback() {
        @Override
        public int queryCodenameApiLevel(@NonNull String codename) {
            return BASE_SDK_LEVEL;
        }
    };

    IMergerLog log = MergerLog.wrapSdkLog(new BuckEventAndroidLogger(context.getBuckEventBus()));

    ManifestMerger merger = new ManifestMerger(log, callback);

    File outManifestFile = outManifestPath.toFile();
    if (!merger.process(outManifestFile, skeletonManifestFile,
            Iterables.toArray(libraryManifestFiles, File.class))) {
        throw new HumanReadableException("Error generating manifest file");
    }

    if (context.getPlatform() == Platform.WINDOWS) {
        // Convert line endings to Lf on Windows.
        try {
            String xmlText = Files.toString(outManifestFile, Charsets.UTF_8);
            xmlText = xmlText.replace("\r\n", "\n");
            Files.write(xmlText.getBytes(Charsets.UTF_8), outManifestFile);
        } catch (IOException e) {
            throw new HumanReadableException("Error converting line endings of manifest file");
        }
    }

    return 0;
}