Java Code Examples for java.nio.CharBuffer#length()

The following examples show how to use java.nio.CharBuffer#length() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DockerConfig.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Credentials createCredentials(String registry, JSONObject value) throws IOException {
    if (value == null) {
        return null;
    }

    byte[] auth = Base64.getDecoder().decode((String) value.get("auth")); // NOI18N
    CharBuffer chars = Charset.forName("UTF-8").newDecoder().decode(ByteBuffer.wrap(auth)); // NOI18N
    int index = -1;
    for (int i = 0; i < chars.length(); i++) {
        if (chars.get(i) == ':') {
            index = i;
            break;
        }
    }
    if (index < 0) {
        throw new IOException("Malformed registry authentication record");
    }
    String username = new String(chars.array(), 0, index);
    char[] password = new char[chars.length() - index - 1];
    if (password.length > 0) {
        System.arraycopy(chars.array(), index + 1, password, 0, password.length);
    }
    return new Credentials(registry, username, password, (String) value.get("email")); // NOI18N
}
 
Example 2
Source File: ReMatcherImpl.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public boolean match(CharBuffer text) {
    try {
        this.text = text;
        int r = 0;
        int t = 0;

        if (this.regex[r] == '^') {
            return (matchhere(r + 1, t) == 1);
        }
        do {
            if (matchhere(r, t) == 1) {
                return true;
            }
        } while (t++ != text.length());
        return false;
    } finally {
        this.text = null;
    }
}
 
Example 3
Source File: SecureBuffer.java    From edslite with GNU General Public License v2.0 6 votes vote down vote up
public void adoptData(CharBuffer cb)
{
    if(cb.hasArray())
        adoptData(cb.array(), cb.position(), cb.remaining());
    else
    {
        char[] arr = new char[cb.length()];
        cb.get(arr);
        cb.rewind();
        if(!cb.isReadOnly())
        {
            while(cb.hasRemaining())
                cb.put((char) _secureRandom.nextInt());
        }
        adoptData(arr, 0, arr.length);
    }
}
 
Example 4
Source File: String.java    From juniversal with MIT License 6 votes vote down vote up
/**
 * Converts the byte array to a string using the default encoding as
 * specified by the file.encoding system property. If the system property is
 * not defined, the default encoding is ISO8859_1 (ISO-Latin-1). If 8859-1
 * is not available, an ASCII encoding is used.
 * 
 * @param data
 *            the byte array to convert to a string.
 * @param start
 *            the starting offset in the byte array.
 * @param length
 *            the number of bytes to convert.
 * @throws NullPointerException
 *             when {@code data} is {@code null}.
 * @throws IndexOutOfBoundsException
 *             if {@code length < 0, start < 0} or {@code start + length >
 *             data.length}.
 */
public String(byte[] data, int start, int length) {
    // start + length could overflow, start/length maybe MaxInt
    if (start >= 0 && 0 <= length && length <= data.length - start) {
        offset = 0;
        Charset charset = defaultCharset();
        int result;
        CharBuffer cb = charset
                .decode(ByteBuffer.wrap(data, start, length));
        if ((result = cb.length()) > 0) {
            value = cb.array();
            count = result;
        } else {
            count = 0;
            value = new char[0];
        }
    } else {
        throw new StringIndexOutOfBoundsException();
    }
}
 
Example 5
Source File: BuiltInEncodingAlgorithm.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void matchWhiteSpaceDelimnatedWords(CharBuffer cb, WordListener wl) {
    Matcher m = SPACE_PATTERN.matcher(cb);
    int i = 0;
    int s = 0;
    while(m.find()) {
        s = m.start();
        if (s != i) {
            wl.word(i, s);
        }
        i = m.end();
    }
    if (i != cb.length())
        wl.word(i, cb.length());
}
 
Example 6
Source File: BuiltInEncodingAlgorithm.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void matchWhiteSpaceDelimnatedWords(CharBuffer cb, WordListener wl) {
    Matcher m = SPACE_PATTERN.matcher(cb);
    int i = 0;
    int s = 0;
    while(m.find()) {
        s = m.start();
        if (s != i) {
            wl.word(i, s);
        }
        i = m.end();
    }
    if (i != cb.length())
        wl.word(i, cb.length());
}
 
Example 7
Source File: OldCharset_AbstractTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
static void assertEqualCBs (String msg, CharBuffer expectedCB, CharBuffer actualCB) {
        boolean match = true;
        boolean lenMatch = true;
        char expected, actual;
        int len = actualCB.length();
        if (expectedCB.length() != len) {
            lenMatch = false;
            if (expectedCB.length() < len) len = expectedCB.length();
        }
        for (int i = 0; i < len; i++) {
            expected = expectedCB.get();
            actual = actualCB.get();
            if (actual != expected) {
                String detail = String.format(
                        "Mismatch at index %d: %d instead of expected %d.\n",
                        i, (int) actual, (int) expected);
                match = false;
                fail(msg + ": " + detail);
            }
//            else {
//                System.out.format("Match index %d: %d = %d\n",
//                        i, (int) actual[i], (int) expected[i]);
//            }
        }
        assertTrue(msg, match);
        assertTrue(msg + "(IN LENGTH ALSO!)", lenMatch);
//        assertTrue(msg, Arrays.equals(actual, expected));
    }
 
Example 8
Source File: ByteChunk.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
public String toStringInternal() {
    if (charset == null) {
        charset = DEFAULT_CHARSET;
    }
    // new String(byte[], int, int, Charset) takes a defensive copy of the
    // entire byte array. This is expensive if only a small subset of the
    // bytes will be used. The code below is from Apache Harmony.
    CharBuffer cb = charset.decode(ByteBuffer.wrap(buff, start, end - start));
    return new String(cb.array(), cb.arrayOffset(), cb.length());
}
 
Example 9
Source File: BuiltInEncodingAlgorithm.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void matchWhiteSpaceDelimnatedWords(CharBuffer cb, WordListener wl) {
    Matcher m = SPACE_PATTERN.matcher(cb);
    int i = 0;
    int s = 0;
    while(m.find()) {
        s = m.start();
        if (s != i) {
            wl.word(i, s);
        }
        i = m.end();
    }
    if (i != cb.length())
        wl.word(i, cb.length());
}
 
Example 10
Source File: StringValue.java    From stratosphere with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the contents of this string to the contents of the given <tt>CharBuffer</tt>.
 * The characters between the buffer's current position (inclusive) and the buffer's
 * limit (exclusive) will be stored in this string.
 *  
 * @param buffer The character buffer to read the characters from.
 */
public void setValue(CharBuffer buffer) {
	Validate.notNull(buffer);
	final int len = buffer.length();
	ensureSize(len);
	buffer.get(this.value, 0, len);
	this.len = len;
	this.hashCode = 0;
}
 
Example 11
Source File: DslJsonSerializer.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
private void serializeRequest(final Request request) {
    if (request.hasContent()) {
        writeFieldName("request");
        jw.writeByte(OBJECT_START);
        writeField("method", request.getMethod());
        writeField("headers", request.getHeaders());
        writeField("cookies", request.getCookies());
        // only one of those can be non-empty
        if (!request.getFormUrlEncodedParameters().isEmpty()) {
            writeField("body", request.getFormUrlEncodedParameters());
        } else if (request.getRawBody() != null) {
            writeField("body", request.getRawBody());
        } else {
            final CharBuffer bodyBuffer = request.getBodyBufferForSerialization();
            if (bodyBuffer != null && bodyBuffer.length() > 0) {
                writeFieldName("body");
                jw.writeString(bodyBuffer);
                jw.writeByte(COMMA);
            }
        }
        if (request.getUrl().hasContent()) {
            serializeUrl(request.getUrl());
        }
        if (request.getSocket().hasContent()) {
            serializeSocket(request.getSocket());
        }
        writeLastField("http_version", request.getHttpVersion());
        jw.writeByte(OBJECT_END);
        jw.writeByte(COMMA);
    }
}
 
Example 12
Source File: DefaultCredentialManager.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private static char[] decodeBytesToChars(final byte[] bytes) {
  final CharBuffer cb = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes));
  final char[] chars = new char[cb.length()];
  cb.get(chars);
  scrub(cb);
  return chars;
}
 
Example 13
Source File: StringValue.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the contents of this string to the contents of the given <tt>CharBuffer</tt>.
 * The characters between the buffer's current position (inclusive) and the buffer's
 * limit (exclusive) will be stored in this string.
 *  
 * @param buffer The character buffer to read the characters from.
 */
public void setValue(CharBuffer buffer) {
	checkNotNull(buffer);
	final int len = buffer.length();
	ensureSize(len);
	buffer.get(this.value, 0, len);
	this.len = len;
	this.hashCode = 0;
}
 
Example 14
Source File: BuiltInEncodingAlgorithm.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void matchWhiteSpaceDelimnatedWords(CharBuffer cb, WordListener wl) {
    Matcher m = SPACE_PATTERN.matcher(cb);
    int i = 0;
    int s = 0;
    while(m.find()) {
        s = m.start();
        if (s != i) {
            wl.word(i, s);
        }
        i = m.end();
    }
    if (i != cb.length())
        wl.word(i, cb.length());
}
 
Example 15
Source File: StringValue.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the contents of this string to the contents of the given <tt>CharBuffer</tt>.
 * The characters between the buffer's current position (inclusive) and the buffer's
 * limit (exclusive) will be stored in this string.
 *  
 * @param buffer The character buffer to read the characters from.
 */
public void setValue(CharBuffer buffer) {
	checkNotNull(buffer);
	final int len = buffer.length();
	ensureSize(len);
	buffer.get(this.value, 0, len);
	this.len = len;
	this.hashCode = 0;
}
 
Example 16
Source File: LoadTextUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static ConvertResult convertLineSeparatorsToSlashN(@Nonnull CharBuffer buffer) {
  int dst = 0;
  char prev = ' ';
  int crCount = 0;
  int lfCount = 0;
  int crlfCount = 0;

  final int length = buffer.length();
  final char[] bufferArray = CharArrayUtil.fromSequenceWithoutCopying(buffer);

  for (int src = 0; src < length; src++) {
    char c = bufferArray != null ? bufferArray[src] : buffer.charAt(src);
    switch (c) {
      case '\r':
        if (bufferArray != null) bufferArray[dst++] = '\n';
        else buffer.put(dst++, '\n');
        crCount++;
        break;
      case '\n':
        if (prev == '\r') {
          crCount--;
          crlfCount++;
        }
        else {
          if (bufferArray != null) bufferArray[dst++] = '\n';
          else buffer.put(dst++, '\n');
          lfCount++;
        }
        break;
      default:
        if (bufferArray != null) bufferArray[dst++] = c;
        else buffer.put(dst++, c);
        break;
    }
    prev = c;
  }

  String detectedLineSeparator = guessLineSeparator(crCount, lfCount, crlfCount);

  CharSequence result = buffer.length() == dst ? buffer : buffer.subSequence(0, dst);
  return new ConvertResult(result, detectedLineSeparator);
}
 
Example 17
Source File: WriterOutputStream.java    From marathonv5 with Apache License 2.0 4 votes vote down vote up
/**
 * Writes <code>len</code> bytes from the specified byte array starting at
 * offset <code>off</code> to this output stream. The general contract for
 * <code>write(b, off, len)</code> is that some of the bytes in the array
 * <code>b</code> are written to the output stream in order; element
 * <code>b[off]</code> is the first byte written and
 * <code>b[off+len-1]</code> is the last byte written by this operation.
 * <p>
 * If <code>off</code> is negative, or <code>len</code> is negative, or
 * <code>off+len</code> is greater than the length of the array
 * <code>b</code>, then an <tt>IndexOutOfBoundsException</tt> is thrown.
 *
 * @param b
 *            the data.
 * @param off
 *            the start offset in the data.
 * @param len
 *            the number of bytes to write.
 * @exception IOException
 *                if an I/O error occurs. In particular, an
 *                <code>IOException</code> is thrown if the output stream is
 *                closed.
 */
@Override
public void write(byte[] b, int off, int len) throws IOException {
    synchronized (writer) {
        if (!isOpen) {
            return;
        }
        if (off < 0 || len <= 0 || off + len > b.length) {
            throw new IndexOutOfBoundsException();
        }
        ByteBuffer bytes = ByteBuffer.wrap(b, off, len);
        CharBuffer chars = CharBuffer.allocate(len);
        byte2char(bytes, chars);
        char[] cbuf = new char[chars.length()];
        chars.get(cbuf, 0, chars.length());
        writer.write(cbuf);
        writer.flush();
    }
}
 
Example 18
Source File: FragmentEncoder.java    From compliance with Apache License 2.0 4 votes vote down vote up
private static String decode(String s, Charset charset) {

      char[] str_buf = new char[s.length()];
      byte[] buf = new byte[s.length() / 3];
      int buf_len = 0;

      for (int i = 0; i < s.length();) {
          char c = s.charAt(i);
          if (c == '+') {
              str_buf[buf_len] = ' ';
          } else if (c == '%') {

              int len = 0;
              do {
                  if (i + 2 >= s.length()) {
                      throw new IllegalArgumentException(
                              "Incomplete % sequence at: " + i);
                  }
                  int d1 = Character.digit(s.charAt(i + 1), 16);
                  int d2 = Character.digit(s.charAt(i + 2), 16);
                  if (d1 == -1 || d2 == -1) {
                      throw new IllegalArgumentException(
                              "Invalid % sequence "
                                      + s.substring(i, i + 3)
                                      + " at " + i);
                  }
                  buf[len++] = (byte) ((d1 << 4) + d2);
                  i += 3;
              } while (i < s.length() && s.charAt(i) == '%');

              CharBuffer cb = charset.decode(ByteBuffer.wrap(buf, 0, len));
              len = cb.length();
              System.arraycopy(cb.array(), 0, str_buf, buf_len, len);
              buf_len += len;
              continue;
          } else {
              str_buf[buf_len] = c;
          }
          i++;
          buf_len++;
      }
      return new String(str_buf, 0, buf_len);
  }
 
Example 19
Source File: String.java    From juniversal with MIT License 4 votes vote down vote up
/**
 * Converts the byte array to a String using the specified encoding.
 * 
 * @param data
 *            the byte array to convert to a String
 * @param start
 *            the starting offset in the byte array
 * @param length
 *            the number of bytes to convert
 * @param encoding
 *            the encoding
 * 
 * @throws IndexOutOfBoundsException
 *             when <code>length < 0, start < 0</code> or
 *             <code>start + length > data.length</code>
 * @throws NullPointerException
 *             when data is null
 * 
 * @see #getBytes()
 * @see #getBytes(int, int, byte[], int)
 * @see #getBytes(String)
 * @see #valueOf(boolean)
 * @see #valueOf(char)
 * @see #valueOf(char[])
 * @see #valueOf(char[], int, int)
 * @see #valueOf(double)
 * @see #valueOf(float)
 * @see #valueOf(int)
 * @see #valueOf(long)
 * @see #valueOf(Object)
 * @since 1.6
 */
public String(byte[] data, int start, int length, final Charset encoding) {
    if (encoding == null) {
        throw new NullPointerException();
    }
    // start + length could overflow, start/length maybe MaxInt
    if (start >= 0 && 0 <= length && length <= data.length - start) {
        offset = 0;
        lastCharset = encoding;
        
        CharBuffer cb = encoding
                .decode(ByteBuffer.wrap(data, start, length));
        value = cb.array();
        count = cb.length();
    } else {
        throw new StringIndexOutOfBoundsException();
    }
}
 
Example 20
Source File: Reader.java    From jtransc with Apache License 2.0 3 votes vote down vote up
/**
 * Reads characters and puts them into the {@code target} character buffer.
 *
 * @param target
 *            the destination character buffer.
 * @return the number of characters put into {@code target} or -1 if the end
 *         of this reader has been reached before a character has been read.
 * @throws IOException
 *             if any I/O error occurs while reading from this reader.
 * @throws NullPointerException
 *             if {@code target} is {@code null}.
 * @throws ReadOnlyBufferException
 *             if {@code target} is read-only.
 */
public int read(CharBuffer target) throws IOException {
    int length = target.length();
    char[] buf = new char[length];
    length = Math.min(length, read(buf));
    if (length > 0) {
        target.put(buf, 0, length);
    }
    return length;
}