Example usage for java.nio CharBuffer allocate

List of usage examples for java.nio CharBuffer allocate

Introduction

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

Prototype

public static CharBuffer allocate(int capacity) 

Source Link

Document

Creates a char buffer based on a newly allocated char array.

Usage

From source file:org.lockss.plugin.clockss.wolterskluwer.TestRewritingReader.java

public void testEmptyReader() throws Exception {
    // Also test that asking for input after EOF doesn't throw
    LineRewritingReader rr = null;//from www .j a  v  a  2 s. co m
    char[] buf = new char[64];
    CharBuffer cb = CharBuffer.allocate(64);

    // Using read()
    try {
        rr = new StringRewritingReader("");
        assertEquals(-1, rr.read());
        assertEquals(-1, rr.read());
    } finally {
        IOUtils.closeQuietly(rr);
    }

    // Using read(char[])
    try {
        rr = new StringRewritingReader("");
        assertEquals(-1, rr.read(buf));
        assertEquals(-1, rr.read(buf));
    } finally {
        IOUtils.closeQuietly(rr);
    }

    // Using read(char[],int,int)
    try {
        rr = new StringRewritingReader("");
        assertEquals(-1, rr.read(buf, 12, 34));
        assertEquals(-1, rr.read(buf, 12, 34));
    } finally {
        IOUtils.closeQuietly(rr);
    }

    // Using read(CharBuffer)
    try {
        rr = new StringRewritingReader("");
        assertEquals(-1, rr.read(cb));
        assertEquals(-1, rr.read(cb));
    } finally {
        IOUtils.closeQuietly(rr);
    }
}

From source file:org.marketcetera.util.unicode.ReaderTest.java

@Test
public void regularReader() throws Exception {
    CloseableRegistry r = new CloseableRegistry();
    try {//from  www.jav a  2  s  .c o m
        ByteArrayInputStream is = new ByteArrayInputStream(HELLO_EN_NAT);
        r.register(new InputStreamWrapper(is));
        UnicodeInputStreamReader reader = new UnicodeInputStreamReader(is);
        r.register(new ReaderWrapper(reader));

        assertNull(reader.getDecodingStrategy());
        assertNull(reader.getRequestedSignatureCharset());
        assertNull(reader.getSignatureCharset());

        assertTrue(reader.ready());

        assertFalse(reader.markSupported());

        try {
            reader.mark(0);
            fail();
        } catch (IOException ex) {
            // Desired.
        }

        try {
            reader.reset();
            fail();
        } catch (IOException ex) {
            // Desired.
        }

        assertEquals(HELLO_EN.charAt(0), reader.read());

        assertEquals(1, reader.skip(1));

        char[] charArray = new char[1];
        assertEquals(1, reader.read(charArray));
        assertEquals(HELLO_EN.charAt(2), charArray[0]);

        charArray = new char[3];
        assertEquals(1, reader.read(charArray, 1, 1));
        assertEquals(HELLO_EN.charAt(3), charArray[1]);

        CharBuffer charBuffer = CharBuffer.allocate(10);
        assertEquals(1, reader.read(charBuffer));
        assertEquals(HELLO_EN.charAt(4), charBuffer.get(0));

        assertEquals(-1, reader.read());
        assertEquals(-1, reader.read(charArray));
        assertEquals(-1, reader.read(charArray, 1, 1));
        assertEquals(-1, reader.read(charBuffer));
        assertFalse(reader.ready());

        reader.close();
        reader.close();

        // Ensure that close() has closed the stream, by trying to
        // read from the reader: this is not testing whether
        // read() fails; it tests whether close() worked.
        try {
            reader.read();
            fail();
        } catch (IOException ex) {
            // Desired.
        }

        try {
            reader.ready();
            fail();
        } catch (IOException ex) {
            // Desired.
        }
    } finally {
        r.close();
    }
}

From source file:org.marketcetera.util.unicode.ReaderTest.java

@Test
public void emptyReader() throws Exception {
    CloseableRegistry r = new CloseableRegistry();
    r = new CloseableRegistry();
    try {/*  w  w w.  j av  a2 s  .c  o  m*/
        ByteArrayInputStream is = new ByteArrayInputStream(ArrayUtils.EMPTY_BYTE_ARRAY);
        r.register(new InputStreamWrapper(is));
        UnicodeInputStreamReader reader = new UnicodeInputStreamReader(is);
        r.register(new ReaderWrapper(reader));

        assertNull(reader.getDecodingStrategy());
        assertNull(reader.getRequestedSignatureCharset());
        assertNull(reader.getSignatureCharset());

        assertFalse(reader.ready());

        assertFalse(reader.markSupported());

        try {
            reader.mark(0);
            fail();
        } catch (IOException ex) {
            // Desired.
        }

        try {
            reader.reset();
            fail();
        } catch (IOException ex) {
            // Desired.
        }

        assertEquals(-1, reader.read());

        char[] charArray = new char[1];
        assertEquals(-1, reader.read(charArray));

        charArray = new char[3];
        assertEquals(-1, reader.read(charArray, 1, 1));

        CharBuffer charBuffer = CharBuffer.allocate(10);
        assertEquals(-1, reader.read(charBuffer));

        reader.close();
        reader.close();

        // Ensure that close() has closed the stream, by trying to
        // read from the reader: this is not testing whether
        // read() fails; it tests whether close() worked.
        try {
            reader.read();
            fail();
        } catch (IOException ex) {
            // Desired.
        }

        try {
            reader.ready();
            fail();
        } catch (IOException ex) {
            // Desired.
        }
    } finally {
        r.close();
    }
}

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

private static Byte encode(final CharsetEncoder encoder, final char c) {
    encoder.reset();//from   ww  w .jav  a  2  s. c o 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);
}

From source file:org.openhab.binding.lutron.internal.net.TelnetSession.java

public TelnetSession() {
    this.telnetClient = new TelnetClient();
    this.charBuffer = CharBuffer.allocate(BUFSIZE);

    this.telnetClient.setReaderThread(true);
    this.telnetClient.registerInputListener(new TelnetInputListener() {
        @Override// w w  w .  j a  va 2 s.c  om
        public void telnetInputAvailable() {
            try {
                readInput();
            } catch (IOException e) {
                notifyInputError(e);
            }
        }
    });
}

From source file:org.paxle.core.doc.impl.AParserDocumentTest.java

protected void appendData(File source, IParserDocument target) throws IOException {
    final StringBuilder sourceText = new StringBuilder();

    // writing Data
    final CharBuffer buffer = CharBuffer.allocate(50);
    final InputStreamReader sourceReader = new InputStreamReader(new FileInputStream(source),
            Charset.forName("UTF-8"));
    while (sourceReader.read(buffer) != -1) {
        buffer.flip();// w  w  w .j  a  va 2  s.  c o  m
        sourceText.append(buffer);
        target.append(buffer.toString());
        buffer.clear();
    }

    sourceReader.close();
    target.flush();
}

From source file:org.wurstworks.tools.pinto.AbstractPintoBean.java

/**
 * Display the help for each of the available command-line parameters supported by this bean. The help is printed to
 * the stream specified by the {@link #setPrintStream(java.io.PrintStream)} property or passed in through the
 * {@link AbstractPintoBean#AbstractPintoBean(Object, String[], java.io.PrintStream)} constructor.
 *///from   w  ww.j a  v  a 2s. c o  m
public void displayHelp() {
    if (_parametersByShortOption == null || _parametersByShortOption.size() == 0) {
        getPrintStream().println("No parameters found for this application!");
    } else {
        // TODO: Add an annotation to put application name, copyright info, and introductory help text on the class level.
        String appName, copyright, introduction;
        PintoApplication application = _parent.getClass().getAnnotation(PintoApplication.class);
        if (application == null) {
            appName = _parent.getClass().getSimpleName();
            copyright = introduction = null;
        } else {
            appName = application.value();
            copyright = application.copyright();
            introduction = application.introduction();
        }

        getPrintStream().println(appName);
        if (!StringUtils.isBlank(copyright)) {
            getPrintStream().println(copyright);
        }
        if (!StringUtils.isBlank(introduction)) {
            getPrintStream().println(introduction);
        }
        getPrintStream().println();

        for (ParameterData parameter : _parametersByShortOption.values()) {
            StringBuilder parameterText = new StringBuilder(PREFIX);
            parameterText.append(SHORT_OPTION_DELIMITER).append(parameter.getShortOption());
            if (parameter.hasLongOption()) {
                parameterText.append(", ").append(LONG_OPTION_DELIMITER).append(parameter.getLongOption());
            }

            // If our parameter text is so long that it will either run into the hanging indent text or directly up
            // to the hanging indent text (i.e., no space left between them)...
            final int length = parameterText.length();
            if (length > HANGING_INDENT - 1) {
                // Then add a new line
                parameterText.append(INDENT_FILLER);
            } else {
                parameterText
                        .append(CharBuffer.allocate(HANGING_INDENT - length).toString().replace('\0', ' '));
            }

            parameterText
                    .append(WordUtils.wrap(parameter.getHelp(), WIDTH - HANGING_INDENT, INDENT_FILLER, true));
            getPrintStream().println(parameterText.toString());
        }
    }
}

From source file:uk.ac.cam.caret.sakai.rwiki.utils.NameHelper.java

private static String normalize(final String nameToNormalize, final boolean isPageName) {
    char[] chars = nameToNormalize.toCharArray();
    int charBufferLength = chars.length + 1 + (isPageName ? DEFAULT_PAGE.length() : 0);
    CharBuffer name = CharBuffer.allocate(charBufferLength);

    int wordStart = 0;

    boolean addSeparator = true;
    boolean addWhiteSpaceOrSeparator = true;
    int numberOfSeparators = 0;

    for (int i = 0; i < chars.length; i++) {
        char c = chars[i];

        if (c == SPACE_SEPARATOR) {
            if (!addWhiteSpaceOrSeparator) {
                name.put(chars, wordStart, i - wordStart);
            }/*from  w ww  . ja  va  2 s  . c  o  m*/
            addSeparator = true;
            addWhiteSpaceOrSeparator = true;
        } else if (Character.isWhitespace(c)) {
            if (!addWhiteSpaceOrSeparator) {
                name.put(chars, wordStart, i - wordStart);

            }
            addWhiteSpaceOrSeparator = true;
        } else if (addSeparator) {
            name.put(SPACE_SEPARATOR);
            if (++numberOfSeparators > 2) {
                chars[i] = Character.toLowerCase(c);
            }
            wordStart = i;
            addSeparator = false;
            addWhiteSpaceOrSeparator = false;
        } else if (addWhiteSpaceOrSeparator) {
            addWhiteSpaceOrSeparator = false;
            wordStart = i;
            name.put(' ');
            if (numberOfSeparators > 2) {
                chars[i] = Character.toLowerCase(c);
            }
        } else {
            if (numberOfSeparators > 2) {
                chars[i] = Character.toLowerCase(c);
            }
        }

    }

    if (addSeparator && isPageName) {
        name.put(SPACE_SEPARATOR);
        name.put(DEFAULT_PAGE);
    } else if (!addWhiteSpaceOrSeparator) {
        name.put(chars, wordStart, chars.length - wordStart);
    }

    int position = name.position();
    name.position(0);
    name.limit(position);

    return name.toString();
}

From source file:uk.ac.ebi.arrayexpress.servlets.HttpProxyServlet.java

@Override
protected void doRequest(HttpServletRequest request, HttpServletResponse response, RequestType requestType)
        throws ServletException, IOException {
    RegexHelper MATCH_URL_REGEX = new RegexHelper("/+(.+)", "i");
    RegexHelper TEST_HOST_IN_URL_REGEX = new RegexHelper("^http\\:/{2}([^/]+)/", "i");
    RegexHelper SQUARE_BRACKETS_REGEX = new RegexHelper("\\[\\]", "g");

    logRequest(logger, request, requestType);

    String url = MATCH_URL_REGEX.matchFirst(request.getPathInfo());
    url = url.replaceFirst("http:/{1,2}", "http://"); // stupid hack as tomcat 6.0 removes second forward slash
    String queryString = request.getQueryString();

    if (0 < url.length()) {
        if (!TEST_HOST_IN_URL_REGEX.test(url)) { // no host here, will self
            url = "http://localhost:" + String.valueOf(request.getLocalPort()) + "/" + url;
        }/*from  w  w w  .ja va  2s  .  c  om*/
        logger.debug("Will access [{}]", url);

        GetMethod getMethod = new GetMethod(url);

        if (null != queryString) {
            queryString = SQUARE_BRACKETS_REGEX.replace(queryString, "%5B%5D");
            getMethod.setQueryString(queryString);
        }

        Enumeration requestHeaders = request.getHeaderNames();
        while (requestHeaders.hasMoreElements()) {
            String name = (String) requestHeaders.nextElement();
            String value = request.getHeader(name);
            if (null != value) {
                getMethod.setRequestHeader(name, value);
            }
        }

        try {
            httpClient.executeMethod(getMethod);

            int statusCode = getMethod.getStatusCode();
            long contentLength = getMethod.getResponseContentLength();
            logger.debug("Got response [{}], length [{}]", statusCode, contentLength);

            Header[] responseHeaders = getMethod.getResponseHeaders();
            for (Header responseHeader : responseHeaders) {
                String name = responseHeader.getName();
                String value = responseHeader.getValue();
                if (null != name && null != value && !(name.equals("Server") || name.equals("Date")
                        || name.equals("Transfer-Encoding"))) {
                    response.setHeader(responseHeader.getName(), responseHeader.getValue());
                }
            }

            if (200 != statusCode) {
                response.setStatus(statusCode);
            }

            InputStream inStream = getMethod.getResponseBodyAsStream();
            if (null != inStream) {
                BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));

                CharBuffer buffer = CharBuffer.allocate(PROXY_BUFFER_SIZE);
                while (in.read(buffer) >= 0) {
                    buffer.flip();
                    out.append(buffer);
                    buffer.clear();
                }

                in.close();
                out.close();
            }
        } catch (Exception x) {
            if (x.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
                logger.warn("Client aborted connection");
            } else {
                logger.error("Caught an exception:", x);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage());
            }
        } finally {
            getMethod.releaseConnection();
        }
    }
}