/** * Serializes a {@link ModelMBeanConstructorInfo} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("consDescriptor", consDescriptor); fields.put("currClass", currClass); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } }
/** * 将对象储存到sharepreference * * @param key * @param device * @param <T> */ public static <T> boolean saveDeviceData(Context context, String key, T device) { if (mSharedPreferences == null) { mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { //Device为自定义类 // 创建对象输出流,并封装字节流 ObjectOutputStream oos = new ObjectOutputStream(baos); // 将对象写入字节流 oos.writeObject(device); // 将字节流编码成base64的字符串 String oAuth_Base64 = new String(Base64.encode(baos .toByteArray(), Base64.DEFAULT)); mSharedPreferences.edit().putString(key, oAuth_Base64).commit(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
/** * Write and read long arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write * cycles. The ObjectOutputStream is reset after each batch of cycles has * completed. * Arguments: <array size> <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { int size = Integer.parseInt(args[0]); int nbatches = Integer.parseInt(args[1]); int ncycles = Integer.parseInt(args[2]); long[][] arrays = new long[ncycles][size]; StreamBuffer sbuf = new StreamBuffer(); ObjectOutputStream oout = new ObjectOutputStream(sbuf.getOutputStream()); ObjectInputStream oin = new ObjectInputStream(sbuf.getInputStream()); doReps(oout, oin, sbuf, arrays, 1); // warmup long start = System.currentTimeMillis(); doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; }
public void run() { try { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(vector); oos.close(); } catch (final IOException ioe) { addException(ioe); } finally { try { testEnd.await(); } catch (Exception e) { addException(e); } } }
/** * Serialize this {@code CertificateRevokedException} instance. * * @serialData the size of the extensions map (int), followed by all of * the extensions in the map, in no particular order. For each extension, * the following data is emitted: the OID String (Object), the criticality * flag (boolean), the length of the encoded extension value byte array * (int), and the encoded extension value bytes. */ private void writeObject(ObjectOutputStream oos) throws IOException { // Write out the non-transient fields // (revocationDate, reason, authority) oos.defaultWriteObject(); // Write out the size (number of mappings) of the extensions map oos.writeInt(extensions.size()); // For each extension in the map, the following are emitted (in order): // the OID String (Object), the criticality flag (boolean), the length // of the encoded extension value byte array (int), and the encoded // extension value byte array. The extensions themselves are emitted // in no particular order. for (Map.Entry<String, Extension> entry : extensions.entrySet()) { Extension ext = entry.getValue(); oos.writeObject(ext.getId()); oos.writeBoolean(ext.isCritical()); byte[] extVal = ext.getValue(); oos.writeInt(extVal.length); oos.write(extVal); } }
/** * Serializes the given collection. * <p> * First writes a <code>int</code> indicating the number of all * serializable elements (implements <code>Serializable</code>, then * objects are writtern one by one.</p> * * @param oos the stream where the collection is writtern to * @param collection the collection to serialize * @throws IOException if I/O exception occurs */ protected final void serialize(ObjectOutputStream oos, Collection collection) throws IOException { Object array[] = collection.toArray(); int serCount = 0; for (int i = 0; i < array.length; i++) { if (array[i] instanceof Serializable) { serCount++; } } oos.writeInt(serCount); for (int i = 0; i < array.length; i++) { if (array[i] instanceof Serializable) { oos.writeObject(array[i]); } } }
public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { if (parameter == null) { ps.setNull(i, SerializableTypeHandler.serializableType); } else { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(parameter); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ps.setBinaryStream(i, bais, bytes.length); } catch (Throwable e) { throw new SerializationException(e); } } }
private void writeObject(ObjectOutputStream s) throws IOException { Vector<Object> values = new Vector<Object>(); s.defaultWriteObject(); // Save the invoker, if its Serializable. if(invoker != null && invoker instanceof Serializable) { values.addElement("invoker"); values.addElement(invoker); } // Save the popup, if its Serializable. if(popup != null && popup instanceof Serializable) { values.addElement("popup"); values.addElement(popup); } s.writeObject(values); if (getUIClassID().equals(uiClassID)) { byte count = JComponent.getWriteObjCounter(this); JComponent.setWriteObjCounter(this, --count); if (count == 0 && ui != null) { ui.installUI(this); } } }
/** * Serializes a {@link ModelMBeanAttributeInfo} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("attrDescriptor", attrDescriptor); fields.put("currClass", currClass); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } }
@Test public void testNullUpValueStaticSerialization() throws LdapException, IOException, ClassNotFoundException { Ava atav = new Ava( schemaManager, "DC", ( String ) null ); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream( baos ); try { atav.writeExternal( out ); fail(); } catch ( IOException ioe ) { String message = ioe.getMessage(); assertEquals( "Cannot serialize a wrong ATAV, the value should not be null", message ); } }
/** * Test serialization of a simple ATAV */ @Test public void testNullAtavSerialization() throws LdapException, IOException, ClassNotFoundException { Ava atav = new Ava(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream( baos ); try { atav.writeExternal( out ); fail(); } catch ( IOException ioe ) { assertTrue( true ); } }
private final void testSerializationAndCloning(Tree node) throws Exception { // Serialize ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(node); oos.flush(); byte[] bytes = baos.toByteArray(); // System.out.println(new String(bytes)); // Deserialize ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); Tree copy = (Tree) ois.readObject(); String txtOriginal = node.toString("debug"); String txtCopy = copy.toString("debug"); assertEquals(txtOriginal, txtCopy); // Cloning txtCopy = node.clone().toString("debug"); assertEquals(txtOriginal, txtCopy); }
/** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { // test a default instance DialValueIndicator i1 = new DialValueIndicator(0, "Label"); DialValueIndicator i2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(i1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray())); i2 = (DialValueIndicator) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertEquals(i1, i2); // test a custom instance }
public XViewBody deepClone() { try { ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(this); ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi = new ObjectInputStream(bi); Object o = oi.readObject(); oi.close(); bi.close(); return (XViewBody) o; } catch (Exception e) { e.printStackTrace(); } return null; }
/** * Serializes an object and writes it to the disk. * <p>The file written will match the pattern "KEYNAME_CLASSNAME.ser"</p> * * @param theKey the key name associated with the object * @param theObject the object to serialize * @return true if the operation completed successfully */ public static final <E extends Serializable> boolean serializeToDisk(final String theKey, final E theObject) { boolean succeeded; try { final File file = new File(theKey + "_" + theObject.getClass().getSimpleName() + ".ser"); if (!file.exists()) { file.createNewFile(); } ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(theObject); oos.close(); succeeded = true; } catch (final Exception theException) { //System.err.println(theException.getMessage()); succeeded = false; } return succeeded; }
/** * Save the {@code BigInteger} instance to a stream. * The magnitude of a BigInteger is serialized as a byte array for * historical reasons. * * @serialData two necessary fields are written as well as obsolete * fields for compatibility with older versions. */ private void writeObject(ObjectOutputStream s) throws IOException { // set the values of the Serializable fields ObjectOutputStream.PutField fields = s.putFields(); fields.put("signum", signum); fields.put("magnitude", magSerializedForm()); // The values written for cached fields are compatible with older // versions, but are ignored in readObject so don't otherwise matter. fields.put("bitCount", -1); fields.put("bitLength", -1); fields.put("lowestSetBit", -2); fields.put("firstNonzeroByteNum", -2); // save them s.writeFields(); }
/** * Used by writeObject to serialize a Collection. * @param oos the {@code ObjectOutputStream} * to use during serialization * @param coll the {@code Collection} to serialize * @throws IOException if serialization failed */ protected final void serialize(ObjectOutputStream oos, Collection<?> coll) throws IOException { int count = 0; Object[] objects = coll.toArray(); for (int i = 0; i < objects.length; i++) { if (objects[i] instanceof Serializable) count++; else objects[i] = null; } oos.writeInt(count); // number of subsequent objects for (int i = 0; count > 0; i++) { Object o = objects[i]; if (o != null) { oos.writeObject(o); count--; } } }
/** * Write and read int arrays to/from a stream. The benchmark is run in * batches, with each batch consisting of a fixed number of read/write * cycles. The ObjectOutputStream is reset after each batch of cycles has * completed. * Arguments: <array size> <# batches> <# cycles per batch> */ public long run(String[] args) throws Exception { int size = Integer.parseInt(args[0]); int nbatches = Integer.parseInt(args[1]); int ncycles = Integer.parseInt(args[2]); int[][] arrays = new int[ncycles][size]; StreamBuffer sbuf = new StreamBuffer(); ObjectOutputStream oout = new ObjectOutputStream(sbuf.getOutputStream()); ObjectInputStream oin = new ObjectInputStream(sbuf.getInputStream()); doReps(oout, oin, sbuf, arrays, 1); // warmup long start = System.currentTimeMillis(); doReps(oout, oin, sbuf, arrays, nbatches); return System.currentTimeMillis() - start; }
/** * @serialData "permissions" field (a Vector containing the SocketPermissions). */ /* * Writes the contents of the perms field out as a Vector for * serialization compatibility with earlier releases. */ private void writeObject(ObjectOutputStream out) throws IOException { // Don't call out.defaultWriteObject() // Write out Vector Vector<SocketPermission> permissions = new Vector<>(perms.size()); synchronized (this) { permissions.addAll(perms); } ObjectOutputStream.PutField pfields = out.putFields(); pfields.put("permissions", permissions); out.writeFields(); }
protected byte[] objectToByte(Object obj){ byte[] bytes; if (obj instanceof String){ bytes = ((String)obj).getBytes(); } else if (obj instanceof byte[]){ bytes = (byte[]) obj; } else { try { //object to bytearray ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(obj); bytes = bo.toByteArray(); bo.close(); oo.close(); } catch(Exception e){ throw new RuntimeException(e); } } return(bytes); }
/** * Serializes a {@link RoleUnresolved} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("myRoleName", roleName); fields.put("myRoleValue", roleValue); fields.put("myPbType", problemType); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } }
/** * Serializes a {@link RoleInfo} to an {@link ObjectOutputStream}. */ private void writeObject(ObjectOutputStream out) throws IOException { if (compat) { // Serializes this instance in the old serial form // ObjectOutputStream.PutField fields = out.putFields(); fields.put("myName", name); fields.put("myIsReadableFlg", isReadable); fields.put("myIsWritableFlg", isWritable); fields.put("myDescription", description); fields.put("myMinDegree", minDegree); fields.put("myMaxDegree", maxDegree); fields.put("myRefMBeanClassName", referencedMBeanClassName); out.writeFields(); } else { // Serializes this instance in the new serial form // out.defaultWriteObject(); } }
/** * Encodes Object into String encoded in HEX format * @param value Object, which will be encoded * @return serialized Object in String encoded in HEX format * @throws IOException */ static String encodeValue(Object value) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(value); oos.close(); } catch (Exception e) { throw (IOException) ExternalUtil.copyAnnotation(new IOException(), e); } byte[] bArray = bos.toByteArray(); StringBuffer strBuff = new StringBuffer(bArray.length * 2); for (int i = 0; i < bArray.length; i++) { if ((bArray[i] < 16) && (bArray[i] >= 0)) { strBuff.append("0"); // NOI18N } strBuff.append(Integer.toHexString((bArray[i] < 0) ? (bArray[i] + 256) : bArray[i])); } return strBuff.toString(); }
private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); // Save serializable event listeners int priority = listenersArray.length - 1; // max priority s.writeInt(priority); // write max priority for (; priority >= 0; priority--) { T[] listeners = listenersArray[priority]; // Write in opposite order of adding for (int i = 0; i < listeners.length; i++) { T listener = listeners[i]; // Save only the serializable listeners if (listener instanceof Serializable) { s.writeObject(listener); } } s.writeObject(null); } }
public static byte[] serialize(Serializable obj) { try { try(ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream objStream = new ObjectOutputStream(out);) { objStream.writeObject(obj); return out.toByteArray(); } } catch(Exception ex) { throw new RuntimeException("Failed to serialize Object of type " + (obj == null ? "null" : obj.getClass().getName()), ex); } }
public WireIO createWireIOClient(Socket clientSocket) { try { clientSocket.setSoTimeout(0); clientSocket.setTcpNoDelay(true); // Necessary at least on Solaris to avoid delays in e.g. readInt() etc. ObjectOutputStream socketOut = new ObjectOutputStream(clientSocket.getOutputStream()); ObjectInputStream socketIn = new ObjectInputStream(clientSocket.getInputStream()); WireIO wireIO = new WireIO(socketOut, socketIn); return wireIO; } catch (IOException ex) { ex.printStackTrace(); } return null; }
private static void testSerialization(File testFile) { String path = testFile.getPath(); try { // serialize test file ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(testFile); oos.close(); // deserialize test file byte[] bytes = baos.toByteArray(); ByteArrayInputStream is = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(is); File newFile = (File) ois.readObject(); // test String newPath = newFile.getPath(); if (!path.equals(newPath)) { throw new RuntimeException( "Serialization should not change file path"); } test(newFile, false); } catch (IOException | ClassNotFoundException ex) { System.err.println("Exception happens in testSerialization"); System.err.println(ex.getMessage()); } }
/** * @serialData the expected values per key, the number of distinct keys, * the number of entries, and the entries in order */ @GwtIncompatible("java.io.ObjectOutputStream") private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(valueSetCapacity); stream.writeInt(keySet().size()); for (K key : keySet()) { stream.writeObject(key); } stream.writeInt(size()); for (Map.Entry<K, V> entry : entries()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } }
private byte[] writeObject(Object object) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(baos); out.writeObject(object); out.close(); return baos.toByteArray(); }
/** * Serializes a message into cluster data * * @param msg * ClusterMessage * @return serialized content as byte[] array * @throws IOException */ public static byte[] serialize(Serializable msg) throws IOException { ByteArrayOutputStream outs = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(outs); out.writeObject(msg); out.flush(); byte[] data = outs.toByteArray(); return data; }
/** * Writes a serialized representation of an arbitrary Java object to * a file. Make sure the serialized object is composed of standard Java types * only to avoid class loader problems. * * @param any The object to be serialized. * @param fileName The file to write to. * @return The full path of the written file. */ public static String writeObject(Object any, String fileName) { File file = new File(fileName); String path = file.getAbsolutePath(); try (FileOutputStream strm = new FileOutputStream(file); OutputStream buffer = new BufferedOutputStream(strm); ObjectOutput output = new ObjectOutputStream(buffer);) { output.writeObject(any); } catch (IOException e) { System.err.println("Output error."); return null; } return path; }
private void writeObject( ObjectOutputStream out) throws IOException { out.writeObject(this.getY()); out.writeObject(elSpec.getP()); out.writeObject(elSpec.getG()); }
@SuppressWarnings("unchecked") protected <T> T serializeDeserializeObject(T o) throws IOException, ClassNotFoundException { T o1; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(o); } try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) { o1 = (T) ois.readObject(); } return o1; }
static byte [] pickleXPE(XPathException xpe) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream xpeos = new ObjectOutputStream(bos); xpeos.writeObject(xpe); xpeos.close(); return bos.toByteArray(); }
static ByteString writeObject2ByteString(Object obj) { final ByteString.Output byteOut = ByteString.newOutput(); try(final ObjectOutputStream objOut = new ObjectOutputStream(byteOut)) { objOut.writeObject(obj); } catch (IOException e) { throw new IllegalStateException( "Unexpected IOException when writing an object to a ByteString.", e); } return byteOut.toByteString(); }
private void sendResponse(ObjectOutputStream out, Object response) throws IOException { out.writeObject(response); out.flush(); System.out.println("sending response to client-app..."); System.out.println(response); }
private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(cookie.name()); out.writeObject(cookie.value()); out.writeLong(cookie.persistent() ? cookie.expiresAt() : NON_VALID_EXPIRES_AT); out.writeObject(cookie.domain()); out.writeObject(cookie.path()); out.writeBoolean(cookie.secure()); out.writeBoolean(cookie.httpOnly()); out.writeBoolean(cookie.hostOnly()); }
/** * See <code>readObject</code> and <code>writeObject</code> in * <code>JComponent</code> for more * information about serialization in Swing. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); if (getUIClassID().equals(uiClassID)) { byte count = JComponent.getWriteObjCounter(this); JComponent.setWriteObjCounter(this, --count); if (count == 0 && ui != null) { ui.installUI(this); } } }
/** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.upArrow, stream); SerialUtilities.writeShape(this.downArrow, stream); SerialUtilities.writeShape(this.leftArrow, stream); SerialUtilities.writeShape(this.rightArrow, stream); }