Java Code Examples for org.apache.commons.lang3.SerializationUtils#serialize()

The following examples show how to use org.apache.commons.lang3.SerializationUtils#serialize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AttributeReleasePolicyTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void verifyServiceAttributeFilterAllAttributes() {
    final ReturnAllAttributeReleasePolicy policy = new ReturnAllAttributeReleasePolicy();
    final Principal p = mock(Principal.class);

    final Map<String, Object> map = new HashMap<>();
    map.put("attr1", "value1");
    map.put("attr2", "value2");
    map.put("attr3", Arrays.asList("v3", "v4"));

    when(p.getAttributes()).thenReturn(map);
    when(p.getId()).thenReturn("principalId");

    final Map<String, Object> attr = policy.getAttributes(p);
    assertEquals(attr.size(), map.size());

    final byte[] data = SerializationUtils.serialize(policy);
    final ReturnAllAttributeReleasePolicy p2 = SerializationUtils.deserialize(data);
    assertNotNull(p2);
}
 
Example 2
Source File: DefaultHasher.java    From metron with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * Returns a hash which has been encoded using the supplied encoder. If input is null then a string
 * containing all '0' will be returned. The length of the string is determined by the hashing algorithm
 * used.
 * @param toHash The value to hash.
 * @return A hash of {@code toHash} that has been encoded.
 * @throws EncoderException If unable to encode the hash then this exception occurs.
 * @throws NoSuchAlgorithmException If the supplied algorithm is not known.
 */
@Override
public String getHash(final Object toHash) throws EncoderException, NoSuchAlgorithmException {
  final MessageDigest messageDigest = MessageDigest.getInstance(algorithm);

  if (toHash == null) {
    return StringUtils.repeat("00", messageDigest.getDigestLength());
  } else if (toHash instanceof String) {
    return getHash(messageDigest, toHash.toString().getBytes(charset));
  } else if (toHash instanceof Serializable) {
    final byte[] serialized = SerializationUtils.serialize((Serializable) toHash);
    return getHash(messageDigest, serialized);
  }

  return null;
}
 
Example 3
Source File: MapList.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected E cloneElement(){
	E cloneObj;
	try {
		byte[] data = SerializationUtils.serialize((Serializable)element);
		cloneObj = SerializationUtils.deserialize(data);
	} catch (Exception e) {
		throw new RuntimeException("serializeClone error: " + e.getMessage(), e);
	} 
	return cloneObj;
}
 
Example 4
Source File: TransactionCommitRequestTest.java    From uphold-sdk-android with MIT License 5 votes vote down vote up
@Test
public void shouldBeSerializableTransactionCommitRequestWithMessageAndSecurityCode() {
    TransactionCommitRequest transactionCommitRequest = new TransactionCommitRequest("foo", "bar");
    byte[] serializedTransactionCommitRequestTest = SerializationUtils.serialize(transactionCommitRequest);
    TransactionCommitRequest deserializedTransactionCommitRequestTest = SerializationUtils.deserialize(serializedTransactionCommitRequestTest);

    Assert.assertEquals(transactionCommitRequest.getMessage(), deserializedTransactionCommitRequestTest.getMessage());
    Assert.assertEquals(transactionCommitRequest.getSecurityCode(), deserializedTransactionCommitRequestTest.getSecurityCode());
}
 
Example 5
Source File: ReserveTest.java    From uphold-sdk-android with MIT License 5 votes vote down vote up
@Test
public void shouldBeSerializable() {
    Reserve reserve = new Reserve();

    byte[] serializedReserve = SerializationUtils.serialize(reserve);
    Reserve deserializedReserve = SerializationUtils.deserialize(serializedReserve);

    Assert.assertTrue(reserve.getClass().equals(deserializedReserve.getClass()));
}
 
Example 6
Source File: ByteCompressionUtilsTest.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@Before
public void setup() throws UserException {
    job = new TaskFlowJob();
    job.setName(this.getClass().getName());
    job.addTask(new JavaTask());

    jobByte = SerializationUtils.serialize(job);
}
 
Example 7
Source File: TransactionCardDepositRequestTest.java    From uphold-sdk-android with MIT License 5 votes vote down vote up
@Test
public void shouldBeSerializable() {
    TransactionDenominationRequest transactionDenominationRequest = new TransactionDenominationRequest("fiz", "bar");
    TransactionCardDepositRequest transactionCardDepositRequest = new TransactionCardDepositRequest(transactionDenominationRequest, "foobar", "1234");
    byte[] serializedTransactionCardOriginRequestTest = SerializationUtils.serialize(transactionCardDepositRequest);
    TransactionCardDepositRequest deserializedTransactionCardDepositRequest = SerializationUtils.deserialize(serializedTransactionCardOriginRequestTest);

    Assert.assertEquals(transactionCardDepositRequest.getDenomination().getAmount(), deserializedTransactionCardDepositRequest.getDenomination().getAmount());
    Assert.assertEquals(transactionCardDepositRequest.getDenomination().getCurrency(), deserializedTransactionCardDepositRequest.getDenomination().getCurrency());
    Assert.assertEquals(transactionCardDepositRequest.getOrigin(), deserializedTransactionCardDepositRequest.getOrigin());
    Assert.assertEquals(transactionCardDepositRequest.getSecurityCode(), deserializedTransactionCardDepositRequest.getSecurityCode());
}
 
Example 8
Source File: SessionRedisRepository.java    From seed with Apache License 2.0 5 votes vote down vote up
/**
 * 存储Session数据到Redis3.x里面
 * <p>实际相当于更新Session数据</p>
 */
void save(MapSession session){
    if(null==session || null==session.getId()){
        LogUtil.getLogger().warn("session or sessionId is null");
        return;
    }
    LogUtil.getLogger().debug("save session-->[{}]", session.getId());
    byte[] key = this.getByteKey(session.getId());
    byte[] value = SerializationUtils.serialize(session);
    if(this.expireSeconds > 0){
        jedisCluster.setex(key, this.expireSeconds, value);
    }else{
        jedisCluster.set(key, value);
    }
}
 
Example 9
Source File: ShiroRedisSessionDao.java    From jee-universal-bms with Apache License 2.0 5 votes vote down vote up
/**
 * save session
 * @param session
 * @throws UnknownSessionException
 */
private void saveSession(Session session) throws UnknownSessionException{
    if(session == null || session.getId() == null){
        logger.error("session or session id is null");
        return;
    }

    byte[] key = getByteKey(session.getId());
    byte[] value = SerializationUtils.serialize((Serializable) session);
    session.setTimeout(sessionTimeout);
    this.redisManager.set(key, value, sessionTimeout);
}
 
Example 10
Source File: Stage.java    From incubator-nemo with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param stageId             ID of the stage.
 * @param taskIndices         indices of the tasks to execute.
 * @param irDag               the DAG of the task in this stage.
 * @param executionProperties set of {@link VertexExecutionProperty} for this stage
 * @param vertexIdToReadables the list of maps between vertex ID and {@link Readable}.
 */
public Stage(final String stageId,
             final List<Integer> taskIndices,
             final DAG<IRVertex, RuntimeEdge<IRVertex>> irDag,
             final ExecutionPropertyMap<VertexExecutionProperty> executionProperties,
             final List<Map<String, Readable>> vertexIdToReadables) {
  super(stageId);
  this.taskIndices = taskIndices;
  this.irDag = irDag;
  this.serializedIRDag = SerializationUtils.serialize(irDag);
  this.executionProperties = executionProperties;
  this.vertexIdToReadables = vertexIdToReadables;
}
 
Example 11
Source File: WebClient2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Background tasks that have been registered before the serialization should
 * wake up and run normally after the deserialization.
 * Until now (2.7-SNAPSHOT 17.09.09) HtmlUnit has probably never supported it.
 * This is currently not requested and this test is just to document the current status.
 * @throws Exception if an error occurs
 */
@Test
@NotYetImplemented
public void serialization_withJSBackgroundTasks() throws Exception {
    final String html =
          "<html><head>\n"
        + "<script>\n"
        + "  function foo() {\n"
        + "    if (window.name == 'hello') {\n"
        + "      alert('exiting');\n"
        + "      clearInterval(intervalId);\n"
        + "    }\n"
        + "  }\n"
        + "  var intervalId = setInterval(foo, 10);\n"
        + "</script></head>\n"
        + "<body></body></html>";
    final HtmlPage page = loadPageWithAlerts(html);
    // verify that 1 background job exists
    assertEquals(1, page.getEnclosingWindow().getJobManager().getJobCount());

    final byte[] bytes = SerializationUtils.serialize(page);
    page.getWebClient().close();

    // deserialize page and verify that 1 background job exists
    final HtmlPage clonedPage = (HtmlPage) SerializationUtils.deserialize(bytes);
    assertEquals(1, clonedPage.getEnclosingWindow().getJobManager().getJobCount());

    // configure a new CollectingAlertHandler (in fact it has surely already one and we could get and cast it)
    final List<String> collectedAlerts = Collections.synchronizedList(new ArrayList<String>());
    final AlertHandler alertHandler = new CollectingAlertHandler(collectedAlerts);
    clonedPage.getWebClient().setAlertHandler(alertHandler);

    // make some change in the page on which background script reacts
    clonedPage.getEnclosingWindow().setName("hello");

    clonedPage.getWebClient().waitForBackgroundJavaScriptStartingBefore(100);
    assertEquals(0, clonedPage.getEnclosingWindow().getJobManager().getJobCount());
    final String[] expectedAlerts = {"exiting"};
    assertEquals(expectedAlerts, collectedAlerts);
}
 
Example 12
Source File: SegmentQueryResult.java    From kylin with Apache License 2.0 4 votes vote down vote up
public void setCubeSegmentStatistics(CubeSegmentStatistics cubeSegmentStatistics) {
    this.cubeSegmentStatisticsBytes = (cubeSegmentStatistics == null ? null : SerializationUtils
            .serialize(cubeSegmentStatistics));
}
 
Example 13
Source File: DefaultBytePackConvert.java    From dog with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public byte[] objectToByteArray(TccContext obj) {

   return SerializationUtils.serialize(obj);
}
 
Example 14
Source File: TaskData.java    From pravega with Apache License 2.0 4 votes vote down vote up
public byte[] serialize() {
    return SerializationUtils.serialize(this);
}
 
Example 15
Source File: VPTreeSerializationTests.java    From deeplearning4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testSerialization_1() throws Exception {
    val points = Nd4j.rand(new int[] {10, 15});
    val treeA = new VPTree(points, true, 2);

    try (val bos = new ByteArrayOutputStream()) {
        SerializationUtils.serialize(treeA, bos);

        try (val bis = new ByteArrayInputStream(bos.toByteArray())) {
            VPTree treeB = SerializationUtils.deserialize(bis);

            assertEquals(points, treeA.getItems());
            assertEquals(points, treeB.getItems());

            assertEquals(treeA.getWorkers(), treeB.getWorkers());

            val row = points.getRow(1).dup('c');

            val dpListA = new ArrayList<DataPoint>();
            val dListA = new ArrayList<Double>();

            val dpListB = new ArrayList<DataPoint>();
            val dListB = new ArrayList<Double>();

            treeA.search(row, 3, dpListA, dListA);
            treeB.search(row, 3, dpListB, dListB);

            assertTrue(dpListA.size() != 0);
            assertTrue(dListA.size() != 0);

            assertEquals(dpListA.size(), dpListB.size());
            assertEquals(dListA.size(), dListB.size());

            for (int e = 0; e < dpListA.size(); e++) {
                val rA = dpListA.get(e).getPoint();
                val rB = dpListB.get(e).getPoint();

                assertEquals(rA, rB);
            }
        }
    }
}
 
Example 16
Source File: JDBCMailRepository.java    From james-project with Apache License 2.0 4 votes vote down vote up
private void insertMessage(Mail mc, Connection conn, MessageInputStream is) throws SQLException, IOException {
    String insertMessageSQL = sqlQueries.getSqlString("insertMessageSQL", true);
    try (PreparedStatement insertMessage = conn.prepareStatement(insertMessageSQL)) {
        int numberOfParameters = insertMessage.getParameterMetaData().getParameterCount();
        insertMessage.setString(1, mc.getName());
        insertMessage.setString(2, repositoryName);
        insertMessage.setString(3, mc.getState());
        insertMessage.setString(4, mc.getErrorMessage());
        if (mc.getMaybeSender().isNullSender()) {
            insertMessage.setNull(5, Types.VARCHAR);
        } else {
            insertMessage.setString(5, mc.getMaybeSender().get().toString());
        }
        StringBuilder recipients = new StringBuilder();
        for (Iterator<MailAddress> i = mc.getRecipients().iterator(); i.hasNext();) {
            recipients.append(i.next().toString());
            if (i.hasNext()) {
                recipients.append("\r\n");
            }
        }
        insertMessage.setString(6, recipients.toString());
        insertMessage.setString(7, mc.getRemoteHost());
        insertMessage.setString(8, mc.getRemoteAddr());
        if (mc.getPerRecipientSpecificHeaders().getHeadersByRecipient().isEmpty()) {
            insertMessage.setObject(9, null);
        } else {
            byte[] bytes = SerializationUtils.serialize(mc.getPerRecipientSpecificHeaders());
            insertMessage.setBinaryStream(9, new ByteArrayInputStream(bytes), bytes.length);
        }
        insertMessage.setTimestamp(10, new java.sql.Timestamp(mc.getLastUpdated().getTime()));

        insertMessage.setBinaryStream(11, is, (int) is.getSize());

        // Store attributes
        if (numberOfParameters > 11) {
            try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                 ObjectOutputStream oos = new ObjectOutputStream(baos)) {
                if (mc instanceof MailImpl) {
                    oos.writeObject(((MailImpl) mc).getAttributesRaw());
                } else {
                    Map<String, Serializable> temp = mc.attributes()
                            .collect(Guavate.toImmutableMap(
                                    attribute -> attribute.getName().asString(),
                                    attribute -> (Serializable) attribute.getValue().value()
                            ));

                    oos.writeObject(temp);
                }
                oos.flush();
                ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
                insertMessage.setBinaryStream(12, attrInputStream, baos.size());
            }
        }

        insertMessage.execute();
    }
}
 
Example 17
Source File: MessageDumpWriter.java    From a with Apache License 2.0 4 votes vote down vote up
public MessageDump toDumpMessage(Message msg) throws JMSException{
	
	MessageDump dump = new MessageDump();
	dump.JMSCorrelationID = msg.getJMSCorrelationID();
	dump.JMSMessageID = msg.getJMSMessageID();
	dump.JMSType = msg.getJMSType();
	dump.JMSDeliveryMode =  msg.getJMSDeliveryMode();
	dump.JMSExpiration = msg.getJMSExpiration();
	dump.JMSRedelivered = msg.getJMSRedelivered();
	dump.JMSTimestamp =  msg.getJMSTimestamp();
	dump.JMSPriority = msg.getJMSPriority();
	
	@SuppressWarnings("rawtypes")
	Enumeration propertyNames = msg.getPropertyNames();
	while(propertyNames.hasMoreElements()){
		String property = (String) propertyNames.nextElement();
		Object propertyValue = msg.getObjectProperty(property);
		if( propertyValue instanceof String){
			dump.stringProperties.put(property, (String)propertyValue);
		} else if ( propertyValue instanceof Integer ){
			dump.intProperties.put(property, (Integer)propertyValue);
		} else if ( propertyValue instanceof Long) {
			dump.longProperties.put(property, (Long)propertyValue);
		} else if( propertyValue instanceof Double) {
			dump.doubleProperties.put(property, (Double) propertyValue);
		} else if (propertyValue instanceof Short) {
			dump.shortProperties.put(property, (Short)propertyValue);
		} else if (propertyValue instanceof Float) {
			dump.floatProperties.put(property, (Float) propertyValue);
		} else if (propertyValue instanceof Byte) {
			dump.byteProperties.put(property, (Byte)propertyValue);
		} else if (propertyValue instanceof Boolean) {
			dump.boolProperties.put(property, (Boolean)propertyValue);
		} else if (propertyValue instanceof Serializable){
			// Object property.. if it's on Classpath and Serializable
			byte[] propBytes = SerializationUtils.serialize((Serializable) propertyValue);
			dump.objectProperties.put(property, Base64.encodeBase64String(propBytes));
		} else {
			// Corner case.
			throw new IllegalArgumentException("Property of key '"+ property +"' is not serializable. Type is: " + propertyValue.getClass().getCanonicalName());
		}
	}
	
	dump.body = "";
	dump.type = "";
	
	if (msg instanceof TextMessage) {
		dump.body = ((TextMessage)msg).getText();
		dump.type = "TextMessage";
	} else if (msg instanceof BytesMessage) {
		BytesMessage bm = (BytesMessage)msg;
		byte[] bytes = new byte[(int) bm.getBodyLength()];
		bm.readBytes(bytes);
		dump.body = Base64.encodeBase64String(bytes);
		dump.type = "BytesMessage";
	} else if (msg instanceof ObjectMessage) {
		ObjectMessage om = (ObjectMessage)msg;
		byte[] objectBytes = SerializationUtils.serialize(om.getObject());
		dump.body = Base64.encodeBase64String(objectBytes);
		dump.type = "ObjectMessage";
	}
	return dump;
}
 
Example 18
Source File: FileTypeTest.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
private void test(final FileType expected) {
    final byte[] serialized = SerializationUtils.serialize(expected);
    final FileType actualFileType = (FileType) SerializationUtils.deserialize(serialized);
    assertEquals(expected, actualFileType);
}
 
Example 19
Source File: SegmentQueryResult.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
public void setCubeSegmentStatistics(CubeSegmentStatistics cubeSegmentStatistics) {
    this.cubeSegmentStatisticsBytes = (cubeSegmentStatistics == null ? null : SerializationUtils
            .serialize(cubeSegmentStatistics));
}
 
Example 20
Source File: JdkMessageSerializer.java    From azeroth with Apache License 2.0 2 votes vote down vote up
/**
 * serialize
 *
 * @param topic topic associated with data
 * @param data  typed data
 * @return serialized bytes
 */
@Override
public byte[] serialize(String topic, Serializable data) {
    return SerializationUtils.serialize(data);
}