Example usage for java.nio CharBuffer wrap

List of usage examples for java.nio CharBuffer wrap

Introduction

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

Prototype

public static CharBuffer wrap(CharSequence chseq) 

Source Link

Document

Creates a new char buffer by wrapping the given char sequence.

Usage

From source file:android.framework.util.jar.Manifest.java

private static void writeEntry(OutputStream os, Attributes.Name name, String value, CharsetEncoder encoder,
        ByteBuffer bBuf) throws IOException {
    String nameString = name.getName();
    os.write(nameString.getBytes(Charsets.US_ASCII));
    os.write(VALUE_SEPARATOR);/*from   w  ww .  ja  va  2 s  .c  om*/

    encoder.reset();
    bBuf.clear().limit(LINE_LENGTH_LIMIT - nameString.length() - 2);

    CharBuffer cBuf = CharBuffer.wrap(value);

    while (true) {
        CoderResult r = encoder.encode(cBuf, bBuf, true);
        if (CoderResult.UNDERFLOW == r) {
            r = encoder.flush(bBuf);
        }
        os.write(bBuf.array(), bBuf.arrayOffset(), bBuf.position());
        os.write(LINE_SEPARATOR);
        if (CoderResult.UNDERFLOW == r) {
            break;
        }
        os.write(' ');
        bBuf.clear().limit(LINE_LENGTH_LIMIT - 1);
    }
}

From source file:org.apache.tajo.util.StringUtils.java

public static char[] convertBytesToChars(byte[] src, Charset charset) {
    CharsetDecoder decoder = charset.newDecoder();
    char[] resultArray = new char[(int) (src.length * decoder.maxCharsPerByte())];

    if (src.length != 0) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(src);
        CharBuffer charBuffer = CharBuffer.wrap(resultArray);

        decoder.onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE);
        decoder.reset();/*from   w  ww.  j  a  v a 2  s  .c  o m*/

        CoderResult coderResult = decoder.decode(byteBuffer, charBuffer, true);
        if (coderResult.isUnderflow()) {
            coderResult = decoder.flush(charBuffer);

            if (coderResult.isUnderflow()) {
                if (resultArray.length != charBuffer.position()) {
                    resultArray = Arrays.copyOf(resultArray, charBuffer.position());
                }
            }
        }
    }

    return resultArray;
}

From source file:HttpDownloadManager.java

public void run() {
    log.info("HttpDownloadManager thread starting.");

    // The download thread runs until release() is called
    while (!released) {
        // The thread blocks here waiting for something to happen
        try {/*from  ww w.j a  v a  2s. c o  m*/
            selector.select();
        } catch (IOException e) {
            // This should never happen.
            log.log(Level.SEVERE, "Error in select()", e);
            return;
        }

        // If release() was called, the thread should exit.
        if (released)
            break;

        // If any new Download objects are pending, deal with them first
        if (!pendingDownloads.isEmpty()) {
            // Although pendingDownloads is a synchronized list, we still
            // need to use a synchronized block to iterate through its
            // elements to prevent a concurrent call to download().
            synchronized (pendingDownloads) {
                Iterator iter = pendingDownloads.iterator();
                while (iter.hasNext()) {
                    // Get the pending download object from the list
                    DownloadImpl download = (DownloadImpl) iter.next();
                    iter.remove(); // And remove it.

                    // Now begin an asynchronous connection to the
                    // specified host and port. We don't block while
                    // waiting to connect.
                    SelectionKey key = null;
                    SocketChannel channel = null;
                    try {
                        // Open an unconnected channel
                        channel = SocketChannel.open();
                        // Put it in non-blocking mode
                        channel.configureBlocking(false);
                        // Register it with the selector, specifying that
                        // we want to know when it is ready to connect
                        // and when it is ready to read.
                        key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT,
                                download);
                        // Create the web server address
                        SocketAddress address = new InetSocketAddress(download.host, download.port);
                        // Ask the channel to start connecting
                        // Note that we don't send the HTTP request yet.
                        // We'll do that when the connection completes.
                        channel.connect(address);
                    } catch (Exception e) {
                        handleError(download, channel, key, e);
                    }
                }
            }
        }

        // Now get the set of keys that are ready for connecting or reading
        Set keys = selector.selectedKeys();
        if (keys == null)
            continue; // bug workaround; should not be needed
        // Loop through the keys in the set
        for (Iterator i = keys.iterator(); i.hasNext();) {
            SelectionKey key = (SelectionKey) i.next();
            i.remove(); // Remove the key from the set before handling

            // Get the Download object we attached to the key
            DownloadImpl download = (DownloadImpl) key.attachment();
            // Get the channel associated with the key.
            SocketChannel channel = (SocketChannel) key.channel();

            try {
                if (key.isConnectable()) {
                    // If the channel is ready to connect, complete the
                    // connection and then send the HTTP GET request to it.
                    if (channel.finishConnect()) {
                        download.status = Status.CONNECTED;
                        // This is the HTTP request we wend
                        String request = "GET " + download.path + " HTTP/1.1\r\n" + "Host: " + download.host
                                + "\r\n" + "Connection: close\r\n" + "\r\n";
                        // Wrap in a CharBuffer and encode to a ByteBuffer
                        ByteBuffer requestBytes = LATIN1.encode(CharBuffer.wrap(request));
                        // Send the request to the server. If the bytes
                        // aren't all written in one call, we busy loop!
                        while (requestBytes.hasRemaining())
                            channel.write(requestBytes);

                        log.info("Sent HTTP request: " + download.host + ":" + download.port + ": " + request);
                    }
                }
                if (key.isReadable()) {
                    // If the key indicates that there is data to be read,
                    // then read it and store it in the Download object.
                    int numbytes = channel.read(buffer);

                    // If we read some bytes, store them, otherwise
                    // the download is complete and we need to note this
                    if (numbytes != -1) {
                        buffer.flip(); // Prepare to drain the buffer
                        download.addData(buffer); // Store the data
                        buffer.clear(); // Prepare for another read
                        log.info("Read " + numbytes + " bytes from " + download.host + ":" + download.port);
                    } else {
                        // If there are no more bytes to read
                        key.cancel(); // We're done with the key
                        channel.close(); // And with the channel.
                        download.status = Status.DONE;
                        if (download.listener != null) // notify listener
                            download.listener.done(download);
                        log.info("Download complete from " + download.host + ":" + download.port);
                    }
                }
            } catch (Exception e) {
                handleError(download, channel, key, e);
            }
        }
    }
    log.info("HttpDownloadManager thread exiting.");
}

From source file:com.all.shared.util.SyncUtils.java

public static String encodeAndZip(List<SyncEventEntity> events) {
    String json = JsonConverter.toJson(events);
    byte[] encodedBytes = null;
    try {//w w w  .j a v a  2 s  . com
        ByteBuffer byteBuffer = UTF_ENCODER.encode(CharBuffer.wrap(json));
        encodedBytes = byteBuffer.array();
    } catch (CharacterCodingException e) {
        LOGGER.warn("Could not encode message with UTF-8.");
        encodedBytes = json.getBytes();
    }
    return new String(Base64.encode(zip(encodedBytes)));
}

From source file:org.nuxeo.common.codec.Crypto.java

/**
 * Utility method to get {@code byte[]} from {@code char[]} since it is recommended to store passwords in
 * {@code char[]} rather than in {@code String}.<br>
 * The default charset of this Java virtual machine is used. There can be conversion issue with unmappable
 * characters: they will be replaced with the charset's default replacement string.
 *
 * @param chars char array to convert/*from w  w w  .  jav  a2  s  . c o m*/
 * @return the byte array converted from {@code chars} using the default charset.
 */
public static byte[] getBytes(char[] chars) {
    CharBuffer charBuffer = CharBuffer.wrap(chars);
    ByteBuffer byteBuffer = Charset.defaultCharset().encode(charBuffer);
    return Arrays.copyOfRange(byteBuffer.array(), 0, byteBuffer.limit());
}

From source file:org.apache.tajo.util.StringUtils.java

public static byte[] convertCharsToBytes(char[] src, Charset charset) {
    CharsetEncoder encoder = charset.newEncoder();
    byte[] resultArray = new byte[(int) (src.length * encoder.maxBytesPerChar())];

    if (src.length != 0) {
        CharBuffer charBuffer = CharBuffer.wrap(src);
        ByteBuffer byteBuffer = ByteBuffer.wrap(resultArray);

        encoder.onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE);
        encoder.reset();/*w  w  w.j  a v a2 s.  co  m*/

        CoderResult coderResult = encoder.encode(charBuffer, byteBuffer, true);
        if (coderResult.isUnderflow()) {
            coderResult = encoder.flush(byteBuffer);

            if (coderResult.isUnderflow()) {
                if (resultArray.length != byteBuffer.position()) {
                    resultArray = Arrays.copyOf(resultArray, byteBuffer.position());
                }
            }
        }
    }

    return resultArray;
}

From source file:itdelatrisu.opsu.replay.Replay.java

/**
 * Saves the replay data to a file in the replays directory.
 *///from  w w  w  . j a  v a 2s.  c  o m
public void save() {
    // create replay directory
    File dir = Options.getReplayDir();
    if (!dir.isDirectory()) {
        if (!dir.mkdir()) {
            ErrorHandler.error("Failed to create replay directory.", null, false);
            return;
        }
    }

    // write file in new thread
    final File file = new File(dir, String.format("%s.osr", getReplayFilename()));
    new Thread() {
        @Override
        public void run() {
            try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
                OsuWriter writer = new OsuWriter(out);

                // header
                writer.write(mode);
                writer.write(version);
                writer.write(beatmapHash);
                writer.write(playerName);
                writer.write(replayHash);
                writer.write(hit300);
                writer.write(hit100);
                writer.write(hit50);
                writer.write(geki);
                writer.write(katu);
                writer.write(miss);
                writer.write(score);
                writer.write(combo);
                writer.write(perfect);
                writer.write(mods);

                // life data
                StringBuilder sb = new StringBuilder();
                if (lifeFrames != null) {
                    NumberFormat nf = new DecimalFormat("##.##");
                    for (int i = 0; i < lifeFrames.length; i++) {
                        LifeFrame frame = lifeFrames[i];
                        sb.append(String.format("%d|%s,", frame.getTime(), nf.format(frame.getPercentage())));
                    }
                }
                writer.write(sb.toString());

                // timestamp
                writer.write(timestamp);

                // LZMA-encoded replay data
                if (frames != null && frames.length > 0) {
                    // build full frame string
                    NumberFormat nf = new DecimalFormat("###.#####");
                    sb = new StringBuilder();
                    for (int i = 0; i < frames.length; i++) {
                        ReplayFrame frame = frames[i];
                        sb.append(String.format("%d|%s|%s|%d,", frame.getTimeDiff(), nf.format(frame.getX()),
                                nf.format(frame.getY()), frame.getKeys()));
                    }
                    sb.append(String.format("%s|0|0|%d", SEED_STRING, seed));

                    // get bytes from string
                    CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder();
                    CharBuffer buffer = CharBuffer.wrap(sb);
                    byte[] bytes = encoder.encode(buffer).array();

                    // compress data
                    ByteArrayOutputStream bout = new ByteArrayOutputStream();
                    LzmaOutputStream compressedOut = new LzmaOutputStream.Builder(bout)
                            .useMediumDictionarySize().build();
                    try {
                        compressedOut.write(bytes);
                    } catch (IOException e) {
                        // possible OOM: https://github.com/jponge/lzma-java/issues/9
                        ErrorHandler.error("LZMA compression failed (possible out-of-memory error).", e, true);
                    }
                    compressedOut.close();
                    bout.close();

                    // write to file
                    byte[] compressed = bout.toByteArray();
                    writer.write(compressed.length);
                    writer.write(compressed);
                } else
                    writer.write(0);

                writer.close();
            } catch (IOException e) {
                ErrorHandler.error("Could not save replay data.", e, true);
            }
        }
    }.start();
}

From source file:org.sonews.daemon.sync.SynchronousNNTPConnection.java

/**
 * Puts the given line into the output buffer, adds a newline character and
 * returns. The method returns immediately and does not block until the line
 * was sent. If line is longer than 510 octets it is split up in several
 * lines. Each line is terminated by \r\n (NNTPConnection.NEWLINE).
 *
 * @param line/*from w  w w . ja v  a2s  .  c o  m*/
 * @param charset
 * @throws java.io.IOException
 */
public void println(final CharSequence line, final Charset charset) throws IOException {
    writeToChannel(CharBuffer.wrap(line), charset, line);
    writeToChannel(CharBuffer.wrap(NEWLINE), charset, null);
}

From source file:com.springrts.springls.Client.java

/**
 * @param msgId overrides any previously set message ID,
 *   use NO_MSG_ID for none./*  www . j a va2  s  . c o m*/
 * @see #setSendMsgId(int msgId)
 */
private boolean sendLine(String text, int msgId) {

    if (!alive || halfDead) {
        return false;
    }

    StringBuilder data = new StringBuilder();

    // prefix message with a message ID:
    if (msgId != NO_MSG_ID) {
        data.append("#").append(msgId).append(" ");
    }
    data.append(text);

    if (fastWrite != null) {
        if (fastWrite.length() != 0) {
            fastWrite.append(Misc.EOL);
        }
        fastWrite.append(data);
        return true;
    }

    if (LOG.isTraceEnabled()) {
        String nameOrIp = (account.getAccess() != Account.Access.NONE) ? account.getName()
                : ip.getHostAddress();
        LOG.trace("[->{}] \"{}\"", nameOrIp, data);
    }

    try {
        // prepare data and add it to the send queue

        data.append(Misc.EOL);

        if ((sockChan == null) || (!sockChan.isConnected())) {
            LOG.warn("SocketChannel is not ready to be written to." + " Killing the client next loop ...");
            context.getClients().killClientDelayed(this, "Quit: undefined connection error");
            return false;
        }

        ByteBuffer buf;
        try {
            buf = context.getServer().getAsciiEncoder().encode(CharBuffer.wrap(data));
        } catch (CharacterCodingException ex) {
            LOG.warn("Unable to encode message. Killing the client next" + " loop ...", ex);
            context.getClients().killClientDelayed(this, "Quit: undefined encoder error");
            return false;
        }

        if (!sendQueue.isEmpty()) {
            sendQueue.add(buf);
        } else {
            sendQueue.add(buf);
            boolean empty = tryToFlushData();
            if (!empty) {
                context.getClients().enqueueDelayedData(this);
            }
        }
    } catch (Exception ex) {
        LOG.error("Failed sending data (undefined). Killing the client next" + " loop ...", ex);
        context.getClients().killClientDelayed(this, "Quit: undefined connection error");
        return false;
    }
    return true;
}

From source file:org.sonews.daemon.sync.SynchronousNNTPConnection.java

/**
 * Writes the given raw lines to the output buffers and finishes with a
 * newline character (\r\n)./*from   w w  w  . j a v  a 2 s  . c o m*/
 *
 * @param rawLines
 * @throws java.io.IOException
 */
@Override
public void println(final byte[] rawLines) throws IOException {
    this.lineBuffers.addOutputBuffer(ByteBuffer.wrap(rawLines));
    writeToChannel(CharBuffer.wrap(NEWLINE), charset, null);
}