Example usage for java.nio ByteBuffer hasRemaining

List of usage examples for java.nio ByteBuffer hasRemaining

Introduction

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

Prototype

public final boolean hasRemaining() 

Source Link

Document

Indicates if there are elements remaining in this buffer, that is if position < limit .

Usage

From source file:org.cryptomator.ui.util.SingleInstanceManager.java

/**
 * Checks if there is a valid port at//from  ww w  .j  ava  2s  .co  m
 * {@link Preferences#userNodeForPackage(Class)} for {@link Main} under the
 * given applicationKey, tries to connect to the port at the loopback
 * address and checks if the port identifies with the applicationKey.
 * 
 * @param applicationKey
 *            key used to load the port and check the identity of the
 *            connection.
 * @return
 */
public static Optional<RemoteInstance> getRemoteInstance(String applicationKey) {
    Optional<Integer> port = getSavedPort(applicationKey);

    if (!port.isPresent()) {
        return Optional.empty();
    }

    SocketChannel channel = null;
    boolean close = true;
    try {
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        LOG.info("connecting to instance {}", port.get());
        channel.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), port.get()));

        SocketChannel fChannel = channel;
        if (!TimeoutTask.attempt(t -> fChannel.finishConnect(), 1000, 10)) {
            return Optional.empty();
        }

        LOG.info("connected to instance {}", port.get());

        final byte[] bytes = applicationKey.getBytes();
        ByteBuffer buf = ByteBuffer.allocate(bytes.length);
        tryFill(channel, buf, 1000);
        if (buf.hasRemaining()) {
            return Optional.empty();
        }

        buf.flip();

        for (int i = 0; i < bytes.length; i++) {
            if (buf.get() != bytes[i]) {
                return Optional.empty();
            }
        }

        close = false;
        return Optional.of(new RemoteInstance(channel));
    } catch (Exception e) {
        return Optional.empty();
    } finally {
        if (close) {
            IOUtils.closeQuietly(channel);
        }
    }
}

From source file:net.vexelon.myglob.utils.Utils.java

/**
 * Reads an input stream into a byte array
 * @param source//  w  w w .  j  a  va 2  s .c o  m
 * @return Byte array of input stream data
 * @throws IOException
 */
public static byte[] read(InputStream source) throws IOException {
    ReadableByteChannel srcChannel = Channels.newChannel(source);
    ByteArrayOutputStream baos = new ByteArrayOutputStream(
            source.available() > 0 ? source.available() : BUFFER_PAGE_SIZE);
    WritableByteChannel destination = Channels.newChannel(baos);

    try {
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_PAGE_SIZE);
        while (srcChannel.read(buffer) > 0) {
            buffer.flip();
            while (buffer.hasRemaining()) {
                destination.write(buffer);
            }
            buffer.clear();
        }
        return baos.toByteArray();
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (srcChannel != null)
                srcChannel.close();
        } catch (IOException e) {
        }
        try {
            if (source != null)
                source.close();
        } catch (IOException e) {
        }
        try {
            if (destination != null)
                destination.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.esxx.Response.java

public static void writeObject(Object object, ContentType ct, OutputStream out) throws IOException {

    if (object == null) {
        return;// www.  ja  v a  2 s . c  o  m
    }

    // Unwrap wrapped objects
    object = JS.toJavaObject(object);

    // Convert complex types to primitive types
    if (object instanceof Node) {
        ESXX esxx = ESXX.getInstance();

        if (ct.match("message/rfc822")) {
            try {
                String xml = esxx.serializeNode((Node) object);
                org.esxx.xmtp.XMTPParser xmtpp = new org.esxx.xmtp.XMTPParser();
                javax.mail.Message msg = xmtpp.convertMessage(new StringReader(xml));
                object = new ByteArrayOutputStream();
                msg.writeTo(new FilterOutputStream((OutputStream) object) {
                    @Override
                    public void write(int b) throws IOException {
                        if (b == '\r') {
                            return;
                        } else if (b == '\n') {
                            out.write('\r');
                            out.write('\n');
                        } else {
                            out.write(b);
                        }
                    }
                });
            } catch (javax.xml.stream.XMLStreamException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            } catch (javax.mail.MessagingException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            }
        } else {
            object = esxx.serializeNode((Node) object);
        }
    } else if (object instanceof Scriptable) {
        if (ct.match("application/x-www-form-urlencoded")) {
            String cs = Parsers.getParameter(ct, "charset", "UTF-8");

            object = StringUtil.encodeFormVariables(cs, (Scriptable) object);
        } else if (ct.match("text/csv")) {
            object = jsToCSV(ct, (Scriptable) object);
        } else {
            object = jsToJSON(object).toString();
        }
    } else if (object instanceof byte[]) {
        object = new ByteArrayInputStream((byte[]) object);
    } else if (object instanceof File) {
        object = new FileInputStream((File) object);
    }

    // Serialize primitive types
    if (object instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream bos = (ByteArrayOutputStream) object;

        bos.writeTo(out);
    } else if (object instanceof ByteBuffer) {
        // Write result as-is to output stream
        WritableByteChannel wbc = Channels.newChannel(out);
        ByteBuffer bb = (ByteBuffer) object;

        bb.rewind();

        while (bb.hasRemaining()) {
            wbc.write(bb);
        }

        wbc.close();
    } else if (object instanceof InputStream) {
        IO.copyStream((InputStream) object, out);
    } else if (object instanceof Reader) {
        // Write stream as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);

        IO.copyReader((Reader) object, ow);
    } else if (object instanceof String) {
        // Write string as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);
        ow.write((String) object);
        ow.flush();
    } else if (object instanceof RenderedImage) {
        Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(ct.getBaseType());

        if (!i.hasNext()) {
            throw new ESXXException("No ImageWriter available for " + ct.getBaseType());
        }

        ImageWriter writer = i.next();

        writer.setOutput(ImageIO.createImageOutputStream(out));
        writer.write((RenderedImage) object);
    } else {
        throw new UnsupportedOperationException("Unsupported object class type: " + object.getClass());
    }
}

From source file:org.apache.usergrid.persistence.map.impl.MapSerializationImpl.java

private static Object deserializeMapEntryKey(ByteBuffer bb) {

    List<Object> stuff = new ArrayList<>();
    while (bb.hasRemaining()) {
        ByteBuffer data = CQLUtils.getWithShortLength(bb);
        if (stuff.size() == 0) {
            stuff.add(DataType.uuid().deserialize(data.slice(), ProtocolVersion.NEWEST_SUPPORTED));
        } else {/*from  w w  w  .j  a v a 2s . c o m*/
            stuff.add(DataType.text().deserialize(data.slice(), ProtocolVersion.NEWEST_SUPPORTED));
        }
        byte equality = bb.get(); // we don't use this but take the equality byte off the buffer

    }

    return stuff;

}

From source file:net.darkmist.alib.io.BufferUtil.java

public static boolean isAll(ByteBuffer buf, byte b) {
    buf = buf.duplicate();/*www  .  ja  va 2s .c  om*/

    while (buf.hasRemaining())
        if (buf.get() != b)
            return false;
    return true;
}

From source file:com.box.restclientv2.httpclientsupport.HttpClientURLEncodedUtils.java

/**
 * Emcode/escape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
 * /*from  ww  w . j ava  2  s.  c  o m*/
 * @param content
 *            the portion to decode
 * @param charset
 *            the charset to use
 * @param blankAsPlus
 *            if {@code true}, then convert space to '+' (e.g. for www-url-form-encoded content), otherwise leave as is.
 * @return
 */
private static String urlencode(final String content, final Charset charset, final BitSet safechars,
        final boolean blankAsPlus) {
    if (content == null) {
        return null;
    }
    StringBuilder buf = new StringBuilder();
    ByteBuffer bb = charset.encode(content);
    while (bb.hasRemaining()) {
        int b = bb.get() & 0xff;
        if (safechars.get(b)) {
            buf.append((char) b);
        } else if (blankAsPlus && b == ' ') {
            buf.append('+');
        } else {
            buf.append("%");
            char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX));
            char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX));
            buf.append(hex1);
            buf.append(hex2);
        }
    }
    return buf.toString();
}

From source file:org.commoncrawl.service.queryserver.index.PositionBasedSequenceFileIndex.java

private static InputStream newInputStream(final ByteBuffer buf) {
    return new InputStream() {
        public synchronized int read() throws IOException {
            if (!buf.hasRemaining()) {
                LOG.error("EOF REACHED in Wrapper Stream!");
                return -1;
            }/*w w w .  ja  va2  s.c om*/
            return buf.get() & 0xff;
        }

        public synchronized int read(byte[] bytes, int off, int len) throws IOException {
            // Read only what's left
            len = Math.min(len, buf.remaining());
            buf.get(bytes, off, len);
            return len;
        }
    };
}

From source file:org.apache.hadoop.hive.ql.udf.generic.GenericUDFUtils.java

public static int findText(Text text, Text subtext, int start) {
    if (start < 0)
        return -1;

    ByteBuffer src = ByteBuffer.wrap(text.getBytes(), 0, text.getLength());
    ByteBuffer tgt = ByteBuffer.wrap(subtext.getBytes(), 0, subtext.getLength());
    byte b = tgt.get();
    src.position(start);/*w ww .j  ava  2 s.  com*/

    while (src.hasRemaining()) {
        if (b == src.get()) {
            src.mark();
            tgt.mark();
            boolean found = true;
            int pos = src.position() - 1;
            while (tgt.hasRemaining()) {
                if (!src.hasRemaining()) {
                    tgt.reset();
                    src.reset();
                    found = false;
                    break;
                }
                if (!(tgt.get() == src.get())) {
                    tgt.reset();
                    src.reset();
                    found = false;
                    break;
                }
            }
            if (found)
                return pos;
        }
    }
    return -1;
}

From source file:io.mycat.util.ByteBufferUtil.java

public static InputStream inputStream(ByteBuffer bytes) {
    final ByteBuffer copy = bytes.duplicate();

    return new InputStream() {
        public int read() {
            if (!copy.hasRemaining()) {
                return -1;
            }/*w w w  .  j av  a  2  s  .  c  o m*/

            return copy.get() & 0xFF;
        }

        @Override
        public int read(byte[] bytes, int off, int len) {
            if (!copy.hasRemaining()) {
                return -1;
            }

            len = Math.min(len, copy.remaining());
            copy.get(bytes, off, len);
            return len;
        }

        @Override
        public int available() {
            return copy.remaining();
        }
    };
}

From source file:com.gistlabs.mechanize.util.apache.URLEncodedUtils.java

/**
 * Emcode/escape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
 * /* w w  w.j av  a2  s .  co  m*/
 * @param content the portion to decode
 * @param charset the charset to use
 * @param blankAsPlus if {@code true}, then convert space to '+' (e.g. for www-url-form-encoded content), otherwise leave as is.
 * @return
 */
private static String urlencode(final String content, final Charset charset, final BitSet safechars,
        final boolean blankAsPlus) {
    if (content == null)
        return null;
    StringBuilder buf = new StringBuilder();
    ByteBuffer bb = charset.encode(content);
    while (bb.hasRemaining()) {
        int b = bb.get() & 0xff;
        if (safechars.get(b))
            buf.append((char) b);
        else if (blankAsPlus && b == ' ')
            buf.append('+');
        else {
            buf.append("%");
            char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, RADIX));
            char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, RADIX));
            buf.append(hex1);
            buf.append(hex2);
        }
    }
    return buf.toString();
}