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.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java

private void setupInsertComboBox() {
    Gson gsonInserts = new Gson();
    //Load the file with the stored offsets
    String directoryName = ij.IJ.getDirectory("ImageJ");
    String objectFilepath = directoryName.concat("OPENFLIMHCA_JSONInsertOffsets.txt");
    String JSONInString = "";
    try {//from w  ww . java2s  .  c  om
        JSONInString = new String(Files.readAllBytes(FileSystems.getDefault().getPath(objectFilepath)));
    } catch (Exception e) {
    }
    insertType.removeAllItems();
    Insert_object[] inserts = gsonInserts.fromJson(JSONInString, Insert_object[].class);
    insertOffsetInfo = new String[inserts.length][inserts[0].getClass().getDeclaredFields().length];
    //System.out.println(inserts[0].getClass().getDeclaredFields().length);
    for (int i = 0; i < inserts.length; i++) {
        insertOffsetInfo[i][0] = inserts[i].getInsertName();
        insertOffsetInfo[i][1] = inserts[i].getInsertOffsets()[0].toString();
        insertOffsetInfo[i][2] = inserts[i].getInsertOffsets()[1].toString();
        insertOffsetInfo[i][3] = inserts[i].getInsertOffsets()[2].toString();
        insertType.addItem(inserts[i].getInsertName());
    }
    InsertOffsetsloaded = true;
}

From source file:com.liferay.blade.cli.ConvertThemeCommand.java

private boolean compassSupport(String themePath) throws Exception {
    File themeDir = new File(themePath);

    File customCss = new File(themeDir, "docroot/_diffs/css/custom.css");

    if (!customCss.exists()) {
        customCss = new File(themeDir, "docroot/_diffs/css/_custom.scss");
    }//from  www . j a  va  2s.  co  m

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

    String css = new String(Files.readAllBytes(customCss.toPath()));

    Matcher matcher = _compassImport.matcher(css);

    return matcher.find();
}

From source file:edu.si.services.itest.UCT_AltId_IT.java

private static void ingest(String pid, Path payload) throws IOException {
    if (!checkObjecsExist(pid)) {
        HttpPost ingest = new HttpPost(
                FEDORA_URI + "/objects/" + pid + "?format=info:fedora/fedora-system:FOXML-1.1");
        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()));
        }/*  w w  w  .  ja v  a 2s.c  o m*/
    }
}

From source file:com.smartsheet.api.internal.SheetResourcesImplTest.java

@Test
public void testGetSheetAsExcel() throws SmartsheetException, IOException {
    File file = new File("src/test/resources/getExcel.xls");
    server.setResponseBody(file);/*from   ww  w .  j a va 2  s. co  m*/
    server.setContentType("application/vnd.ms-excel");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    sheetResource.getSheetAsExcel(1234L, output);

    assertNotNull(output);
    assertTrue(output.toByteArray().length > 0);

    //byte[] original = IOUtils.toByteArray(new FileReader(file));
    byte[] data = Files.readAllBytes(Paths.get(file.getPath()));
    assertEquals(data.length, output.toByteArray().length);
}

From source file:io.spotnext.maven.mojo.TransformTypesMojo.java

/** {@inheritDoc} */
@Override// w  w w . j a  v a2  s .  c om
public void execute() throws MojoExecutionException {
    if (skip) {
        getLog().info("Skipping type transformation!");
        return;
    }

    trackExecution("start");

    final ClassLoader classLoader = getClassloader();
    final List<ClassFileTransformer> transformers = getClassFileTransformers(classLoader);

    List<File> classFiles = FileUtils.getFiles(project.getBuild().getOutputDirectory(),
            f -> f.getAbsolutePath().endsWith(".class"));
    getLog().debug("Found class files for processing: "
            + classFiles.stream().map(f -> f.getName()).collect(Collectors.joining(", ")));

    if (CollectionUtils.isNotEmpty(transformers)) {
        if (CollectionUtils.isNotEmpty(classFiles)) {
            getLog().info(String.format("Transforming %s classes", classFiles.size()));

            for (final File f : classFiles) {
                if (f.getName().endsWith(Constants.CLASS_EXTENSION)) {
                    String relativeClassFilePath = StringUtils.remove(f.getPath(),
                            project.getBuild().getOutputDirectory());
                    relativeClassFilePath = StringUtils.removeStart(relativeClassFilePath, "/");
                    final String className = relativeClassFilePath.substring(0,
                            relativeClassFilePath.length() - Constants.CLASS_EXTENSION.length());

                    trackExecution("Loading class: " + f.getAbsolutePath());

                    byte[] byteCode;
                    try {
                        byteCode = Files.readAllBytes(f.toPath());
                    } catch (final IOException e) {
                        String message = String.format("Can't read bytecode for class %s", className);
                        buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                        throw new IllegalStateException(message, e);
                    }

                    trackExecution("Loaded class: " + f.getAbsolutePath());

                    for (final ClassFileTransformer t : transformers) {
                        try {

                            // log exceptions into separate folder, to be able to inspect them even if Eclipse swallows them ...
                            if (t instanceof AbstractBaseClassTransformer) {
                                ((AbstractBaseClassTransformer) t).setErrorLogger(this::logError);
                            }

                            // returns null if nothing has been transformed
                            byteCode = t.transform(classLoader, className, null, null, byteCode);
                        } catch (final Exception e) {
                            String exception = "Exception during transformation of class: "
                                    + f.getAbsolutePath() + "\n" + e.getMessage();
                            trackExecution(exception);
                            String message = String.format("Can't transform class %s, transformer %s: %s",
                                    className, t.getClass().getSimpleName(), ExceptionUtils.getStackTrace(e));
                            buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                            throw new MojoExecutionException(exception, e);
                        }
                    }

                    if (byteCode != null && byteCode.length > 0) {
                        try {
                            Files.write(f.toPath(), byteCode, StandardOpenOption.CREATE,
                                    StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

                            trackExecution("Saved transformed class: " + f.getAbsolutePath());
                        } catch (final IOException e) {
                            String message = "Could not write modified class: " + relativeClassFilePath;
                            buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                            throw new IllegalStateException(message);
                        } finally {
                            buildContext.refresh(f);
                            getLog().info("Applied transformation to type: " + f.getAbsolutePath());
                        }
                    } else {
                        trackExecution("No changes made for class: " + f.getAbsolutePath());
                        getLog().debug("No transformation was applied to type: " + f.getAbsolutePath());
                    }
                }
            }
        } else {
            getLog().info("No class files found");
        }

        trackExecution("All classes in build output folder transformed");

        if (includeJars) {
            final String packaging = project.getPackaging();
            final Artifact artifact = project.getArtifact();

            if ("jar".equals(packaging) && artifact != null) {
                try {
                    final File source = artifact.getFile();

                    if (source.isFile()) {
                        final File destination = new File(source.getParent(), "instrument.jar");

                        final JarTransformer transformer = new JarTransformer(getLog(), classLoader,
                                Arrays.asList(source), transformers);
                        transformer.transform(destination);

                        final File sourceRename = new File(source.getParent(),
                                "notransform-" + source.getName());

                        if (source.renameTo(sourceRename)) {
                            throw new MojoExecutionException(String.format("Could not move %s to %s",
                                    source.toString(), sourceRename.toString()));
                        }

                        if (destination.renameTo(sourceRename)) {
                            throw new MojoExecutionException(String.format("Could not move %s to %s",
                                    destination.toString(), sourceRename.toString()));
                        }

                        buildContext.refresh(destination);
                    }
                } catch (final Exception e) {
                    buildContext.addMessage(artifact.getFile(), 0, 0, e.getMessage(),
                            BuildContext.SEVERITY_ERROR, e);
                    throw new MojoExecutionException(e.getMessage(), e);
                }
            } else {
                getLog().debug(String.format("Artifact %s not a jar file",
                        artifact != null ? (artifact.getGroupId() + ":" + artifact.getArtifactId())
                                : "<null>"));
            }
        }
    } else {
        getLog().info("No class transformers configured");
    }
}

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

@Test
public void downloadDocumentAppIdMockTest() throws IOException, URISyntaxException {
    File ifile = new File("./src/main/resources/sample");
    Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf");
    byte[] idDocByteArray = Files.readAllBytes(idDocPath);

    CreditCardApplicationDocumentDTO ccAppDocDTO = new CreditCardApplicationDocumentDTO();
    ccAppDocDTO.setId(1L);/*from   w ww .  j  a va 2s .  c o  m*/
    ccAppDocDTO.setDocument(idDocByteArray);
    ccAppDocDTO.setFileName("name");
    List<CreditCardApplicationDocumentDTO> ccAppDocDTOs = new ArrayList<CreditCardApplicationDocumentDTO>();
    ccAppDocDTOs.add(ccAppDocDTO);
    CreditCardApplicationDTO ccAppDTO = getCreditCardApplicationDTOMock(1L);

    Mockito.when(mockDocService.getDocumentsByApplicationId(1L)).thenReturn(ccAppDocDTOs);
    ResponseEntity<?> response = mockDocController.downloadDocumentByAppId(1L);
    List<CreditCardApplicationDocumentDTO> result = (List<CreditCardApplicationDocumentDTO>) response.getBody();

    Assert.assertEquals(result.size(), 1);
}

From source file:fr.pilato.elasticsearch.crawler.fs.util.FsCrawlerUtil.java

/**
 * Reads a mapping from dir/version/type.json file
 *
 * @param dir Directory containing mapping files per major version
 * @param version Elasticsearch major version number (only major digit is kept so for 2.3.4 it will be 2)
 * @param type The expected type (will be expanded to type.json)
 * @return the mapping// ww w  .j a v  a  2s  . c  om
 * @throws URISyntaxException
 * @throws IOException
 */
public static String readMapping(Path dir, String version, String type) throws URISyntaxException, IOException {
    Path file = dir.resolve(version).resolve(type + ".json");
    return new String(Files.readAllBytes(file), "UTF-8");
}

From source file:com.grillecube.engine.renderer.model.json.JSONHelper.java

/**
 * return a String which contains the full file bytes
 * /*from   w w  w  .  j a  v a 2s .  c  om*/
 * @throws IOException
 */
public static String readFile(File file) throws IOException {
    if (!file.exists()) {
        throw new IOException("Couldnt read model file. (It doesnt exists: " + file.getPath() + ")");
    }
    if (file.isDirectory()) {
        throw new IOException("Couldnt read model file. (It is a directory!!! " + file.getPath() + ")");
    }
    if (!file.canRead() && !file.setReadable(true)) {
        throw new IOException("Couldnt read model file. (Missing read permissions: " + file.getPath() + ")");
    }

    byte[] encoded = Files.readAllBytes(Paths.get(file.getPath()));
    return (new String(encoded, StandardCharsets.UTF_8));
}

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

public static String getTextReportString(String reportPath, AppInfo appInfo) {
    byte[] encoded = null;
    try {/*from  ww  w .  j  a  va2s.  com*/
        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:com.liferay.blade.cli.command.ConvertThemeCommand.java

private static boolean _compassSupport(String themePath) throws Exception {
    File themeDir = new File(themePath);

    File customCss = new File(themeDir, "docroot/_diffs/css/custom.css");

    if (!customCss.exists()) {
        customCss = new File(themeDir, "docroot/_diffs/css/_custom.scss");
    }/*w  w w .ja  v  a 2 s.c  om*/

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

    String css = new String(Files.readAllBytes(customCss.toPath()));

    Matcher matcher = _compassImport.matcher(css);

    return matcher.find();
}