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.mweagle.tereus.commands.evaluation.common.LambdaUtils.java

public String createFunction(final String logicalResourceName, final String lambdaSourceRoot,
        final String bucketName, final String s3KeyName)
        throws IOException, InterruptedException, NoSuchAlgorithmException {

    // Build it, zip it, and upload it.  Return:
    /*// w  ww.jav a  2 s  .c  om
    {
      "S3Bucket" : String,
      "S3Key" : String,
      "S3ObjectVersion" : "TODO - not yet implemented"
    }
    */
    this.logger.info("Looking for source {} relative to {}", lambdaSourceRoot, templateRoot);
    final String lambdaDir = this.templateRoot.resolve(lambdaSourceRoot).normalize().toAbsolutePath()
            .toString();
    final Path lambdaPath = Paths.get(lambdaDir);

    // Build command?
    final Optional<String> buildCommand = lambdaBuildCommand(lambdaDir);
    if (buildCommand.isPresent()) {
        this.logger.info("{} Lambda source: {}", buildCommand.get(), lambdaDir);
        try {
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec(buildCommand.get(), null, new File(lambdaDir));
            this.logger.info("Waiting for `{}` to complete", buildCommand.get());

            final int buildExitCode = pr.waitFor();
            if (0 != buildExitCode) {
                logger.error("Failed to `{}`: {}", buildCommand.get(), buildExitCode);
                throw new IOException(buildCommand.get() + " failed for: " + lambdaDir);
            }
        } catch (Exception ex) {
            final String processPath = System.getenv("PATH");
            this.logger.error("`{}` failed. Confirm that PATH contains the required executable.",
                    buildCommand.get());
            this.logger.error("$PATH: {}", processPath);
            throw ex;
        }
    } else {
        this.logger.debug("No additional Lambda build file detected");
    }

    Path lambdaSource = null;
    boolean cleanupLambdaSource = false;
    MessageDigest md = MessageDigest.getInstance("SHA-256");

    try {
        final BiPredicate<Path, java.nio.file.attribute.BasicFileAttributes> matcher = (path, fileAttrs) -> {
            final String fileExtension = com.google.common.io.Files.getFileExtension(path.toString());
            return (fileExtension.toLowerCase().compareTo("jar") == 0);
        };

        // Find/compress the Lambda source
        // If there is a JAR file in the source root, then use that for the upload
        List<Path> jarFiles = Files.find(lambdaPath, 1, matcher).collect(Collectors.toList());

        if (!jarFiles.isEmpty()) {
            Preconditions.checkArgument(jarFiles.size() == 1, "More than 1 JAR file detected in directory: {}",
                    lambdaDir);
            lambdaSource = jarFiles.get(0);
            md.update(Files.readAllBytes(lambdaSource));
        } else {
            lambdaSource = Files.createTempFile("lambda-", ".zip");
            this.logger.info("Zipping lambda source code: {}", lambdaSource.toString());
            final FileOutputStream os = new FileOutputStream(lambdaSource.toFile());
            final ZipOutputStream zipOS = new ZipOutputStream(os);
            createStableZip(zipOS, lambdaPath, lambdaPath, md);
            zipOS.close();
            this.logger.info("Compressed filesize: {} bytes", lambdaSource.toFile().length());
            cleanupLambdaSource = true;
        }

        // Upload it
        final String sourceHash = Hex.encodeHexString(md.digest());
        this.logger.info("Lambda source hash: {}", sourceHash);
        if (!s3KeyName.isEmpty()) {
            this.logger.warn(
                    "User supplied S3 keyname overrides content-addressable name. Automatic updates disabled.");
        }
        final String keyName = !s3KeyName.isEmpty() ? s3KeyName
                : String.format("%s-lambda-%s.%s", logicalResourceName, sourceHash,
                        com.google.common.io.Files.getFileExtension(lambdaSource.toString()));
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("S3Bucket", new JsonPrimitive(bucketName));
        jsonObject.add("S3Key", new JsonPrimitive(keyName));

        // Upload it to s3...
        final FileInputStream fis = new FileInputStream(lambdaSource.toFile());
        try (S3Resource resource = new S3Resource(bucketName, keyName, fis,
                Optional.of(lambdaSource.toFile().length()))) {
            this.logger.info("Source payload S3 URL: {}", resource.getS3Path());

            if (resource.exists()) {
                this.logger.info("Source {} already uploaded to S3", keyName);
            } else if (!this.dryRun) {
                Optional<String> result = resource.upload();
                this.logger.info("Uploaded Lambda source to: {}", result.get());
                resource.setReleased(true);
            } else {
                this.logger.info("Dry run requested (-n/--noop). Lambda payload upload bypassed.");
            }
        }
        final Gson serializer = new GsonBuilder().disableHtmlEscaping().enableComplexMapKeySerialization()
                .create();
        return serializer.toJson(jsonObject);
    } finally {
        if (cleanupLambdaSource) {
            this.logger.debug("Deleting temporary file: {}", lambdaSource.toString());
            Files.deleteIfExists(lambdaSource);
        }
    }
}

From source file:com.cami.web.controller.FileController.java

/**
 * *************************************************
 * URL: /appel-offre/file/get/{value} get(): get file as an attachment
 *
 * @param response : passed by the server
 * @param value : value from the URL/*  www. ja  va2s  .  com*/
 * @return void **************************************************
 */
@RequestMapping(value = "/get/{value}", method = RequestMethod.GET)
public void get(HttpServletResponse response, @PathVariable String value) {
    System.out.println(value);
    String savedFileName = getSavedFileName(SAVE_DIRECTORY, value);
    File file = new File(savedFileName);
    Path source = Paths.get(savedFileName);
    FileMeta getFile = new FileMeta();

    try {

        getFile.setFileName(file.getName());
        getFile.setFileSize(Files.size(source) / 1024 + " Kb");
        getFile.setFileType(Files.probeContentType(source));

        response.setContentType(getFile.getFileType());
        response.setHeader("Content-disposition", "attachment; filename=\"" + getFile.getFileName() + "\"");
        FileCopyUtils.copy(Files.readAllBytes(source), response.getOutputStream());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:au.edu.uws.eresearch.cr8it.TransformationHandler.java

private static String readFile(String path) {
    byte[] encoded = null;
    try {//from  ww  w  .  j a va  2s . c om
        encoded = Files.readAllBytes(Paths.get(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new String(encoded);
}

From source file:org.exist.xquery.RestBinariesTest.java

/**
 * {@see https://github.com/eXist-db/exist/issues/790#error-case-5}
 *
 * response:stream is used to return Base64 encoded binary.
 *///from   w  ww  . ja v a2  s. c  o  m
@Test
public void readAndStreamBinarySax() throws IOException, JAXBException {
    final byte[] data = randomData(1024 * 1024); // 1MB
    final Path tmpInFile = createTemporaryFile(data);

    final String query = "import module namespace file = \"http://exist-db.org/xquery/file\";\n"
            + "import module namespace response = \"http://exist-db.org/xquery/response\";\n"
            + "let $bin := file:read-binary('" + tmpInFile.toAbsolutePath().toString() + "')\n"
            + "return response:stream($bin, 'media-type=application/octet-stream')";

    final HttpResponse response = postXquery(query);

    final HttpEntity entity = response.getEntity();
    try (final FastByteArrayOutputStream baos = new FastByteArrayOutputStream()) {
        entity.writeTo(baos);

        assertArrayEquals(Files.readAllBytes(tmpInFile), Base64.decodeBase64(baos.toByteArray()));
    }
}

From source file:Global.java

private Action<Void> getConfigSecretAction() {
    return new Action.Simple() {
        @Override//from  w ww  . j a va 2  s  .  c  o  m
        public Result call(Http.Context ctx) throws Throwable {
            if (ctx.request().method().toLowerCase().equals("post")) {
                Form<User> newSiteAdminUserForm = form(User.class).bindFromRequest();

                if (hasError(newSiteAdminUserForm)) {
                    return badRequest(secret.render(SiteAdmin.SITEADMIN_DEFAULT_LOGINID, newSiteAdminUserForm));
                }

                User siteAdmin = SiteAdmin.updateDefaultSiteAdmin(newSiteAdminUserForm.get());
                replaceSiteSecretKey(createSeed(siteAdmin.password));
                isRestartRequired = true;
                return ok(restart.render());
            } else {
                return ok(secret.render(SiteAdmin.SITEADMIN_DEFAULT_LOGINID, new Form<>(User.class)));
            }
        }

        private String createSeed(String basicSeed) {
            String seed = basicSeed;
            try {
                seed += InetAddress.getLocalHost();
            } catch (Exception e) {
                play.Logger.warn("Failed to get localhost address", e);
            }
            return seed;
        }

        private void replaceSiteSecretKey(String seed) throws IOException {
            SecureRandom random = new SecureRandom(seed.getBytes());
            String secret = new BigInteger(130, random).toString(32);

            Path path = Paths.get("conf/application.conf");
            byte[] bytes = Files.readAllBytes(path);
            String config = new String(bytes);
            config = config.replace(DEFAULT_SECRET, secret);
            Files.write(path, config.getBytes());
        }

        private boolean hasError(Form<User> newUserForm) {
            if (StringUtils.isBlank(newUserForm.field("loginId").value())) {
                newUserForm.reject("loginId", "user.wrongloginId.alert");
            }

            if (!newUserForm.field("loginId").value().equals("admin")) {
                newUserForm.reject("loginId", "user.wrongloginId.alert");
            }

            if (StringUtils.isBlank(newUserForm.field("password").value())) {
                newUserForm.reject("password", "user.wrongPassword.alert");
            }

            if (!newUserForm.field("password").value().equals(newUserForm.field("retypedPassword").value())) {
                newUserForm.reject("retypedPassword", "user.confirmPassword.alert");
            }

            if (StringUtils.isBlank(newUserForm.field("email").value())) {
                newUserForm.reject("email", "validation.invalidEmail");
            }

            if (User.isEmailExist(newUserForm.field("email").value())) {
                newUserForm.reject("email", "user.email.duplicate");
            }

            return newUserForm.hasErrors();
        }
    };
}

From source file:com.github.anba.es6draft.v8.MiniJSUnitTest.java

private static boolean containsNativeSyntax(Path p) {
    try {// w  w w  .  ja v a2s. c om
        String content = new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
        return content.indexOf('%') != -1;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:com.adobe.aem.demomachine.Json2Csv.java

static String readFile(String path, Charset encoding) throws IOException {

    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, encoding);

}

From source file:com.anitech.resting.http.request.RequestDataMassager.java

private static StringEntity massageXMLData(Object inputData) throws RestingException {
    logger.debug("Inside massageXMLData!");
    StringEntity stringEntity = null;/*  w  w w  . ja v a2 s.c  om*/
    if (inputData instanceof Map<?, ?>) {
        try {
            String xmlString = RestingUtil.covertMapToXML((Map<?, ?>) inputData,
                    RestingConstants.REQUEST_XML_ROOT);
            logger.debug("Map>" + xmlString);
            stringEntity = new StringEntity(xmlString);
        } catch (UnsupportedEncodingException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof String) {
        logger.debug("String>" + inputData);
        try {
            stringEntity = new StringEntity((String) inputData);
        } catch (UnsupportedEncodingException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof StringBuffer || inputData instanceof StringBuilder) {
        logger.debug("String Buffer/Builder>" + inputData.toString());
        try {
            stringEntity = new StringEntity((String) inputData.toString());
        } catch (UnsupportedEncodingException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof File) {
        try {
            logger.debug("File>"
                    + new String(Files.readAllBytes(((File) inputData).toPath()), Charset.defaultCharset()));
            byte[] bytes = Files.readAllBytes(((File) inputData).toPath());
            stringEntity = new StringEntity(new String(bytes, Charset.defaultCharset()));
        } catch (IOException e) {
            throw new RestingException(e);
        }
    } else if (inputData instanceof InputStream) {
        InputStream inputStream = ((InputStream) inputData);
        try {
            byte[] buffer = new byte[inputStream.available()];
            int length = inputStream.read(buffer);
            logger.debug("InputStream>" + new String(buffer, 0, length, Charset.defaultCharset()));
            stringEntity = new StringEntity(new String(buffer, 0, length, Charset.defaultCharset()));
        } catch (IOException e) {
            throw new RestingException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else {
        logger.error("Unparseable data format found in inputs!");
        throw new RestingException("Unparseable data format found in inputs!");
    }
    return stringEntity;
}

From source file:net.troja.eve.producersaid.utils.EveCentral.java

private String getData(final String url) throws IOException {
    String result = null;/*  w  ww.j a  v a 2 s.  c  om*/
    if (fileName == null) {
        final CloseableHttpClient httpclient = HttpClients.createDefault();
        final HttpGet request = new HttpGet(url);
        try {
            request.setHeader("User-Agent", USER_AGENT);
            final HttpResponse response = httpclient.execute(request);
            final int status = response.getStatusLine().getStatusCode();
            if ((status >= HttpStatus.SC_OK) && (status < HttpStatus.SC_MULTIPLE_CHOICES)) {
                final HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(entity);
                }
            } else {
                throw new IOException(
                        "Download error: " + status + " " + response.getStatusLine().getReasonPhrase());
            }
        } finally {
            request.reset();
            httpclient.close();
        }
    } else {
        result = new String(Files.readAllBytes(Paths.get(fileName)), "UTF-8");
    }
    return result;
}

From source file:com.github.ukase.service.BulkRenderer.java

private byte[] getFileData(String id) {
    File pdf = getPdfFile(id);//  w ww .  j  ava2  s .  c  om
    Path pdfPath = pdf.getAbsoluteFile().toPath();
    try {
        return Files.readAllBytes(pdfPath);
    } catch (IOException e) {
        log.error("Cannot read pdf file data " + pdf.getAbsolutePath());
        return null;
    }
}