Esempio n. 1
0
  @Test
  public void testOutputFormatVertex() {
    try {
      final TestingOutputFormat outputFormat = new TestingOutputFormat();
      final OutputFormatVertex of = new OutputFormatVertex("Name");
      new TaskConfig(of.getConfiguration())
          .setStubWrapper(new UserCodeObjectWrapper<OutputFormat<?>>(outputFormat));
      final ClassLoader cl = getClass().getClassLoader();

      try {
        of.initializeOnMaster(cl);
        fail("Did not throw expected exception.");
      } catch (TestException e) {
        // all good
      }

      OutputFormatVertex copy = SerializationUtils.clone(of);
      try {
        copy.initializeOnMaster(cl);
        fail("Did not throw expected exception.");
      } catch (TestException e) {
        // all good
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
Esempio n. 2
0
  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");
  }
Esempio n. 3
0
  @Override
  public final IFuzzyValue<Boolean> execute(
      final IContext p_context,
      final boolean p_parallel,
      final List<ITerm> p_argument,
      final List<ITerm> p_return,
      final List<ITerm> p_annotation) {
    final Key l_key = p_argument.get(0).raw();
    final EAlgorithm l_algorithm = EAlgorithm.from(l_key.getAlgorithm());

    p_argument
        .subList(1, p_argument.size())
        .stream()
        .map(i -> Base64.getDecoder().decode(i.<String>raw()))
        .map(
            i -> {
              try {
                return l_algorithm.getDecryptCipher(l_key).doFinal(i);
              } catch (final NoSuchPaddingException
                  | NoSuchAlgorithmException
                  | InvalidKeyException
                  | BadPaddingException
                  | IllegalBlockSizeException l_exception) {
                return null;
              }
            })
        .filter(Objects::nonNull)
        .map(i -> CRawTerm.from(SerializationUtils.deserialize(i)))
        .forEach(p_return::add);

    return CFuzzyValue.from(true);
  }
Esempio n. 4
0
 /** Carregamento de cache do disco. */
 public static void load() {
   long time = System.currentTimeMillis();
   File file = new File("./data/owner.map");
   if (file.exists()) {
     try {
       HashMap<String, Object> map;
       FileInputStream fileInputStream = new FileInputStream(file);
       try {
         map = SerializationUtils.deserialize(fileInputStream);
       } finally {
         fileInputStream.close();
       }
       for (String key : map.keySet()) {
         Object value = map.get(key);
         if (value instanceof Owner) {
           Owner owner = (Owner) value;
           put(key, owner);
         }
       }
       Server.logLoad(time, file);
     } catch (Exception ex) {
       Server.logError(ex);
     }
   }
 }
  @Test
  public void testLimitedView() throws IOException {
    File file = folder.newFile();
    FileChannel chan = new RandomAccessFile(file, "rw").getChannel();
    BinaryIndexTableWriter writer = BinaryIndexTableWriter.create(BinaryFormat.create(), chan, 3);
    writer.writeEntry(12, new int[] {0});
    writer.writeEntry(17, new int[] {1, 3});
    writer.writeEntry(19, new int[] {4, 5});

    MappedByteBuffer buffer = chan.map(FileChannel.MapMode.READ_ONLY, 0, chan.size());
    BinaryIndexTable tbl = BinaryIndexTable.fromBuffer(3, buffer);
    tbl = tbl.createLimitedView(2);
    assertThat(tbl.getKeys(), hasSize(2));
    assertThat(tbl.getKeys(), contains(12L, 17L));
    assertThat(tbl.getEntry(12), contains(0));
    assertThat(tbl.getEntry(17), contains(1));
    assertThat(tbl.getEntry(19), nullValue());
    assertThat(tbl.getEntry(-1), nullValue());

    BinaryIndexTable serializedTbl = SerializationUtils.clone(tbl);
    assertThat(serializedTbl.getKeys(), hasSize(2));
    assertThat(serializedTbl.getKeys(), contains(12L, 17L));
    assertThat(serializedTbl.getEntry(12), contains(0));
    assertThat(serializedTbl.getEntry(17), contains(1));
    assertThat(serializedTbl.getEntry(19), nullValue());
    assertThat(serializedTbl.getEntry(-1), nullValue());
  }
  @Test
  public void testStoringSecretKeys() throws IOException {
    final AesCipherService cipherService = new AesCipherService();
    cipherService.setKeySize(AESKeySizes.KEY_SIZE_256);

    final Key key = cipherService.generateNewKey();
    final byte[] keyBytes = SerializationUtils.serialize(key);
    final ByteString keyByteString = ByteString.copyFrom(keyBytes);

    final String keyName = "GLOBAL";
    final SecretKeys keys =
        SecretKeys.newBuilder().putAllKeys(ImmutableMap.of(keyName, keyByteString)).build();

    final EncryptionService service1 = new EncryptionServiceImpl(cipherService, toKeyMap(keys));

    final byte[] encryptedData = service1.encrypt("data".getBytes(), keyName);
    assertThat("data", is(new String(service1.decrypt(encryptedData, keyName))));

    final File secretKeysFile = new File("build/temp/secretKeys");
    secretKeysFile.getParentFile().mkdirs();
    try (final OutputStream os = new FileOutputStream(secretKeysFile)) {
      keys.writeTo(os);
    }

    final AesCipherService cipherService2 = new AesCipherService();
    cipherService2.setKeySize(AESKeySizes.KEY_SIZE_256);
    try (final InputStream is = new FileInputStream(secretKeysFile)) {
      final EncryptionService service2 =
          new EncryptionServiceImpl(cipherService2, toKeyMap(SecretKeys.parseFrom(is)));
      assertThat("data", is(new String(service2.decrypt(encryptedData, keyName))));
    }
  }
 private void updateReviewDataInternal(Serializable results) {
   String selection = MovieContract.MovieEntry.COLUMN_MOVIE_ID + "=?";
   String[] selectionArgs = new String[] {mMovieId.toString()};
   ContentValues cv = new ContentValues();
   cv.put(MovieContract.MovieEntry.COLUMN_MOVIE_REVIEWS, SerializationUtils.serialize(results));
   getActivity()
       .getContentResolver()
       .update(MovieContract.MovieEntry.buildUriReviews(mMovieId), cv, selection, selectionArgs);
 }
 @SuppressWarnings("unchecked")
 @Override
 public T getUserCodeObject() {
   // return a clone because some code retrieves this and runs configure() on it before
   // the job is actually run. This way we can always hand out a pristine copy.
   Serializable ser = (Serializable) userCodeObject;
   T cloned = (T) SerializationUtils.clone(ser);
   return cloned;
 }
Esempio n. 9
0
 /** Carregamento de cache do disco. */
 public static synchronized void load() {
   Server.logDebug("Loading handle.map...");
   File file = new File("handle.map");
   if (file.exists()) {
     try {
       FileInputStream fileInputStream = new FileInputStream(file);
       try {
         HashMap<String, Handle> map = SerializationUtils.deserialize(fileInputStream);
         HANDLE_MAP.putAll(map);
       } finally {
         fileInputStream.close();
       }
     } catch (Exception ex) {
       Server.logError(ex);
     }
   }
 }
Esempio n. 10
0
 /** Armazenamento de cache em disco. */
 public static synchronized void store() {
   if (HANDLE_CHANGED) {
     try {
       Server.logDebug("Storing handle.map...");
       FileOutputStream outputStream = new FileOutputStream("handle.map");
       try {
         SerializationUtils.serialize(HANDLE_MAP, outputStream);
         // Atualiza flag de atualização.
         HANDLE_CHANGED = false;
       } finally {
         outputStream.close();
       }
     } catch (Exception ex) {
       Server.logError(ex);
     }
   }
 }
Esempio n. 11
0
 /** Carregamento de cache do disco. */
 public static synchronized void load() {
   long time = System.currentTimeMillis();
   File file = new File("owner.map");
   if (file.exists()) {
     try {
       HashMap<String, Owner> map;
       FileInputStream fileInputStream = new FileInputStream(file);
       try {
         map = SerializationUtils.deserialize(fileInputStream);
       } finally {
         fileInputStream.close();
       }
       OWNER_MAP.putAll(map);
       Server.logLoad(time, file);
     } catch (Exception ex) {
       Server.logError(ex);
     }
   }
 }
Esempio n. 12
0
 /** Armazenamento de cache em disco. */
 public static synchronized void store() {
   if (OWNER_CHANGED) {
     try {
       long time = System.currentTimeMillis();
       File file = new File("owner.map");
       FileOutputStream outputStream = new FileOutputStream(file);
       try {
         SerializationUtils.serialize(OWNER_MAP, outputStream);
         // Atualiza flag de atualização.
         OWNER_CHANGED = false;
       } finally {
         outputStream.close();
       }
       Server.logStore(time, file);
     } catch (Exception ex) {
       Server.logError(ex);
     }
   }
 }
Esempio n. 13
0
 /** Armazenamento de cache em disco. */
 public static void store() {
   if (OWNER_CHANGED) {
     try {
       long time = System.currentTimeMillis();
       HashMap<String, Owner> map = getMap();
       File file = new File("./data/owner.map");
       FileOutputStream outputStream = new FileOutputStream(file);
       try {
         SerializationUtils.serialize(map, outputStream);
         // Atualiza flag de atualização.
         OWNER_CHANGED = false;
       } finally {
         outputStream.close();
       }
       Server.logStore(time, file);
     } catch (Exception ex) {
       Server.logError(ex);
     }
   }
 }
  @Override
  public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    Uri uri = ((CursorLoader) loader).getUri();
    if (!data.moveToFirst()) data = null;
    int match = sUriMatcher.match(uri);
    switch (match) {
      case MovieProvider.MOVIE_WITH_ID:
        mMovieAdapter.swapCursor(data);
        Log.v(LOG_TAG, "In onLoadFinished Movie ");
        if (!movieDetailsModified.get()) {
          if (data == null || !data.moveToFirst()) {
            Toast.makeText(
                    getContext(),
                    "No Data Loaded. Please go back and select movie again",
                    Toast.LENGTH_LONG)
                .show();
            getActivity().onBackPressed();
            return;
          }
          mMovieData = SerializationUtils.deserialize(data.getBlob(1));
          movieRowId = data.getLong(MovieQuery.COL_MOVIEID);
          mMovieId = mMovieData.id;
          title = mMovieData.original_title;
          Log.v(LOG_TAG, "Movie Title = " + title);
          ((TextView) rootView.findViewById(R.id.title_text)).setText(title);

          ImageView imageView = (ImageView) rootView.findViewById(R.id.imageView);
          Picasso.with(getContext())
              .load(String.format(sImgUrl, sImgSize, mMovieData.poster_path))
              .error(R.drawable.abc_btn_rating_star_off_mtrl_alpha)
              // .fit()
              .into(imageView);

          if (data.getInt(3) <= 0) movieMinutesModified.set(false);
          else {
            movieMinutesModified.set(true);
            ((TextView) rootView.findViewById(R.id.runtime_text))
                .setText(Integer.toString(data.getInt(MovieQuery.COL_MOVIE_RUNTIME)) + "min");
          }

          String mMovieVoteAverage = Double.toString(mMovieData.vote_average);

          ((TextView) rootView.findViewById(R.id.voteaverage_text))
              .setText(mMovieVoteAverage + "/10");
          Float f = Float.parseFloat(mMovieVoteAverage);
          ((RatingBar) rootView.findViewById(R.id.ratingBar)).setRating(f);

          ((TextView) rootView.findViewById(R.id.release_text))
              .setText(Utility.getYear(mMovieData.release_date));

          btnToggle = (Button) rootView.findViewById(R.id.chkState);
          if (data.getInt(MovieQuery.COL_MOVIE_FAVOURITE) != 0) btnToggle.setText("Favourite");
          else btnToggle.setText("Mark as Favourite");

          ((TextView) rootView.findViewById(R.id.overview_text)).setText(mMovieData.overview);

          movieDetailsModified.set(true);
          if (!movieMinutesModified.get()) {
            updateMinutesDataOrAskServer(data);
          }
          Log.v(LOG_TAG, "Out of Load Finish Movie");
        }
        break;
      case MovieProvider.MOVIE_TRAILERS:
        Log.v(LOG_TAG, "In Trailer load finish loader");
        if (!trailerDataModified.get()) updateTrailerDataOrAskServer(data);
        Log.v(LOG_TAG, "out Trailer load finish loader");
        break;
      case MovieProvider.MOVIE_REVIEWS:
        Log.v(LOG_TAG, "In Review load finish loader");
        if (!reviewDataModified.get()) updateReviewDataOrAskServer(data);
        Log.v(LOG_TAG, "out Review load finish loader");
        break;
    }
  }
 public byte[] serialise(final Serializable o) {
   return org.apache.commons.lang3.SerializationUtils.serialize(o);
 }
 public Object deserialise(final byte[] bytes) {
   return org.apache.commons.lang3.SerializationUtils.deserialize(bytes);
 }
Esempio n. 17
0
 /** @return the deep copy of the internal <code>Properties</code> of this TachyonConf instance. */
 public Properties getInternalProperties() {
   return SerializationUtils.clone(mProperties);
 }
  @Test
  public void shouldBeSerializable() {
    Denomination denomination = new Denomination("foo", "bar", "fuz", "buz");
    Destination destination =
        new Destination(
            "fizbiz", "foobar", "biz", "foobiz", "foobuz", "fizbuz", "fizbiz", "foo", "bar", "fiz",
            "biz", "buz");
    Fee fee = new Fee("foo", "bar", "fuz", "buz", "biz");
    List<Fee> fees = new ArrayList<>();
    List<Normalized> normalizeds = new ArrayList<>();
    List<Source> sources = new ArrayList<>();
    Origin origin =
        new Origin(
            "biz", "foo", "fiz", "bar", "foobar", "foobiz", "fiz", "biz", "fuzbuz", "fuz", sources,
            "buz", "FOOBAR");
    Parameters parameters =
        new Parameters("foobar", "foobiz", "foobuz", "fizbiz", "fuz", "fiz", 1, "foo", "bar");
    Normalized normalized = new Normalized("foo", "bar", "fiz", "biz", "fixbiz");
    Source source = new Source("FUZBUZ", "FIZBIZ");
    Transaction transaction =
        new Transaction(
            "foobar",
            "foobiz",
            denomination,
            destination,
            fees,
            "fuzbuz",
            "qux",
            normalizeds,
            origin,
            parameters,
            "fizbiz",
            "foobuz",
            "foo");

    fees.add(fee);
    normalizeds.add(normalized);
    sources.add(source);

    byte[] serializedTransaction = SerializationUtils.serialize(transaction);
    Transaction deserializedTransaction = SerializationUtils.deserialize(serializedTransaction);

    Assert.assertEquals(transaction.getCreatedAt(), deserializedTransaction.getCreatedAt());
    Assert.assertEquals(
        transaction.getDenomination().getAmount(),
        deserializedTransaction.getDenomination().getAmount());
    Assert.assertEquals(
        transaction.getDenomination().getCurrency(),
        deserializedTransaction.getDenomination().getCurrency());
    Assert.assertEquals(
        transaction.getDenomination().getPair(),
        deserializedTransaction.getDenomination().getPair());
    Assert.assertEquals(
        transaction.getDenomination().getRate(),
        deserializedTransaction.getDenomination().getRate());
    Assert.assertEquals(
        transaction.getDestination().getAccountId(),
        deserializedTransaction.getDestination().getAccountId());
    Assert.assertEquals(
        transaction.getDestination().getAccountType(),
        deserializedTransaction.getDestination().getAccountType());
    Assert.assertEquals(
        transaction.getDestination().getAmount(),
        deserializedTransaction.getDestination().getAmount());
    Assert.assertEquals(
        transaction.getDestination().getBase(), deserializedTransaction.getDestination().getBase());
    Assert.assertEquals(
        transaction.getDestination().getCardId(),
        deserializedTransaction.getDestination().getCardId());
    Assert.assertEquals(
        transaction.getDestination().getCommission(),
        deserializedTransaction.getDestination().getCommission());
    Assert.assertEquals(
        transaction.getDestination().getCurrency(),
        deserializedTransaction.getDestination().getCurrency());
    Assert.assertEquals(
        transaction.getDestination().getDescription(),
        deserializedTransaction.getDestination().getDescription());
    Assert.assertEquals(
        transaction.getDestination().getFee(), deserializedTransaction.getDestination().getFee());
    Assert.assertEquals(
        transaction.getDestination().getRate(), deserializedTransaction.getDestination().getRate());
    Assert.assertEquals(
        transaction.getDestination().getType(), deserializedTransaction.getDestination().getType());
    Assert.assertEquals(
        transaction.getDestination().getUsername(),
        deserializedTransaction.getDestination().getUsername());
    Assert.assertEquals(
        transaction.getFees().get(0).getAmount(),
        deserializedTransaction.getFees().get(0).getAmount());
    Assert.assertEquals(
        transaction.getFees().get(0).getCurrency(),
        deserializedTransaction.getFees().get(0).getCurrency());
    Assert.assertEquals(
        transaction.getFees().get(0).getPercentage(),
        deserializedTransaction.getFees().get(0).getPercentage());
    Assert.assertEquals(
        transaction.getFees().get(0).getTarget(),
        deserializedTransaction.getFees().get(0).getTarget());
    Assert.assertEquals(
        transaction.getFees().get(0).getType(), deserializedTransaction.getFees().get(0).getType());
    Assert.assertEquals(transaction.getId(), deserializedTransaction.getId());
    Assert.assertEquals(transaction.getMessage(), deserializedTransaction.getMessage());
    Assert.assertEquals(transaction.getNetwork(), deserializedTransaction.getNetwork());
    Assert.assertEquals(transaction.getNormalized().size(), 1);
    Assert.assertEquals(
        transaction.getNormalized().get(0).getAmount(),
        deserializedTransaction.getNormalized().get(0).getAmount());
    Assert.assertEquals(
        transaction.getNormalized().get(0).getCommission(),
        deserializedTransaction.getNormalized().get(0).getCommission());
    Assert.assertEquals(
        transaction.getNormalized().get(0).getCurrency(),
        deserializedTransaction.getNormalized().get(0).getCurrency());
    Assert.assertEquals(
        transaction.getNormalized().get(0).getFee(),
        deserializedTransaction.getNormalized().get(0).getFee());
    Assert.assertEquals(
        transaction.getNormalized().get(0).getRate(),
        deserializedTransaction.getNormalized().get(0).getRate());
    Assert.assertEquals(
        transaction.getOrigin().getAccountId(), deserializedTransaction.getOrigin().getAccountId());
    Assert.assertEquals(
        transaction.getOrigin().getAccountType(),
        deserializedTransaction.getOrigin().getAccountType());
    Assert.assertEquals(
        transaction.getOrigin().getAmount(), deserializedTransaction.getOrigin().getAmount());
    Assert.assertEquals(
        transaction.getOrigin().getBase(), deserializedTransaction.getOrigin().getBase());
    Assert.assertEquals(
        transaction.getOrigin().getCardId(), deserializedTransaction.getOrigin().getCardId());
    Assert.assertEquals(
        transaction.getOrigin().getCommission(),
        deserializedTransaction.getOrigin().getCommission());
    Assert.assertEquals(
        transaction.getOrigin().getCurrency(), deserializedTransaction.getOrigin().getCurrency());
    Assert.assertEquals(
        transaction.getOrigin().getDescription(),
        deserializedTransaction.getOrigin().getDescription());
    Assert.assertEquals(
        transaction.getOrigin().getFee(), deserializedTransaction.getOrigin().getFee());
    Assert.assertEquals(
        transaction.getOrigin().getRate(), deserializedTransaction.getOrigin().getRate());
    Assert.assertEquals(
        transaction.getOrigin().getSources().size(),
        deserializedTransaction.getOrigin().getSources().size());
    Assert.assertEquals(
        transaction.getOrigin().getSources().get(0).getAmount(),
        deserializedTransaction.getOrigin().getSources().get(0).getAmount());
    Assert.assertEquals(
        transaction.getOrigin().getSources().get(0).getId(),
        deserializedTransaction.getOrigin().getSources().get(0).getId());
    Assert.assertEquals(
        transaction.getOrigin().getType(), deserializedTransaction.getOrigin().getType());
    Assert.assertEquals(
        transaction.getOrigin().getUsername(), deserializedTransaction.getOrigin().getUsername());
    Assert.assertEquals(
        transaction.getParams().getCurrency(), deserializedTransaction.getParams().getCurrency());
    Assert.assertEquals(
        transaction.getParams().getMargin(), deserializedTransaction.getParams().getMargin());
    Assert.assertEquals(
        transaction.getParams().getPair(), deserializedTransaction.getParams().getPair());
    Assert.assertEquals(
        transaction.getParams().getProgress(), deserializedTransaction.getParams().getProgress());
    Assert.assertEquals(
        transaction.getParams().getRate(), deserializedTransaction.getParams().getRate());
    Assert.assertEquals(
        transaction.getParams().getRefunds(), deserializedTransaction.getParams().getRefunds());
    Assert.assertEquals(
        transaction.getParams().getTtl(), deserializedTransaction.getParams().getTtl());
    Assert.assertEquals(
        transaction.getParams().getTxid(), deserializedTransaction.getParams().getTxid());
    Assert.assertEquals(
        transaction.getParams().getType(), deserializedTransaction.getParams().getType());
    Assert.assertEquals(transaction.getRefundedById(), deserializedTransaction.getRefundedById());
    Assert.assertEquals(transaction.getStatus(), deserializedTransaction.getStatus());
    Assert.assertEquals(transaction.getType(), deserializedTransaction.getType());
  }
Esempio n. 19
0
 /**
  * 发送消息
  *
  * @param object
  * @throws IOException
  */
 public void sendMessage(Serializable object) throws IOException {
   channel.basicPublish("", endPointName, null, SerializationUtils.serialize(object));
 }
Esempio n. 20
0
 public static List<LabelValue> makeListBlank(Class<? extends Enum> clazz) {
   ArrayList<LabelValue> list = (ArrayList<LabelValue>) makeList(clazz);
   List<LabelValue> result = SerializationUtils.clone(list);
   result.add(0, new LabelValue("请选择", ""));
   return result;
 }
Esempio n. 21
0
 public Conf copy() {
   return SerializationUtils.clone(this);
 }
  /**
   * Obtiene la configuraci\u00F3n de entregas del pedido
   *
   * @param session
   */
  public void obtenerEntregas(HttpSession session) {
    // cjui\u00F1a
    Collection<EntregaDetallePedidoDTO> entregasResp = new ArrayList<EntregaDetallePedidoDTO>();
    Collection<DetallePedidoDTO> detPedResp = new ArrayList<DetallePedidoDTO>();
    Collection<VistaDetallePedidoDTO> detallePedidoDTOCol =
        (Collection<VistaDetallePedidoDTO>) session.getAttribute(DETALLELPEDIDOAUX);
    if (!CollectionUtils.isEmpty(detallePedidoDTOCol)) {
      for (VistaDetallePedidoDTO detPed : detallePedidoDTOCol) {
        if (!CollectionUtils.isEmpty(detPed.getEntregaDetallePedidoCol())) {
          Collection<EntregaDetallePedidoDTO> entregas =
              (Collection<EntregaDetallePedidoDTO>) detPed.getEntregaDetallePedidoCol();
          if (CollectionUtils.isEmpty(entregasResp)) {
            entregasResp =
                (Collection<EntregaDetallePedidoDTO>)
                    SerializationUtils.clone((Serializable) entregas);
            for (EntregaDetallePedidoDTO entPed : entregasResp) {
              detPedResp = new ArrayList<DetallePedidoDTO>();
              entPed.getEntregaPedidoDTO().setNpDetallePedido(new ArrayList<DetallePedidoDTO>());
              DetallePedidoDTO dp = new DetallePedidoDTO();
              dp.setArticuloDTO(new ArticuloDTO());
              dp.getArticuloDTO()
                  .setId(
                      (ArticuloID)
                          SerializationUtils.clone((Serializable) detPed.getArticuloDTO().getId()));
              dp.getArticuloDTO()
                  .setDescripcionArticulo(detPed.getArticuloDTO().getDescripcionArticulo());
              dp.getArticuloDTO().setCodigoBarrasActivo(new ArticuloBitacoraCodigoBarrasDTO());
              dp.getArticuloDTO()
                  .getCodigoBarrasActivo()
                  .setId(
                      (ArticuloBitacoraCodigoBarrasID)
                          SerializationUtils.clone(
                              (Serializable)
                                  detPed.getArticuloDTO().getCodigoBarrasActivo().getId()));
              dp.setEstadoDetallePedidoDTO(new EstadoDetallePedidoDTO());
              dp.getEstadoDetallePedidoDTO().setCantidadEstado(entPed.getCantidadEntrega());
              dp.setNpContadorDespacho(entPed.getCantidadDespacho());
              dp.setNpContadorEntrega(entPed.getCantidadEntrega());
              detPedResp.add(dp);
              entPed.getEntregaPedidoDTO().setNpDetallePedido(detPedResp);
            }
          } else {
            for (EntregaDetallePedidoDTO entDetPed : entregas) {
              Boolean existeEntrega = Boolean.FALSE;
              DetallePedidoDTO dp = new DetallePedidoDTO();
              dp.setArticuloDTO(new ArticuloDTO());
              dp.getArticuloDTO()
                  .setId(
                      (ArticuloID)
                          SerializationUtils.clone((Serializable) detPed.getArticuloDTO().getId()));
              dp.getArticuloDTO()
                  .setDescripcionArticulo(detPed.getArticuloDTO().getDescripcionArticulo());
              dp.getArticuloDTO().setCodigoBarrasActivo(new ArticuloBitacoraCodigoBarrasDTO());
              dp.getArticuloDTO()
                  .getCodigoBarrasActivo()
                  .setId(
                      (ArticuloBitacoraCodigoBarrasID)
                          SerializationUtils.clone(
                              (Serializable)
                                  detPed.getArticuloDTO().getCodigoBarrasActivo().getId()));
              dp.setEstadoDetallePedidoDTO(new EstadoDetallePedidoDTO());
              dp.getEstadoDetallePedidoDTO().setCantidadEstado(entDetPed.getCantidadEntrega());
              dp.setNpContadorDespacho(entDetPed.getCantidadDespacho());
              dp.setNpContadorEntrega(entDetPed.getCantidadEntrega());

              for (EntregaDetallePedidoDTO entPedRes : entregasResp) {
                Long diferencia =
                    entDetPed.getEntregaPedidoDTO().getFechaEntregaCliente().getTime()
                        - entPedRes.getEntregaPedidoDTO().getFechaEntregaCliente().getTime();
                if (diferencia == 0L
                    && entDetPed
                        .getEntregaPedidoDTO()
                        .getDireccionEntrega()
                        .toUpperCase()
                        .trim()
                        .equals(
                            entPedRes
                                .getEntregaPedidoDTO()
                                .getDireccionEntrega()
                                .toUpperCase()
                                .trim())) {
                  entPedRes.getEntregaPedidoDTO().getNpDetallePedido().add(dp);
                  existeEntrega = Boolean.TRUE;
                  break;
                }
              }
              if (!existeEntrega) {
                entDetPed
                    .getEntregaPedidoDTO()
                    .setNpDetallePedido(new ArrayList<DetallePedidoDTO>());
                entDetPed.getEntregaPedidoDTO().getNpDetallePedido().add(dp);
                entregasResp.add(entDetPed);
              }
            }
          }
        }
      }
    }

    for (EntregaDetallePedidoDTO entPed : entregasResp) {
      Long cantidadDespacho = 0L;
      Long cantidadEntrega = 0L;
      for (DetallePedidoDTO detallePedido : entPed.getEntregaPedidoDTO().getNpDetallePedido()) {
        cantidadDespacho = cantidadDespacho + detallePedido.getNpContadorDespacho();
        cantidadEntrega = cantidadEntrega + detallePedido.getNpContadorEntrega();
      }
      entPed.setCantidadDespacho(cantidadDespacho);
      entPed.setCantidadEntrega(cantidadEntrega);
    }
    session.setAttribute(ENTREGAS_RESPONSABLES, entregasResp);
  }
 private void updateReviewDataOrAskServer(Cursor data) {
   byte[] bReview = data == null ? null : data.getBlob(1);
   if (bReview == null || bReview.length == 0) getReviewDataAsync();
   else handleReviewResults((List<Map<String, String>>) SerializationUtils.deserialize(bReview));
 }
 private void updateTrailerDataOrAskServer(Cursor data) {
   byte[] bTrailer = data == null ? null : data.getBlob(1);
   if (bTrailer == null || bTrailer.length == 0) getVideoDataAsync();
   else handleTrailerResults((List<Map<String, String>>) SerializationUtils.deserialize(bTrailer));
 }
Esempio n. 25
0
  private int processEntityContext(
      final EntityTypeInvocationHandler handler,
      int pos,
      final TransactionItems items,
      final List<EntityLinkDesc> delayedUpdates,
      final ODataChangeset changeset) {

    LOG.debug("Process '{}'", handler);

    items.put(handler, null);

    final ODataEntity entity = SerializationUtils.clone(handler.getEntity());
    entity.getNavigationLinks().clear();

    final AttachedEntityStatus currentStatus =
        EntityContainerFactory.getContext().entityContext().getStatus(handler);

    if (AttachedEntityStatus.DELETED != currentStatus) {
      entity.getProperties().clear();
      EngineUtils.addProperties(factory.getMetadata(), handler.getPropertyChanges(), entity);
    }

    for (Map.Entry<NavigationProperty, Object> property : handler.getLinkChanges().entrySet()) {
      final ODataLinkType type =
          Collection.class.isAssignableFrom(property.getValue().getClass())
              ? ODataLinkType.ENTITY_SET_NAVIGATION
              : ODataLinkType.ENTITY_NAVIGATION;

      final Set<EntityTypeInvocationHandler> toBeLinked =
          new HashSet<EntityTypeInvocationHandler>();
      final String serviceRoot = factory.getServiceRoot();

      for (Object proxy :
          type == ODataLinkType.ENTITY_SET_NAVIGATION
              ? (Collection) property.getValue()
              : Collections.singleton(property.getValue())) {

        final EntityTypeInvocationHandler target =
            (EntityTypeInvocationHandler) Proxy.getInvocationHandler(proxy);

        final AttachedEntityStatus status =
            EntityContainerFactory.getContext().entityContext().getStatus(target);

        final URI editLink = target.getEntity().getEditLink();

        if ((status == AttachedEntityStatus.ATTACHED || status == AttachedEntityStatus.LINKED)
            && !target.isChanged()) {
          entity.addLink(
              buildNavigationLink(
                  property.getKey().name(),
                  URIUtils.getURI(serviceRoot, editLink.toASCIIString()),
                  type));
        } else {
          if (!items.contains(target)) {
            pos = processEntityContext(target, pos, items, delayedUpdates, changeset);
            pos++;
          }

          final Integer targetPos = items.get(target);
          if (targetPos == null) {
            // schedule update for the current object
            LOG.debug("Schedule '{}' from '{}' to '{}'", type.name(), handler, target);
            toBeLinked.add(target);
          } else if (status == AttachedEntityStatus.CHANGED) {
            entity.addLink(
                buildNavigationLink(
                    property.getKey().name(),
                    URIUtils.getURI(serviceRoot, editLink.toASCIIString()),
                    type));
          } else {
            // create the link for the current object
            LOG.debug("'{}' from '{}' to (${}) '{}'", type.name(), handler, targetPos, target);

            entity.addLink(
                buildNavigationLink(property.getKey().name(), URI.create("$" + targetPos), type));
          }
        }
      }

      if (!toBeLinked.isEmpty()) {
        delayedUpdates.add(new EntityLinkDesc(property.getKey().name(), handler, toBeLinked, type));
      }
    }

    // insert into the batch
    LOG.debug("{}: Insert '{}' into the batch", pos, handler);
    batch(handler, entity, changeset);

    items.put(handler, pos);

    int startingPos = pos;

    if (handler.getEntity().isMediaEntity()) {

      // update media properties
      if (!handler.getPropertyChanges().isEmpty()) {
        final URI targetURI =
            currentStatus == AttachedEntityStatus.NEW
                ? URI.create("$" + startingPos)
                : URIUtils.getURI(
                    factory.getServiceRoot(), handler.getEntity().getEditLink().toASCIIString());
        batchUpdate(handler, targetURI, entity, changeset);
        pos++;
        items.put(handler, pos);
      }

      // update media content
      if (handler.getStreamChanges() != null) {
        final URI targetURI =
            currentStatus == AttachedEntityStatus.NEW
                ? URI.create("$" + startingPos + "/$value")
                : URIUtils.getURI(
                    factory.getServiceRoot(),
                    handler.getEntity().getEditLink().toASCIIString() + "/$value");

        batchUpdateMediaEntity(handler, targetURI, handler.getStreamChanges(), changeset);

        // update media info (use null key)
        pos++;
        items.put(null, pos);
      }
    }

    for (Map.Entry<String, InputStream> streamedChanges :
        handler.getStreamedPropertyChanges().entrySet()) {
      final URI targetURI =
          currentStatus == AttachedEntityStatus.NEW
              ? URI.create("$" + startingPos)
              : URIUtils.getURI(
                  factory.getServiceRoot(),
                  EngineUtils.getEditMediaLink(streamedChanges.getKey(), entity).toASCIIString());

      batchUpdateMediaResource(handler, targetURI, streamedChanges.getValue(), changeset);

      // update media info (use null key)
      pos++;
      items.put(handler, pos);
    }

    return pos;
  }
Esempio n. 26
0
 @Override
 public Object clone(Object obj) {
   return SerializationUtils.clone((Serializable) obj);
 }
Esempio n. 27
0
 /** @return The byte array representation of this object */
 public byte[] getBytes() {
   return SerializationUtils.serialize(this);
 }