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.diffplug.gradle.pde.PdeProductBuildConfig.java

static void transformProductFile(File input, File output, PluginCatalog catalog, String version)
        throws IOException {
    String inputStr = new String(Files.readAllBytes(input.toPath()), StandardCharsets.UTF_8);
    String result = StringPrinter.buildString(printer -> {
        String[] lines = FileMisc.toUnixNewline(inputStr).split("\n");
        for (String line : lines) {
            ProductFileUtil.transformProductFile(printer, line, catalog, version);
        }/* w  w w  .  j  av  a  2  s.c  o  m*/
    });
    Files.write(output.toPath(), result.getBytes(StandardCharsets.UTF_8));
}

From source file:org.shareok.data.datahandlers.DataHandlersUtil.java

public static String getPublisherApiKeyByName(String publisher)
        throws SecurityFileDoesNotExistException, IOException {
    String key = "";
    String securityFilePath = ShareokdataManager.getSecurityFilePath();
    File securityFile = new File(securityFilePath);
    if (!securityFile.exists()) {
        throw new SecurityFileDoesNotExistException("The security file does NOT exist!");
    }/*from  www .jav a2  s  . c  o  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 (publisher.equals(credentialObj.getRepoName())) {
            key = credentialObj.getUserName();
        }
    }
    return key;
}

From source file:io.github.casnix.spawnerdropper.SpawnerStack.java

public static boolean PutSpawnerIntoService(String spawnerType) {
    // Read ./SpawnerDropper.SpawnerStack.json into a string

    // get the value of JSON->{spawnerType} and add 1 to it.

    // Write file back to disk
    try {//from w w  w  .j  av a2s . c om
        // Read entire ./SpawnerDropper.SpawnerStack.json into a string
        String spawnerStack = new String(
                Files.readAllBytes(Paths.get("./plugins/SpawnerDropper/SpawnerStack.json")));

        // get the value of JSON->{spawnerType}
        JSONParser parser = new JSONParser();

        Object obj = parser.parse(spawnerStack);

        JSONObject jsonObj = (JSONObject) obj;

        long numberInService = (Long) jsonObj.get(spawnerType);

        if (numberInService < 0) {
            numberInService = 0;
        }

        //         System.out.println("[SD DBG MSG] PSIS numberInServer("+numberInService+")");
        numberInService += 1;
        jsonObj.put(spawnerType, new Long(numberInService));

        FileWriter file = new FileWriter("./plugins/SpawnerDropper/SpawnerStack.json");
        file.write(jsonObj.toJSONString());
        file.flush();
        file.close();

        return true;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught ParseException in PutSpawnerIntoService(String)");
        e.printStackTrace();

        return false;
    } catch (FileNotFoundException e) {
        Bukkit.getLogger()
                .warning("[SpawnerDropper] Could not find ./plugins/SpawnerDropper/SpawnerStack.json");
        e.printStackTrace();

        return false;
    } catch (IOException e) {
        Bukkit.getLogger().warning("[SpawnerDropper] Caught IOException in PutSpawnerIntoService(String)");
        e.printStackTrace();

        return false;
    }
}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.sidhdhi.SidhdhiQuery.java

/**
 * Read content from a given file and return as a string
 *
 * @param path/*www .jav a2  s.c  om*/
 * @param encoding
 * @return
 */
public static String readFile(String path, Charset encoding) {
    byte[] encoded = new byte[0];
    try {
        encoded = Files.readAllBytes(Paths.get(path));
    } catch (IOException e) {
        log.error("Error reading Sidhdhi query from file.");
    }
    return new String(encoded, encoding);
}

From source file:org.lecture.integration.tutorial.TutorialIntegrationTest.java

@Test
public void testPatch() throws Exception {

    String original = "Hallo Welt!";

    String modified = new String(Files.readAllBytes(Paths.get(getClass().getResource("/modified.md").toURI())));

    PatchService ps = new DmpPatchService();

    String patch = ps.createPatch(original, modified);
    mockMvc.perform(patch("/tutorials/1").content(patch).contentType(TEXT_PLAIN_UTF8))
            .andExpect(status().isNoContent());

    mockMvc.perform(get("/tutorials/1/raw")).andExpect(status().isOk())
            .andExpect(jsonPath("$.content", is(modified)));

}

From source file:org.kurento.room.test.AutodiscoveryKmsUrlTest.java

@Test
public void test() throws IOException {

    Path backup = null;//w  w w  . ja  va  2  s.c o m

    Path configFile = Paths.get(StandardSystemProperty.USER_HOME.value(), ".kurento", "config.properties");

    System.setProperty("kms.uris", "[\"autodiscovery\"]");

    try {

        if (Files.exists(configFile)) {

            backup = configFile.getParent().resolve("config.properties.old");

            Files.move(configFile, backup);
            log.debug("Backed-up old config.properties");
        }

        Files.createDirectories(configFile.getParent());

        try (BufferedWriter writer = Files.newBufferedWriter(configFile, StandardCharsets.UTF_8)) {
            writer.write("kms.url.provider: " + TestKmsUrlProvider.class.getName() + "\r\n");
        }

        String contents = new String(Files.readAllBytes(configFile));
        log.debug("Config file contents:\n{}", contents);

        ConfigurableApplicationContext app = KurentoRoomServerApp.start(new String[] { "--server.port=7777" });

        NotificationRoomManager notifRoomManager = app.getBean(NotificationRoomManager.class);

        final RoomManager roomManager = notifRoomManager.getRoomManager();

        final KurentoClientSessionInfo kcSessionInfo = new DefaultKurentoClientSessionInfo("participantId",
                "roomName");

        new Thread(new Runnable() {
            @Override
            public void run() {
                roomManager.joinRoom("userName", "roomName", false, kcSessionInfo, "participantId");
            }
        }).start();

        try {
            Boolean result = queue.poll(10, TimeUnit.SECONDS);

            if (result == null) {
                fail("Event in KmsUrlProvider not called");
            } else {
                if (!result) {
                    fail("Test failed");
                }
            }

        } catch (InterruptedException e) {
            fail("KmsUrlProvider was not called");
        }

    } finally {

        Files.delete(configFile);

        if (backup != null) {
            Files.move(backup, configFile);
        }
    }
}

From source file:gov.nist.appvet.toolmgr.ToolServiceAdapter.java

public static String getHtmlReportString(String reportPath, AppInfo appInfo) {
    byte[] encoded = null;
    try {//from www  .j  av  a 2s . c om
        encoded = Files.readAllBytes(Paths.get(reportPath));
        return Charset.defaultCharset().decode(ByteBuffer.wrap(encoded)).toString();
    } catch (final IOException e) {
        appInfo.log.error(e.getMessage());
        return null;
    } finally {
        encoded = null;
    }
}

From source file:grakn.core.daemon.executor.Executor.java

public boolean isProcessRunning(Path pidFile) {
    String processPid;/*from  w  w w  . j a  va 2 s .  c  o m*/
    if (pidFile.toFile().exists()) {
        try {
            processPid = new String(Files.readAllBytes(pidFile), StandardCharsets.UTF_8);
            if (processPid.trim().isEmpty()) {
                return false;
            }
            Result command = executeAndWait(checkPIDRunningCommand(processPid), null);

            if (command.exitCode() != 0) {
                System.out.println(command.stderr());
            }
            return command.exitCode() == 0;
        } catch (NumberFormatException | IOException e) {
            return false;
        }
    }
    return false;
}

From source file:com.epam.reportportal.extension.bugtracking.rally.RallyStrategyTest.java

public RallyStrategy rallyMock() {
    return new RallyStrategy() {
        @Override/*  ww w . j av a 2  s  .  c o m*/
        public RallyRestApi getRallyRestApi(URI server, String apiKey) {
            final RallyRestApi rallyRestApi = mock(RallyRestApi.class);
            try {
                when(rallyRestApi.query(argThat(new ArgumentMatcher<QueryRequest>() {
                    @Override
                    public boolean matches(Object argument) {
                        if (argument == null)
                            return false;
                        QueryRequest rq = (QueryRequest) argument;
                        final String url = "/typedefinition.js?start=1&pagesize=200&fetch=ObjectID%2CAttributes&order=ObjectID&query=%28Name+%3D+Defect%29";
                        return url.equals(rq.toUrl());
                    }
                }))).thenReturn(new QueryResponse(new String(Files
                        .readAllBytes(new File("src/test/resources/rally/TypeDefinition.json").toPath()))));
                when(rallyRestApi.query(argThat(new ArgumentMatcher<QueryRequest>() {
                    @Override
                    public boolean matches(Object argument) {
                        if (argument == null)
                            return false;
                        QueryRequest rq = (QueryRequest) argument;
                        String url = "/TypeDefinition/36321741237/Attributes?start=1&pagesize=200&fetch=AllowedValues%2CElementName%2CName%2CRequired%2CType%2CObjectID%2CReadOnly&order=ObjectID";
                        return url.equals(rq.toUrl());

                    }
                }))).thenReturn(new QueryResponse(new String(Files.readAllBytes(
                        new File("src/test/resources/rally/AttributeDefinition.json").toPath()))));
                when(rallyRestApi.query(argThat(new ArgumentMatcher<QueryRequest>() {
                    @Override
                    public boolean matches(Object argument) {
                        if (argument == null)
                            return false;
                        QueryRequest rq = (QueryRequest) argument;
                        String url = "/AttributeDefinition/-12537/AllowedValues?start=1&pagesize=200&fetch=StringValue&order=ObjectID";
                        return url.equals(rq.toUrl());
                    }
                }))).thenReturn(new QueryResponse(new String(
                        Files.readAllBytes(new File("src/test/resources/rally/AllowedValue.json").toPath()))));
                when(rallyRestApi.query(argThat(new ArgumentMatcher<QueryRequest>() {
                    @Override
                    public boolean matches(Object argument) {
                        if (argument == null)
                            return false;
                        QueryRequest rq = (QueryRequest) argument;
                        String url = "/defect.js?start=1&pagesize=1&fetch=true&order=ObjectID";
                        return url.equals(rq.toUrl());
                    }
                }))).thenReturn(new QueryResponse(new String(
                        Files.readAllBytes(new File("src/test/resources/rally/Defect.json").toPath()))));
                when(rallyRestApi.query(argThat(new ArgumentMatcher<QueryRequest>() {
                    @Override
                    public boolean matches(Object argument) {
                        if (argument == null)
                            return false;
                        QueryRequest rq = (QueryRequest) argument;
                        String url = "/defect.js?start=1&pagesize=200&fetch=true&order=ObjectID&query=%28FormattedID+%3D+DE1%29";
                        return url.equals(rq.toUrl());
                    }
                }))).thenReturn(new QueryResponse(new String(
                        Files.readAllBytes(new File("src/test/resources/rally/Defect.json").toPath()))));
                when(rallyRestApi.query(argThat(new ArgumentMatcher<QueryRequest>() {
                    @Override
                    public boolean matches(Object argument) {
                        if (argument == null)
                            return false;
                        QueryRequest rq = (QueryRequest) argument;
                        String url = "/defect.js?start=1&pagesize=200&fetch=true&order=ObjectID&query=%28Name+contains+test%29";
                        return url.equals(rq.toUrl());
                    }
                }))).thenReturn(new QueryResponse(new String(
                        Files.readAllBytes(new File("src/test/resources/rally/Defect.json").toPath()))));
                when(rallyRestApi.create(argThat(new ArgumentMatcher<CreateRequest>() {
                    @Override
                    public boolean matches(Object argument) {
                        if (argument == null)
                            return false;
                        CreateRequest rq = (CreateRequest) argument;
                        String url = "/defect/create.js?fetch=true";
                        return url.equals(rq.toUrl());
                    }
                }))).thenReturn(new CreateResponse(new String(
                        Files.readAllBytes(new File("src/test/resources/rally/CreateTicket.json").toPath()))));
                when(rallyRestApi.update(argThat(new ArgumentMatcher<UpdateRequest>() {
                    @Override
                    public boolean matches(Object argument) {
                        if (argument == null)
                            return false;
                        UpdateRequest rq = (UpdateRequest) argument;
                        String url = "/defect/51333816331.js?fetch=true";
                        return url.equals(rq.toUrl());
                    }
                }))).thenReturn(new UpdateResponse(new String(
                        Files.readAllBytes(new File("src/test/resources/rally/UpdateTicket.json").toPath()))));
            } catch (IOException e) {

            }
            return rallyRestApi;
        }
    };
}

From source file:edu.si.services.camel.fcrepo.FcrepoIntegrationTest.java

private static void ingest(String pid, Path payload) throws IOException {
    if (!checkObjectExist(pid)) {
        String ingestURI = FEDORA_URI + "/objects/" + pid
                + "?format=info:fedora/fedora-system:FOXML-1.1&ignoreMime=true";

        logger.debug("INGEST URI = {}", ingestURI);

        HttpPost ingest = new HttpPost(ingestURI);
        ingest.setEntity(new ByteArrayEntity(Files.readAllBytes(payload)));
        ingest.setHeader("Content-type", MediaType.TEXT_XML);
        try (CloseableHttpResponse pidRes = httpClient.execute(ingest)) {
            assertEquals("Failed to ingest " + pid + "!", SC_CREATED, pidRes.getStatusLine().getStatusCode());
            logger.info("Ingested test object {}", EntityUtils.toString(pidRes.getEntity()));
        }/*from  ww  w  . j a  va2  s.c  om*/
    }
}