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:com.cloudbees.jenkins.support.filter.FilteredOutputStreamTest.java

@Issue("JENKINS-21670")
@Test//from   w ww.j  a v  a2  s. c o m
public void shouldSupportLinesLargerThanDefaultBufferSize() throws IOException {
    CharBuffer input = CharBuffer.allocate(FilteredConstants.DEFAULT_DECODER_CAPACITY * 10);
    for (int i = 0; i < input.capacity(); i++) {
        input.put('*');
    }
    input.flip();
    InputStream in = new CharSequenceInputStream(input, UTF_8);
    FilteredOutputStream out = new FilteredOutputStream(testOutput, s -> s.replace('*', 'a'));

    IOUtils.copy(in, out);
    String contents = new String(testOutput.toByteArray(), UTF_8);

    assertThat(contents).isEmpty();

    out.flush();
    contents = new String(testOutput.toByteArray(), UTF_8);

    assertThat(contents).isNotEmpty().matches("^a+$");
}

From source file:com.gargoylesoftware.htmlunit.NoHttpResponseTest.java

@Override
public void run() {
    try {/*www . ja va 2 s  .c  o  m*/
        serverSocket_ = new ServerSocket(port_);
        started_.set(true);
        LOG.info("Starting listening on port " + port_);
        while (!shutdown_) {
            final Socket s = serverSocket_.accept();
            final BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

            final CharBuffer cb = CharBuffer.allocate(5000);
            br.read(cb);
            cb.flip();
            final String in = cb.toString();
            cb.rewind();

            final RawResponseData responseData = getResponseData(in);

            if (responseData == null || responseData.getStringContent() == DROP_CONNECTION) {
                LOG.info("Closing impolitely in & output streams");
                s.getOutputStream().close();
            } else {
                final PrintWriter pw = new PrintWriter(s.getOutputStream());
                pw.println("HTTP/1.0 " + responseData.getStatusCode() + " " + responseData.getStatusMessage());
                for (final NameValuePair header : responseData.getHeaders()) {
                    pw.println(header.getName() + ": " + header.getValue());
                }
                pw.println();
                pw.println(responseData.getStringContent());
                pw.println();
                pw.flush();
                pw.close();
            }
            br.close();
            s.close();
        }
    } catch (final SocketException e) {
        if (!shutdown_) {
            LOG.error(e);
        }
    } catch (final IOException e) {
        LOG.error(e);
    } finally {
        LOG.info("Finished listening on port " + port_);
    }
}

From source file:com.metawiring.load.generators.LineExtractGenerator.java

private void loadLines(String filename) {

    InputStream stream = LineExtractGenerator.class.getClassLoader().getResourceAsStream(filename);
    if (stream == null) {
        throw new RuntimeException(filename + " was missing.");
    }//from w w w  . j av a2s  .  c o  m

    CharBuffer linesImage;
    try {
        InputStreamReader isr = new InputStreamReader(stream);
        linesImage = CharBuffer.allocate(1024 * 1024);
        isr.read(linesImage);
        isr.close();
    } catch (IOException e) {
        logger.error(e.getMessage());
        throw new RuntimeException(e);
    }
    linesImage.flip();
    Collections.addAll(lines, linesImage.toString().split("\n"));
}

From source file:com.metawiring.load.generators.LoremExtractGenerator.java

private CharBuffer loadLoremIpsum() {
    InputStream stream = LoremExtractGenerator.class.getClassLoader()
            .getResourceAsStream("data/lorem_ipsum_full.txt");
    if (stream == null) {
        throw new RuntimeException("lorem_ipsum_full.txt was missing.");
    }/*from   w  ww  .j a v a  2s . co  m*/

    CharBuffer image;
    try {
        InputStreamReader isr = new InputStreamReader(stream);
        image = CharBuffer.allocate(1024 * 1024);
        isr.read(image);
        isr.close();
    } catch (IOException e) {
        logger.error(e.getMessage());
        throw new RuntimeException(e);
    }
    image.flip();

    return image.asReadOnlyBuffer();

}

From source file:com.metawiring.load.generators.ExtractGenerator.java

private CharBuffer loadFileData() {
    InputStream stream = null;/*from   ww w  . j a  va2 s .c  o m*/
    File onFileSystem = new File("data" + File.separator + fileName);

    if (onFileSystem.exists()) {
        try {
            stream = new FileInputStream(onFileSystem);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(
                    "Unable to find file " + onFileSystem.getPath() + " after verifying that it exists.");
        }
        logger.debug("Loaded file data from " + onFileSystem.getPath());
    }

    if (stream == null) {
        stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("data/" + fileName);
        logger.debug("Loaded file data from classpath resource " + fileName);
    }

    if (stream == null) {
        throw new RuntimeException(fileName + " was missing.");
    }

    CharBuffer image;
    try {
        InputStreamReader isr = new InputStreamReader(stream);
        image = CharBuffer.allocate(1024 * 1024);
        isr.read(image);
        isr.close();
    } catch (IOException e) {
        logger.error(e.getMessage());
        throw new RuntimeException(e);
    }
    image.flip();

    return image.asReadOnlyBuffer();

}

From source file:com.google.flatbuffers.Table.java

/**
 * Create a Java `String` from UTF-8 data stored inside the FlatBuffer.
 *
 * This allocates a new string and converts to wide chars upon each access,
 * which is not very efficient. Instead, each FlatBuffer string also comes with an
 * accessor based on __vector_as_bytebuffer below, which is much more efficient,
 * assuming your Java program can handle UTF-8 data directly.
 *
 * @param offset An `int` index into the Table's ByteBuffer.
 * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`.
 *///from  ww w  .  ja  v a 2s .co m
protected String __string(int offset) {
    CharsetDecoder decoder = UTF8_DECODER.get();
    decoder.reset();

    offset += bb.getInt(offset);
    ByteBuffer src = bb.duplicate().order(ByteOrder.LITTLE_ENDIAN);
    int length = src.getInt(offset);
    src.position(offset + SIZEOF_INT);
    src.limit(offset + SIZEOF_INT + length);

    int required = (int) ((float) length * decoder.maxCharsPerByte());
    CharBuffer dst = CHAR_BUFFER.get();
    if (dst == null || dst.capacity() < required) {
        dst = CharBuffer.allocate(required);
        CHAR_BUFFER.set(dst);
    }

    dst.clear();

    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new Error(x);
    }

    return dst.flip().toString();
}

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

private int getNextCharacter() throws IOException {
    CharBuffer buf = readerBuffer;
    if (buf.remaining() == 0) {
        buf.clear();// w  w w  .j a  v a  2 s .com
        int read = reader.read(buf);
        buf.flip();
        assert read != 0;
        if (read < 0) {
            return EOF;
        }
    }
    return buf.get();
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

public String loadTouchOscXML(String zipTouchoscFilePath) {
    List<String> touchoscFilePathList = new ArrayList<String>();
    IPath path = new Path(zipTouchoscFilePath);
    String xml = "";
    try {//from  www. j a  v a2 s  . c om
        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());
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileIS, Charset.forName("UTF-8")));
            CharBuffer charBuffer = CharBuffer.allocate(65535);
            while (reader.read(charBuffer) != -1)

                charBuffer.flip();

            xml = charBuffer.toString();

        }

        fileIS.close();

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    return xml;
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

public void dumpTouchOsc(TOP top, String destDirname, String destFilename) {

    reverseZOrders(top);/* w  ww.  jav a  2 s  .  co  m*/
    //
    // Get tests for TouchOSC legacy compliances : need precise version info
    //
    //applyBase64Transformation(top);

    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    //
    // 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);

    String dirname;
    if (destDirname == null) {
        dirname = Platform.getInstanceLocation().getURL().getPath() + "/" + UUID.randomUUID().toString();

        if (Platform.inDebugMode()) {
            System.out.println("creating " + dirname + " directory");
        }

        new File(dirname).mkdir();
    } else {
        dirname = destDirname;
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(dirname + "/" + "index.xml");

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

    resource.getContents().add(top);

    try {
        Map<Object, Object> options = new HashMap<Object, Object>();
        options.put(XMLResource.OPTION_ENCODING, "UTF-8");
        resource.save(options);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String TOUCHOSC_HEADER = "<touchosc:TOP xmi:version=\"2.0\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:touchosc=\"http:///net.sf.smbt.touchosc/src/net/sf/smbt/touchosc/model/touchosc.xsd\">";
    String TOUCHOSC_FOOTER = "</touchosc:TOP>";

    String path = touchoscURI.path().toString();
    String outputZipFile = dirname + "/" + destFilename + ".touchosc";

    try {
        FileInputStream touchoscFile = new FileInputStream(path);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(touchoscFile, Charset.forName("ASCII")));
        CharBuffer charBuffer = CharBuffer.allocate(65535);
        while (reader.read(charBuffer) != -1)

            charBuffer.flip();

        String content = charBuffer.toString();
        content = content.replace(TOUCHOSC_HEADER, "<touchosc>");
        content = content.replace(TOUCHOSC_FOOTER, "</touchosc>");
        content = content.replace("<layout>", "<layout version=\"10\" mode=\"" + top.getLayout().getMode()
                + "\" orientation=\"" + top.getLayout().getOrientation() + "\">");
        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=");
        content = content.replace("xypad", "xy");

        touchoscFile.close();

        FileOutputStream os = new FileOutputStream(path);

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName("UTF-8")));

        writer.write(content);
        writer.flush();

        os.flush();
        os.close();

        FileOutputStream fos = new FileOutputStream(outputZipFile);
        ZipOutputStream fileOS = new ZipOutputStream(fos);

        ZipEntry ze = new ZipEntry("index.xml");
        fileOS.putNextEntry(ze);
        fileOS.write(content.getBytes(Charset.forName("UTF-8")));
        fileOS.flush();
        fileOS.close();
        fos.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        File f = new File(path);
        if (f.exists() && f.canWrite()) {
            if (!f.delete()) {
                throw new IllegalArgumentException(path + " deletion failed");
            }
        }
    }
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

/**
 * Initialize UI model from a .touchosc file
 * //from  www  .jav  a 2 s  .  c om
 * @param zipTouchoscFilePath a .touchosc file
 * 
 * @return UI model
 */
public TouchOscApp loadAppFromTouchOscXML2(String zipTouchoscFilePath) {
    //
    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    //
    // 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 {
        URL url = TouchOSCUtils.class.getClassLoader().getResource(".");

        FileInputStream touchoscFile = new FileInputStream(url.getPath() + "../samples/" + zipTouchoscFilePath);
        ZipInputStream fileIS = new ZipInputStream(touchoscFile);

        ZipEntry zEntry = null;
        while ((zEntry = fileIS.getNextEntry()) != null) {
            if (zEntry.getName().endsWith(".xml")) {
                touchoscFilePathList.add(url.getPath() + "../samples/_" + zipTouchoscFilePath);
            }
            FileOutputStream os = new FileOutputStream(url.getPath() + "../samples/_" + zipTouchoscFilePath);
            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("<?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;
}