Example usage for java.io ObjectOutputStream flush

List of usage examples for java.io ObjectOutputStream flush

Introduction

In this page you can find the example usage for java.io ObjectOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:com.novemberain.quartz.mongodb.MongoDBJobStore.java

private String getKeyOfNonSerializableStringMapEntry(Map<String, ?> data) {

    for (Map.Entry<String, ?> entry : data.entrySet()) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {//ww  w.  ja  va  2s .c  o  m
            ObjectOutputStream out = new ObjectOutputStream(baos);
            out.writeObject(entry.getValue());
            out.flush();
        } catch (IOException e) {
            return entry.getKey();
        }
    }

    return null;
}

From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java

public void store() {
    File file = null;/* w ww  .  j  a v  a 2s.  c o  m*/
    try {
        file = File.createTempFile("scenario", ".bin");
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(this);
        oos.flush();
        oos.close();
        System.setProperty("scenario", file.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.axis2.engine.MessageContextSaveATest.java

public void testSimpleMC() throws Exception {
    String title = "MessageContextSaveATest:testSimpleMC(): ";
    log.debug(title + "start - - - - - - - - - - - - - - - -");

    MessageContext simpleMsg = new MessageContext();
    MessageContext restoredSimpleMsg = null;

    File theFile = null;/*from   w  ww. ja  va2 s  .  co  m*/
    String theFilename = null;

    boolean savedMessageContext = false;
    boolean restoredMessageContext = false;
    boolean comparesOk = false;

    try {
        theFile = File.createTempFile("Simple", null);
        theFilename = theFile.getName();
        log.debug(title + "temp file = [" + theFilename + "]");
    } catch (Exception ex) {
        log.debug(title + "error creating temp file = [" + ex.getMessage() + "]");
        theFile = null;
    }

    if (theFile != null) {
        // ---------------------------------------------------------
        // save to the temporary file
        // ---------------------------------------------------------
        try {
            // setup an output stream to a physical file
            FileOutputStream outStream = new FileOutputStream(theFile);

            // attach a stream capable of writing objects to the 
            // stream connected to the file
            ObjectOutputStream outObjStream = new ObjectOutputStream(outStream);

            // try to save the message context
            log.debug(title + "saving message context.....");
            savedMessageContext = false;
            outObjStream.writeObject(simpleMsg);

            // close out the streams
            outObjStream.flush();
            outObjStream.close();
            outStream.flush();
            outStream.close();

            savedMessageContext = true;
            log.debug(title + "....saved message context.....");

            long filesize = theFile.length();
            log.debug(title + "file size after save [" + filesize + "]   temp file = [" + theFilename + "]");

        } catch (Exception ex2) {
            log.debug(title + "error with saving message context = [" + ex2.getClass().getName() + " : "
                    + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        assertTrue(savedMessageContext);

        // ---------------------------------------------------------
        // restore from the temporary file
        // ---------------------------------------------------------
        try {
            // setup an input stream to the file
            FileInputStream inStream = new FileInputStream(theFile);

            // attach a stream capable of reading objects from the 
            // stream connected to the file
            ObjectInputStream inObjStream = new ObjectInputStream(inStream);

            // try to restore the message context
            log.debug(title + "restoring a message context.....");
            restoredMessageContext = false;

            restoredSimpleMsg = (MessageContext) inObjStream.readObject();
            inObjStream.close();
            inStream.close();

            restoredSimpleMsg.activate(configurationContext);

            restoredMessageContext = true;
            log.debug(title + "....restored message context.....");

            // compare to original execution chain
            ArrayList restored_execChain = restoredSimpleMsg.getExecutionChain();
            ArrayList orig_execChain = simpleMsg.getExecutionChain();

            comparesOk = ActivateUtils.isEquivalent(restored_execChain, orig_execChain, false);
            log.debug(title + "execution chain equivalency [" + comparesOk + "]");
            assertTrue(comparesOk);

            // check executed list
            Iterator restored_executed_it = restoredSimpleMsg.getExecutedPhases();
            Iterator orig_executed_it = simpleMsg.getExecutedPhases();
            if ((restored_executed_it != null) && (orig_executed_it != null)) {
                while (restored_executed_it.hasNext() && orig_executed_it.hasNext()) {
                    Object p1 = restored_executed_it.next();
                    Object p2 = orig_executed_it.next();

                    comparesOk = comparePhases(p1, p2);
                    log.debug(title + "executed phase list:  compare phases [" + comparesOk + "]");
                    assertTrue(comparesOk);
                }
            } else {
                // problem with the executed lists
                assertTrue(false);
            }

        } catch (Exception ex2) {
            log.debug(title + "error with saving message context = [" + ex2.getClass().getName() + " : "
                    + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        assertTrue(restoredMessageContext);

        // if the save/restore of the message context succeeded,
        // then don't keep the temporary file around
        boolean removeTmpFile = savedMessageContext && restoredMessageContext && comparesOk;
        if (removeTmpFile) {
            try {
                theFile.delete();
            } catch (Exception e) {
                // just absorb it
            }
        }
    }

    log.debug(title + "end - - - - - - - - - - - - - - - -");
}

From source file:org.apache.axis2.engine.MessageContextSaveATest.java

public void testMapping() throws Exception {

    String title = "MessageContextSaveATest:testMapping(): ";
    log.debug(title + "start - - - - - - - - - - - - - - - -");

    MessageContext restoredMC = null;

    //---------------------------------------------------------------------
    // make sure that the operation context messageContexts table 
    // has an entry for the message context that we working with
    //---------------------------------------------------------------------
    // look at the OperationContext messageContexts table
    HashMap mcMap1 = mc.getOperationContext().getMessageContexts();

    if ((mcMap1 == null) || (mcMap1.isEmpty())) {
        mc.getAxisOperation().addMessageContext(mc, mc.getOperationContext());
    }/*from  w  ww . j  a va2  s.  co m*/
    // update the table
    mcMap1 = mc.getOperationContext().getMessageContexts();

    log.debug(title + "- - - - - original message contexts table- - - - - - - - - - -");
    showMcMap(mcMap1);

    //---------------------------------------------------------------------
    // save and restore the message context
    //---------------------------------------------------------------------

    File theFile;
    String theFilename = null;

    boolean pause = false;
    boolean savedMessageContext = false;
    boolean restoredMessageContext = false;
    boolean comparesOk = false;

    try {
        theFile = File.createTempFile("McMappings", null);
        theFilename = theFile.getName();
        log.debug(title + "temp file = [" + theFilename + "]");
    } catch (Exception ex) {
        log.debug(title + "error creating temp file = [" + ex.getMessage() + "]");
        theFile = null;
    }

    if (theFile != null) {
        // ---------------------------------------------------------
        // save to the temporary file
        // ---------------------------------------------------------
        try {
            // setup an output stream to a physical file
            FileOutputStream outStream = new FileOutputStream(theFile);

            // attach a stream capable of writing objects to the 
            // stream connected to the file
            ObjectOutputStream outObjStream = new ObjectOutputStream(outStream);

            // try to save the message context
            log.debug(title + "saving message context.....");
            savedMessageContext = false;
            outObjStream.writeObject(mc);

            // close out the streams
            outObjStream.flush();
            outObjStream.close();
            outStream.flush();
            outStream.close();

            savedMessageContext = true;
            log.debug(title + "....saved message context.....");

            long filesize = theFile.length();
            log.debug(title + "file size after save [" + filesize + "]   temp file = [" + theFilename + "]");

        } catch (Exception ex2) {
            log.debug(title + "error with saving message context = [" + ex2.getClass().getName() + " : "
                    + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        assertTrue(savedMessageContext);

        // ---------------------------------------------------------
        // restore from the temporary file
        // ---------------------------------------------------------
        try {
            // setup an input stream to the file
            FileInputStream inStream = new FileInputStream(theFile);

            // attach a stream capable of reading objects from the 
            // stream connected to the file
            ObjectInputStream inObjStream = new ObjectInputStream(inStream);

            // try to restore the message context
            log.debug(title + "restoring a message context.....");
            restoredMessageContext = false;

            restoredMC = (MessageContext) inObjStream.readObject();
            inObjStream.close();
            inStream.close();

            restoredMC.activate(configurationContext);

            restoredMessageContext = true;
            log.debug(title + "....restored message context.....");

            // get the table after the restore
            HashMap mcMap2 = restoredMC.getOperationContext().getMessageContexts();

            log.debug(
                    "MessageContextSaveATest:testMapping(): - - - - - restored message contexts table- - - - - - - - - - -");
            showMcMap(mcMap2);

            boolean okMap = compareMCMaps(mcMap1, mcMap2);
            assertTrue(okMap);

        } catch (Exception ex2) {
            log.debug(title + "error with restoring message context = [" + ex2.getClass().getName() + " : "
                    + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        assertTrue(restoredMessageContext);

        // if the save/restore of the message context succeeded,
        // then don't keep the temporary file around
        boolean removeTmpFile = savedMessageContext && restoredMessageContext && comparesOk;
        if (removeTmpFile) {
            try {
                theFile.delete();
            } catch (Exception e) {
                // just absorb it
            }
        }
    }

    log.debug(title + "end - - - - - - - - - - - - - - - -");

}

From source file:se.sics.kompics.p2p.experiment.dsl.SimulationScenario.java

/**
 * Transform./*from  ww w  .  j a va2s .com*/
 * 
 * @param main
 *            the main
 * @param directory
 *            the directory
 */
public final void transform(Class<? extends ComponentDefinition> main, String directory) {
    Properties p = new Properties();

    File dir = null;
    File file = null;
    try {
        dir = new File(directory);
        dir.mkdirs();
        dir.setWritable(true);
        file = File.createTempFile("scenario", ".bin", dir);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
        oos.writeObject(this);
        oos.flush();
        oos.close();
        System.setProperty("scenario", file.getAbsolutePath());
        p.setProperty("scenario", file.getAbsolutePath());
        p.store(new FileOutputStream(file.getAbsolutePath() + ".properties"), null);
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        Loader cl = AccessController.doPrivileged(new PrivilegedAction<Loader>() {
            @Override
            public Loader run() {
                return new Loader();
            }
        });
        cl.addTranslator(ClassPool.getDefault(), new TimeInterceptor(dir));
        Thread.currentThread().setContextClassLoader(cl);
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        cl.run(main.getCanonicalName(), null);
    } catch (Throwable e) {
        throw new RuntimeException("Exception caught during simulation", e);
    }
}

From source file:org.apache.axis2.engine.MessageContextSaveATest.java

public void testMcProperties() throws Exception {
    String title = "MessageContextSaveATest:testMcProperties(): ";
    log.debug(title + "start - - - - - - - - - - - - - - - -");

    MessageContext simpleMsg = new MessageContext();
    MessageContext restoredSimpleMsg = null;

    simpleMsg.setProperty("key1", "value1");
    simpleMsg.setProperty("key2", null);
    simpleMsg.setProperty("key3", new Integer(3));
    simpleMsg.setProperty("key4", new Long(4L));

    File theFile = null;/*w  w  w.  java2 s .  co m*/
    String theFilename = null;

    boolean pause = false;
    boolean savedMessageContext = false;
    boolean restoredMessageContext = false;
    boolean comparesOk = false;

    try {
        theFile = File.createTempFile("McProps", null);
        theFilename = theFile.getName();
        log.debug(title + "temp file = [" + theFilename + "]");
    } catch (Exception ex) {
        log.debug(title + "error creating temp file = [" + ex.getMessage() + "]");
        theFile = null;
    }

    if (theFile != null) {
        // ---------------------------------------------------------
        // save to the temporary file
        // ---------------------------------------------------------
        try {
            // setup an output stream to a physical file
            FileOutputStream outStream = new FileOutputStream(theFile);

            // attach a stream capable of writing objects to the 
            // stream connected to the file
            ObjectOutputStream outObjStream = new ObjectOutputStream(outStream);

            // try to save the message context
            log.debug(title + "saving message context.....");
            savedMessageContext = false;
            outObjStream.writeObject(simpleMsg);

            // close out the streams
            outObjStream.flush();
            outObjStream.close();
            outStream.flush();
            outStream.close();

            savedMessageContext = true;
            log.debug(title + "....saved message context.....");

            long filesize = theFile.length();
            log.debug(title + "file size after save [" + filesize + "]   temp file = [" + theFilename + "]");

        } catch (Exception ex2) {
            log.debug(title + "error with saving message context = [" + ex2.getClass().getName() + " : "
                    + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        assertTrue(savedMessageContext);

        // ---------------------------------------------------------
        // restore from the temporary file
        // ---------------------------------------------------------
        try {
            // setup an input stream to the file
            FileInputStream inStream = new FileInputStream(theFile);

            // attach a stream capable of reading objects from the 
            // stream connected to the file
            ObjectInputStream inObjStream = new ObjectInputStream(inStream);

            // try to restore the message context
            log.debug(title + "restoring a message context.....");
            restoredMessageContext = false;

            restoredSimpleMsg = (MessageContext) inObjStream.readObject();
            inObjStream.close();
            inStream.close();

            restoredSimpleMsg.activate(configurationContext);

            restoredMessageContext = true;
            log.debug(title + "....restored message context.....");

            // compare to original execution chain
            ArrayList restored_execChain = restoredSimpleMsg.getExecutionChain();
            ArrayList orig_execChain = simpleMsg.getExecutionChain();

            comparesOk = ActivateUtils.isEquivalent(restored_execChain, orig_execChain, false);
            log.debug(title + "execution chain equivalency [" + comparesOk + "]");
            assertTrue(comparesOk);

            // check executed list
            Iterator restored_executed_it = restoredSimpleMsg.getExecutedPhases();
            Iterator orig_executed_it = simpleMsg.getExecutedPhases();
            if ((restored_executed_it != null) && (orig_executed_it != null)) {
                while (restored_executed_it.hasNext() && orig_executed_it.hasNext()) {
                    Object p1 = restored_executed_it.next();
                    Object p2 = orig_executed_it.next();

                    comparesOk = comparePhases(p1, p2);
                    log.debug(title + "executed phase list:  compare phases [" + comparesOk + "]");
                    assertTrue(comparesOk);
                }
            } else {
                // problem with the executed lists
                assertTrue(false);
            }

            // check the properties
            String value1 = (String) restoredSimpleMsg.getProperty("key1");
            Object value2 = restoredSimpleMsg.getProperty("key2");
            Integer value3 = (Integer) restoredSimpleMsg.getProperty("key3");
            Long value4 = (Long) restoredSimpleMsg.getProperty("key4");

            assertEquals("value1", value1);
            assertNull(value2);

            boolean isOk = false;
            if ((value3 != null) && value3.equals(new Integer(3))) {
                isOk = true;
            }
            assertTrue(isOk);

            if ((value4 != null) && value4.equals(new Long(4L))) {
                isOk = true;
            }
            assertTrue(isOk);

        } catch (Exception ex2) {
            log.debug(title + "error with restoring message context = [" + ex2.getClass().getName() + " : "
                    + ex2.getMessage() + "]");
            ex2.printStackTrace();
        }

        assertTrue(restoredMessageContext);

        // if the save/restore of the message context succeeded,
        // then don't keep the temporary file around
        boolean removeTmpFile = savedMessageContext && restoredMessageContext && comparesOk;
        if (removeTmpFile) {
            try {
                theFile.delete();
            } catch (Exception e) {
                // just absorb it
            }
        }
    }

    log.debug(title + "end - - - - - - - - - - - - - - - -");
}

From source file:org.adl.samplerte.server.CourseService.java

/**
 * Updates the list of courses for which a chosen user is registered.
 * @param iCourseIDs The list of courses that are selected
 * @param iPath The web path// w w  w. j  a  va2s . c om
 * @param iUserID The ID of the user.
 * @return String representation of the success of this action (true or false)
 */
public String updateRegCourses(Vector iCourseIDs, String iPath, String iUserID) {
    String result = "true";
    mUserID = iUserID;

    Connection conn;
    Connection csConn;

    PreparedStatement stmtSelectCourse;
    PreparedStatement stmtSelectUserCourse;
    PreparedStatement stmtInsertUserCourse;
    PreparedStatement stmtInsertCourseStatus;
    PreparedStatement stmtDeleteUserCourse;
    PreparedStatement stmtDeleteCourseStatus;
    PreparedStatement stmtDeleteCourseObjectives;

    String sqlSelectUserCourse = "SELECT * FROM UserCourseInfo WHERE UserID = ? AND CourseID = ?";

    String sqlSelectCourse = "SELECT * FROM UserCourseInfo WHERE UserID = ?";

    String sqlInsertUserCourse = "INSERT INTO UserCourseInfo (UserID, CourseID) VALUES(?,?)";

    String sqlDeleteUserCourse = "DELETE FROM UserCourseInfo WHERE UserID = ? AND CourseID = ?";

    String sqlInsertCourseStatus = "INSERT INTO CourseStatus (learnerID, courseID) VALUES(?,?)";

    String sqlDeleteCourseStatus = "DELETE FROM CourseStatus WHERE learnerID = ? AND courseID = ?";

    String sqlDeleteCourseObjectives = "DELETE FROM Objectives WHERE learnerID = ? AND scopeID = ?";

    try {
        conn = LMSDatabaseHandler.getConnection();
        csConn = LMSDBHandler.getConnection();
        stmtSelectCourse = conn.prepareStatement(sqlSelectCourse);
        stmtSelectUserCourse = conn.prepareStatement(sqlSelectUserCourse);
        stmtInsertUserCourse = conn.prepareStatement(sqlInsertUserCourse);
        stmtDeleteUserCourse = conn.prepareStatement(sqlDeleteUserCourse);
        stmtInsertCourseStatus = csConn.prepareStatement(sqlInsertCourseStatus);
        stmtDeleteCourseStatus = csConn.prepareStatement(sqlDeleteCourseStatus);

        stmtDeleteCourseObjectives = csConn.prepareStatement(sqlDeleteCourseObjectives);
        SeqActivityTree mySeqActivityTree;

        //String selectedCourses = "|";

        List unregisterCourses = new ArrayList();

        RTEFileHandler fileHandler = new RTEFileHandler();

        String regTestString = "UN_Course-";

        // Process the list of parameters and register for the course if applicable

        for (int i = 0; i < iCourseIDs.size(); i++) {
            String paramName = (String) iCourseIDs.elementAt(i);

            // This is an Unregister request, put this in the unregister list
            if (paramName.indexOf("RE_Course-") != -1) {
                unregisterCourses.add(paramName.substring(3, paramName.length()));
            }

            int locSkillId = paramName.indexOf(regTestString);

            if (locSkillId != -1) {
                String courseID = paramName.substring(3, paramName.length());

                ResultSet userCourseRS = null;

                synchronized (stmtSelectUserCourse) {
                    stmtSelectUserCourse.setString(1, mUserID);
                    stmtSelectUserCourse.setString(2, courseID);
                    userCourseRS = stmtSelectUserCourse.executeQuery();
                }

                if (userCourseRS.next() == false) {
                    synchronized (stmtInsertUserCourse) {
                        stmtInsertUserCourse.setString(1, mUserID);
                        stmtInsertUserCourse.setString(2, courseID);
                        stmtInsertUserCourse.executeUpdate();
                    }

                    synchronized (stmtInsertCourseStatus) {
                        stmtInsertCourseStatus.setString(1, mUserID);
                        stmtInsertCourseStatus.setString(2, courseID);
                        stmtInsertCourseStatus.executeUpdate();
                    }

                    String tree = iPath + "CourseImports" + File.separator + courseID + File.separator
                            + "serialize.obj";
                    FileInputStream in = new FileInputStream(tree);
                    ObjectInputStream ie = new ObjectInputStream(in);
                    mySeqActivityTree = (SeqActivityTree) ie.readObject();
                    ie.close();
                    in.close();
                    // Set the student ID
                    mySeqActivityTree.setLearnerID(mUserID);

                    String scope = mySeqActivityTree.getScopeID();

                    // Get any global objectives identified in the manifest
                    // from the activity tree.
                    Vector theGobalObjectiveList = mySeqActivityTree.getGlobalObjectives();

                    if (theGobalObjectiveList != null) {
                        ADLSeqUtilities.createGlobalObjs(mUserID, scope, theGobalObjectiveList);
                    }
                    String userDir = File.separator + SRTEFILESDIR + File.separator + mUserID + File.separator
                            + courseID;

                    File theRTESCODataDir = new File(userDir);

                    // The course directory should not exist yet
                    if (!theRTESCODataDir.isDirectory()) {
                        theRTESCODataDir.mkdirs();
                    }

                    //Serialize the activity tree out to the user directory
                    String sampleRTERoot = File.separator + SRTEFILESDIR;
                    String serializeFileName = sampleRTERoot + File.separator + mUserID + File.separator
                            + courseID + File.separator + "serialize.obj";

                    FileOutputStream outFile = new FileOutputStream(serializeFileName);
                    ObjectOutputStream s = new ObjectOutputStream(outFile);
                    s.writeObject(mySeqActivityTree);
                    s.flush();
                    s.close();
                    outFile.close();

                    userCourseRS.close();
                }
            }
        }

        Iterator unregIter = unregisterCourses.iterator();
        while (unregIter.hasNext()) {
            String courseID = unregIter.next().toString();

            ResultSet userCourseRS = null;

            synchronized (stmtSelectUserCourse) {
                stmtSelectUserCourse.setString(1, mUserID);
                stmtSelectUserCourse.setString(2, courseID);
                userCourseRS = stmtSelectUserCourse.executeQuery();
            }

            // Look for courses that are not selected for the user
            if (userCourseRS.next() == true) {
                synchronized (stmtDeleteUserCourse) {
                    stmtDeleteUserCourse.setString(1, mUserID);
                    stmtDeleteUserCourse.setString(2, courseID);
                    stmtDeleteUserCourse.executeUpdate();
                }
                synchronized (stmtDeleteCourseStatus) {
                    // if adlseq:objectivesGlobalToSystem = "false" in the manifest related to this course
                    // scopeID will be == to courseID and should be removed upon deletion of that course
                    stmtDeleteCourseObjectives.setString(1, mUserID);
                    stmtDeleteCourseObjectives.setString(2, courseID);
                    stmtDeleteCourseObjectives.executeUpdate();

                    stmtDeleteCourseStatus.setString(1, mUserID);
                    stmtDeleteCourseStatus.setString(2, courseID);
                    stmtDeleteCourseStatus.executeUpdate();
                }
                fileHandler.deleteCourseFiles(courseID, mUserID);
            }
        }
        stmtSelectCourse.close();
        stmtSelectUserCourse.close();
        stmtInsertUserCourse.close();
        stmtDeleteUserCourse.close();
        stmtInsertCourseStatus.close();
        stmtDeleteCourseStatus.close();
        conn.close();
        LMSDBHandler.closeConnection();
    } catch (Exception e) {
        result = "false";
    }

    return result;
}

From source file:gtu._work.ui.SvnLastestCommitInfoUI.java

private void initGUI() {
    try {/*from   w  w  w  . j  a  v  a  2  s . co  m*/
        BorderLayout thisLayout = new BorderLayout();
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(thisLayout);
        this.setFocusable(false);
        this.setTitle("SVN lastest commit wather");
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            {
                jPanel1 = new JPanel();
                BorderLayout jPanel1Layout = new BorderLayout();
                jPanel1.setLayout(jPanel1Layout);
                jTabbedPane1.addTab("svn dir", null, jPanel1, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
                    {
                        TableModel svnTableModel = new DefaultTableModel();
                        svnTable = new JTable();
                        jScrollPane1.setViewportView(svnTable);
                        svnTable.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                try {
                                    if (evt.getButton() == 3) {
                                        final List<File> list = new ArrayList<File>();
                                        SvnFile svnFile = null;
                                        final StringBuilder sb = new StringBuilder();
                                        for (int row : svnTable.getSelectedRows()) {
                                            svnFile = (SvnFile) svnTable.getModel().getValueAt(
                                                    svnTable.getRowSorter().convertRowIndexToModel(row),
                                                    SvnTableColumn.SVN_FILE.pos);
                                            list.add(svnFile.file);
                                            sb.append(svnFile.file.getName() + ",");
                                        }
                                        if (sb.length() > 200) {
                                            sb.delete(200, sb.length() - 1);
                                        }
                                        JMenuItem copySelectedMeun = new JMenuItem();
                                        copySelectedMeun.setText("copy selected file : " + list.size());
                                        copySelectedMeun.addActionListener(new ActionListener() {
                                            public void actionPerformed(ActionEvent e) {
                                                if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION != JOptionPaneUtil
                                                        .newInstance().iconPlainMessage().confirmButtonYesNo()
                                                        .showConfirmDialog(
                                                                "are you sure copy files :\n" + sb + "\n???",
                                                                "COPY SELECTED FILE : " + list.size())) {
                                                    return;
                                                }
                                                final File copyToDir = JFileChooserUtil.newInstance()
                                                        .selectDirectoryOnly().showOpenDialog()
                                                        .getApproveSelectedFile();
                                                if (copyToDir == null) {
                                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                                            .showMessageDialog("dir folder is not correct!",
                                                                    "ERROR");
                                                    return;
                                                }
                                                new Thread(Thread.currentThread().getThreadGroup(),
                                                        new Runnable() {
                                                            public void run() {
                                                                StringBuilder errMsg = new StringBuilder();
                                                                int errCount = 0;
                                                                for (File f : list) {
                                                                    try {
                                                                        FileUtil.copyFile(f, new File(copyToDir,
                                                                                f.getName()));
                                                                    } catch (IOException e) {
                                                                        e.printStackTrace();
                                                                        errCount++;
                                                                        errMsg.append(f + "\n");
                                                                    }
                                                                }

                                                                JOptionPaneUtil.newInstance().iconPlainMessage()
                                                                        .showMessageDialog(
                                                                                "copy completed!\nerror : "
                                                                                        + errCount
                                                                                        + "\nerror list : \n"
                                                                                        + errMsg,
                                                                                "COMPLETED");
                                                            }
                                                        }, "copySelectedFiles_" + hashCode()).start();
                                            }
                                        });

                                        JMenuItem copySelectedOringTreeMeun = new JMenuItem();
                                        copySelectedOringTreeMeun
                                                .setText("copy selected file (orign tree): " + list.size());
                                        copySelectedOringTreeMeun.addActionListener(new ActionListener() {
                                            public void actionPerformed(ActionEvent e) {
                                                if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION != JOptionPaneUtil
                                                        .newInstance().iconPlainMessage().confirmButtonYesNo()
                                                        .showConfirmDialog(
                                                                "are you sure copy files :\n" + sb + "\n???",
                                                                "COPY SELECTED FILE : " + list.size())) {
                                                    return;
                                                }
                                                final File copyToDir = JFileChooserUtil.newInstance()
                                                        .selectDirectoryOnly().showOpenDialog()
                                                        .getApproveSelectedFile();
                                                if (copyToDir == null) {
                                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                                            .showMessageDialog("dir folder is not correct!",
                                                                    "ERROR");
                                                    return;
                                                }
                                                new Thread(Thread.currentThread().getThreadGroup(),
                                                        new Runnable() {
                                                            public void run() {
                                                                File srcBaseDir = FileUtil
                                                                        .exportReceiveBaseDir(list);
                                                                int cutLength = 0;
                                                                if (srcBaseDir != null) {
                                                                    cutLength = srcBaseDir.getAbsolutePath()
                                                                            .length();
                                                                }

                                                                StringBuilder errMsg = new StringBuilder();
                                                                int errCount = 0;
                                                                File newFile = null;
                                                                for (File f : list) {
                                                                    try {
                                                                        newFile = new File(copyToDir + "/"
                                                                                + f.getAbsolutePath()
                                                                                        .substring(cutLength),
                                                                                f.getName());
                                                                        newFile.getParentFile().mkdirs();
                                                                        FileUtil.copyFile(f, newFile);
                                                                    } catch (IOException e) {
                                                                        e.printStackTrace();
                                                                        errCount++;
                                                                        errMsg.append(f + "\n");
                                                                    }
                                                                }

                                                                JOptionPaneUtil.newInstance().iconPlainMessage()
                                                                        .showMessageDialog(
                                                                                "copy completed!\nerror : "
                                                                                        + errCount
                                                                                        + "\nerror list : \n"
                                                                                        + errMsg,
                                                                                "COMPLETED");
                                                            }
                                                        }, "copySelectedFiles_orignTree_" + hashCode()).start();
                                            }
                                        });

                                        JPopupMenuUtil.newInstance(svnTable).applyEvent(evt)
                                                .addJMenuItem(copySelectedMeun, copySelectedOringTreeMeun)
                                                .show();
                                    }

                                    if (!JMouseEventUtil.buttonLeftClick(2, evt)) {
                                        return;
                                    }
                                    int row = JTableUtil.newInstance(svnTable).getSelectedRow();
                                    SvnFile svnFile = (SvnFile) svnTable.getModel().getValueAt(row,
                                            SvnTableColumn.SVN_FILE.pos);
                                    String command = String.format("cmd /c call \"%s\"", svnFile.file);
                                    System.out.println(command);
                                    try {
                                        Runtime.getRuntime().exec(command);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }
                        });
                        svnTable.setModel(svnTableModel);
                        JTableUtil.defaultSetting(svnTable);
                    }
                }
                {
                    jPanel3 = new JPanel();
                    jPanel1.add(jPanel3, BorderLayout.NORTH);
                    jPanel3.setPreferredSize(new java.awt.Dimension(379, 35));
                    {
                        filterText = new JTextField();
                        jPanel3.add(filterText);
                        filterText.setPreferredSize(new java.awt.Dimension(258, 24));
                        filterText.getDocument()
                                .addDocumentListener(JCommonUtil.getDocumentListener(new HandleDocumentEvent() {
                                    public void process(DocumentEvent event) {
                                        try {
                                            String scanText = JCommonUtil.getDocumentText(event);
                                            reloadSvnTable(scanText, _defaultScanProcess);
                                        } catch (Exception ex) {
                                            JCommonUtil.handleException(ex);
                                        }
                                    }
                                }));
                    }
                    {
                        choiceSvnDir = new JButton();
                        jPanel3.add(choiceSvnDir);
                        choiceSvnDir.setText("choice svn dir");
                        choiceSvnDir.setPreferredSize(new java.awt.Dimension(154, 24));
                        choiceSvnDir.addActionListener(new ActionListener() {

                            Pattern svnOutputPattern = Pattern
                                    .compile("\\s*(\\d*)\\s+(\\d+)\\s+(\\w+)\\s+([\\S]+)");

                            public void actionPerformed(ActionEvent evt) {
                                try {
                                    System.out.println("choiceSvnDir.actionPerformed, event=" + evt);
                                    final File svnDir = JFileChooserUtil.newInstance().selectDirectoryOnly()
                                            .showOpenDialog().getApproveSelectedFile();
                                    if (svnDir == null) {
                                        JOptionPaneUtil.newInstance().iconErrorMessage()
                                                .showMessageDialog("dir is not correct!", "ERROR");
                                        return;
                                    }
                                    Thread thread = new Thread(Thread.currentThread().getThreadGroup(),
                                            new Runnable() {
                                                public void run() {
                                                    long startTime = System.currentTimeMillis();
                                                    String command = String
                                                            .format("cmd /c svn status -v \"%s\"", svnDir);
                                                    Matcher matcher = null;
                                                    try {
                                                        long projectLastestVersion = 0;
                                                        SvnFile svnFile = null;
                                                        Process process = Runtime.getRuntime().exec(command);
                                                        BufferedReader reader = new BufferedReader(
                                                                new InputStreamReader(process.getInputStream(),
                                                                        "BIG5"));
                                                        for (String line = null; (line = reader
                                                                .readLine()) != null;) {
                                                            matcher = svnOutputPattern.matcher(line);
                                                            if (matcher.find()) {
                                                                try {
                                                                    if (StringUtils
                                                                            .isNotBlank(matcher.group(1))) {
                                                                        projectLastestVersion = Math.max(
                                                                                projectLastestVersion,
                                                                                Long.parseLong(
                                                                                        matcher.group(1)));
                                                                    }
                                                                    svnFile = new SvnFile();
                                                                    svnFile.lastestVersion = Long
                                                                            .parseLong(matcher.group(2));
                                                                    svnFile.author = matcher.group(3);
                                                                    svnFile.filePath = matcher.group(4);
                                                                    svnFile.file = new File(svnFile.filePath);
                                                                    svnFile.fileName = svnFile.file.getName();
                                                                    svnFileSet.add(svnFile);
                                                                    authorSet.add(svnFile.author);
                                                                    String extension = null;
                                                                    if (svnFile.file.isFile()
                                                                            && (extension = getExtension(
                                                                                    svnFile.fileName)) != null) {
                                                                        fileExtenstionSet.add(extension);
                                                                    }
                                                                } catch (Exception ex) {
                                                                    ex.printStackTrace();
                                                                }
                                                            } else {
                                                                System.out.println("ignore : " + line);
                                                            }
                                                        }
                                                        reader.close();
                                                        lastestVersion = projectLastestVersion;
                                                        projectName = svnDir.getName();
                                                        resetUiAndShowMessage(startTime, projectName,
                                                                projectLastestVersion);
                                                    } catch (IOException e) {
                                                        JCommonUtil.handleException(e);
                                                    }
                                                }
                                            }, "loadSvnLastest_" + this.hashCode());
                                    thread.setDaemon(true);
                                    thread.start();
                                    setTitle("sweeping...");
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }

                            String getExtension(String name) {
                                int pos = -1;
                                if ((pos = name.lastIndexOf(".")) != -1) {
                                    return name.substring(pos).toLowerCase();
                                }
                                return null;
                            }
                        });
                    }
                    {
                        jLabel1 = new JLabel();
                        jPanel3.add(jLabel1);
                        jLabel1.setText("match :");
                        jLabel1.setPreferredSize(new java.awt.Dimension(56, 22));
                    }
                    {
                        matchCount = new JLabel();
                        jPanel3.add(matchCount);
                        matchCount.setPreferredSize(new java.awt.Dimension(82, 22));
                    }
                }
            }
            {
                jPanel2 = new JPanel();
                FlowLayout jPanel2Layout = new FlowLayout();
                jPanel2.setLayout(jPanel2Layout);
                jTabbedPane1.addTab("config", null, jPanel2, null);
                {
                    DefaultComboBoxModel authorComboBoxModel = new DefaultComboBoxModel();
                    authorComboBox = new JComboBox();
                    jPanel2.add(authorComboBox);
                    authorComboBox.setModel(authorComboBoxModel);
                    authorComboBox.setPreferredSize(new java.awt.Dimension(260, 24));
                    authorComboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                Object author = authorComboBox.getSelectedItem();
                                if (author instanceof Map.Entry) {
                                    Map.Entry<?, ?> entry = (Map.Entry<?, ?>) author;
                                    reloadSvnTable((String) entry.getKey(), _authorScanProcess);
                                } else {
                                    reloadSvnTable((String) author, _authorScanProcess);
                                }
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    ComboBoxModel jComboBox1Model = new DefaultComboBoxModel();
                    fileExtensionComboBox = new JComboBox();
                    jPanel2.add(fileExtensionComboBox);
                    fileExtensionComboBox.setModel(jComboBox1Model);
                    fileExtensionComboBox.setPreferredSize(new java.awt.Dimension(186, 24));
                    fileExtensionComboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                String extension = (String) fileExtensionComboBox.getSelectedItem();
                                reloadSvnTable(extension, _fileExtensionScanProcess);
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    jScrollPane2 = new JScrollPane();
                    jScrollPane2.setPreferredSize(new java.awt.Dimension(130, 200));
                    jPanel2.add(jScrollPane2);
                    {
                        DefaultListModel model = new DefaultListModel();
                        fileExtensionFilter = new JList();
                        jScrollPane2.setViewportView(fileExtensionFilter);
                        fileExtensionFilter.setModel(model);
                        fileExtensionFilter.addListSelectionListener(new ListSelectionListener() {
                            public void valueChanged(ListSelectionEvent evt) {
                                try {
                                    System.out
                                            .println(Arrays.toString(fileExtensionFilter.getSelectedValues()));
                                    String extensionStr = "";
                                    StringBuilder sb = new StringBuilder();
                                    for (Object val : fileExtensionFilter.getSelectedValues()) {
                                        sb.append(val + ",");
                                    }
                                    extensionStr = (sb.length() > 0 ? sb.deleteCharAt(sb.length() - 1) : sb)
                                            .toString();
                                    System.out.format("extensionStr = [%s]\n", extensionStr);
                                    multiExtendsionFilter.setName(extensionStr);
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }
                        });
                    }
                }
                {
                    multiExtendsionFilter = new JButton();
                    jPanel2.add(multiExtendsionFilter);
                    multiExtendsionFilter.setText("multi extension filter");
                    multiExtendsionFilter.setPreferredSize(new java.awt.Dimension(166, 34));
                    multiExtendsionFilter.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                reloadSvnTable(multiExtendsionFilter.getName(), _fileExtensionMultiScanProcess);
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    loadAuthorReference = new JButton();
                    jPanel2.add(loadAuthorReference);
                    loadAuthorReference.setText("load author reference");
                    loadAuthorReference.setPreferredSize(new java.awt.Dimension(188, 35));
                    loadAuthorReference.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                File file = JFileChooserUtil.newInstance().selectFileOnly().showOpenDialog()
                                        .getApproveSelectedFile();
                                if (file == null) {
                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                            .showMessageDialog("file is not correct!", "ERROR");
                                    return;
                                }
                                authorProps.load(new FileInputStream(file));
                                reloadAuthorComboBox();
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    saveCurrentData = new JButton();
                    jPanel2.add(saveCurrentData);
                    saveCurrentData.setText("save current data");
                    saveCurrentData.setPreferredSize(new java.awt.Dimension(166, 34));
                    saveCurrentData.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                File saveDataConfig = new File(jarExistLocation, getSaveCurrentDataFileName());
                                ObjectOutputStream writer = new ObjectOutputStream(
                                        new FileOutputStream(saveDataConfig));
                                writer.writeObject(projectName);
                                writer.writeObject(authorSet);
                                writer.writeObject(fileExtenstionSet);
                                writer.writeObject(svnFileSet);
                                writer.writeObject(authorProps);
                                writer.writeObject(lastestVersion);
                                writer.flush();
                                writer.close();

                                JOptionPaneUtil.newInstance().iconInformationMessage()
                                        .showMessageDialog("current project : " + projectName
                                                + " save completed! \n" + saveDataConfig, "SUCCESS");
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    loadDataFromFile = new JButton();
                    jPanel2.add(loadDataFromFile);
                    loadDataFromFile.setText("load data cfg");
                    loadDataFromFile.setPreferredSize(new java.awt.Dimension(165, 35));
                    loadDataFromFile.addActionListener(new ActionListener() {
                        @SuppressWarnings("unchecked")
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                File file = JFileChooserUtil.newInstance().selectFileOnly()
                                        .addAcceptFile(".cfg", ".cfg").showOpenDialog()
                                        .getApproveSelectedFile();
                                if (file == null) {
                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                            .showMessageDialog("file is not correct!", "ERROR");
                                    return;
                                }
                                long startTime = System.currentTimeMillis();
                                ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
                                projectName = (String) input.readObject();
                                authorSet = (Set<String>) input.readObject();
                                fileExtenstionSet = (Set<String>) input.readObject();
                                svnFileSet = (Set<SvnFile>) input.readObject();
                                authorProps = (Properties) input.readObject();
                                lastestVersion = (Long) input.readObject();
                                input.close();

                                resetUiAndShowMessage(startTime, projectName, lastestVersion);
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
            }
        }
        pack();
        this.setSize(726, 459);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

/**
 * @see org.apache.james.mailrepository.lib.AbstractMailRepository#internalStore(Mail)
 *///  w  w  w  .j av a2s .  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);
    }
}

From source file:com.gs.collections.impl.test.Verify.java

private static String encodeObject(Object actualObject) {
    try {/*w w w. ja  va  2s  .com*/
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(actualObject);
        objectOutputStream.flush();
        objectOutputStream.close();

        String string = new Base64(76, LINE_SEPARATOR, false)
                .encodeAsString(byteArrayOutputStream.toByteArray());
        String trimmedString = Verify.removeFinalNewline(string);
        return Verify.addFinalNewline(trimmedString);
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}