Example usage for java.nio ByteBuffer wrap

List of usage examples for java.nio ByteBuffer wrap

Introduction

In this page you can find the example usage for java.nio ByteBuffer wrap.

Prototype

public static ByteBuffer wrap(byte[] array) 

Source Link

Document

Creates a new byte buffer by wrapping the given byte array.

Usage

From source file:net.sf.yal10n.analyzer.ExploratoryEncodingTest.java

/**
 * Test how malformed input is reported in a coder result.
 * @throws Exception any error//from   w  ww.jav a2  s  . co m
 */
@Test
public void testMalformedEncodingResult() throws Exception {
    ByteBuffer buffer = ByteBuffer.wrap(data);

    CharsetDecoder decoder = utf8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
            .onUnmappableCharacter(CodingErrorAction.REPORT);
    CharBuffer chars = CharBuffer.allocate(100);
    CoderResult result = decoder.decode(buffer, chars, false);
    Assert.assertTrue(result.isMalformed());
}

From source file:com.adaptris.core.services.metadata.Base64DecodeMetadataService.java

private String toString(byte[] metadataValue, String charset) throws UnsupportedEncodingException {
    Charset cset = Charset.defaultCharset();
    if (!isEmpty(charset)) {
        cset = Charset.forName(charset);
    }/* w w w  . ja  va 2s  . c  o m*/
    return cset.decode(ByteBuffer.wrap(metadataValue)).toString();
}

From source file:org.jhk.pulsing.web.controller.UserController.java

@RequestMapping(value = "/createUser", method = RequestMethod.POST, consumes = {
        MediaType.MULTIPART_FORM_DATA_VALUE })
public @ResponseBody Result<User> createUser(@RequestParam User user,
        @RequestParam(name = "picture", required = false) MultipartFile mPicture) {
    _LOGGER.debug("UserController.createUser: " + user + "; "
            + (mPicture != null ? ("picture size is: " + mPicture.getSize()) : "picture not submitted"));

    if (mPicture != null) {
        try {// w w  w .  ja v a 2s  .c o m
            ByteBuffer pBuffer = ByteBuffer.wrap(mPicture.getBytes());

            Picture picture = Picture.newBuilder().build();
            picture.setContent(pBuffer);
            picture.setName(mPicture.getOriginalFilename());
            user.setPicture(picture);
        } catch (IOException iException) {
            _LOGGER.error("Could not get picture bytes", iException);
        }
    }

    return userService.createUser(user);
}

From source file:com.rackspacecloud.blueflood.io.serializers.CounterRollupSerializationTest.java

@Test
public void testCounterV1RoundTrip() throws IOException {
    CounterRollup c0 = new CounterRollup().withCount(7442245).withSampleCount(1);
    CounterRollup c1 = new CounterRollup().withCount(34454722343L).withSampleCount(10);

    if (System.getProperty("GENERATE_COUNTER_SERIALIZATION") != null) {
        OutputStream os = new FileOutputStream("src/test/resources/serializations/counter_version_"
                + Constants.VERSION_1_COUNTER_ROLLUP + ".bin", false);
        os.write(Base64.encodeBase64(new NumericSerializer.CounterRollupSerializer().toByteBuffer(c0).array()));
        os.write("\n".getBytes());
        os.write(Base64.encodeBase64(new NumericSerializer.CounterRollupSerializer().toByteBuffer(c1).array()));
        os.write("\n".getBytes());
        os.close();/*from   w  w w .java  2  s .c  o m*/
    }

    Assert.assertTrue(new File("src/test/resources/serializations").exists());

    int count = 0;
    int version = 0;
    final int maxVersion = Constants.VERSION_1_COUNTER_ROLLUP;
    while (version <= maxVersion) {
        BufferedReader reader = new BufferedReader(
                new FileReader("src/test/resources/serializations/counter_version_" + version + ".bin"));

        ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
        CounterRollup cc0 = NumericSerializer.serializerFor(CounterRollup.class).fromByteBuffer(bb);
        Assert.assertEquals(c0, cc0);

        bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
        CounterRollup cc1 = NumericSerializer.serializerFor(CounterRollup.class).fromByteBuffer(bb);
        Assert.assertEquals(c1, cc1);

        Assert.assertFalse(cc0.equals(cc1));
        version++;
        count++;
    }

    Assert.assertTrue(count > 0);
}

From source file:me.footlights.core.crypto.Fingerprint.java

public static Fingerprint decode(String algorithmName, String hash) throws NoSuchAlgorithmException {
    MessageDigest algorithm = MessageDigest.getInstance(algorithmName);
    final URI uri;
    try {/*w w w  .  j  a va2s  .c  o m*/
        uri = new URI("urn", algorithmName + ":" + hash, null);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }

    return new Fingerprint(algorithm, ByteBuffer.wrap(new Base32().decode(hash.getBytes())), uri);
}

From source file:rxweb.RxJavaServerTests.java

public void echoCapitalizedStream() throws IOException {
    server.post("/test",
            (request,// ww w .j a  v  a2 s  .c  om
                    response) -> response.content(request.getContent()
                            .map(data -> ByteBuffer.wrap(new String(data.array(), StandardCharsets.UTF_8)
                                    .toUpperCase().getBytes(StandardCharsets.UTF_8)))));
    String content = Request.Post("http://localhost:8080/test")
            .bodyString("This is a test!", ContentType.TEXT_PLAIN).execute().returnContent().asString();
    Assert.assertEquals("THIS IS A TEST!", content);
}

From source file:com.oddprints.util.ImageBlobStore.java

public BlobKey writeImageData(byte[] bytes) throws IOException {
    FileService fileService = FileServiceFactory.getFileService();

    AppEngineFile file = fileService.createNewBlobFile("image/jpeg");
    // This time lock because we intend to finalize
    boolean lock = true;
    FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);

    writeChannel.write(ByteBuffer.wrap(bytes));

    // Now finalize
    writeChannel.closeFinally();/*  w  w  w .  j a  va 2s . c  o  m*/

    return fileService.getBlobKey(file);
}

From source file:org.apache.asterix.experiment.action.derived.RunAQLFileAction.java

@Override
public void doPerform() throws Exception {
    String aql = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(aqlFilePath))).toString();
    String uri = MessageFormat.format(REST_URI_TEMPLATE, restHost, String.valueOf(restPort));
    HttpPost post = new HttpPost(uri);
    post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    post.setEntity(new StringEntity(aql, StandardCharsets.UTF_8));
    HttpEntity entity = httpClient.execute(post).getEntity();
    if (entity != null && entity.isStreaming()) {
        printStream(entity.getContent());
    }/*from ww w .j  a va 2 s. c om*/
    if (aql.contains("compact")) {
        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("Compaction has been completed");
        }
    }
}

From source file:ch.cyberduck.core.sds.SDSDelegatingCopyFeature.java

@Override
public void copy(final Path source, final Path target, final TransferStatus status,
        final ConnectionCallback callback) throws BackgroundException {
    if (containerService.getContainer(target).getType().contains(Path.Type.vault)) {
        final FileKey fileKey = TripleCryptConverter.toSwaggerFileKey(Crypto.generateFileKey());
        final ObjectWriter writer = session.getClient().getJSON().getContext(null).writerFor(FileKey.class);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {/* w  ww  . j av  a 2s . c  o m*/
            writer.writeValue(out, fileKey);
        } catch (IOException e) {
            throw new DefaultIOExceptionMappingService().map(e);
        }
        status.setFilekey(ByteBuffer.wrap(out.toByteArray()));
    }
    if (containerService.getContainer(source).getType().contains(Path.Type.vault)
            || containerService.getContainer(target).getType().contains(Path.Type.vault)) {
        new DefaultCopyFeature(session).copy(source, target, status, callback);
    } else {
        if (StringUtils.equals(source.getName(), target.getName())) {
            proxy.copy(source, target, status, callback);
        } else {
            new DefaultCopyFeature(session).copy(source, target, status, callback);
        }
    }
}