Example usage for java.io ByteArrayOutputStream size

List of usage examples for java.io ByteArrayOutputStream size

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream size.

Prototype

public synchronized int size() 

Source Link

Document

Returns the current size of the buffer.

Usage

From source file:org.commoncrawl.util.CompressedURLFPListV2.java

public static void validateURLFPFlagSerializationMultipleSubDomains() {
    TreeMultimap<Long, URLFPV2> sourceMap = TreeMultimap.create();
    TreeMultimap<Long, URLFPV2> destMap = TreeMultimap.create();
    ;//from   w w  w .j  a  va  2  s . c  o m

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    Builder firstBuilder = new Builder(FLAG_ARCHIVE_SEGMENT_ID | FLAG_SERIALIZE_URLFP_FLAGS);

    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "0", 1, 255);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "1", 2, 255);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "2", 3, 255);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "3", 4, 0);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "4", 1, 255);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "5", 2, 255);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "6", 3, 255);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "7", 4, 0);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "8", 1, 255);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "9", 2, 255);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "10", 3, 255);
    insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "11", 4, 0);

    addMapToBuilder(firstBuilder, sourceMap);

    try {
        // flush to byte stream ...
        firstBuilder.flush(byteStream);
        // now set up to read the stream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(byteStream.toByteArray(), 0,
                byteStream.size());
        Reader reader = new Reader(inputStream);

        while (reader.hasNext()) {
            URLFPV2 fp = reader.next();
            destMap.put(fp.getRootDomainHash(), fp);
        }
        reader.close();

        Assert.assertTrue(sourceMap.equals(destMap));

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.xmlrpc.server.XmlRpcStreamServer.java

/** Returns, whether the 
/** Processes a "connection". The "connection" is an opaque object, which is
 * being handled by the subclasses./*w w w .ja  v  a 2 s.c  o  m*/
 * @param pConfig The request configuration.
 * @param pConnection The "connection" being processed.
 * @throws XmlRpcException Processing the request failed.
 */
public void execute(XmlRpcStreamRequestConfig pConfig, ServerStreamConnection pConnection)
        throws XmlRpcException {
    log.debug("execute: ->");
    try {
        Object result;
        Throwable error;
        InputStream istream = null;
        try {
            istream = getInputStream(pConfig, pConnection);
            XmlRpcRequest request = getRequest(pConfig, istream);
            result = execute(request);
            istream.close();
            istream = null;
            error = null;
            log.debug("execute: Request performed successfully");
        } catch (Throwable t) {
            logError(t);
            result = null;
            error = t;
        } finally {
            if (istream != null) {
                try {
                    istream.close();
                } catch (Throwable ignore) {
                }
            }
        }
        boolean contentLengthRequired = isContentLengthRequired(pConfig);
        ByteArrayOutputStream baos;
        OutputStream ostream;
        if (contentLengthRequired) {
            baos = new ByteArrayOutputStream();
            ostream = baos;
        } else {
            baos = null;
            ostream = pConnection.newOutputStream();
        }
        ostream = getOutputStream(pConnection, pConfig, ostream);
        try {
            if (error == null) {
                writeResponse(pConfig, ostream, result);
            } else {
                writeError(pConfig, ostream, error);
            }
            ostream.close();
            ostream = null;
        } finally {
            if (ostream != null) {
                try {
                    ostream.close();
                } catch (Throwable ignore) {
                }
            }
        }
        if (baos != null) {
            OutputStream dest = getOutputStream(pConfig, pConnection, baos.size());
            try {
                baos.writeTo(dest);
                dest.close();
                dest = null;
            } finally {
                if (dest != null) {
                    try {
                        dest.close();
                    } catch (Throwable ignore) {
                    }
                }
            }
        }
        pConnection.close();
        pConnection = null;
    } catch (IOException e) {
        throw new XmlRpcException("I/O error while processing request: " + e.getMessage(), e);
    } finally {
        if (pConnection != null) {
            try {
                pConnection.close();
            } catch (Throwable ignore) {
            }
        }
    }
    log.debug("execute: <-");
}

From source file:edu.ucsd.xmlrpc.xmlrpc.server.XmlRpcStreamServer.java

/** Returns, whether the 
/** Processes a "connection". The "connection" is an opaque object, which is
 * being handled by the subclasses./*from  w  ww  .  j  a  va  2  s . c  o  m*/
 * @param pConfig The request configuration.
 * @param pConnection The "connection" being processed.
 * @throws XmlRpcException Processing the request failed.
 */
public void execute(XmlRpcStreamRequestConfig pConfig, ServerStreamConnection pConnection, WebServer wServer)
        throws XmlRpcException {
    log.debug("execute: ->");
    Object result;
    Throwable error;
    try {
        InputStream istream = null;
        try {
            istream = getInputStream(pConfig, pConnection);
            XmlRpcRequest request = getRequest(pConfig, istream);

            // Ucsd modified code
            StoredRequest storedRequest = new StoredRequest((XmlRpcClientRequestImpl) request);
            if (wServer != null) {
                wServer.addRequest(storedRequest.getRequest().getJobID(), storedRequest);
            }

            result = execute(request);
            storedRequest.setValid(true);
            ;
            storedRequest.setResult(result);

            //TODO DEMO remove
            if (result.equals(-9)) {
                throw new Throwable("Server Disconnected");
            }
            // end

            istream.close();
            istream = null;
            error = null;
            log.debug("execute: Request performed successfully");
        } catch (Throwable t) {
            logError(t);
            result = null;
            error = t;
        } finally {
            if (istream != null) {
                try {
                    istream.close();
                } catch (Throwable ignore) {
                }
            }
        }
        boolean contentLengthRequired = isContentLengthRequired(pConfig);
        ByteArrayOutputStream baos;
        OutputStream ostream;
        if (contentLengthRequired) {
            baos = new ByteArrayOutputStream();
            ostream = baos;
        } else {
            baos = null;
            ostream = pConnection.newOutputStream();
        }
        ostream = getOutputStream(pConnection, pConfig, ostream);
        try {
            if (error == null) {
                writeResponse(pConfig, ostream, result);
            } else {
                writeError(pConfig, ostream, error);
            }
            ostream.close();
            ostream = null;
        } finally {
            if (ostream != null) {
                try {
                    ostream.close();
                } catch (Throwable ignore) {
                }
            }
        }
        if (baos != null) {
            OutputStream dest = getOutputStream(pConfig, pConnection, baos.size());
            try {
                baos.writeTo(dest);
                dest.close();
                dest = null;
            } finally {
                if (dest != null) {
                    try {
                        dest.close();
                    } catch (Throwable ignore) {
                    }
                }
            }
        }
        pConnection.close();
        pConnection = null;
    } catch (IOException e) {
        throw new XmlRpcException("I/O error while processing request: " + e.getMessage(), e);
    } finally {
        if (pConnection != null) {
            try {
                pConnection.close();
            } catch (Throwable ignore) {
            }
        }
    }
    log.debug("execute: <-");
}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Update a resource using Smartsheet REST API.
 *
 * Exceptions:/*from  w  w  w .j av a  2 s. co m*/
 *   IllegalArgumentException : if any argument is null, or path is empty string
 *   InvalidRequestException : if there is any problem with the REST API request
 *   AuthorizationException : if there is any problem with the REST API authorization(access token)
 *   ResourceNotFoundException : if the resource can not be found
 *   ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
 *   SmartsheetRestException : if there is any other REST API related error occurred during the operation
 *   SmartsheetException : if there is any other error occurred during the operation
 *
 * @param <T> the generic type
 * @param path the relative path of the resource
 * @param objectClass the resource object class
 * @param object the object to create
 * @return the updated resource
 * @throws SmartsheetException the smartsheet exception
 */
protected <T> T updateResource(String path, Class<T> objectClass, T object) throws SmartsheetException {
    Util.throwIfNull(path, object);
    Util.throwIfEmpty(path);

    HttpRequest request;
    request = createHttpRequest(smartsheet.getBaseURI().resolve(path), HttpMethod.PUT);

    ByteArrayOutputStream objectBytesStream = new ByteArrayOutputStream();
    this.smartsheet.getJsonSerializer().serialize(object, objectBytesStream);
    HttpEntity entity = new HttpEntity();
    entity.setContentType("application/json");
    entity.setContent(new ByteArrayInputStream(objectBytesStream.toByteArray()));
    entity.setContentLength(objectBytesStream.size());
    request.setEntity(entity);

    T obj = null;
    try {
        HttpResponse response = this.smartsheet.getHttpClient().request(request);
        switch (response.getStatusCode()) {
        case 200:
            obj = this.smartsheet.getJsonSerializer()
                    .deserializeResult(objectClass, response.getEntity().getContent()).getResult();
            break;
        default:
            handleError(response);
        }
    } finally {
        smartsheet.getHttpClient().releaseConnection();
    }

    return obj;
}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Put an object to Smartsheet REST API and receive a list of objects from response.
 *
 * Exceptions://from w  w  w  . jav  a 2 s.c  o m
 *   IllegalArgumentException : if any argument is null, or path is empty string
 *   InvalidRequestException : if there is any problem with the REST API request
 *   AuthorizationException : if there is any problem with the REST API authorization(access token)
 *   ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
 *   SmartsheetRestException : if there is any other REST API related error occurred during the operation
 *   SmartsheetException : if there is any other error occurred during the operation
 *
 * @param <T> the generic type
 * @param <S> the generic type
 * @param path the relative path of the resource collections
 * @param objectToPut the object to put
 * @param objectClassToReceive the resource object class to receive
 * @return the object list
 * @throws SmartsheetException the smartsheet exception
 */
protected <T, S> List<S> putAndReceiveList(String path, T objectToPut, Class<S> objectClassToReceive)
        throws SmartsheetException {
    Util.throwIfNull(path, objectToPut, objectClassToReceive);
    Util.throwIfEmpty(path);

    HttpRequest request = createHttpRequest(smartsheet.getBaseURI().resolve(path), HttpMethod.PUT);

    ByteArrayOutputStream objectBytesStream = new ByteArrayOutputStream();
    this.smartsheet.getJsonSerializer().serialize(objectToPut, objectBytesStream);
    HttpEntity entity = new HttpEntity();
    entity.setContentType("application/json");
    entity.setContent(new ByteArrayInputStream(objectBytesStream.toByteArray()));
    entity.setContentLength(objectBytesStream.size());
    request.setEntity(entity);

    List<S> obj = null;
    try {
        HttpResponse response = this.smartsheet.getHttpClient().request(request);
        switch (response.getStatusCode()) {
        case 200:
            obj = this.smartsheet.getJsonSerializer()
                    .deserializeListResult(objectClassToReceive, response.getEntity().getContent()).getResult();
            break;
        default:
            handleError(response);
        }
    } finally {
        smartsheet.getHttpClient().releaseConnection();
    }

    return obj;
}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Post an object to Smartsheet REST API and receive a list of objects from response.
 *
 * Parameters: - path : the relative path of the resource collections - objectToPost : the object to post -
 * objectClassToReceive : the resource object class to receive
 *
 * Returns: the object list//w  ww . j a  va 2 s  .c  o m
 *
 * Exceptions:
 *   IllegalArgumentException : if any argument is null, or path is empty string
 *   InvalidRequestException : if there is any problem with the REST API request
 *   AuthorizationException : if there is any problem with the REST API authorization(access token)
 *   ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
 *   SmartsheetRestException : if there is any other REST API related error occurred during the operation
 *   SmartsheetException : if there is any other error occurred during the operation
 *
 * @param <T> the generic type
 * @param <S> the generic type
 * @param path the path
 * @param objectToPost the object to post
 * @param objectClassToReceive the object class to receive
 * @return the list
 * @throws SmartsheetException the smartsheet exception
 */
protected <T, S> List<S> postAndReceiveList(String path, T objectToPost, Class<S> objectClassToReceive)
        throws SmartsheetException {
    Util.throwIfNull(path, objectToPost, objectClassToReceive);
    Util.throwIfEmpty(path);

    HttpRequest request = createHttpRequest(smartsheet.getBaseURI().resolve(path), HttpMethod.POST);

    ByteArrayOutputStream objectBytesStream = new ByteArrayOutputStream();
    this.smartsheet.getJsonSerializer().serialize(objectToPost, objectBytesStream);
    HttpEntity entity = new HttpEntity();
    entity.setContentType("application/json");
    entity.setContent(new ByteArrayInputStream(objectBytesStream.toByteArray()));
    entity.setContentLength(objectBytesStream.size());
    request.setEntity(entity);

    List<S> obj = null;
    try {
        HttpResponse response = this.smartsheet.getHttpClient().request(request);
        switch (response.getStatusCode()) {
        case 200:
            obj = this.smartsheet.getJsonSerializer()
                    .deserializeListResult(objectClassToReceive, response.getEntity().getContent()).getResult();
            break;
        default:
            handleError(response);
        }
    } finally {
        smartsheet.getHttpClient().releaseConnection();
    }

    return obj;
}

From source file:com.smartsheet.api.internal.AbstractResources.java

/**
 * Post an object to Smartsheet REST API and receive a CopyOrMoveRowResult object from response.
 *
 * Parameters: - path : the relative path of the resource collections - objectToPost : the object to post -
 *
 * Returns: the object/*  w  w w  .j a v  a  2  s.c  om*/
 *
 * Exceptions:
 *   IllegalArgumentException : if any argument is null, or path is empty string
 *   InvalidRequestException : if there is any problem with the REST API request
 *   AuthorizationException : if there is any problem with the REST API authorization(access token)
 *   ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
 *   SmartsheetRestException : if there is any other REST API related error occurred during the operation
 *   SmartsheetException : if there is any other error occurred during the operation
 *
 * @param path the path
 * @param objectToPost the object to post
 * @return the result object
 * @throws SmartsheetException the smartsheet exception
 */
protected CopyOrMoveRowResult postAndReceiveRowObject(String path, CopyOrMoveRowDirective objectToPost)
        throws SmartsheetException {
    Util.throwIfNull(path, objectToPost);
    Util.throwIfEmpty(path);

    HttpRequest request = createHttpRequest(smartsheet.getBaseURI().resolve(path), HttpMethod.POST);

    ByteArrayOutputStream objectBytesStream = new ByteArrayOutputStream();
    this.smartsheet.getJsonSerializer().serialize(objectToPost, objectBytesStream);
    HttpEntity entity = new HttpEntity();
    entity.setContentType("application/json");
    entity.setContent(new ByteArrayInputStream(objectBytesStream.toByteArray()));
    entity.setContentLength(objectBytesStream.size());
    request.setEntity(entity);

    CopyOrMoveRowResult obj = null;
    try {
        HttpResponse response = this.smartsheet.getHttpClient().request(request);
        switch (response.getStatusCode()) {
        case 200:
            obj = this.smartsheet.getJsonSerializer()
                    .deserializeCopyOrMoveRow(response.getEntity().getContent());
            break;
        default:
            handleError(response);
        }
    } finally {
        smartsheet.getHttpClient().releaseConnection();
    }

    return obj;
}

From source file:it.classhidra.core.controller.bsController.java

static public int calc(Object oldObj) {

    ObjectOutputStream oos = null;
    try {//w w w  .j a va2 s .com
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bos);
        oos.writeObject(oldObj);
        oos.flush();
        return bos.size();

        //         ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
        //         ois = new ObjectInputStream(bin);

        //         retVal = ois.readObject();

    } catch (Exception e) {
        e.toString();
    } finally {
        try {
            oos.close();
            //            ois.close();
        } catch (java.io.IOException e) {
            //            throw (e);
        }
    }
    return 0;
}

From source file:com.hichinaschool.flashcards.libanki.importer.Anki2Importer.java

/**
 * Return the contents of the given input stream, limited to Anki2Importer.MEDIAPICKLIMIT bytes
 * This is only used for comparison of media files with the limited resources of mobile devices
 *//*  w  w w.java2  s . c  om*/
byte[] _mediaPick(BufferedInputStream is) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(MEDIAPICKLIMIT * 2);
        byte[] buf = new byte[MEDIAPICKLIMIT];
        int readLen;
        int readSoFar = 0;
        is.mark(MEDIAPICKLIMIT * 2);
        while (true) {
            readLen = is.read(buf);
            baos.write(buf);
            if (readLen == -1) {
                break;
            }
            readSoFar += readLen;
            if (readSoFar > MEDIAPICKLIMIT) {
                break;
            }
        }
        is.reset();
        byte[] result = new byte[MEDIAPICKLIMIT];
        System.arraycopy(baos.toByteArray(), 0, result, 0, Math.min(baos.size(), MEDIAPICKLIMIT));
        return result;
    } catch (FileNotFoundException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}

From source file:org.apache.axis.components.compiler.Jikes.java

/**
 * Execute the compiler/*ww  w  .  j  a  va 2  s  . c o  m*/
 */
public boolean compile() throws IOException {

    List args = new ArrayList();
    // command line name
    args.add("jikes");
    // indicate Emacs output mode must be used
    args.add("+E");
    // avoid warnings
    // Option nowarn with one hyphen only
    args.add("-nowarn");

    int exitValue;
    ByteArrayOutputStream tmpErr = new ByteArrayOutputStream(OUTPUT_BUFFER_SIZE);

    try {
        Process p = Runtime.getRuntime().exec(toStringArray(fillArguments(args)));

        BufferedInputStream compilerErr = new BufferedInputStream(p.getErrorStream());

        StreamPumper errPumper = new StreamPumper(compilerErr, tmpErr);

        errPumper.start();

        p.waitFor();
        exitValue = p.exitValue();

        // Wait until the complete error stream has been read
        errPumper.join();
        compilerErr.close();

        p.destroy();

        tmpErr.close();
        this.errors = new ByteArrayInputStream(tmpErr.toByteArray());

    } catch (InterruptedException somethingHappened) {
        log.debug("Jikes.compile():SomethingHappened", somethingHappened);
        return false;
    }

    // Jikes returns 0 even when there are some types of errors.
    // Check if any error output as well
    // Return should be OK when both exitValue and
    // tmpErr.size() are 0 ?!
    return ((exitValue == 0) && (tmpErr.size() == 0));
}