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:io.github.swagger2markup.extensions.SchemaExtensionTest.java

@Test
public void testSwagger2AsciiDocSchemaExtension() throws IOException, URISyntaxException {
    //Given//from   w  w w.ja  v  a 2 s.  c o  m
    Path file = Paths.get(SchemaExtensionTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Properties properties = new Properties();
    properties.load(SchemaExtensionTest.class.getResourceAsStream("/config/config.properties"));
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder(properties).build();
    Swagger2MarkupExtensionRegistry registry = new Swagger2MarkupExtensionRegistryBuilder()
            //.withDefinitionsDocumentExtension(new SchemaExtension(Paths.get("src/test/resources/docs/asciidoc/extensions").toUri()))
            .build();
    Swagger2MarkupConverter.from(file).withConfig(config).withExtensionRegistry(registry).build()
            .toFolder(outputDirectory);

    //Then
    assertThat(new String(Files.readAllBytes(outputDirectory.resolve("definitions.adoc")))).contains("=== Pet");
    assertThat(new String(Files.readAllBytes(outputDirectory.resolve("definitions.adoc"))))
            .contains("==== XML Schema");
}

From source file:com.twosigma.beaker.chart.serializer.RastersSerializer.java

@Override
public void serialize(Rasters raster, JsonGenerator jgen, SerializerProvider sp)
        throws IOException, JsonProcessingException {

    jgen.writeStartObject();/*  ww w .ja va  2 s . c  o m*/

    jgen.writeObjectField("type", raster.getClass().getSimpleName());
    jgen.writeObjectField("x", raster.getX());
    jgen.writeObjectField("y", raster.getY());
    jgen.writeObjectField("opacity", raster.getOpacity());
    jgen.writeObjectField("visible", raster.getVisible());
    jgen.writeObjectField("yAxis", raster.getYAxis());
    jgen.writeObjectField("position", raster.getPosition());
    if (raster.getWidth() != null) {
        jgen.writeObjectField("width", raster.getWidth());
    }
    if (raster.getHeight() != null) {
        jgen.writeObjectField("height", raster.getHeight());
    }
    // datastring will override file path/url
    if (raster.getDataString() != null) {
        jgen.writeObjectField("value", Bytes2Base64(raster.getDataString(), null));
    } else if (!raster.getFilePath().isEmpty()) {
        String path = raster.getFilePath();
        byte[] picture = Files.readAllBytes(new File(path).toPath());
        String extension = "";
        int i = path.lastIndexOf('.');
        if (i > 0) {
            extension = path.substring(i + 1);
        }
        jgen.writeObjectField("value", Bytes2Base64(picture, extension));
    } else if (!raster.getFileUrl().isEmpty()) {
        jgen.writeObjectField("value", raster.getFileUrl());
    }

    jgen.writeEndObject();
}

From source file:io.fabric8.vertx.maven.plugin.ConfigConversionUtilTest.java

@Test
public void convertArrayYamlToJson() throws Exception {
    Path yamlFile = Paths.get(this.getClass().getResource("/testconfig2.yaml").toURI());
    Path jsonFilePath = Files.createTempFile("testconfig2", ".json");
    assertNotNull(yamlFile);/*from   w  w w. j  a  v a  2s.c o m*/
    assertTrue(yamlFile.toFile().isFile());
    assertTrue(yamlFile.toFile().exists());
    ConfigConverterUtil.convertYamlToJson(yamlFile, jsonFilePath);
    assertNotNull(jsonFilePath);
    String jsonDoc = new String(Files.readAllBytes(jsonFilePath));
    assertNotNull(jsonDoc);
    JSONObject jsonMap = new JSONObject(jsonDoc);
    assertNotNull(jsonMap);
    assertNotNull(jsonMap.get("names"));
    JSONArray names = jsonMap.getJSONArray("names");
    assertTrue(names.length() == 4);
    assertEquals(names.get(0), "kamesh");

}

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

private static void processCommandLine(final CommandLine cmdLine) throws IOException {
    final Path _srcRoot = Paths.get(cmdLine.getOptionValue(IN_FOLDER_OPTION));
    final Path _trgRoot = Paths.get(cmdLine.getOptionValue(OUT_FOLDER_OPTION));

    final Predicate<Path> _nonClassFileSelector = p -> !p.toString().endsWith(".class")
            && Files.isRegularFile(p);
    final BiConsumer<Path, Path> _fileCopier = (srcPath, trgPath) -> {
        try {//from  w ww.j  a  v a2s .  c o  m
            Files.copy(srcPath, trgPath);
        } catch (final IOException _ex) {
            throw new RuntimeException(_ex);
        }
    };
    processFiles(_srcRoot, _trgRoot, _nonClassFileSelector, _fileCopier);

    final Predicate<Path> _classFileSelector = p -> p.toString().endsWith(".class");
    final String _methodNameRegex = cmdLine.getOptionValue(METHOD_NAME_REGEX_OPTION, METHOD_NAME_REGEX);
    final Boolean _onlyAnnotatedTests = cmdLine.hasOption(ONLY_ANNOTATED_TESTS_OPTION);
    final BiConsumer<Path, Path> _classInstrumenter = (srcPath, trgPath) -> {
        try {
            final byte[] _bytecode = Files.readAllBytes(srcPath);
            final ClassReader _cr = new ClassReader(_bytecode);
            final ClassWriter _cw = new ClassWriter(_cr, ClassWriter.COMPUTE_MAXS);
            final ClassVisitor _cv1 = new LoggerInitializingClassVisitor(CLI.ASM_VERSION, _cw);
            final ClassVisitor _cv2 = new TracingClassVisitor(_cv1, _methodNameRegex, _onlyAnnotatedTests);
            _cr.accept(_cv2, 0);
            final byte[] _out = _cw.toByteArray();
            Files.write(trgPath, _out);
        } catch (final IOException _ex) {
            throw new RuntimeException(_ex);
        }
    };
    processFiles(_srcRoot, _trgRoot, _classFileSelector, _classInstrumenter);
}

From source file:com.spotify.helios.servicescommon.PersistentAtomicReference.java

private PersistentAtomicReference(final Path filename, final JavaType javaType,
        final Supplier<? extends T> initialValue) throws IOException, InterruptedException {
    try {/*from   w  ww  .  ja  v a 2 s  .  c om*/
        this.filename = filename.toAbsolutePath();
        this.tempfilename = filename.getFileSystem().getPath(this.filename.toString() + ".tmp");
        if (Files.exists(filename)) {
            final byte[] bytes = Files.readAllBytes(filename);
            if (bytes.length > 0) {
                value = Json.read(bytes, javaType);
            } else {
                value = initialValue.get();
            }
        } else {
            value = initialValue.get();
        }
    } catch (InterruptedIOException | ClosedByInterruptException e) {
        throw new InterruptedException(e.getMessage());
    }
}

From source file:com.oneops.boo.ClientConfigInterpolator.java

/**
 * Take key/value pairs from a OneOps configuration profile and interpolate a Boo YAML template
 * with them.//from w  ww . j  a va2 s . c om
 * 
 * @param booYamlFile template to use
 * @param booConfigFile to use for key/value pairs
 * @param profile in configuration file to use for key/value pairs
 * @return Interpolate Boo YAML template
 * @throws IOException throw if there are errors interpolating the template
 */
public String interpolate(File booYamlFile, File booConfigFile, String profile) throws IOException {
    String booYaml = new String(Files.readAllBytes(booYamlFile.toPath()));
    return interpolate(booYaml, booConfigFile, profile);
}

From source file:com.github.ukase.service.PdfRendererTest.java

private byte[] getFile(String file) throws IOException {
    File dataFile = new File(settings.getResources(), file);
    if (!dataFile.exists()) {
        return null;
    }//from  ww  w  .  j av  a2 s  .co m
    return Files.readAllBytes(dataFile.toPath());
}

From source file:com.github.ffremont.microservices.springboot.node.tasks.InstallJarTaskTest.java

@Test
public void testRun() throws Exception {
    MicroServiceTask msTask = this.create();
    MicroServiceRest ms = msTask.getMs();

    Path msVersionFolder = Paths.get(this.nodeBase, ms.getName(), ms.getVersion());
    Files.createDirectories(msVersionFolder);
    when(helper.targetDirOf(anyObject())).thenReturn(msVersionFolder);
    when(helper.targetJarOf(anyObject()))
            .thenReturn(Paths.get(msVersionFolder.toString(), NodeHelper.jarNameOf(ms)));

    task.run(msTask);//ww  w  . j  av a  2 s  . c o  m

    Path checksumFile = Paths.get(msVersionFolder.toString(), InstallTask.CHECKSUM_FILE_NAME + ".txt");
    assertTrue(Files.exists(checksumFile));
    assertArrayEquals(ms.getSha1().getBytes(), Files.readAllBytes(checksumFile));

    Path binary = Paths.get(msVersionFolder.toString(), NodeHelper.jarNameOf(ms));
    assertTrue(Files.exists(binary));

    LOG.info("testRun : " + nodeBase);
}

From source file:com.samlikescode.stackoverflow.questions.q33386664.DataHolderTest.java

@Test
public void dataHolderTest() throws Exception {
    String input = new String(Files.readAllBytes(Paths.get(
            "/Users/berrysa/projects/stackoverflow/src/main/java/com/samlikescode/stackoverflow/questions/q33386664/input.xml")));
    DataHolder dataHolder = om.readValue(input, DataHolder.class);

    Map<Id, DataHolder.Data> dataContainer = dataHolder.dataContainer;

    Id expectedId1 = new Id();
    expectedId1.eventId = 1;//  w ww  .  j a v a 2 s  .c  o  m
    expectedId1.groupId = 1;
    assertEquals(1, dataContainer.get(expectedId1));
}

From source file:org.yroffin.neo4b.services.BoardMapper.java

public void map() throws IOException, URISyntaxException {

    // GET/*from   ww  w . j  a v  a2  s.  c  o m*/
    spark.Spark.get("/api/boardManagement/v1/boards", (request, response) -> {
        response.type("application/json");
        response.body(boardResource.getBoards(request.body(), BoardRest.class));
        return response.body();
    });

    // POST
    spark.Spark.post("/api/boardManagement/v1/boards", (request, response) -> {
        response.type("application/json");
        response.body(boardResource.createBoard(request.body(), BoardRest.class));
        return response.body();
    });

    // DELETE
    spark.Spark.delete("/api/boardManagement/v1/boards/:id", (request, response) -> {
        response.type("application/json");
        try {
            response.body(boardResource.deleteBoard(request.params(":id"), BoardRest.class));
        } catch (org.yroffin.neo4b.exception.NotFoundException e) {
            response.body("{}");
            response.status(404);
        }
        return response.body();
    });

    // Static
    // Spark.staticFileLocation("public");

    spark.Spark.get("*", (request, response) -> {
        String path = request.pathInfo();
        if (path.compareTo("/") == 0) {
            path = "/index.html";
        }
        String content = new String(Files.readAllBytes(Paths.get("src/main/resources/public" + path)));
        if (path.endsWith(".css")) {
            response.type("text/css");
        }
        return content;
    });
}