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.dbgl.gui.AddGameWizardDialog.java

private Control page1() {
    final Group group = new Group(shell, SWT.NONE);
    group.setText(settings.msg("dialog.addgamewizard.step2"));
    group.setLayout(new GridLayout());

    Composite installexeComposite = new Composite(group, SWT.NONE);
    installexeComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    installexeComposite.setLayout(new GridLayout(3, false));
    final Label mainExeLabel = new Label(installexeComposite, SWT.NONE);
    mainExeLabel.setText(settings.msg("dialog.addgamewizard.installexe"));
    installExe = new Text(installexeComposite, SWT.BORDER);
    installExe.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    final BrowseButton installexeBrowseButton = new BrowseButton(installexeComposite, SWT.NONE);
    installexeBrowseButton.connect(shell, installExe, null, BrowseType.FILE, CanonicalType.INSTALLER, false,
            null);/*  w  w w. j  a  va2  s  .c o m*/

    final Label parametersLabel = new Label(installexeComposite, SWT.NONE);
    parametersLabel.setText(settings.msg("dialog.profile.mainparameters"));
    installParameters = new Text(installexeComposite, SWT.BORDER);
    installParameters.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));

    final Label manualLabel = new Label(installexeComposite, SWT.NONE);
    manualLabel.setText(settings.msg("dialog.addgamewizard.manualmode"));
    btnInstallManual = new Button(installexeComposite, SWT.CHECK);
    btnInstallManual.setText(settings.msg("dialog.addgamewizard.manualmodeinfo"));
    btnInstallManual.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 2, 1));

    final Group mountGroup = new Group(group, SWT.NONE);
    GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
    gd.verticalIndent = 20;
    mountGroup.setLayoutData(gd);
    mountGroup.setText(settings.msg("dialog.template.mountingoverview"));
    mountGroup.setLayout(new GridLayout(2, false));

    mountingpoints = new List(mountGroup, SWT.V_SCROLL | SWT.BORDER);
    mountingpoints.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 3));
    mountingpoints.addMouseListener(new MouseAdapter() {
        public void mouseDoubleClick(final MouseEvent event) {
            if (mountingpoints.getSelectionIndex() == -1) {
                doAddMount();
            } else {
                doEditMount();
            }
        }
    });

    final Button addButton = new Button(mountGroup, SWT.NONE);
    addButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    addButton.setText(settings.msg("dialog.template.mount.add"));
    addButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(final SelectionEvent event) {
            doAddMount();
        }
    });

    final Button editButton = new Button(mountGroup, SWT.NONE);
    editButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    editButton.setText(settings.msg("dialog.template.mount.edit"));
    editButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(final SelectionEvent event) {
            doEditMount();
        }
    });

    final Button removeButton = new Button(mountGroup, SWT.NONE);
    removeButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
    removeButton.setText(settings.msg("dialog.template.mount.remove"));
    removeButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(final SelectionEvent event) {
            doRemoveMount();
        }
    });

    VerifyListener addMountListener = new VerifyListener() {
        public void verifyText(final VerifyEvent event) {
            if (event.text.length() > 1) {
                addMountIfNoMounts(event.text);
            }
        }
    };
    installExe.addVerifyListener(addMountListener);

    Group associationGroup = new Group(group, SWT.NONE);
    associationGroup.setText(settings.msg("dialog.template.association"));
    associationGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    associationGroup.setLayout(new GridLayout(2, false));

    final Label dbversionLabel = new Label(associationGroup, SWT.NONE);
    dbversionLabel.setText(settings.msg("dialog.template.dosboxversion"));
    final Combo dbversion = new Combo(associationGroup, SWT.READ_ONLY);
    dbversion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
    dbversion.setVisibleItemCount(20);

    for (DosboxVersion dbv : dbversionsList) {
        dbversion.add(dbv.getTitle());
    }
    int dbversionIndex = DosboxVersion.findIndexById(dbversionsList, profile.getDbversionId());
    dbversion.select(dbversionIndex);

    dbversion.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(final SelectionEvent event) {
            try {
                String[] mounts = profile.getConf().getAutoexec().getMountingpoints();

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(bos);
                Conf newDosboxVersion = new Conf(dbversionsList.get(dbversion.getSelectionIndex()), ps);
                profile.getConf().switchToDosboxVersion(newDosboxVersion);
                profile.setDbversionId(newDosboxVersion.getDbversion().getId());

                profile.getConf().unmountDosboxMounts();
                for (String m : mounts)
                    profile.getConf().addMount(m);
                mountingpoints.setItems(profile.getConf().getAutoexec().getMountingpoints());

                if (bos.size() > 0) {
                    GeneralPurposeDialogs.warningMessage(getParent(), bos.toString());
                    bos.reset();
                }
            } catch (IOException e) {
                GeneralPurposeDialogs.warningMessage(getParent(), e);
            }
        }
    });

    return group;
}

From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializerTest.java

@Test
public void testArchiveSerializeApplicationVersion() throws Exception {
    underTest.setArchive(true);// w w w .  ja  va  2 s .co m
    underTest.setMarshallerMap(liveMarshallerMap);

    // Set a spy on the ApplicationVersionConverter
    ApplicationVersionConverter applicationVersionConverter = spy(new ApplicationVersionConverter());
    XStreamMarshaller xsm = (XStreamMarshaller) underTest.getMarshallerMap().get(StreamId.APPLICATION_VERSION)
            .getMarshaller();
    XStream x = xsm.getXStream();
    x.registerConverter(applicationVersionConverter, XStream.PRIORITY_VERY_HIGH); // because there is a non-spy
                                                                                  // version of this already
                                                                                  // registered in the configure
                                                                                  // method

    ByteArrayOutputStream result = new ByteArrayOutputStream();

    when(arxFactory.newArchiveOutputStream(result)).thenAnswer(invocationOnMock -> new ArchiveOutputStream() {
        @Override
        public void putArchiveEntry(ArchiveEntry archiveEntry) throws IOException {
        }

        @Override
        public void closeArchiveEntry() throws IOException {
        }

        @Override
        public void finish() throws IOException {
        }

        @Override
        public ArchiveEntry createArchiveEntry(File file, String s) throws IOException {
            return mock(ArchiveEntry.class);
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            result.write(b, off, len);
        }
    });

    underTest.serialize(state, StreamId.APPLICATION_VERSION, result);

    verify(applicationVersionConverter, atLeastOnce()).canConvert(ApplicationVersion.class);
    // cant verify the marshal(...) method b/c it's final
    verify(applicationVersionConverter).marshalInternal(eq(applicationVersion),
            any(HierarchicalStreamWriter.class), any(MarshallingContext.class));
    assertTrue(result.size() > 1);
}

From source file:org.apache.pdfbox.pdfparser.BaseParser.java

/**
 * This will read a COSStream from the input stream.
 *
 * @param file The file to write the stream to when reading.
 * @param dic The dictionary that goes with this stream.
 *
 * @return The parsed pdf stream.// www. ja v a2s. c  o m
 *
 * @throws IOException If there is an error reading the stream.
 */
protected COSStream parseCOSStream(COSDictionary dic, RandomAccess file) throws IOException {
    COSStream stream = new COSStream(dic, file);
    OutputStream out = null;
    try {
        String streamString = readString();
        //long streamLength;

        if (!streamString.equals(STREAM_STRING)) {
            throw new IOException("expected='stream' actual='" + streamString + "'");
        }

        //PDF Ref 3.2.7 A stream must be followed by either
        //a CRLF or LF but nothing else.

        int whitespace = pdfSource.read();

        //see brother_scan_cover.pdf, it adds whitespaces
        //after the stream but before the start of the
        //data, so just read those first
        while (whitespace == 0x20) {
            whitespace = pdfSource.read();
        }

        if (whitespace == 0x0D) {
            whitespace = pdfSource.read();
            if (whitespace != 0x0A) {
                pdfSource.unread(whitespace);
                //The spec says this is invalid but it happens in the real
                //world so we must support it.
            }
        } else if (whitespace == 0x0A) {
            //that is fine
        } else {
            //we are in an error.
            //but again we will do a lenient parsing and just assume that everything
            //is fine
            pdfSource.unread(whitespace);
        }

        /*This needs to be dic.getItem because when we are parsing, the underlying object
         * might still be null.
         */
        COSBase streamLength = dic.getItem(COSName.LENGTH);

        //Need to keep track of the
        out = stream.createFilteredStream(streamLength);

        // try to read stream length - even if it is an indirect object
        int length = -1;
        if (streamLength instanceof COSNumber) {
            length = ((COSNumber) streamLength).intValue();
        }
        // commented out next chunk since for the sequentially working PDFParser
        // we do not know if length object is redefined later on and the currently
        // read indirect object might be obsolete (e.g. not referenced in xref table);
        // this would result in reading wrong number of bytes;
        // Thus the only reliable information is a direct length. 
        // This exclusion shouldn't harm much since in case of indirect objects they will
        // typically be defined after the stream object, thus keeping the directly
        // provided length will fix most cases
        //            else if ( ( streamLength instanceof COSObject ) &&
        //                      ( ( (COSObject) streamLength ).getObject() instanceof COSNumber ) )
        //            {
        //                length = ( (COSNumber) ( (COSObject) streamLength ).getObject() ).intValue();
        //            } 

        if (length == -1) {
            // Couldn't determine length from dict: just
            // scan until we find endstream:
            readUntilEndStream(out);
        } else {
            // Copy length bytes over:
            int left = length;
            while (left > 0) {
                final int chunk = Math.min(left, strmBufLen);
                final int readCount = pdfSource.read(strmBuf, 0, chunk);
                if (readCount == -1) {
                    break;
                }
                out.write(strmBuf, 0, readCount);
                left -= readCount;
            }

            // in order to handle broken documents we test if 'endstream' is reached
            // if not, length value possibly was wrong, fall back to scanning for endstream

            // fill buffer with next bytes and test for 'endstream' (with leading whitespaces)
            int readCount = pdfSource.read(strmBuf, 0, 20);
            if (readCount > 0) {
                boolean foundEndstream = false;
                int nextEndstreamCIdx = 0;
                for (int cIdx = 0; cIdx < readCount; cIdx++) {
                    final int ch = strmBuf[cIdx] & 0xff;
                    if (ch == ENDSTREAM[nextEndstreamCIdx]) {
                        if (++nextEndstreamCIdx >= ENDSTREAM.length) {
                            foundEndstream = true;
                            break;
                        }
                    } else if ((nextEndstreamCIdx > 0) || (!isWhitespace(ch))) {
                        // not found
                        break;
                    }
                }

                // push back test bytes
                pdfSource.unread(strmBuf, 0, readCount);

                // if 'endstream' was not found fall back to scanning
                if (!foundEndstream) {
                    LOG.warn("Specified stream length " + length
                            + " is wrong. Fall back to reading stream until 'endstream'.");

                    // push back all read stream bytes
                    out.flush(); // we got a buffered stream wrapper around filteredStream thus first flush to underlying stream
                    InputStream writtenStreamBytes = stream.getFilteredStream();
                    ByteArrayOutputStream bout = new ByteArrayOutputStream(length);

                    while ((readCount = writtenStreamBytes.read(strmBuf)) >= 0) {
                        bout.write(strmBuf, 0, readCount);
                    }
                    try {
                        pdfSource.unread(bout.toByteArray());
                    } catch (IOException ioe) {
                        throw new WrappedIOException("Could not push back " + bout.size()
                                + " bytes in order to reparse stream. "
                                + "Try increasing push back buffer using system property " + PROP_PUSHBACK_SIZE,
                                ioe);
                    }
                    // create new filtered stream
                    out = stream.createFilteredStream(streamLength);
                    // scan until we find endstream:
                    readUntilEndStream(out);
                }
            }
        }

        skipSpaces();
        String endStream = readString();

        if (!endStream.equals(ENDSTREAM_STRING)) {
            /*
             * Sometimes stream objects don't have an endstream tag so readUntilEndStream(out)
             * also can stop on endobj tags. If that's the case we need to make sure to unread
             * the endobj so parseObject() can handle that case normally.
             */
            if (endStream.startsWith(ENDOBJ_STRING)) {
                byte[] endobjarray = endStream.getBytes("ISO-8859-1");
                pdfSource.unread(endobjarray);
            }
            /*
             * Some PDF files don't contain a new line after endstream so we
             * need to make sure that the next object number is getting read separately
             * and not part of the endstream keyword. Ex. Some files would have "endstream8"
             * instead of "endstream"
             */
            else if (endStream.startsWith(ENDSTREAM_STRING)) {
                String extra = endStream.substring(9, endStream.length());
                endStream = endStream.substring(0, 9);
                byte[] array = extra.getBytes("ISO-8859-1");
                pdfSource.unread(array);
            } else {
                /*
                 * If for some reason we get something else here, Read until we find the next
                 * "endstream"
                 */
                readUntilEndStream(out);
                endStream = readString();
                if (!endStream.equals(ENDSTREAM_STRING)) {
                    throw new IOException("expected='endstream' actual='" + endStream + "' " + pdfSource);
                }
            }
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }
    return stream;
}

From source file:org.mrgeo.vector.mrsvector.VectorTile.java

public void printstats() {
    int totalsize = 0;
    int size = 0;

    if (strings != null) {
        for (final String s : strings) {
            size += s.length();//from   ww w .  j ava2 s.  co m
        }
        totalsize += size;

        System.out.println("strings: " + strings.length + " (" + human(size) + ")");

    }

    {
        try {

            final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            final ObjectOutputStream out = new ObjectOutputStream(bytes);
            out.writeObject(nodes);

            size = bytes.size();
            totalsize += size;
            System.out.println("nodes: " + nodes.length + " (" + human(size) + ")");
        } catch (final IOException e) {
            e.printStackTrace();
        }

    }

    try {
        final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        final ObjectOutputStream out = new ObjectOutputStream(bytes);
        out.writeObject(ways);

        size = bytes.size();
        totalsize += size;
        System.out.println("ways: " + ways.length + " (" + human(size) + ")");
    } catch (final IOException e) {
        e.printStackTrace();
    }

    try {
        final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        final ObjectOutputStream out = new ObjectOutputStream(bytes);
        out.writeObject(relations);

        size = bytes.size();
        totalsize += size;
        System.out.println("relations: " + relations.length + " (" + human(size) + ")");
    } catch (final IOException e) {
        e.printStackTrace();
    }

    System.out.println("total size: " + human(totalsize));
}

From source file:gov.lanl.adore.djatoka.openurl.OpenURLJP2KMetadata.java

/**
 * Returns the OpenURLResponse of a JSON object defining the core image properties. Having obtained a result, this
 * method is then responsible for transforming it into an OpenURLResponse that acts as a proxy for
 * HttpServletResponse./*from  w  ww .  j av  a 2s.  c o  m*/
 */
@Override
public OpenURLResponse resolve(final ServiceType serviceType, final ContextObject contextObject,
        final OpenURLRequest openURLRequest, final OpenURLRequestProcessor processor) {

    String responseFormat = RESPONSE_TYPE;
    int status = HttpServletResponse.SC_OK;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode rootNode = mapper.createObjectNode();
        final IExtract jp2 = new KduExtractExe();

        ImageRecord r = ReferentManager.getImageRecord(contextObject.getReferent());
        r = jp2.getMetadata(r);

        rootNode.put("identifier", r.getIdentifier());
        rootNode.put("imagefile", r.getImageFile());
        rootNode.put("width", r.getWidth());
        rootNode.put("height", r.getHeight());
        rootNode.put("dwtLevels", r.getDWTLevels());
        rootNode.put("levels", r.getLevels());
        rootNode.put("compositingLayerCount", r.getCompositingLayerCount());

        mapper.writeValue(baos, rootNode);
    } catch (final DjatokaException e) {
        responseFormat = "text/plain";
        status = HttpServletResponse.SC_NOT_FOUND;
    } catch (final Exception e) {
        baos = new ByteArrayOutputStream();

        try {
            if (e.getMessage() != null) {
                baos.write(e.getMessage().getBytes("UTF-8"));
            } else {
                LOGGER.error(e.getMessage(), e);
                baos.write("Internal Server Error: ".getBytes());
            }
        } catch (final UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (final IOException e2) {
            e2.printStackTrace();
        }

        responseFormat = "text/plain";
        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    final HashMap<String, String> header_map = new HashMap<String, String>();
    header_map.put("Content-Length", baos.size() + "");
    header_map.put("Date", HttpDate.getHttpDate());
    return new OpenURLResponse(status, responseFormat, baos.toByteArray(), header_map);
}

From source file:at.irian.myfaces.wscope.renderkit.html.WsServerSideStateCacheImpl.java

protected Object serializeView(FacesContext context, Object serializedView) {
    if (log.isLoggable(Level.FINEST)) {
        log.finest("Entering serializeView");
    }//from  w ww. java  2s.  com

    if (isSerializeStateInSession(context)) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Processing serializeView - serialize state in session");
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        try {
            OutputStream os = baos;
            if (isCompressStateInSession(context)) {
                if (log.isLoggable(Level.FINEST)) {
                    log.finest("Processing serializeView - serialize compressed");
                }

                os.write(COMPRESSED_FLAG);
                os = new GZIPOutputStream(os, 1024);
            } else {
                if (log.isLoggable(Level.FINEST)) {
                    log.finest("Processing serializeView - serialize uncompressed");
                }

                os.write(UNCOMPRESSED_FLAG);
            }

            //Object[] stateArray = (Object[]) serializedView;

            ObjectOutputStream out = new ObjectOutputStream(os);

            out.writeObject(serializedView);
            //out.writeObject(stateArray[0]);
            //out.writeObject(stateArray[1]);
            out.close();
            baos.close();

            if (log.isLoggable(Level.FINEST)) {
                log.finest("Exiting serializeView - serialized. Bytes : " + baos.size());
            }
            return baos.toByteArray();
        } catch (IOException e) {
            log.log(Level.SEVERE, "Exiting serializeView - Could not serialize state: " + e.getMessage(), e);
            return null;
        }
    }

    if (log.isLoggable(Level.FINEST)) {
        log.finest("Exiting serializeView - do not serialize state in session.");
    }

    return serializedView;

}

From source file:org.eclipse.skalli.gerrit.client.internal.GerritClientImpl.java

/**
 * Performs a SSH command//from  w ww  .j  a  v a2 s .  c  o  m
 *
 * @param command
 *            the command to execute
 *
 * @return the resulting lines
 *
 * @throws ConnectionException in case of connection / communication problems
 * @throws CommandException    in case of unsuccessful commands
 */
private List<String> sshCommand(final String command) throws ConnectionException, CommandException {
    LOG.info(MessageFormat.format("Sending on behalf of ''{0}'': ''{1}''", onBehalfOf, command));

    boolean manuallyConnected = false;

    ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
    ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
    ByteArrayInputStream baisIn = new ByteArrayInputStream(new byte[0]);
    ChannelExec channel = null;
    try {
        if (client == null || session == null) {
            connect();
            manuallyConnected = true;
        }
        channel = (ChannelExec) session.openChannel("exec");
        channel.setInputStream(baisIn);
        channel.setOutputStream(baosOut);
        channel.setErrStream(baosErr);
        channel.setCommand(command);
        channel.connect();
        while (!channel.isClosed()) {
            try {
                Thread.sleep(SLEEP_INTERVAL);
            } catch (InterruptedException e) {
                throw andDisconnect(new CommandException());
            }
        }
        List<String> result = new LinkedList<String>();
        InputStreamReader inR = new InputStreamReader(new ByteArrayInputStream(baosOut.toByteArray()),
                "ISO-8859-1");
        BufferedReader buf = new BufferedReader(inR);
        String line;
        while ((line = buf.readLine()) != null) {
            result.add(line);
        }

        if (result.size() > 0) {
            checkForErrorsInResponse(result.get(0));
        }

        if (baosErr.size() > 0) {
            InputStreamReader errISR = new InputStreamReader(new ByteArrayInputStream(baosErr.toByteArray()),
                    "ISO-8859-1");
            BufferedReader errBR = new BufferedReader(errISR);
            StringBuffer errSB = new StringBuffer("Gerrit CLI returned with an error:");
            String errLine;
            while ((errLine = errBR.readLine()) != null) {
                errSB.append("\n").append(errLine);
            }
            throw andDisconnect(new CommandException(errSB.toString()));
        }

        return result;
    } catch (JSchException e) {
        throw andDisconnect(new ConnectionException("Failed to create/open channel.", e));
    } catch (IOException e) {
        throw andDisconnect(new ConnectionException("Failed to read errors from channel.", e));
    } finally {
        closeQuietly(channel, baisIn, baosOut, baosErr, manuallyConnected);
    }
}

From source file:byps.test.TestSerializePrimitiveTypes.java

public void internaltestPerformancePrimitiveTypes(BBinaryModel protocol, int objCount, int loopCount, int flags)
        throws IOException {

    TestUtils.protocol = protocol;/*from   w w  w . ja  va 2s  .  com*/

    BTransport transport = TestUtils.createTransport(flags, BMessageHeader.BYPS_VERSION_CURRENT, 0);

    BOutput bout = transport.getOutput();
    long bytesCount = 0;
    ByteBuffer buf = null;

    ListTypes obj = new ListTypes();
    obj.primitiveTypes1 = new ArrayList<PrimitiveTypes>();
    for (int i = 0; i < objCount; i++) {
        PrimitiveTypes item = TestUtils.createObjectPrimitiveTypes();
        obj.primitiveTypes1.add(item);
    }

    long t1 = System.currentTimeMillis();
    ByteArrayOutputStream os = null;
    for (int i = 0; i < loopCount; i++) {
        bout.store(obj);
        buf = bout.toByteBuffer();
        os = new ByteArrayOutputStream();
        BWire.bufferToStream(buf, (transport.getWire().getFlags() & BWire.FLAG_GZIP) != 0, os);
    }
    long t2 = System.currentTimeMillis();
    bytesCount = (long) loopCount * buf.remaining();

    //TestUtils.printBuffer(log, buf);

    long t3 = System.currentTimeMillis();
    for (int i = 0; i < loopCount; i++) {
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        buf = BWire.bufferFromStream(is);
        BInput bin = transport.getInput(null, buf);
        Object objR = bin.load();
        if (i == 0) {
            TestUtils.assertEquals(null, "obj", obj, objR);
        }

        buf.flip();
    }
    long t4 = System.currentTimeMillis();

    log.info("bmodel=" + protocol.toString().substring(0, 2) + ", gzip=" + ((flags & BWire.FLAG_GZIP) != 0)
            + ", #objs=" + String.format("%6d", objCount) + ", #loops=" + String.format("%6d", loopCount)
            + ", ser-ms=" + String.format("%6d", (t2 - t1) + (t4 - t3)) + "/" + String.format("%6d", (t2 - t1))
            + "/" + String.format("%6d", (t4 - t3)) + ", #kb-per-message="
            + String.format("%4.2f", (double) os.size() / 1000) + ", #kb-total="
            + String.format("%4.2f", (double) bytesCount / 1000));

}

From source file:org.dbgl.gui.EditProfileDialog.java

public static Profile duplicateProfile(final Profile prof, final java.util.List<DosboxVersion> dbversionsList,
        final Database dbase, final Shell shell) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(bos);

    try {//  w ww.j a va  2s .  c o m
        dbase.startTransaction();
        DosboxVersion dbversion = DosboxVersion.findById(dbversionsList, prof.getDbversionId());
        Conf newCompositeConf = new Conf(prof, dbversion, ps);
        Profile newProfile = dbase.duplicateProfile(prof);
        dbase.saveNativeCommands(dbase.readNativeCommandsList(prof.getId(), -1), newProfile.getId(), -1);
        String newCapturesString = FileUtils.constructCapturesDir(newProfile.getId());
        File newCaptures = FileUtils.canonicalToData(newCapturesString);
        FileUtils.createDir(newCaptures);
        String newConfFile = FileUtils.constructUniqueConfigFileString(newProfile.getId(), prof.getTitle(),
                newCompositeConf.getAutoexec().isIncomplete() ? null
                        : newCompositeConf.getAutoexec().getCanonicalMainDir());

        newProfile = new Profile(newProfile.getId(), newConfFile, newCapturesString, newProfile);

        newCompositeConf.injectOrUpdateProfile(newProfile);
        newCompositeConf.save();

        newProfile = dbase.updateProfileConf(newConfFile, newCapturesString, newProfile.getId());
        dbase.commitTransaction();
        if (GeneralPurposeDialogs.confirmMessage(shell,
                Settings.getInstance().msg("dialog.profile.confirm.capturesduplication"))) {
            FileUtils.copyFiles(prof.getCanonicalCaptures(), newCaptures);
        }
        if (bos.size() > 0) {
            GeneralPurposeDialogs.warningMessage(shell, bos.toString());
            bos.reset();
        }
        return newProfile;
    } catch (Exception e) {
        GeneralPurposeDialogs.warningMessage(shell, e);
        try {
            dbase.rollbackTransaction();
        } catch (SQLException se) {
            GeneralPurposeDialogs.warningMessage(shell, se);
        }
        return null;
    } finally {
        dbase.finishTransaction();
    }
}

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

/**
 * @see org.apache.james.mailrepository.lib.AbstractMailRepository#internalStore(Mail)
 *///w w w .  ja v  a 2  s.  co  m
protected void internalStore(Mail mc) throws IOException, MessagingException {
    Connection conn = null;
    try {
        conn = datasource.getConnection();
        // Need to determine whether need to insert this record, or update
        // it.

        // Determine whether the message body has changed, and possibly
        // avoid
        // updating the database.
        boolean saveBody;

        MimeMessage messageBody = mc.getMessage();
        // if the message is a CopyOnWrite proxy we check the modified
        // wrapped object.
        if (messageBody instanceof MimeMessageCopyOnWriteProxy) {
            MimeMessageCopyOnWriteProxy messageCow = (MimeMessageCopyOnWriteProxy) messageBody;
            messageBody = messageCow.getWrappedMessage();
        }
        if (messageBody instanceof MimeMessageWrapper) {
            MimeMessageWrapper message = (MimeMessageWrapper) messageBody;
            saveBody = message.isModified();
            if (saveBody) {
                message.loadMessage();
            }
        } else {
            saveBody = true;
        }
        MessageInputStream is = new MessageInputStream(mc, sr, inMemorySizeLimit, true);

        // Begin a transaction
        conn.setAutoCommit(false);

        PreparedStatement checkMessageExists = null;
        ResultSet rsExists = null;
        boolean exists = false;
        try {
            checkMessageExists = conn.prepareStatement(sqlQueries.getSqlString("checkMessageExistsSQL", true));
            checkMessageExists.setString(1, mc.getName());
            checkMessageExists.setString(2, repositoryName);
            rsExists = checkMessageExists.executeQuery();
            exists = rsExists.next() && rsExists.getInt(1) > 0;
        } finally {
            theJDBCUtil.closeJDBCResultSet(rsExists);
            theJDBCUtil.closeJDBCStatement(checkMessageExists);
        }

        if (exists) {
            // MessageInputStream is = new
            // MessageInputStream(mc,sr,inMemorySizeLimit, true);

            // Update the existing record
            PreparedStatement updateMessage = null;

            try {
                updateMessage = conn.prepareStatement(sqlQueries.getSqlString("updateMessageSQL", true));
                updateMessage.setString(1, mc.getState());
                updateMessage.setString(2, mc.getErrorMessage());
                if (mc.getSender() == null) {
                    updateMessage.setNull(3, java.sql.Types.VARCHAR);
                } else {
                    updateMessage.setString(3, mc.getSender().toString());
                }
                StringBuilder recipients = new StringBuilder();
                for (Iterator<MailAddress> i = mc.getRecipients().iterator(); i.hasNext();) {
                    recipients.append(i.next().toString());
                    if (i.hasNext()) {
                        recipients.append("\r\n");
                    }
                }
                updateMessage.setString(4, recipients.toString());
                updateMessage.setString(5, mc.getRemoteHost());
                updateMessage.setString(6, mc.getRemoteAddr());
                updateMessage.setTimestamp(7, new java.sql.Timestamp(mc.getLastUpdated().getTime()));
                updateMessage.setString(8, mc.getName());
                updateMessage.setString(9, repositoryName);
                updateMessage.execute();
            } finally {
                Statement localUpdateMessage = updateMessage;
                // Clear reference to statement
                updateMessage = null;
                theJDBCUtil.closeJDBCStatement(localUpdateMessage);
            }

            // Determine whether attributes are used and available for
            // storing
            if (jdbcMailAttributesReady && mc.hasAttributes()) {
                String updateMessageAttrSql = sqlQueries.getSqlString("updateMessageAttributesSQL", false);
                PreparedStatement updateMessageAttr = null;
                try {
                    updateMessageAttr = conn.prepareStatement(updateMessageAttrSql);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(baos);
                    try {
                        if (mc instanceof MailImpl) {
                            oos.writeObject(((MailImpl) mc).getAttributesRaw());
                        } else {
                            HashMap<String, Serializable> temp = new HashMap<String, Serializable>();
                            for (Iterator<String> i = mc.getAttributeNames(); i.hasNext();) {
                                String hashKey = i.next();
                                temp.put(hashKey, mc.getAttribute(hashKey));
                            }
                            oos.writeObject(temp);
                        }
                        oos.flush();
                        ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
                        updateMessageAttr.setBinaryStream(1, attrInputStream, baos.size());
                    } finally {
                        try {
                            if (oos != null) {
                                oos.close();
                            }
                        } catch (IOException ioe) {
                            getLogger().debug(
                                    "JDBCMailRepository: Unexpected exception while closing output stream.",
                                    ioe);
                        }
                    }
                    updateMessageAttr.setString(2, mc.getName());
                    updateMessageAttr.setString(3, repositoryName);
                    updateMessageAttr.execute();
                } catch (SQLException sqle) {
                    getLogger().info("JDBCMailRepository: Trying to update mail attributes failed.", sqle);

                } finally {
                    theJDBCUtil.closeJDBCStatement(updateMessageAttr);
                }
            }

            if (saveBody) {

                PreparedStatement updateMessageBody = conn
                        .prepareStatement(sqlQueries.getSqlString("updateMessageBodySQL", true));
                try {
                    updateMessageBody.setBinaryStream(1, is, (int) is.getSize());
                    updateMessageBody.setString(2, mc.getName());
                    updateMessageBody.setString(3, repositoryName);
                    updateMessageBody.execute();

                } finally {
                    theJDBCUtil.closeJDBCStatement(updateMessageBody);
                }
            }

        } else {
            // Insert the record into the database
            PreparedStatement insertMessage = null;
            try {
                String insertMessageSQL = sqlQueries.getSqlString("insertMessageSQL", true);
                int number_of_parameters = getNumberOfParameters(insertMessageSQL);
                insertMessage = conn.prepareStatement(insertMessageSQL);
                insertMessage.setString(1, mc.getName());
                insertMessage.setString(2, repositoryName);
                insertMessage.setString(3, mc.getState());
                insertMessage.setString(4, mc.getErrorMessage());
                if (mc.getSender() == null) {
                    insertMessage.setNull(5, java.sql.Types.VARCHAR);
                } else {
                    insertMessage.setString(5, mc.getSender().toString());
                }
                StringBuilder recipients = new StringBuilder();
                for (Iterator<MailAddress> i = mc.getRecipients().iterator(); i.hasNext();) {
                    recipients.append(i.next().toString());
                    if (i.hasNext()) {
                        recipients.append("\r\n");
                    }
                }
                insertMessage.setString(6, recipients.toString());
                insertMessage.setString(7, mc.getRemoteHost());
                insertMessage.setString(8, mc.getRemoteAddr());
                insertMessage.setTimestamp(9, new java.sql.Timestamp(mc.getLastUpdated().getTime()));

                insertMessage.setBinaryStream(10, is, (int) is.getSize());

                // Store attributes
                if (number_of_parameters > 10) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(baos);
                    try {
                        if (mc instanceof MailImpl) {
                            oos.writeObject(((MailImpl) mc).getAttributesRaw());
                        } else {
                            HashMap<String, Serializable> temp = new HashMap<String, Serializable>();
                            for (Iterator<String> i = mc.getAttributeNames(); i.hasNext();) {
                                String hashKey = i.next();
                                temp.put(hashKey, mc.getAttribute(hashKey));
                            }
                            oos.writeObject(temp);
                        }
                        oos.flush();
                        ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
                        insertMessage.setBinaryStream(11, attrInputStream, baos.size());
                    } finally {
                        try {
                            if (oos != null) {
                                oos.close();
                            }
                        } catch (IOException ioe) {
                            getLogger().debug(
                                    "JDBCMailRepository: Unexpected exception while closing output stream.",
                                    ioe);
                        }
                    }
                }

                insertMessage.execute();
            } finally {
                theJDBCUtil.closeJDBCStatement(insertMessage);
            }
        }

        conn.commit();
        conn.setAutoCommit(true);
    } catch (SQLException e) {
        getLogger().debug("Failed to store internal mail", e);
        throw new IOException(e.getMessage());
    } finally {
        theJDBCUtil.closeJDBCConnection(conn);
    }
}