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.ericsson.eiffel.remrem.generate.EiffelRemremControllerIntegrationTest.java

private String loadEventBody(final String fileName) throws IOException {
    URL url = getClass().getClassLoader().getResource(fileName);
    assert url != null;
    String path = url.getPath().replace("%20", " ");
    File file = new File(path);
    final byte[] bytes = Files.readAllBytes(file.toPath());
    return new String(bytes);
}

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

@Override
public void doPerform() throws Exception {
    FileOutputStream csvFileOut = new FileOutputStream(csvFilePath.toFile());
    PrintWriter printer = new PrintWriter(csvFileOut, true);
    try {/*from w  w w . ja  v a2  s .  co  m*/
        if (aqlFilePath.toFile().isDirectory()) {
            for (File f : aqlFilePath.toFile().listFiles()) {
                queriesToRun.add(f.toPath());
            }
        } else {
            queriesToRun.add(aqlFilePath);
        }

        for (Path p : queriesToRun) {
            String sqlpp = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(p))).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(sqlpp, StandardCharsets.UTF_8));
            long start = System.currentTimeMillis();
            HttpResponse resp = httpClient.execute(post);
            HttpEntity entity = resp.getEntity();
            if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpException("Query returned error" + EntityUtils.toString(entity));
            }
            EntityUtils.consume(entity);
            long end = System.currentTimeMillis();
            long wallClock = end - start;
            String currLine = p.getFileName().toString() + ',' + wallClock;
            System.out.println(currLine);
            printer.print(currLine + '\n');
        }
    } finally {
        printer.close();
    }
}

From source file:org.hawkular.apm.tests.dockerized.TestScenariosFinder.java

public String readFile(File file) throws IOException {
    byte[] bytes = Files.readAllBytes(Paths.get(file.toURI()));
    return new String(bytes);
}

From source file:com.alliander.osgp.shared.security.CertificateHelper.java

/**
 * Read certificate bytes from disk//from   w  w w. j  a v a  2 s.  c om
 *
 * @param keyPath
 * @return bytes of key
 * @throws IOException
 */
private static byte[] readKeyFromDisk(final String keyPath) throws IOException {
    return Files.readAllBytes(new File(keyPath).toPath());
}

From source file:ai.susi.server.api.cms.AppsService.java

@Override
public JSONObject serviceImpl(Query query, HttpServletResponse response, Authorization auth,
        final JsonObjectWithDefault permissions) throws APIException {

    String categorySelection = query.get("category", "");

    // generate json
    File apps = new File(DAO.html_dir, "apps");
    JSONObject json = new JSONObject(true);
    JSONArray app_array = new JSONArray();
    json.put("apps", app_array);
    JSONObject categories = new JSONObject(true);
    for (String appname : apps.list())
        try {/*from   w w  w.j a  v a2s. co m*/
            // read app and verify the structure of the app
            File apppath = new File(apps, appname);
            if (!apppath.isDirectory())
                continue;
            Set<String> files = new HashSet<>();
            for (String f : apppath.list())
                files.add(f);
            if (!files.contains("index.html"))
                continue;
            if (!files.contains("app.json"))
                continue;
            File json_ld_file = new File(apppath, "app.json");
            String jsonString = new String(Files.readAllBytes(json_ld_file.toPath()), StandardCharsets.UTF_8);
            JSONObject json_ld = new JSONObject(jsonString);

            // translate permissions
            if (json_ld.has("permissions")) {
                String p = json_ld.getString("permissions");
                String[] ps = p.split(",");
                JSONArray a = new JSONArray();
                for (String s : ps)
                    a.put(s);
                json_ld.put("permissions", a);
            }

            // check category
            if (json_ld.has("applicationCategory") && json_ld.has("name")) {
                String cname = json_ld.getString("applicationCategory");
                if (categorySelection.length() == 0 || categorySelection.equals(cname))
                    app_array.put(json_ld);
                String aname = json_ld.getString("name");
                if (!categories.has(cname))
                    categories.put(cname, new JSONArray());
                JSONArray appnames = categories.getJSONArray(cname);
                appnames.put(aname);
            }
        } catch (Throwable e) {
            Log.getLog().warn(e);
        }
    // write categories
    json.put("categories", categories.keySet().toArray(new String[categories.length()]));
    json.put("category", categories);

    return json;
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

@Test
public void verifyTestConfigurationFiles() throws Exception {
    final Set<Class<?>> modules = CheckUtil.getCheckstyleModules();
    final Set<String> packages = CheckUtil.getPackages(modules);

    Assert.assertTrue("no modules", modules.size() > 0);

    // sonar//from w  w w  .java2 s . c  om

    final File extensionFile = new File(getSonarPath("checkstyle-extensions.xml"));

    Assert.assertTrue("'checkstyle-extensions.xml' must exist in sonar", extensionFile.exists());

    final String input = new String(Files.readAllBytes(extensionFile.toPath()), UTF_8);

    final Document document = XmlUtil.getRawXml(extensionFile.getAbsolutePath(), input, input);

    validateSonarFile(document, new HashSet<>(modules));

    // eclipsecs

    for (String p : packages) {
        Assert.assertTrue("folder " + p + " must exist in eclipsecs", new File(getEclipseCsPath(p)).exists());

        final Set<Class<?>> pkgModules = CheckUtil.getModulesInPackage(modules, p);

        validateEclipseCsMetaXmlFile(new File(getEclipseCsPath(p + "/checkstyle-metadata.xml")), p,
                new HashSet<>(pkgModules));

        validateEclipseCsMetaPropFile(new File(getEclipseCsPath(p + "/checkstyle-metadata.properties")), p,
                new HashSet<>(pkgModules));
    }
}

From source file:com.netscape.cmstools.user.UserCertAddCLI.java

public void execute(String[] args) throws Exception {
    // Always check for "--help" prior to parsing
    if (Arrays.asList(args).contains("--help")) {
        printHelp();/*  w w  w.  ja va2  s .  c  o  m*/
        return;
    }

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

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length != 1) {
        throw new Exception("No User ID specified.");
    }

    String userID = cmdArgs[0];
    String inputFile = cmd.getOptionValue("input");
    String serialNumber = cmd.getOptionValue("serial");

    String encoded;

    if (inputFile != null && serialNumber != null) {
        throw new Exception("Conflicting options: --input and --serial.");

    } else if (inputFile != null) {
        if (verbose) {
            System.out.println("Reading certificate from " + inputFile + ".");
        }

        encoded = new String(Files.readAllBytes(Paths.get(inputFile)));
        if (verbose) {
            System.out.println(encoded);
        }

    } else if (serialNumber != null) {
        if (verbose) {
            System.out.println("Downloading certificate " + serialNumber + ".");
        }

        CAClient caClient = MainCLI.createCAClient(parent.getClient());
        CACertClient certClient = new CACertClient(caClient);

        CertData certData = certClient.getCert(new CertId(serialNumber));
        encoded = certData.getEncoded();

    } else {
        throw new Exception("Missing input file or serial number.");
    }

    UserCertData userCertData = new UserCertData();
    userCertData.setEncoded(encoded);

    if (verbose) {
        System.out.println(userCertData);
    }

    UserClient userClient = userCertCLI.getUserClient();
    userCertData = userClient.addUserCert(userID, userCertData);

    MainCLI.printMessage("Added certificate \"" + userCertData.getID() + "\"");

    UserCertCLI.printCert(userCertData, false, false);
}

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

private static StringEntity massageJSONData(Object inputData) throws RestingException {
    logger.debug("Inside massageJSONData!");
    StringEntity stringEntity = null;// w  w w.  ja  va 2 s  .  c o m
    if (inputData instanceof Map<?, ?>) {
        try {
            logger.debug("Map>" + new JSONObject((Map<?, ?>) inputData).toJSONString());
            stringEntity = new StringEntity(new JSONObject((Map<?, ?>) inputData).toJSONString());
        } 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:com.google.identitytoolkit.GitkitClient.java

/**
 * Constructs a Gitkit client from a JSON config file
 *
 * @param configPath Path to JSON configuration file
 * @return Gitkit client//from ww w  .ja v  a2s.c  om
 */
public static GitkitClient createFromJson(String configPath) throws JSONException, IOException {
    JSONObject configData = new JSONObject(StandardCharsets.UTF_8
            .decode(ByteBuffer.wrap(Files.readAllBytes(Paths.get(configPath)))).toString());

    return new GitkitClient.Builder().setGoogleClientId(configData.getString("clientId"))
            .setServiceAccountEmail(configData.getString("serviceAccountEmail"))
            .setKeyStream(new FileInputStream(configData.getString("serviceAccountPrivateKeyFile")))
            .setWidgetUrl(configData.getString("widgetUrl")).setCookieName(configData.getString("cookieName"))
            .setServerApiKey(configData.optString("serverApiKey", null)).build();
}

From source file:net.troja.eve.crest.CrestDataProcessorTest.java

private String getExampleData() throws URISyntaxException, IOException {
    final URL resource = getClass().getResource(EXAMPLE_FILE);
    final Path file = Paths.get(resource.toURI());
    final String answer = new String(Files.readAllBytes(file));
    return answer;
}