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.example.video.Detect.java

/**
 * Performs label analysis on the video at the provided file path.
 *
 * @param filePath the path to the video file to analyze.
 *//*from  www .  j a  v a  2  s  .c  o m*/
public static void analyzeLabelsFile(String filePath)
        throws ExecutionException, IOException, InterruptedException {
    VideoIntelligenceServiceSettings settings = VideoIntelligenceServiceSettings.defaultBuilder().build();
    VideoIntelligenceServiceClient client = VideoIntelligenceServiceClient.create(settings);

    Path path = Paths.get(filePath);
    byte[] data = Files.readAllBytes(path);
    byte[] encodedBytes = Base64.encodeBase64(data);

    AnnotateVideoRequest request = AnnotateVideoRequest.newBuilder()
            .setInputContent(new String(encodedBytes, "UTF-8")).addFeatures(Feature.LABEL_DETECTION).build();

    OperationFuture<AnnotateVideoResponse> operation = client.annotateVideoAsync(request);

    System.out.println("Waiting for operation to complete...");
    for (VideoAnnotationResults result : operation.get().getAnnotationResultsList()) {
        if (result.getLabelAnnotationsCount() > 0) {
            System.out.println("Labels:");
            for (LabelAnnotation annotation : result.getLabelAnnotationsList()) {
                System.out.println("\tDescription: " + annotation.getDescription());
                for (LabelLocation loc : annotation.getLocationsList()) {
                    if (loc.getSegment().getStartTimeOffset() == -1
                            && loc.getSegment().getEndTimeOffset() == -1) {
                        System.out.println("\tLocation: Entire video");
                    } else {
                        System.out.printf("\tLocation: %fs - %fs\n",
                                loc.getSegment().getStartTimeOffset() / 1000000.0,
                                loc.getSegment().getEndTimeOffset() / 1000000.0);
                    }
                }
                System.out.println();
            }
        } else {
            System.out.println("No labels detected in " + filePath);
        }
    }
}

From source file:ee.ria.xroad.confproxy.commandline.ConfProxyUtilViewConf.java

/**
 * Generates a string that describes the certificate information for the
 * provided key id.//w  w  w  .j  a  va  2s .co  m
 * @param keyId the key id
 * @param conf configuration proxy properties instance
 * @return string describing certificate information
 */
private String certInfo(final String keyId, final ConfProxyProperties conf) {
    if (keyId == null) {
        return "";
    }
    Path certPath = conf.getCertPath(keyId).toAbsolutePath();
    byte[] certBytes;
    try {
        certBytes = Files.readAllBytes(certPath);
    } catch (IOException e) {
        log.warn("Cert file missing: {}", e);
        return " (CERTIFICATE FILE MISSING!)";
    }
    try {
        CryptoUtils.readCertificate(certBytes);
    } catch (Exception e) {
        log.warn("Invalid certificate: {}", e);
        return " (INVALID CERTIFICATE - " + e.getMessage() + ")";
    }
    return " (Certificate: " + certPath.toString() + ")";
}

From source file:com.team3637.service.ScheduleServiceMySQLImpl.java

@Override
public void importCSV(String inputFile) {
    try {/*from  ww w  . j av a 2  s  . c  o  m*/
        String csvData = new String(Files.readAllBytes(FileSystems.getDefault().getPath(inputFile)));
        csvData = csvData.replaceAll("\\r", "");
        CSVParser parser = CSVParser.parse(csvData, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (CSVRecord record : parser) {
            Schedule schedule = new Schedule();
            schedule.setId(Integer.parseInt(record.get(0)));
            schedule.setMatchNum(Integer.parseInt(record.get(1)));
            schedule.setB1(Integer.parseInt(record.get(2)));
            schedule.setB2(Integer.parseInt(record.get(3)));
            schedule.setB3(Integer.parseInt(record.get(4)));
            schedule.setR1(Integer.parseInt(record.get(5)));
            schedule.setR2(Integer.parseInt(record.get(6)));
            schedule.setR3(Integer.parseInt(record.get(7)));
            if (checkForMatch(schedule))
                update(schedule);
            else
                create(schedule);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.spee.sbweb.controller.UploadController.java

private static String readFile(String path, Charset encoding) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, encoding);
}

From source file:org.springsource.restbucks.PaymentProcessIntegrationTest.java

/**
 * Creates a new {@link Order} by looking up the orders link from the source and posting the content of
 * {@code orders.json} to it. Verifies we get receive a {@code 201 Created} and a {@code Location} header. Follows the
 * location header to retrieve the {@link Order} just created.
 * //w  w  w.j  a v a  2 s  . c  o m
 * @param source
 * @return
 * @throws Exception
 */
private MockHttpServletResponse createNewOrder(MockHttpServletResponse source) throws Exception {

    String content = source.getContentAsString();
    Link ordersLink = links.findLinkWithRel(ORDERS_REL, content);

    ClassPathResource resource = new ClassPathResource("order.json");
    byte[] data = Files.readAllBytes(resource.getFile().toPath());

    MockHttpServletResponse result = mvc
            .perform(post(ordersLink.getHref()).contentType(MediaType.APPLICATION_JSON).content(data)). //
            andExpect(status().isCreated()). //
            andExpect(header().string("Location", is(notNullValue()))). //
            andReturn().getResponse();

    return mvc.perform(get(result.getHeader("Location"))).andReturn().getResponse();
}

From source file:com.att.aro.core.packetanalysis.impl.VideoUsageAnalysisImpl.java

/**
 * <pre>/*www  .  jav a  2s  . c  o  m*/
 * Loads a replacement for missing thumbnails, blocked by DRM. The default
 * is the VO App icon image User defined replacement needs to be a PNG image
 * and should be in the VideoOptimizerLibrary and named broken_thumbnail.png
 *
 * @return byte[] of a png image
 */
private byte[] loadDefaultThumbnail() {
    byte[] data = null;
    String brokenThumbnailPath = Util.getVideoOptimizerLibrary() + Util.FILE_SEPARATOR + "broken_thumbnail.png";
    if (filemanager.fileExist(brokenThumbnailPath)) {
        try {
            Path path = Paths.get(brokenThumbnailPath);
            data = Files.readAllBytes(path);
        } catch (IOException e) {
            log.debug("getThumnail IOException:" + e.getMessage());
        }
    } else {
        String iconName = "aro_24.png";
        String appIconPath = Util.getVideoOptimizerLibrary() + Util.FILE_SEPARATOR + iconName;
        if (!filemanager.fileExist(appIconPath)) {
            Util.makeLibFilesFromJar(iconName);
        }
        if (filemanager.fileExist(appIconPath)) {
            try {
                Path path = Paths.get(appIconPath);
                data = Files.readAllBytes(path);
            } catch (IOException e) {
                log.debug("getIconThumnail IOException:" + e.getMessage());
            }
        }
    }
    return data;
}

From source file:com.sastix.cms.server.services.content.HashedDirectoryServiceTest.java

@Test
public void testGetDataByURI() throws IOException, URISyntaxException {
    final String UURI = UUID.randomUUID().toString() + "-" + TENANT_ID + "/demo.txt";
    final String path = hashedDirectoryService.storeFile(UURI, TENANT_ID, "HELLO Data".getBytes());

    Path content = hashedDirectoryService.getDataByURI(UURI, TENANT_ID);
    Assert.assertEquals(new String(Files.readAllBytes(content)), "HELLO Data");
}

From source file:com.fratello.longevity.smooth.object.SpecialFile.java

private boolean testFilterProperty_Hash(SpecialFile other) {
    String srcHashAlgo = this.filter.getHashString();
    String[] possibilties = new String[] { "MD5", "SHA-1", "SHA-256", "SHA-512" };
    boolean goodToContinue = false;
    for (String s : possibilties)
        if (s.compareTo(srcHashAlgo) == 0) {
            goodToContinue = true;/*from  ww w . j av  a 2 s.  c  o m*/
            break;
        }
    if (!goodToContinue)
        return false;
    try {
        MessageDigest md1 = MessageDigest.getInstance(srcHashAlgo);
        MessageDigest md2 = MessageDigest.getInstance(srcHashAlgo);
        if (!Arrays.equals(md1.digest(Files.readAllBytes(this.PATH)),
                md2.digest(Files.readAllBytes(other.PATH)))) {
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}

From source file:io.undertow.server.handlers.accesslog.AccessLogFileTestCase.java

@Test
public void testLogLotsOfThreads() throws IOException, InterruptedException, ExecutionException {
    Path directory = logDirectory;
    Path logFileName = directory.resolve("server2.log");

    DefaultAccessLogReceiver logReceiver = new DefaultAccessLogReceiver(DefaultServer.getWorker(), directory,
            "server2.");
    CompletionLatchHandler latchHandler;
    DefaultServer.setRootHandler(latchHandler = new CompletionLatchHandler(NUM_REQUESTS * NUM_THREADS,
            new AccessLogHandler(HELLO_HANDLER, logReceiver, "REQ %{i,test-header}",
                    AccessLogFileTestCase.class.getClassLoader())));

    ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
    try {/*ww w .  ja  v a 2s.c o  m*/

        final List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < NUM_THREADS; ++i) {
            final int threadNo = i;
            futures.add(executor.submit(new Runnable() {
                @Override
                public void run() {
                    TestHttpClient client = new TestHttpClient();
                    try {
                        for (int i = 0; i < NUM_REQUESTS; ++i) {
                            HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
                            get.addHeader("test-header", "thread-" + threadNo + "-request-" + i);
                            HttpResponse result = client.execute(get);
                            Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
                            final String response = HttpClientUtils.readResponse(result);
                            Assert.assertEquals("Hello", response);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        client.getConnectionManager().shutdown();
                    }
                }
            }));
        }
        for (Future<?> future : futures) {
            future.get();
        }

    } finally {
        executor.shutdown();
    }
    latchHandler.await();
    logReceiver.awaitWrittenForTest();
    String completeLog = new String(Files.readAllBytes(logFileName));
    for (int i = 0; i < NUM_THREADS; ++i) {
        for (int j = 0; j < NUM_REQUESTS; ++j) {
            Assert.assertTrue(completeLog.contains("REQ thread-" + i + "-request-" + j));
        }
    }

}

From source file:com.sesnu.orion.web.service.ReportService.java

public String generateOrderAuthReport(Approval appr, String state) throws DocumentException, IOException {
    Bid bid = bidDao.get(appr.getForId());
    OrderView order = orderDao.get(bid.getOrderRef());
    Item item = itemDao.get(order.getItemId());
    List<BidView> bids = bidDao.list(order.getId());

    String orginalHtml = conf.getFile("orderAuth.html");
    Estimate est = estService.totalEstimate(order, null, bid, item);

    String editedHtml = orginalHtml.replace("ORDER_DATE", Util.parseDate(order.getCreatedOn()));
    editedHtml = setPaths(editedHtml, state);
    editedHtml = editedHtml.replace("PRODUCT_NAME", item.getName());
    editedHtml = editedHtml.replace("ORDERED_BY", order.getOrderedBy());
    editedHtml = editedHtml.replace("BRAND_NAME", item.getBrand());
    editedHtml = editedHtml.replace("DEPARTMENT", "Import"); // whose department ?
    editedHtml = editedHtml.replace("PACKAGING",
            order.getBaseSize().toString() + order.getBaseUnit() + "X" + order.getQtyPerPack() + "pcs");
    editedHtml = editedHtml.replace("BUDGET_REF", order.getBudgetRef());
    editedHtml = editedHtml.replace("QTY_PER_CONT", order.getPckPerCont().toString());
    editedHtml = editedHtml.replace("DESTINATION", order.getDestinationPort());
    editedHtml = editedHtml.replace("QUANTITY", order.getContQnt() + "X" + order.getContSize() + "'");
    editedHtml = editedHtml.replace("LATEST_ETA", Util.parseDate(order.getLatestETA()));

    editedHtml = editedHtml.replace("IN_TRANSIT", shipDao.InTransitCount(item.getId()).toString());
    editedHtml = editedHtml.replace("IN_PORT", shipDao.InPortCount(item.getId()).toString());
    editedHtml = editedHtml.replace("IN_TERMINAL", shipDao.InTerminalCount(item.getId()).toString());
    BigInteger newItemOrders = orderDao.newOrdersCount(item.getId()).subtract(new BigInteger("1"));
    editedHtml = editedHtml.replace("NEW_ORDERS", newItemOrders.toString());
    editedHtml = editedHtml.replace("ORDER_DATE", bid.getUpdatedOn());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < bids.size(); i++) {
        BidView abid = bids.get(i);/*from   w  w w. j  a  va2  s .  com*/
        sb.append("<tr>");
        sb.append("<td>");
        sb.append(i + 1);
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getSupplier());
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getCifCnf());
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getFob());
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getCurrency());
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getPaymentMethod() == null ? "" : abid.getPaymentMethod());
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.isSelected() ? "Yes" : "No");
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getRemark() == null ? "" : abid.getRemark());
        sb.append("</td>");
        sb.append("</tr>");
    }

    editedHtml = editedHtml.replace("BID_DATA_TABLE", sb.toString());
    editedHtml = editedHtml.replace("EST_TRANSIT_DAYS", bid.getEstTransitDays().toString());
    Calendar c = Calendar.getInstance();
    c.setTime(order.getLatestETA());
    c.add(Calendar.DATE, bid.getEstTransitDays());
    editedHtml = editedHtml.replace("LATEST_DATE_OF_SHIP", Util.parseDate(c.getTime()));
    editedHtml = editedHtml.replace("IMPORTER", order.getImporter());

    Exchange cur = exchangeDao.get("Other", "Other", "USD", "AOA");
    if (cur == null) {
        return null;
    }

    editedHtml = editedHtml.replace("TOTAL_CNF_USD", Util.parseCurrency(bid.getTotalBid()));
    Double pricePerPack = (bid.getTotalBid() * cur.getRate() + est.getValue()) / order.getContQnt()
            / order.getPckPerCont();
    pricePerPack = pricePerPack / cur.getRate();
    pricePerPack = (double) (Math.round(pricePerPack * 100.0) / 100);
    editedHtml = editedHtml.replace("LANDED_COST_TO_WH", pricePerPack.toString());
    Double totalEstPrice = pricePerPack * 1.12;
    editedHtml = editedHtml.replace("COST_PLUS_MRG", totalEstPrice.toString());
    String emailTo = appr.getRequestedBy() + " [" + (userDao.getUserName(appr.getRequestedBy())).getEmail()
            + "]";
    String emailCC = appr.getApprover() + " [" + (userDao.getUserName(appr.getApprover())).getEmail() + "]";
    editedHtml = editedHtml.replace("EMAIL_TO", emailTo);
    editedHtml = editedHtml.replace("EMAIL_CC", emailCC);

    if (!state.equals("preview")) {
        editedHtml = editedHtml.replace("SIGNATURE", appr.getApprover());
        editedHtml = editedHtml.replace("APPROVED_ON", new Date().toGMTString());
        String pdfFilePath = util.convertToPdf(editedHtml); // convert to pdf
        Path path = Paths.get(pdfFilePath);

        byte[] data = Files.readAllBytes(path); // convert to byte array
        String[] frag = pdfFilePath.split("/");
        String fileName = frag[frag.length - 1]; // get file name
        util.writeToS3(data, fileName); // write to s3
        sendApprovalEmail(appr, pdfFilePath, order);
        Files.deleteIfExists(path);

        Document doc = new Document(order.getId(), fileName, "Order Authorization", Util.parseDate(new Date()),
                "");
        docDao.saveOrUpdate(doc);
    } else {
        editedHtml = editedHtml.replace("APPROVED_ON", "");
    }
    return editedHtml;
}