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:com.twosigma.beakerx.chart.serializer.RastersSerializer.java

@Override
public void serialize(Rasters rasters, JsonGenerator jgen, SerializerProvider sp) throws IOException {
    validate(rasters);/*from   ww  w  . ja  va 2 s  .  co  m*/

    jgen.writeStartObject();

    jgen.writeObjectField(TYPE, SerializerUtil.getTypeName(rasters));
    jgen.writeObjectField("x", rasters.getX());
    jgen.writeObjectField("y", rasters.getY());
    jgen.writeObjectField("opacity", rasters.getOpacity());
    jgen.writeObjectField("visible", rasters.getVisible());
    jgen.writeObjectField("yAxis", rasters.getYAxis());
    jgen.writeObjectField("position", rasters.getPosition());
    jgen.writeObjectField("width", rasters.getWidth());
    jgen.writeObjectField("height", rasters.getHeight());

    // datastring will override file path/url
    if (rasters.getDataString() != null) {
        jgen.writeObjectField("value", Bytes2Base64(rasters.getDataString(), null));
    } else if (!rasters.getFilePath().isEmpty()) {
        String path = rasters.getFilePath();
        File file = new File(path);

        if (!file.exists()) {
            throw new FileNotFoundException("Cannot find file " + path);
        }

        byte[] picture = Files.readAllBytes(new File(path).toPath());
        String extension = "";
        int i = path.lastIndexOf('.');
        if (i > 0) {
            extension = path.substring(i + 1);
        }

        jgen.writeObjectField("value", Bytes2Base64(picture, extension));
    } else if (!rasters.getFileUrl().isEmpty()) {
        jgen.writeObjectField("value", rasters.getFileUrl());
    }

    jgen.writeEndObject();
}

From source file:dlauncher.authorization.DefaultCredentialsManager.java

public DefaultCredentialsManager(File accountsFile, Charset encoding) throws IOException {
    this.accountsFile = accountsFile;
    this.encoding = encoding;
    if (accountsFile.exists()) {
        byte[] encoded = Files.readAllBytes(accountsFile.toPath());
        JSONObject obj = new JSONObject(new String(encoded, encoding));
        this.clientToken = obj.optString("clientToken", UUID.randomUUID().toString());
        JSONArray arr = obj.optJSONArray("authenticationDatabase");
        if (arr != null) {
            for (int i = 0; i < arr.length(); i++) {
                JSONObject obj1 = arr.getJSONObject(i);
                this.authDatabase.add(
                        new AuthorizationInfoImpl(obj1.getString("accessToken"), false, obj1.getString("uuid"),
                                obj1.getString("displayName"), obj1.optString("twitch_acces_token", null),
                                obj1.getString("userid"), obj1.getString("username")));
            }//from  w w  w .j  a  v  a  2s. c  o  m
        }
    } else {
        this.clientToken = UUID.randomUUID().toString();
    }
}

From source file:com.chenshu.compress.CompressTest.java

@Setup
public void prepare() {
    try {/*from  w  w  w  .j a  va  2  s . com*/
        src = Files.readAllBytes(Paths.get("./THIRDPARTYLICENSEREADME.txt"));
        data_jdk_gz = getJdkGzipCompressContent();
        data_commons_gz = getCommonsGzipCompressContent();
        data_commons_bz2 = getCommonsBZip2CompressContent();
        data_commons_deflate = getCommonsDeflateCompressContent();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.github.ffremont.microservices.springboot.node.tasks.InstallTask.java

/**
 * Installation/* w  w  w.  j  av  a2 s.  co m*/
 *
 * @param task
 * @throws
 * com.github.ffremont.microservices.springboot.node.exceptions.InvalidInstallationException
 * @throws
 * com.github.ffremont.microservices.springboot.node.exceptions.FailCreateMsException
 */
@Override
public void run(MicroServiceTask task)
        throws InvalidInstallationException, FailCreateMsException, TaskException {
    LOG.info("Installation du micro service {}...", task.getMs().getName());
    Path msVersionFolder = helper.targetDirOf(task.getMs());
    LOG.debug("Rpertoire d'installation {}", msVersionFolder);

    try {
        if (Files.notExists(msVersionFolder)) {
            Files.createDirectories(msVersionFolder);
            LOG.debug("Rpertoire cr");
        }

        // vrification du CHECKSUM
        Path checksumPath = Paths.get(msVersionFolder.toString(), CHECKSUM_FILE_NAME + ".txt");

        if (Files.exists(checksumPath)) {
            LOG.debug("Checksum rcupr {}", checksumPath);
            if (!task.getMs().getSha1().equals(new String(Files.readAllBytes(checksumPath)))) {
                throw new InvalidInstallationException("Le checksum n'est pas valide : " + this.nodeBase);
            }
        } else {
            installJarTask.run(task);
        }

        installPropTask.run(task);
    } catch (IOException ex) {
        LOG.warn("Anomalie non prvue lors de l'installation", ex);
        throw new FailCreateMsException("Installation impossible", ex);
    }

    LOG.info("Micro service {} install", task.getMs().getName());
}

From source file:com.mweagle.tereus.commands.evaluation.common.FileUtils.java

public String fileContents(String pathArg) throws Exception {
    try {//  ww  w. java  2  s. c  om
        Path resolved = this.templateRoot.resolve(pathArg).normalize();
        return new String(Files.readAllBytes(resolved), "UTF-8");
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.msf4j.perftest.echo.springboot.EchoService.java

@RequestMapping("/EchoService/fileecho")
@ResponseBody//from   w w  w  . j a  v  a 2  s. c  o m
public String fileWrite(@RequestBody String body) throws InterruptedException, IOException {
    String returnStr = "";
    java.nio.file.Path tempfile = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
    Files.write(tempfile, body.getBytes(Charset.defaultCharset()), StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);
    returnStr = new String(Files.readAllBytes(tempfile), Charset.defaultCharset());
    Files.delete(tempfile);
    return returnStr;
}

From source file:org.apache.asterix.experiment.action.derived.RunAQLFileAction.java

@Override
public void doPerform() throws Exception {
    String aql = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(aqlFilePath))).toString();
    String uri = MessageFormat.format(REST_URI_TEMPLATE, restHost, String.valueOf(restPort));
    HttpPost post = new HttpPost(uri);
    post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    post.setEntity(new StringEntity(aql, StandardCharsets.UTF_8));
    HttpEntity entity = httpClient.execute(post).getEntity();
    if (entity != null && entity.isStreaming()) {
        printStream(entity.getContent());
    }/*from   ww  w .  j  ava2  s. c o m*/
    if (aql.contains("compact")) {
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("Compaction has been completed");
        }
    }
}

From source file:com.ibm.util.merge.persistence.FilesystemPersistence.java

/**********************************************************************************
 * Cache JSON templates found in the template folder.
 * Note: The template folder is initialized from Merge.java from the web.xml value  for
 * merge-templates-folder, if it is not initilized the default value is /tmp/templates
 *
 * @param folder that contains template files
 *//*from  ww  w .  j a  v a2 s . com*/
@Override
public List<Template> loadAllTemplates() {
    List<Template> templates = new ArrayList<>();
    int count = 0;
    if (templateFolder.listFiles() == null) {
        throw new RuntimeException("Template Folder data was not found! " + templateFolder);
    }
    for (File file : templateFolder.listFiles()) {
        log.debug("Inspect potential template file: " + file);
        if (!file.isDirectory() && !file.getName().startsWith(".")) {
            try {
                String json = new String(Files.readAllBytes(file.toPath()));
                Template template = jsonProxy.fromJSON(json, Template.class);
                templates.add(template);
                log.info("Loaded template " + template.getFullName() + " : " + file.getAbsolutePath());
                count++;
            } catch (JsonSyntaxException e) {
                log.warn("Malformed JSON Template:" + file.getName(), e);
            } catch (FileNotFoundException e) {
                log.info("Moving on after file read error on " + file.getName(), e);
            } catch (IOException e) {
                log.warn("IOException Reading:" + file.getName(), e);
            }
        }

    }
    log.info("Loaded " + Integer.toString(count) + " templates from " + templateFolder);
    return templates;
}

From source file:net.arccotangent.pacchat.filesystem.KeyManager.java

public static KeyPair loadRSAKeys() {
    try {//  w  ww  . ja v a 2 s .  com
        km_log.i("Loading RSA key pair from disk.");
        byte[] privEncoded = Files.readAllBytes(privkeyFile.toPath());
        byte[] pubEncoded = Files.readAllBytes(pubkeyFile.toPath());

        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.decodeBase64(pubEncoded));
        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privEncoded));

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PublicKey pubkey = keyFactory.generatePublic(pubSpec);
        PrivateKey privkey = keyFactory.generatePrivate(privSpec);

        return new KeyPair(pubkey, privkey);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
        km_log.e("Error while loading keypair!");
        e.printStackTrace();
    }
    return null;
}

From source file:ch.sportchef.business.event.control.EventImageService.java

public byte[] getImage(@NotNull final Long eventId) throws IOException {
    final File file = new File(IMAGE_UPLOAD_PATH, String.format("%d%s", eventId, FILE_EXTENSION)); //NON-NLS
    if (file.exists()) {
        return Files.readAllBytes(file.toPath());
    }//from ww  w  .  ja v a2  s  . c o  m
    throw new NotFoundException(String.format("event with id '%d' has no image", eventId)); //NON-NLS
}