org.apache.commons.lang3.SerializationUtils Java Examples

The following examples show how to use org.apache.commons.lang3.SerializationUtils. 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 verifyServiceAttributeFilterAllowedAttributes() {
    final ReturnAllowedAttributeReleasePolicy policy = new ReturnAllowedAttributeReleasePolicy();
    policy.setAllowedAttributes(Arrays.asList("attr1", "attr3"));
    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(), 2);
    assertTrue(attr.containsKey("attr1"));
    assertTrue(attr.containsKey("attr3"));
    
    final byte[] data = SerializationUtils.serialize(policy);
    final ReturnAllowedAttributeReleasePolicy p2 = SerializationUtils.deserialize(data);
    assertNotNull(p2);
    assertEquals(p2.getAllowedAttributes(), policy.getAllowedAttributes());
}
 
Example #2
Source File: FSSpecStoreTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
protected Spec readSpecFromFile(Path path) throws IOException {
  if (path.getName().contains("fail")) {
    throw new IOException("Mean to fail in the test");
  } else if (path.getName().contains("serDeFail")) {

    // Simulate the way that a serDe exception
    FSDataInputStream fis = fs.open(path);
    SerializationUtils.deserialize(ByteStreams.toByteArray(fis));

    // This line should never be reached since we generate SerDe Exception on purpose.
    Assert.assertTrue(false);
    return null;
  }
  else return initFlowSpec(Files.createTempDir().getAbsolutePath());
}
 
Example #3
Source File: TaskExecutor.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    Thread.currentThread().setContextClassLoader(TaskThread.class.getClassLoader());
    executorDriver.sendStatusUpdate(Protos.TaskStatus.newBuilder().setTaskId(taskInfo.getTaskId()).setState(Protos.TaskState.TASK_RUNNING).build());
    Map<String, Object> data = SerializationUtils.deserialize(taskInfo.getData().toByteArray());
    ShardingContexts shardingContexts = (ShardingContexts) data.get("shardingContext");
    @SuppressWarnings("unchecked")
    JobConfigurationContext jobConfig = new JobConfigurationContext((Map<String, String>) data.get("jobConfigContext"));
    try {
        ElasticJob elasticJob = getElasticJobInstance(jobConfig);
        final CloudJobFacade jobFacade = new CloudJobFacade(shardingContexts, jobConfig, jobEventBus);
        if (jobConfig.isTransient()) {
            JobExecutorFactory.getJobExecutor(elasticJob, jobFacade).execute();
            executorDriver.sendStatusUpdate(Protos.TaskStatus.newBuilder().setTaskId(taskInfo.getTaskId()).setState(Protos.TaskState.TASK_FINISHED).build());
        } else {
            new DaemonTaskScheduler(elasticJob, jobConfig, jobFacade, executorDriver, taskInfo.getTaskId()).init();
        }
        // CHECKSTYLE:OFF
    } catch (final Throwable ex) {
        // CHECKSTYLE:ON
        log.error("Elastic-Job-Cloud-Executor error", ex);
        executorDriver.sendStatusUpdate(Protos.TaskStatus.newBuilder().setTaskId(taskInfo.getTaskId()).setState(Protos.TaskState.TASK_ERROR).setMessage(ExceptionUtil.transform(ex)).build());
        executorDriver.stop();
        throw ex;
    }
}
 
Example #4
Source File: KFoldCrossValidation.java    From NeurophFramework with Apache License 2.0 6 votes vote down vote up
@Override
public FoldResult call() throws Exception {
    // make a cloned copy of neural network
    NeuralNetwork neuralNet = SerializationUtils.clone(neuralNetwork);
    Evaluation evaluation = new Evaluation();
    evaluation.addEvaluator(new ErrorEvaluator(new MeanSquaredError()));
    if (neuralNetwork.getOutputsCount() == 1) {
        evaluation.addEvaluator(new ClassifierEvaluator.Binary(0.5)); // classification threshold 0.5
    } else {
        evaluation.addEvaluator(new ClassifierEvaluator.MultiClass(dataSet.getColumnNames()));
    }

    neuralNetwork.learn(trainingSet);

    EvaluationResult evaluationResult = evaluation.evaluate(neuralNet, validationSet);
    FoldResult foldResult = new FoldResult(neuralNet, trainingSet, validationSet);
    foldResult.setConfusionMatrix(evaluationResult.getConfusionMatrix());
    // todo: get mean and std of evaluation resulst and diferentialte regression anc classification

    allFoldsCompleted.countDown();

    return foldResult;
}
 
Example #5
Source File: SerializeUIView.java    From flow with Apache License 2.0 6 votes vote down vote up
public SerializeUIView() {
    Div label = new Div();
    label.setId("message");

    NativeButton button = createButton("Serialize", "serialize", event -> {
        UI ui = UI.getCurrent();
        try {
            byte[] serialize = SerializationUtils.serialize(ui);

            String result = serialize.length > 0 ?
                    "Successfully serialized ui" :
                    "Serialization failed";
            label.setText(result);
        }catch(SerializationException se) {
            label.setText(se.getMessage());
        }
    });

    add(label, button);
}
 
Example #6
Source File: BatchPayloadParser.java    From syncope with Apache License 2.0 6 votes vote down vote up
public static <T extends BatchItem> List<T> parse(
        final InputStream in,
        final MediaType multipartMixed,
        final T template) throws IOException {

    List<BatchPayloadLine> lines;
    try (BatchPayloadLineReader lineReader = new BatchPayloadLineReader(in, multipartMixed)) {
        lines = lineReader.read();
    }

    return split(lines, multipartMixed.getParameters().get(RESTHeaders.BOUNDARY_PARAMETER)).stream().
            map(bodyPart -> {
                LOG.debug("Body part:\n{}", bodyPart);

                T item = SerializationUtils.clone(template);

                consumeHeaders(bodyPart, item);
                item.setContent(
                        bodyPart.stream().map(BatchPayloadLine::toString).collect(Collectors.joining()));

                return item;
            }).collect(Collectors.toList());
}
 
Example #7
Source File: XrGrammarTest.java    From batfish with Apache License 2.0 6 votes vote down vote up
private @Nonnull CiscoXrConfiguration parseVendorConfig(String hostname) {
  String src = readResource(TESTCONFIGS_PREFIX + hostname, UTF_8);
  Settings settings = new Settings();
  configureBatfishTestSettings(settings);
  CiscoXrCombinedParser ciscoXrParser = new CiscoXrCombinedParser(src, settings);
  CiscoXrControlPlaneExtractor extractor =
      new CiscoXrControlPlaneExtractor(
          src, ciscoXrParser, ConfigurationFormat.CISCO_IOS_XR, new Warnings());
  ParserRuleContext tree =
      Batfish.parse(
          ciscoXrParser, new BatfishLogger(BatfishLogger.LEVELSTR_FATAL, false), settings);
  extractor.processParseTree(TEST_SNAPSHOT, tree);
  CiscoXrConfiguration vendorConfiguration =
      (CiscoXrConfiguration) extractor.getVendorConfiguration();
  vendorConfiguration.setFilename(TESTCONFIGS_PREFIX + hostname);
  // crash if not serializable
  return SerializationUtils.clone(vendorConfiguration);
}
 
Example #8
Source File: AddressRequestTest.java    From uphold-sdk-android with MIT License 5 votes vote down vote up
@Test
public void addressRequestShouldBeSerializable() {
    AddressRequest addressRequest = new AddressRequest("foo");
    byte[] serializedAddressRequest = SerializationUtils.serialize(addressRequest);
    AddressRequest deserializedAddressRequest = SerializationUtils.deserialize(serializedAddressRequest);

    Assert.assertEquals(addressRequest.getNetwork(), deserializedAddressRequest.getNetwork());
}
 
Example #9
Source File: EnumSingletonTest.java    From blog with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	System.out
			.println("Well, you think your EnumSingleton is really a singleton");

	System.out.println("The id of the INSTANCE object is "
			+ System.identityHashCode(EnumSingleton.INSTANCE));

	System.out.println("I will create another instance using reflection");
	Constructor<EnumSingleton> privateConstructor = EnumSingleton.class
			.getDeclaredConstructor(String.class, int.class);
	privateConstructor.setAccessible(true);
	try {
		privateConstructor.newInstance();
	} catch (IllegalArgumentException e) {
		System.out
				.println("D'oh! An exception prevented me from creating a new instance: "
						+ e.getMessage());
	}

	System.out.println("Hmm, I will try one more option - Serialisation");

	EnumSingleton clone = SerializationUtils.clone(EnumSingleton.INSTANCE);

	System.out.println("D'oh! Even serialization did not work. id = "
			+ System.identityHashCode(clone));

	System.out.println("I give up");
}
 
Example #10
Source File: MemcachedCacheManager.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T get(Object key, Class<T> type) {
    byte[] value = memcachedCache.get(key);
    if (value == null) {
        return null;
    }
    Object obj = SerializationUtils.deserialize(value);
    if (obj != null && type != null && !type.isInstance(value)) {
        throw new IllegalStateException(
                "Cached value is not of required type [" + type.getName() + "]: " + value);
    }
    return (T) obj;
}
 
Example #11
Source File: FastDateFormatTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testLang303() {
    Calendar cal = Calendar.getInstance();
    cal.set(2004,11,31);

    FastDateFormat format = FastDateFormat.getInstance("yyyy/MM/dd");
    String output = format.format(cal);

    format = (FastDateFormat) SerializationUtils.deserialize( SerializationUtils.serialize( format ) );
    assertEquals(output, format.format(cal));
}
 
Example #12
Source File: MemcachedChunkingCache.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public KeyHook lookupKeyHook(String keyS) {
    byte[] bytes = super.getBinary(keyS);
    if (bytes == null) {
        return null;
    }
    return (KeyHook) SerializationUtils.deserialize(bytes);
}
 
Example #13
Source File: DeviceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public DeviceDriverStateHolder loadDriverState(Device device) {
   Preconditions.checkNotNull(device, "device cannot be null");
   Preconditions.checkNotNull(device.getId(), "device must have an id");

   BoundStatement bound = new BoundStatement(loadState);
   Row r;
   try(Context ctxt = loadDriverStateTimer.time()) {
      r = session.execute(bound.bind(device.getId())).one();
   }

   if(r == null) {
      return null;
   }

   Map<String,String> encoded = r.getMap(NonEntityColumns.ATTRIBUTES, String.class, String.class);
   AttributeMap attributes = AttributeMap.newMap();
   for(Map.Entry<String, String> entry: encoded.entrySet()) {
      AttributeKey<?> key = key(entry.getKey());
      if(key == null) {
         continue;
      }
      Object value = deserialize(key, entry.getValue());
      // this shouldn't be necessary...
      attributes.add(key.coerceToValue(value));
   }


   Map<String,Object> variables = new HashMap<>();
   ByteBuffer buf = r.getBytes(NonEntityColumns.VARIABLES);
   if (buf != null) {
      variables = SerializationUtils.deserialize(Bytes.getArray(buf));
   }

   return new DeviceDriverStateHolder(attributes, variables);
}
 
Example #14
Source File: SegmentQueryCache.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public SegmentQueryResult get(String key) {
    byte[] value = memcachedCache.get(key);
    if (value == null) {
        return null;
    }
    return (SegmentQueryResult) (SerializationUtils.deserialize(value));
}
 
Example #15
Source File: Bgpv4RouteTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavaSerialization() {
  Bgpv4Route br =
      Bgpv4Route.builder()
          .setNetwork(Prefix.parse("1.1.1.0/24"))
          .setNextHopInterface("blah")
          .setOriginatorIp(Ip.parse("1.1.1.1"))
          .setOriginType(OriginType.IGP)
          .setProtocol(RoutingProtocol.BGP)
          .build();
  assertThat(SerializationUtils.clone(br), equalTo(br));
}
 
Example #16
Source File: Layer2VniTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavaSerialization() {
  SortedSet<Ip> bumTransportIps = ImmutableSortedSet.of(Ip.parse("2.2.2.2"), Ip.parse("2.2.2.3"));
  Layer2Vni vs =
      testBuilder()
          .setBumTransportIps(bumTransportIps)
          .setBumTransportMethod(BumTransportMethod.UNICAST_FLOOD_GROUP)
          .setSourceAddress(Ip.parse("1.2.3.4"))
          .setUdpPort(2345)
          .setVlan(7)
          .setVni(10007)
          .build();
  assertThat(SerializationUtils.clone(vs), equalTo(vs));
}
 
Example #17
Source File: EntityManagerFactoryCallableSerializationTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void serializationRoundTrip() {
    final Object em = SerializationUtils.deserialize(SerializationUtils.serialize(Serializable.class.cast(this.em)));
    assertTrue(EntityManager.class.isInstance(em));
    final ReloadableEntityManagerFactory factory = ReloadableEntityManagerFactory.class.cast(Reflections.get(em, "entityManagerFactory"));
    assertNotNull(factory.getDelegate());
    assertNotNull(Reflections.get(factory, "entityManagerFactoryCallable"));
}
 
Example #18
Source File: CardTest.java    From uphold-sdk-android with MIT License 5 votes vote down vote up
@Test
public void shouldBeSerializable() {
    HashMap<String, String> addressMap = new HashMap<>();
    List<Normalized> normalizedList = new ArrayList<>();

    addressMap.put("FOO", "BAR");
    normalizedList.add(new Normalized("foo", "bar", "foobar"));

    Settings settings = new Settings(1, true);
    Card card = new Card("foobar", addressMap, "foo", "bar", "foobar", "foobuz", "fiz", normalizedList, settings);

    byte[] serializedCard = SerializationUtils.serialize(card);
    Card deserializedCard = SerializationUtils.deserialize(serializedCard);

    Assert.assertEquals(card.getAddress().size(), deserializedCard.getAddress().size());
    Assert.assertEquals(card.getAddress().get("FOO"), deserializedCard.getAddress().get("FOO"));
    Assert.assertEquals(card.getAvailable(), deserializedCard.getAvailable());
    Assert.assertEquals(card.getBalance(), deserializedCard.getBalance());
    Assert.assertEquals(card.getCurrency(), deserializedCard.getCurrency());
    Assert.assertEquals(card.getId(), deserializedCard.getId());
    Assert.assertEquals(card.getLabel(), deserializedCard.getLabel());
    Assert.assertEquals(card.getLastTransactionAt(), deserializedCard.getLastTransactionAt());
    Assert.assertEquals(card.getNormalized().size(), deserializedCard.getNormalized().size());
    Assert.assertEquals(card.getNormalized().get(0).getAvailable(), deserializedCard.getNormalized().get(0).getAvailable());
    Assert.assertEquals(card.getNormalized().get(0).getBalance(), deserializedCard.getNormalized().get(0).getBalance());
    Assert.assertEquals(card.getNormalized().get(0).getCurrency(), deserializedCard.getNormalized().get(0).getCurrency());
    Assert.assertEquals(card.getSettings().getPosition(), deserializedCard.getSettings().getPosition());
    Assert.assertEquals(card.getSettings().getProtected(), deserializedCard.getSettings().getProtected());
    Assert.assertEquals(card.getSettings().getStarred(), deserializedCard.getSettings().getStarred());
}
 
Example #19
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 #20
Source File: AttributeReleasePolicyTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyAttributeFilterMappedAttributes() {
    final ReturnMappedAttributeReleasePolicy policy = new ReturnMappedAttributeReleasePolicy();
    final Map<String, String> mappedAttr = new HashMap<>();
    mappedAttr.put("attr1", "newAttr1");
    
    policy.setAllowedAttributes(mappedAttr);
            
    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(), 1);
    assertTrue(attr.containsKey("newAttr1"));
    
    final byte[] data = SerializationUtils.serialize(policy);
    final ReturnMappedAttributeReleasePolicy p2 = SerializationUtils.deserialize(data);
    assertNotNull(p2);
    assertEquals(p2.getAllowedAttributes(), policy.getAllowedAttributes());
}
 
Example #21
Source File: ConfigurationTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavaSerialization() {
  // TODO: other properties
  Map<String, CommunityMatchExpr> communityMatchExprs =
      ImmutableMap.of("cme", AllStandardCommunities.instance());
  Map<String, CommunitySetExpr> communitySetExprs =
      ImmutableMap.of("cse", new LiteralCommunitySet(CommunitySet.of(StandardCommunity.of(2L))));
  Map<String, CommunitySetMatchExpr> communitySetMatchExprs =
      ImmutableMap.of("csme", new HasCommunity(AllStandardCommunities.instance()));
  Map<String, CommunitySet> communitySets =
      ImmutableMap.of("cs", CommunitySet.of(StandardCommunity.of(1L)));
  Map<Location, LocationInfo> locationInfo =
      ImmutableMap.of(
          new InterfaceLocation("n", "i"),
          new LocationInfo(true, UniverseIpSpace.INSTANCE, EmptyIpSpace.INSTANCE));
  Configuration c = new Configuration("h", ConfigurationFormat.CISCO_IOS);
  c.setCommunityMatchExprs(communityMatchExprs);
  c.setCommunitySetExprs(communitySetExprs);
  c.setCommunitySetMatchExprs(communitySetMatchExprs);
  c.setCommunitySets(communitySets);
  c.setLocationInfo(locationInfo);
  Configuration cloned = SerializationUtils.clone(c);

  assertThat(cloned.getCommunityMatchExprs(), equalTo(communityMatchExprs));
  assertThat(cloned.getCommunitySetExprs(), equalTo(communitySetExprs));
  assertThat(cloned.getCommunitySetMatchExprs(), equalTo(communitySetMatchExprs));
  assertThat(cloned.getCommunitySets(), equalTo(communitySets));
  assertThat(cloned.getLocationInfo(), equalTo(locationInfo));
}
 
Example #22
Source File: LocalAsTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testEquals() {
  new EqualsTester()
      .addEqualityGroup(
          LocalAs.instance(),
          LocalAs.instance(),
          SerializationUtils.clone(LocalAs.instance()),
          BatfishObjectMapper.clone(LocalAs.instance(), AsExpr.class))
      .addEqualityGroup(3L)
      .testEquals();
}
 
Example #23
Source File: TunnelConfigurationTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavaSerialization() {
  TunnelConfiguration tc =
      TunnelConfiguration.builder()
          .setDestinationAddress(Ip.parse("1.1.1.1"))
          .setSourceAddress(Ip.parse("2.2.2.2"))
          .build();
  assertThat(SerializationUtils.clone(tc), equalTo(tc));
}
 
Example #24
Source File: RedisKeeperServerStateUnknownTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackup() throws IOException{
			
	//active
	KeeperMeta keeperMeta = SerializationUtils.clone(redisKeeperServer.getCurrentKeeperMeta());
	keeperMeta.setPort(keeperMeta.getPort() + 1);
	ShardStatus shardStatus = createShardStatus(keeperMeta, null, redisMasterMeta);
	unknown.setShardStatus(shardStatus);
	
	RedisKeeperServerState newState = redisKeeperServer.getRedisKeeperServerState();
	Assert.assertTrue(newState instanceof RedisKeeperServerStateBackup);
	Assert.assertEquals(new InetSocketAddress(keeperMeta.getIp(), keeperMeta.getPort()),
			newState.getMaster().getSocketAddress());
	
}
 
Example #25
Source File: PlatformHistory.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
public void addPlatformBuilder(PlatformBuilder platformBuilder) {
    if (platforms.stream().anyMatch(platform -> !platform.isDeleted && platform.getPlatformKey().equals(platformBuilder.buildPlatformKey()))) {
        throw new RuntimeException("Platform " + platformBuilder.getApplicationName() + "-" + platformBuilder.getPlatformName() + " already exists in platform history");
    }
    PlatformBuilder newPlatformBuilder = SerializationUtils.clone(platformBuilder);
    platforms.add(new PlatformTimestampedBuilders(newPlatformBuilder));
}
 
Example #26
Source File: MemcachedChunkingCache.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public KeyHook lookupKeyHook(String keyS) {
    byte[] bytes = super.getBinary(keyS);
    if (bytes == null) {
        return null;
    }
    return (KeyHook) SerializationUtils.deserialize(bytes);
}
 
Example #27
Source File: SimulatedTaskExecutor.java    From incubator-nemo with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the state of the task.
 *
 * @param taskId          of the task.
 * @param attemptIdx      of the task.
 * @param newState        of the task.
 * @param vertexPutOnHold the vertex put on hold.
 * @param cause           only provided as non-empty upon recoverable failures.
 */
private void onTaskStateChanged(final String taskId,
                                final int attemptIdx,
                                final TaskState.State newState,
                                final Optional<String> vertexPutOnHold,
                                final Optional<TaskState.RecoverableTaskFailureCause> cause) {
  this.sendMetric("TaskMetric", taskId,
    "stateTransitionEvent", SerializationUtils.serialize(new StateTransitionEvent<>(
      this.currentTime.get(), null, newState
    )));

  final ControlMessage.TaskStateChangedMsg.Builder msgBuilder =
    ControlMessage.TaskStateChangedMsg.newBuilder()
      .setExecutorId(executorRepresenter.getExecutorId())
      .setTaskId(taskId)
      .setAttemptIdx(attemptIdx)
      .setState(MessageUtils.convertState(newState));
  if (newState == TaskState.State.ON_HOLD && vertexPutOnHold.isPresent()) {
    msgBuilder.setVertexPutOnHoldId(vertexPutOnHold.get());
  }
  cause.ifPresent(c -> msgBuilder.setFailureCause(MessageUtils.convertFailureCause(c)));

  // Send taskStateChangedMsg to master!
  this.sendControlMessage(
    ControlMessage.Message.newBuilder()
      .setId(RuntimeIdManager.generateMessageId())
      .setListenerId(MessageEnvironment.RUNTIME_MASTER_MESSAGE_LISTENER_ID)
      .setType(ControlMessage.MessageType.TaskStateChanged)
      .setTaskStateChangedMsg(msgBuilder.build())
      .build());
}
 
Example #28
Source File: ShiroRedisCache.java    From jee-universal-bms with Apache License 2.0 5 votes vote down vote up
/**
 * 获得byte[]型的key
 * @param key
 * @return
 */
private byte[] getByteKey(K key){
    if(key instanceof String){
        String preKey = this.keyPrefix + key;
        return preKey.getBytes();
    }else{
        return SerializationUtils.serialize((Serializable) key);
    }
}
 
Example #29
Source File: BridgeTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavaSerialization() {
  Bridge bridge =
      Bridge.builder()
          .setPorts(ImmutableSet.of("a"))
          .setPvid(2)
          .setVids(IntegerSpace.of(2))
          .build();

  assertThat(SerializationUtils.clone(bridge), equalTo(bridge));
}
 
Example #30
Source File: SQLResponse.java    From kylin with Apache License 2.0 5 votes vote down vote up
@JsonIgnore
public List<QueryContext.CubeSegmentStatisticsResult> getCubeSegmentStatisticsList() {
    try {
        return queryStatistics == null ? Lists.<QueryContext.CubeSegmentStatisticsResult> newArrayList()
                : (List<QueryContext.CubeSegmentStatisticsResult>) SerializationUtils.deserialize(queryStatistics);
    } catch (Exception e) { // deserialize exception should not block query
        logger.warn("Error while deserialize queryStatistics due to " + e);
        return Lists.newArrayList();
    }
}