Example usage for java.io ObjectOutputStream ObjectOutputStream

List of usage examples for java.io ObjectOutputStream ObjectOutputStream

Introduction

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

Prototype

public ObjectOutputStream(OutputStream out) throws IOException 

Source Link

Document

Creates an ObjectOutputStream that writes to the specified OutputStream.

Usage

From source file:com.tempescope.wunderground.WeatherLocationManager.java

public void save() {
    if (file != null) {
        try {//from   w  w w.  j a va 2 s  .  co m
            ObjectOutputStream out = new ObjectOutputStream(
                    new BufferedOutputStream(new FileOutputStream(file)));
            out.writeObject(this);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:WriteDoubleUsingSockets.java

public void init() {
    Date d = new Date();
    // Get the portnumber and servername and allow to be called from a
    // java main program also
    try {//from   w  w w.jav  a 2s.  c  om
        String param;
        param = getParameter("PortNumber");
        if (param != null)
            PortNumber = Integer.parseInt(param);
        param = getParameter("ServerName");
        if (param != null)
            ServerName = param;
    } catch (NullPointerException e) { // Must be called from a main ignore
    }
    try {
        Socket skt = new Socket(ServerName, PortNumber);
        os = new DataOutputStream(skt.getOutputStream());
    } catch (Exception e) {
        Label l = new Label(e.toString());
        add(l);
        System.out.println(e);
        return;
    }
    try {
        s = new ObjectOutputStream(os);
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("Unable to open stream as an object stream");
    }
    try {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 25; i++) {
            s.writeObject(new Double(i));
        }
        os.close();
        long endTime = System.currentTimeMillis() - startTime;
        Label l = new Label(
                "Writing 25 doubles server took: " + new Long(endTime).toString() + " milliseconds.");
        add(l);
        System.out.println("Object written");
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("Unable to write Objects");
    }
}

From source file:com.moisespsena.vraptor.javaobjectserialization.JavaObjectSerializerBuilder.java

@Override
public void serialize() {
    ObjectOutputStream out = null;

    try {//from  ww  w .  ja v a  2s  .c om
        if (outputStream instanceof ObjectOutputStream) {
            out = (ObjectOutputStream) outputStream;
        } else {
            out = new ObjectOutputStream(outputStream);
        }

        out.writeObject(source);
        out.flush();
    } catch (final IOException e) {
        throw new SerializationException(e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                throw new SerializationException(e);
            }
        }
    }
}

From source file:com.bah.applefox.main.plugins.pageranking.utilities.PRtoFile.java

public static boolean writeToFile(String[] args) {
    String fileName = args[16];/*from   w  w  w . java  2  s  . c o  m*/
    File f = new File(fileName);
    try {
        f.createNewFile();
        OutputStream file = new FileOutputStream(f);
        OutputStream buffer = new BufferedOutputStream(file);
        ObjectOutput out = new ObjectOutputStream(buffer);
        out.writeObject(createMap(args));
        out.flush();
        out.close();
    } catch (IOException e) {
        if (e.getMessage() != null) {
            log.error(e.getMessage());
        } else {
            log.error(e.getStackTrace());
        }
        return false;
    } catch (AccumuloException e) {
        if (e.getMessage() != null) {
            log.error(e.getMessage());
        } else {
            log.error(e.getStackTrace());
        }
        return false;
    } catch (AccumuloSecurityException e) {
        if (e.getMessage() != null) {
            log.error(e.getMessage());
        } else {
            log.error(e.getStackTrace());
        }
        return false;
    } catch (TableNotFoundException e) {
        if (e.getMessage() != null) {
            log.error(e.getMessage());
        } else {
            log.error(e.getStackTrace());
        }
        return false;
    }

    return true;

}

From source file:com.google.u2f.gaedemo.impl.DataStoreImpl.java

@Override
public String storeSessionData(EnrollSessionData sessionData) {

    SecretKey key = new SecretKeySpec(SecretKeys.get().sessionEncryptionKey(), "AES");
    byte[] ivBytes = new byte[16];
    random.nextBytes(ivBytes);//from  w w  w .j  ava2 s.  c  o m
    final IvParameterSpec IV = new IvParameterSpec(ivBytes);
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, IV);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    }

    SealedObject sealed;
    try {
        sealed = new SealedObject(sessionData, cipher);
    } catch (IllegalBlockSizeException | IOException e) {
        throw new RuntimeException(e);
    }

    ByteArrayOutputStream out;
    try {
        out = new ByteArrayOutputStream();
        ObjectOutputStream outer = new ObjectOutputStream(out);

        outer.writeObject(sealed);
        outer.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return Base64.encodeBase64URLSafeString(out.toByteArray());
}

From source file:cn.guoyukun.spring.jpa.repository.hibernate.type.ObjectSerializeUserType.java

/**
 * Hibernate??//from  w w w . jav a 2s. com
 * ?PreparedStateme??
 */
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
        throws HibernateException, SQLException {
    ObjectOutputStream oos = null;
    if (value == null) {
        st.setNull(index, Types.VARCHAR);
    } else {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(value);
            oos.close();

            byte[] objectBytes = bos.toByteArray();
            String hexStr = Hex.encodeHexString(objectBytes);

            st.setString(index, hexStr);
        } catch (Exception e) {
            throw new HibernateException(e);
        } finally {
            try {
                oos.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:io.cloudslang.engine.queue.entities.ExecutionMessageConverter.java

private byte[] objToBytes(Object obj) {
    ObjectOutputStream oos = null;
    try {//from   www . j  a v a 2s .c  om
        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        initPayloadMetaData(bout);

        BufferedOutputStream bos = new BufferedOutputStream(bout);
        oos = new ObjectOutputStream(bos);

        oos.writeObject(obj);
        oos.flush();

        return bout.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException("Failed to serialize execution plan. Error: ", ex);
    } finally {
        IOUtils.closeQuietly(oos);
    }
}

From source file:com.cedarsoft.crypt.HashTest.java

License:asdf

@Test
public void testSerialization() throws IOException, ClassNotFoundException {
    Hash hash = Hash.fromHex(Algorithm.SHA256, "1234");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    new ObjectOutputStream(out).writeObject(hash);

    Hash deserialized = (Hash) new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())).readObject();
    assertEquals(deserialized, hash);/* ww  w .  j av  a  2 s . com*/
}

From source file:org.nebulaframework.util.io.IOSupport.java

/**
 * Serializes the given object and returns a byte[] representation of
 * the serialized data.//from   w  w w.  j  a va2s.c  o  m
 * 
 * @param obj Object to Serialize
 * 
 * @return byte[] of serialized data
 * 
 * @throws IOException if thrown during serialization
 */
public static <T extends Serializable> byte[] serializeToBytes(T obj) throws IOException {

    Assert.notNull(obj);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(obj);

    return bos.toByteArray();
}

From source file:edu.cwru.sepia.runner.SimpleModelEpisodicRunner.java

@Override
public void run() {
    seed = configuration.getInt("RandomSeed", 6);
    numEpisodes = configuration.getInt("NumEpisodes", 1);
    episodesPerSave = configuration.getInt("EpisodesPerSave", 0);
    saveAgents = configuration.getBoolean("SaveAgents", false);

    SimpleModel model = new SimpleModel(stateCreator.createState(), stateCreator, configuration);
    File baseDirectory = new File("saves");
    baseDirectory.mkdirs();//from w  w w  . j a va2s .  c o m
    env = new Environment(agents, model, seed, configuration);
    for (int episode = 0; episode < numEpisodes; episode++) {
        if (logger.isLoggable(Level.FINE))
            logger.fine("=======> Starting episode " + episode);
        try {
            env.runEpisode();
        } catch (InterruptedException e) {
            logger.log(Level.SEVERE, "Unable to complete episode " + episode, e);
        }
        if (episodesPerSave > 0 && episode % episodesPerSave == 0) {
            saveState(new File(baseDirectory.getPath() + "/state" + episode + ".sepiaSave"),
                    env.getModel().getState());
            for (int j = 0; saveAgents && j < agents.length; j++) {
                try {
                    ObjectOutputStream agentOut = new ObjectOutputStream(
                            new FileOutputStream(baseDirectory.getPath() + "/agent" + j + "-" + episode));
                    agentOut.writeObject(agents[j]);
                    agentOut.close();
                } catch (Exception ex) {
                    logger.info("Unable to save agent " + j);
                }
            }
        }
    }
}