Java Examples for java.io.Serializable

The following java examples will help you to understand the usage of java.io.Serializable. These source code samples are taken from different open source projects.

Example 1
Project: zen-project-master  File: ReflectionHelperTest.java View source code
@Test
public void test() {
    ReflectionHelper reflect = new ReflectionHelper();
    assertTrue(reflect.safeInstanceOf(new BitSet(), "java.util.BitSet"));
    assertTrue(reflect.safeInstanceOf(new BitSet(), "java.io.Serializable"));
    assertFalse(reflect.safeInstanceOf(new Object(), "java.io.Serializable"));
    assertFalse(reflect.safeInstanceOf(new Object(), "java.io.FunnyName"));
    try {
        reflect.safeInstanceOf(null, "java.io.Serializable");
        fail();
    } catch (NullPointerException e) {
    }
}
Example 2
Project: deadcode4j-master  File: An_InterfacesAnalyzer.java View source code
@Test
public void reportsClassImplementingSubInterfaceAsBeingUsed() {
    objectUnderTest = new InterfacesAnalyzer("junit", "java.io.Serializable") {
    };
    analyzeFile("ClassImplementingExternalizable.class");
    analyzeFile("SubClassOfClassImplementingExternalizable.class");
    assertThatDependenciesAreReported("ClassImplementingExternalizable", "SubClassOfClassImplementingExternalizable");
}
Example 3
Project: ArchUnit-master  File: HasParameterTypesTest.java View source code
@Test
public void predicate_on_parameters_by_Class() {
    HasParameterTypes hasParameterTypes = newHasParameterTypes(String.class, Serializable.class);
    assertThat(parameterTypes(String.class, Serializable.class).apply(hasParameterTypes)).as("predicate matches").isTrue();
    assertThat(parameterTypes(String.class).apply(hasParameterTypes)).as("predicate matches").isFalse();
    assertThat(parameterTypes(Serializable.class).apply(hasParameterTypes)).as("predicate matches").isFalse();
    assertThat(parameterTypes(Object.class).apply(hasParameterTypes)).as("predicate matches").isFalse();
    assertThat(parameterTypes(String.class, Serializable.class).getDescription()).isEqualTo("parameter types [java.lang.String, java.io.Serializable]");
}
Example 4
Project: jacorb-master  File: ValueHandler.java View source code
public static void writeValue(org.omg.CORBA.portable.OutputStream out, java.io.Serializable value) {
    byte version = ValueHandler.getMaximumStreamFormatVersion(out);
    javax.rmi.CORBA.ValueHandler vh = javax.rmi.CORBA.Util.createValueHandler();
    if (version == ValueHandler.STREAM_FORMAT_VERSION_1) {
        vh.writeValue(out, value);
    } else if (version == ValueHandler.STREAM_FORMAT_VERSION_2) {
        ((ValueHandlerMultiFormat) vh).writeValue(out, value, ValueHandler.STREAM_FORMAT_VERSION_2);
    } else {
        throw new MARSHAL("Unsupported stream format version.");
    }
}
Example 5
Project: Wicket-Page-Test-master  File: SerializableProxyFactoryTest.java View source code
public void testSerialzable() {
    SerializableProxyFactory factory = new SerializableProxyFactory();
    Foo original = new Foo() {

        public void m1() {
            called = true;
        }
    };
    Foo proxy = factory.createProxy(Foo.class, original);
    proxy.m1();
    assert called;
    assert proxy instanceof Serializable;
}
Example 6
Project: groovy-eclipse-master  File: SerialVersionUIDTests.java View source code
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=101476
public void test001() {
    this.runConformTest(new String[] { "X.java", "import java.io.Serializable;\n" + "\n" + "public class X implements Serializable {\n" + "	private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException {}\n" + "	private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException {}\n" + "}" }, "");
}
Example 7
Project: savara-core-master  File: InMemorySessionStoreTest.java View source code
@Test
public void testRemoveSession() {
    InMemorySessionStore store = new InMemorySessionStore();
    DefaultSession s = new DefaultSession();
    try {
        ProtocolId pid = new ProtocolId("p", "r");
        ConversationId id = new ConversationId("1");
        if (store.create(pid, id, s) == null) {
            fail("No context created");
        }
        java.io.Serializable c1 = store.find(pid, id);
        if (c1 == null) {
            fail("Should not be null");
        }
        store.remove(pid, id);
        if (store.find(pid, id) != null) {
            fail("Should not find the session");
        }
    } catch (Exception e) {
        fail("Not expecting: " + e);
    }
}
Example 8
Project: android-lite-http-master  File: SerializableBody.java View source code
public static byte[] getBytes(Serializable ser) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        oos = new ObjectOutputStream(baos);
        oos.writeObject(ser);
        return baos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 9
Project: brigen-base-master  File: MailInfo.java View source code
// for serialize
private void writeObject(ObjectOutputStream stream) throws IOException {
    if ((tos != null) && !(tos instanceof Serializable)) {
        // to java.io.Serializable
        tos = new HashSet<>(tos);
    }
    if ((ccs != null) && !(ccs instanceof Serializable)) {
        // to java.io.Serializable
        ccs = new HashSet<>(ccs);
    }
    if ((bccs != null) && !(bccs instanceof Serializable)) {
        // to java.io.Serializable
        bccs = new HashSet<>(bccs);
    }
    if ((replyTos != null) && !(replyTos instanceof Serializable)) {
        // to java.io.Serializable
        replyTos = new HashSet<>(replyTos);
    }
    stream.defaultWriteObject();
}
Example 10
Project: client-control-master  File: TestBackendMessage.java View source code
@Test
public void shouldBeSerializable() throws Exception {
    AllMessage<String> allMessage = new AllMessage<String>("type", "body");
    BackendMessage backendMessage = new BackendMessage(allMessage);
    AllMessage<?> actual = backendMessage.getMessage();
    assertNotNull(actual);
    assertNotSame(allMessage, actual);
    assertEquals(allMessage.getType(), actual.getType());
    assertEquals(allMessage.getBody(), actual.getBody());
    assertTrue(backendMessage instanceof Serializable);
}
Example 11
Project: ComplexEventProcessingPlatform-master  File: ConditionParser.java View source code
/**
	 * Parses attribute-value pairs of events from a string.
	 * Syntax of the string must be: attribute1=attributevalue1[;attribute2=attributevalue2] 
	 */
public static SushiMapTree<String, Serializable> extractEventAttributes(String conditionString) {
    SushiMapTree<String, Serializable> eventAttributes = new SushiMapTree<String, Serializable>();
    String[] attributes = conditionString.split(";");
    for (String attribute : attributes) {
        String[] attributePair = attribute.split("=");
        if (attributePair.length == 2) {
            eventAttributes.put(attributePair[0], attributePair[1]);
        }
    }
    return eventAttributes;
}
Example 12
Project: erma-master  File: ArrayDecomposerTest.java View source code
/**
   * see ArrayDecomposer#decompose(Object, IdentityHashMap)
   */
public void testDecompose() {
    Object[] original = new Object[2];
    original[0] = "abc";
    original[1] = new Exception();
    Object[] decomposed = (Object[]) _decomposer.decompose(original, new IdentityHashMap<Object, Serializable>());
    assertEquals(original.length, decomposed.length);
    List<Object> decomposedObjects = _delegate.getDecomposedObjects();
    assertTrue(decomposedObjects.containsAll(Arrays.asList(original)));
}
Example 13
Project: gdx-proto-master  File: ObjectSize.java View source code
public static long getObjectSize(Serializable ser) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(ser);
        oos.close();
    } catch (Exception e) {
        throw new GdxRuntimeException(e.toString());
    }
    return baos.size();
}
Example 14
Project: gluster-ovirt-poc-master  File: ObjectStreamSerializer.java View source code
@Override
public Object serialize(Serializable payload) throws SerializationExeption {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(baos);
        objectOutputStream.writeObject(payload);
        return baos.toByteArray();
    } catch (IOException e) {
        throw new SerializationExeption(e);
    }
}
Example 15
Project: nevado-master  File: AdministeredObjectsTest.java View source code
@Test
public void testsImplements() {
    Assert.assertTrue(Serializable.class.isAssignableFrom(NevadoDestination.class));
    Assert.assertTrue(Referenceable.class.isAssignableFrom(NevadoDestination.class));
    Assert.assertTrue(Serializable.class.isAssignableFrom(NevadoConnectionFactory.class));
    Assert.assertTrue(Referenceable.class.isAssignableFrom(NevadoConnectionFactory.class));
}
Example 16
Project: quickml-master  File: ProbabilityInjectingEnricherTest.java View source code
@Test
public void simpleTest() {
    final Map<String, Map<Serializable, Double>> valueProbsByAttr = Maps.newHashMap();
    Map<Serializable, Double> valueProbs = Maps.newHashMap();
    valueProbs.put(5, 0.2);
    valueProbsByAttr.put("testkey", valueProbs);
    ProbabilityInjectingEnricher probabilityInjectingEnricher = new ProbabilityInjectingEnricher(valueProbsByAttr);
    AttributesMap inputAttributes = AttributesMap.newHashMap();
    inputAttributes.put("testkey", 5);
    final AttributesMap outputAttributes = probabilityInjectingEnricher.apply(inputAttributes);
    Assert.assertEquals("The pre-existing attribute is still there", 5, outputAttributes.get("testkey"));
    Assert.assertEquals("The newly added attribute is there", 0.2, outputAttributes.get("testkey-PROB"));
}
Example 17
Project: error-prone-master  File: UIntersectionTypeTest.java View source code
@Test
public void equality() {
    new EqualsTester().addEqualityGroup(UIntersectionType.create(UClassIdent.create("java.lang.CharSequence"), UClassIdent.create("java.io.Serializable"))).addEqualityGroup(UIntersectionType.create(UClassIdent.create("java.lang.Number"), UClassIdent.create("java.io.Serializable"))).testEquals();
}
Example 18
Project: intellij-community-master  File: PostfixTemplateTestCase.java View source code
@Override
protected void setUp() throws Exception {
    super.setUp();
    myFixture.addClass("package java.lang;\n" + "public final class Boolean implements java.io.Serializable, Comparable<Boolean> {}");
    myFixture.addClass("package java.lang;\n" + "public final class Byte implements java.io.Serializable, Comparable<Byte> {}");
    myFixture.addClass("package java.lang;\n" + "public interface Iterable<T> {}");
    myFixture.addClass("package java.util;\n" + "public class ArrayList<E> extends AbstractList<E>\n" + "        implements List<E>, Iterable<E>, RandomAccess, Cloneable, java.io.Serializable {}");
    myFixture.addClass("package java.lang;\n" + "public interface AutoCloseable {}");
}
Example 19
Project: spring-data-redis-master  File: ReferenceResolverImpl.java View source code
/*
	 * (non-Javadoc)
	 * @see org.springframework.data.redis.core.convert.ReferenceResolver#resolveReference(java.io.Serializable, java.io.Serializable, java.lang.Class)
	 */
@Override
public Map<byte[], byte[]> resolveReference(Serializable id, String keyspace) {
    final byte[] key = converter.convert(keyspace + ":" + id);
    return redisOps.execute(new RedisCallback<Map<byte[], byte[]>>() {

        @Override
        public Map<byte[], byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
            return connection.hGetAll(key);
        }
    });
}
Example 20
Project: VUE-master  File: Part.java View source code
public org.osid.repository.Part createPart(org.osid.shared.Id partStructureId, java.io.Serializable value) throws org.osid.repository.RepositoryException {
    if ((partStructureId == null) || (value == null)) {
        throw new org.osid.repository.RepositoryException(org.osid.repository.RepositoryException.NULL_ARGUMENT);
    }
    org.osid.repository.PartStructureIterator psi = recordStructure.getPartStructures();
    while (psi.hasNextPartStructure()) {
        org.osid.repository.PartStructure partStructure = psi.nextPartStructure();
        try {
            if (partStructureId.isEqual(partStructure.getId())) {
                org.osid.repository.Part part = new Part(partStructureId, recordStructure, partStructure, value);
                partVector.addElement(part);
                this.partStructure = partStructure;
                return part;
            }
        } catch (org.osid.OsidException oex) {
            throw new org.osid.repository.RepositoryException(org.osid.repository.RepositoryException.OPERATION_FAILED);
        }
    }
    throw new org.osid.repository.RepositoryException(org.osid.repository.RepositoryException.UNKNOWN_ID);
}
Example 21
Project: spring-data-aerospike-master  File: AerospikeKeyValueAdapter.java View source code
/* 
	 * (non-Javadoc)
	 * @see org.springframework.data.keyvalue.core.KeyValueAdapter#delete(java.io.Serializable, java.io.Serializable)
	 */
@Override
public Object delete(Serializable id, Serializable keyspace) {
    Key key = new Key(namespace, keyspace.toString(), id.toString());
    Object object = get(id, keyspace);
    if (object != null) {
        WritePolicy wp = new WritePolicy();
        wp.recordExistsAction = RecordExistsAction.UPDATE_ONLY;
        client.delete(wp, key);
    }
    return object;
}
Example 22
Project: dubbo-master  File: AbstractSerializationPersionFailTest.java View source code
@Test
public void test_Person() throws Exception {
    try {
        ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
        objectOutput.writeObject(new Person());
        fail();
    } catch (NotSerializableException expected) {
    } catch (IllegalStateException expected) {
        assertThat(expected.getMessage(), containsString("Serialized class com.alibaba.dubbo.common.model.Person must implement java.io.Serializable"));
    }
}
Example 23
Project: Empower-master  File: AbstractSerializationPersionFailTest.java View source code
@Test
public void test_Person() throws Exception {
    try {
        ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream);
        objectOutput.writeObject(new Person());
        fail();
    } catch (NotSerializableException expected) {
    } catch (IllegalStateException expected) {
        assertThat(expected.getMessage(), containsString("Serialized class com.alibaba.dubbo.common.model.Person must implement java.io.Serializable"));
    }
}
Example 24
Project: rtgov-master  File: EventList.java View source code
/**
     * This method resolves the contained list.
     * 
     * @param cl The classloader
     */
@SuppressWarnings("unchecked")
protected void resolve(final java.lang.ClassLoader cl) {
    try {
        java.io.ByteArrayInputStream bais = new java.io.ByteArrayInputStream(_serializedList);
        java.io.ObjectInputStream ois = new java.io.ObjectInputStream(bais) {

            protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                return (Class.forName(desc.getName(), false, cl));
            }
        };
        _list = (java.util.List<? extends Serializable>) ois.readObject();
        if (LOG.isLoggable(Level.FINEST)) {
            LOG.finest("Deserialized event list: " + _list);
        }
        ois.close();
        bais.close();
    } catch (Throwable e) {
        String mesg = java.util.PropertyResourceBundle.getBundle("epn-core.Messages").getString("EPN-CORE-4");
        LOG.severe(mesg);
        throw new IllegalArgumentException(mesg, e);
    }
}
Example 25
Project: eclipse.jdt.core-master  File: SerialVersionUIDTests.java View source code
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=101476
public void test001() {
    this.runConformTest(new String[] { "X.java", "import java.io.Serializable;\n" + "\n" + "public class X implements Serializable {\n" + "	private void readObject(java.io.ObjectInputStream stream) throws java.io.IOException {}\n" + "	private void writeObject(java.io.ObjectOutputStream stream) throws java.io.IOException {}\n" + "}" }, "");
}
Example 26
Project: q-municate-android-master  File: QBImportFriendsCommand.java View source code
public static void start(Context context, List<String> friendsFacebookList, List<String> friendsContactsList) {
    Intent intent = new Intent(QBServiceConsts.IMPORT_FRIENDS_ACTION, null, context, QBService.class);
    intent.putExtra(QBServiceConsts.EXTRA_FRIENDS_FACEBOOK, (java.io.Serializable) friendsFacebookList);
    intent.putExtra(QBServiceConsts.EXTRA_FRIENDS_CONTACTS, (java.io.Serializable) friendsContactsList);
    context.startService(intent);
}
Example 27
Project: google-web-toolkit-svnmirror-master  File: SerializableTypeOracleBuilderTest.java View source code
/**
   * Test with a generic class whose type parameter is exposed only in certain
   * subclasses.
   * 
   * NOTE: This test has been disabled because it requires a better pruner in
   * STOB. See SerializableTypeOracleBuilder.pruneUnreachableTypes().
   */
public void disabledTestMaybeExposedParameter() throws UnableToCompleteException, NotFoundException {
    Set<Resource> resources = new HashSet<Resource>();
    addStandardClasses(resources);
    {
        StringBuilder code = new StringBuilder();
        code.append("import java.io.Serializable;\n");
        code.append("public abstract class List<T> implements Serializable {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("List", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class EmptyList<T> extends List<T> {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("EmptyList", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class LinkedList<T> extends List<T> {\n");
        code.append("  T head;\n");
        code.append("  LinkedList<T> next;\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("LinkedList", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class CantSerialize {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("CantSerialize", code));
    }
    TreeLogger logger = createLogger();
    TypeOracle to = TypeOracleTestingUtils.buildTypeOracle(logger, resources);
    JGenericType list = to.getType("List").isGenericType();
    JGenericType emptyList = to.getType("EmptyList").isGenericType();
    JClassType cantSerialize = to.getType("CantSerialize");
    JParameterizedType listOfCantSerialize = to.getParameterizedType(list, makeArray(cantSerialize));
    SerializableTypeOracleBuilder sob = createSerializableTypeOracleBuilder(logger, to);
    sob.addRootType(logger, listOfCantSerialize);
    SerializableTypeOracle so = sob.build(logger);
    assertFieldSerializable(so, listOfCantSerialize);
    assertSerializableTypes(so, list.getRawType(), emptyList.getRawType());
}
Example 28
Project: gwt-master  File: SerializableTypeOracleBuilderTest.java View source code
/**
   * Test with a generic class whose type parameter is exposed only in certain
   * subclasses.
   *
   * NOTE: This test has been disabled because it requires a better pruner in
   * STOB. See SerializableTypeOracleBuilder.pruneUnreachableTypes().
   */
public void disabledTestMaybeExposedParameter() throws UnableToCompleteException, NotFoundException {
    Set<Resource> resources = new HashSet<Resource>();
    addStandardClasses(resources);
    {
        StringBuilder code = new StringBuilder();
        code.append("import java.io.Serializable;\n");
        code.append("public abstract class List<T> implements Serializable {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("List", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class EmptyList<T> extends List<T> {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("EmptyList", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class LinkedList<T> extends List<T> {\n");
        code.append("  T head;\n");
        code.append("  LinkedList<T> next;\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("LinkedList", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class CantSerialize {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("CantSerialize", code));
    }
    TreeLogger logger = createLogger();
    TypeOracle to = TypeOracleTestingUtils.buildTypeOracle(logger, resources);
    JGenericType list = to.getType("List").isGenericType();
    JGenericType emptyList = to.getType("EmptyList").isGenericType();
    JClassType cantSerialize = to.getType("CantSerialize");
    JParameterizedType listOfCantSerialize = to.getParameterizedType(list, makeArray(cantSerialize));
    SerializableTypeOracleBuilder sob = createSerializableTypeOracleBuilder(logger, to);
    sob.addRootType(logger, listOfCantSerialize);
    SerializableTypeOracle so = sob.build(logger);
    assertFieldSerializable(so, listOfCantSerialize);
    assertSerializableTypes(so, list.getRawType(), emptyList.getRawType());
}
Example 29
Project: gwt-sandbox-master  File: SerializableTypeOracleBuilderTest.java View source code
/**
   * Test with a generic class whose type parameter is exposed only in certain
   * subclasses.
   * 
   * NOTE: This test has been disabled because it requires a better pruner in
   * STOB. See SerializableTypeOracleBuilder.pruneUnreachableTypes().
   */
public void disabledTestMaybeExposedParameter() throws UnableToCompleteException, NotFoundException {
    Set<Resource> resources = new HashSet<Resource>();
    addStandardClasses(resources);
    {
        StringBuilder code = new StringBuilder();
        code.append("import java.io.Serializable;\n");
        code.append("public abstract class List<T> implements Serializable {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("List", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class EmptyList<T> extends List<T> {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("EmptyList", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class LinkedList<T> extends List<T> {\n");
        code.append("  T head;\n");
        code.append("  LinkedList<T> next;\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("LinkedList", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class CantSerialize {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("CantSerialize", code));
    }
    TreeLogger logger = createLogger();
    TypeOracle to = TypeOracleTestingUtils.buildTypeOracle(logger, resources);
    JGenericType list = to.getType("List").isGenericType();
    JGenericType emptyList = to.getType("EmptyList").isGenericType();
    JClassType cantSerialize = to.getType("CantSerialize");
    JParameterizedType listOfCantSerialize = to.getParameterizedType(list, makeArray(cantSerialize));
    SerializableTypeOracleBuilder sob = createSerializableTypeOracleBuilder(logger, to);
    sob.addRootType(logger, listOfCantSerialize);
    SerializableTypeOracle so = sob.build(logger);
    assertFieldSerializable(so, listOfCantSerialize);
    assertSerializableTypes(so, list.getRawType(), emptyList.getRawType());
}
Example 30
Project: gwt.svn-master  File: SerializableTypeOracleBuilderTest.java View source code
/**
   * Test with a generic class whose type parameter is exposed only in certain
   * subclasses.
   * 
   * NOTE: This test has been disabled because it requires a better pruner in
   * STOB. See SerializableTypeOracleBuilder.pruneUnreachableTypes().
   */
public void disabledTestMaybeExposedParameter() throws UnableToCompleteException, NotFoundException {
    Set<Resource> resources = new HashSet<Resource>();
    addStandardClasses(resources);
    {
        StringBuilder code = new StringBuilder();
        code.append("import java.io.Serializable;\n");
        code.append("public abstract class List<T> implements Serializable {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("List", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class EmptyList<T> extends List<T> {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("EmptyList", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class LinkedList<T> extends List<T> {\n");
        code.append("  T head;\n");
        code.append("  LinkedList<T> next;\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("LinkedList", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class CantSerialize {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("CantSerialize", code));
    }
    TreeLogger logger = createLogger();
    TypeOracle to = TypeOracleTestingUtils.buildTypeOracle(logger, resources);
    JGenericType list = to.getType("List").isGenericType();
    JGenericType emptyList = to.getType("EmptyList").isGenericType();
    JClassType cantSerialize = to.getType("CantSerialize");
    JParameterizedType listOfCantSerialize = to.getParameterizedType(list, makeArray(cantSerialize));
    SerializableTypeOracleBuilder sob = createSerializableTypeOracleBuilder(logger, to);
    sob.addRootType(logger, listOfCantSerialize);
    SerializableTypeOracle so = sob.build(logger);
    assertFieldSerializable(so, listOfCantSerialize);
    assertSerializableTypes(so, list.getRawType(), emptyList.getRawType());
}
Example 31
Project: scalagwt-gwt-master  File: SerializableTypeOracleBuilderTest.java View source code
/**
   * Test with a generic class whose type parameter is exposed only in certain
   * subclasses.
   * 
   * NOTE: This test has been disabled because it requires a better pruner in
   * STOB. See SerializableTypeOracleBuilder.pruneUnreachableTypes().
   */
public void disabledTestMaybeExposedParameter() throws UnableToCompleteException, NotFoundException {
    Set<Resource> resources = new HashSet<Resource>();
    addStandardClasses(resources);
    {
        StringBuilder code = new StringBuilder();
        code.append("import java.io.Serializable;\n");
        code.append("public abstract class List<T> implements Serializable {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("List", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class EmptyList<T> extends List<T> {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("EmptyList", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class LinkedList<T> extends List<T> {\n");
        code.append("  T head;\n");
        code.append("  LinkedList<T> next;\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("LinkedList", code));
    }
    {
        StringBuilder code = new StringBuilder();
        code.append("public class CantSerialize {\n");
        code.append("}\n");
        resources.add(new StaticJavaResource("CantSerialize", code));
    }
    TreeLogger logger = createLogger();
    TypeOracle to = TypeOracleTestingUtils.buildTypeOracle(logger, resources);
    JGenericType list = to.getType("List").isGenericType();
    JGenericType emptyList = to.getType("EmptyList").isGenericType();
    JClassType cantSerialize = to.getType("CantSerialize");
    JParameterizedType listOfCantSerialize = to.getParameterizedType(list, makeArray(cantSerialize));
    SerializableTypeOracleBuilder sob = createSerializableTypeOracleBuilder(logger, to);
    sob.addRootType(logger, listOfCantSerialize);
    SerializableTypeOracle so = sob.build(logger);
    assertFieldSerializable(so, listOfCantSerialize);
    assertSerializableTypes(so, list.getRawType(), emptyList.getRawType());
}
Example 32
Project: cistern-master  File: Copy.java View source code
public static Object clone(Serializable object) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    try {
        ObjectInputStream ois = new ObjectInputStream(bais);
        return ois.readObject();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}
Example 33
Project: ehour-master  File: PrimaryKeyCache.java View source code
public void putKey(Class<?> domainObjectClass, Serializable oldKey, Serializable newKey) {
    Map<Serializable, Serializable> oldNewKeyMap;
    if (keyMap.containsKey(domainObjectClass)) {
        oldNewKeyMap = keyMap.get(domainObjectClass);
    } else {
        oldNewKeyMap = new HashMap<>();
    }
    oldNewKeyMap.put(oldKey, newKey);
    keyMap.put(domainObjectClass, oldNewKeyMap);
}
Example 34
Project: hibernate-orm-master  File: CacheHelper.java View source code
public static Serializable fromSharedCache(SharedSessionContractImplementor session, Object cacheKey, RegionAccessStrategy cacheAccessStrategy) {
    final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
    Serializable cachedValue = null;
    eventListenerManager.cacheGetStart();
    try {
        cachedValue = (Serializable) cacheAccessStrategy.get(session, cacheKey, session.getTimestamp());
    } finally {
        eventListenerManager.cacheGetEnd(cachedValue != null);
    }
    return cachedValue;
}
Example 35
Project: http-queue-master  File: JMSSenderUtil.java View source code
public static void sendJMSMessage(ConnectionFactory connectionFactory, Destination destination, Serializable message) {
    Connection conn = null;
    Session session = null;
    MessageProducer publisher = null;
    try {
        conn = connectionFactory.createConnection();
        session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        publisher = session.createProducer(destination);
        ObjectMessage msg = session.createObjectMessage(message);
        publisher.send(msg);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (publisher != null)
                publisher.close();
            if (session != null)
                session.close();
            if (conn != null)
                conn.close();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }
}
Example 36
Project: ismp_manager-master  File: ServiceCheckMessageSend.java View source code
public void springSend(final Serializable object) throws Exception {
    jmsTemplate.send(destination, new MessageCreator() {

        @Override
        public Message createMessage(Session session) throws JMSException {
            MapMessage msg = session.createMapMessage();
            ServiceCheckModel model = (ServiceCheckModel) object;
            msg.setString("nodeid", model.getNodeid());
            msg.setString("ipAddr", model.getIpAddr());
            msg.setString("serviceType", model.getType());
            msg.setString("pingStatus", model.getPingStatus());
            msg.setDouble("responseTime", model.getResponseTime());
            msg.setString("pingTime", format.format(new Date()));
            return msg;
        }
    });
}
Example 37
Project: jasm-master  File: JLS_5_5_CastingConversion_1.java View source code
public static void main(String[] args) {
    Object x = new Integer(1);
    Object y = new Float(2.0);
    Cloneable z = new int[10];
    Serializable w = new int[10];
    try {
        Integer a = (Integer) x;
        System.out.println("Cast 1 ... OK");
    } catch (ClassCastException e) {
        System.out.println("ClassCastException");
        e.printStackTrace();
    }
    try {
        Integer a = (Integer) y;
    } catch (ClassCastException e) {
        System.out.println("Cast 2 ... OK");
    }
    try {
        int[] a = (int[]) z;
        System.out.println("Cast 3 ... OK");
    } catch (ClassCastException e) {
        System.out.println("ClassCastException");
        e.printStackTrace();
    }
    try {
        int[] a = (int[]) w;
        System.out.println("Cast 4 ... OK");
    } catch (ClassCastException e) {
        System.out.println("ClassCastException");
        e.printStackTrace();
    }
}
Example 38
Project: kannel-java-master  File: SimpleJMSTranslator.java View source code
public Serializable kannelToObject(SMSPacketMessage sms) {
    SimpleMessage sMesg = null;
    KString sender = sms.getSender();
    KString receiver = sms.getReceiver();
    KString udhdata = sms.getUdhdata();
    KString message = sms.getMsgdata();
    sMesg = new SimpleMessage(new String(sender.getString()), new String(receiver.getString()), new String(udhdata.getString()), new String(message.getString()));
    return sMesg;
}
Example 39
Project: mobicents-master  File: CancelTimerAfterTxCommitRunnable.java View source code
/*
	 * (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
public void run() {
    final TimerTaskData taskData = task.getData();
    final Serializable taskID = taskData.getTaskID();
    if (logger.isDebugEnabled()) {
        logger.debug("Cancelling timer task for timer ID " + taskID);
    }
    executor.getLocalRunningTasksMap().remove(taskID);
    try {
        task.getScheduledFuture().cancel(false);
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
    }
}
Example 40
Project: openjdk-master  File: ValueHandlerImpl.java View source code
// See javax.rmi.CORBA.ValueHandlerMultiFormat
public void writeValue(org.omg.CORBA.portable.OutputStream out, java.io.Serializable value, byte streamFormatVersion) {
    if (streamFormatVersion == 2) {
        if (!(out instanceof org.omg.CORBA.portable.ValueOutputStream)) {
            throw omgWrapper.notAValueoutputstream();
        }
    } else if (streamFormatVersion != 1) {
        throw omgWrapper.invalidStreamFormatVersion(new Integer(streamFormatVersion));
    }
    writeValueWithVersion(out, value, streamFormatVersion);
}
Example 41
Project: openolat-master  File: AuditInterceptor.java View source code
/**
	 * @see org.hibernate.Interceptor#onSave(java.lang.Object, java.io.Serializable, java.lang.Object[], java.lang.String[], org.hibernate.type.Type[])
	 */
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
    // automatically set the creationdate property on Auditable (all OLAT entities implement Auditable)
    if (entity instanceof CreateInfo) {
        creates++;
        for (int i = 0; i < propertyNames.length; i++) {
            if ("creationDate".equals(propertyNames[i])) {
                if (state[i] == null) {
                    state[i] = new Date();
                    return true;
                }
            }
        }
    }
    return false;
}
Example 42
Project: OurGrid-master  File: ScheduleActionWithFixedDelaySender.java View source code
public void execute(ScheduleActionWithFixedDelayResponseTO response, ServiceManager manager) {
    String actionName = response.getActionName();
    long delay = response.getDelay();
    long initialDelay = response.getInitialDelay();
    TimeUnit timeUnit = response.getTimeUnit();
    Serializable handler = response.getHandler();
    Future<?> future = response.hasInitialDelay() ? manager.scheduleActionWithFixedDelay(actionName, initialDelay, delay, timeUnit, handler) : manager.scheduleActionWithFixedDelay(actionName, delay, timeUnit, handler);
    if (response.storeFuture()) {
        WorkerDAOFactory.getInstance().getFutureDAO().setReportAccountingActionFuture(future);
    }
}
Example 43
Project: park_java-master  File: IntegerRangeValidator.java View source code
@Override
public boolean validateInternal(Entity entity, Serializable instance, Map<String, FieldMetadata> entityFieldMetadata, Map<String, String> validationConfiguration, BasicFieldMetadata propertyMetadata, String propertyName, String value) {
    int val = Integer.parseInt(value);
    String max = validationConfiguration.get("max");
    String min = validationConfiguration.get("min");
    if (max != null) {
        if (val > Integer.parseInt(max))
            return false;
    }
    if (min != null) {
        if (val < Integer.parseInt(min))
            return false;
    }
    return true;
}
Example 44
Project: rife-master  File: FilteredTagProcessorMvel.java View source code
public Object processExpression(Template template, Class rootType, String rootName, Object rootValue, String expression, Map<String, Object> context) throws Exception {
    Serializable compiled = (Serializable) template.getCacheObject(expression);
    if (null == compiled) {
        compiled = MVEL.compileExpression(expression);
        template.cacheObject(expression, compiled);
    }
    return MVEL.executeExpression(compiled, rootValue, context, Boolean.class);
}
Example 45
Project: roaster-master  File: InterfacedTestBase.java View source code
@Test
public void testGetInterfaces() throws Exception {
    this.source.addInterface(Serializable.class);
    this.source.addInterface("com.example.Custom");
    this.source.addInterface("com.other.Custom");
    assertEquals(3, this.source.getInterfaces().size());
    assertTrue(this.source.hasInterface("com.example.Custom"));
    assertTrue(this.source.hasInterface("com.other.Custom"));
    assertTrue(this.source.hasImport(Serializable.class));
    assertTrue(this.source.hasImport("com.example.Custom"));
    assertFalse(this.source.hasImport("com.other.Custom"));
}
Example 46
Project: udig-community-master  File: Preload.java View source code
public void earlyStartup() {
    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put("url", WorldWindTileProtocol.class.getResource("earthimages.xml"));
    List<IService> match = CatalogPlugin.getDefault().getServiceFactory().acquire(params);
    if (!match.isEmpty()) {
        ICatalog local = CatalogPlugin.getDefault().getLocalCatalog();
        local.add(match.get(0));
    }
}
Example 47
Project: Weibo-Material-master  File: ObjectUtil.java View source code
public static <T> T cloneObject(T t) {
    if (t == null)
        return null;
    if (!(t instanceof Serializable)) {
        return t;
    }
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        try {
            out = new ObjectOutputStream(bos);
            out.writeObject(t);
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            in = new ObjectInputStream(bis);
            @SuppressWarnings("unchecked") T tmpT = (T) in.readObject();
            return tmpT;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    } catch (Exception e) {
    }
    return t;
}
Example 48
Project: blaze-persistence-master  File: FilterUtils.java View source code
@SuppressWarnings("unchecked")
public static Object parseValue(Class<?> clazz, Object value) {
    try {
        return FormatUtils.getParsedValue((Class<? extends Serializable>) clazz, value.toString());
    } catch (ParseException ex) {
        throw new IllegalArgumentException("The given value '" + value + "' could not be parsed into an object of type '" + clazz.getName() + "'", ex);
    }
}
Example 49
Project: classfilewriter-master  File: SimpleTest.java View source code
@Test
public void testAddingInterfaces() {
    ClassFile test = new ClassFile("com/test/BClass", "java/lang/Object", getClass().getClassLoader(), "java/io/Serializable");
    Class<?> clazz = test.define();
    Assert.assertEquals("com.test.BClass", clazz.getName());
    Assert.assertTrue(Serializable.class.isAssignableFrom(clazz));
    Assert.assertEquals(1, clazz.getInterfaces().length);
}
Example 50
Project: dionysus-master  File: EntityIDTest.java View source code
@Test
public void makeSureEntityIDCanbeDetect() {
    Metamodel model = entityManager.getMetamodel();
    final Reflections reflections = new Reflections(EntityIDTest.class.getPackage().getName());
    Set<Class<?>> entities = reflections.getTypesAnnotatedWith(Entity.class);
    for (Class<?> entity : entities) {
        EntityType<?> entityType = model.entity(entity);
        Class<?> id = entityType.getIdType().getJavaType();
        System.out.println(entityType);
        if (entity.equals(InvalidEntity.class)) {
            Assert.assertEquals(id, Serializable.class);
        } else {
            Assert.assertNotEquals(id, Serializable.class);
        }
    }
}
Example 51
Project: ehcache3-master  File: ArrayPackageScopeTest.java View source code
@Test
public void testArrayPackageScope() throws Exception {
    @SuppressWarnings("unchecked") StatefulSerializer<Serializable> serializer = new CompactJavaSerializer(null);
    serializer.init(new TransientStateRepository());
    ClassLoader loaderA = createClassNameRewritingLoader(Foo_A.class);
    Serializable a = (Serializable) Array.newInstance(loaderA.loadClass(newClassName(Foo_A.class)), 0);
    ByteBuffer encodedA = serializer.serialize(a);
    pushTccl(createClassNameRewritingLoader(Foo_B.class));
    try {
        Serializable b = serializer.read(encodedA);
        Assert.assertTrue(b.getClass().isArray());
    } finally {
        popTccl();
    }
}
Example 52
Project: jboss-classfilewriter-master  File: SimpleTest.java View source code
@Test
public void testAddingInterfaces() {
    ClassFile test = new ClassFile("com/test/BClass", "java/lang/Object", getClass().getClassLoader(), "java/io/Serializable");
    Class<?> clazz = test.define();
    Assert.assertEquals("com.test.BClass", clazz.getName());
    Assert.assertTrue(Serializable.class.isAssignableFrom(clazz));
    Assert.assertEquals(1, clazz.getInterfaces().length);
}
Example 53
Project: jPOS-master  File: BSHTransactionParticipant.java View source code
public void abort(long id, java.io.Serializable context) {
    LogEvent ev = new LogEvent(this, "abort");
    if (abortMethod != null) {
        try {
            executeMethod(abortMethod, id, context, ev, "");
        } catch (Exception ex) {
            ev.addMessage(ex);
        }
    } else {
        defaultAbort(id, context, ev);
    }
    if (trace)
        Logger.log(ev);
}
Example 54
Project: karaf-cellar-master  File: ExportServiceListenerTest.java View source code
@Test
public void testGetServiceInterfaces() throws Exception {
    System.out.println("Test Service interfaces with null service");
    Set<String> expectedResult = new LinkedHashSet<String>();
    Set<String> result = listener.getServiceInterfaces(null, null);
    Assert.assertEquals(expectedResult, result);
    result = listener.getServiceInterfaces(null, new String[] { "*" });
    Assert.assertEquals(expectedResult, result);
    System.out.println("Test Service interfaces with ArrayList and wildcard services");
    result = listener.getServiceInterfaces(new ArrayList(), new String[] { "*" });
    Assert.assertTrue(result.contains("java.util.List"));
    System.out.println("Test Service interfaces with ArrayList and List/Serializable services");
    result = listener.getServiceInterfaces(new ArrayList(), new String[] { "java.util.List", "java.io.Serializable" });
    Assert.assertTrue(result.contains("java.util.List"));
    Assert.assertTrue(result.contains("java.io.Serializable"));
}
Example 55
Project: loadimpact-sdk-java-master  File: ObjectUtils.java View source code
/**
     * Makes a deep-copy clone of an object.
     * @param obj   target object, that must implements {@link java.io.Serializable}
     * @return deep-copy
     */
public static Serializable copy(Serializable obj) {
    try {
        ByteArrayOutputStream buf = new ByteArrayOutputStream(4096);
        ObjectOutputStream out = new ObjectOutputStream(buf);
        out.writeObject(obj);
        out.close();
        ByteArrayInputStream buf2 = new ByteArrayInputStream(buf.toByteArray());
        ObjectInputStream in = new ObjectInputStream(buf2);
        Serializable obj2 = (Serializable) in.readObject();
        in.close();
        return obj2;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}
Example 56
Project: offheap-store-master  File: ArrayPackageScopeTest.java View source code
@Test
public void testArrayPackageScope() throws Exception {
    Portability<Serializable> p = new SerializablePortability();
    ClassLoader loaderA = createClassNameRewritingLoader(Foo_A.class);
    Serializable a = (Serializable) Array.newInstance(loaderA.loadClass(newClassName(Foo_A.class)), 0);
    ByteBuffer encodedA = p.encode(a);
    pushTccl(createClassNameRewritingLoader(Foo_B.class));
    try {
        Serializable b = p.decode(encodedA);
        Assert.assertTrue(b.getClass().isArray());
    } finally {
        popTccl();
    }
}
Example 57
Project: sculptor-master  File: Option.java View source code
private static Serializable getId(Object domainObject) {
    if (PropertyUtils.isReadable(domainObject, "id")) {
        try {
            return (Serializable) PropertyUtils.getProperty(domainObject, "id");
        } catch (Exception e) {
            throw new IllegalArgumentException("Can't get id property of domainObject: " + domainObject);
        }
    } else {
        // no id property, don't know if it is new
        throw new IllegalArgumentException("No id property in domainObject: " + domainObject);
    }
}
Example 58
Project: spring-data-commons-master  File: ReflectionEntityInformationUnitTests.java View source code
// DATACMNS-357
@Test
public void detectsNewStateForEntitiesWithPrimitiveIds() {
    PrimitiveId primitiveId = new PrimitiveId();
    EntityInformation<PrimitiveId, Serializable> information = new ReflectionEntityInformation<>(PrimitiveId.class);
    assertThat(information.isNew(primitiveId)).isTrue();
    primitiveId.id = 5L;
    assertThat(information.isNew(primitiveId)).isFalse();
}
Example 59
Project: tesb-rt-se-master  File: CallContextFactoryImpl.java View source code
@Override
public String marshalObject(E ctx) {
    if (ctx instanceof Serializable) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(ctx);
            oos.close();
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.FINER)) {
                LOGGER.log(Level.FINER, "Exception caught: ", e);
            }
        }
        return new String(Base64Coder.encode(baos.toByteArray()));
    } else {
        throw new IllegalArgumentException("Marshalled object should implement " + " java.io.Serializable");
    }
}
Example 60
Project: xtext-master  File: Option.java View source code
private static Serializable getId(Object domainObject) {
    if (PropertyUtils.isReadable(domainObject, "id")) {
        try {
            return (Serializable) PropertyUtils.getProperty(domainObject, "id");
        } catch (Exception e) {
            throw new IllegalArgumentException("Can't get id property of domainObject: " + domainObject);
        }
    } else {
        // no id property, don't know if it is new
        throw new IllegalArgumentException("No id property in domainObject: " + domainObject);
    }
}
Example 61
Project: glassfish-main-master  File: CheckActivationSpecSerializable.java View source code
/** <p>
   * Test that "activationspec-class" implements java.io.Serializable
   * </p>
   *
   * @param descriptor deployment descriptor for the rar file
   * @return result object containing the result of the individual test
   * performed
   */
public Result check(ConnectorDescriptor descriptor) {
    Result result = getInitializedResult();
    ComponentNameConstructor compName = getVerifierContext().getComponentNameConstructor();
    if (!descriptor.getInBoundDefined()) {
        result.addNaDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
        result.notApplicable(smh.getLocalString("com.sun.enterprise.tools.verifier.tests.connector.messageinflow.notApp", "Resource Adapter does not provide inbound communication"));
        return result;
    }
    InboundResourceAdapter ra = descriptor.getInboundResourceAdapter();
    Set msgListeners = ra.getMessageListeners();
    boolean oneFailed = false;
    Iterator iter = msgListeners.iterator();
    while (iter.hasNext()) {
        MessageListener msgListener = (MessageListener) iter.next();
        String impl = msgListener.getActivationSpecClass();
        Class implClass = null;
        try {
            implClass = Class.forName(impl, false, getVerifierContext().getClassLoader());
        } catch (ClassNotFoundException e) {
            result.addErrorDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
            result.failed(smh.getLocalString("com.sun.enterprise.tools.verifier.tests.connector.messageinflow.nonexist", "Error: The class [ {0} ] as defined under activationspec-class in the deployment descriptor does not exist", new Object[] { impl }));
            return result;
        }
        if (!isImplementorOf(implClass, "java.io.Serializable")) {
            oneFailed = true;
            result.addErrorDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
            result.failed(smh.getLocalString(getClass().getName() + ".failed", "Error: activationspec-class [ {0} ] does not implement java.io.Serializable", new Object[] { impl }));
            return result;
        }
    }
    if (!oneFailed) {
        result.addGoodDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
        result.passed(smh.getLocalString(getClass().getName() + ".passed", "Success: all activationspec-class implement java.io.Serializable"));
    }
    return result;
}
Example 62
Project: glassfish-master  File: CheckActivationSpecSerializable.java View source code
/** <p>
   * Test that "activationspec-class" implements java.io.Serializable
   * </p>
   *
   * @param descriptor deployment descriptor for the rar file
   * @return result object containing the result of the individual test
   * performed
   */
public Result check(ConnectorDescriptor descriptor) {
    Result result = getInitializedResult();
    ComponentNameConstructor compName = getVerifierContext().getComponentNameConstructor();
    if (!descriptor.getInBoundDefined()) {
        result.addNaDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
        result.notApplicable(smh.getLocalString("com.sun.enterprise.tools.verifier.tests.connector.messageinflow.notApp", "Resource Adapter does not provide inbound communication"));
        return result;
    }
    InboundResourceAdapter ra = descriptor.getInboundResourceAdapter();
    Set msgListeners = ra.getMessageListeners();
    boolean oneFailed = false;
    Iterator iter = msgListeners.iterator();
    while (iter.hasNext()) {
        MessageListener msgListener = (MessageListener) iter.next();
        String impl = msgListener.getActivationSpecClass();
        Class implClass = null;
        try {
            implClass = Class.forName(impl, false, getVerifierContext().getClassLoader());
        } catch (ClassNotFoundException e) {
            result.addErrorDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
            result.failed(smh.getLocalString("com.sun.enterprise.tools.verifier.tests.connector.messageinflow.nonexist", "Error: The class [ {0} ] as defined under activationspec-class in the deployment descriptor does not exist", new Object[] { impl }));
            return result;
        }
        if (!isImplementorOf(implClass, "java.io.Serializable")) {
            oneFailed = true;
            result.addErrorDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
            result.failed(smh.getLocalString(getClass().getName() + ".failed", "Error: activationspec-class [ {0} ] does not implement java.io.Serializable", new Object[] { impl }));
            return result;
        }
    }
    if (!oneFailed) {
        result.addGoodDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
        result.passed(smh.getLocalString(getClass().getName() + ".passed", "Success: all activationspec-class implement java.io.Serializable"));
    }
    return result;
}
Example 63
Project: Payara-master  File: CheckActivationSpecSerializable.java View source code
/** <p>
   * Test that "activationspec-class" implements java.io.Serializable
   * </p>
   *
   * @param descriptor deployment descriptor for the rar file
   * @return result object containing the result of the individual test
   * performed
   */
public Result check(ConnectorDescriptor descriptor) {
    Result result = getInitializedResult();
    ComponentNameConstructor compName = getVerifierContext().getComponentNameConstructor();
    if (!descriptor.getInBoundDefined()) {
        result.addNaDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
        result.notApplicable(smh.getLocalString("com.sun.enterprise.tools.verifier.tests.connector.messageinflow.notApp", "Resource Adapter does not provide inbound communication"));
        return result;
    }
    InboundResourceAdapter ra = descriptor.getInboundResourceAdapter();
    Set msgListeners = ra.getMessageListeners();
    boolean oneFailed = false;
    Iterator iter = msgListeners.iterator();
    while (iter.hasNext()) {
        MessageListener msgListener = (MessageListener) iter.next();
        String impl = msgListener.getActivationSpecClass();
        Class implClass = null;
        try {
            implClass = Class.forName(impl, false, getVerifierContext().getClassLoader());
        } catch (ClassNotFoundException e) {
            result.addErrorDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
            result.failed(smh.getLocalString("com.sun.enterprise.tools.verifier.tests.connector.messageinflow.nonexist", "Error: The class [ {0} ] as defined under activationspec-class in the deployment descriptor does not exist", new Object[] { impl }));
            return result;
        }
        if (!isImplementorOf(implClass, "java.io.Serializable")) {
            oneFailed = true;
            result.addErrorDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
            result.failed(smh.getLocalString(getClass().getName() + ".failed", "Error: activationspec-class [ {0} ] does not implement java.io.Serializable", new Object[] { impl }));
            return result;
        }
    }
    if (!oneFailed) {
        result.addGoodDetails(smh.getLocalString("tests.componentNameConstructor", "For [ {0} ]", new Object[] { compName.toString() }));
        result.passed(smh.getLocalString(getClass().getName() + ".passed", "Success: all activationspec-class implement java.io.Serializable"));
    }
    return result;
}
Example 64
Project: classlib6-master  File: ValueHandlerImpl.java View source code
// See javax.rmi.CORBA.ValueHandlerMultiFormat
public void writeValue(org.omg.CORBA.portable.OutputStream out, java.io.Serializable value, byte streamFormatVersion) {
    if (streamFormatVersion == 2) {
        if (!(out instanceof org.omg.CORBA.portable.ValueOutputStream)) {
            throw omgWrapper.notAValueoutputstream();
        }
    } else if (streamFormatVersion != 1) {
        throw omgWrapper.invalidStreamFormatVersion(new Integer(streamFormatVersion));
    }
    writeValueWithVersion(out, value, streamFormatVersion);
}
Example 65
Project: ikvm-openjdk-master  File: ValueHandlerImpl.java View source code
// See javax.rmi.CORBA.ValueHandlerMultiFormat
public void writeValue(org.omg.CORBA.portable.OutputStream out, java.io.Serializable value, byte streamFormatVersion) {
    if (streamFormatVersion == 2) {
        if (!(out instanceof org.omg.CORBA.portable.ValueOutputStream)) {
            throw omgWrapper.notAValueoutputstream();
        }
    } else if (streamFormatVersion != 1) {
        throw omgWrapper.invalidStreamFormatVersion(new Integer(streamFormatVersion));
    }
    writeValueWithVersion(out, value, streamFormatVersion);
}
Example 66
Project: jboss-openjdk-orb-master  File: ValueHandlerImpl.java View source code
// See javax.rmi.CORBA.ValueHandlerMultiFormat
public void writeValue(org.omg.CORBA.portable.OutputStream out, java.io.Serializable value, byte streamFormatVersion) {
    if (streamFormatVersion == 2) {
        if (!(out instanceof org.omg.CORBA.portable.ValueOutputStream)) {
            throw omgWrapper.notAValueoutputstream();
        }
    } else if (streamFormatVersion != 1) {
        throw omgWrapper.invalidStreamFormatVersion(new Integer(streamFormatVersion));
    }
    writeValueWithVersion(out, value, streamFormatVersion);
}
Example 67
Project: JDK-master  File: SerializationTester.java View source code
static boolean test(Object obj) {
    if (!(obj instanceof Serializable)) {
        return false;
    }
    try {
        stream.writeObject(obj);
    } catch (IOException e) {
        return false;
    } finally {
        // written object.
        try {
            stream.reset();
        } catch (IOException e) {
        }
    }
    return true;
}
Example 68
Project: jdk7u-corba-master  File: ValueHandlerImpl.java View source code
// See javax.rmi.CORBA.ValueHandlerMultiFormat
public void writeValue(org.omg.CORBA.portable.OutputStream out, java.io.Serializable value, byte streamFormatVersion) {
    if (streamFormatVersion == 2) {
        if (!(out instanceof org.omg.CORBA.portable.ValueOutputStream)) {
            throw omgWrapper.notAValueoutputstream();
        }
    } else if (streamFormatVersion != 1) {
        throw omgWrapper.invalidStreamFormatVersion(new Integer(streamFormatVersion));
    }
    writeValueWithVersion(out, value, streamFormatVersion);
}
Example 69
Project: ManagedRuntimeInitiative-master  File: ValueHandlerImpl.java View source code
// See javax.rmi.CORBA.ValueHandlerMultiFormat
public void writeValue(org.omg.CORBA.portable.OutputStream out, java.io.Serializable value, byte streamFormatVersion) {
    if (streamFormatVersion == 2) {
        if (!(out instanceof org.omg.CORBA.portable.ValueOutputStream)) {
            throw omgWrapper.notAValueoutputstream();
        }
    } else if (streamFormatVersion != 1) {
        throw omgWrapper.invalidStreamFormatVersion(new Integer(streamFormatVersion));
    }
    writeValueWithVersion(out, value, streamFormatVersion);
}
Example 70
Project: commons-collections-master  File: CollectionBagTest.java View source code
//    public void testCreate() throws Exception {
//        resetEmpty();
//        writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CollectionBag.emptyCollection.version4.obj");
//        resetFull();
//        writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/CollectionBag.fullCollection.version4.obj");
//    }
//-----------------------------------------------------------------------
/**
     * Compare the current serialized form of the Bag
     * against the canonical version in SVN.
     */
public void testEmptyBagCompatibility() throws IOException, ClassNotFoundException {
    // test to make sure the canonical form has been preserved
    final Bag<T> bag = makeObject();
    if (bag instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) {
        final Bag<?> bag2 = (Bag<?>) readExternalFormFromDisk(getCanonicalEmptyCollectionName(bag));
        assertTrue("Bag is empty", bag2.size() == 0);
        assertEquals(bag, bag2);
    }
}
Example 71
Project: jcodemodel-master  File: JTypeVarTest.java View source code
@Test
public void testBasic() throws JClassAlreadyExistsException {
    final JCodeModel cm = new JCodeModel();
    final JDefinedClass cls = cm._class("Test");
    final JMethod m = cls.method(JMod.PUBLIC, cm.VOID, "foo");
    final JTypeVar tv = m.generify("T");
    tv.bound(cm.parseType("java.lang.Comparable<T>").boxify());
    tv.bound(cm.ref(Serializable.class));
    assertEquals("T extends java.lang.Comparable<T> & java.io.Serializable", CodeModelTestsHelper.toString(tv));
    assertEquals("public<T extends java.lang.Comparable<T> & java.io.Serializable> void foo() {\n" + "}\n", CodeModelTestsHelper.toString(m).replace("\r", ""));
}
Example 72
Project: zaproxy-master  File: ViewState.java View source code
/** 
         * encode a object to a base64 string
         * @param o is a implemented java.io.Serializable object
         * @return the encoded object
         */
public static String encode(Serializable o) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        try {
            oos.writeObject(o);
            oos.flush();
        } finally {
            oos.close();
        }
        return Base64.encodeBytes(bos.toByteArray());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 73
Project: AIDR-master  File: ImageFeedDao.java View source code
@Override
public Serializable save(ImageFeed imageFeed) {
    Long savedId = -1L;
    Date currentDate = new Date();
    if (imageFeed != null) {
        if (imageFeed.getId() == null) {
            imageFeed.setCreatedAt(currentDate);
        }
        imageFeed.setUpdatedAt(currentDate);
        savedId = (Long) super.save(imageFeed);
    }
    return savedId;
}
Example 74
Project: beakerx-master  File: MessageFactoryTest.java View source code
public static Message getExecuteRequestMessage(String code) {
    Message message = new Message();
    Header header = new Header();
    header.setTypeEnum(JupyterMessages.EXECUTE_REQUEST);
    message.setHeader(header);
    HashMap<String, Serializable> content = new HashMap<>();
    content.put("code", code);
    message.setContent(content);
    return message;
}
Example 75
Project: bonita-web-master  File: ApplicationPageFilterCreatorTest.java View source code
@Test
public void should_return_filter_based_on_given_field_and_value_on_create() throws Exception {
    //given
    given(converter.convert("name")).willReturn("name");
    //when
    final Filter<? extends Serializable> filter = creator.create("name", "a name");
    //then
    assertThat(filter).isNotNull();
    assertThat(filter.getField()).isEqualTo("name");
    assertThat(filter.getValue()).isEqualTo("a name");
}
Example 76
Project: bugsnag-eclipse-plugin-master  File: SerializationUtils.java View source code
public static String serialize(Serializable object) {
    String encoded = null;
    try {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        encoded = Base64.encodeBase64String(byteArrayOutputStream.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return encoded;
}
Example 77
Project: cache2k-master  File: RuntimeCopyTransformer.java View source code
@Override
public Object copy(Object obj) {
    if (obj == null) {
        return null;
    }
    if (SimpleObjectCopyFactory.isImmutable(obj.getClass())) {
        return obj;
    }
    if (obj instanceof Serializable) {
        return serializableCopyTransformer.copy(obj);
    }
    throw new IllegalArgumentException("Cannot determine copy / marshalling method for: " + obj.getClass().getName());
}
Example 78
Project: calopsita-master  File: RepositoryInterceptor.java View source code
@Override
public Object instantiate(String className, EntityMode mode, Serializable id) throws CallbackException {
    Object object = instantiator.instantiate(new Target(new Mirror().reflectClass(className), ""), new Parameters());
    Field field = new Mirror().on(className).reflectAll().fieldsMatching(new Matcher<Field>() {

        public boolean accepts(Field field) {
            return field.isAnnotationPresent(Id.class);
        }
    }).get(0);
    new Mirror().on(object).set().field(field).withValue(id);
    return object;
}
Example 79
Project: Cangol-appcore-master  File: SocketClientTest.java View source code
public void testSend() throws Exception {
    final SocketClient socketClient = new SocketClient();
    socketClient.connect(getContext(), "127.0.0.1", 8080, true, 10 * 1000, new SocketHandler() {

        @Override
        public boolean handleSocketWrite(OutputStream outputStream) throws IOException {
            return false;
        }

        @Override
        public boolean handleSocketRead(int timeout, InputStream inputStream) throws IOException, ClassNotFoundException {
            return false;
        }

        @Override
        protected Object getSend() {
            return null;
        }

        @Override
        protected void onFail(Object obj, Exception e) {
            socketClient.cancel(true);
        }
    });
    socketClient.connect(getContext(), "127.0.0.1", 8080, true, 10 * 1000, new SocketSerializableHandler() {

        @Override
        protected Object getSend() {
            return null;
        }

        @Override
        public void onReceive(Serializable msg) {
        }

        @Override
        protected void onFail(Object obj, Exception e) {
        }
    });
}
Example 80
Project: cdo-master  File: CDOUUIDHexGenerator.java View source code
@Override
public Serializable generate(SessionImplementor session, Object obj) {
    if (!(obj instanceof CDORevision)) {
        return super.generate(session, obj);
    }
    final EntityPersister entityPersister = session.getEntityPersister(null, obj);
    final Serializable id = entityPersister.getIdentifier(obj, session);
    if (id != null) {
        return id;
    }
    return super.generate(session, obj);
}
Example 81
Project: clinic-softacad-master  File: DynamicInstantiator.java View source code
public Object instantiate(Serializable id) {
    if (Cuisine.class.getName().equals(entityName)) {
        return ProxyHelper.newCuisineProxy(id);
    }
    if (Country.class.getName().equals(entityName)) {
        return ProxyHelper.newCountryProxy(id);
    } else {
        throw new IllegalArgumentException("unknown entity for instantiation [" + entityName + "]");
    }
}
Example 82
Project: controller-master  File: ReadyTransactionReplyTest.java View source code
@Test
public void testSerialization() {
    String cohortPath = "cohort path";
    ReadyTransactionReply expected = new ReadyTransactionReply(cohortPath);
    Object serialized = expected.toSerializable();
    assertEquals("Serialized type", ReadyTransactionReply.class, serialized.getClass());
    ReadyTransactionReply actual = ReadyTransactionReply.fromSerializable(SerializationUtils.clone((Serializable) serialized));
    assertEquals("getVersion", DataStoreVersions.CURRENT_VERSION, actual.getVersion());
    assertEquals("getCohortPath", cohortPath, actual.getCohortPath());
}
Example 83
Project: dcache-master  File: SpreadAndWaitTest.java View source code
@Test
public void testNext() throws InterruptedException {
    CellStub stub = mock(CellStub.class);
    when(stub.send(any(CellPath.class), any(Serializable.class), any(Class.class))).thenAnswer(new InvokesSuccess<>());
    SpreadAndWait<String> sut = new SpreadAndWait<>(stub);
    sut.send(new CellPath("test"), String.class, "test");
    assertThat(sut.next(), is("test"));
    assertThat(sut.next(), is(nullValue()));
}
Example 84
Project: deep-spark-master  File: ExtractorConfigTest.java View source code
/** 
* 
* Method: getInteger(String key) 
* 
*/
@Test
public void testGetInteger() throws Exception {
    String value = "1234";
    ExtractorConfig extractorConfig = new ExtractorConfig();
    Map<String, Serializable> values = new HashedMap();
    values.put(value, value);
    extractorConfig.setValues(values);
    Integer result = extractorConfig.getInteger(value);
    assertEquals("The result must be " + value, new Integer(value), result);
}
Example 85
Project: deeplearning4j-master  File: TestStorageMetaData.java View source code
@Test
public void testStorageMetaData() {
    Serializable extraMeta = "ExtraMetaData";
    long timeStamp = 123456;
    StorageMetaData m = new SbeStorageMetaData(timeStamp, "sessionID", "typeID", "workerID", "org.some.class.InitType", "org.some.class.UpdateType", extraMeta);
    byte[] bytes = m.encode();
    StorageMetaData m2 = new SbeStorageMetaData();
    m2.decode(bytes);
    assertEquals(m, m2);
    assertArrayEquals(bytes, m2.encode());
    //Sanity check: null values
    m = new SbeStorageMetaData(0, null, null, null, null, (String) null);
    bytes = m.encode();
    m2 = new SbeStorageMetaData();
    m2.decode(bytes);
    //In practice, we don't want these things to ever be null anyway...
    assertNullOrZeroLength(m2.getSessionID());
    assertNullOrZeroLength(m2.getTypeID());
    assertNullOrZeroLength(m2.getWorkerID());
    assertNullOrZeroLength(m2.getInitTypeClass());
    assertNullOrZeroLength(m2.getUpdateTypeClass());
    assertArrayEquals(bytes, m2.encode());
}
Example 86
Project: eve-java-master  File: MemoryState.java View source code
/*
	 * (non-Javadoc)
	 * @see
	 * com.almende.eve.state.AbstractState#locPutIfUnchanged(java.lang.String,
	 * java.io.Serializable, java.io.Serializable)
	 */
@Override
public boolean locPutIfUnchanged(final String key, final Serializable newVal, final Serializable oldVal) {
    if (newVal == null && oldVal == null) {
        return !properties.containsKey(key);
    } else if (newVal == null) {
        return properties.remove(key, oldVal);
    } else if (oldVal == null) {
        return properties.putIfAbsent(key, newVal) == null;
    } else {
        return properties.replace(key, oldVal, newVal);
    }
}
Example 87
Project: fastjson-master  File: JavaObjectDeserializer.java View source code
@SuppressWarnings("unchecked")
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    if (type instanceof GenericArrayType) {
        Type componentType = ((GenericArrayType) type).getGenericComponentType();
        if (componentType instanceof TypeVariable) {
            TypeVariable<?> componentVar = (TypeVariable<?>) componentType;
            componentType = componentVar.getBounds()[0];
        }
        List<Object> list = new ArrayList<Object>();
        parser.parseArray(componentType, list);
        Class<?> componentClass;
        if (componentType instanceof Class) {
            componentClass = (Class<?>) componentType;
            Object[] array = (Object[]) Array.newInstance(componentClass, list.size());
            list.toArray(array);
            return (T) array;
        } else {
            return (T) list.toArray();
        }
    }
    if (type instanceof Class && type != Object.class && type != Serializable.class) {
        return (T) parser.parseObject(type);
    }
    return (T) parser.parse(fieldName);
}
Example 88
Project: geotoolkit-master  File: ShapefileDemo.java View source code
public static void main(String[] args) throws DataStoreException, URISyntaxException {
    Demos.init();
    //create using a Parameters object--------------------------------------
    System.out.println(ShapefileFeatureStoreFactory.PARAMETERS_DESCRIPTOR);
    final ParameterValueGroup parameters = ShapefileFeatureStoreFactory.PARAMETERS_DESCRIPTOR.createValue();
    Parameters.getOrCreate(ShapefileFeatureStoreFactory.PATH, parameters).setValue(ShapefileDemo.class.getResource("/data/world/Countries.shp").toURI());
    final FeatureStore store1 = (FeatureStore) DataStores.open(parameters);
    //create using a Map----------------------------------------------------
    final Map<String, Serializable> map = new HashMap<String, Serializable>();
    map.put("path", ShapefileDemo.class.getResource("/data/world/Countries.shp").toURI());
    final FeatureStore store2 = (FeatureStore) DataStores.open(map);
}
Example 89
Project: geotools-cookbook-master  File: PropertyDataStoreFactory.java View source code
/**
     * Lookups the directory containing property files in the params argument,
     * and returns the corresponding <code>java.io.File</code>.
     * <p>
     * The file is first checked for existence as an absolute path in the
     * filesystem. If such a directory is not found, then it is treated as a
     * relative path, taking Java system property <code>"user.dir"</code> as the
     * base.
     * </p>
     * 
     * @param params
     * @throws IllegalArgumentException if directory is not a directory.
     * @throws FileNotFoundException if directory does not exists
     * @throws IOException if {@linkplain #DIRECTORY} doesn't find parameter in
     *         <code>params</code> file does not exists.
     */
private File directoryLookup(Map<String, java.io.Serializable> params) throws IOException, FileNotFoundException, IllegalArgumentException {
    File file = (File) DIRECTORY.lookUp(params);
    if (!file.exists()) {
        File currentDir = new File(System.getProperty("user.dir"));
        String path = DIRECTORY.lookUp(params).toString();
        file = new File(currentDir, path);
        if (!file.exists()) {
            throw new FileNotFoundException(file.getAbsolutePath());
        }
    }
    if (file.isDirectory()) {
        return file;
    } else {
        // directory
        if (file.getPath().endsWith(".properties")) {
            return file.getParentFile();
        } else {
            throw new IllegalArgumentException(file.getAbsolutePath() + " is not a directory");
        }
    }
}
Example 90
Project: geotools-old-master  File: PropertyDataStoreFactory.java View source code
/**
     * Lookups the directory containing property files in the params argument,
     * and returns the corresponding <code>java.io.File</code>.
     * <p>
     * The file is first checked for existence as an absolute path in the
     * filesystem. If such a directory is not found, then it is treated as a
     * relative path, taking Java system property <code>"user.dir"</code> as the
     * base.
     * </p>
     * 
     * @param params
     * @throws IllegalArgumentException if directory is not a directory.
     * @throws FileNotFoundException if directory does not exists
     * @throws IOException if {@linkplain #DIRECTORY} doesn't find parameter in
     *         <code>params</code> file does not exists.
     */
private File directoryLookup(Map<String, java.io.Serializable> params) throws IOException, FileNotFoundException, IllegalArgumentException {
    File file = (File) DIRECTORY.lookUp(params);
    if (!file.exists()) {
        File currentDir = new File(System.getProperty("user.dir"));
        String path = DIRECTORY.lookUp(params).toString();
        file = new File(currentDir, path);
        if (!file.exists()) {
            throw new FileNotFoundException(file.getAbsolutePath());
        }
    }
    if (file.isDirectory()) {
        return file;
    } else {
        // directory
        if (file.getPath().endsWith(".properties")) {
            return file.getParentFile();
        } else {
            throw new IllegalArgumentException(file.getAbsolutePath() + " is not a directory");
        }
    }
}
Example 91
Project: geotools_trunk-master  File: PropertyDataStoreFactory.java View source code
/**
     * Lookups the directory containing property files in the params argument,
     * and returns the corresponding <code>java.io.File</code>.
     * <p>
     * The file is first checked for existence as an absolute path in the
     * filesystem. If such a directory is not found, then it is treated as a
     * relative path, taking Java system property <code>"user.dir"</code> as the
     * base.
     * </p>
     * 
     * @param params
     * @throws IllegalArgumentException if directory is not a directory.
     * @throws FileNotFoundException if directory does not exists
     * @throws IOException if {@linkplain #DIRECTORY} doesn't find parameter in
     *         <code>params</code> file does not exists.
     */
private File directoryLookup(Map<String, java.io.Serializable> params) throws IOException, FileNotFoundException, IllegalArgumentException {
    File file = (File) DIRECTORY.lookUp(params);
    if (!file.exists()) {
        File currentDir = new File(System.getProperty("user.dir"));
        String path = DIRECTORY.lookUp(params).toString();
        file = new File(currentDir, path);
        if (!file.exists()) {
            throw new FileNotFoundException(file.getAbsolutePath());
        }
    }
    if (file.isDirectory()) {
        return file;
    } else {
        // directory
        if (file.getPath().endsWith(".properties")) {
            return file.getParentFile();
        } else {
            throw new IllegalArgumentException(file.getAbsolutePath() + " is not a directory");
        }
    }
}
Example 92
Project: geowave-master  File: BaseDataStoreTest.java View source code
protected DataStore createDataStore() throws IOException, GeoWavePluginException {
    final Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put("gwNamespace", "test_" + getClass().getName());
    final StoreFactoryFamilySpi storeFactoryFamily = new MemoryStoreFactoryFamily();
    // delete existing data
    new GeoWavePluginConfig(storeFactoryFamily, params).getDataStore().delete(new QueryOptions(), new EverythingQuery());
    return new GeoWaveGTDataStoreFactory(storeFactoryFamily).createNewDataStore(params);
}
Example 93
Project: GraphTea-master  File: SerializedAttrSet.java View source code
/**
     * a unmodifiable copy of attributes in this object
     */
public void setBinding(Binding binding) {
    attrs.clear();
    Map<String, Object> bindingAttrs = binding.getAttrs();
    for (String key : bindingAttrs.keySet()) {
        Object val = bindingAttrs.get(key);
        if (val instanceof Serializable) {
            attrs.put(key, (Serializable) val);
        }
    //            else
    //                System.out.println(key + "Is not serializable! --wouldnt save!");
    }
}
Example 94
Project: hadoop-20-master  File: SerializableUtils.java View source code
public static Object getFromBytes(byte[] data, Class<? extends Serializable> expectedType) throws IOException, ClassNotFoundException {
    if (data == null) {
        throw new IOException("data is null");
    }
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = null;
    Object obj = null;
    try {
        is = new ObjectInputStream(in);
        obj = is.readObject();
        if (obj.getClass() != expectedType) {
            throw new IOException("The data provided is not a serialized object of type : " + expectedType);
        }
    } finally {
        if (is != null) {
            is.close();
        }
        in.close();
    }
    return obj;
}
Example 95
Project: hbnpojogen-master  File: IDPresentAwareGenerator.java View source code
@Override
public Serializable generate(SessionImplementor session, Object obj) {
    Serializable result = null;
    // if user has set the id manually, don't change it.
    try {
        Class<?> clazz = obj.getClass();
        Method idMethod = clazz.getMethod("getId");
        result = (Serializable) idMethod.invoke(obj);
    } catch (Exception e) {
    }
    // as if generator was set to AUTO
    if (result == null || (result.toString().equals("0"))) {
        return super.generate(session, obj);
    }
    return result;
}
Example 96
Project: hibernate-core-ogm-master  File: DynamicInstantiator.java View source code
public Object instantiate(Serializable id) {
    if (Cuisine.class.getName().equals(entityName)) {
        return ProxyHelper.newCuisineProxy(id);
    }
    if (Country.class.getName().equals(entityName)) {
        return ProxyHelper.newCountryProxy(id);
    } else {
        throw new IllegalArgumentException("unknown entity for instantiation [" + entityName + "]");
    }
}
Example 97
Project: hibernate-master-class-master  File: InterceptorDirtyCheckingTest.java View source code
@Override
public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
    if (entity instanceof DirtyAware) {
        DirtyAware dirtyAware = (DirtyAware) entity;
        Set<String> dirtyProperties = dirtyAware.getDirtyProperties();
        int[] dirtyPropertiesIndices = new int[dirtyProperties.size()];
        List<String> propertyNamesList = Arrays.asList(propertyNames);
        int i = 0;
        for (String dirtyProperty : dirtyProperties) {
            LOGGER.info("The {} property is dirty", dirtyProperty);
            dirtyPropertiesIndices[i++] = propertyNamesList.indexOf(dirtyProperty);
        }
        dirtyAware.clearDirtyProperties();
        return dirtyPropertiesIndices;
    }
    return super.findDirty(entity, id, currentState, previousState, propertyNames, types);
}
Example 98
Project: Hibernate-Search-on-action-master  File: AutomaticDistributorShardingStrategy.java View source code
public DirectoryProvider<?> getDirectoryProviderForAddition(Class<?> entityType, Serializable id, String idInString, Document document) {
    //make sure it is used on the right class
    assert entityType.getName().equals(Item.class.getName());
    String distributorId = document.get("distributor.id");
    int providerIndex = Integer.parseInt(distributorId) - 1;
    //ensure we never go over
    assert providerIndex < shardNbr : "The number of distributor are higher than available shards";
    return providers[providerIndex];
}
Example 99
Project: jboss-as7-jbpm-module-master  File: JMSSessionWriter.java View source code
public void write(Object message) throws IOException {
    try {
        ObjectMessage clientMessage = this.session.createObjectMessage();
        clientMessage.setObject((Serializable) message);
        clientMessage.setStringProperty(TaskServiceConstants.SELECTOR_NAME, this.selector);
        this.producer.send(clientMessage);
        this.session.commit();
    } catch (JMSException e) {
        throw new IOException("Unable to create message: " + e.getMessage());
    } finally {
        try {
            this.session.commit();
        } catch (JMSException e) {
            throw new IOException("Unable to commit message: " + e.getMessage());
        }
    }
}
Example 100
Project: jboss-deployers-master  File: MCFDeployer.java View source code
public void build(DeploymentUnit unit, Map<String, ManagedObject> managedObjects) throws DeploymentException {
    ManagedObjectFactory factory = ManagedObjectFactoryBuilder.create();
    Map<String, Object> attachments = unit.getAttachments();
    for (Object metaData : attachments.values()) {
        if (metaData instanceof Serializable) {
            Serializable smetaData = Serializable.class.cast(metaData);
            ManagedObject mo = factory.initManagedObject(smetaData, null, null);
            if (mo != null)
                managedObjects.put(mo.getName(), mo);
        }
    }
}
Example 101
Project: JEECQRS-JCommonDomain-Integration-master  File: EventReplayer.java View source code
public void replay(String bucketId) {
    log.log(Level.INFO, "Event Replayer replaying for bucket {0}", bucketId);
    Iterator<ChangeSet> it = persistence.allChanges(bucketId);
    while (it.hasNext()) {
        ChangeSet cs = it.next();
        Iterator<Serializable> eit = cs.events();
        while (eit.hasNext()) {
            Event e = (Event) eit.next();
            eventBus.dispatch(e);
        }
    }
}