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:com.google.dart.tools.core.utilities.compiler.DartSourceMapping.java

private String getContentsOf(IPath filePath) throws IOException {
    IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(filePath);

    if (resource == null || resource.getRawLocation() == null) {
        throw new FileNotFoundException();
    }//from  w  ww . j a  v  a2 s. co  m

    return Files.toString(resource.getRawLocation().toFile(), Charset.defaultCharset());
}

From source file:org.apache.metron.maas.service.runner.Runner.java

private static Endpoint readEndpoint(File cwd) throws Exception {
    String content = "";
    File f = new File(cwd, "endpoint.dat");
    for (int i = 0; i < NUM_ATTEMPTS; i++) {
        if (f.exists()) {
            try {
                content = Files.toString(f, Charsets.US_ASCII);
            } catch (IOException ioe) {
            }//  w w w. j  a v a2s  . c o m
            if (content != null && content.length() > 0) {
                try {
                    Endpoint ep = ConfigUtil.INSTANCE.read(content.getBytes(), Endpoint.class);
                    return ep;
                } catch (Exception ex) {
                    LOG.error("Unable to parse " + content + ": " + ex.getMessage(), ex);
                }
            }
        }
        Thread.sleep(SLEEP_AMT);
    }
    throw new IllegalStateException("Unable to start process within the allotted time (10 minutes)");
}

From source file:com.android.tools.idea.templates.AndroidGradleTestCase.java

public static void updateGradleVersions(@NotNull File file) throws IOException {
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null) {
            for (File child : files) {
                updateGradleVersions(child);
            }//from  w ww.j  ava2 s . co  m
        }
    } else if (file.getPath().endsWith(DOT_GRADLE) && file.isFile()) {
        String contents = Files.toString(file, Charsets.UTF_8);

        boolean changed = false;
        Pattern pattern = Pattern.compile("classpath ['\"]com.android.tools.build:gradle:(.+)['\"]");
        Matcher matcher = pattern.matcher(contents);
        if (matcher.find()) {
            contents = contents.substring(0, matcher.start(1)) + SdkConstants.GRADLE_PLUGIN_RECOMMENDED_VERSION
                    + contents.substring(matcher.end(1));
            changed = true;
        }

        pattern = Pattern.compile("buildToolsVersion ['\"](.+)['\"]");
        matcher = pattern.matcher(contents);
        if (matcher.find()) {
            contents = contents.substring(0, matcher.start(1)) + GradleImport.CURRENT_BUILD_TOOLS_VERSION
                    + contents.substring(matcher.end(1));
            changed = true;
        }

        String repository = System.getProperty(TemplateWizard.MAVEN_URL_PROPERTY);
        if (repository != null) {
            pattern = Pattern.compile("mavenCentral\\(\\)");
            matcher = pattern.matcher(contents);
            if (matcher.find()) {
                contents = contents.substring(0, matcher.start()) + "maven { url '" + repository + "' };"
                        + contents.substring(matcher.start()); // note: start; not end; we're prepending, not replacing!
                changed = true;
            }
            pattern = Pattern.compile("jcenter\\(\\)");
            matcher = pattern.matcher(contents);
            if (matcher.find()) {
                contents = contents.substring(0, matcher.start()) + "maven { url '" + repository + "' };"
                        + contents.substring(matcher.start()); // note: start; not end; we're prepending, not replacing!
                changed = true;
            }
        }

        if (changed) {
            Files.write(contents, file, Charsets.UTF_8);
        }
    }
}

From source file:com.example.cloud.iot.examples.DeviceRegistryExample.java

/** Create a device that is authenticated using RS256. */
public static void createDeviceWithRs256(String deviceId, String certificateFilePath, String projectId,
        String cloudRegion, String registryName) throws GeneralSecurityException, IOException {
    GoogleCredential credential = GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
    final CloudIot service = new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory,
            init).setApplicationName(APP_NAME).build();

    final String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
            + registryName;/*from w  w w  . ja va  2s  .c o m*/

    PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
    String key = Files.toString(new File(certificateFilePath), Charsets.UTF_8);
    publicKeyCredential.setKey(key);
    publicKeyCredential.setFormat("RSA_X509_PEM");

    DeviceCredential devCredential = new DeviceCredential();
    devCredential.setPublicKey(publicKeyCredential);

    System.out.println("Creating device with id: " + deviceId);
    Device device = new Device();
    device.setId(deviceId);
    device.setCredentials(Arrays.asList(devCredential));
    Device createdDevice = service.projects().locations().registries().devices().create(registryPath, device)
            .execute();

    System.out.println("Created device: " + createdDevice.toPrettyString());
}

From source file:nl.mpcjanssen.simpletask.AddTask.java

@Override
public void onCreate(Bundle savedInstanceState) {
    Log.v(TAG, "onCreate()");

    m_app = (TodoApplication) getApplication();
    m_app.setActionBarStyle(getWindow());
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    super.onCreate(savedInstanceState);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Constants.BROADCAST_UPDATE_UI);
    intentFilter.addAction(Constants.BROADCAST_SYNC_START);
    intentFilter.addAction(Constants.BROADCAST_SYNC_DONE);

    localBroadcastManager = m_app.getLocalBroadCastManager();

    m_broadcastReceiver = new BroadcastReceiver() {
        @Override/*  w  ww.ja v a2s  . co m*/
        public void onReceive(Context context, @NotNull Intent intent) {
            if (intent.getAction().equals(Constants.BROADCAST_SYNC_START)) {
                setProgressBarIndeterminateVisibility(true);
            } else if (intent.getAction().equals(Constants.BROADCAST_SYNC_DONE)) {
                setProgressBarIndeterminateVisibility(false);
            }
        }
    };
    localBroadcastManager.registerReceiver(m_broadcastReceiver, intentFilter);

    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    final Intent intent = getIntent();
    ActiveFilter mFilter = new ActiveFilter();
    mFilter.initFromIntent(intent);
    final String action = intent.getAction();
    // create shortcut and exit
    if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
        Log.d(TAG, "Setting up shortcut icon");
        setupShortcut();
        finish();
        return;
    } else if (Intent.ACTION_SEND.equals(action)) {
        Log.d(TAG, "Share");
        if (intent.hasExtra(Intent.EXTRA_STREAM)) {
            Uri uri = (Uri) intent.getExtras().get(Intent.EXTRA_STREAM);
            try {
                File sharedFile = new File(uri.getPath());
                share_text = Files.toString(sharedFile, Charsets.UTF_8);
            } catch (FileNotFoundException e) {
                share_text = "";
                e.printStackTrace();
            } catch (IOException e) {
                share_text = "";
                e.printStackTrace();
            }

        } else if (intent.hasExtra(Intent.EXTRA_TEXT)) {
            share_text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT).toString();
        } else {
            share_text = "";
        }
        if (!m_app.hasShareTaskShowsEdit()) {
            if (!share_text.equals("")) {
                addBackgroundTask(share_text);
            }
            finish();
            return;
        }
    } else if ("com.google.android.gm.action.AUTO_SEND".equals(action)) {
        // Called as note to self from google search/now
        noteToSelf(intent);
        finish();
        return;
    } else if (Constants.INTENT_BACKGROUND_TASK.equals(action)) {
        Log.v(TAG, "Adding background task");
        if (intent.hasExtra(Constants.EXTRA_BACKGROUND_TASK)) {
            addBackgroundTask(intent.getStringExtra(Constants.EXTRA_BACKGROUND_TASK));
        } else {
            Log.w(TAG, "Task was not in extras");
        }
        finish();
        return;
    }

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

    setContentView(R.layout.add_task);

    // text
    textInputField = (EditText) findViewById(R.id.taskText);
    m_app.setEditTextHint(textInputField, R.string.tasktexthint);

    if (share_text != null) {
        textInputField.setText(share_text);
    }

    Task iniTask = null;
    setTitle(R.string.addtask);

    m_backup = m_app.getTaskCache(this).getTasksToUpdate();
    if (m_backup != null && m_backup.size() > 0) {
        ArrayList<String> prefill = new ArrayList<String>();
        for (Task t : m_backup) {
            prefill.add(t.inFileFormat());
        }
        String sPrefill = Util.join(prefill, "\n");
        textInputField.setText(sPrefill);
        setTitle(R.string.updatetask);
    } else {
        if (textInputField.getText().length() == 0) {
            iniTask = new Task(1, "");
            iniTask.initWithFilter(mFilter);
        }

        if (iniTask != null && iniTask.getTags().size() == 1) {
            List<String> ps = iniTask.getTags();
            String project = ps.get(0);
            if (!project.equals("-")) {
                textInputField.append(" +" + project);
            }
        }

        if (iniTask != null && iniTask.getLists().size() == 1) {
            List<String> cs = iniTask.getLists();
            String context = cs.get(0);
            if (!context.equals("-")) {
                textInputField.append(" @" + context);
            }
        }
    }
    // Listen to enter events, use IME_ACTION_NEXT for soft keyboards
    // like Swype where ENTER keyCode is not generated.

    int inputFlags = InputType.TYPE_CLASS_TEXT;

    if (m_app.hasCapitalizeTasks()) {
        inputFlags |= InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
    }
    textInputField.setRawInputType(inputFlags);
    textInputField.setImeOptions(EditorInfo.IME_ACTION_NEXT);
    textInputField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, @Nullable KeyEvent keyEvent) {

            boolean hardwareEnterUp = keyEvent != null && keyEvent.getAction() == KeyEvent.ACTION_UP
                    && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER;
            boolean hardwareEnterDown = keyEvent != null && keyEvent.getAction() == KeyEvent.ACTION_DOWN
                    && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER;
            boolean imeActionNext = (actionId == EditorInfo.IME_ACTION_NEXT);

            if (imeActionNext || hardwareEnterUp) {
                // Move cursor to end of line
                int position = textInputField.getSelectionStart();
                String remainingText = textInputField.getText().toString().substring(position);
                int endOfLineDistance = remainingText.indexOf('\n');
                int endOfLine;
                if (endOfLineDistance == -1) {
                    endOfLine = textInputField.length();
                } else {
                    endOfLine = position + endOfLineDistance;
                }
                textInputField.setSelection(endOfLine);
                replaceTextAtSelection("\n", false);

                if (hasCloneTags()) {
                    String precedingText = textInputField.getText().toString().substring(0, endOfLine);
                    int lineStart = precedingText.lastIndexOf('\n');
                    String line;
                    if (lineStart != -1) {
                        line = precedingText.substring(lineStart, endOfLine);
                    } else {
                        line = precedingText;
                    }
                    Task t = new Task(0, line);
                    LinkedHashSet<String> tags = new LinkedHashSet<String>();
                    for (String ctx : t.getLists()) {
                        tags.add("@" + ctx);
                    }
                    for (String prj : t.getTags()) {
                        tags.add("+" + prj);
                    }
                    replaceTextAtSelection(Util.join(tags, " "), true);
                }
                endOfLine++;
                textInputField.setSelection(endOfLine);
            }
            return (imeActionNext || hardwareEnterDown || hardwareEnterUp);
        }
    });

    setCloneTags(m_app.isAddTagsCloneTags());
    setWordWrap(m_app.isWordWrap());

    findViewById(R.id.cb_wrap).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setWordWrap(hasWordWrap());
        }
    });

    int textIndex = 0;
    textInputField.setSelection(textIndex);

    // Set button callbacks
    findViewById(R.id.btnContext).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showContextMenu();
        }
    });
    findViewById(R.id.btnProject).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showTagMenu();
        }
    });
    findViewById(R.id.btnPrio).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showPrioMenu();
        }
    });

    findViewById(R.id.btnDue).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            insertDate(Task.DUE_DATE);
        }
    });
    findViewById(R.id.btnThreshold).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            insertDate(Task.THRESHOLD_DATE);
        }
    });

    if (m_backup != null && m_backup.size() > 0) {
        textInputField.setSelection(textInputField.getText().length());
    }
}

From source file:org.jclouds.examples.compute.basics.MainApp.java

private static String getCredentialFromJsonKeyFile(String filename) {
    try {//from  w  w  w .  j a  v  a  2  s  .  c  om
        String fileContents = Files.toString(new File(filename), UTF_8);
        Supplier<Credentials> credentialSupplier = new GoogleCredentialsFromJson(fileContents);
        String credential = credentialSupplier.get().credential;
        return credential;
    } catch (IOException e) {
        System.err.println("Exception reading private key from '%s': " + filename);
        e.printStackTrace();
        System.exit(1);
        return null;
    }
}

From source file:be.crydust.jscompinplace.CompileInplaceTask.java

@Override
public void execute() {
    Compiler.setLoggingLevel(Level.OFF);

    CompilerOptions options = createCompilerOptions();

    List<SourceFile> externs = findExternFiles();
    List<SourceFile> sourceFiles = findSourceFiles();

    log("Compiling " + sourceFiles.size() + " file(s) with " + externs.size() + " extern(s)");

    for (SourceFile sourceFile : sourceFiles) {

        Compiler compiler = createCompiler(options);

        log("Compiling " + sourceFile.getOriginalPath());

        Result result = compiler.compile(externs, Arrays.asList(sourceFile), options);

        if (result.success) {
            StringBuilder source = new StringBuilder(compiler.toSource());

            if (this.outputWrapperFile != null) {
                try {
                    this.outputWrapper = Files.toString(this.outputWrapperFile, UTF_8);
                } catch (Exception e) {
                    throw new BuildException("Invalid output_wrapper_file specified.");
                }/*from   w w w  .  j  a v a2 s.  c  o m*/
            }

            if (this.outputWrapper != null) {
                int pos = -1;
                pos = this.outputWrapper.indexOf(CommandLineRunner.OUTPUT_MARKER);
                if (pos > -1) {
                    String prefix = this.outputWrapper.substring(0, pos);
                    source.insert(0, prefix);

                    // end of outputWrapper
                    int suffixStart = pos + CommandLineRunner.OUTPUT_MARKER.length();
                    String suffix = this.outputWrapper.substring(suffixStart);
                    source.append(suffix);
                } else {
                    throw new BuildException("Invalid output_wrapper specified. " + "Missing '"
                            + CommandLineRunner.OUTPUT_MARKER + "'.");
                }
            }

            writeResult(new File(sourceFile.getOriginalPath()), source.toString());
        } else {
            throw new BuildException("Compilation failed.");
        }
    }
}

From source file:io.hops.hopsworks.api.certs.CertSigningService.java

@POST
@Path("/hopsworks")
@AllowCORS//from   ww w . j  a  v a  2 s. c om
@RolesAllowed({ "AGENT", "CLUSTER_AGENT" })
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response hopsworks(@Context HttpServletRequest req, @Context SecurityContext sc, String jsonString)
        throws AppException, IOException, InterruptedException {
    JSONObject json = new JSONObject(jsonString);
    String pubAgentCert = "no certificate";
    String caPubCert = "no certificate";
    String intermediateCaPubCert = "no certificate";
    Users user = userBean.findByEmail(sc.getUserPrincipal().getName());
    ClusterCert clusterCert;
    if (json.has("csr")) {
        String csr = json.getString("csr");
        clusterCert = checkCSR(user, csr);
        try {
            pubAgentCert = opensslOperations.signCertificateRequest(csr, true, false, false);
            caPubCert = Files.toString(new File(settings.getCertsDir() + "/certs/ca.cert.pem"), Charsets.UTF_8);
            intermediateCaPubCert = Files.toString(
                    new File(settings.getIntermediateCaDir() + "/certs/intermediate.cert.pem"), Charsets.UTF_8);
            clusterCert.setSerialNumber(getSerialNumFromCert(pubAgentCert));
            clusterCertFacade.update(clusterCert);
        } catch (IOException | InterruptedException ex) {
            logger.log(Level.SEVERE, null, ex);
            throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), ex.toString());
        }
    }

    CsrDTO dto = new CsrDTO(caPubCert, intermediateCaPubCert, pubAgentCert, settings.getHadoopVersionedDir());
    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(dto).build();
}

From source file:org.aegis.app.sample.ec2.computer1.java

private static String getPrivateKeyFromFile(String filename) {
    try {//  w ww  .  j a  v  a 2  s. co  m
        return Files.toString(new File(filename), Charsets.UTF_8);
    } catch (IOException e) {
        System.err.println("Exception reading private key from '%s': " + filename);
        e.printStackTrace();
        System.exit(1);
        return null;
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.SchedulerServiceImpl.java

/**
 * Submits an XML file to the job-planner REST using an HTTP client.
 *
 * @param sessionId the id of the client which submits the job
 * @param file      the XML file that is submitted
 * @return an error message upon failure, "id=<jobId>" upon success
 * @throws RestServerException/*w  w  w  .j a va  2  s.c o m*/
 * @throws ServiceException
 */
public String planXMLFile(String sessionId, File file) throws RestServerException, ServiceException {
    HttpPost method = new HttpPost(SchedulerConfig.get().getJobplannerUrl());
    method.addHeader("sessionId", sessionId);
    method.addHeader("Content-type", ContentType.APPLICATION_XML.toString());

    try {
        StringEntity entity = new StringEntity(Files.toString(file, Charset.forName("ISO-8859-1")),
                ContentType.APPLICATION_XML);
        method.setEntity(entity);

        HttpResponse execute = httpClient.execute(method);
        InputStream is = execute.getEntity().getContent();
        String ret = convertToString(is);
        if (execute.getStatusLine().getStatusCode() == Status.CREATED.getStatusCode()) {
            return ret;
        } else {
            throw new RestServerException(execute.getStatusLine().getStatusCode(), ret);
        }
    } catch (IOException e) {
        throw new ServiceException("Failed to read response: " + e.getMessage());
    } finally {
        method.releaseConnection();
        if (file != null) {
            file.delete();
        }
    }
}