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.evolveum.midpoint.testing.longtest.TestLdap.java

/**
 * Just a first step for the following test.
 * Also, Guybrush has a photo. Check that binary property mapping works.
 */// w  ww. j  a v  a2s . c om
@Test
public void test202AssignLdapAccountToGuybrush() throws Exception {
    final String TEST_NAME = "test202AssignLdapAccountToGuybrush";
    TestUtil.displayTestTile(this, TEST_NAME);

    // GIVEN
    Task task = taskManager.createTaskInstance(TestLdap.class.getName() + "." + TEST_NAME);
    OperationResult result = task.getResult();

    byte[] photoIn = Files.readAllBytes(Paths.get(DOT_JPG_FILENAME));
    display("Photo in", MiscUtil.binaryToHex(photoIn));
    modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_JPEG_PHOTO, task, result, photoIn);

    Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(
            UserType.F_JPEG_PHOTO, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
    PrismObject<UserType> userBefore = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, options, task,
            result);
    display("User before", userBefore);
    byte[] userJpegPhotoBefore = userBefore.asObjectable().getJpegPhoto();
    assertEquals("Photo byte length changed (user before)", photoIn.length, userJpegPhotoBefore.length);
    assertTrue("Photo bytes do not match (user before)", Arrays.equals(photoIn, userJpegPhotoBefore));

    // WHEN
    TestUtil.displayWhen(TEST_NAME);
    assignAccount(USER_GUYBRUSH_OID, RESOURCE_OPENDJ_OID, null, task, result);

    // THEN
    TestUtil.displayThen(TEST_NAME);
    result.computeStatus();
    TestUtil.assertSuccess(result);

    Entry entry = assertOpenDjAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true);
    byte[] jpegPhotoLdap = OpenDJController.getAttributeValueBinary(entry, "jpegPhoto");
    assertNotNull("No jpegPhoto in LDAP entry", jpegPhotoLdap);
    assertEquals("Byte length changed (LDAP)", photoIn.length, jpegPhotoLdap.length);
    assertTrue("Bytes do not match (LDAP)", Arrays.equals(photoIn, jpegPhotoLdap));

    PrismObject<UserType> userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, options, task,
            result);
    display("User after", userAfter);
    String accountOid = getSingleLinkOid(userAfter);
    PrismObject<ShadowType> shadow = getShadowModel(accountOid);

    PrismContainer<?> attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES);
    QName jpegPhotoQName = new QName(RESOURCE_OPENDJ_NAMESPACE, "jpegPhoto");
    PrismProperty<byte[]> jpegPhotoAttr = attributesContainer.findProperty(jpegPhotoQName);
    byte[] photoBytesOut = jpegPhotoAttr.getValues().get(0).getValue();

    display("Photo bytes out", MiscUtil.binaryToHex(photoBytesOut));

    assertEquals("Photo byte length changed (shadow)", photoIn.length, photoBytesOut.length);
    assertTrue("Photo bytes do not match (shadow)", Arrays.equals(photoIn, photoBytesOut));
}

From source file:io.fabric8.docker.client.Config.java

private boolean tryServiceAccount(Config config) {
    if (Utils.getSystemPropertyOrEnvVar(KUBERNETES_AUTH_TRYSERVICEACCOUNT_SYSTEM_PROPERTY, true)) {
        try {
            String token = new String(
                    Files.readAllBytes(new File(KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH).toPath()));
            if (token != null) {
                config.getAuthConfigs().put(DOCKER_AUTH_FALLBACK_KEY, new AuthConfigBuilder()
                        .withUsername(KUBERNETES_SERVICE_ACCOUNT_USER).withPassword(token).build());
                return true;
            }/*from   w  ww.j  av  a  2  s  .  c o m*/
        } catch (IOException e) {
            // No service account token available...
        }
    }
    return false;
}

From source file:com.ontotext.s4.service.S4ServiceClient.java

/**
 * Annotates the contents of a single file returning an
 * {@link InputStream} from which the annotated content can be read
 * /*from w ww.j  av  a 2s  .  co  m*/
 * @param documentContent the file which will be annotated
 * @param documentEncoding the encoding of the file which will be annotated
 * @param documentMimeType the MIME type of the file which will be annotated
 * @param serializationFormat the serialization format used for the annotated content
  *
 * @throws IOException if there are problems reading the contents of the file
 * @throws S4ServiceClientException
 */
public InputStream annotateFileContentsAsStream(File documentContent, Charset documentEncoding,
        SupportedMimeType documentMimeType, ResponseFormat serializationFormat)
        throws IOException, S4ServiceClientException {

    Path documentPath = documentContent.toPath();
    if (!Files.isReadable(documentPath)) {
        throw new IOException("File " + documentPath.toString() + " is not readable.");
    }
    ByteBuffer buff;
    buff = ByteBuffer.wrap(Files.readAllBytes(documentPath));
    String content = documentEncoding.decode(buff).toString();

    return annotateDocumentAsStream(content, documentMimeType, serializationFormat);
}

From source file:com.netscape.cmstools.client.ClientCertImportCLI.java

public void importCACert(File dbPath, File dbPasswordFile, String certFile, String nickname,
        String trustAttributes) throws Exception {

    if (nickname != null) {
        importCert(dbPath, dbPasswordFile, certFile, nickname, trustAttributes);
        return;//from   w ww . j a  v a 2 s . c  o m
    }

    String pemCert = new String(Files.readAllBytes(Paths.get(certFile))).trim();
    byte[] binCert = Cert.parseCertificate(pemCert);

    CryptoManager manager = CryptoManager.getInstance();
    X509Certificate cert = manager.importCACertPackage(binCert);
    setTrustAttributes(cert, trustAttributes);

    MainCLI.printMessage("Imported certificate \"" + cert.getNickname() + "\"");
}

From source file:com.hmiard.blackwater.projects.Builder.java

/**
 * Utility fonction. Return an UTF-8 encoded string from a file.
 *
 * @param path String//from   ww  w.  java  2 s . co m
 * @return String
 * @throws IOException
 */
public static String readFile(String path) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, StandardCharsets.UTF_8);
}

From source file:io.apiman.test.common.echo.EchoServerVertx.java

private Buffer getResource(String fPath) {
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource(fPath).getFile());
    Buffer buff;//from w  ww  .j  a v  a  2 s.c  om
    try {
        buff = Buffer.buffer(Files.readAllBytes(file.toPath()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return buff;
}

From source file:com.puppycrawl.tools.checkstyle.internal.XdocsPagesTest.java

@Test
public void testAllCheckSectionsEx() throws Exception {
    final ModuleFactory moduleFactory = TestUtils.getPackageObjectFactory();

    final Path path = Paths.get(XdocUtil.DIRECTORY_PATH + "/config.xml");
    final String fileName = path.getFileName().toString();

    final String input = new String(Files.readAllBytes(path), UTF_8);
    final Document document = XmlUtil.getRawXml(fileName, input, input);
    final NodeList sources = document.getElementsByTagName("section");

    for (int position = 0; position < sources.getLength(); position++) {
        final Node section = sources.item(position);
        final String sectionName = section.getAttributes().getNamedItem("name").getNodeValue();

        if (!"Checker".equals(sectionName) && !"TreeWalker".equals(sectionName)) {
            continue;
        }/*from  w w  w  . j a  v a 2s .  c o m*/

        validateCheckSection(moduleFactory, fileName, sectionName, section);
    }
}

From source file:com.eternitywall.ots.OtsCli.java

public static void upgrade(String argsOts, boolean shrink) {
    try {//  ww w. ja  v a  2 s . co  m
        Path pathOts = Paths.get(argsOts);
        byte[] byteOts = Files.readAllBytes(pathOts);
        DetachedTimestampFile detachedOts = DetachedTimestampFile.deserialize(byteOts);

        boolean changed = OpenTimestamps.upgrade(detachedOts);

        if (shrink == true) {
            detachedOts.getTimestamp().shrink();
        }

        if (detachedOts.timestamp.isTimestampComplete()) {
            System.out.println("Success! Timestamp complete");
        } else {
            System.out.println("Failed! Timestamp not complete");
        }

        if (shrink || changed) {
            // Copy Bak File
            byte[] byteBak = Files.readAllBytes(pathOts);
            Path pathBak = Paths.get(argsOts + ".bak");
            Files.write(pathBak, byteBak);

            // Write new Upgrade Result
            Files.write(pathOts, detachedOts.serialize());
        }
    } catch (IOException e) {
        log.severe("No valid file");
    } catch (Exception e) {
        e.printStackTrace();
        log.severe("Shrink error");
    }
}

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

public final void loadShops() {
    try {//from   www . jav  a  2  s . co 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) {
            Bukkit.getLogger().severe("[mcDropShop] Null shopList!");
            this.NullListException = true;
            return;
        }

        JSONObject shopObj;
        //System.out.println("[MDS DBG MSG] lS shopList.size() = "+shopList.size());
        for (int index = 0; index < shopList.size(); index++) {
            //System.out.println(index);

            shopObj = (JSONObject) (shopList.get(index));

            if (shopObj == null)
                continue; // Skip missing indices

            Holograms holo = new Holograms(this.plugin);
            holo.loadShop(shopObj, (JSONObject) jsonObj);

            Shops.shops.put(holo.shopName, holo);
        }
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in loadShops(void)");
        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 loadShops(void)");
        e.printStackTrace();
    }

    return;
}

From source file:com.bmwcarit.barefoot.topology.DijkstraBenchmark.java

@Test
public void testSSMTstream() throws JSONException, IOException {
    logger.info("SSMT (fastest, priority) stream test");

    Dijkstra<Road, RoadPoint> algo = new Dijkstra<>();
    JSONArray jsonsamples = new JSONArray(
            new String(Files.readAllBytes(Paths.get(MatcherTest.class.getResource("x0001-015.json").getPath())),
                    Charset.defaultCharset()));

    assertTrue(jsonsamples.length() > 1);

    MatcherSample sample1 = new MatcherSample(jsonsamples.getJSONObject(0)), sample2 = null;

    for (int i = 1; i < jsonsamples.length(); ++i) {
        sample2 = new MatcherSample(jsonsamples.getJSONObject(i));

        Set<RoadPoint> sources = map.spatial().radius(sample1.point(), 100);
        Set<RoadPoint> targets = map.spatial().radius(sample2.point(), 100);

        assertTrue(!sources.isEmpty());//from  w  ww  .  ja  va 2  s . c om
        assertTrue(!targets.isEmpty());

        Stopwatch sw = new Stopwatch();
        sw.start();

        int valids = 0;
        for (RoadPoint source : sources) {
            Map<RoadPoint, List<Road>> routes = algo.route(source, targets, new TimePriority(), new Distance(),
                    10000.0);

            for (List<Road> route : routes.values()) {
                if (route != null) {
                    valids += 1;
                }
            }
        }

        sw.stop();

        logger.info("{} x {} routes with {} ({}) valid ({} ms)", sources.size(), targets.size(), valids,
                sources.size() * targets.size(), sw.ms());

        sample1 = sample2;
    }
}