List of usage examples for java.io ObjectStreamClass getName
public String getName()
From source file:com.centurylink.mdw.common.translator.impl.JavaObjectTranslator.java
public Object realToObject(String str) throws TranslationException { ObjectInputStream ois = null; try {//from www . j a v a 2 s . c o m byte[] decoded = decodeBase64(str); ByteArrayInputStream bais = new ByteArrayInputStream(decoded); ois = new ObjectInputStream(bais); try { return ois.readObject(); } catch (ClassNotFoundException ex) { ois.close(); bais = new ByteArrayInputStream(decoded); ois = new ObjectInputStream(bais) { @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { try { return CompiledJavaCache.getResourceClass(desc.getName(), getClass().getClassLoader(), getPackage()); } catch (ClassNotFoundException ex) { if (getPackage() != null && getPackage().getCloudClassLoader() != null) return getPackage().getCloudClassLoader().loadClass(desc.getName()); else throw ex; } catch (MdwJavaException ex) { throw new ClassNotFoundException(desc.getName(), ex); } } }; return ois.readObject(); } } catch (Throwable t) { // including NoClassDefFoundError throw new TranslationException(t.getMessage(), t); } finally { if (ois != null) { try { ois.close(); } catch (IOException ex) { } } } }
From source file:com.lts.core.commons.io.SerialKiller.java
@Override protected Class<?> resolveClass(ObjectStreamClass serialInput) throws IOException, ClassNotFoundException { //Enforce SerialKiller's blacklist for (String blackRegExp : blacklist) { Pattern blackPattern = Pattern.compile(blackRegExp); Matcher blackMatcher = blackPattern.matcher(serialInput.getName()); if (blackMatcher.find()) { throw new InvalidClassException("[!] Blocked by SerialKiller's blacklist '" + blackRegExp + "'. Match found for '" + serialInput.getName() + "'"); }/*from w w w . j av a 2 s .c o m*/ } //Enforce SerialKiller's whitelist boolean safeClass = false; for (String whiteRegExp : whitelist) { Pattern whitePattern = Pattern.compile(whiteRegExp); Matcher whiteMatcher = whitePattern.matcher(serialInput.getName()); if (whiteMatcher.find()) { safeClass = true; } } if (!safeClass) { throw new InvalidClassException( "[!] Blocked by SerialKiller's whitelist. No match found for '" + serialInput.getName() + "'"); } return super.resolveClass(serialInput); }
From source file:jade.content.onto.SerializableOntology.java
/** *///from www . ja v a 2s . c o m protected Object toObject(AbsObject abs, String lcType, Ontology globalOnto) throws UnknownSchemaException, UngroundedException, OntologyException { if (SERIALIZABLE.equals(abs.getTypeName())) { try { AbsPrimitive absValue = (AbsPrimitive) abs.getAbsObject(SERIALIZABLE_VALUE); String stringValue = absValue.getString(); byte[] value = Base64.decodeBase64(stringValue.getBytes("US-ASCII")); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(value)) { protected Class resolveClass(ObjectStreamClass v) throws IOException, ClassNotFoundException { if (myClassLoader != null) { // FIXME: Manage primitive class fields. Refactor with AgentMobilityService return Class.forName(v.getName(), true, myClassLoader); } else { return super.resolveClass(v); } } }; return in.readObject(); } catch (Throwable t) { throw new OntologyException("Error in object deserialization.", t); } } else { throw new OntologyException("Abs-object " + abs + " is not serializable"); } }
From source file:com.datatorrent.stram.FSRecoveryHandler.java
@Override public Object restore() throws IOException { FileContext fc = FileContext.getFileContext(fs.getUri()); // recover from wherever it was left if (fc.util().exists(snapshotBackupPath)) { LOG.warn("Incomplete checkpoint, reverting to {}", snapshotBackupPath); fc.rename(snapshotBackupPath, snapshotPath, Rename.OVERWRITE); // combine logs (w/o append, create new file) Path tmpLogPath = new Path(basedir, "log.combined"); FSDataOutputStream fsOut = fc.create(tmpLogPath, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE)); try {/*from ww w . java 2s.c o m*/ FSDataInputStream fsIn = fc.open(logBackupPath); try { IOUtils.copy(fsIn, fsOut); } finally { fsIn.close(); } fsIn = fc.open(logPath); try { IOUtils.copy(fsIn, fsOut); } finally { fsIn.close(); } } finally { fsOut.close(); } fc.rename(tmpLogPath, logPath, Rename.OVERWRITE); fc.delete(logBackupPath, false); } else { // we have log backup, but no checkpoint backup // failure between log rotation and writing checkpoint if (fc.util().exists(logBackupPath)) { LOG.warn("Found {}, did checkpointing fail?", logBackupPath); fc.rename(logBackupPath, logPath, Rename.OVERWRITE); } } if (!fc.util().exists(snapshotPath)) { LOG.debug("No existing checkpoint."); return null; } LOG.debug("Reading checkpoint {}", snapshotPath); InputStream is = fc.open(snapshotPath); // indeterministic class loading behavior // http://stackoverflow.com/questions/9110677/readresolve-not-working-an-instance-of-guavas-serializedform-appears final ClassLoader loader = Thread.currentThread().getContextClassLoader(); ObjectInputStream ois = new ObjectInputStream(is) { @Override protected Class<?> resolveClass(ObjectStreamClass objectStreamClass) throws IOException, ClassNotFoundException { return Class.forName(objectStreamClass.getName(), true, loader); } }; //ObjectInputStream ois = new ObjectInputStream(is); try { return ois.readObject(); } catch (ClassNotFoundException cnfe) { throw new IOException("Failed to read checkpointed state", cnfe); } finally { ois.close(); } }
From source file:com.adito.boot.AbstractPropertyClass.java
public void restore() throws IOException { log.info("Restoring property class " + getName()); if (store == null) { throw new IllegalStateException("Nothing stored for " + getName()); }// w w w.j av a 2 s.co m ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(store.toByteArray())) { protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { try { return Class.forName(desc.getName(), false, AbstractPropertyClass.this.getClass().getClassLoader()); } catch (ClassNotFoundException ex) { return super.resolveClass(desc); } } }; try { definitions = (Map<String, PropertyDefinition>) ois.readObject(); categories = (List<PropertyDefinitionCategory>) ois.readObject(); categoryMap = (Map<String, PropertyDefinitionCategory>) ois.readObject(); store = null; // PropertyClass member variable is transient so we need to reinitialise for (PropertyDefinition def : definitions.values()) def.init(this); for (PropertyDefinitionCategory cat : categories) cat.setPropertyClass(this); } catch (ClassNotFoundException cnfe) { throw new IOException("Deserialisation failed. " + cnfe.getMessage()); } finally { ois.close(); } }
From source file:ws.salient.aws.dynamodb.DynamoDBStore.java
public Session get(Command command, KnowledgeRepository repository, Properties properties, Injector parentInjector, Sessions sessions, QuerySpec sessionQuery) { String sessionId = command.getSessionId(); String accountId = command.getAccountId(); SecretKeySpec secretKey;/*www. j ava 2s . c o m*/ ByteBuffer encryptedKey; Session session = new Session(sessionId); Page<Item, QueryOutcome> page = dynamodb.getTable("SalientSession").query(sessionQuery).firstPage(); if (page != null && page.size() > 0) { try { Item result = page.iterator().next(); encryptedKey = ByteBuffer.wrap((byte[]) result.getMap("secretKey").get("encrypted")); if (encryptedKey != null) { DecryptResult decrypt = kms.decrypt(new DecryptRequest() .addEncryptionContextEntry("accountId", accountId) .addEncryptionContextEntry("sessionId", sessionId).withCiphertextBlob(encryptedKey)); byte[] key = decrypt.getPlaintext().array(); secretKey = new SecretKeySpec(key, (String) result.getMap("secretKey").get("algorithm")); } else { secretKey = null; } result = decrypt(result, secretKey, "properties", "session"); properties = json.readValue(result.getBinary("properties"), Properties.class); String knowledgeBaseId = result.getString("knowledgeBaseId"); KnowledgeBase knowledgeBase = repository.getKnowledgeBase(knowledgeBaseId); String timestamp = result.getString("timestamp"); session.init(knowledgeBase, properties, parentInjector, Instant.parse(timestamp), result.getBinary("session"), sessions); int processCount = session.getProcessCount(); List<Item> eventItems = new LinkedList(); ItemCollection<QueryOutcome> query = dynamodb.getTable("SalientSessionEvent") .query(new QuerySpec().withConsistentRead(true).withHashKey("sessionId", sessionId) .withRangeKeyCondition(new RangeKeyCondition("timestamp").gt(timestamp))); query.pages().forEach((eventPage) -> { eventPage.forEach((eventItem) -> { eventItems.add(eventItem); }); }); List<Command> commands = new LinkedList(); eventItems.forEach((eventItem) -> { try { eventItem = decrypt(eventItem, secretKey, "command"); byte[] value = eventItem.getBinary("command"); ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(value)) { protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { return session.getKnowledgeBase().getContainer().getClassLoader() .loadClass(desc.getName()); } }; Command event = (Command) objectIn.readObject(); if (event instanceof WorkItem) { session.getWorkItemHandlers().forEach((handler) -> { handler.getCompletedWorkItemIds().add(((WorkItem) event).getWorkItemId()); }); } commands.add(event); } catch (ClassNotFoundException | IOException ex) { throw new RuntimeException(ex); } }); commands.forEach((event) -> { session.accept(event); }); session.getWorkItemHandlers().forEach((handler) -> { handler.getCompletedWorkItemIds().clear(); }); } catch (IOException ex) { throw new RuntimeException(ex); } } else { GenerateDataKeyResult dataKey = generateEncryptionKey(accountId, sessionId); byte[] key = dataKey.getPlaintext().array(); secretKey = new SecretKeySpec(key, "AES"); encryptedKey = dataKey.getCiphertextBlob(); KnowledgeBase knowledgeBase = repository.getKnowledgeBase(command.getKnowledgeBaseId()); session.init(knowledgeBase, properties, parentInjector, command.getTimestamp(), sessions); } session.setEncryptedKey(encryptedKey); session.setSecretKey(secretKey); return session; }
From source file:com.offbynull.coroutines.instrumenter.InstrumenterTest.java
@Test public void mustProperlySuspendWithSerialization() throws Exception { try (URLClassLoader classLoader = loadClassesInZipResourceAndInstrument( SERIALIZABLE_INVOKE_TEST + ".zip")) { Class<Coroutine> cls = (Class<Coroutine>) classLoader.loadClass(SERIALIZABLE_INVOKE_TEST); Coroutine coroutine = ConstructorUtils.invokeConstructor(cls, new StringBuilder()); // Create and run original for a few cycles CoroutineRunner originalRunner = new CoroutineRunner(coroutine); Assert.assertTrue(originalRunner.execute()); Assert.assertTrue(originalRunner.execute()); Assert.assertTrue(originalRunner.execute()); Assert.assertTrue(originalRunner.execute()); Assert.assertTrue(originalRunner.execute()); Assert.assertTrue(originalRunner.execute()); // Serialize ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(originalRunner); oos.close();// w w w .j av a 2 s . c om baos.close(); byte[] serializedCoroutine = baos.toByteArray(); // Deserialize ByteArrayInputStream bais = new ByteArrayInputStream(serializedCoroutine); ObjectInputStream ois = new ObjectInputStream(bais) { @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { try { return super.resolveClass(desc); } catch (ClassNotFoundException cnfe) { return classLoader.loadClass(desc.getName()); } } }; CoroutineRunner deserializedRunner = (CoroutineRunner) ois.readObject(); // Continue running deserialized Assert.assertTrue(deserializedRunner.execute()); Assert.assertTrue(deserializedRunner.execute()); Assert.assertTrue(deserializedRunner.execute()); Assert.assertTrue(deserializedRunner.execute()); Assert.assertFalse(deserializedRunner.execute()); // coroutine finished executing here Assert.assertTrue(deserializedRunner.execute()); Assert.assertTrue(deserializedRunner.execute()); Assert.assertTrue(deserializedRunner.execute()); // Assert everything continued fine with deserialized version Object deserializedCoroutine = FieldUtils.readField(deserializedRunner, "coroutine", true); StringBuilder deserializedBuilder = (StringBuilder) FieldUtils.readField(deserializedCoroutine, "builder", true); Assert.assertEquals("started\n" + "0\n" + "1\n" + "2\n" + "3\n" + "4\n" + "5\n" + "6\n" + "7\n" + "8\n" + "9\n" + "started\n" + "0\n" + "1\n" + "2\n", deserializedBuilder.toString()); } }
From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java
/** * Serializes the given class to the getCurrentDirectory() directory. The * static serializedInstance() method of clazz will be called to get an * examplar of clazz. This examplar will then be serialized out to a file * stored in getCurrentDirectory()./* www . j a va 2 s . co m*/ * * @param clazz the class to serialize. * @throws RuntimeException if clazz cannot be serialized. This exception * has an informative message and wraps the * originally thrown exception as root cause. * @see #getCurrentDirectory() */ private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException { File current = new File(getCurrentDirectory()); if (!current.exists() || !current.isDirectory()) { throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. " + "\nThis is where the serialized classes should be. " + "Please run serializeCurrentDirectory() first."); } try { Field field = clazz.getDeclaredField("serialVersionUID"); int modifiers = field.getModifiers(); boolean _static = Modifier.isStatic(modifiers); boolean _final = Modifier.isFinal(modifiers); field.setAccessible(true); if (!_static || !_final || !(23L == field.getLong(null))) { throw new RuntimeException( "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L"); } int numFields = getNumNonSerialVersionUIDFields(clazz); if (numFields > 0) { Method method = clazz.getMethod("serializableInstance"); Object object = method.invoke(null); File file = new File(current, clazz.getName() + ".ser"); boolean created = file.createNewFile(); FileOutputStream out = new FileOutputStream(file); ObjectOutputStream objOut = new ObjectOutputStream(out); objOut.writeObject(object); out.close(); } // Make entry in list of class fields. ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz); String className = objectStreamClass.getName(); ObjectStreamField[] fields = objectStreamClass.getFields(); @SuppressWarnings("Convert2Diamond") List<String> fieldList = new ArrayList<>(); for (ObjectStreamField objectStreamField : fields) { String fieldName = objectStreamField.getName(); fieldList.add(fieldName); } classFields.put(className, fieldList); } catch (NoSuchFieldException e) { throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz + ". Please make one and set it " + "to 23L.")); } catch (NoSuchMethodException e) { throw new RuntimeException( "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e); } catch (IllegalAccessException e) { throw new RuntimeException( "The method serializableInstance() of " + "class " + clazz + " is not public.", e); } catch (InvocationTargetException e) { throw new RuntimeException( "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e); } catch (IOException e) { throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory() + " when trying to serialize " + clazz + ".", e); } }
From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java
/** * Serializes the given class to the getCurrentDirectory() directory. The * static serializedInstance() method of clazz will be called to get an * examplar of clazz. This examplar will then be serialized out to a file * stored in getCurrentDirectory()./*from w w w. j ava2 s. c o m*/ * * @param clazz the class to serialize. * @throws RuntimeException if clazz cannot be serialized. This exception * has an informative message and wraps the * originally thrown exception as root cause. * @see #getCurrentDirectory() */ private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException { File current = new File(getCurrentDirectory()); if (!current.exists() || !current.isDirectory()) { throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. " + "\nThis is where the serialized classes should be. " + "Please run serializeCurrentDirectory() first."); } try { Field field = clazz.getDeclaredField("serialVersionUID"); int modifiers = field.getModifiers(); boolean _static = Modifier.isStatic(modifiers); boolean _final = Modifier.isFinal(modifiers); field.setAccessible(true); if (!_static || !_final || !(23L == field.getLong(null))) { throw new RuntimeException( "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L"); } int numFields = getNumNonSerialVersionUIDFields(clazz); if (numFields > 0) { Method method = clazz.getMethod("serializableInstance", new Class[0]); Object object = method.invoke(null, new Object[0]); File file = new File(current, clazz.getName() + ".ser"); file.createNewFile(); FileOutputStream out = new FileOutputStream(file); ObjectOutputStream objOut = new ObjectOutputStream(out); objOut.writeObject(object); out.close(); } // Make entry in list of class fields. ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz); String className = objectStreamClass.getName(); ObjectStreamField[] fields = objectStreamClass.getFields(); List<String> fieldList = new ArrayList<String>(); for (ObjectStreamField objectStreamField : fields) { String fieldName = objectStreamField.getName(); fieldList.add(fieldName); } classFields.put(className, fieldList); } catch (NoSuchFieldException e) { throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz + ". Please make one and set it " + "to 23L.")); } catch (NoSuchMethodException e) { throw new RuntimeException( "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e); } catch (IllegalAccessException e) { throw new RuntimeException( "The method serializableInstance() of " + "class " + clazz + " is not public.", e); } catch (InvocationTargetException e) { throw new RuntimeException( "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e); } catch (IOException e) { throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory() + " when trying to serialize " + clazz + ".", e); } }
From source file:net.sf.ehcache.store.DiskStore.java
private Element loadElementFromDiskElement(DiskElement diskElement) throws IOException, ClassNotFoundException { Element element;// ww w . ja v a 2 s .c o m // Load the element randomAccessFile.seek(diskElement.position); final byte[] buffer = new byte[diskElement.payloadSize]; randomAccessFile.readFully(buffer); final ByteArrayInputStream instr = new ByteArrayInputStream(buffer); final ObjectInputStream objstr = new ObjectInputStream(instr) { /** * Overridden because of: * Bug 1324221 ehcache DiskStore has issues when used in Tomcat */ protected Class resolveClass(ObjectStreamClass clazz) throws ClassNotFoundException, IOException { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); return Class.forName(clazz.getName(), false, classLoader); } catch (ClassNotFoundException e) { // Use the default as a fallback because of // bug 1517565 - DiskStore loadElementFromDiskElement return super.resolveClass(clazz); } } }; element = (Element) objstr.readObject(); objstr.close(); return element; }