/**
  * @param type
  * @return
  */
 private String getTypeString(JType type) {
   String typeString =
       SerializationUtils.getRpcTypeName(type)
           + "/"
           + SerializationUtils.getSerializationSignature(typeOracle, type);
   return typeString;
 }
 @Test(expected = ClassCastException.class)
 public void testDeserializeClassCastException() {
   final String value = "Hello";
   final byte[] serialized = SerializationUtils.serialize(value);
   Assert.assertEquals(value, SerializationUtils.deserialize(serialized));
   // Causes ClassCastException in call site, not in SerializationUtils.deserialize
   @SuppressWarnings("unused") // needed to cause Exception
   final Integer i = SerializationUtils.deserialize(serialized);
 }
示例#3
0
 /**
  * Protect a specific value if it is considered mutable
  *
  * @param <S> the type of the value, which must be {@link Serializable}
  * @param value the value to protect if it is mutable (may be <tt>null</tt>)
  * @param immutableClasses a set of classes that can be considered immutable over and above the
  *     {@link #DEFAULT_IMMUTABLE_CLASSES default set}
  * @return a cloned instance (via serialization) or the instance itself, if immutable
  */
 @SuppressWarnings("unchecked")
 public static <S extends Serializable> S protectValue(S value, Set<Class<?>> immutableClasses) {
   if (!mustProtectValue(value, immutableClasses)) {
     return value;
   }
   // We have to clone it
   // No worries about the return type; it has to be the same as we put into the serializer
   return (S) SerializationUtils.deserialize(SerializationUtils.serialize(value));
 }
  /**
   * Writes a method to produce a map of class name to type string for Java.
   *
   * <pre>
   * private static Map&lt;String&lt;?&gt;, String&gt; loadSignaturesJava() {
   *   Map&lt;String&lt;?&gt;, String&gt; result = new HashMap&lt;String&lt;?&gt;, String&gt;();
   *   result.put(
   *       com.google.gwt.user.client.rpc.core.java.lang.String_FieldSerializer.concreteType(),
   *       &quot;java.lang.String/2004016611&quot;);
   *   ...
   *   return result;
   * }
   * </pre>
   */
  private void writeLoadSignaturesJava() {
    srcWriter.println("@SuppressWarnings(\"deprecation\")");
    srcWriter.println("private static Map<String, String> loadSignaturesJava() {");
    srcWriter.indent();
    srcWriter.println("Map<String, String> result = new HashMap<String, String>();");

    for (JType type : getSerializableTypes()) {
      String typeString = typeStrings.get(type);

      if (!serializationOracle.maybeInstantiated(type)
          && !deserializationOracle.maybeInstantiated(type)) {
        continue;
      }

      String typeRef;
      JClassType customSerializer =
          SerializableTypeOracleBuilder.findCustomFieldSerializer(typeOracle, type);
      if (customSerializer != null
          && CustomFieldSerializerValidator.getConcreteTypeMethod(customSerializer) != null) {
        typeRef = customSerializer.getQualifiedSourceName() + ".concreteType()";
      } else {
        typeRef = '"' + SerializationUtils.getRpcTypeName(type) + '"';
      }

      srcWriter.println("result.put(" + typeRef + ", \"" + typeString + "\");");
    }

    srcWriter.println("return result;");
    srcWriter.outdent();
    srcWriter.println("}");
    srcWriter.println();
  }
  /**
   * Writes a method to produce a map of type string -> class name of {@link TypeHandler} for Java.
   *
   * <pre>
   * private static Map&lt;String, String&gt; loadMethodsJava() {
   *   Map&lt;String, String&gt; result = new HashMap&lt;String, String&gt;();
   *   result.put(
   *       &quot;java.lang.String/2004016611&quot;,
   *       &quot;com.google.gwt.user.client.rpc.core.java.lang.String_FieldSerializer&quot;
   *   ...
   *   return result;
   * }
   * </pre>
   */
  private void writeLoadMethodsJava() {
    srcWriter.println("@SuppressWarnings(\"deprecation\")");
    srcWriter.println("private static Map<String, String> loadMethodsJava() {");
    srcWriter.indent();
    srcWriter.println("Map<String, String> result = new HashMap<String, String>();");

    List<JType> filteredTypes = new ArrayList<JType>();
    JType[] types = getSerializableTypes();
    int n = types.length;
    for (int index = 0; index < n; ++index) {
      JType type = types[index];
      if (serializationOracle.maybeInstantiated(type)
          || deserializationOracle.maybeInstantiated(type)) {
        filteredTypes.add(type);
      }
    }

    for (JType type : filteredTypes) {
      String typeString = typeStrings.get(type);
      assert typeString != null : "Missing type signature for " + type.getQualifiedSourceName();
      srcWriter.println(
          "result.put(\""
              + typeString
              + "\", \""
              + SerializationUtils.getStandardSerializerName((JClassType) type)
              + "\");");
    }

    srcWriter.println("return result;");
    srcWriter.outdent();
    srcWriter.println("}");
    srcWriter.println();
  }
 public void testDeserializeBytesBadStream() throws Exception {
   try {
     SerializationUtils.deserialize(new byte[0]);
   } catch (SerializationException ex) {
     return;
   }
   fail();
 }
 public void testDeserializeBytesNull() throws Exception {
   try {
     SerializationUtils.deserialize((byte[]) null);
   } catch (IllegalArgumentException ex) {
     return;
   }
   fail();
 }
 public void testDeserializeStreamNull() throws Exception {
   try {
     SerializationUtils.deserialize((InputStream) null);
   } catch (IllegalArgumentException ex) {
     return;
   }
   fail();
 }
 public void testSerializeStreamNullNull() throws Exception {
   try {
     SerializationUtils.serialize(null, null);
   } catch (IllegalArgumentException ex) {
     return;
   }
   fail();
 }
示例#10
0
  @Test
  public void testDates() throws Exception {
    Assert.assertEquals(
        Date.class, SerializationUtils.toObject(SerializationUtils.toJson(new Date())).getClass());

    // SerializationUtils.toJson(SerializationUtils.fromJson("{_action=null, _id={_inc=-1320293295,
    // _new=false, _time=1354236890, _machine=1951282283}, contents={id=xdIJbiV1BlSD, f=JsNOwXa1,
    // d=DQkP, e=Umj9n, b=p5d4wNOtPbs2QC5VQ9, c=Fize, a=0SVtbmBhlPbOw, in=e, z=r1I0vOMlEs,
    // y=f1mkaEna1L2iVdg, x=15}, metadata={touched={insertStage=Fri Nov 30 01:54:50 CET 2012,
    // sleepy1=Fri Nov 30 01:56:42 CET 2012, sleepy3=Fri Nov 30 01:56:42 CET 2012, sleepy4=Fri Nov
    // 30 01:56:41 CET 2012, sleepy5=Fri Nov 30 01:56:42 CET 2012, sleepy6=Fri Nov 30 01:56:41 CET
    // 2012, sleepy7=Fri Nov 30 01:56:42 CET 2012, sleepy8=Fri Nov 30 01:56:42 CET 2012, sleepy9=Fri
    // Nov 30 01:56:32 CET 2012}, fetched={sleepy1=Fri Nov 30 01:56:42 CET 2012, sleepy0=Fri Nov 30
    // 01:56:42 CET 2012, sleepy3=Fri Nov 30 01:56:42 CET 2012, sleepy4=Fri Nov 30 01:56:41 CET
    // 2012, sleepy5=Fri Nov 30 01:56:41 CET 2012, sleepy6=Fri Nov 30 01:56:41 CET 2012, sleepy7=Fri
    // Nov 30 01:56:42 CET 2012, sleepy8=Fri Nov 30 01:56:42 CET 2012, sleepy9=Fri Nov 30 01:56:32
    // CET 2012}}}"));
  }
 public void testCloneUnserializable() throws Exception {
   try {
     iMap.put(new Object(), new Object());
     SerializationUtils.clone(iMap);
   } catch (SerializationException ex) {
     return;
   }
   fail();
 }
示例#12
0
 protected String computeTypeNameExpression(JType paramType) {
   String typeName;
   if (typeStrings.containsKey(paramType)) {
     typeName = typeStrings.get(paramType);
   } else {
     typeName = SerializationUtils.getRpcTypeName(paramType);
   }
   return typeName == null ? null : ('"' + typeName + '"');
 }
 @Test
 public void testSerializeStreamObjNull() throws Exception {
   try {
     SerializationUtils.serialize(iMap, null);
   } catch (final IllegalArgumentException ex) {
     return;
   }
   fail();
 }
 @Test
 public void testDeserializeStreamBadStream() throws Exception {
   try {
     SerializationUtils.deserialize(new ByteArrayInputStream(new byte[0]));
   } catch (final SerializationException ex) {
     return;
   }
   fail();
 }
 public void testSerializeStreamUnserializable() throws Exception {
   ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
   try {
     iMap.put(new Object(), new Object());
     SerializationUtils.serialize(iMap, streamTest);
   } catch (SerializationException ex) {
     return;
   }
   fail();
 }
  public void testDeserializeBytesOfNull() throws Exception {
    ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(streamReal);
    oos.writeObject(null);
    oos.flush();
    oos.close();

    Object test = SerializationUtils.deserialize(streamReal.toByteArray());
    assertNull(test);
  }
  @Test
  public void testWriteRead() {
    DataSetIterator iter = new IrisDataSetIterator(150, 150);
    String irisData = "irisData.dat";

    DataSet freshDataSet = iter.next(150);

    SerializationUtils.saveObject(freshDataSet, new File(irisData));

    DataSet readDataSet = SerializationUtils.readObject(new File(irisData));

    assertEquals(freshDataSet.getFeatureMatrix(), readDataSet.getFeatureMatrix());
    assertEquals(freshDataSet.getLabels(), readDataSet.getLabels());
    try {
      FileUtils.forceDelete(new File(irisData));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 @Test
 public void testSerializeBytesUnserializable() throws Exception {
   try {
     iMap.put(new Object(), new Object());
     SerializationUtils.serialize(iMap);
   } catch (final SerializationException ex) {
     return;
   }
   fail();
 }
示例#19
0
  @Test
  public void testForFunction_Serializable() {
    Navigator<Integer> navigator =
        SerializationUtils.serializedCopy(
            Navigators.forFunction(ImmutableSet.of(1, 2, 3), new MyFun()));

    assertEquals(ImmutableSet.of(1, 2, 3), ImmutableSet.copyOf(navigator.domain()));
    assertEquals(ImmutableSet.of(2, 2), ImmutableSet.copyOf(navigator.related(1)));
    assertEquals(ImmutableSet.of(4, 3), ImmutableSet.copyOf(navigator.related(2)));
    assertEquals(ImmutableSet.of(6, 4), ImmutableSet.copyOf(navigator.related(3)));
  }
  @Override
  public Object deserialize(byte[] bytes) throws SerializationException {
    if (SerializationUtils.isEmpty(bytes)) {
      return null;
    }

    try {
      return unmarshaller.unmarshal(new StreamSource(new ByteArrayInputStream(bytes)));
    } catch (Exception ex) {
      throw new SerializationException("Cannot deserialize bytes", ex);
    }
  }
 public void testClone() throws Exception {
   Object test = SerializationUtils.clone(iMap);
   assertNotNull(test);
   assertTrue(test instanceof HashMap);
   assertTrue(test != iMap);
   HashMap testMap = (HashMap) test;
   assertEquals(iString, testMap.get("FOO"));
   assertTrue(iString != testMap.get("FOO"));
   assertEquals(iInteger, testMap.get("BAR"));
   assertTrue(iInteger != testMap.get("BAR"));
   assertEquals(iMap, testMap);
 }
  public void testDeserializeStreamClassNotFound() throws Exception {
    ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(streamReal);
    oos.writeObject(new ClassNotFoundSerialization());
    oos.flush();
    oos.close();

    ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
    try {
      Object test = SerializationUtils.deserialize(inTest);
    } catch (SerializationException se) {
      assertEquals("java.lang.ClassNotFoundException: " + CLASS_NOT_FOUND_MESSAGE, se.getMessage());
    }
  }
示例#23
0
  protected void generateTypeHandlers(
      TreeLogger logger,
      GeneratorContextExt context,
      SerializableTypeOracle typesSentFromBrowser,
      SerializableTypeOracle typesSentToBrowser)
      throws UnableToCompleteException {
    Event event = SpeedTracerLogger.start(CompilerEventType.GENERATOR_RPC_TYPE_SERIALIZER);
    TypeSerializerCreator tsc =
        new TypeSerializerCreator(
            logger,
            typesSentFromBrowser,
            typesSentToBrowser,
            context,
            SerializationUtils.getTypeSerializerQualifiedName(serviceIntf),
            SerializationUtils.getTypeSerializerSimpleName(serviceIntf));
    tsc.realize(logger);
    event.end();

    typeStrings = new HashMap<JType, String>(tsc.getTypeStrings());
    typeStrings.put(serviceIntf, TypeNameObfuscator.SERVICE_INTERFACE_ID);

    cachedTypeLastModifiedTimes = tsc.getTypeLastModifiedTimeMap();
  }
 public void testSerializeIOException() throws Exception {
   // forces an IOException when the ObjectOutputStream is created, to test not closing the stream
   // in the finally block
   OutputStream streamTest =
       new OutputStream() {
         public void write(int arg0) throws IOException {
           throw new IOException(SERIALIZE_IO_EXCEPTION_MESSAGE);
         }
       };
   try {
     SerializationUtils.serialize(iMap, streamTest);
   } catch (SerializationException e) {
     assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage());
   }
 }
  public void testSerializeBytesNull() throws Exception {
    byte[] testBytes = SerializationUtils.serialize(null);

    ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(streamReal);
    oos.writeObject(null);
    oos.flush();
    oos.close();

    byte[] realBytes = streamReal.toByteArray();
    assertEquals(testBytes.length, realBytes.length);
    for (int i = 0; i < realBytes.length; i++) {
      assertEquals(realBytes[i], testBytes[i]);
    }
  }
示例#26
0
 private void readValues(boolean ignoreEof) throws IOException {
   int control = input.read();
   if (control == -1) {
     if (!ignoreEof) {
       throw new EOFException("Read past end of RLE integer from " + input);
     }
     used = numLiterals = 0;
     return;
   } else if (control < 0x80) {
     numLiterals = control + RunLengthIntegerWriter.MIN_REPEAT_SIZE;
     used = 0;
     repeat = true;
     delta = input.read();
     if (delta == -1) {
       throw new EOFException("End of stream in RLE Integer from " + input);
     }
     // convert from 0 to 255 to -128 to 127 by converting to a signed byte
     delta = (byte) (0 + delta);
     if (signed) {
       literals[0] = utils.readVslong(input);
     } else {
       literals[0] = utils.readVulong(input);
     }
   } else {
     repeat = false;
     numLiterals = 0x100 - control;
     used = 0;
     for (int i = 0; i < numLiterals; ++i) {
       if (signed) {
         literals[i] = utils.readVslong(input);
       } else {
         literals[i] = utils.readVulong(input);
       }
     }
   }
 }
  public void testDeserializeBytes() throws Exception {
    ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(streamReal);
    oos.writeObject(iMap);
    oos.flush();
    oos.close();

    Object test = SerializationUtils.deserialize(streamReal.toByteArray());
    assertNotNull(test);
    assertTrue(test instanceof HashMap);
    assertTrue(test != iMap);
    HashMap testMap = (HashMap) test;
    assertEquals(iString, testMap.get("FOO"));
    assertTrue(iString != testMap.get("FOO"));
    assertEquals(iInteger, testMap.get("BAR"));
    assertTrue(iInteger != testMap.get("BAR"));
    assertEquals(iMap, testMap);
  }
  @Test
  public void testSerializeStream() throws Exception {
    final ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
    SerializationUtils.serialize(iMap, streamTest);

    final ByteArrayOutputStream streamReal = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(streamReal);
    oos.writeObject(iMap);
    oos.flush();
    oos.close();

    final byte[] testBytes = streamTest.toByteArray();
    final byte[] realBytes = streamReal.toByteArray();
    assertEquals(testBytes.length, realBytes.length);
    for (int i = 0; i < realBytes.length; i++) {
      assertEquals(realBytes[i], testBytes[i]);
    }
  }
  @Test
  public void testPrimitiveTypeClassSerialization() {
    final Class<?>[] primitiveTypes = {
      byte.class,
      short.class,
      int.class,
      long.class,
      float.class,
      double.class,
      boolean.class,
      char.class,
      void.class
    };

    for (final Class<?> primitiveType : primitiveTypes) {
      final Class<?> clone = SerializationUtils.clone(primitiveType);
      assertEquals(primitiveType, clone);
    }
  }
  /*
   * check whether we can use a previously generated version of a
   * FieldSerializer.  If so, mark it for reuse, and return true.
   * Otherwise return false.
   */
  private boolean findCacheableFieldSerializerAndMarkForReuseIfAvailable(
      GeneratorContextExt ctx, JType type) {

    CachedRebindResult lastResult = ctx.getCachedGeneratorResult();
    if (lastResult == null || !ctx.isGeneratorResultCachingEnabled()) {
      return false;
    }

    String fieldSerializerName = SerializationUtils.getStandardSerializerName((JClassType) type);

    if (type instanceof JClassType) {
      // check that it is available for reuse
      if (!lastResult.isTypeCached(fieldSerializerName)) {
        return false;
      }
    } else {
      return false;
    }

    try {
      /*
       * TODO(jbrosenberg): Change this check to use getVersion() from
       * TypeOracle, once that is available.
       */
      long lastModified = ctx.getSourceLastModifiedTime((JClassType) type);

      if (lastModified != 0L && lastModified < lastResult.getTimeGenerated()) {

        // use cached version
        return ctx.reuseTypeFromCacheIfAvailable(fieldSerializerName);
      }
    } catch (RuntimeException ex) {
      // could get an exception checking modified time
    }

    return false;
  }