Example usage for java.nio.file Files readAllBytes

List of usage examples for java.nio.file Files readAllBytes

Introduction

In this page you can find the example usage for java.nio.file Files readAllBytes.

Prototype

public static byte[] readAllBytes(Path path) throws IOException 

Source Link

Document

Reads all the bytes from a file.

Usage

From source file:dpfmanager.shell.interfaces.gui.component.show.ShowController.java

public String getContent(String path) {
    String content = "";
    try {//  w w w . j  a  va  2s .c om
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        content = new String(encoded);
        if (path.endsWith("json")) {
            content = new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(content));
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return content;
}

From source file:com.ontotext.s4.service.S4ServiceClient.java

/**
 * Annotates the contents of a single file with the specified MIME type. Returns an object which allows
  * for convenient access to the annotations in the annotated document.
 * //from  www  . j a v a2  s  . co m
 * @param documentContent the file whose contents will be annotated
 * @param documentEncoding the encoding of the document file
 * @param documentMimeType the MIME type of the document to annotated content as well as the annotations produced
 * @throws IOException
 * @throws S4ServiceClientException
 */
public AnnotatedDocument annotateFileContents(File documentContent, Charset documentEncoding,
        SupportedMimeType documentMimeType) throws IOException, S4ServiceClientException {

    Path documentPath = documentContent.toPath();
    if (!Files.isReadable(documentPath)) {
        throw new IOException("File " + documentPath.toString() + " is not readable.");
    }
    ByteBuffer buff;
    buff = ByteBuffer.wrap(Files.readAllBytes(documentPath));
    String content = documentEncoding.decode(buff).toString();

    return annotateDocument(content, documentMimeType);
}

From source file:org.primeframework.mvc.test.RequestBuilder.java

/**
 * Sets the body content.//from ww  w  .j a  v  a  2  s . c  om
 *
 * @param body   The body as a {@link Path} to the JSON file.
 * @param values key value pairs of replacement values for use in the JSON file.
 * @return
 * @throws IOException
 */
public RequestBuilder withBodyFile(Path body, Object... values) throws IOException {
    if (values.length == 0) {
        return withBody(Files.readAllBytes(body));
    }
    return withBody(BodyTools.processTemplate(body, values));
}

From source file:com.twosigma.beakerx.mimetype.MIMEContainer.java

protected static byte[] getBytes(Object data) throws IOException {
    byte[] bytes;
    if (isValidURL(data.toString())) {
        bytes = ByteStreams.toByteArray((new URL(data.toString()).openStream()));
    } else if (exists(data.toString())) {
        Path path = Paths.get(data.toString());
        bytes = Files.readAllBytes(path);
    } else {//  w  w w. jav a  2s .c  om
        throw new FileNotFoundException(data.toString() + " doesn't exist. ");
    }
    return bytes;
}

From source file:de.alpharogroup.crypto.key.reader.PublicKeyReader.java

/**
 * Read the public key from a pem file as base64 encoded {@link String} value.
 *
 * @param file/*from w w  w .  j a  va 2 s  . co  m*/
 *            the file in pem format that contains the public key.
 * @return the base64 encoded {@link String} value.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static String readPemFileAsBase64(final File file) throws IOException {
    final byte[] keyBytes = Files.readAllBytes(file.toPath());
    final String publicKeyAsBase64String = new String(keyBytes).replace(BEGIN_PUBLIC_KEY_PREFIX, "")
            .replace(END_PUBLIC_KEY_SUFFIX, "");
    return publicKeyAsBase64String;
}

From source file:net.rptools.maptool.client.AppUtil.java

public static String readClientId() {
    Path clientFile = Paths.get(getAppHome().getAbsolutePath(), CLIENT_ID_FILE);
    String clientId = "unknown";
    if (!clientFile.toFile().exists()) {
        clientId = UUID.randomUUID().toString();
        try {/*from w  ww  .  j  a  v  a  2 s .  co  m*/
            Files.write(clientFile, clientId.getBytes());
        } catch (IOException e) {
            log.info("msg.error.unableToCreateClientIdFile", e);
        }
    } else {
        try {
            clientId = new String(Files.readAllBytes(clientFile));
        } catch (IOException e) {
            log.info("msg.error.unableToReadClientIdFile", e);
        }
    }
    return clientId;

}

From source file:com.netscape.cmstools.CMCResponse.java

public static void main(String args[]) throws Exception {

    Option option = new Option("d", true, "NSS database location");
    option.setArgName("path");
    options.addOption(option);/*from  w ww .  ja  v a  2s .c o  m*/

    option = new Option("i", true, "Input file containing CMC response in binary format");
    option.setArgName("path");
    options.addOption(option);

    option = new Option("o", true,
            "Output file to store certificate chain in PKCS #7 PEM format; also prints out cert base 64 encoding individually");
    option.setArgName("path");
    options.addOption(option);

    options.addOption("v", "verbose", false,
            "Run in verbose mode. Base64 encoding of certs in response will be printed individually");

    options.addOption(null, "help", false, "Show help message.");

    CommandLine cmd = parser.parse(options, args, true);

    @SuppressWarnings("unused")
    String database = cmd.getOptionValue("d");

    String input = cmd.getOptionValue("i");
    String output = cmd.getOptionValue("o");
    boolean printCerts = cmd.hasOption("v");

    if (cmd.hasOption("help")) {
        printUsage();
        System.exit(1);
    }

    if (input == null) {
        System.err.println("ERROR: Missing input CMC response");
        System.err.println("Try 'CMCResponse --help' for more information.");
        System.exit(1);
    }

    // load CMC response
    byte[] data = Files.readAllBytes(Paths.get(input));

    // display CMC response
    CMCResponse response = new CMCResponse(data);
    response.printContent(printCerts);

    // terminate if any of the statuses is not a SUCCESS
    Collection<CMCStatusInfoV2> statusInfos = response.getStatusInfos();
    if (statusInfos != null) { // full response
        for (CMCStatusInfoV2 statusInfo : statusInfos) {

            int status = statusInfo.getStatus();
            if (status == CMCStatusInfoV2.SUCCESS) {
                continue;
            }

            SEQUENCE bodyList = statusInfo.getBodyList();

            Collection<INTEGER> list = new ArrayList<>();
            for (int i = 0; i < bodyList.size(); i++) {
                INTEGER n = (INTEGER) bodyList.elementAt(i);
                list.add(n);
            }

            System.err.println("ERROR: CMC status for " + list + ": " + CMCStatusInfoV2.STATUS[status]);
            System.exit(1);
        }
    }

    // export PKCS #7 if requested
    if (output != null) {
        PKCS7 pkcs7 = new PKCS7(data);

        try (FileWriter fw = new FileWriter(output)) {
            fw.write(pkcs7.toPEMString());
        }
        System.out.println("\nPKCS#7 now stored in file: " + output);
    }
}

From source file:com.netflix.nicobar.cassandra.CassandraArchiveRepository.java

/**
 * insert a Jar into the script archive//from   w  ww. ja va  2 s. co m
 */
@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path jarFilePath;
    try {
        jarFilePath = Paths.get(jarScriptArchive.getRootUrl().toURI());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    int shardNum = calculateShardNum(moduleId);
    byte[] jarBytes = Files.readAllBytes(jarFilePath);
    byte[] hash = calculateHash(jarBytes);
    Map<String, Object> columns = new HashMap<String, Object>();
    columns.put(Columns.module_id.name(), moduleId.toString());
    columns.put(Columns.module_name.name(), moduleId.getName());
    columns.put(Columns.module_version.name(), moduleId.getVersion());
    columns.put(Columns.shard_num.name(), shardNum);
    columns.put(Columns.last_update.name(), jarScriptArchive.getCreateTime());
    columns.put(Columns.archive_content_hash.name(), hash);
    columns.put(Columns.archive_content.name(), jarBytes);

    String serialized = getConfig().getModuleSpecSerializer().serialize(moduleSpec);
    columns.put(Columns.module_spec.name(), serialized);
    try {
        cassandra.upsert(moduleId.toString(), columns);
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:com.ethercamp.harmony.service.ImportContractIndexTest.java

private static byte[] resourceToBytes(Resource resource) throws IOException {
    return Files.readAllBytes(Paths.get(resource.getURI()));
}

From source file:com.visionspace.jenkins.vstart.plugin.VSPluginPerformer.java

public boolean logToWorkspace(Long reportId, AbstractBuild build, BuildListener listener) {
    try {//  w  ww . java  2 s  .c o  m
        org.json.JSONObject report = vstObject.getReport(reportId);
        FilePath jPath = new FilePath(build.getWorkspace(), build.getWorkspace().toString() + "/VSTART_JSON");
        if (!jPath.exists()) {
            jPath.mkdirs();
        }

        String filePath = jPath + "/VSTART_JSON_" + build.getId() + ".json";

        JSONArray reports;
        try {
            String content = new String(Files.readAllBytes(Paths.get(filePath)));
            reports = new JSONArray(content);
        } catch (IOException e) {
            Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.WARNING, null, e);
            reports = new JSONArray();
        }

        reports.put(report);

        PrintWriter wj = new PrintWriter(filePath);
        wj.println(reports.toString());
        wj.close();

        //TODO: check test case result
        /*
        if (report.getString("status").equals("PASSED")) {          
        */
        return true;
        /* } */

    } catch (URISyntaxException ex) {
        Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Error on performing the workspace logging -> " + ex.getReason());
    } catch (IOException ex) {
        Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Error on performing the workspace logging -> " + ex.toString());
    } catch (InterruptedException ex) {
        Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Error on performing the workspace logging -> " + ex.getMessage());
    }
    return false;

}