Example usage for java.io ByteArrayInputStream available

List of usage examples for java.io ByteArrayInputStream available

Introduction

In this page you can find the example usage for java.io ByteArrayInputStream available.

Prototype

public synchronized int available() 

Source Link

Document

Returns the number of remaining bytes that can be read (or skipped over) from this input stream.

Usage

From source file:com.adito.util.ProxiedHttpMethod.java

public HttpResponse execute(HttpRequest request, HttpConnection connection) throws IOException {

    String encodedContent = "";
    /**/*from ww w  . j av a  2 s . c o m*/
     * Encode parameters into content if application/x-www-form-urlencoded
     */
    if (wwwURLEncodedParameters) {
        String key;
        String value;
        Vector v;
        for (Enumeration e = getParameterNames(); e.hasMoreElements();) {

            key = (String) e.nextElement();
            v = getParameterValueList(key);

            for (Iterator it2 = v.iterator(); it2.hasNext();) {
                value = (String) it2.next();
                encodedContent += (encodedContent.length() > 0 ? "&" : "")
                        + Util.urlEncode(key,
                                (charsetEncoding == null ? SystemProperties.get("adito.urlencoding", "UTF-8")
                                        : charsetEncoding))
                        + "="
                        + Util.urlEncode(value,
                                (charsetEncoding == null ? SystemProperties.get("adito.urlencoding", "UTF-8")
                                        : charsetEncoding));
            }
        }

        if (encodedContent.length() > 0) {
            if (charsetEncoding == null) {
                ByteArrayInputStream in = new ByteArrayInputStream(encodedContent.getBytes());
                setContent(in, in.available(), "application/x-www-form-urlencoded");
            } else {
                ByteArrayInputStream in = new ByteArrayInputStream(encodedContent.getBytes(charsetEncoding));
                setContent(in, in.available(), "application/x-www-form-urlencoded");
            }
        }
    }

    // Setup all the proxied headers
    for (Enumeration e = proxiedHeaders.getHeaderFieldNames(); e.hasMoreElements();) {
        String header = (String) e.nextElement();
        if (header.equalsIgnoreCase("Authorization"))
            if (request.getHeaderField("Authorization") != null)
                continue;
        String[] values = proxiedHeaders.getHeaderFields(header);
        for (int i = 0; i < values.length; i++) {
            request.addHeaderField(header, values[i]);
        }
    }

    request.performRequest(this, connection);

    // If the request is multipart/form-data then copy the streams now
    if (content != null) {

        if (log.isDebugEnabled())
            log.debug("Sending " + contentLength + " bytes of content");

        content.mark(bufferSize);

        try {
            int read;
            byte[] buf = new byte[4096];
            long total = 0;

            do {
                read = content.read(buf, 0, (int) Math.min(buf.length, contentLength - total));

                if (log.isDebugEnabled())
                    log.debug("Sent " + read + " bytes of content");
                if (read > -1) {
                    total += read;
                    connection.getOutputStream().write(buf, 0, read);
                    connection.getOutputStream().flush();
                }
            } while (read > -1 && (contentLength - total) > 0);

        } finally {
            content.reset();
        }

        if (log.isDebugEnabled())
            log.debug("Completed sending request content");
    }

    return new HttpResponse(connection);
}

From source file:com.sslexplorer.util.ProxiedHttpMethod.java

public HttpResponse execute(HttpRequest request, HttpConnection connection) throws IOException {

    String encodedContent = "";
    /**/*from   w ww.j  ava  2  s .  c  o  m*/
     * Encode parameters into content if application/x-www-form-urlencoded
     */
    if (wwwURLEncodedParameters) {
        String key;
        String value;
        Vector v;
        for (Enumeration e = getParameterNames(); e.hasMoreElements();) {

            key = (String) e.nextElement();
            v = getParameterValueList(key);

            for (Iterator it2 = v.iterator(); it2.hasNext();) {
                value = (String) it2.next();
                encodedContent += (encodedContent.length() > 0 ? "&" : "") + Util.urlEncode(key,
                        (charsetEncoding == null ? SystemProperties.get("sslexplorer.urlencoding", "UTF-8")
                                : charsetEncoding))
                        + "="
                        + Util.urlEncode(value,
                                (charsetEncoding == null
                                        ? SystemProperties.get("sslexplorer.urlencoding", "UTF-8")
                                        : charsetEncoding));
            }
        }

        if (encodedContent.length() > 0) {
            if (charsetEncoding == null) {
                ByteArrayInputStream in = new ByteArrayInputStream(encodedContent.getBytes());
                setContent(in, in.available(), "application/x-www-form-urlencoded");
            } else {
                ByteArrayInputStream in = new ByteArrayInputStream(encodedContent.getBytes(charsetEncoding));
                setContent(in, in.available(), "application/x-www-form-urlencoded");
            }
        }
    }

    // Setup all the proxied headers
    for (Enumeration e = proxiedHeaders.getHeaderFieldNames(); e.hasMoreElements();) {
        String header = (String) e.nextElement();
        if (header.equalsIgnoreCase("Authorization"))
            if (request.getHeaderField("Authorization") != null)
                continue;
        String[] values = proxiedHeaders.getHeaderFields(header);
        for (int i = 0; i < values.length; i++) {
            request.addHeaderField(header, values[i]);
        }
    }

    request.performRequest(this, connection);

    // If the request is multipart/form-data then copy the streams now
    if (content != null) {

        if (log.isDebugEnabled())
            log.debug("Sending " + contentLength + " bytes of content");

        content.mark(bufferSize);

        try {
            int read;
            byte[] buf = new byte[4096];
            long total = 0;

            do {
                read = content.read(buf, 0, (int) Math.min(buf.length, contentLength - total));

                if (log.isDebugEnabled())
                    log.debug("Sent " + read + " bytes of content");
                if (read > -1) {
                    total += read;
                    connection.getOutputStream().write(buf, 0, read);
                    connection.getOutputStream().flush();
                }
            } while (read > -1 && (contentLength - total) > 0);

        } finally {
            content.reset();
        }

        if (log.isDebugEnabled())
            log.debug("Completed sending request content");
    }

    return new HttpResponse(connection);
}

From source file:org.apache.cordova.test.CordovaResourceApiTest.java

protected void setUp() throws Exception {
    super.setUp();
    setUpWithStartUrl(null);/*from  ww  w  . j  a va 2 s  .  c o m*/
    resourceApi = cordovaWebView.getResourceApi();
    resourceApi.setThreadCheckingEnabled(false);
    cordovaWebView.getPluginManager()
            .addService(new PluginEntry("CordovaResourceApiTestPlugin1", new CordovaPlugin() {
                @Override
                public Uri remapUri(Uri uri) {
                    if (uri.getQuery() != null && uri.getQuery().contains("pluginRewrite")) {
                        return cordovaWebView.getResourceApi()
                                .remapUri(Uri.parse("data:text/plain;charset=utf-8,pass"));
                    }
                    if (uri.getQuery() != null && uri.getQuery().contains("pluginUri")) {
                        return toPluginUri(uri);
                    }
                    return null;
                }

                @Override
                public OpenForReadResult handleOpenForRead(Uri uri) throws IOException {
                    Uri orig = fromPluginUri(uri);
                    ByteArrayInputStream retStream = new ByteArrayInputStream(
                            orig.toString().getBytes(StandardCharsets.UTF_8));
                    return new OpenForReadResult(uri, retStream, "text/plain", retStream.available(), null);
                }

                @Override
                public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
                        throws JSONException {
                    synchronized (CordovaResourceApiTest.this) {
                        execPayload = args.getString(0);
                        execStatus = args.getInt(1);
                        CordovaResourceApiTest.this.notify();
                    }
                    return true;
                }
            }));
}

From source file:groovyx.net.http.EncoderRegistry.java

/**
 * Default request encoder for a binary stream.  Acceptable argument
 * types are://from   www .j ava  2  s .c o  m
 * <ul>
 *   <li>InputStream</li>
 *   <li>byte[] / ByteArrayOutputStream</li>
 *   <li>Closure</li>
 * </ul>
 * If a closure is given, it is executed with an OutputStream passed
 * as the single closure argument.  Any data sent to the stream from the
 * body of the closure is used as the request content body.
 * @param data
 * @return an {@link HttpEntity} encapsulating this request data
 * @throws UnsupportedEncodingException
 */
public InputStreamEntity encodeStream(Object data, Object contentType) throws UnsupportedEncodingException {
    InputStreamEntity entity = null;

    if (data instanceof ByteArrayInputStream) {
        // special case for ByteArrayIS so that we can set the content length.
        ByteArrayInputStream in = ((ByteArrayInputStream) data);
        entity = new InputStreamEntity(in, in.available());
    } else if (data instanceof InputStream) {
        entity = new InputStreamEntity((InputStream) data, -1);
    } else if (data instanceof byte[]) {
        byte[] out = ((byte[]) data);
        entity = new InputStreamEntity(new ByteArrayInputStream(out), out.length);
    } else if (data instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream out = ((ByteArrayOutputStream) data);
        entity = new InputStreamEntity(new ByteArrayInputStream(out.toByteArray()), out.size());
    } else if (data instanceof Closure) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ((Closure) data).call(out); // data is written to out
        entity = new InputStreamEntity(new ByteArrayInputStream(out.toByteArray()), out.size());
    }

    if (entity == null)
        throw new IllegalArgumentException("Don't know how to encode " + data + " as a byte stream");

    if (contentType == null)
        contentType = ContentType.BINARY;
    entity.setContentType(contentType.toString());
    return entity;
}

From source file:com.jayway.restassured.internal.http.EncoderRegistry.java

/**
 * Default request encoder for a binary stream.  Acceptable argument
 * types are://from  w w w .  ja  v a2s  .  c om
 * <ul>
 * <li>InputStream</li>
 * <li>byte[] / ByteArrayOutputStream</li>
 * <li>Closure</li>
 * </ul>
 * If a closure is given, it is executed with an OutputStream passed
 * as the single closure argument.  Any data sent to the stream from the
 * body of the closure is used as the request content body.
 *
 * @param data
 * @return an {@link HttpEntity} encapsulating this request data
 * @throws UnsupportedEncodingException
 */
public InputStreamEntity encodeStream(Object contentType, Object data) throws UnsupportedEncodingException {
    InputStreamEntity entity = null;

    if (data instanceof ByteArrayInputStream) {
        // special case for ByteArrayIS so that we can set the content length.
        ByteArrayInputStream in = ((ByteArrayInputStream) data);
        entity = new InputStreamEntity(in, in.available());
    } else if (data instanceof InputStream) {
        entity = new InputStreamEntity((InputStream) data, -1);
    } else if (data instanceof File) {
        FileInputStream fileInputStream;
        File file = (File) data;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("File " + file.getPath() + " not found", e);
        }
        entity = new InputStreamEntity(fileInputStream, -1);
    } else if (data instanceof byte[]) {
        byte[] out = ((byte[]) data);
        entity = new InputStreamEntity(new ByteArrayInputStream(out), out.length);
    } else if (data instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream out = ((ByteArrayOutputStream) data);
        entity = new InputStreamEntity(new ByteArrayInputStream(out.toByteArray()), out.size());
    } else if (data instanceof Closure) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ((Closure) data).call(out); // data is written to out
        entity = new InputStreamEntity(new ByteArrayInputStream(out.toByteArray()), out.size());
    }

    if (entity == null)
        throw new IllegalArgumentException("Don't know how to encode " + data
                + " as a byte stream.\n\nPlease use EncoderConfig (EncoderConfig#encodeContentTypeAs) to specify how to serialize data for this content-type.\n"
                + "For example: \"given().config(RestAssured.config().encoderConfig(encoderConfig().encodeContentTypeAs(\""
                + ContentTypeExtractor.getContentTypeWithoutCharset(contentTypeToString(contentType))
                + "\", ContentType.TEXT))). ..\"");

    entity.setContentType(contentTypeToString(contentType));
    return entity;
}

From source file:org.lockss.util.TestCharsetUtil.java

/**
 * Method: joinStreamsWithCharset(byte[] buf,
 *                                InputStream tail, String charset)
 *//*from   www .j ava  2  s.c o  m*/
public void testJoinStreamsWithCharset() throws Exception {
    byte[] buf = new byte[100]; // create an input stream
    String buf_string;
    ByteArrayInputStream bais = new ByteArrayInputStream(HTML_FILE.getBytes("UTF-8"));
    // read the first 100 bytes.
    int in_length = bais.available();
    bais.read(buf, 0, buf.length);
    buf_string = new String(buf, "UTF-8");
    int str_length = buf_string.length();
    assertEquals(in_length - buf.length, bais.available());
    // create a new CharsetReader
    Reader rdr = CharsetUtil.joinStreamsWithCharset(buf, bais, "UTF-8");
    char[] charbuf = new char[str_length];
    // read in the chars that we already read...
    rdr.read(charbuf);
    assertEquals(buf_string.toCharArray(), charbuf);
}

From source file:org.apache.pdfbox.pdmodel.font.PDFont.java

/**
 * Returns the width of the given Unicode string.
 *
 * @param text The text to get the width of.
 * @return The width of the string in 1/1000 units of text space.
 * @throws IOException If there is an error getting the width information.
 *///from www .  j  av a 2  s  .  c  om
public float getStringWidth(String text) throws IOException {
    byte[] bytes = encode(text);
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);

    float width = 0;
    while (in.available() > 0) {
        int code = readCode(in);
        width += getWidth(code);
    }

    return width;
}

From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java

protected void applyParameters(PreparedStatement statement, ParameterValueList parameters)
        throws SQLException, SenderException {
    // statement.clearParameters();

    /*/*from   w w w .  ja v a2  s  .  c  om*/
          // getParameterMetaData() is not supported on the WebSphere java.sql.PreparedStatement implementation.
          int senderParameterCount = parameters.size();
          int statementParameterCount = statement.getParameterMetaData().getParameterCount();
          if (statementParameterCount<senderParameterCount) {
             throw new SenderException(getLogPrefix()+"statement has more ["+statementParameterCount+"] parameters defined than sender ["+senderParameterCount+"]");
          }
    */

    for (int i = 0; i < parameters.size(); i++) {
        ParameterValue pv = parameters.getParameterValue(i);
        String paramType = pv.getDefinition().getType();
        Object value = pv.getValue();
        //      log.debug("applying parameter ["+(i+1)+","+parameters.getParameterValue(i).getDefinition().getName()+"], value["+parameterValue+"]");

        if (Parameter.TYPE_DATE.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.DATE);
            } else {
                statement.setDate(i + 1, new java.sql.Date(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_DATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIMESTAMP.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIME);
            } else {
                statement.setTime(i + 1, new java.sql.Time(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_XMLDATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_NUMBER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.NUMERIC);
            } else {
                statement.setDouble(i + 1, ((Number) value).doubleValue());
            }
        } else if (Parameter.TYPE_INTEGER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.INTEGER);
            } else {
                statement.setInt(i + 1, (Integer) value);
            }
        } else if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) {
            if (value instanceof FileInputStream) {
                FileInputStream fis = (FileInputStream) value;
                long len = 0;
                try {
                    len = fis.getChannel().size();
                } catch (IOException e) {
                    log.warn(getLogPrefix() + "could not determine file size", e);
                }
                statement.setBinaryStream(i + 1, fis, (int) len);
            } else if (value instanceof ByteArrayInputStream) {
                ByteArrayInputStream bais = (ByteArrayInputStream) value;
                long len = bais.available();
                statement.setBinaryStream(i + 1, bais, (int) len);
            } else {
                throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass()
                        + "] for parameter [" + pv.getDefinition().getName() + "]");
            }
        } else if ("string2bytes".equals(paramType)) {
            statement.setBytes(i + 1, ((String) value).getBytes());
        } else if ("bytes".equals(paramType)) {
            statement.setBytes(i + 1, (byte[]) value);
        } else {
            statement.setString(i + 1, (String) value);
        }
    }
}

From source file:de.dal33t.powerfolder.test.transfer.BandwidthLimitText.java

public void testLimiteds() {
    BandwidthLimiter bl = BandwidthLimiter.LAN_INPUT_BANDWIDTH_LIMITER;
    bl.setAvailable(10000);// w w  w.j a  v a  2s.c  o m
    byte b[] = new byte[1000];

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try (LimitedOutputStream out = new LimitedOutputStream(bl, bout)) {
        out.write(b);
    } catch (IOException e) {
        fail(e.toString());
    }
    assertTrue("Wrong amount left/write", bl.getAvailable() == 10000 - b.length);
    assertTrue("Wrong amount written", bout.size() == b.length);
    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
    bl.setAvailable(10000);
    int read = 0;
    try (LimitedInputStream in = new LimitedInputStream(bl, bin)) {
        read = in.read(b);
    } catch (IOException e) {
        fail(e.toString());
    }
    assertTrue("Wrong amount left/read", bl.getAvailable() == 10000 - read);
    assertTrue("Wrong amount read", bin.available() == b.length - read);
}

From source file:com.github.devnied.emvnfccard.parser.EmvParser.java

/**
 * Extract list of application file locator from Afl response
 *
 * @param pAfl/*from   w w  w. j  a  va  2 s.c o m*/
 *            AFL data
 * @return list of AFL
 */
protected List<Afl> extractAfl(final byte[] pAfl) {
    List<Afl> list = new ArrayList<Afl>();
    ByteArrayInputStream bai = new ByteArrayInputStream(pAfl);
    while (bai.available() >= 4) {
        Afl afl = new Afl();
        afl.setSfi(bai.read() >> 3);
        afl.setFirstRecord(bai.read());
        afl.setLastRecord(bai.read());
        afl.setOfflineAuthentication(bai.read() == 1);
        list.add(afl);
    }
    return list;
}