Example usage for java.nio CharBuffer charAt

List of usage examples for java.nio CharBuffer charAt

Introduction

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

Prototype

public final char charAt(int index) 

Source Link

Document

Returns the character located at the specified index in the buffer.

Usage

From source file:Main.java

public static void main(String[] args) {
    CharBuffer cb1 = CharBuffer.allocate(50);
    cb1.append("java2s.com");
    cb1.rewind();/*from  w  w w . jav a  2s.c om*/

    System.out.println(cb1.charAt(2));
    System.out.println(Arrays.toString(cb1.array()));

}

From source file:Main.java

public static void main(String[] args) {
    CharBuffer cb1 = CharBuffer.allocate(50);
    cb1.append("java2s.com");
    cb1.rewind();//from   w w w . ja  v a 2  s  .  c  om

    System.out.println(cb1.charAt(2));
    System.out.println(Arrays.toString(cb1.array()));

    CharBuffer cb2 = cb1.slice();
    System.out.println(Arrays.toString(cb2.array()));

}

From source file:Main.java

public static void main(String[] args) {
    CharBuffer cb1 = CharBuffer.allocate(50);
    cb1.append("java2s.com");
    cb1.rewind();//from  w  w  w.  j a  v  a  2  s.c  o m

    System.out.println(cb1.charAt(2));
    System.out.println(Arrays.toString(cb1.array()));

    CharBuffer cb2 = cb1.compact();
    System.out.println(Arrays.toString(cb2.array()));

}

From source file:com.healthmarketscience.jackcess.impl.office.EncryptionHeader.java

private static String readCspName(ByteBuffer buffer) {

    // unicode string, must be multiple of 2
    int rem = (buffer.remaining() / 2) * 2;
    String cspName = "";
    if (rem > 0) {

        ByteBuffer cspNameBuf = ByteBuffer.wrap(ByteUtil.getBytes(buffer, rem));
        CharBuffer tmpCspName = UNICODE_CHARSET.decode(cspNameBuf);

        // should be null terminated, strip that
        for (int i = 0; i < tmpCspName.limit(); ++i) {
            if (tmpCspName.charAt(i) == '\0') {
                tmpCspName.limit(i);//from w  w  w  .  j a  v  a2 s . c  o  m
                break;
            }
        }

        cspName = tmpCspName.toString();
    }

    return cspName;
}

From source file:com.arksoft.epamms.ZGlobal1_Operation.java

public int StartEmailClientForListReus(View vResult, String entityName, String attributeName,
        String contextName, String stringScope, int bUseOnlySelectedEntities, int bUseParentSelectedEntities,
        String stringSubject, String stringCopyTo, // comma separated list
        String stringBlindCopy, // comma separated list
        String stringBody, String stringAttachment, String stringEmailClient, int lFlags,
        String stringBlindCopyFlag) // reserved
{
    String stringParentEntity = null;
    String s = null;//from  ww w . j  a  va2 s  .  co m
    int lEntityCnt;
    int ulAttributeLth = 0;
    int lTotalSize;
    int lLth = 0;
    int lRC;

    if (bUseParentSelectedEntities != 0)
        stringParentEntity = MiGetParentEntityNameForView(stringParentEntity, vResult, entityName);

    lEntityCnt = CountEntitiesForView(vResult, entityName);
    ulAttributeLth = GetAttributeDisplayLength(ulAttributeLth, vResult, entityName, attributeName, contextName);
    lTotalSize = lEntityCnt * (int) ulAttributeLth; // a starting point
    CharBuffer cbMemory = CharBuffer.allocate(lTotalSize + 1);
    // DrAllocTaskMemory( cbMemory, lTotalSize + 1 );

    // For each entity, append the specified data to the list.
    // lRC = SetCursorFirstEntity( vResult, entityName, stringScope );
    lRC = SetEntityCursor(vResult, entityName, "", zPOS_FIRST, "", "", "", 0, stringScope, "");

    while (lRC > zCURSOR_UNCHANGED) {
        if (bUseOnlySelectedEntities == 0
                || ((bUseOnlySelectedEntities != 0) && GetSelectStateOfEntity(vResult, entityName) != 0)
                || ((bUseParentSelectedEntities != 0)
                        && GetSelectStateOfEntity(vResult, stringParentEntity) != 0)) {
            s = GetVariableFromAttribute(s, 0, zTYPE_STRING, lTotalSize - lLth - 1, vResult, entityName,
                    attributeName, contextName,
                    contextName != null && contextName.isEmpty() == false ? 0 : zUSE_DEFAULT_CONTEXT);
            lLth = zstrcpy(cbMemory, lLth, s);
            while (lLth > 0 && cbMemory.charAt(lLth - 1) == ' ') {
                lLth--;
                cbMemory.put(lLth, '\0');
            }
        }

        // lRC = SetCursorNextEntity( vResult, entityName, stringScope );
        lRC = SetEntityCursor(vResult, entityName, "", zPOS_NEXT, "", "", "", 0, stringScope, "");
        if (lRC > zCURSOR_UNCHANGED) {
            // lLth = zstrlen( stringMemory );
            if (lTotalSize - lLth < (int) ulAttributeLth) {
                s = cbMemory.toString();

                lEntityCnt *= 2;
                lTotalSize = lEntityCnt * (int) ulAttributeLth;
                cbMemory = CharBuffer.allocate(lTotalSize + 1);
                zstrcpy(cbMemory, 0, s);
            }

            if (lLth > 0 && cbMemory.charAt(lLth - 1) != ',') {
                cbMemory.put(lLth++, ',');
                cbMemory.put(lLth, '\0');
            }
        }
    }

    if (stringBlindCopyFlag.charAt(0) == 'Y') {
        // Email Addresses are to be put in Blind Copy parameter.
        TraceLineS("Blind Copies: ", cbMemory.toString());
        lRC = m_ZDRVROPR.StartEmailClient(stringBlindCopy, // Regular send parameter
                stringSubject, stringCopyTo, // comma separated list
                cbMemory.toString(), // Blind Copy parameter
                stringBody, stringAttachment, "", lFlags); // reserved
    } else {
        // Email Addresses are to be put in regular Send parameter.
        TraceLineS("Regular Copies: ", cbMemory.toString());
        lRC = m_ZDRVROPR.StartEmailClient(cbMemory.toString(), // comma separated list
                stringSubject, stringCopyTo, // comma separated list
                stringBlindCopy, // comma separated list
                stringBody, stringAttachment, stringEmailClient, lFlags); // reserved
    }

    // DrFreeTaskMemory( (String) cbMemory );
    return lRC;
}

From source file:com.quinsoft.swauopencuas.ZGLOBAL1_Operation.java

public int StartEmailClientForListReus(View vResult, String entityName, String attributeName,
        String contextName, String stringScope, int bUseOnlySelectedEntities, int bUseParentSelectedEntities,
        String stringSubject, String stringCopyTo, // comma separated list
        String stringBlindCopy, // comma separated list
        String stringBody, String stringAttachment, String stringEmailClient, int lFlags,
        String stringBlindCopyFlag) // reserved
{
    String stringParentEntity = null;
    String s = null;//  www  .  ja va2s  .  c o m
    int lEntityCnt;
    int ulAttributeLth = 0;
    int lTotalSize;
    int lLth = 0;
    int lRC;

    if (bUseParentSelectedEntities != 0)
        stringParentEntity = MiGetParentEntityNameForView(stringParentEntity, vResult, entityName);

    lEntityCnt = CountEntitiesForView(vResult, entityName);
    ulAttributeLth = GetAttributeDisplayLength(ulAttributeLth, vResult, entityName, attributeName, contextName);
    lTotalSize = lEntityCnt * ulAttributeLth; // a starting point
    CharBuffer cbMemory = CharBuffer.allocate(lTotalSize + 1);
    // DrAllocTaskMemory( cbMemory, lTotalSize + 1 );

    // For each entity, append the specified data to the list.
    // lRC = SetCursorFirstEntity( vResult, entityName, stringScope );
    lRC = SetEntityCursor(vResult, entityName, "", zPOS_FIRST, "", "", "", 0, stringScope, "");

    while (lRC > zCURSOR_UNCHANGED) {
        if (bUseOnlySelectedEntities == 0
                || ((bUseOnlySelectedEntities != 0) && GetSelectStateOfEntity(vResult, entityName) != 0)
                || ((bUseParentSelectedEntities != 0)
                        && GetSelectStateOfEntity(vResult, stringParentEntity) != 0)) {
            s = GetVariableFromAttribute(s, 0, zTYPE_STRING, lTotalSize - lLth - 1, vResult, entityName,
                    attributeName, contextName,
                    contextName != null && contextName.isEmpty() == false ? 0 : zUSE_DEFAULT_CONTEXT);
            lLth = zstrcpy(cbMemory, lLth, s);
            while (lLth > 0 && cbMemory.charAt(lLth - 1) == ' ') {
                lLth--;
                cbMemory.put(lLth, '\0');
            }
        }

        // lRC = SetCursorNextEntity( vResult, entityName, stringScope );
        lRC = SetEntityCursor(vResult, entityName, "", zPOS_NEXT, "", "", "", 0, stringScope, "");
        if (lRC > zCURSOR_UNCHANGED) {
            // lLth = zstrlen( stringMemory );
            if (lTotalSize - lLth < ulAttributeLth) {
                s = cbMemory.toString();

                lEntityCnt *= 2;
                lTotalSize = lEntityCnt * ulAttributeLth;
                cbMemory = CharBuffer.allocate(lTotalSize + 1);
                zstrcpy(cbMemory, 0, s);
            }

            if (lLth > 0 && cbMemory.charAt(lLth - 1) != ',') {
                cbMemory.put(lLth++, ',');
                cbMemory.put(lLth, '\0');
            }
        }
    }

    if (stringBlindCopyFlag.charAt(0) == 'Y') {
        // Email Addresses are to be put in Blind Copy parameter.
        TraceLineS("Blind Copies: ", cbMemory.toString());
        lRC = m_ZDRVROPR.StartEmailClient(stringBlindCopy, // Regular send parameter
                stringSubject, stringCopyTo, // comma separated list
                cbMemory.toString(), // Blind Copy parameter
                stringBody, stringAttachment, "", lFlags); // reserved
    } else {
        // Email Addresses are to be put in regular Send parameter.
        TraceLineS("Regular Copies: ", cbMemory.toString());
        lRC = m_ZDRVROPR.StartEmailClient(cbMemory.toString(), // comma separated list
                stringSubject, stringCopyTo, // comma separated list
                stringBlindCopy, // comma separated list
                stringBody, stringAttachment, stringEmailClient, lFlags); // reserved
    }

    // DrFreeTaskMemory( (String) cbMemory );
    return lRC;
}

From source file:org.nuxeo.ecm.platform.filemanager.service.extension.NoteImporter.java

protected static String guessEncoding(Blob blob) throws IOException {
    // encoding already known?
    if (blob.getEncoding() != null) {
        return null;
    }//from   www  .  j  a  v  a2  s.c om

    // bad mime type?
    String mimeType = blob.getMimeType();
    if (mimeType == null) {
        return null;
    }
    if (!mimeType.startsWith("text/") && !mimeType.startsWith("application/xhtml")) {
        // not a text file, we shouldn't be in the Note importer
        return null;
    }

    byte[] bytes = blob.getByteArray();

    List<String> charsets = new ArrayList<>(Arrays.asList("utf-8", "iso-8859-1"));

    String CSEQ = "charset=";
    int i = mimeType.indexOf(CSEQ);
    if (i > 0) {
        // charset specified in MIME type
        String onlyMimeType = mimeType.substring(0, i).replace(";", "").trim();
        blob.setMimeType(onlyMimeType);
        String charset = mimeType.substring(i + CSEQ.length());
        i = charset.indexOf(";");
        if (i > 0) {
            charset = charset.substring(0, i);
        }
        charset = charset.trim().replace("\"", "");
        charsets.add(0, charset);
    } else {
        // charset detected from the actual bytes
        CharsetMatch charsetMatch = new CharsetDetector().setText(bytes).detect();
        if (charsetMatch != null) {
            String charset = charsetMatch.getName();
            charsets.add(0, charset);
        }
    }

    // now convert the string according to the charset, and fallback on others if not possible
    for (String charset : charsets) {
        try {
            Charset cs = Charset.forName(charset);
            CharsetDecoder d = cs.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
                    .onUnmappableCharacter(CodingErrorAction.REPORT);
            CharBuffer cb = d.decode(ByteBuffer.wrap(bytes));
            if (cb.length() != 0 && cb.charAt(0) == '\ufeff') {
                // remove BOM
                cb = cb.subSequence(1, cb.length());
            }
            return cb.toString();
        } catch (IllegalArgumentException e) {
            // illegal charset
        } catch (CharacterCodingException e) {
            // could not decode
        }
    }
    // nothing worked, use platform
    return null;
}

From source file:org.paxle.core.norm.impl.ReferenceNormalizer.java

static String urlDecode(final String str, final Charset charset) throws ParseException {
    int percent = str.indexOf('%');
    if (percent == -1)
        return str;

    final StringBuffer sb = new StringBuffer(str.length()); // buffer to build the converted string
    final ByteArrayOutputStream baos = new ByteArrayOutputStream(8); // buffer for conversion of contiguous %-encoded bytes
    int last = 0;
    final int len = str.length();
    do {/*  w w w.  ja va 2  s .c o  m*/
        sb.append(str.substring(last, percent)); // write non-encoded part

        // loop to convert sequence of %-encoded tokens into bytes. Contiguous byte-sequences have to be dealt with
        // in one block before decoding, because - dependant on the charset - more than one byte may be needed to
        // represent a single character. If the conversion to bytes was done sequentially, decoding might fail
        do {
            if (percent + 3 > str.length())
                throw new ParseException("unexpected end of input", percent + 3);
            final String token = str.substring(percent + 1, percent + 3);
            if (!token.matches("[0-9a-fA-F]{2}"))
                throw new ParseException("illegal url-encoded token '" + token + "'", percent);

            final int tokenValue = Integer.parseInt(token, 16) & 0xFF;
            baos.write(tokenValue);
            percent += 3;
        } while (percent < len && str.charAt(percent) == '%');

        if (baos.size() > 0) {
            final CharBuffer decoded = charset.decode(ByteBuffer.wrap(baos.toByteArray()));
            baos.reset(); // reuse the ByteArrayOutputStream in the next run
            for (int i = 0; i < decoded.length(); i++) {
                final char c = decoded.charAt(i);
                switch (c) {
                case '#':
                    sb.append("%23");
                    continue;
                case '%':
                    sb.append("%25");
                    continue;
                case '&':
                    sb.append("%26");
                    continue;
                case '=':
                    sb.append("%3D");
                    continue;
                case '?':
                    sb.append("%3F");
                    continue;
                default:
                    sb.append(c);
                    continue;
                }
            }
        }

        last = percent; // byte after the token
        percent = str.indexOf('%', last); // search for next token, returns -1 if last > len
    } while (percent != -1);
    return sb.append(str.substring(last)).toString();
}

From source file:pyromaniac.IO.MMFastaImporter.java

/**
 * _init qual./*from   w ww .jav  a2  s.c o  m*/
 *
 * @throws Exception the exception
 */
private void _initQual() throws Exception {
    FileInputStream tempStream = new FileInputStream(new File(this.qualFile));
    FileChannel fcQual = tempStream.getChannel();
    this.qualSizeLong = fcQual.size();

    //qual starts LL contains pairs, marking file #no (in  qualBuffers) and position #no (in the buffer).
    this.qualStartsLL = new ArrayList<Pair<Integer, Long>>();

    for (long startPosition = 0L; startPosition < this.qualSizeLong; startPosition += HALF_GIGA) {
        MappedByteBuffer qualBuffer = fcQual.map(FileChannel.MapMode.READ_ONLY, startPosition,
                Math.min(this.qualSizeLong - startPosition, HALF_GIGA)); //map half a gig to this channel.
        this.qualBuffers.add(qualBuffer);
        int qbf_pos = qualBuffers.size() - 1;
        int maxBuffer = 2048;
        int bufferSize = (qualBuffer.capacity() > maxBuffer) ? maxBuffer : qualBuffer.capacity();

        qualBuffer.limit(bufferSize);
        qualBuffer.position(0);

        while (qualBuffer.position() != qualBuffer.capacity()) {
            int prevPos = qualBuffer.position();
            CharBuffer result = decoder.decode(qualBuffer);
            qualBuffer.position(prevPos);

            for (int i = 0; i < result.capacity(); i++) {
                char curr = result.charAt(i);
                int posInFile = prevPos + i;

                if (curr == BEGINNING_FASTA_HEADER) {
                    qualStartsLL.add(new Pair<Integer, Long>(qbf_pos, new Long(posInFile)));
                }
            }

            int newPos = qualBuffer.limit();

            if (qualBuffer.limit() + bufferSize > qualBuffer.capacity())
                qualBuffer.limit(qualBuffer.capacity());
            else
                qualBuffer.limit(qualBuffer.limit() + bufferSize);
            qualBuffer.position(newPos);
        }
        qualBuffer.rewind();
    }
}

From source file:pyromaniac.IO.MMFastaImporter.java

/**
 * _init seq.//from   w w  w. ja  va2s. c om
 *
 * @throws Exception the exception
 */
private void _initSeq() throws Exception {
    FileInputStream tempStream = new FileInputStream(new File(this.seqFile));
    FileChannel fcSeq = tempStream.getChannel();
    this.seqSizeLong = fcSeq.size();
    this.seqStartsLL = new ArrayList<Pair<Integer, Long>>();

    for (long startPosition = 0L; startPosition < this.seqSizeLong; startPosition += HALF_GIGA) {
        MappedByteBuffer seqBuffer = fcSeq.map(FileChannel.MapMode.READ_ONLY, startPosition,
                Math.min(this.seqSizeLong - startPosition, HALF_GIGA));

        this.seqBuffers.add(seqBuffer);
        int sbf_pos = seqBuffers.size() - 1;
        int maxBuffer = 2048;
        int bufferSize = (seqBuffer.capacity() > maxBuffer) ? maxBuffer : seqBuffer.capacity();

        seqBuffer.limit(bufferSize);
        seqBuffer.position(0);

        while (seqBuffer.position() != seqBuffer.capacity()) {
            int prevPos = seqBuffer.position();
            CharBuffer result = decoder.decode(seqBuffer);
            seqBuffer.position(prevPos);

            for (int i = 0; i < result.capacity(); i++) {
                char curr = result.charAt(i);
                int posInFile = prevPos + i;

                if (curr == BEGINNING_FASTA_HEADER) {
                    seqStartsLL.add(new Pair<Integer, Long>(sbf_pos, new Long(posInFile)));
                }
            }

            int newPos = seqBuffer.limit();

            if (seqBuffer.limit() + bufferSize > seqBuffer.capacity())
                seqBuffer.limit(seqBuffer.capacity());
            else
                seqBuffer.limit(seqBuffer.limit() + bufferSize);
            seqBuffer.position(newPos);
        }
        seqBuffer.rewind();
    }

}