Example usage for java.nio CharBuffer rewind

List of usage examples for java.nio CharBuffer rewind

Introduction

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

Prototype

public final Buffer rewind() 

Source Link

Document

Rewinds this buffer.

Usage

From source file:BufferEquality.java

public static void main(String[] args) {
    CharBuffer cb1 = CharBuffer.allocate(5), cb2 = CharBuffer.allocate(5);
    cb1.put('B').put('u').put('f').put('f').put('A');
    cb2.put('B').put('u').put('f').put('f').put('B');
    cb1.rewind();
    cb2.rewind();/*from w ww. ja  va 2 s.c  o m*/
    System.out.println(cb1.limit(4).equals(cb2.limit(4)));
    // Should be "true"
}

From source file:jenkins.plugins.publish_over_cifs.CifsHostConfiguration.java

@SuppressWarnings("PMD.EmptyCatchBlock")
private static String encode(final String raw) {
    if (raw == null)
        return null;
    final StringBuilder encoded = new StringBuilder(raw.length() * ESCAPED_BUILDER_SIZE_MULTIPLIER);
    final CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
    final CharBuffer buffer = CharBuffer.allocate(1);
    for (final char c : raw.toCharArray()) {
        if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
            encoded.append(c);//w w  w .j  a v  a 2s  . c o m
        } else {
            buffer.put(0, c);
            buffer.rewind();
            try {
                final ByteBuffer bytes = encoder.encode(buffer);
                while (bytes.hasRemaining()) {
                    final byte oneByte = bytes.get();
                    encoded.append('%');
                    encoded.append(toDigit((oneByte >> HI_TO_LOW_NIBBLE_BIT_SHIFT) & LOW_NIBBLE_BIT_MASK));
                    encoded.append(toDigit(oneByte & LOW_NIBBLE_BIT_MASK));
                }
            } catch (final CharacterCodingException cce) {
                throw new BapPublisherException(Messages.exception_encode_cce(cce.getLocalizedMessage()), cce);
            }
        }
    }
    return encoded.toString();
}

From source file:foam.blob.RestBlobService.java

@Override
public Blob put_(X x, Blob blob) {
    if (blob instanceof IdentifiedBlob) {
        return blob;
    }/*  www. jav  a 2s  . c  o m*/

    HttpURLConnection connection = null;
    OutputStream os = null;
    InputStream is = null;

    try {
        URL url = new URL(address_);
        connection = (HttpURLConnection) url.openConnection();

        //configure HttpURLConnection
        connection.setConnectTimeout(5 * 1000);
        connection.setReadTimeout(5 * 1000);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        //set request method
        connection.setRequestMethod("PUT");

        //configure http header
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Connection", "keep-alive");
        connection.setRequestProperty("Content-Type", "application/octet-stream");

        // get connection ouput stream
        os = connection.getOutputStream();

        //output blob into connection
        blob.read(os, 0, blob.getSize());

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Upload failed");
        }

        is = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        CharBuffer cb = CharBuffer.allocate(65535);
        reader.read(cb);
        cb.rewind();

        return (Blob) getX().create(JSONParser.class).parseString(cb.toString(), IdentifiedBlob.class);
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
        IOUtils.close(connection);
    }
}

From source file:StreamUtil.java

/**
 * Reads the stream and generates a String content using the charset specified.
 * Stream will be closed at the end of the operation.
 * @param in InputStream as the input./* w  w w. java2 s. c  o m*/
 * @param charset The charset to use to create the String object.
 * @return The output String.
 * @throws IOException
 */
public static String inputStream2String(final InputStream is, final Charset charset) throws IOException {
    try {
        StringBuilder out = new StringBuilder();
        byte[] b = new byte[4096];
        byte[] savedBytes = new byte[1];
        boolean hasSavedBytes = false;
        CharsetDecoder decoder = charset.newDecoder();
        for (int n; (n = is.read(b)) != -1;) {
            if (hasSavedBytes) {
                byte[] bTmp = new byte[savedBytes.length + b.length];
                System.arraycopy(savedBytes, 0, bTmp, 0, savedBytes.length);
                System.arraycopy(b, 0, bTmp, savedBytes.length, b.length);
                b = bTmp;
                hasSavedBytes = false;
                n = n + savedBytes.length;
            }

            CharBuffer charBuffer = decodeHelper(b, n, charset);
            if (charBuffer == null) {
                int nrOfChars = 0;
                while (charBuffer == null) {
                    nrOfChars++;
                    charBuffer = decodeHelper(b, n - nrOfChars, charset);
                    if (nrOfChars > 10 && nrOfChars < n) {
                        try {
                            charBuffer = decoder.decode(ByteBuffer.wrap(b, 0, n));
                        } catch (MalformedInputException ex) {
                            throw new IOException(
                                    "File not in supported encoding (" + charset.displayName() + ")", ex);
                        }
                    }
                }
                savedBytes = new byte[nrOfChars];
                hasSavedBytes = true;
                for (int i = 0; i < nrOfChars; i++) {
                    savedBytes[i] = b[n - nrOfChars + i];
                }
            }

            charBuffer.rewind(); // Bring the buffer's pointer to 0
            out.append(charBuffer.toString());
        }
        if (hasSavedBytes) {
            try {
                CharBuffer charBuffer = decoder.decode(ByteBuffer.wrap(savedBytes, 0, savedBytes.length));
            } catch (MalformedInputException ex) {
                throw new IOException("File not in supported encoding (" + charset.displayName() + ")", ex);
            }
        }
        return out.toString();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.NoHttpResponseTest.java

@Override
public void run() {
    try {//w  w  w.  ja v  a 2 s . c  om
        serverSocket_ = new ServerSocket(port_);
        started_.set(true);
        LOG.info("Starting listening on port " + port_);
        while (!shutdown_) {
            final Socket s = serverSocket_.accept();
            final BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

            final CharBuffer cb = CharBuffer.allocate(5000);
            br.read(cb);
            cb.flip();
            final String in = cb.toString();
            cb.rewind();

            final RawResponseData responseData = getResponseData(in);

            if (responseData == null || responseData.getStringContent() == DROP_CONNECTION) {
                LOG.info("Closing impolitely in & output streams");
                s.getOutputStream().close();
            } else {
                final PrintWriter pw = new PrintWriter(s.getOutputStream());
                pw.println("HTTP/1.0 " + responseData.getStatusCode() + " " + responseData.getStatusMessage());
                for (final NameValuePair header : responseData.getHeaders()) {
                    pw.println(header.getName() + ": " + header.getValue());
                }
                pw.println();
                pw.println(responseData.getStringContent());
                pw.println();
                pw.flush();
                pw.close();
            }
            br.close();
            s.close();
        }
    } catch (final SocketException e) {
        if (!shutdown_) {
            LOG.error(e);
        }
    } catch (final IOException e) {
        LOG.error(e);
    } finally {
        LOG.info("Finished listening on port " + port_);
    }
}

From source file:hudson.Util.java

/**
 * Encode a single path component for use in an HTTP URL.
 * Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~)
 * and HTTP special characters (/;:?) as specified in RFC1738,
 * plus backslash (Windows path separator).
 * Note that slash(/) is encoded, so the given string should be a
 * single path component used in constructing a URL.
 * Method name inspired by PHP's rawencode.
 */// www.  j a  v  a  2 s . c o  m
public static String rawEncode(String s) {
    boolean escaped = false;
    StringBuilder out = null;
    CharsetEncoder enc = null;
    CharBuffer buf = null;
    char c;
    for (int i = 0, m = s.length(); i < m; i++) {
        c = s.charAt(i);
        if ((c < 64 || c > 90) && (c < 97 || c > 122) && (c < 38 || c > 57 || c == 47) && c != 61 && c != 36
                && c != 33 && c != 95) {
            if (!escaped) {
                out = new StringBuilder(i + (m - i) * 3);
                out.append(s.substring(0, i));
                enc = Charset.forName("UTF-8").newEncoder();
                buf = CharBuffer.allocate(1);
                escaped = true;
            }
            // 1 char -> UTF8
            buf.put(0, c);
            buf.rewind();
            try {
                for (byte b : enc.encode(buf).array()) {
                    out.append('%');
                    out.append(toDigit((b >> 4) & 0xF));
                    out.append(toDigit(b & 0xF));
                }
            } catch (CharacterCodingException ex) {
            }
        } else if (escaped) {
            out.append(c);
        }
    }
    return escaped ? out.toString() : s;
}

From source file:hudson.Util.java

/**
 * Encode a single path component for use in an HTTP URL.
 * Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~)
 * and HTTP special characters (/;:?) as specified in RFC1738.
 * (so alphanumeric and !@$&*()-_=+',. are not encoded)
 * Note that slash(/) is encoded, so the given string should be a
 * single path component used in constructing a URL.
 * Method name inspired by PHP's rawurlencode.
 *///from w  ww.j  av  a2  s.com
public static String rawEncode(String s) {
    boolean escaped = false;
    StringBuilder out = null;
    CharsetEncoder enc = null;
    CharBuffer buf = null;
    char c;
    for (int i = 0, m = s.length(); i < m; i++) {
        c = s.charAt(i);
        if (c > 122 || uriMap[c]) {
            if (!escaped) {
                out = new StringBuilder(i + (m - i) * 3);
                out.append(s.substring(0, i));
                enc = Charset.forName("UTF-8").newEncoder();
                buf = CharBuffer.allocate(1);
                escaped = true;
            }
            // 1 char -> UTF8
            buf.put(0, c);
            buf.rewind();
            try {
                ByteBuffer bytes = enc.encode(buf);
                while (bytes.hasRemaining()) {
                    byte b = bytes.get();
                    out.append('%');
                    out.append(toDigit((b >> 4) & 0xF));
                    out.append(toDigit(b & 0xF));
                }
            } catch (CharacterCodingException ex) {
            }
        } else if (escaped) {
            out.append(c);
        }
    }
    return escaped ? out.toString() : s;
}

From source file:org.apache.ofbiz.base.util.UtilIO.java

/** Copy a Reader to an Appendable, optionally closing the input.
 *
 * @param reader the Reader to copy from
 * @param closeIn whether to close the input when the copy is done
 * @param out the Appendable to copy to//from  w  w  w. j  a  va  2s . c  o  m
 * @throws IOException if an error occurs
 */
public static void copy(Reader reader, boolean closeIn, Appendable out) throws IOException {
    try {
        CharBuffer buffer = CharBuffer.allocate(4096);
        while (reader.read(buffer) > 0) {
            buffer.flip();
            buffer.rewind();
            out.append(buffer);
        }
    } finally {
        if (closeIn)
            IOUtils.closeQuietly(reader);
    }
}

From source file:org.colombbus.tangara.io.ScriptReader.java

/**
  * Try to decode a byte buffer with a charset
  */* w w  w  .  j a  v  a2s . com*/
  * @param content
  *            the bute buffer
  * @param cs
  *            the charset
  * @return <code>null</code> if the charset is not supported, or the decoded
  *         string
  */
 private static String tryDecodeBufferWithCharset(ByteBuffer content, Charset cs) {
     CharBuffer buffer = CharBuffer.allocate(content.capacity() * 2);
     CharsetDecoder decoder = createDecoder(cs);
     content.rewind();
     CoderResult coderRes = decoder.decode(content, buffer, true);
     if (coderRes.isError() == false) {
         buffer.rewind();
         return buffer.toString().trim();
     }
     return null;
 }