Example usage for java.nio CharBuffer flip

List of usage examples for java.nio CharBuffer flip

Introduction

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

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

From source file:GetWebPageApp.java

public static void main(String args[]) throws Exception {
    String resource, host, file;//from   w w w  .j a v  a2  s .c  om
    int slashPos;

    resource = "www.java2s.com/index.htm"; // skip HTTP://
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
        resource = resource + "/";
        slashPos = resource.indexOf('/');
    }
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
        Charset charset = Charset.forName("ISO-8859-1");
        CharsetDecoder decoder = charset.newDecoder();
        CharsetEncoder encoder = charset.newEncoder();

        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        CharBuffer charBuffer = CharBuffer.allocate(1024);

        InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(socketAddress);

        selector = Selector.open();

        channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ);

        while (selector.select(500) > 0) {
            Set readyKeys = selector.selectedKeys();
            try {
                Iterator readyItor = readyKeys.iterator();

                while (readyItor.hasNext()) {

                    SelectionKey key = (SelectionKey) readyItor.next();
                    readyItor.remove();
                    SocketChannel keyChannel = (SocketChannel) key.channel();

                    if (key.isConnectable()) {
                        if (keyChannel.isConnectionPending()) {
                            keyChannel.finishConnect();
                        }
                        String request = "GET " + file + " \r\n\r\n";
                        keyChannel.write(encoder.encode(CharBuffer.wrap(request)));
                    } else if (key.isReadable()) {
                        keyChannel.read(buffer);
                        buffer.flip();

                        decoder.decode(buffer, charBuffer, false);
                        charBuffer.flip();
                        System.out.print(charBuffer);

                        buffer.clear();
                        charBuffer.clear();

                    } else {
                        System.err.println("Unknown key");
                    }
                }
            } catch (ConcurrentModificationException e) {
            }
        }
    } catch (UnknownHostException e) {
        System.err.println(e);
    } catch (IOException e) {
        System.err.println(e);
    } finally {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException ignored) {
            }
        }
    }
    System.out.println("\nDone.");
}

From source file:Main.java

public static byte[] char2byte(String encode, char... chars) {
    Charset cs = Charset.forName(encode);
    CharBuffer cb = CharBuffer.allocate(chars.length);
    cb.put(chars);//from   www  .  j  a  v a  2s.c  o m
    cb.flip();
    ByteBuffer bb = cs.encode(cb);
    return bb.array();
}

From source file:Main.java

public static byte[] getBytes(char[] buffer, int offset, int length) {

    CharBuffer cb = CharBuffer.allocate(length);
    cb.put(buffer, offset, length);//from ww  w. j a va2s .c o  m
    cb.flip();

    return Charset.defaultCharset().encode(cb).array();
}

From source file:com.compomics.colims.core.util.AccessionConverter.java

/**
 * fetches the html page at the passed url as a string
 *
 * @param aUrl the url to fetch the html page from
 * @return the page at the url in textual form
 * @throws IOException//from  w w w  .  j a v  a  2 s  .c om
 */
public static String getPage(String aUrl) throws IOException {
    StringBuilder input = new StringBuilder();
    String htmlPage;
    try (Reader r = openReader(aUrl)) {
        CharBuffer buffer = CharBuffer.allocate(256);
        while ((r.read(buffer)) != -1) {
            input.append(buffer.flip());
            buffer.clear();
        }
    } catch (IOException e) {
        throw new IOException("EMBL-EBI server is not available at the moment, please try again later.");
    }
    htmlPage = input.toString();
    return htmlPage;
}

From source file:fi.johannes.kata.ocr.utils.files.CFileOperations.java

public static void writeChunk(CharBuffer cb, String outputFile) throws IOException {
    cb.flip();
    try (BufferedWriter bw = new BufferedWriter(new PrintWriter(outputFile))) {
        bw.write(cb.toString());/*w w w.  j a va  2  s .  c  o  m*/
        cb.clear();
    }
}

From source file:net.fenyo.mail4hotspot.service.Browser.java

public static String getHtml(final String target_url, final Cookie[] cookies) throws IOException {
    // log.debug("RETRIEVING_URL=" + target_url);
    final URL url = new URL(target_url);

    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.69.60.6", 3128)); 
    // final HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);

    //      HttpURLConnection.setFollowRedirects(true);
    // conn.setRequestProperty("User-agent", "my agent name");

    conn.setRequestProperty("Accept-Language", "en-US");

    //      conn.setRequestProperty(key, value);

    // allow both GZip and Deflate (ZLib) encodings
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    final String encoding = conn.getContentEncoding();
    InputStream is = null;/*from   w  w w.  jav  a 2s.c  om*/
    // create the appropriate stream wrapper based on the encoding type
    if (encoding != null && encoding.equalsIgnoreCase("gzip"))
        is = new GZIPInputStream(conn.getInputStream());
    else if (encoding != null && encoding.equalsIgnoreCase("deflate"))
        is = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
    else
        is = conn.getInputStream();

    final InputStreamReader reader = new InputStreamReader(new BufferedInputStream(is));

    final CharBuffer cb = CharBuffer.allocate(1024 * 1024);
    int ret;
    do {
        ret = reader.read(cb);
    } while (ret > 0);
    cb.flip();
    return cb.toString();
}

From source file:ChannelToWriter.java

/**
 * Read bytes from the specified channel, decode them using the specified
 * Charset, and write the resulting characters to the specified writer
 */// w  w  w .ja  v  a2s.co  m
public static void copy(ReadableByteChannel channel, Writer writer, Charset charset) throws IOException {
    // Get and configure the CharsetDecoder we'll use
    CharsetDecoder decoder = charset.newDecoder();
    decoder.onMalformedInput(CodingErrorAction.IGNORE);
    decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);

    // Get the buffers we'll use, and the backing array for the CharBuffer.
    ByteBuffer bytes = ByteBuffer.allocateDirect(2 * 1024);
    CharBuffer chars = CharBuffer.allocate(2 * 1024);
    char[] array = chars.array();

    while (channel.read(bytes) != -1) { // Read from channel until EOF
        bytes.flip(); // Switch to drain mode for decoding
        // Decode the byte buffer into the char buffer.
        // Pass false to indicate that we're not done.
        decoder.decode(bytes, chars, false);

        // Put the char buffer into drain mode, and write its contents
        // to the Writer, reading them from the backing array.
        chars.flip();
        writer.write(array, chars.position(), chars.remaining());

        // Discard all bytes we decoded, and put the byte buffer back into
        // fill mode. Since all characters were output, clear that buffer.
        bytes.compact(); // Discard decoded bytes
        chars.clear(); // Clear the character buffer
    }

    // At this point there may still be some bytes in the buffer to decode
    // So put the buffer into drain mode call decode() a final time, and
    // finish with a flush().
    bytes.flip();
    decoder.decode(bytes, chars, true); // True means final call
    decoder.flush(chars); // Flush any buffered chars
    // Write these final chars (if any) to the writer.
    chars.flip();
    writer.write(array, chars.position(), chars.remaining());
    writer.flush();
}

From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java

/**
 * decoding string from mysql is not easy. literals is encoded in utf8. chances are some lierals are encoded in 
 * binary. we need this pretty logic to convert mysql binary to string
 * @param buf/*from  w w  w.j  a  va  2 s. co m*/
 * @return
 */
public static CharBuffer readStringCrazy(Decoder decoder, ByteBuf buf) {
    CharBuffer cbuf = MysqlString.decode(decoder, buf.nioBuffer());
    cbuf.flip();
    return cbuf;
}

From source file:ch.rasc.edsutil.optimizer.WebResourceProcessor.java

private static String inputStream2String(InputStream is, Charset cs) throws IOException {
    StringBuilder to = new StringBuilder();
    try (Reader from = new InputStreamReader(is, cs.newDecoder())) {
        CharBuffer buf = CharBuffer.allocate(0x800);
        while (from.read(buf) != -1) {
            buf.flip();
            to.append(buf);//from w w w.j a v  a2  s . com
            buf.clear();
        }
        return to.toString();
    }
}

From source file:com.cloudbees.jenkins.support.filter.FilteredWriterTest.java

@Issue("JENKINS-21670")
@Test//from  w ww.  ja  va  2s.  c  o m
public void shouldSupportLinesLongerThanDefaultBufferSize() throws Exception {
    CharBuffer input = CharBuffer.allocate(FilteredConstants.DEFAULT_DECODER_CAPACITY * 10);
    for (int i = 0; i < input.capacity(); i++) {
        input.put('+');
    }
    input.flip();
    CharSequenceReader reader = new CharSequenceReader(input);
    ContentFilter filter = s -> s.replace('+', '-');
    StringWriter output = new StringWriter();
    FilteredWriter writer = new FilteredWriter(output, filter);

    IOUtils.copy(reader, writer);
    assertThat(output.toString()).isEmpty();

    writer.flush();

    assertThat(output.toString()).isNotEmpty().matches("^-+$");

}