Example usage for java.io ObjectOutput writeObject

List of usage examples for java.io ObjectOutput writeObject

Introduction

In this page you can find the example usage for java.io ObjectOutput writeObject.

Prototype

public void writeObject(Object obj) throws IOException;

Source Link

Document

Write an object to the underlying storage or stream.

Usage

From source file:org.buzzjoe.SimpleDataStorage.SimpleDataStorage.java

/**
 * Stores some Data in this.data container.<br>
 * //from w  ww  .  j a v a  2  s.co  m
 * @param keyName f.e. 'myKey' or 'buzzjoe.home'
 * @param data data to be stored. Accepts String and Integer by default. Other datatypes will be serialized.
 * @param serializeData set to true if you want to serialize in every case
 * 
 */
public void set(String keyName, Object data, boolean serializeData) {

    if ((data instanceof Integer || data instanceof String) && !serializeData) {
        this.data.setProperty(keyName, data.toString());
        this.dataChanged = true;
    } else {

        // okay. Seems like we got something to serialize
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = null;
        try {
            ObjectOutput out = new ObjectOutputStream(bos);
            out.writeObject(data);
            out.close();
            buf = bos.toByteArray();

        } catch (Exception e) {
            System.out.println("SimpleDataStorage - Error: Given datatype for key " + keyName
                    + " is not serializeable. Can't store it.");
            System.out.println(e.toString());
        }

        byte[] encoded = Base64.encodeBase64(buf);
        String outString = "";
        try {
            outString = new String(encoded, "ASCII");
        } catch (Exception e) {

        }
        this.data.setProperty(keyName, outString);
        this.dataChanged = true;
    }

    // this is a very bad idea. But it is the only secure way to store
    // the data to the file system. 
    // Needs some polish because method is called after every changing action
    if (this.doAutosave)
        this.writeToFile();
}

From source file:info.magnolia.cms.core.version.VersionManager.java

/**
 * create version of the specified node and all child nodes based on the given <code>Rule</code>
 *
 * @param node to be versioned// ww w . j  av a  2  s  . c om
 * @param rule
 * @return newly created version node
 * @throws UnsupportedOperationException if repository implementation does not support Versions API
 * @throws javax.jcr.RepositoryException if any repository error occurs
 */
private Version createVersion(Content node, Rule rule)
        throws UnsupportedRepositoryOperationException, RepositoryException {
    if (VersionConfig.getMaxVersionIndex() < 1) {
        log.debug("Ignore create version, MaxVersionIndex < 1");
        log.debug("Returning root version of the source node");
        return node.getJCRNode().getVersionHistory().getRootVersion();
    }
    CopyUtil.getInstance().copyToversion(node, new RuleBasedContentFilter(rule));
    Content versionedNode = this.getVersionedNode(node);
    Content systemInfo = this.getSystemNode(versionedNode);
    // add serialized rule which was used to create this version
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ObjectOutput objectOut = new ObjectOutputStream(out);
        objectOut.writeObject(rule);
        objectOut.flush();
        objectOut.close();
        NodeData nodeData;
        // PROPERTY_RULE is not a part of MetaData to allow versioning of node types which does NOT support MetaData
        if (!systemInfo.hasNodeData(PROPERTY_RULE))
            nodeData = systemInfo.createNodeData(PROPERTY_RULE);
        else
            nodeData = systemInfo.getNodeData(PROPERTY_RULE);
        nodeData.setValue(out.toString());
    } catch (IOException e) {
        throw new RepositoryException("Unable to add serialized Rule to the versioned content");
    }
    // temp fix, MgnlContext should always have user either logged-in or anonymous
    String userName = "";
    if (MgnlContext.getUser() != null)
        userName = MgnlContext.getUser().getName();
    // add all system properties for this version
    if (!systemInfo.hasNodeData(ContentVersion.VERSION_USER))
        systemInfo.createNodeData(ContentVersion.VERSION_USER).setValue(userName);
    else
        systemInfo.getNodeData(ContentVersion.VERSION_USER).setValue(userName);
    if (!systemInfo.hasNodeData(ContentVersion.NAME))
        systemInfo.createNodeData(ContentVersion.NAME).setValue(node.getName());
    else
        systemInfo.getNodeData(ContentVersion.NAME).setValue(node.getName());

    versionedNode.save();
    // add version
    Version newVersion = versionedNode.getJCRNode().checkin();
    versionedNode.getJCRNode().checkout();
    try {
        this.setMaxVersionHistory(versionedNode);
    } catch (RepositoryException re) {
        log.error("Failed to limit version history to the maximum configured", re);
        log.error("New version has already been created");
    }

    return newVersion;
}

From source file:com.ethanruffing.preferenceabstraction.AutoPreferences.java

/**
 * Stores any object in the preferences, overwriting any identically-named
 * properties./*  ww  w .j  av  a  2s .c  o m*/
 * <p>
 * Note: Do not abuse this method. Many backends are not intended for
 * storing large data chunks and can be severely inhibited by doing so.
 *
 * @param key   The key to store the object under.
 * @param value The object to store.
 */
@Override
public void put(String key, Object value) {
    if (configType == ConfigurationType.SYSTEM) {
        // Translate to a byte array.
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = null;
        try {
            out = new ObjectOutputStream(bos);
            out.writeObject(value);
            put(key, bos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException ex) {
                // ignore close exception
            }
            try {
                bos.close();
            } catch (IOException ex) {
                // ignore close exception
            }
        }
    } else {
        fileConfig.setProperty(key, value);
    }
}

From source file:org.apache.stratos.cartridge.agent.registrant.RegistrantDatabase.java

private void persist(Registrant registrant) throws CartridgeAgentException {
    try {/*from  ww  w  .  j  ava 2 s .co m*/
        ObjectOutput out = null;
        try {
            // Serialize to a file
            if (!new File("registrants").exists() && !new File("registrants").mkdirs()) {
                throw new IOException("Cannot create registrants directory");
            }
            out = new ObjectOutputStream(
                    new FileOutputStream("registrants" + File.separator + registrant.getKey() + ".ser"));
            out.writeObject(registrant);
            out.close();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    } catch (IOException e) {
        log.error("Could not serialize registrant " + registrant, e);
    }
}

From source file:org.jfree.data.junit.KeyedObjectsTests.java

/**
 * Serialize an instance, restore it, and check for equality.
 *///  w w  w . java2s. co m
public void testSerialization() {

    KeyedObjects ko1 = new KeyedObjects();
    ko1.addObject("Key 1", "Object 1");
    ko1.addObject("Key 2", null);
    ko1.addObject("Key 3", "Object 2");

    KeyedObjects ko2 = null;

    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(ko1);
        out.close();

        ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
        ko2 = (KeyedObjects) in.readObject();
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals(ko1, ko2);

}

From source file:org.jfree.data.junit.DefaultKeyedValuesTest.java

/**
 * Serialize an instance, restore it, and check for equality.
 *///from   w  w  w  .  j  a  v  a2 s.  c  om
public void testSerialization() {

    DefaultKeyedValues v1 = new DefaultKeyedValues();
    v1.addValue("Key 1", new Double(23));
    v1.addValue("Key 2", null);
    v1.addValue("Key 3", new Double(42));

    DefaultKeyedValues v2 = null;

    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(v1);
        out.close();

        ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()));
        v2 = (DefaultKeyedValues) in.readObject();
        in.close();
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    assertEquals(v1, v2);

}

From source file:com.act.reachables.Network.java

public void serialize(String toFile) {
    try {//  w  w w  . j a  v  a 2  s. com
        OutputStream file = new FileOutputStream(toFile);
        OutputStream buffer = new BufferedOutputStream(file);
        ObjectOutput output = new ObjectOutputStream(buffer);
        try {
            output.writeObject(this);
        } finally {
            output.close();
        }
    } catch (IOException ex) {
        throw new RuntimeException("Network serialize failed: " + ex);
    }
}

From source file:uk.co.revsys.content.repository.cloud.CloudCacheStore.java

@Override
protected void toStreamLockSafe(ObjectOutput objectOutput) throws CacheLoaderException {
    try {//from  w w w  .ja  va2s .c  o  m
        objectOutput.writeObject(containerName);
    } catch (Exception e) {
        throw convertToCacheLoaderException("Error while writing to stream", e);
    }
}

From source file:com.exadel.flamingo.flex.messaging.amf.io.AMF0Serializer.java

private void writeAMF3Data(AMF3Object data) throws IOException {
    outputStream.writeByte(AMF0Body.DATA_TYPE_AMF3_OBJECT);
    //ObjectOutput amf3 = GraniteContext.getCurrentInstance().getGraniteConfig().newAMF3Serializer(outputStream);
    ObjectOutput amf3 = new AMF3Serializer(outputStream);
    amf3.writeObject(data.getValue());
}

From source file:org.openspaces.remoting.ExecutorRemotingTask.java

public void writeExternal(ObjectOutput out) throws IOException {
    out.writeUTF(lookupName);/*from   w ww. j  a  v  a 2 s .  co  m*/
    out.writeUTF(methodName);
    if (arguments == null) {
        out.writeInt(0);
    } else {
        out.writeInt(arguments.length);
        for (Object arg : arguments) {
            out.writeObject(arg);
        }
    }
    if (metaArguments == null) {
        out.writeInt(0);
    } else {
        out.writeInt(metaArguments.length);
        for (Object arg : metaArguments) {
            out.writeObject(arg);
        }
    }

    methodHash.writeExternal(out);
}