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.opennms.web.admin.nodeManagement.SnmpConfigServlet.java

private void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    SnmpInfo snmpInfo = createFromRequest(request);
    String firstIPAddress = request.getParameter("firstIPAddress");
    String lastIPAddress = request.getParameter("lastIPAddress");
    String ipAddress = request.getParameter("ipAddress");
    LOG.debug("doPost: snmpInfo:{}, firstIpAddress:{}, lastIpAddress:{}", snmpInfo.toString(), firstIPAddress,
            lastIPAddress);/* ww w  . j  ava 2  s . c om*/

    final SnmpConfigServletAction action = determineAction(request);
    boolean sendEvent = parseCheckboxValue(request.getParameter("sendEventOption"));
    boolean saveLocally = parseCheckboxValue(request.getParameter("saveLocallyOption"));
    switch (action) {
    case GetConfigForIp:
        request.setAttribute("snmpConfigForIp",
                new SnmpInfo(SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr(ipAddress))));
        request.setAttribute("firstIPAddress", ipAddress);
        break;
    case Save:
        boolean success = false;
        SnmpEventInfo eventInfo = snmpInfo.createEventInfo(firstIPAddress, lastIPAddress);
        if (saveLocally) {
            SnmpPeerFactory.getInstance().define(eventInfo);
            SnmpPeerFactory.getInstance().saveCurrent();
            success |= true;
        }
        if (sendEvent) {
            success |= sendEvent(eventInfo.createEvent("web ui"));
        }
        if (success)
            request.setAttribute("success", "success"); // the value doesn't matter, but it must be not null
        break;
    default:
    case Default:
        break;
    }
    request.setAttribute("snmpConfig", Files.toString(SnmpPeerFactory.getFile(), Charsets.UTF_8));

    RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/admin/snmpConfig.jsp");
    dispatcher.forward(request, response);
}

From source file:org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.java

static void addPublicKeyToOptionsIfPresentInNodeElement(NodeElement nodeElement, TemplateOptions options)
        throws IOException {
    if (nodeElement.getPrivatekeyfile() != null)
        options.authorizePublicKey(Files.toString(nodeElement.getPublickeyfile(), Charsets.UTF_8));
}

From source file:sample.youtube.UploadThread.java

private static ResumableGDataFileUploader prepareVideoUploader(YouTubeService service, String videoFilePath,
        File[] descriptionFiles, String inputDescription, String title, List<Output> videoOutputList,
        String url, String youtubeUsername) throws IOException, ServiceException, InterruptedException {

    System.out.println("\nProcessing... Email:" + youtubeUsername + " Video:" + videoFilePath);

    File videoFile = new File(videoFilePath);
    if (!videoFile.exists()) {
        System.out.println("Sorry, that video doesn't exist.");
        return null;
    }/*  w  w w  .  j  a va 2s  .  c  o m*/
    String randomDescription = "";
    if (descriptionFiles.length > 0) {
        final Random random = new Random();
        int randomInt = randomInteger(0, descriptionFiles.length - 1, random);

        File descriptionFile = descriptionFiles[randomInt];
        randomDescription = Files.toString(descriptionFile, Charsets.UTF_8);

        if (randomDescription != null) {
            randomDescription = randomDescription.replaceAll("\\[TITLE\\]", title);
            randomDescription = randomDescription.replaceAll("http://url", url);
        }
    }

    MediaFileSource ms = new MediaFileSource(videoFile, VIDEO_FILE_FORMAT);
    String videoTitle = title;
    VideoEntry newEntry = new VideoEntry();
    YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
    mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Tech"));
    mg.setTitle(new MediaTitle());
    mg.getTitle().setPlainTextContent(videoTitle);
    mg.setKeywords(new MediaKeywords());
    mg.getKeywords().addKeyword("gdata-test");
    mg.setDescription(new MediaDescription());
    mg.getDescription().setPlainTextContent(inputDescription + "\n" + randomDescription);

    ResumableGDataFileUploader uploader = new ResumableGDataFileUploader.Builder(service,
            new URL(RESUMABLE_UPLOAD_URL), ms, newEntry).title(videoTitle).chunkSize(DEFAULT_CHUNK_SIZE)
                    .build();
    return uploader;
}

From source file:com.facebook.buck.testutil.integration.ProjectWorkspace.java

/**
 * This will copy the template directory, renaming files named {@code BUCK.test} to {@code BUCK}
 * in the process. Files whose names end in {@code .expected} will not be copied.
 *///from   www  . j a v  a  2 s  .  c  o  m
public void setUp() throws IOException {
    DefaultKnownBuildRuleTypes.resetInstance();

    MoreFiles.copyRecursively(templatePath, destPath, BUILD_FILE_RENAME);

    if (Platform.detect() == Platform.WINDOWS) {
        // Hack for symlinks on Windows.
        SimpleFileVisitor<Path> copyDirVisitor = new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                // On Windows, symbolic links from git repository are checked out as normal files
                // containing a one-line path. In order to distinguish them, paths are read and pointed
                // files are trued to locate. Once the pointed file is found, it will be copied to target.
                // On NTFS length of path must be greater than 0 and less than 4096.
                if (attrs.size() > 0 && attrs.size() <= 4096) {
                    File file = path.toFile();
                    String linkTo = Files.toString(file, Charsets.UTF_8);
                    File linkToFile = new File(templatePath.toFile(), linkTo);
                    if (linkToFile.isFile()) {
                        java.nio.file.Files.copy(linkToFile.toPath(), path,
                                StandardCopyOption.REPLACE_EXISTING);
                    } else if (linkToFile.isDirectory()) {
                        if (!file.delete()) {
                            throw new IOException();
                        }
                        MoreFiles.copyRecursively(linkToFile.toPath(), path);
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        };
        java.nio.file.Files.walkFileTree(destPath, copyDirVisitor);
    }
    isSetUp = true;
}

From source file:org.ftccommunity.ftcxtensible.networking.http.RobotHttpServerHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        String page;//from ww w. j  a  v  a 2 s. c  om

        if (req.getMethod() == HttpMethod.POST) {
            LinkedList<InterfaceHttpData> postData = new LinkedList<>();
            HttpPostRequestDecoder postRequestDecoder = new HttpPostRequestDecoder(
                    new DefaultHttpDataFactory(false), req);
            postRequestDecoder.getBodyHttpDatas();
            for (InterfaceHttpData data : postRequestDecoder.getBodyHttpDatas()) {
                if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    postData.add(data);
                }
            }
            context.addPostData(postData);
        }

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }

        HttpResponseStatus responseStatus = OK;
        String uri = (req.getUri().equals("/") ? context.getServerSettings().getIndex() : req.getUri());
        if (uri.equals(context.getServerSettings().getHardwareMapJsonPage())) {
            GsonBuilder gsonBuilder = new GsonBuilder().enableComplexMapKeySerialization();
            Gson gson = gsonBuilder.create();
            HardwareMap hardwareMap = context.hardwareMap();
            page = gson.toJson(ImmutableSet.copyOf(hardwareMap.dcMotor));
        } else if (uri.equals(context.getServerSettings().getLogPage())) {
            page = context.status().getLog();
        } else {
            if (cache.containsKey(uri)) {
                page = cache.get(uri);
                responseStatus = NOT_MODIFIED;
            } else {
                try {
                    page = Files.toString(new File(serverSettings.getWebDirectory() + uri), Charsets.UTF_8);
                } catch (FileNotFoundException e) {
                    Log.e("NET_OP_MODE::", "Cannot find main: + " + serverSettings.getWebDirectory() + uri);
                    page = "File Not Found!";
                    responseStatus = NOT_FOUND;
                } catch (IOException e) {
                    page = "An Error Occurred!\n" + e.toString();
                    responseStatus = NOT_FOUND;
                    Log.e("NET_OP_MODE::", e.toString(), e);
                }
                cache.put(uri, page);
            }
        }

        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus,
                Unpooled.wrappedBuffer(page.getBytes(Charsets.UTF_8)));

        String extension = MimeTypeMap.getFileExtensionFromUrl(uri);
        String MIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

        response.headers().set(CONTENT_TYPE, (MIME != null ? MIME : MimeForExtension(extension))
                + (MIME != null && MIME.equals("application/octet-stream") ? "" : "; charset=utf-8"));
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}

From source file:org.ctoolkit.maven.plugins.optimizer.CssOptimizer.java

/**
 * Encode images in css file and return encoded css content
 *
 * @param cssCustomFile css custom file/*from   w  w w.  ja v a2 s  .c o m*/
 * @return css content with encoded images to base64
 * @throws IOException if IOException occurs
 */
private static String encodeImages(File cssCustomFile) throws IOException {
    String cssCustomString = Files.toString(cssCustomFile, Charsets.UTF_8);

    // match all images paths
    Matcher m = Pattern.compile("url\\(.*\\)").matcher(cssCustomString);

    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String imgSrc = m.group(0).replace("url(\"", "").replace("\")", "");

        if (imgSrc.startsWith(DATA_IMAGE_PNG_BASE64)) // image is already encoded
        {
            continue;
        }

        File file = cssCustomFile.getParentFile();

        for (final String next : Arrays.asList(imgSrc.split("/"))) {
            if ("..".equals(next)) {
                file = file.getParentFile();
            } else {
                File[] files = file.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        return name.equals(next);
                    }
                });

                if (files.length == 0) {
                    continue;
                }

                file = files[0];
            }

            if (file.isFile()) {
                break;
            }

        }

        if (file.isFile()) {
            String extension = file.getName().substring(file.getName().indexOf(".") + 1);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(ImageIO.read(file), extension, baos);

            String encodedImage = DatatypeConverter.printBase64Binary(baos.toByteArray());

            m.appendReplacement(sb, MessageFormat.format(URL_DATA_IMAGE_BASE64, extension, encodedImage));
        }
    }
    m.appendTail(sb);

    return sb.toString();
}

From source file:com.google.devtools.build.lib.util.ResourceUsage.java

/**
 * Returns the current total idle time of the processors since system boot.
 * Reads /proc/stat to obtain this information.
 *///from  ww  w.  ja  va 2s  .  co  m
private static long getCurrentTotalIdleTimeInJiffies() {
    try {
        File file = new File("/proc/stat");
        String content = Files.toString(file, US_ASCII);
        String value = Iterables.get(WHITESPACE_SPLITTER.split(content), 5);
        return Long.parseLong(value);
    } catch (NumberFormatException | IOException e) {
        return 0L;
    }
}

From source file:ext.deployit.community.ci.dictionary.ScriptRunner.java

protected static String loadScriptFs(String path) throws IOException {
    File f = new File(SCRIPT_PATH, path);
    if (!f.exists()) {
        logger.debug("directory script not found at {}", f.getAbsolutePath());
        return null;
    }/*w  w  w . ja  v  a2s  . co m*/
    String script = Files.toString(f, Charset.defaultCharset());
    return script;
}

From source file:org.apache.s4.fixtures.CommTestUtils.java

public static String readFileAsString(File f) throws IOException {
    return Files.toString(f, Charset.defaultCharset());

}

From source file:com.axemblr.provisionr.commands.CreatePoolCommand.java

private AdminAccess collectCurrentUserCredentialsForAdminAccess() {
    String userHome = System.getProperty("user.home");

    try {/*from w  ww .ja  v  a  2  s. c o  m*/
        String publicKey = Files.toString(new File(userHome, ".ssh/id_rsa.pub"), Charsets.UTF_8);
        String privateKey = Files.toString(new File(userHome, ".ssh/id_rsa"), Charsets.UTF_8);

        return AdminAccess.builder().username(System.getProperty("user.name")).publicKey(publicKey)
                .privateKey(privateKey).createAdminAccess();
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}