Search in sources :

Example 1 with ObjectInputStream

use of java.io.ObjectInputStream in project tomcat by apache.

the class JDBCStore method load.

/**
     * Load the Session associated with the id <code>id</code>.
     * If no such session is found <code>null</code> is returned.
     *
     * @param id a value of type <code>String</code>
     * @return the stored <code>Session</code>
     * @exception ClassNotFoundException if an error occurs
     * @exception IOException if an input/output error occurred
     */
@Override
public Session load(String id) throws ClassNotFoundException, IOException {
    StandardSession _session = null;
    org.apache.catalina.Context context = getManager().getContext();
    Log contextLog = context.getLogger();
    synchronized (this) {
        int numberOfTries = 2;
        while (numberOfTries > 0) {
            Connection _conn = getConnection();
            if (_conn == null) {
                return null;
            }
            ClassLoader oldThreadContextCL = context.bind(Globals.IS_SECURITY_ENABLED, null);
            try {
                if (preparedLoadSql == null) {
                    String loadSql = "SELECT " + sessionIdCol + ", " + sessionDataCol + " FROM " + sessionTable + " WHERE " + sessionIdCol + " = ? AND " + sessionAppCol + " = ?";
                    preparedLoadSql = _conn.prepareStatement(loadSql);
                }
                preparedLoadSql.setString(1, id);
                preparedLoadSql.setString(2, getName());
                try (ResultSet rst = preparedLoadSql.executeQuery()) {
                    if (rst.next()) {
                        try (ObjectInputStream ois = getObjectInputStream(rst.getBinaryStream(2))) {
                            if (contextLog.isDebugEnabled()) {
                                contextLog.debug(sm.getString(getStoreName() + ".loading", id, sessionTable));
                            }
                            _session = (StandardSession) manager.createEmptySession();
                            _session.readObjectData(ois);
                            _session.setManager(manager);
                        }
                    } else if (context.getLogger().isDebugEnabled()) {
                        contextLog.debug(getStoreName() + ": No persisted data object found");
                    }
                    // Break out after the finally block
                    numberOfTries = 0;
                }
            } catch (SQLException e) {
                contextLog.error(sm.getString(getStoreName() + ".SQLException", e));
                if (dbConnection != null)
                    close(dbConnection);
            } finally {
                context.unbind(Globals.IS_SECURITY_ENABLED, oldThreadContextCL);
                release(_conn);
            }
            numberOfTries--;
        }
    }
    return _session;
}
Also used : Log(org.apache.juli.logging.Log) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ObjectInputStream(java.io.ObjectInputStream)

Example 2 with ObjectInputStream

use of java.io.ObjectInputStream in project hbase by apache.

the class HbaseObjectWritableFor96Migration method readObject.

/**
   * Read a {@link Writable}, {@link String}, primitive type, or an array of
   * the preceding.
   * @param in
   * @param objectWritable
   * @param conf
   * @return the object
   * @throws IOException
   */
@SuppressWarnings("unchecked")
static Object readObject(DataInput in, HbaseObjectWritableFor96Migration objectWritable, Configuration conf) throws IOException {
    Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in));
    Object instance;
    if (declaredClass.isPrimitive()) {
        // primitive types
        if (declaredClass == Boolean.TYPE) {
            // boolean
            instance = Boolean.valueOf(in.readBoolean());
        } else if (declaredClass == Character.TYPE) {
            // char
            instance = Character.valueOf(in.readChar());
        } else if (declaredClass == Byte.TYPE) {
            // byte
            instance = Byte.valueOf(in.readByte());
        } else if (declaredClass == Short.TYPE) {
            // short
            instance = Short.valueOf(in.readShort());
        } else if (declaredClass == Integer.TYPE) {
            // int
            instance = Integer.valueOf(in.readInt());
        } else if (declaredClass == Long.TYPE) {
            // long
            instance = Long.valueOf(in.readLong());
        } else if (declaredClass == Float.TYPE) {
            // float
            instance = Float.valueOf(in.readFloat());
        } else if (declaredClass == Double.TYPE) {
            // double
            instance = Double.valueOf(in.readDouble());
        } else if (declaredClass == Void.TYPE) {
            // void
            instance = null;
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }
    } else if (declaredClass.isArray()) {
        // array
        if (declaredClass.equals(byte[].class)) {
            instance = Bytes.readByteArray(in);
        } else {
            int length = in.readInt();
            instance = Array.newInstance(declaredClass.getComponentType(), length);
            for (int i = 0; i < length; i++) {
                Array.set(instance, i, readObject(in, conf));
            }
        }
    } else if (declaredClass.equals(Array.class)) {
        //an array not declared in CLASS_TO_CODE
        Class<?> componentType = readClass(conf, in);
        int length = in.readInt();
        instance = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(instance, i, readObject(in, conf));
        }
    } else if (List.class.isAssignableFrom(declaredClass)) {
        // List
        int length = in.readInt();
        instance = new ArrayList(length);
        for (int i = 0; i < length; i++) {
            ((ArrayList) instance).add(readObject(in, conf));
        }
    } else if (declaredClass == String.class) {
        // String
        instance = Text.readString(in);
    } else if (declaredClass.isEnum()) {
        // enum
        instance = Enum.valueOf((Class<? extends Enum>) declaredClass, Text.readString(in));
    } else if (declaredClass == Message.class) {
        String className = Text.readString(in);
        try {
            declaredClass = getClassByName(conf, className);
            instance = tryInstantiateProtobuf(declaredClass, in);
        } catch (ClassNotFoundException e) {
            LOG.error("Can't find class " + className, e);
            throw new IOException("Can't find class " + className, e);
        }
    } else if (Scan.class.isAssignableFrom(declaredClass)) {
        int length = in.readInt();
        byte[] scanBytes = new byte[length];
        in.readFully(scanBytes);
        ClientProtos.Scan.Builder scanProto = ClientProtos.Scan.newBuilder();
        ProtobufUtil.mergeFrom(scanProto, scanBytes);
        instance = ProtobufUtil.toScan(scanProto.build());
    } else {
        // Writable or Serializable
        Class instanceClass = null;
        int b = (byte) WritableUtils.readVInt(in);
        if (b == NOT_ENCODED) {
            String className = Text.readString(in);
            if ("org.apache.hadoop.hbase.regionserver.wal.HLog$Entry".equals(className)) {
                className = Entry.class.getName();
            }
            try {
                instanceClass = getClassByName(conf, className);
            } catch (ClassNotFoundException e) {
                LOG.error("Can't find class " + className, e);
                throw new IOException("Can't find class " + className, e);
            }
        } else {
            instanceClass = CODE_TO_CLASS.get(b);
        }
        if (Writable.class.isAssignableFrom(instanceClass)) {
            Writable writable = WritableFactories.newInstance(instanceClass, conf);
            try {
                writable.readFields(in);
            } catch (Exception e) {
                LOG.error("Error in readFields", e);
                throw new IOException("Error in readFields", e);
            }
            instance = writable;
            if (instanceClass == NullInstance.class) {
                // null
                declaredClass = ((NullInstance) instance).declaredClass;
                instance = null;
            }
        } else {
            int length = in.readInt();
            byte[] objectBytes = new byte[length];
            in.readFully(objectBytes);
            ByteArrayInputStream bis = null;
            ObjectInputStream ois = null;
            try {
                bis = new ByteArrayInputStream(objectBytes);
                ois = new ObjectInputStream(bis);
                instance = ois.readObject();
            } catch (ClassNotFoundException e) {
                LOG.error("Class not found when attempting to deserialize object", e);
                throw new IOException("Class not found when attempting to " + "deserialize object", e);
            } finally {
                if (bis != null)
                    bis.close();
                if (ois != null)
                    ois.close();
            }
        }
    }
    if (objectWritable != null) {
        // store values
        objectWritable.declaredClass = declaredClass;
        objectWritable.instance = instance;
    }
    return instance;
}
Also used : ArrayList(java.util.ArrayList) Writable(org.apache.hadoop.io.Writable) MapWritable(org.apache.hadoop.io.MapWritable) ObjectWritable(org.apache.hadoop.io.ObjectWritable) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) List(java.util.List) ArrayList(java.util.ArrayList) Scan(org.apache.hadoop.hbase.client.Scan) ClientProtos(org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos) ObjectInputStream(java.io.ObjectInputStream)

Example 3 with ObjectInputStream

use of java.io.ObjectInputStream in project lucida by claritylab.

the class DeserializationFilter method apply.

/**
	 * Filters an array of <code>Result</code> objects.
	 * 
	 * @param results results to filter
	 * @return filtered results
	 */
public Result[] apply(Result[] results) {
    // any input file set?
    if (serialFiles == null || serialFiles.length == 0)
        return results;
    // keep old results
    ArrayList<Result> resultsL = new ArrayList<Result>();
    for (Result result : results) resultsL.add(result);
    // deserialize and add results
    for (File serialFile : serialFiles) {
        // input file exists?
        if (!serialFile.exists())
            continue;
        try {
            FileInputStream fis = new FileInputStream(serialFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            try {
                while (true) {
                    Object o = ois.readObject();
                    if (o instanceof Result) {
                        Result result = (Result) o;
                        resultsL.add(result);
                    }
                }
            } catch (EOFException e) {
            /* end of file reached */
            }
            ois.close();
        } catch (Exception e) {
            MsgPrinter.printErrorMsg("Could not read serialized results:");
            MsgPrinter.printErrorMsg(e.toString());
            System.exit(1);
        }
    }
    return resultsL.toArray(new Result[resultsL.size()]);
}
Also used : ArrayList(java.util.ArrayList) EOFException(java.io.EOFException) File(java.io.File) FileInputStream(java.io.FileInputStream) EOFException(java.io.EOFException) Result(info.ephyra.search.Result) ObjectInputStream(java.io.ObjectInputStream)

Example 4 with ObjectInputStream

use of java.io.ObjectInputStream in project cas by apereo.

the class SerializationUtils method deserialize.

/**
     * Deserialize an object.
     *
     * @param <T>         the type parameter
     * @param inputStream The stream to be deserialized
     * @return the object
     * @since 5.0.0
     */
public static <T> T deserialize(final InputStream inputStream) {
    ObjectInputStream in = null;
    try {
        in = new ObjectInputStream(inputStream);
        final T obj = (T) in.readObject();
        return obj;
    } catch (final ClassNotFoundException | IOException e) {
        throw Throwables.propagate(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
                throw Throwables.propagate(e);
            }
        }
    }
}
Also used : IOException(java.io.IOException) ObjectInputStream(java.io.ObjectInputStream)

Example 5 with ObjectInputStream

use of java.io.ObjectInputStream in project hibernate-orm by hibernate.

the class TypedValueSerializationTest method testTypedValueSerialization.

@Test
@TestForIssue(jiraKey = "HHH-9024")
public void testTypedValueSerialization() throws Exception {
    final Type mockType = mock(Type.class);
    final String value = "foo";
    final TypedValue typedValue = new TypedValue(mockType, value);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(typedValue);
    final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
    final TypedValue typedValueClone = (TypedValue) ois.readObject();
    assertEquals(typedValue.hashCode(), typedValueClone.hashCode());
    assertEquals(typedValue.toString(), typedValueClone.toString());
    assertEquals(typedValue.getValue(), typedValueClone.getValue());
}
Also used : Type(org.hibernate.type.Type) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) TypedValue(org.hibernate.engine.spi.TypedValue) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test) TestForIssue(org.hibernate.testing.TestForIssue)

Aggregations

ObjectInputStream (java.io.ObjectInputStream)2146 ByteArrayInputStream (java.io.ByteArrayInputStream)1394 ObjectOutputStream (java.io.ObjectOutputStream)966 ByteArrayOutputStream (java.io.ByteArrayOutputStream)803 IOException (java.io.IOException)744 Test (org.junit.Test)456 FileInputStream (java.io.FileInputStream)339 File (java.io.File)197 InputStream (java.io.InputStream)156 ArrayList (java.util.ArrayList)90 BufferedInputStream (java.io.BufferedInputStream)84 Serializable (java.io.Serializable)66 FileNotFoundException (java.io.FileNotFoundException)64 FileOutputStream (java.io.FileOutputStream)63 HashMap (java.util.HashMap)63 Socket (java.net.Socket)49 Map (java.util.Map)47 ObjectInput (java.io.ObjectInput)46 GZIPInputStream (java.util.zip.GZIPInputStream)44 List (java.util.List)37