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.google.gerrit.pgm.init.InitAdminUser.java

private AccountSshKey createSshKey(Account.Id id, String keyFile) throws IOException {
    Path p = Paths.get(keyFile);
    if (!Files.exists(p)) {
        throw new IOException(String.format("Cannot add public SSH key: %s is not a file", keyFile));
    }/*from w w w.  j  av a 2s.  c o  m*/
    String content = new String(Files.readAllBytes(p), UTF_8);
    return new AccountSshKey(new AccountSshKey.Id(id, 1), content);
}

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

@Override
public byte[] getBytesByURI(final String resourceURI, final String tenantID) throws IOException {
    return Files.readAllBytes(Paths.get(getAbsolutePath(resourceURI, tenantID)));
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

/**
 * read Public Key From File/* www .  j  ava2s.c  om*/
 * @param filePath
 * @return PublicKey
 * @throws IOException
 */
public PublicKey readPublicKeyFromFile(String filePath) throws Exception {
    // Read file to a byte array.
    Path path = Paths.get(filePath);
    byte[] pubKeyByteArray = Files.readAllBytes(path);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(pubKeyByteArray);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
}

From source file:de.alpharogroup.crypto.key.reader.PrivateKeyReader.java

/**
 * Read the private key from a pem file as base64 encoded {@link String} value.
 *
 * @param file/*w  w w  .  jav a 2 s . c o  m*/
 *            the file in pem format that contains the private key.
 * @return the base64 encoded {@link String} value.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static String readPemFileAsBase64(final File file) throws IOException {
    final byte[] keyBytes = Files.readAllBytes(file.toPath());
    final String privateKeyAsBase64String = new String(keyBytes).replace(BEGIN_RSA_PRIVATE_KEY_PREFIX, "")
            .replace(END_RSA_PRIVATE_KEY_SUFFIX, "").trim();
    return privateKeyAsBase64String;
}

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

public StreamedContent getImageThumbnail() 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();
    } else {/*from w  ww.  j av a2  s  . c om*/
        String path = GlobalsBean.destThumbnail + GlobalsBean.separator
                + context.getExternalContext().getRequestParameterMap().get("imageID");
        Path filePath = Paths.get(path);
        byte[] data = Files.readAllBytes(filePath);
        return new DefaultStreamedContent(new ByteArrayInputStream(data));
    }
}

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

public String findStartPage(final Path metadataPath) {
    final String json;
    try {//from  w ww .j  a  v  a 2 s .  co  m
        json = new String(Files.readAllBytes(metadataPath), "UTF-8");
    } catch (IOException e) {
        LOG.error("Error in determining if it is a cms zip resource: {}", e.getLocalizedMessage());
        throw new ResourceAccessError("Zip " + metadataPath.getFileName() + " cannot be read. ");
    }

    final Map<String, Object> map = gsonJsonParser.parseMap(json);

    String startPage;
    if (map.get(METADATA_STARTPAGE) != null) {
        startPage = (String) map.get(METADATA_STARTPAGE);
    } else if (map.get(METADATA_STARTPAGE_CAMEL) != null) {
        startPage = (String) map.get(METADATA_STARTPAGE_CAMEL);
    } else {
        throw new ResourceAccessError("Start page in Zip " + metadataPath.getFileName() + " cannot be found");
    }

    return startPage;
}

From source file:org.alienlabs.hatchetharry.service.DataGenerator.java

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = { "PATH_TRAVERSAL_IN",
        "PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS" }, justification = "the difference is in fake.setDeckArchive() ")
@Override//from  w ww  . j a  va 2s  .  c  o  m
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public void afterPropertiesSet() throws Exception {
    if ((this.generateCardCollection) && (this.cardCollectionDao.count() == 0)) {
        try {
            final JAXBContext context = JAXBContext.newInstance(CardCollectionRootElement.class);
            final Unmarshaller um = context.createUnmarshaller();
            final CardCollectionRootElement cardCollection = (CardCollectionRootElement) um
                    .unmarshal(new File(ResourceBundle.getBundle(DataGenerator.class.getCanonicalName())
                            .getString("AllCardsInCollectionUntilReturnToRavnica")));

            final Object[] array = cardCollection.getCardCollectionList().toArray();

            for (final Object element : array) {
                this.cardCollectionDao.save((CardCollection) element);
            }
        } catch (final JAXBException e) {
            LOGGER.error("Error while generating card collection!", e);
        }
    }

    if ((this.generateData) && (null == this.persistenceService.getDeckArchiveByName("Aura Bant"))) {
        final Path path = Paths.get(
                ResourceBundle.getBundle(DataGenerator.class.getCanonicalName()).getString("AuraBantDeck"));
        final byte[] content = Files.readAllBytes(path);
        final String deckContent = new String(content, "UTF-8");
        this.importDeckService.importDeck(deckContent, "Aura Bant", false);
    }

    DataGenerator.LOGGER.info("preparing to import decks");

    if (((null == this.persistenceService.getDeckArchiveByName("aggro-combo Red / Black"))
            && (null == this.persistenceService.getDeckArchiveByName("burn mono-Red")))
            || ((this.persistenceService.getDeckByDeckArchiveName("aggro-combo Red / Black").getCards()
                    .isEmpty())
                    || (this.persistenceService.getDeckByDeckArchiveName("burn mono-Red").getCards()
                            .isEmpty()))) {
        DataGenerator.LOGGER.info("importing decks");

        final DeckArchive da1;
        final DeckArchive da2;
        final Deck deck1;
        final Deck deck2;

        if (null == this.persistenceService.getDeckArchiveByName("aggro-combo Red / Black")) {
            da1 = new DeckArchive();
            da1.setDeckName("aggro-combo Red / Black");
            this.persistenceService.saveOrUpdateDeckArchive(da1);
            deck1 = new Deck();
            deck1.setPlayerId(1L);
            deck1.setDeckArchive(da1);
        } else {
            da1 = this.persistenceService.getDeckArchiveByName("aggro-combo Red / Black");
            deck1 = this.persistenceService.getDeckByDeckArchiveName("aggro-combo Red / Black");
        }

        if (null == this.persistenceService.getDeckArchiveByName("burn mono-Red")) {
            da2 = new DeckArchive();
            da2.setDeckName("burn mono-Red");
            this.persistenceService.saveOrUpdateDeckArchive(da2);
            deck2 = new Deck();
            deck2.setPlayerId(2L);
            deck2.setDeckArchive(da2);
        } else {
            da2 = this.persistenceService.getDeckArchiveByName("burn mono-Red");
            deck2 = this.persistenceService.getDeckByDeckArchiveName("burn mono-Red");
        }

        for (int j = 1; j < 3; j++) {
            if (((j == 1) && ((deck1.getCards() == null) || (deck1.getCards().isEmpty())))
                    || (((j == 2) && ((deck2.getCards() == null) || (deck2.getCards().isEmpty()))))) {
                for (int i = 0; i < 60; i++) {
                    // A CollectibleCard can be duplicated: lands, normal
                    // cards
                    //
                    MagicCard card = null;

                    final CollectibleCard cc = new CollectibleCard();
                    cc.setTitle(j == 1 ? DataGenerator.TITLES1[i] : DataGenerator.TITLES2[i]);
                    cc.setDeckArchiveId(j == 1 ? da1.getDeckArchiveId() : da2.getDeckArchiveId());

                    // A CollectibleCard can be duplicated: lands, normal
                    // cards
                    // which may be present 4 times in a Deck...
                    this.persistenceService.saveCollectibleCard(cc);

                    if (j == 1) {
                        card = new MagicCard("cards/" + DataGenerator.TITLES1[i] + "_small.jpg",
                                "cards/" + DataGenerator.TITLES1[i] + ".jpg",
                                "cards/" + DataGenerator.TITLES1[i] + "Thumb.jpg", DataGenerator.TITLES1[i], "",
                                "", null, Integer.valueOf(0));
                        card.setDeck(deck1);
                    } else {
                        card = new MagicCard("cards/" + DataGenerator.TITLES2[i] + "_small.jpg",
                                "cards/" + DataGenerator.TITLES2[i] + ".jpg",
                                "cards/" + DataGenerator.TITLES2[i] + "Thumb.jpg", DataGenerator.TITLES2[i], "",
                                "", null, Integer.valueOf(0));
                        card.setDeck(deck2);
                    }

                    card.setGameId(-1L);
                    card.setUuidObject(UUID.randomUUID());
                    card.setX(16L);
                    card.setY(16L);
                    card.setZone(CardZone.LIBRARY);

                    if (j == 1) {
                        final List<MagicCard> cards = deck1.getCards();
                        cards.add(card);
                        deck1.setCards(cards);
                    } else {
                        final List<MagicCard> cards = deck2.getCards();
                        cards.add(card);
                        deck2.setCards(cards);
                    }
                }
            } else {
                if (j == 1) {
                    final List<MagicCard> cards = this.persistenceService
                            .getAllCardsFromDeck("aggro-combo Red / Black");
                    deck1.setCards(cards);
                } else {
                    final List<MagicCard> cards = this.persistenceService.getAllCardsFromDeck("burn mono-Red");
                    deck2.setCards(cards);
                }
            }

            if (j == 1) {
                this.persistenceService.saveOrUpdateDeck(deck1);
                this.persistenceService.saveOrUpdateDeckArchive(da1);
                DataGenerator.LOGGER.info("updated deck 1");
            } else {
                this.persistenceService.saveOrUpdateDeck(deck2);
                this.persistenceService.saveOrUpdateDeckArchive(da2);
                DataGenerator.LOGGER.info("updated deck 2");
            }
        }
    }
}

From source file:org.jetbrains.webdemo.examples.ExamplesLoader.java

private static void loadDefaultFiles(String folderPath, String projectId, List<ProjectFile> files,
        boolean loadTestVersion) throws IOException {
    File solutionFile = new File(folderPath + File.separator + "Solution.kt");
    File testFile = new File(folderPath + File.separator + "Test.kt");
    File taskFile = new File(folderPath + File.separator + "Task.kt");

    if (testFile.exists() && !isAlreadyLoaded(files, testFile.getName())) {
        String testText = new String(Files.readAllBytes(testFile.toPath())).replaceAll("\r\n", "\n");
        files.add(0, new TestFile(testText, projectId + "/" + testFile.getName()));
    }/*from   w  w w.j av a  2  s. c om*/

    if (loadTestVersion) {
        if (solutionFile.exists() && !isAlreadyLoaded(files, solutionFile.getName())) {
            String solutionText = new String(Files.readAllBytes(solutionFile.toPath())).replaceAll("\r\n",
                    "\n");
            files.add(0, new SolutionFile(solutionText, projectId + "/" + solutionFile.getName()));
        }
    } else {
        if (taskFile.exists() && !isAlreadyLoaded(files, taskFile.getName())) {
            String solutionText = new String(Files.readAllBytes(solutionFile.toPath())).replaceAll("\r\n",
                    "\n");
            String taskText = new String(Files.readAllBytes(taskFile.toPath())).replaceAll("\r\n", "\n");
            files.add(0, new TaskFile(taskText, solutionText, projectId + "/" + taskFile.getName()));
        }
    }

}

From source file:edu.harvard.iq.dataverse.api.imports.ImportServiceBean.java

@TransactionAttribute(REQUIRES_NEW)
public JsonObjectBuilder handleFile(DataverseRequest dataverseRequest, Dataverse owner, File file,
        ImportType importType, PrintWriter validationLog, PrintWriter cleanupLog)
        throws ImportException, IOException {

    System.out.println("handling file: " + file.getAbsolutePath());
    String ddiXMLToParse;/*from  w w  w. jav a  2s  .co  m*/
    try {
        ddiXMLToParse = new String(Files.readAllBytes(file.toPath()));
        JsonObjectBuilder status = doImport(dataverseRequest, owner, ddiXMLToParse,
                file.getParentFile().getName() + "/" + file.getName(), importType, cleanupLog);
        status.add("file", file.getName());
        logger.log(Level.INFO, "completed doImport {0}/{1}",
                new Object[] { file.getParentFile().getName(), file.getName() });
        return status;
    } catch (ImportException ex) {
        String msg = "Import Exception processing file " + file.getParentFile().getName() + "/" + file.getName()
                + ", msg:" + ex.getMessage();
        logger.info(msg);
        if (validationLog != null) {
            validationLog.println(msg);
        }
        return Json.createObjectBuilder().add("message", "Import Exception processing file "
                + file.getParentFile().getName() + "/" + file.getName() + ", msg:" + ex.getMessage());
    } catch (IOException e) {
        Throwable causedBy = e.getCause();
        while (causedBy != null && causedBy.getCause() != null) {
            causedBy = causedBy.getCause();
        }
        String stackLine = "";
        if (causedBy != null && causedBy.getStackTrace() != null && causedBy.getStackTrace().length > 0) {
            stackLine = causedBy.getStackTrace()[0].toString();
        }
        String msg = "Unexpected Error in handleFile(), file:" + file.getParentFile().getName() + "/"
                + file.getName();
        if (e.getMessage() != null) {
            msg += "message: " + e.getMessage();
        }
        msg += ", caused by: " + causedBy;
        if (causedBy != null && causedBy.getMessage() != null) {
            msg += ", caused by message: " + causedBy.getMessage();
        }
        msg += " at line: " + stackLine;

        validationLog.println(msg);
        e.printStackTrace();

        return Json.createObjectBuilder().add("message", "Unexpected Exception processing file "
                + file.getParentFile().getName() + "/" + file.getName() + ", msg:" + e.getMessage());

    }
}

From source file:com.thoughtworks.go.server.service.plugins.AnalyticsPluginAssetsServiceTest.java

@Test
public void onPluginMetadataLoad_shouldCopyPluginEndpointJsWhenCachingPluginStaticAssets() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);

    addAnalyticsPluginInfoToStore(PLUGIN_ID);
    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);
    when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive());

    assetsService.onPluginMetadataCreate(PLUGIN_ID);

    Path actualPath = Paths.get(railsRoot.getAbsolutePath(), "public", assetsService.assetPathFor(PLUGIN_ID),
            "analytics-endpoint.js");

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(actualPath.toFile().exists());
    byte[] expected = IOUtils.toByteArray(getClass().getResourceAsStream("/plugin-endpoint.js"));
    assertArrayEquals("Content of plugin-endpoint.js should be preserved", expected,
            Files.readAllBytes(actualPath));
}