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:org.shareok.data.datahandlers.DataHandlersUtil.java

public static String[] getRepoCredentials(String repoName)
        throws SecurityFileDoesNotExistException, IOException {
    String[] credentials = new String[2];
    String securityFilePath = ShareokdataManager.getSecurityFilePath();
    File securityFile = new File(securityFilePath);
    if (!securityFile.exists()) {
        throw new SecurityFileDoesNotExistException("The security file does NOT exist!");
    }// w w w . j av  a 2s  . co m
    String content = new String(Files.readAllBytes(Paths.get(securityFilePath)));
    ObjectMapper mapper = new ObjectMapper();
    RepoCredential[] credentialObjects = mapper.readValue(content, RepoCredential[].class);
    for (RepoCredential credentialObj : credentialObjects) {
        if (repoName.equals(credentialObj.getRepoName())) {
            credentials[0] = credentialObj.getUserName();
            credentials[1] = credentialObj.getPassword();
        }
    }
    return credentials;
}

From source file:uk.dsxt.voting.common.utils.PropertiesHelper.java

public static String getResourceString(String name, String encoding) {
    if (name == null || name.isEmpty())
        return "";
    try {/* w  w  w. jav a 2 s.  c  o  m*/
        final File resourceFile = getConfFile(name);
        if (resourceFile.exists()) {
            try {
                byte[] encoded = Files.readAllBytes(Paths.get(resourceFile.getPath()));
                log.debug("getResourceString. Resource ({}) found: {}", name, resourceFile.getAbsolutePath());
                return new String(encoded, Charset.forName(encoding));
            } catch (IOException e) {
                log.warn("getResourceString. Couldn't read resource from file: {}. error={}",
                        resourceFile.getAbsolutePath(), e.getMessage());
            }
        }

        log.info("getResourceString. Loading resource from jar: {}", name);
        final URL resource = getResource(name);
        if (resource == null) {
            log.warn("getResourceString. Couldn't load resource from jar file: {}.", name);
            return "";
        }
        return IOUtils.toString(resource.openStream(), Charset.forName(encoding));
    } catch (Exception e) {
        log.error("getResourceString. Couldn't read a resource file.", e);
    }
    return "";
}

From source file:gaffer.data.elementdefinition.ElementDefinitions.java

private static <T extends ElementDefinitions> T fromJson(final Class<T> clazz, final Object[] jsonItems)
        throws SchemaException {
    T elementDefs = null;/*from w  w  w  . java  2 s.  com*/
    for (final Object jsonItem : jsonItems) {
        final T elDefsTmp;
        try {
            if (jsonItem instanceof InputStream) {
                elDefsTmp = JSON_SERIALISER.deserialise(((InputStream) jsonItem), clazz);
            } else if (jsonItem instanceof Path) {
                elDefsTmp = JSON_SERIALISER.deserialise(Files.readAllBytes((Path) jsonItem), clazz);
            } else {
                elDefsTmp = JSON_SERIALISER.deserialise(((byte[]) jsonItem), clazz);
            }
        } catch (IOException e) {
            throw new SchemaException("Failed to load element definitions from bytes", e);
        }

        if (null == elementDefs) {
            elementDefs = elDefsTmp;
        } else {
            elementDefs.merge(elDefsTmp);
        }
    }

    return elementDefs;
}

From source file:com.codealot.textstore.FileStore.java

@Override
public String getText(final String id) throws IOException {
    checkId(id);/*from   ww w. j  av  a2s. co  m*/
    final Path textPath = idToPath(id);
    final byte[] bytes = Files.readAllBytes(textPath);
    return new String(bytes, StandardCharsets.UTF_8);
}

From source file:io.github.microcks.util.postman.PostmanTestStepsRunner.java

/**
 * Build a new PostmanTestStepsRunner for a collection.
 * @param collectionFilePath The path to SoapUI project file
 * @throws java.io.IOException if file cannot be found or accessed.
 *//* w w w .  j  ava 2 s  .co  m*/
public PostmanTestStepsRunner(String collectionFilePath) throws IOException {
    try {
        // Read Json bytes.
        byte[] jsonBytes = Files.readAllBytes(Paths.get(collectionFilePath));
        // Convert them to Node using Jackson object mapper.
        ObjectMapper mapper = new ObjectMapper();
        collection = mapper.readTree(jsonBytes);
    } catch (Exception e) {
        throw new IOException("Postman collection file");
    }
}

From source file:com.netscape.cmstools.pkcs7.PKCS7CertFindCLI.java

public void execute(String[] args) throws Exception {

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

    if (cmd.hasOption("help")) {
        printHelp();/*from   w ww.ja  v  a  2 s.c  o  m*/
        return;
    }

    if (cmd.hasOption("verbose")) {
        PKILogger.setLevel(PKILogger.Level.INFO);

    } else if (cmd.hasOption("debug")) {
        PKILogger.setLevel(PKILogger.Level.DEBUG);
    }

    String filename = cmd.getOptionValue("pkcs7-file");

    if (filename == null) {
        throw new Exception("Missing PKCS #7 file.");
    }

    logger.info("Loading PKCS #7 data from " + filename);
    String str = new String(Files.readAllBytes(Paths.get(filename))).trim();
    PKCS7 pkcs7 = new PKCS7(str);

    X509Certificate[] certs = pkcs7.getCertificates();
    if (certs == null || certs.length == 0) {
        System.out.println("PKCS #7 data contains no certificates");
        return;
    }

    // sort certs from root to leaf
    certs = CryptoUtil.sortCertificateChain(certs);

    boolean first = true;

    for (X509Certificate cert : certs) {

        if (first) {
            first = false;
        } else {
            System.out.println();
        }

        PKCS7CertCLI.printCertInfo(cert);
    }
}

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

@Override
public boolean perform(AbstractBuild build, Launcher launcher, final BuildListener listener) {

    Result buildResult = build.getResult();

    if (!Result.SUCCESS.equals(buildResult)) {
        // Don't process for unsuccessful builds
        listener.getLogger().println("Build status is not SUCCESS (" + build.getResult().toString() + ").");
        return false;
    }//from ww w.ja  v  a 2 s  .  c o m

    VSPluginPerformer performer = new VSPluginPerformer();
    //add build action
    performer.addBuildAction(build);

    try {

        //DO REPORT HERE
        FilePath jPath = new FilePath(build.getWorkspace(), build.getWorkspace() + "/VSTART_JSON");

        if (!jPath.exists()) {
            return false;
        }

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

        //read .json file
        String content = new String(Files.readAllBytes(Paths.get(filePath)));
        JSONArray reports = new JSONArray(content);

        //Generate html report
        VSPluginHtmlWriter htmlWriter = new VSPluginHtmlWriter();
        boolean reportResult = htmlWriter.doHtmlReport(build, reports);

        return reportResult;

    } catch (IOException ex) {
        Logger.getLogger(VSPluginPublisher.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger()
                .println("Exception during the Publisher's perform! -> " + ex.getLocalizedMessage());
        return false;
    } catch (InterruptedException ex) {
        Logger.getLogger(VSPluginPublisher.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Exception during the VSTART run! -> " + ex.getLocalizedMessage());
        return false;
    }
}

From source file:com.difference.historybook.proxy.ProxyTest.java

@Test
public void testChunkedResponseHandling() throws IOException {
    String fileName = "src/test/resources/__files/response.txt";
    Path path = Paths.get(fileName).toAbsolutePath();
    byte[] body = Files.readAllBytes(path);

    stubFor(get(urlEqualTo("/some/page")).willReturn(
            aResponse().withStatus(200).withHeader("Content-Type", "text/html").withBodyFile("response.txt")));

    Proxy proxy = getProxy().setPort(PROXY_PORT);
    try {//from www  . j  av a2  s  .c om
        proxy.start();

        java.net.Proxy proxyServer = new java.net.Proxy(java.net.Proxy.Type.HTTP,
                new InetSocketAddress("127.0.0.1", PROXY_PORT));
        HttpURLConnection connection = (HttpURLConnection) new URL(
                "http://localhost:" + DUMMY_SERVER_PORT + "/some/page").openConnection(proxyServer);

        // The purpose of this test is to test chunked response handling, but there doesn't seem
        // to be an easy way to force this in WireMock (or any of the other tools I looked at)
        // Having it response with the content of a file seems to result in it switching to 
        // chunked responses, but there isn't a reason this needs to be the case.
        // The following test is really testing to make sure this test is still working
        // and forcing chunked mode responses.
        assertEquals("chunked", connection.getHeaderField("Transfer-Encoding"));

        byte[] fetchedContent = IOUtils.toByteArray(connection.getInputStream());
        assertArrayEquals(body, fetchedContent);

        proxy.stop();
    } catch (Exception e) {
        fail(e.getLocalizedMessage());
    }

}

From source file:com.movilizer.mds.webservice.services.MafManagementService.java

protected MafSource readSource(File sourceFile) {
    try {//  w w  w.  jav a2  s.c  om
        MafCliMetaFile meta = readMetaFile(sourceFile);
        String scriptSrc = new String(Files.readAllBytes(sourceFile.toPath()));
        meta.getSource().setScriptSrc(scriptSrc);
        return meta.getSource();
    } catch (IOException e) {
        throw new MovilizerMAFManagementException(e);
    }
}

From source file:org.sakuli.services.receiver.gearman.model.builder.ScreenshotDivConverter.java

protected String extractScreenshotAsBase64(Throwable exception) {
    if (exception instanceof SakuliExceptionWithScreenshot) {
        Path screenshotPath = ((SakuliExceptionWithScreenshot) exception).getScreenshot();
        if (screenshotPath != null) {
            try {
                byte[] binaryScreenshot = Files.readAllBytes(screenshotPath);
                String base64String = new BASE64Encoder().encode(binaryScreenshot);
                for (String newLine : Arrays.asList("\n", "\r")) {
                    base64String = StringUtils.remove(base64String, newLine);
                }//from w w  w  .ja va  2s.com
                return base64String;
            } catch (IOException e) {
                exceptionHandler.handleException(new SakuliReceiverException(e, String.format(
                        "error during the BASE64 encoding of the screenshot '%s'", screenshotPath.toString())));
            }
        }
    }
    return null;
}