/**
  * Deserializes a NIS boot info.
  *
  * @param deserializer The deserializer.
  */
 public NisBootInfo(final Deserializer deserializer) {
   // To provide a smooth transition from old structure
   final Integer bootStrategy = deserializer.readOptionalInt("bootNis");
   this.bootStrategy = null == bootStrategy ? 0 : bootStrategy;
   this.accountId = deserializer.readOptionalString("account");
   this.nodeName = deserializer.readOptionalString("nodeName");
 }
Ejemplo n.º 2
0
 public GensonBuilder withDeserializers(Deserializer<?>... deserializer) {
   for (Deserializer<?> d : deserializer) {
     Type typeOfConverter =
         TypeUtil.typeOf(0, TypeUtil.lookupGenericType(Deserializer.class, d.getClass()));
     typeOfConverter = TypeUtil.expandType(typeOfConverter, d.getClass());
     registerDeserializer(d, typeOfConverter);
   }
   return this;
 }
  /**
   * Sets the fields based on deserializer.
   *
   * @param deserializer The deserializer.
   */
  public void deserialize(final Deserializer deserializer, final boolean remoteIsOptional) {
    this.setLanguage(deserializer.readString("language"));
    if (remoteIsOptional) {
      this.setNisEndpoint(deserializer.readOptionalObject("remoteServer", NodeEndpoint::new));
    } else {
      this.setNisEndpoint(deserializer.readObject("remoteServer", NodeEndpoint::new));
    }
    this.setNisBootInfo(deserializer.readObject("nisBootInfo", NisBootInfo::new));

    this.setFirstStart(deserializer.readOptionalInt("firstStart"));
  }
Ejemplo n.º 4
0
 private void addDefaultDeserializers(List<? extends Deserializer<?>> deserializers) {
   if (deserializers != null) {
     for (Deserializer<?> deserializer : deserializers) {
       Type typeOfConverter =
           TypeUtil.typeOf(
               0, TypeUtil.lookupGenericType(Deserializer.class, deserializer.getClass()));
       typeOfConverter = TypeUtil.expandType(typeOfConverter, deserializer.getClass());
       if (!deserializersMap.containsKey(typeOfConverter))
         deserializersMap.put(typeOfConverter, deserializer);
     }
   }
 }
Ejemplo n.º 5
0
  public Object deserialize(InputStream is, Hashtable extendedContext) throws Exception {

    // getting deserializer
    Class targetCls = (Class) extendedContext.get("targetClass");
    Object objectOfTargetCls = targetCls.newInstance();
    TypeDesc desc =
        (TypeDesc)
            objectOfTargetCls
                .getClass()
                .getMethod("getTypeDesc", new Class[] {})
                .invoke(objectOfTargetCls, new Object[] {});
    final QName xmlType; // = desc.getXmlType();
    xmlType =
        new QName(
            "http://" + objectOfTargetCls.getClass().getName(),
            org.uengine.util.UEngineUtil.getClassNameOnly(objectOfTargetCls.getClass()));
    Deserializer dser =
        (Deserializer)
            objectOfTargetCls
                .getClass()
                .getMethod("getDeserializer", new Class[] {String.class, Class.class, QName.class})
                .invoke(
                    objectOfTargetCls, new Object[] {"", objectOfTargetCls.getClass(), xmlType});
    // end
    System.out.println("dser:" + dser);

    DeserializationContext context =
        new DeserializationContextImpl(
            new org.xml.sax.InputSource(is),
            /*			new MessageContext(null){
            	public String getEncodingStyle(){
            		return xmlType.getNamespaceURI();
            	}
            },*/
            new MessageContext(new AxisClient()),
            // Message.RESPONSE
            "PurchaseOrder");

    boolean oldVal = context.isDoneParsing();
    ((DeserializationContextImpl) context).deserializing(true);
    context.pushElementHandler(new EnvelopeHandler((SOAPHandler) dser));

    //	        context.getRecorder().replay(0, -1, (org.xml.sax.ContentHandler)context);
    context.getRecorder().replay(0, -1, (org.xml.sax.ContentHandler) context);

    ((DeserializationContextImpl) context).deserializing(oldVal);

    context.parse();

    return dser.getValue();
  }
Ejemplo n.º 6
0
  /** Tests deserialize and getters. */
  @Test
  public void testDeserialize() throws Exception {
    LLC llc = deserializer.deserialize(bytes, 0, bytes.length);

    assertEquals(dsap, llc.getDsap());
    assertEquals(ssap, llc.getSsap());
    assertEquals(ctrl, llc.getCtrl());
  }
Ejemplo n.º 7
0
 private <T> void registerDeserializer(Deserializer<T> deserializer, Type type) {
   if (deserializersMap.containsKey(type))
     throw new IllegalStateException(
         "Can not register deserializer "
             + deserializer.getClass()
             + ". A custom deserializer is already registered for type "
             + type);
   deserializersMap.put(type, deserializer);
 }
Ejemplo n.º 8
0
 /**
  * Initializes a SerDe.
  *
  * @param deserializer
  * @param conf
  * @param tblProps
  * @param partProps
  * @throws SerDeException
  */
 public static void initializeSerDeWithoutErrorCheck(
     Deserializer deserializer, Configuration conf, Properties tblProps, Properties partProps)
     throws SerDeException {
   if (deserializer instanceof AbstractSerDe) {
     ((AbstractSerDe) deserializer).initialize(conf, tblProps, partProps);
   } else {
     deserializer.initialize(conf, createOverlayedProperties(tblProps, partProps));
   }
 }
Ejemplo n.º 9
0
  static void deser(PrintStream out, Deserializer deserializer, String name, int warmups, int loops)
      throws Exception {
    final byte[] data = deserializer.getSerializer().serialize(foo);
    int len = data.length;
    Foo f = new Foo();
    deserializer.mergeFrom(data, f);
    SerializableObjects.assertEquals(foo, f);

    for (int i = 0; i < warmups; i++) deserializer.mergeFrom(data, new Foo());

    long start = System.currentTimeMillis();

    for (int i = 0; i < loops; i++) deserializer.mergeFrom(data, new Foo());

    long finish = System.currentTimeMillis();
    long elapsed = finish - start;
    out.println(elapsed + " ms elapsed with " + len + " bytes for " + name);
  }
Ejemplo n.º 10
0
  /** Tests toString. */
  @Test
  public void testToStringLLC() throws Exception {
    LLC llc = deserializer.deserialize(bytes, 0, bytes.length);
    String str = llc.toString();

    assertTrue(StringUtils.contains(str, "dsap=" + dsap));
    assertTrue(StringUtils.contains(str, "ssap=" + ssap));
    assertTrue(StringUtils.contains(str, "ctrl=" + ctrl));
  }
Ejemplo n.º 11
0
  private <T> Response<T> sendRequest(
      RequestType type,
      SlaveContext slaveContext,
      Serializer serializer,
      Deserializer<T> deserializer) {
    // TODO Refactor, break into smaller methods
    Triplet<Channel, ChannelBuffer, ByteBuffer> channelContext = null;
    try {
      // Send 'em over the wire
      channelContext = getChannel();
      Channel channel = channelContext.first();
      ChannelBuffer buffer = channelContext.second();
      buffer.clear();
      buffer = new ChunkingChannelBuffer(buffer, channel, MAX_FRAME_LENGTH);
      buffer.writeByte(type.ordinal());
      if (type.includesSlaveContext()) {
        writeSlaveContext(buffer, slaveContext);
      }
      serializer.write(buffer, channelContext.third());
      if (buffer.writerIndex() > 0) {
        channel.write(buffer);
      }

      // Read the response
      @SuppressWarnings("unchecked")
      BlockingReadHandler<ChannelBuffer> reader =
          (BlockingReadHandler<ChannelBuffer>) channel.getPipeline().get("blockingHandler");
      final Triplet<Channel, ChannelBuffer, ByteBuffer> finalChannelContext = channelContext;
      DechunkingChannelBuffer dechunkingBuffer =
          new DechunkingChannelBuffer(reader) {
            @Override
            protected ChannelBuffer readNext() {
              ChannelBuffer result = super.readNext();
              if (result == null) {
                channelPool.dispose(finalChannelContext);
                throw new HaCommunicationException("Channel has been closed");
              }
              return result;
            }
          };
      T response = deserializer.read(dechunkingBuffer);
      TransactionStream txStreams =
          type.includesSlaveContext()
              ? readTransactionStreams(dechunkingBuffer)
              : TransactionStream.EMPTY;
      return new Response<T>(response, txStreams);
    } catch (ClosedChannelException e) {
      channelPool.dispose(channelContext);
      throw new HaCommunicationException(e);
    } catch (IOException e) {
      throw new HaCommunicationException(e);
    } catch (InterruptedException e) {
      throw new HaCommunicationException(e);
    } catch (Exception e) {
      throw new HaCommunicationException(e);
    }
  }
Ejemplo n.º 12
0
  public Object deserialize(Object o, Class clazz) throws DeserializationException {
    Object result = null;

    try {
      Assert.assertNotNull(o, "Input parameter [" + o + "] cannot be null");
      Assert.assertNotNull(o, "Input parameter [" + clazz + "] cannot be null");

      SourceBean xml = null;
      if (o instanceof SourceBean) {
        xml = (SourceBean) o;
      } else if (o instanceof String) {
        xml = SourceBean.fromXMLString((String) o);
      } else {
        throw new DeserializationException(
            "Impossible to deserialize from an object of type [" + o.getClass().getName() + "]");
      }

      Deserializer deserializer = mappings.get(clazz);
      if (deserializer == null) {
        throw new DeserializationException(
            "Impossible to deserialize to an object of type [" + clazz.getName() + "]");
      }

      if (xml.getAttribute("ROWS") != null) {
        List list = new ArrayList();
        List<SourceBean> rows = xml.getAttributeAsList("ROWS.ROW");
        for (SourceBean row : rows) {
          list.add(deserializer.deserialize(row, clazz));
        }
        result = list;
      } else {
        result = deserializer.deserialize(o, clazz);
      }
    } catch (Throwable t) {
      throw new DeserializationException("An error occurred while deserializing object: " + o, t);
    } finally {

    }

    return result;
  }
Ejemplo n.º 13
0
  /**
   * Deserializes a transaction.
   *
   * @param options The deserialization options.
   * @param deserializer The deserializer.
   * @return The deserialized transaction.
   */
  private static Transaction deserialize(
      final VerifiableEntity.DeserializationOptions options, final Deserializer deserializer) {
    final int type = deserializer.readInt("type");

    final BiFunction<VerifiableEntity.DeserializationOptions, Deserializer, Transaction>
        constructor = TYPE_TO_CONSTRUCTOR_MAP.getOrDefault(type, null);
    if (null == constructor) {
      throw new IllegalArgumentException("Unknown transaction type: " + type);
    }

    return constructor.apply(options, deserializer);
  }
Ejemplo n.º 14
0
  public static void decrypt(InputStream is, OutputStream os)
      throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, ClassNotFoundException,
          InvalidAlgorithmParameterException, InvalidKeyException {
    SecretKey key = Deserializer.deserializeObject();

    // get Cipher instance and initiate in decrypt mode
    Cipher decryptCipher = Cipher.getInstance("AES");
    decryptCipher.init(Cipher.DECRYPT_MODE, key);

    // create CipherOutputStream to decrypt the data using decryptCipher
    is = new CipherInputStream(is, decryptCipher);
    writeData(is, os);
  }
Ejemplo n.º 15
0
 /**
  * Initializes a SerDe.
  *
  * @param deserializer
  * @param conf
  * @param tblProps
  * @param partProps
  * @throws SerDeException
  */
 public static void initializeSerDe(
     Deserializer deserializer, Configuration conf, Properties tblProps, Properties partProps)
     throws SerDeException {
   if (deserializer instanceof AbstractSerDe) {
     ((AbstractSerDe) deserializer).initialize(conf, tblProps, partProps);
     String msg = ((AbstractSerDe) deserializer).getConfigurationErrors();
     if (msg != null && !msg.isEmpty()) {
       throw new SerDeException(msg);
     }
   } else {
     deserializer.initialize(conf, createOverlayedProperties(tblProps, partProps));
   }
 }
Ejemplo n.º 16
0
  /**
   * Returns the index entry of a block in the given map file. If the required index entry is not
   * cached, it will be read from the map file index and put in the cache.
   *
   * @param subFileParameter the parameters of the map file for which the index entry is needed.
   * @param blockNumber the number of the block in the map file.
   * @return the index entry or -1 if the block number is invalid.
   */
  long getIndexEntry(SubFileParameter subFileParameter, long blockNumber) {
    try {
      // check if the block number is out of bounds
      if (blockNumber >= subFileParameter.numberOfBlocks) {
        return -1;
      }

      // calculate the index block number
      long indexBlockNumber = blockNumber / INDEX_ENTRIES_PER_BLOCK;

      // create the cache entry key for this request
      IndexCacheEntryKey indexCacheEntryKey =
          new IndexCacheEntryKey(subFileParameter, indexBlockNumber);

      // check for cached index block
      byte[] indexBlock = this.map.get(indexCacheEntryKey);
      if (indexBlock == null) {
        // cache miss, seek to the correct index block in the file and read it
        long indexBlockPosition =
            subFileParameter.indexStartAddress + indexBlockNumber * SIZE_OF_INDEX_BLOCK;

        int remainingIndexSize = (int) (subFileParameter.indexEndAddress - indexBlockPosition);
        int indexBlockSize = Math.min(SIZE_OF_INDEX_BLOCK, remainingIndexSize);
        indexBlock = new byte[indexBlockSize];

        this.randomAccessFile.seek(indexBlockPosition);
        if (this.randomAccessFile.read(indexBlock, 0, indexBlockSize) != indexBlockSize) {
          LOG.warning("reading the current index block has failed");
          return -1;
        }

        // put the index block in the map
        this.map.put(indexCacheEntryKey, indexBlock);
      }

      // calculate the address of the index entry inside the index block
      long indexEntryInBlock = blockNumber % INDEX_ENTRIES_PER_BLOCK;
      int addressInIndexBlock = (int) (indexEntryInBlock * SubFileParameter.BYTES_PER_INDEX_ENTRY);

      // return the real index entry
      return Deserializer.getFiveBytesLong(indexBlock, addressInIndexBlock);
    } catch (IOException e) {
      LOG.log(Level.SEVERE, null, e);
      return -1;
    }
  }
Ejemplo n.º 17
0
  public static <T> T parse(Object object, Type type) {

    Deserializer deserializer = getDeserializer(type);

    return deserializer.deserialize(object, type);
  }
Ejemplo n.º 18
0
 public static void start(PrintStream out, int warmups, int loops) throws Exception {
   for (Deserializer s : DESERIALIZERS) deser(out, s, s.getName(), warmups, loops);
 }