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:org.datacleaner.user.UserPreferencesImpl.java

@Override
public void save() {
    if (_userPreferencesFile == null) {
        logger.debug("Not saving user preferences, since no user preferences file has been provided");
        return;// w w w .j ava  2  s .  c o  m
    }

    logger.info("Saving user preferences to {}", _userPreferencesFile.getName().getPath());

    ObjectOutputStream outputStream = null;
    try {
        OutputStream fileOutputStream = _userPreferencesFile.getContent().getOutputStream();
        outputStream = new ObjectOutputStream(fileOutputStream);
        outputStream.writeObject(this);
        outputStream.flush();
    } catch (Exception e) {
        logger.warn("Unexpected error while saving user preferences", e);
        throw new IllegalStateException(e);
    } finally {
        FileHelper.safeClose(outputStream);
    }
}

From source file:org.apache.lens.ml.LensMLImpl.java

/**
 * Persist model.//from w w w.  j  a  v  a  2s  .  co m
 *
 * @param model the model
 * @return the path
 * @throws IOException Signals that an I/O exception has occurred.
 */
private Path persistModel(MLModel model) throws IOException {
    // Get model save path
    Path algoDir = getAlgoDir(model.getAlgoName());
    FileSystem fs = algoDir.getFileSystem(conf);

    if (!fs.exists(algoDir)) {
        fs.mkdirs(algoDir);
    }

    Path modelSavePath = new Path(algoDir, model.getId());
    ObjectOutputStream outputStream = null;

    try {
        outputStream = new ObjectOutputStream(fs.create(modelSavePath, false));
        outputStream.writeObject(model);
        outputStream.flush();
    } catch (IOException io) {
        LOG.error("Error saving model " + model.getId() + " reason: " + io.getMessage());
        throw io;
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
    return modelSavePath;
}

From source file:org.kchine.rpf.PoolUtils.java

public static byte[] objectToBytes(Object obj) throws NoSuchObjectException {
    ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
    try {//  w ww.j a va2  s  .  c  o  m
        ObjectOutputStream oos = new ObjectOutputStream(baoStream);
        oos.writeObject(obj);
        oos.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return baoStream.toByteArray();
}

From source file:org.deidentifier.arx.gui.worker.WorkerSave.java

/**
 * Writes the lattice to the file./*from  www. j  a va  2  s.  c  o  m*/
 *
 * @param model
 * @param zip
 * @return
 * @throws IOException
 */
private Map<String, Integer> writeLattice(final Model model, final ZipOutputStream zip) throws IOException {

    // Mapping
    final Map<String, Integer> map = new HashMap<String, Integer>();
    if ((model.getResult() == null) || (model.getResult().getLattice() == null)) {
        return map;
    }

    // Write lattice
    final ARXLattice l = model.getResult().getLattice();
    zip.putNextEntry(new ZipEntry("lattice.xml")); //$NON-NLS-1$
    toXML(map, l, zip);

    zip.putNextEntry(new ZipEntry("lattice.dat")); //$NON-NLS-1$
    ObjectOutputStream oos = new ObjectOutputStream(zip);
    oos.writeObject(model.getResult().getLattice());
    oos.writeObject(model.getResult().getLattice().access().getAttributeMap());
    oos.flush();

    // Write score
    zip.putNextEntry(new ZipEntry("infoloss.dat")); //$NON-NLS-1$
    final Map<Integer, InformationLoss<?>> max = new HashMap<Integer, InformationLoss<?>>();
    final Map<Integer, InformationLoss<?>> min = new HashMap<Integer, InformationLoss<?>>();
    for (final ARXNode[] level : l.getLevels()) {
        for (final ARXNode n : level) {
            final String key = Arrays.toString(n.getTransformation());
            min.put(map.get(key), n.getLowestScore());
            max.put(map.get(key), n.getHighestScore());
        }
    }
    oos = new ObjectOutputStream(zip);
    oos.writeObject(min);
    oos.writeObject(max);
    oos.flush();
    min.clear();
    max.clear();

    // Write attributes
    zip.putNextEntry(new ZipEntry("attributes.dat")); //$NON-NLS-1$
    final Map<Integer, Map<Integer, Object>> attrs = new HashMap<Integer, Map<Integer, Object>>();
    for (final ARXNode[] level : l.getLevels()) {
        for (final ARXNode n : level) {
            final String key = Arrays.toString(n.getTransformation());
            attrs.put(map.get(key), n.getAttributes());
        }
    }
    oos = new ObjectOutputStream(zip);
    oos.writeObject(attrs);
    oos.flush();
    attrs.clear();

    // Return mapping
    return map;
}

From source file:hermes.impl.DefaultXMLHelper.java

public XMLMessage createXMLMessage(ObjectFactory factory, Message message)
        throws JMSException, IOException, EncoderException {
    try {/* ww  w  . j  ava  2 s.  co m*/
        XMLMessage rval = factory.createXMLMessage();

        if (message instanceof TextMessage) {
            rval = factory.createXMLTextMessage();

            XMLTextMessage textRval = (XMLTextMessage) rval;
            TextMessage textMessage = (TextMessage) message;

            if (isBase64EncodeTextMessages()) {
                byte[] bytes = base64EncoderTL.get().encode(textMessage.getText().getBytes());
                textRval.setText(new String(bytes, "ASCII"));
                textRval.setCodec(BASE64_CODEC);
            } else {
                textRval.setText(textMessage.getText());
            }
        } else if (message instanceof MapMessage) {
            rval = factory.createXMLMapMessage();

            XMLMapMessage mapRval = (XMLMapMessage) rval;
            MapMessage mapMessage = (MapMessage) message;

            for (Enumeration iter = mapMessage.getMapNames(); iter.hasMoreElements();) {
                String propertyName = (String) iter.nextElement();
                Object propertyValue = mapMessage.getObject(propertyName);
                Property xmlProperty = factory.createProperty();

                if (propertyValue != null) {
                    xmlProperty.setValue(propertyValue.toString());
                    xmlProperty.setType(propertyValue.getClass().getName());
                }
                xmlProperty.setName(propertyName);

                mapRval.getBodyProperty().add(xmlProperty);
            }
        } else if (message instanceof BytesMessage) {
            rval = factory.createXMLBytesMessage();

            XMLBytesMessage bytesRval = (XMLBytesMessage) rval;
            BytesMessage bytesMessage = (BytesMessage) message;
            ByteArrayOutputStream bosream = new ByteArrayOutputStream();

            bytesMessage.reset();

            try {
                for (;;) {
                    bosream.write(bytesMessage.readByte());
                }
            } catch (MessageEOFException ex) {
                // NOP
            }

            bytesRval.setBytes(new String(base64EncoderTL.get().encode(bosream.toByteArray())));
        } else if (message instanceof ObjectMessage) {
            rval = factory.createXMLObjectMessage();

            XMLObjectMessage objectRval = (XMLObjectMessage) rval;
            ObjectMessage objectMessage = (ObjectMessage) message;

            ByteArrayOutputStream bostream = new ByteArrayOutputStream();
            ObjectOutputStream oostream = new ObjectOutputStream(bostream);

            oostream.writeObject(objectMessage.getObject());
            oostream.flush();
            byte b[] = base64EncoderTL.get().encode(bostream.toByteArray());
            String s = new String(b, "ASCII");
            objectRval.setObject(s);
        }

        if (message.getJMSReplyTo() != null) {
            rval.setJMSReplyTo(JMSUtils.getDestinationName(message.getJMSReplyTo()));
            rval.setJMSReplyToDomain(Domain.getDomain(message.getJMSReplyTo()).getId());
        }

        // try/catch each individually as we sometime find some JMS
        // providers
        // can barf
        try {
            rval.setJMSDeliveryMode(message.getJMSDeliveryMode());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSExpiration(message.getJMSExpiration());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSMessageID(message.getJMSMessageID());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSPriority(message.getJMSPriority());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSRedelivered(message.getJMSRedelivered());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        } catch (IllegalStateException ex) {
            // http://hermesjms.com/forum/viewtopic.php?f=4&t=346

            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSTimestamp(message.getJMSTimestamp());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSType(message.getJMSType());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            rval.setJMSCorrelationID(message.getJMSCorrelationID());
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        try {
            if (message.getJMSDestination() != null) {
                rval.setJMSDestination(JMSUtils.getDestinationName(message.getJMSDestination()));
                rval.setFromQueue(JMSUtils.isQueue(message.getJMSDestination()));
            }
        } catch (JMSException ex) {
            log.error(ex.getMessage(), ex);
        }

        for (final Enumeration iter = message.getPropertyNames(); iter.hasMoreElements();) {
            String propertyName = (String) iter.nextElement();

            if (!propertyName.startsWith("JMS")) {
                Object propertyValue = message.getObjectProperty(propertyName);
                Property property = factory.createProperty();

                property.setName(propertyName);

                if (propertyValue != null) {
                    property.setValue(StringEscapeUtils.escapeXml(propertyValue.toString()));
                    property.setType(propertyValue.getClass().getName());
                }

                rval.getHeaderProperty().add(property);
            }
        }

        return rval;
    } catch (Exception ex) {
        throw new HermesException(ex);
    }
}

From source file:com.holycityaudio.SpinCAD.SpinCADFile.java

public void fileSaveBank(SpinCADBank b) {
    File fileToBeSaved = new File(prefs.get("MRUBankFolder", "") + "/" + b.bankFileName);
    String filePath = fileToBeSaved.getPath();
    loadRecentBankFileList();/*from  w  ww .j  av  a2s.  co m*/

    try {
        FileOutputStream fos = new FileOutputStream(filePath);
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        oos.writeObject(b);

        oos.flush();
        oos.close();
    } catch (Exception e) {
        System.out.println("Exception during serialization: " + e);
        //      System.exit(0); 
    } finally {
        saveMRUBankFolder(filePath);
        recentBankFileList.add(fileToBeSaved);
        saveRecentBankFileList();
    }
}

From source file:com.izforge.izpack.compiler.packager.impl.PackagerBase.java

/**
 * Write an arbitrary object to installer jar.
 *
 * @throws IOException for any I/O error
 *//*from w  ww .ja  va 2  s. co  m*/
protected void writeInstallerObject(String entryName, Object object) throws IOException {
    installerJar.putNextEntry(new org.apache.tools.zip.ZipEntry(RESOURCES_PATH + entryName));
    ObjectOutputStream out = new ObjectOutputStream(installerJar);
    try {
        out.writeObject(object);
    } catch (IOException e) {
        throw new IOException("Error serializing instance of " + object.getClass().getName() + " as entry \""
                + entryName + "\"", e);
    } finally {
        out.flush();
        installerJar.closeEntry();
    }
}

From source file:org.apache.lens.ml.impl.LensMLImpl.java

/**
 * Persist model.//ww w .  jav a 2 s .co m
 *
 * @param model the model
 * @return the path
 * @throws IOException Signals that an I/O exception has occurred.
 */
private Path persistModel(MLModel model) throws IOException {
    // Get model save path
    Path algoDir = getAlgoDir(model.getAlgoName());
    FileSystem fs = algoDir.getFileSystem(conf);

    if (!fs.exists(algoDir)) {
        fs.mkdirs(algoDir);
    }

    Path modelSavePath = new Path(algoDir, model.getId());
    ObjectOutputStream outputStream = null;

    try {
        outputStream = new ObjectOutputStream(fs.create(modelSavePath, false));
        outputStream.writeObject(model);
        outputStream.flush();
    } catch (IOException io) {
        log.error("Error saving model " + model.getId() + " reason: " + io.getMessage(), io);
        throw io;
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
    return modelSavePath;
}

From source file:cat.albirar.framework.dynabean.annotations.DynaBeanAnnotationsTest.java

/**
 * Test the serialization feature.// www . java2 s  .  co m
 */
@Test
public void testSerialize() throws Exception {
    ByteArrayOutputStream baos;
    IAnnotatedModel model, model1;
    ObjectOutputStream out;
    ByteArrayInputStream bais;
    ObjectInputStream in;

    // Prepare bean
    model = factory.newDynaBean(IAnnotatedModel.class);

    // Prepare stream
    baos = new ByteArrayOutputStream();
    out = new ObjectOutputStream(baos);
    out.writeObject(model);
    out.flush();

    // Deserialize
    bais = new ByteArrayInputStream(baos.toByteArray());
    in = new ObjectInputStream(bais);
    model1 = (IAnnotatedModel) in.readObject();

    // Test if equals
    Assert.assertNotNull(model1);
    Assert.assertEquals(model, model1);
    Assert.assertNotSame(model, model1);
}

From source file:org.jboss.dashboard.workspace.PanelInstance.java

public void setContentData(Serializable data) {
    //this.data = data;
    try {// w w w  .ja  v  a 2  s  .  co m
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(buf);
        out.writeObject(data);
        out.flush();
        out.close();
        setPersistence(Base64.encode(buf.toByteArray()));
    } catch (Exception e) {
        log.error("Cannot persist content data for instance " + dbid, e);
    }
    log.debug("ContentData for instance " + getDbid() + " set to " + data);
    log.debug(" persistence = " + persistence);
}