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:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

/**
 * Initialize UI model from a .jzml file
 * //  w ww.  j a  va2  s.c  o  m
 * @param zipTouchoscFilePath a .jzml file
 * 
 * @return UI model
 */
public TouchOscApp loadAppFromTouchOscXML(String zipTouchoscFilePath) {
    //
    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    IPath path = new Path(zipTouchoscFilePath);

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    List<String> touchoscFilePathList = new ArrayList<String>();
    try {
        FileInputStream touchoscFile = new FileInputStream(zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);

        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(path.removeLastSegments(1) + "/_" + path.lastSegment());
            }
            FileOutputStream os = new FileOutputStream(path.removeLastSegments(1) + "/_" + path.lastSegment());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.append("</touchosc:TOP>\n");
            charBuffer.flip();

            String content = charBuffer.toString();
            content = content.replace("<touchosc>", "");
            content = content.replace("</touchosc>", "");
            content = content.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", TOUCHOSC_XMLNS_HEADER);
            content = content.replace("numberX=", "number_x=");
            content = content.replace("numberY=", "number_y=");
            content = content.replace("invertedX=", "inverted_x=");
            content = content.replace("invertedY=", "inverted_y=");
            content = content.replace("localOff=", "local_off=");
            content = content.replace("oscCs=", "osc_cs=");

            writer.write(content);
            writer.flush();
            os.flush();
            os.close();
        }
        fileIS.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(touchoscFilePathList.get(0));

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.getResource(touchoscURI, true);

    Object obj = (Object) resource.getContents().get(0);
    if (obj instanceof TOP) {
        TOP top = (TOP) obj;
        reverseZOrders(top);
        return initAppFromTouchOsc(top.getLayout(), "horizontal".equals(top.getLayout().getOrientation()),
                "0".equals(top.getLayout().getMode()));
    }
    return null;
}

From source file:com.asakusafw.runtime.io.csv.CsvParser.java

private void emit(int c) throws IOException {
    assert c >= 0;
    CharBuffer buf = lineBuffer;
    if (buf.remaining() == 0) {
        if (buf.capacity() == BUFFER_LIMIT) {
            throw new IOException(
                    MessageFormat.format("Line is too large (near {0}:{1}, size={2}, record-number={3})", path,
                            currentPhysicalHeadLine, BUFFER_LIMIT, currentRecordNumber));
        }/*from  w  w w .ja v  a 2 s . c  o m*/
        CharBuffer newBuf = CharBuffer.allocate(Math.min(buf.capacity() * 2, BUFFER_LIMIT));
        newBuf.clear();
        buf.flip();
        newBuf.put(buf);
        buf = newBuf;
        lineBuffer = newBuf;
    }
    buf.put((char) c);
}

From source file:org.apache.fop.fonts.MultiByteFont.java

/**
 * Map sequence GS, comprising a sequence of Glyph Indices, to output sequence CS,
 * comprising a sequence of UTF-16 encoded Unicode Code Points.
 * @param gs a GlyphSequence containing glyph indices
 * @returns a CharSequence containing UTF-16 encoded Unicode characters
 */// w  w w .j av  a  2 s  . c om
private CharSequence mapGlyphsToChars(GlyphSequence gs) {
    int ng = gs.getGlyphCount();
    CharBuffer cb = CharBuffer.allocate(ng);
    int ccMissing = Typeface.NOT_FOUND;
    for (int i = 0, n = ng; i < n; i++) {
        int gi = gs.getGlyph(i);
        int cc = findCharacterFromGlyphIndex(gi);
        if ((cc == 0) || (cc > 0x10FFFF)) {
            cc = ccMissing;
            log.warn("Unable to map glyph index " + gi + " to Unicode scalar in font '" + getFullName()
                    + "', substituting missing character '" + (char) cc + "'");
        }
        if (cc > 0x00FFFF) {
            int sh;
            int sl;
            cc -= 0x10000;
            sh = ((cc >> 10) & 0x3FF) + 0xD800;
            sl = ((cc >> 0) & 0x3FF) + 0xDC00;
            cb.put((char) sh);
            cb.put((char) sl);
        } else {
            cb.put((char) cc);
        }
    }
    cb.flip();
    return (CharSequence) cb;
}

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 .java 2  s .  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.auraframework.util.text.Hash.java

/**
 * Consumes and closes a reader to generate its contents' hash.
 *
 * @param reader the reader for pulling content. Must be at the beginning of file.
 *//*from  ww  w . j  a v a2  s.  co  m*/
public void setHash(Reader reader) throws IOException, IllegalStateException {
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        Charset utf8 = Charset.forName("UTF-8");
        CharBuffer cbuffer = CharBuffer.allocate(2048);
        while (reader.read(cbuffer) >= 0) {
            cbuffer.flip();
            ByteBuffer bytes = utf8.encode(cbuffer);
            digest.update(bytes);
            cbuffer.clear();
        }
        setHash(digest.digest());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("MD5 is a required MessageDigest algorithm, but is not registered here.");
    } finally {
        reader.close();
    }
}

From source file:org.codehaus.groovy.grails.web.util.StreamByteBuffer.java

public String readAsString(Charset charset) throws CharacterCodingException {
    int unreadSize = totalBytesUnread();
    if (unreadSize > 0) {
        CharsetDecoder decoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE)
                .onUnmappableCharacter(CodingErrorAction.REPLACE);
        CharBuffer charbuffer = CharBuffer.allocate(unreadSize);
        ByteBuffer buf = null;/* w w  w .  ja v a2s . c  o m*/
        while (prepareRead() != -1) {
            buf = currentReadChunk.readToNioBuffer();
            boolean endOfInput = (prepareRead() == -1);
            CoderResult result = decoder.decode(buf, charbuffer, endOfInput);
            if (endOfInput) {
                if (!result.isUnderflow()) {
                    result.throwException();
                }
            }
        }
        CoderResult result = decoder.flush(charbuffer);
        if (buf.hasRemaining()) {
            throw new IllegalStateException("There's a bug here, buffer wasn't read fully.");
        }
        if (!result.isUnderflow()) {
            result.throwException();
        }
        charbuffer.flip();
        String str;
        if (charbuffer.hasArray()) {
            int len = charbuffer.remaining();
            char[] ch = charbuffer.array();
            if (len != ch.length) {
                ch = ArrayUtils.subarray(ch, 0, len);
            }
            str = StringCharArrayAccessor.createString(ch);
        } else {
            str = charbuffer.toString();
        }
        return str;
    }
    return null;
}

From source file:org.ingini.mongodb.jongo.example.util.CollectionManager.java

private static void fill(DBCollection collection, String collectionContentFilePath) {
    StringBuilder stringBuilder = new StringBuilder();

    try {//from  w  ww . j  a  va  2s.  com
        InputStreamReader inputStreamReader = new InputStreamReader( //
                CollectionManager.class.getClassLoader().getResourceAsStream(collectionContentFilePath),
                "UTF-8");
        CharBuffer buf = CharBuffer.allocate(BUFFER_SIZE);
        for (int read = inputStreamReader.read(buf); read != EOF; read = inputStreamReader.read(buf)) {
            buf.flip();
            stringBuilder.append(buf, START, read);

        }
    } catch (IOException e) {
        System.out.println("Unable to read input stream due to an exception! Exception: "
                + ExceptionUtils.getStackTrace(e));
        throw new IllegalStateException(e);
    }

    BasicDBList parse = (BasicDBList) JSON.parse(stringBuilder.toString(),
            new MongoIdTransformerJSONCallback());
    collection.insert(parse.toArray(new DBObject[parse.size()]));
}

From source file:org.kuali.student.common.io.IOUtils.java

private static String decode(CharsetDecoder decoder, byte[] in) {

    ByteBuffer inBuf = ByteBuffer.wrap(in);

    CharBuffer outBuf = CharBuffer.allocate(inBuf.capacity() * Math.round(decoder.maxCharsPerByte() + 0.5f));

    decoder.decode(inBuf, outBuf, true);

    decoder.flush(outBuf);/*from   w  ww .  ja  va  2s.  co m*/

    decoder.reset();

    return outBuf.flip().toString();

}

From source file:org.omnaest.utils.structure.container.ByteArrayContainer.java

/**
 * Copies the content from a {@link Readable} using the given encoding
 * //  w w  w .  j  a  va 2s  .  c o m
 * @param readable
 * @param encoding
 * @return this
 */
public ByteArrayContainer copyFrom(Readable readable, String encoding) {
    //
    this.isContentInvalid = false;
    if (readable != null) {
        //
        encoding = StringUtils.defaultString(encoding, ENCODING_UTF8);

        //
        try {
            //
            final StringBuffer stringBuffer = new StringBuffer();
            final CharBuffer charBuffer = CharBuffer.wrap(new char[1000]);
            for (int read = 0; read >= 0;) {
                //
                charBuffer.clear();
                read = readable.read(charBuffer);
                charBuffer.flip();
                if (read > 0) {
                    stringBuffer.append(charBuffer, 0, read);
                }
            }

            this.copyFrom(stringBuffer, encoding);
        } catch (IOException e) {
            //
            this.isContentInvalid = true;

            //
            this.handleException(e);
        }
    }

    //
    return this;
}

From source file:org.openbel.framework.ws.utils.Converter.java

private static Byte encode(final CharsetEncoder encoder, final char c) {
    encoder.reset();/*  ww w  .java 2s .co  m*/
    if (!encoder.canEncode(c)) {
        return null;
    }
    encoder.reset();
    ByteBuffer buffer = ByteBuffer.allocate(1);
    CharBuffer charBuffer = CharBuffer.allocate(1).put(c);
    charBuffer.flip();
    CoderResult result = null;

    result = encoder.encode(charBuffer, buffer, false);
    if (!result.isUnderflow()) {
        return null;
    }
    result = encoder.encode(charBuffer, buffer, true);
    if (result.isMalformed() || result.isUnmappable()) {
        return null;
    }
    result = encoder.flush(buffer);
    if (!result.isUnderflow()) {
        return null;
    }
    buffer.flip();
    return buffer.get(0);
}