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.spotify.helios.agent.AgentService.java

/**
 * Create a new agent instance.// www.  j  a  v a  2s  .  co  m
 *
 * @param config The service configuration.
 * @param environment The DropWizard environment.
 * @throws ConfigurationException If an error occurs with the DropWizard configuration.
 * @throws InterruptedException If the thread is interrupted.
 * @throws IOException IOException
 */
public AgentService(final AgentConfig config, final Environment environment)
        throws ConfigurationException, InterruptedException, IOException {
    // Create state directory, if necessary
    final Path stateDirectory = config.getStateDirectory().toAbsolutePath().normalize();
    if (!Files.exists(stateDirectory)) {
        try {
            Files.createDirectories(stateDirectory);
        } catch (IOException e) {
            log.error("Failed to create state directory: {}", stateDirectory, e);
            throw Throwables.propagate(e);
        }
    }

    // Take a file lock in the state directory to ensure this is the only agent using it
    final Path lockPath = config.getStateDirectory().resolve("lock");
    try {
        stateLockFile = FileChannel.open(lockPath, CREATE, WRITE);
        stateLock = stateLockFile.tryLock();
        if (stateLock == null) {
            throw new IllegalStateException("State lock file already locked: " + lockPath);
        }
    } catch (OverlappingFileLockException e) {
        throw new IllegalStateException("State lock file already locked: " + lockPath);
    } catch (IOException e) {
        log.error("Failed to take state lock: {}", lockPath, e);
        throw Throwables.propagate(e);
    }

    final Path idPath = config.getStateDirectory().resolve("id");
    final String id;
    try {
        if (Files.exists(idPath)) {
            id = new String(Files.readAllBytes(idPath), UTF_8);
        } else {
            id = config.getId();
            Files.write(idPath, id.getBytes(UTF_8));
        }
    } catch (IOException e) {
        log.error("Failed to set up id file: {}", idPath, e);
        throw Throwables.propagate(e);
    }

    // Configure metrics
    final MetricRegistry metricsRegistry = environment.metrics();
    final RiemannSupport riemannSupport = new RiemannSupport(metricsRegistry, config.getRiemannHostPort(),
            config.getName(), "helios-agent");
    final RiemannFacade riemannFacade = riemannSupport.getFacade();
    if (config.isInhibitMetrics()) {
        log.info("Not starting metrics");
        metrics = new NoopMetrics();
    } else {
        log.info("Starting metrics");
        metrics = new MetricsImpl(metricsRegistry, MetricsImpl.Type.AGENT);
        environment.lifecycle().manage(riemannSupport);
        if (!Strings.isNullOrEmpty(config.getStatsdHostPort())) {
            environment.lifecycle()
                    .manage(new ManagedStatsdReporter(config.getStatsdHostPort(), metricsRegistry));
        }

        final FastForwardConfig ffwdConfig = config.getFfwdConfig();
        if (ffwdConfig != null) {
            environment.lifecycle().manage(FastForwardReporter.create(metricsRegistry, ffwdConfig.getAddress(),
                    ffwdConfig.getMetricKey(), ffwdConfig.getReportingIntervalSeconds()));
        }
    }

    // This CountDownLatch will signal EnvironmentVariableReporter and LabelReporter when to report
    // data to ZK. They only report once and then stop, so we need to tell them when to start
    // reporting otherwise they'll race with ZooKeeperRegistrarService and might have their data
    // erased if they are too fast.
    final CountDownLatch zkRegistrationSignal = new CountDownLatch(1);

    this.zooKeeperClient = setupZookeeperClient(config, id, zkRegistrationSignal);
    final DockerHealthChecker dockerHealthChecker = new DockerHealthChecker(metrics.getSupervisorMetrics(),
            TimeUnit.SECONDS, 30, riemannFacade);
    environment.lifecycle().manage(dockerHealthChecker);
    environment.lifecycle().manage(new RiemannHeartBeat(TimeUnit.MINUTES, 2, riemannFacade));

    // Set up model
    final ZooKeeperModelReporter modelReporter = new ZooKeeperModelReporter(riemannFacade,
            metrics.getZooKeeperMetrics());
    final ZooKeeperClientProvider zkClientProvider = new ZooKeeperClientProvider(zooKeeperClient,
            modelReporter);
    final KafkaClientProvider kafkaClientProvider = new KafkaClientProvider(config.getKafkaBrokers());

    final TaskHistoryWriter historyWriter;
    if (config.isJobHistoryDisabled()) {
        historyWriter = null;
    } else {
        historyWriter = new TaskHistoryWriter(config.getName(), zooKeeperClient,
                stateDirectory.resolve(TASK_HISTORY_FILENAME));
    }

    try {
        this.model = new ZooKeeperAgentModel(zkClientProvider, kafkaClientProvider, config.getName(),
                stateDirectory, historyWriter);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    // Set up service registrar
    this.serviceRegistrar = createServiceRegistrar(config.getServiceRegistrarPlugin(),
            config.getServiceRegistryAddress(), config.getDomain());

    final ZooKeeperNodeUpdaterFactory nodeUpdaterFactory = new ZooKeeperNodeUpdaterFactory(zooKeeperClient);

    final DockerClient dockerClient;
    if (isNullOrEmpty(config.getDockerHost().dockerCertPath())) {
        dockerClient = new PollingDockerClient(config.getDockerHost().uri());
    } else {
        final Path dockerCertPath = java.nio.file.Paths.get(config.getDockerHost().dockerCertPath());
        final DockerCertificates dockerCertificates;
        try {
            dockerCertificates = new DockerCertificates(dockerCertPath);
        } catch (DockerCertificateException e) {
            throw Throwables.propagate(e);
        }

        dockerClient = new PollingDockerClient(config.getDockerHost().uri(), dockerCertificates);
    }

    final DockerClient monitoredDockerClient = MonitoredDockerClient.wrap(riemannFacade, dockerClient);

    this.hostInfoReporter = new HostInfoReporter((OperatingSystemMXBean) getOperatingSystemMXBean(),
            nodeUpdaterFactory, config.getName(), dockerClient, config.getDockerHost(), 1, TimeUnit.MINUTES,
            zkRegistrationSignal);

    this.agentInfoReporter = new AgentInfoReporter(getRuntimeMXBean(), nodeUpdaterFactory, config.getName(), 1,
            TimeUnit.MINUTES, zkRegistrationSignal);

    this.environmentVariableReporter = new EnvironmentVariableReporter(config.getName(), config.getEnvVars(),
            nodeUpdaterFactory, zkRegistrationSignal);

    this.labelReporter = new LabelReporter(config.getName(), config.getLabels(), nodeUpdaterFactory,
            zkRegistrationSignal);

    final String namespace = "helios-" + id;

    final List<ContainerDecorator> decorators = Lists.newArrayList();

    if (!isNullOrEmpty(config.getRedirectToSyslog())) {
        decorators.add(new SyslogRedirectingContainerDecorator(config.getRedirectToSyslog()));
    }

    if (!config.getBinds().isEmpty()) {
        decorators.add(new BindVolumeContainerDecorator(config.getBinds()));
    }

    if (!config.getExtraHosts().isEmpty()) {
        decorators.add(new AddExtraHostContainerDecorator(config.getExtraHosts()));
    }

    final SupervisorFactory supervisorFactory = new SupervisorFactory(model, monitoredDockerClient,
            config.getEnvVars(), serviceRegistrar, decorators, config.getDockerHost(), config.getName(),
            metrics.getSupervisorMetrics(), namespace, config.getDomain(), config.getDns());

    final ReactorFactory reactorFactory = new ReactorFactory();

    final PortAllocator portAllocator = new PortAllocator(config.getPortRangeStart(), config.getPortRangeEnd());

    final PersistentAtomicReference<Map<JobId, Execution>> executions;
    try {
        executions = PersistentAtomicReference.create(stateDirectory.resolve("executions.json"),
                JOBID_EXECUTIONS_MAP, Suppliers.ofInstance(EMPTY_EXECUTIONS));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    final Reaper reaper = new Reaper(dockerClient, namespace);
    this.agent = new Agent(model, supervisorFactory, reactorFactory, executions, portAllocator, reaper);

    final ZooKeeperHealthChecker zkHealthChecker = new ZooKeeperHealthChecker(zooKeeperClient,
            Paths.statusHosts(), riemannFacade, TimeUnit.MINUTES, 2);
    environment.lifecycle().manage(zkHealthChecker);

    if (!config.getNoHttp()) {

        environment.healthChecks().register("docker", dockerHealthChecker);
        environment.healthChecks().register("zookeeper", zkHealthChecker);

        // Report health checks as a gauge metric
        environment.healthChecks().getNames().forEach(name -> environment.metrics()
                .register("helios." + name + ".ok", new HealthCheckGauge(environment.healthChecks(), name)));

        environment.jersey().register(new AgentModelTaskResource(model));
        environment.jersey().register(new AgentModelTaskStatusResource(model));
        environment.lifecycle().manage(this);

        this.server = ServiceUtil
                .createServerFactory(config.getHttpEndpoint(), config.getAdminEndpoint(), config.getNoHttp())
                .build(environment);
    } else {
        this.server = null;
    }
    environment.lifecycle().manage(this);
}

From source file:com.sastix.cms.server.controllers.ResourceController.java

@RequestMapping(value = "/v" + Constants.REST_API_1_0 + "/" + Constants.GET_DATA, method = RequestMethod.POST)
public byte[] getData(@Valid @RequestBody DataDTO dataDTO, HttpServletResponse response, BindingResult result)
        throws ContentValidationException, ResourceAccessError, IOException {
    LOG.trace(Constants.GET_DATA);/* w  ww.  j a va  2s.co  m*/
    final Path responseFile = resourceService.getDataPath(dataDTO);
    final byte[] responseData = Files.readAllBytes(responseFile);
    final String mimeType = tika.detect(responseData);
    response.setContentType(mimeType);
    response.setContentLength(responseData.length);
    return responseData;
}

From source file:com.ccserver.digital.controller.AdminControllerTest.java

@Test
public void downloadApplication() throws IOException {
    CreditCardApplicationDTO ccApp = getCreditCardApplicationDTOMock(1L);
    Mockito.when(ccAppService.getApplication(1L)).thenReturn(ccApp);

    File ifile = new File("./src/main/resources/sample");
    Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf");
    byte[] idDocByteArray = Files.readAllBytes(idDocPath);

    Map<String, byte[]> docs = new HashMap<String, byte[]>();
    docs.put("abc", idDocByteArray);

    Mockito.when(docsService.getFullDocumentsByApplicationId(1L)).thenReturn(docs);

    Mockito.when(response.getOutputStream()).thenReturn(servletOutputStream);

    Mockito.when(zipFileService.zipIt(docs)).thenReturn(idDocByteArray);

    // when/*from  w  w  w  . j  a  v  a  2 s.  c om*/
    ResponseEntity<?> application = controller.downloadApplication(1L, response);

    // then
    Assert.assertEquals(HttpStatus.OK, application.getStatusCode());
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

/**
 * Read public key from file./*from   w ww.ja  va 2  s  .c  o  m*/
 * @param filePath
 * @return
 * @throws IOException
 */
public PrivateKey readPrivateKeyFromFile(String filePath) throws Exception {
    // Read file to a byte array.
    String privateKeyFileName = filePath;
    Path path = Paths.get(privateKeyFileName);
    byte[] privKeyByteArray = Files.readAllBytes(path);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyByteArray);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey myPrivKey = keyFactory.generatePrivate(keySpec);
    return myPrivKey;
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGeneratorSmokeTest.java

@Test
public void runSmokeTestInlineExplicitMapping() throws IOException, CodeGenerationException {
    // XXX: only really checks #resolve()
    URI rootUri = URI.create("http://example.com/");

    Path outputDirectory = fs.getPath("output");
    generator.setOutputDirectory(outputDirectory);

    SchemaLoader schemas = loadSchema(rootUri, "/schemas/inline.json");
    generator.setSchemaLoader(schemas);/*from w ww.  ja  va  2s  .c  o m*/

    Mapping rootMapping = new Mapping(URI.create("http://example.com/schemas/inline.json#"),
            new ClassName("com.example.test.schemas", "WithInline"));
    generator.addMapping(rootMapping.getTarget(), rootMapping);

    Mapping inlineMapping = new Mapping(URI.create("http://example.com/schemas/inline.json#/properties/inline"),
            new ClassName("com.example.test.schemas", "Inline"));
    generator.addMapping(inlineMapping.getTarget(), inlineMapping);

    generator.generate(rootMapping.getTarget());
    generator.generate(inlineMapping.getTarget());

    Path generatedTypeFile = outputDirectory.resolve("com/example/test/schemas/WithInline.java");
    assertTrue(Files.exists(generatedTypeFile));
    System.out.println(new String(Files.readAllBytes(generatedTypeFile), StandardCharsets.UTF_8));
    Path generatedInlineTypeFile = outputDirectory.resolve("com/example/test/schemas/Inline.java");
    assertTrue(Files.exists(generatedInlineTypeFile));
}

From source file:dyco4j.instrumentation.internals.CLI.java

private static void getMemberId2NameMapping(final Collection<Path> filenames, final ProgramData programData) {
    for (final Path _arg : filenames) {
        try {//from  ww  w  .j a va2s .c o  m
            final ClassReader _cr = new ClassReader(Files.readAllBytes(_arg));
            final ClassVisitor _cv = new ProgramDataCollectingClassVisitor(programData);
            _cr.accept(_cv, 0);
        } catch (final Exception _ex) {
            throw new RuntimeException(_ex);
        }
    }
}

From source file:com.pentaho.ctools.issues.cda.CDAExportToXls.java

/**
 * ############################### Test Case 1 ###############################
 *
 * Test Case Name://from   www .  ja  v a 2s .co m
 *    Asserting that export to excel follows output options
 * Description:
 *    The test pretends validate the CDA-100 issue, asserting that export to excel follows output options.
 *
 * Steps:
 *    1. Select "Sample query on SampleData - Jdbc" on "dataAccessSelector"
 *    2. Wait for and assert elements and text on page
 *    3. Export file and assure it has same md5 as expected
 *
 */
@Test
public void tc01_CdaFileViewer_ExportOutputOptions() {
    this.log.info("tc01_CdaFileViewer_ExportOutputOption");

    /*
     * ## Step 1
     */
    //Open sample CDA file
    driver.get(baseUrl + "plugin/cda/api/previewQuery?path=/public/Issues/CDA/CDA-100/CDA-100.cda");

    //wait for invisibility of waiting pop-up
    this.elemHelper.WaitForElementInvisibility(driver,
            By.xpath("//div[@class='busy-indicator-container waitPopup']"), 180);

    //Wait for buttons: button, Cache This AND Query URL
    WebElement DataSelector = this.elemHelper.WaitForElementPresenceAndVisible(driver,
            By.id("dataAccessSelector"));
    assertNotNull(DataSelector);
    Select select = new Select(this.elemHelper.FindElement(driver, By.id("dataAccessSelector")));
    select.selectByVisibleText("Sql Query on SampleData - Jdbc");
    this.elemHelper.FindElement(driver, By.cssSelector("div.blockUI.blockOverlay"));
    this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay"), 180);
    WebElement cacheButton = this.elemHelper.WaitForElementPresenceAndVisible(driver,
            By.xpath("//button[@id='cachethis']"));
    assertNotNull(cacheButton);
    WebElement queryButton = this.elemHelper.WaitForElementPresenceAndVisible(driver,
            By.xpath("//button[@id='queryUrl']"));
    assertNotNull(queryButton);
    WebElement refreshButton = this.elemHelper.WaitForElementPresenceAndVisible(driver,
            By.xpath("//button[@id='button']"));
    assertNotNull(refreshButton);

    /*
     * ## Step 2
     */
    //wait to render page
    this.elemHelper.WaitForElementInvisibility(driver, By.cssSelector("div.blockUI.blockOverlay"), 180);

    //Check the presented contains
    WebElement elemStatus = this.elemHelper.FindElement(driver, By.id("status"));
    assertEquals("Shipped", elemStatus.getAttribute("value"));
    elemStatus = this.elemHelper.FindElement(driver, By.id("orderDate"));
    assertEquals("2003-03-01", elemStatus.getAttribute("value"));

    //Check text on table
    String columnOneRowOne = this.elemHelper.WaitForElementPresentGetText(driver,
            By.xpath("//table[@id='contents']/tbody/tr/td"));
    String columnTwoRowOne = this.elemHelper.WaitForElementPresentGetText(driver,
            By.xpath("//table[@id='contents']/tbody/tr/td[2]"));
    assertEquals("S10_1678", columnOneRowOne);
    assertEquals("10107", columnTwoRowOne);

    /*
     * ## Step 3
     */
    WebElement buttonExport = this.elemHelper.FindElement(driver, By.id("export"));
    assertNotNull(buttonExport);
    try {
        //Delete the existence if exist
        new File(this.exportFilePath).delete();

        //Click to export
        buttonExport.click();

        //Wait for file to be created in the destination dir
        DirectoryWatcher dw = new DirectoryWatcher();
        dw.WatchForCreate(downloadDir);

        //Check if the file really exist
        File exportFile = new File(this.exportFilePath);
        // assertTrue(exportFile.exists());

        //Wait for the file to be downloaded totally
        for (int i = 0; i < 50; i++) { //we only try 50 times == 5000 ms
            long nSize = FileUtils.sizeOf(exportFile);
            //Since the file always contents the same data, we wait for the expected bytes
            if (nSize >= 300000) {
                break;
            }
            this.log.info("BeforeSleep " + nSize);
            Thread.sleep(100);
        }

        this.log.info("File size :" + FileUtils.sizeOf(exportFile));

        //Check if the file downloaded is the expected
        String md5 = DigestUtils.md5Hex(Files.readAllBytes(exportFile.toPath()));
        assertEquals(md5, "f87ea229efc4da71d47a90ef2029564d");

        //The delete file
        DeleteFile();

    } catch (Exception e) {
        this.log.error(e.getMessage());
    }
}

From source file:com.tocsi.images.ImageListBean.java

public StreamedContent getImageFullSize() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
        // So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL.
        return new DefaultStreamedContent();
        //return null;
    } else {//from w w  w.j  a  va  2  s. c  o  m
        String path = GlobalsBean.destOriginal + GlobalsBean.separator + imageFileName;
        Path filePath = Paths.get(path);
        byte[] data = Files.readAllBytes(filePath);
        return new DefaultStreamedContent(new ByteArrayInputStream(data));
    }
}

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

/**
 * Generates a colon delimited hex string describing the anchor file for
 * the given proxy instance./*from   ww w  . j ava 2  s.  c om*/
 * @param conf configuration proxy properties instance
 * @return colon delimited hex string describing the anchor file
 * @throws Exception if the hash could not be computed
 */
private String anchorHash(final ConfProxyProperties conf) throws Exception {
    byte[] anchorBytes = null;
    try {
        Path anchorPath = Paths.get(conf.getProxyAnchorPath());
        anchorBytes = Files.readAllBytes(anchorPath);
    } catch (IOException e) {
        fail("Failed to load proxy '" + conf.getInstance() + "' anchor file: ", e);
    }
    String hash = CryptoUtils.hexDigest(CryptoUtils.SHA224_ID, anchorBytes);
    return StringUtils.join(hash.toUpperCase().split("(?<=\\G.{2})"), ':');
}

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final Shops delShop(String shopName, Player player) {
    try {//from  w ww .  j  av a2  s .c o m
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONArray shopList = (JSONArray) jsonObj.get("shopsArray");

        // Make sure that our array isn't empty
        if (shopList == null) {
            player.sendMessage("\u00A7e<\u00A73mcDropShop : internal error 0x00\u00A7e>");

            return this;
        } else if (jsonObj.get(shopName) == null) {
            player.sendMessage("\u00A7e<\u00A73mcDropShop : internal error 0x01\u00A7e>");

            return this;
        }

        JSONObject shopObj;

        String shopName2;
        int index;
        // Find our shop in our array         
        for (index = 0; index < shopList.size(); index++) {
            shopObj = (JSONObject) (shopList.get(index));

            shopName2 = (String) shopObj.get("shopName");

            if (shopName2.equals(shopName)) {
                break;
            }

        }

        // Remove shop from array
        shopList.remove(index);

        // Update the entire JSON table in memory
        jsonObj.put("shopsArray", shopList);

        // Now remove the shop data from the root
        jsonObj.remove(shopName);

        // Update Shops.json
        FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json");

        shopsJSON.write(jsonObj.toJSONString());

        shopsJSON.flush();
        shopsJSON.close();

        Shops.shops.remove(shopName);

        player.sendMessage("\u00a7aShop removed!");

        return this;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in addShop()");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in addShop()");
        e.printStackTrace();
    }

    return this;
}