Exemplo n.º 1
1
 public <T> List<byte[]> query(
     Path basePath,
     Path baseOutputPath,
     long beginNS,
     long endNS,
     int numReducers,
     T fields,
     Configuration conf,
     FileSystem fs,
     PcapFilterConfigurator<T> filterImpl)
     throws IOException, ClassNotFoundException, InterruptedException {
   String fileName =
       Joiner.on("_")
           .join(beginNS, endNS, filterImpl.queryToString(fields), UUID.randomUUID().toString());
   if (LOG.isDebugEnabled()) {
     DateFormat format =
         SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.LONG, SimpleDateFormat.LONG);
     String from = format.format(new Date(Long.divideUnsigned(beginNS, 1000000)));
     String to = format.format(new Date(Long.divideUnsigned(endNS, 1000000)));
     LOG.debug(
         "Executing query "
             + filterImpl.queryToString(fields)
             + " on timerange "
             + from
             + " to "
             + to);
   }
   Path outputPath = new Path(baseOutputPath, fileName);
   Job job =
       createJob(basePath, outputPath, beginNS, endNS, numReducers, fields, conf, fs, filterImpl);
   boolean completed = job.waitForCompletion(true);
   if (completed) {
     return readResults(outputPath, conf, fs);
   } else {
     throw new RuntimeException(
         "Unable to complete query due to errors.  Please check logs for full errors.");
   }
 }
Exemplo n.º 2
0
 @Override
 public void bindView(View view, Context context, Cursor cursor) {
   super.bindView(view, context, cursor);
   TextView setup = (TextView) view.findViewById(R.id.text3);
   TextView reply = (TextView) view.findViewById(R.id.text4);
   locationCursor.moveToPosition(cursor.getPosition());
   long rt = locationCursor.getLong(1);
   if (rt > 0) {
     Calendar cal = Calendar.getInstance();
     cal.setTimeInMillis(rt);
     DateFormat sdf = SimpleDateFormat.getDateTimeInstance();
     setup.setText("requested on: " + sdf.format(cal.getTime()));
   } else {
     setup.setText("requested on: <not available>");
   }
   rt = locationCursor.getLong(2);
   if (rt > 0) {
     Calendar cal = Calendar.getInstance();
     cal.setTimeInMillis(rt);
     DateFormat sdf = SimpleDateFormat.getDateTimeInstance();
     reply.setText("updated on:" + sdf.format(cal.getTime()));
     ((ImageView) view.findViewById(R.id.status))
         .setImageResource(android.R.drawable.presence_online);
   } else {
     reply.setText("updated on: <not available>");
   }
 }
  private void updateArtifactEntry(final BufferedReader reader, final BufferedWriter writer)
      throws IOException {

    // this line remains the same
    writer.write(project.getArtifactId());
    writer.newLine();
    // next line is version, author (or "deployer"), date & time,
    reader.readLine();
    writer.write(
        project.getVersion()
            + " was last deployed by "
            + System.getProperty("user.name")
            + " at "
            + SimpleDateFormat.getDateTimeInstance().format(now));
    writer.newLine();
    // next line is the quote
    for (String line = reader.readLine();
        null != line && 0 < line.length();
        line = reader.readLine()) {}
    ;
    final String quote = project.getProperties().getProperty("version.quote");
    if (null != quote) {
      writer.write(quote);
      writer.newLine();
      writer.newLine();
    }
  }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder = null;
      UserActivityTypPrx rowItem = getItem(position);

      LayoutInflater mInflater =
          (LayoutInflater) _context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
      if (convertView == null) {
        convertView = mInflater.inflate(_resource, null);
        holder = new ViewHolder();
        holder.imageView = (ImageView) convertView.findViewById(_imageProjectionView);
        holder.txtTitle = (TextView) convertView.findViewById(_textProjectionView);
        holder.txtSubtitle = (TextView) convertView.findViewById(_subtextProjectionView);
        convertView.setTag(holder);
      } else holder = (ViewHolder) convertView.getTag();

      byte[] avatarBytes = null;
      if (rowItem.getUserActivityType() == ActivityType.TRIPJOIN
          || rowItem.getUserActivityType() == ActivityType.TRIPREQUESTANSWERED) {
        List<PassengerTyp> passengers = rowItem.getActivityTrip().getTripPassengers();
        avatarBytes = passengers.get(passengers.size() - 1).getPassengerUser().getAvatarBytes();
      } else {
        avatarBytes = rowItem.getActivityTrip().getTripDriver().getAvatarBytes();
      }
      holder.txtTitle.setText(rowItem._toString());
      holder.txtSubtitle.setText(
          SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.MEDIUM)
              .format(new Date(rowItem.getTimeStampInMillis())));
      holder.imageView.setImageBitmap(
          BitmapFactory.decodeByteArray(avatarBytes, 0, avatarBytes.length));

      return convertView;
    }
Exemplo n.º 5
0
 @Override
 public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
   switch (seekBar.getId()) {
     case R.id.trackbar:
       if (fromUser) {
         application.editingTrack.editingPos = progress;
       }
       Track.TrackPoint tp = application.editingTrack.getPoint(progress);
       // double ele = tp.elevation * elevationFactor;
       ((TextView) findViewById(R.id.tp_number)).setText("#" + (progress + 1));
       // FIXME Need UTM support here
       ((TextView) findViewById(R.id.tp_latitude))
           .setText(StringFormatter.coordinate(tp.latitude));
       ((TextView) findViewById(R.id.tp_longitude))
           .setText(StringFormatter.coordinate(tp.longitude));
       // ((TextView) findViewById(R.id.tp_elevation)).setText(String.valueOf(Math.round(ele)) + "
       // " + elevationAbbr);
       ((TextView) findViewById(R.id.tp_time))
           .setText(
               SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT)
                   .format(new Date(tp.time)));
       boolean mapChanged =
           application.setMapCenter(tp.latitude, tp.longitude, true, false, false);
       if (mapChanged) map.updateMapInfo();
       map.updateMapCenter();
       break;
   }
 }
 private static SimpleDateFormat getSimpleDateFormat() {
   SimpleDateFormat ret = DATE_FORMATS.get();
   if (ret == null) {
     ret = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance();
     DATE_FORMATS.set(ret);
   }
   return ret;
 }
Exemplo n.º 7
0
  /* Shows the transactions made by the host we control
   */
  private void showLocalTransaction(ClientConnection clientConnection) {
    try {
      final String formatString = "%-20s %-10s %-20s %-25s %-25s %-16s %s\n";
      Vector<TransactionBlock> peerTransaction = clientConnection.getAllTransaction();

      if (peerTransaction.isEmpty() == false) {
        this.ourShell.out.printf(
            formatString,
            "DataName",
            "Version",
            "Schedule",
            "Transaction start",
            "Transaction end",
            "Size",
            "#Files");
      }
      for (TransactionBlock tBlock : peerTransaction) {
        Calendar transactionDate = Calendar.getInstance();
        transactionDate.setTimeInMillis(tBlock.getTransactionStartTime());
        String hrDateStart =
            SimpleDateFormat.getDateTimeInstance().format(transactionDate.getTime());

        String hrDateEnd;
        if (tBlock.getTransactionEndTime() != 0) {
          transactionDate.setTimeInMillis(tBlock.getTransactionEndTime());
          hrDateEnd = SimpleDateFormat.getDateTimeInstance().format(transactionDate.getTime());
        } else {
          hrDateEnd = "In progress";
        }

        String humanReadableSize =
            new SuffixedNumber(tBlock.getTransactionSize(), "bytes").toString();
        this.ourShell.out.printf(
            formatString,
            tBlock.getDataName(),
            Long.toHexString(tBlock.getBlockId()),
            tBlock.getScheduleName(),
            hrDateStart,
            hrDateEnd,
            humanReadableSize,
            tBlock.getNumberOfHeaderBlocks());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 8
0
 /**
  * To String
  *
  * @see java.lang.Object#toString()
  */
 @Override
 public String toString() {
   DateFormat df = SimpleDateFormat.getDateTimeInstance();
   return df.format(new Date())
       + " - queue: "
       + this.queue
       + ", type: "
       + this.type
       + ", status: "
       + this.status;
 }
Exemplo n.º 9
0
 protected String getDateFormatString() {
   String custom = CFG_GUI.CFG.getDateTimeFormatDownloadListAddedDateColumn();
   if (StringUtils.isNotEmpty(custom)) {
     return custom;
   }
   DateFormat sd = SimpleDateFormat.getDateTimeInstance();
   if (sd instanceof SimpleDateFormat) {
     return ((SimpleDateFormat) sd).toPattern();
   }
   return _GUI.T.added_date_column_dateformat();
 }
 @Override
 public String toString() {
   DateFormat format = SimpleDateFormat.getDateTimeInstance();
   return "<sitereport site=\""
       + this.server
       + "\" path=\""
       + this.path
       + "\" time=\""
       + format.format(timestamp)
       + "\" status=\""
       + this.status
       + " "
       + getStatusText()
       + "\" responcetime=\""
       + this.responsetime
       + "\" />";
 }
Exemplo n.º 11
0
 /**
  * Returns the date format pattern to be used, based on the date range.
  *
  * @param start the start date in milliseconds
  * @param end the end date in milliseconds
  * @return the date format
  */
 private DateFormat getDateFormat(double start, double end) {
   if (mDateFormat != null) {
     SimpleDateFormat format = null;
     try {
       format = new SimpleDateFormat(mDateFormat);
       return format;
     } catch (Exception e) {
       // do nothing here
     }
   }
   DateFormat format = SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM);
   double diff = end - start;
   if (diff > DAY && diff < 5 * DAY) {
     format = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
   } else if (diff < DAY) {
     format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.MEDIUM);
   }
   return format;
 }
Exemplo n.º 12
0
    @Override
    public void commandCompleted(int id, int exitcode) {
      Bitmap bmp = null;
      FileOutputStream out = null;
      try {
        int size = mSettings.screenshotSize();
        bmp = ImageUtil.getResizedImage(path, size);
        if (bmp != null) {
          Date dt = new Date();
          String date =
              SimpleDateFormat.getDateTimeInstance(
                      SimpleDateFormat.SHORT, SimpleDateFormat.MEDIUM, sLocale)
                  .format(dt);
          date = date.replace(':', '-'); // .replace(' ', '_');
          String fName = PREFIX + "[" + date + "]" + "[" + dt.getTime() + "]" + ".jpg";
          out = new FileOutputStream(FileUtil.getExternalFullPath(mContext, fName));
          bmp.compress(Bitmap.CompressFormat.JPEG, 60, out);

          File del = new File(path);
          del.delete();

          new FileSender(mContext, FileType.SCREENSHOT).start();
        }
      } catch (Exception e) {
        ACRA.getErrorReporter().handleSilentException(e);

      } finally {
        if (bmp != null && !bmp.isRecycled()) {
          bmp.recycle();
          bmp = null;
        }
        if (out != null) {
          try {
            out.close();

          } catch (IOException e) {
            Debug.exception(e);
          }
          out = null;
        }
      }
    }
Exemplo n.º 13
0
/**
 * The NTP Refresh Service polls the configured timeserver with a configurable interval and posts a
 * new event of type ({@link DateTimeType} to the event bus. The interval is 15 minutes by default
 * and can be changed via openhab.cfg.
 *
 * @author Thomas.Eichstaedt-Engelen
 * @since 0.8.0
 */
public class NtpBinding extends AbstractActiveBinding<NtpBindingProvider>
    implements ManagedService {

  private static final Logger logger = LoggerFactory.getLogger(NtpBinding.class);

  /** timeout for requests to the NTP server */
  private static final int NTP_TIMEOUT = 5000;

  // List of time servers: http://tf.nist.gov/service/time-servers.html
  protected String hostname = "ptbtime1.ptb.de";

  /** Default refresh interval (currently 15 minutes) */
  private long refreshInterval = 900000L;

  /** for logging purposes */
  private static final DateFormat SDF =
      SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.FULL, SimpleDateFormat.FULL);

  @Override
  protected String getName() {
    return "NTP Refresh Service";
  }

  @Override
  protected long getRefreshInterval() {
    return refreshInterval;
  }

  /** @{inheritDoc} */
  @Override
  public void execute() {

    if (!bindingsExist()) {
      logger.debug("There is no existing NTP binding configuration => refresh cycle aborted!");
      return;
    }

    long networkTimeInMillis = getTime(hostname);

    logger.debug("Got time from {}: {}", hostname, SDF.format(new Date(networkTimeInMillis)));

    for (NtpBindingProvider provider : providers) {
      for (String itemName : provider.getItemNames()) {
        updateTime(provider, itemName, networkTimeInMillis);
      }
    }
  }

  private void updateTime(NtpBindingProvider provider, String itemName, long networkTimeInMillis) {
    TimeZone timeZone = provider.getTimeZone(itemName);
    Locale locale = provider.getLocale(itemName);

    Calendar calendar = Calendar.getInstance(timeZone, locale);
    calendar.setTimeInMillis(networkTimeInMillis);

    eventPublisher.postUpdate(itemName, new DateTimeType(calendar));
  }

  /**
   * Queries the given timeserver <code>hostname</code> and returns the time in milliseconds.
   *
   * @param hostname the timeserver to query
   * @return the time in milliseconds or the current time of the system if an error occurs.
   */
  protected static long getTime(String hostname) {

    try {
      NTPUDPClient timeClient = new NTPUDPClient();
      timeClient.setDefaultTimeout(NTP_TIMEOUT);
      InetAddress inetAddress = InetAddress.getByName(hostname);
      TimeInfo timeInfo = timeClient.getTime(inetAddress);

      return timeInfo.getReturnTime();
    } catch (UnknownHostException uhe) {
      logger.warn(
          "the given hostname '{}' of the timeserver is unknown -> returning current sytem time instead",
          hostname);
    } catch (IOException ioe) {
      logger.warn(
          "couldn't establish network connection [host '{}'] -> returning current sytem time instead",
          hostname);
    }

    return System.currentTimeMillis();
  }

  /** {@inheritDoc} */
  @SuppressWarnings("rawtypes")
  public void updated(Dictionary config) throws ConfigurationException {

    if (config != null) {
      String hostnameString = (String) config.get("hostname");
      if (StringUtils.isNotBlank(hostnameString)) {
        hostname = hostnameString;
      }

      String refreshIntervalString = (String) config.get("refresh");
      if (StringUtils.isNotBlank(refreshIntervalString)) {
        refreshInterval = Long.parseLong(refreshIntervalString);
      }

      setProperlyConfigured(true);
    }
  }

  /** {@inheritDoc} */
  @Override
  public void bindingChanged(BindingProvider provider, String itemName) {
    NtpGenericBindingProvider ntpBindingProvider = (NtpGenericBindingProvider) provider;
    if (ntpBindingProvider.providesBindingFor(itemName)) {
      long networkTimeInMillis = getTime(hostname);
      updateTime(ntpBindingProvider, itemName, networkTimeInMillis);
    }
    super.bindingChanged(provider, itemName);
  }
}
Exemplo n.º 14
0
 private String formatDate(Date date) {
   if (date == null) return "";
   return SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.LONG)
       .format(date);
 }
 private String func_98062_b(long par1) {
   GregorianCalendar var3 = new GregorianCalendar(TimeZone.getDefault());
   var3.setTimeInMillis(par1);
   return SimpleDateFormat.getDateTimeInstance().format(var3.getTime());
 }
Exemplo n.º 16
0
 public LocalDateTimeField() {
   this(
       ((SimpleDateFormat) SimpleDateFormat.getDateTimeInstance())
           .toPattern()); // TODO: find out the pattern for the DateTimeFormatter's
   // FormatStyle.MEDIUM
 }
Exemplo n.º 17
0
/**
 * Use the GensonBuilder class when you want to create a custom Genson instance. This class allows
 * you for example to register custom converters/serializers/deserializers {@link
 * #withConverters(Converter...)} or custom converter Factories {@link
 * #withConverterFactory(Factory)}.
 *
 * <p>This class combines the GensonBuilder design pattern with template pattern providing handy
 * configuration and extensibility. All its public methods are intended to be used in the
 * GensonBuilder "style" and its protected methods are part of the template. When you call {@link
 * #create()} method, it will start assembling all the configuration and build all the required
 * components by using the protected methods. For example if you wish to use in your projects a
 * GensonBuilder that will always create some custom {@link
 * com.owlike.genson.reflect.BeanDescriptorProvider BeanDescriptorProvider} you have to extend
 * {@link #createBeanDescriptorProvider()}, or imagine that you implemented some Converters that you
 * always want to register then override {@link #getDefaultConverters()}.
 *
 * @author eugen
 */
public class GensonBuilder {
  private final Map<Type, Serializer<?>> serializersMap = new HashMap<Type, Serializer<?>>();
  private final Map<Type, Deserializer<?>> deserializersMap = new HashMap<Type, Deserializer<?>>();
  private final List<Factory<?>> converterFactories = new ArrayList<Factory<?>>();
  private final List<ContextualFactory<?>> contextualFactories =
      new ArrayList<ContextualFactory<?>>();
  private final List<BeanPropertyFactory> beanPropertyFactories =
      new ArrayList<BeanPropertyFactory>();

  private boolean skipNull = false;
  private boolean htmlSafe = false;
  private boolean withClassMetadata = false;
  private boolean throwExcOnNoDebugInfo = false;
  private boolean useGettersAndSetters = true;
  private boolean useFields = true;
  private boolean withBeanViewConverter = false;
  private boolean useRuntimeTypeForSerialization = false;
  private boolean withDebugInfoPropertyNameResolver = false;
  private boolean strictDoubleParse = false;
  private boolean indent = false;
  private boolean metadata = false;
  private boolean failOnMissingProperty = false;

  private List<GensonBundle> _bundles = new ArrayList<GensonBundle>();

  private PropertyNameResolver propertyNameResolver;
  private BeanMutatorAccessorResolver mutatorAccessorResolver;
  private VisibilityFilter propertyFilter = VisibilityFilter.PACKAGE_PUBLIC;
  private VisibilityFilter methodFilter = VisibilityFilter.PACKAGE_PUBLIC;
  private VisibilityFilter constructorFilter = VisibilityFilter.PACKAGE_PUBLIC;

  private ClassLoader classLoader = getClass().getClassLoader();
  private BeanDescriptorProvider beanDescriptorProvider;
  private DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance();
  private boolean useDateAsTimestamp = true;
  private boolean classMetadataWithStaticType = true;

  // for the moment we don't allow to override
  private BeanViewDescriptorProvider beanViewDescriptorProvider;

  private final Map<String, Class<?>> withClassAliases = new HashMap<String, Class<?>>();
  private final Map<Class<?>, BeanView<?>> registeredViews = new HashMap<Class<?>, BeanView<?>>();

  private ChainedFactory customFactoryChain;

  private final Map<Class<?>, Object> defaultValues = new HashMap<Class<?>, Object>();
  private boolean failOnNullPrimitive = false;
  private RuntimePropertyFilter runtimePropertyFilter = RuntimePropertyFilter.noFilter;

  public GensonBuilder() {
    defaultValues.put(int.class, 0);
    defaultValues.put(long.class, 0l);
    defaultValues.put(short.class, (short) 0);
    defaultValues.put(double.class, 0d);
    defaultValues.put(float.class, 0f);
    defaultValues.put(boolean.class, false);
    defaultValues.put(byte.class, (byte) 0);
    defaultValues.put(char.class, '\u0000');
  }

  /**
   * Alias used in serialized class metadata instead of the full class name. See {@link
   * com.owlike.genson.convert.ClassMetadataConverter ClassMetadataConverter} for more metadata. If
   * you add an alias, it will automatically enable the class metadata feature, as if you used
   * {@link #useClassMetadata(boolean)}.
   *
   * @param alias
   * @param forClass
   * @return a reference to this builder.
   */
  public GensonBuilder addAlias(String alias, Class<?> forClass) {
    withClassMetadata = true;
    withClassAliases.put(alias, forClass);
    return this;
  }

  /**
   * Registers converters mapping them to their corresponding parameterized type.
   *
   * @param converter
   * @return a reference to this builder.
   */
  public GensonBuilder withConverters(Converter<?>... converter) {
    for (Converter<?> c : converter) {
      Type typeOfConverter =
          TypeUtil.typeOf(0, TypeUtil.lookupGenericType(Converter.class, c.getClass()));
      typeOfConverter = TypeUtil.expandType(typeOfConverter, c.getClass());
      registerConverter(c, typeOfConverter);
    }
    return this;
  }

  /**
   * Register converter by mapping it to type argument.
   *
   * @param converter to register
   * @param type of objects this converter handles
   * @return a reference to this builder.
   */
  public <T> GensonBuilder withConverter(Converter<T> converter, Class<? extends T> type) {
    registerConverter(converter, type);
    return this;
  }

  /**
   * Register converter by mapping it to the parameterized type of type argument.
   *
   * @param converter to register
   * @param type of objects this converter handles
   * @return a reference to this builder.
   */
  public <T> GensonBuilder withConverter(Converter<T> converter, GenericType<? extends T> type) {
    registerConverter(converter, type.getType());
    return this;
  }

  private <T> void registerConverter(Converter<T> converter, Type type) {
    if (serializersMap.containsKey(type))
      throw new IllegalStateException(
          "Can not register converter "
              + converter.getClass()
              + ". A custom serializer is already registered for type "
              + type);
    if (deserializersMap.containsKey(type))
      throw new IllegalStateException(
          "Can not register converter "
              + converter.getClass()
              + ". A custom deserializer is already registered for type "
              + type);
    serializersMap.put(type, converter);
    deserializersMap.put(type, converter);
  }

  public GensonBuilder withSerializers(Serializer<?>... serializer) {
    for (Serializer<?> s : serializer) {
      Type typeOfConverter =
          TypeUtil.typeOf(0, TypeUtil.lookupGenericType(Serializer.class, s.getClass()));
      typeOfConverter = TypeUtil.expandType(typeOfConverter, s.getClass());
      registerSerializer(s, typeOfConverter);
    }
    return this;
  }

  public <T> GensonBuilder withSerializer(Serializer<T> serializer, Class<? extends T> type) {
    registerSerializer(serializer, type);
    return this;
  }

  public <T> GensonBuilder withSerializer(Serializer<T> serializer, GenericType<? extends T> type) {
    registerSerializer(serializer, type.getType());
    return this;
  }

  private <T> void registerSerializer(Serializer<T> serializer, Type type) {
    if (serializersMap.containsKey(type))
      throw new IllegalStateException(
          "Can not register serializer "
              + serializer.getClass()
              + ". A custom serializer is already registered for type "
              + type);
    serializersMap.put(type, serializer);
  }

  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;
  }

  public <T> GensonBuilder withDeserializer(Deserializer<T> deserializer, Class<? extends T> type) {
    registerDeserializer(deserializer, type);
    return this;
  }

  public <T> GensonBuilder withDeserializer(
      Deserializer<T> deserializer, GenericType<? extends T> type) {
    registerDeserializer(deserializer, type.getType());
    return this;
  }

  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);
  }

  /**
   * Registers converter factories.
   *
   * @param factory to register
   * @return a reference to this builder.
   */
  public GensonBuilder withConverterFactory(Factory<? extends Converter<?>> factory) {
    converterFactories.add(factory);
    return this;
  }

  /**
   * Registers serializer factories.
   *
   * @param factory to register
   * @return a reference to this builder.
   */
  public GensonBuilder withSerializerFactory(Factory<? extends Serializer<?>> factory) {
    converterFactories.add(factory);
    return this;
  }

  /**
   * Registers deserializer factories.
   *
   * @param factory to register
   * @return a reference to this builder.
   */
  public GensonBuilder withDeserializerFactory(Factory<? extends Deserializer<?>> factory) {
    converterFactories.add(factory);
    return this;
  }

  /**
   * ContextualFactory is actually in a beta status, it will not be removed, but might be
   * refactored.
   */
  public GensonBuilder withContextualFactory(ContextualFactory<?>... factories) {
    contextualFactories.addAll(Arrays.asList(factories));
    return this;
  }

  /**
   * A ChainedFactory provides a way to use custom Converters that have access to the default
   * Converters. An example of use is to wrap incoming/outgoing json in a root object and delegate
   * then the ser/de to the default Converter.
   *
   * <p>This mechanism is internally used by Genson to decorate the different Converters with
   * additional behaviour (null handling, ser/de of polymorphic types with class info, runtime type
   * based ser/de, etc).
   *
   * <p>Note that you can't use it in situations where you want to start reading/writing some
   * partial infos and want to delegate the rest to the default Converter.
   */
  public GensonBuilder withConverterFactory(ChainedFactory chainedFactory) {
    if (customFactoryChain == null) customFactoryChain = chainedFactory;
    else {
      customFactoryChain.append(chainedFactory);
    }
    return this;
  }

  /**
   * Allows you to register new BeanPropertyFactory responsible of creating BeanProperty accessors,
   * mutators and BeanCreators. This is a very low level feature, you probably don't need it.
   */
  public GensonBuilder withBeanPropertyFactory(BeanPropertyFactory... factories) {
    beanPropertyFactories.addAll(Arrays.asList(factories));
    return this;
  }

  /**
   * Register some genson bundles. For example to enable JAXB support:
   *
   * <p>
   *
   * <pre>
   * builder.withBundle(new JAXBExtension());
   * </pre>
   *
   * <b>All bundles should be registered before any other customization.</b>
   *
   * @see GensonBundle
   */
  public GensonBuilder withBundle(GensonBundle... bundles) {
    for (GensonBundle bundle : bundles) {
      bundle.configure(this);
      _bundles.add(bundle);
    }
    return this;
  }

  /**
   * Override the default classloader
   *
   * @param loader classloader which will be used to load classes while deserializing
   * @return a reference to this builder
   */
  public GensonBuilder withClassLoader(ClassLoader loader) {
    classLoader = loader;
    return this;
  }

  /**
   * Replaces default {@link com.owlike.genson.reflect.BeanMutatorAccessorResolver
   * BeanMutatorAccessorResolver} by the specified one.
   *
   * @param resolver
   * @return a reference to this builder.
   */
  public GensonBuilder set(BeanMutatorAccessorResolver resolver) {
    mutatorAccessorResolver = resolver;
    return this;
  }

  /**
   * Replaces default {@link com.owlike.genson.reflect.PropertyNameResolver PropertyNameResolver} by
   * the specified one.
   *
   * @param resolver
   * @return a reference to this builder.
   */
  public GensonBuilder set(PropertyNameResolver resolver) {
    propertyNameResolver = resolver;
    return this;
  }

  /**
   * Register additional BeanMutatorAccessorResolver that will be used before the standard ones.
   *
   * @param resolvers
   * @return a reference to this builder.
   */
  public GensonBuilder with(BeanMutatorAccessorResolver... resolvers) {
    if (mutatorAccessorResolver == null)
      mutatorAccessorResolver = createBeanMutatorAccessorResolver();
    if (mutatorAccessorResolver instanceof BeanMutatorAccessorResolver.CompositeResolver)
      ((BeanMutatorAccessorResolver.CompositeResolver) mutatorAccessorResolver).add(resolvers);
    else
      throw new IllegalStateException(
          "You can not add multiple resolvers if the base resolver is not of type "
              + BeanMutatorAccessorResolver.CompositeResolver.class.getName());
    return this;
  }

  public Map<Type, Serializer<?>> getSerializersMap() {
    return Collections.unmodifiableMap(serializersMap);
  }

  public Map<Type, Deserializer<?>> getDeserializersMap() {
    return Collections.unmodifiableMap(deserializersMap);
  }

  public ClassLoader getClassLoader() {
    return classLoader;
  }

  /**
   * Registers the specified resolvers in the order they were defined and before the standard ones.
   *
   * @param resolvers
   * @return a reference to this builder.
   */
  public GensonBuilder with(PropertyNameResolver... resolvers) {
    if (propertyNameResolver == null) propertyNameResolver = createPropertyNameResolver();
    if (propertyNameResolver instanceof PropertyNameResolver.CompositePropertyNameResolver)
      ((PropertyNameResolver.CompositePropertyNameResolver) propertyNameResolver).add(resolvers);
    else
      throw new IllegalStateException(
          "You can not add multiple resolvers if the base resolver is not of type "
              + PropertyNameResolver.CompositePropertyNameResolver.class.getName());
    return this;
  }

  /** Renames all fields named field to toName. */
  public GensonBuilder rename(String field, String toName) {
    return rename(field, null, toName, null);
  }

  /** Renames all fields of type fieldOfType to toName. */
  public GensonBuilder rename(Class<?> fieldOfType, String toName) {
    return rename(null, null, toName, fieldOfType);
  }

  /** Renames all fields named field declared in class fromClass to toName. */
  public GensonBuilder rename(String field, Class<?> fromClass, String toName) {
    return rename(field, fromClass, toName, null);
  }

  /** Renames all fields named field and of type fieldOfType to toName. */
  public GensonBuilder rename(String field, String toName, Class<?> fieldOfType) {
    return rename(field, null, toName, fieldOfType);
  }

  /** Renames all fields named field, of type fieldOfType and declared in fromClass to toName. */
  public GensonBuilder rename(
      final String field, final Class<?> fromClass, final String toName, final Class<?> ofType) {
    return with(new RenamingPropertyNameResolver(field, fromClass, ofType, toName));
  }

  public GensonBuilder exclude(String field) {
    return filter(field, null, null, true);
  }

  public GensonBuilder exclude(Class<?> fieldOfType) {
    return filter(null, null, fieldOfType, true);
  }

  public GensonBuilder exclude(String field, Class<?> fromClass) {
    return filter(field, fromClass, null, true);
  }

  public GensonBuilder exclude(String field, Class<?> fromClass, Class<?> ofType) {
    return filter(field, fromClass, ofType, true);
  }

  public GensonBuilder include(String field) {
    return filter(field, null, null, false);
  }

  public GensonBuilder include(Class<?> fieldOfType) {
    return filter(null, null, fieldOfType, false);
  }

  public GensonBuilder include(String field, Class<?> fromClass) {
    return filter(field, fromClass, null, false);
  }

  public GensonBuilder include(String field, Class<?> fromClass, Class<?> ofType) {
    return filter(field, fromClass, ofType, false);
  }

  private GensonBuilder filter(
      final String field,
      final Class<?> declaringClass,
      final Class<?> ofType,
      final boolean exclude) {
    return with(new PropertyFilter(exclude, field, declaringClass, ofType));
  }

  /**
   * If true will not serialize null values
   *
   * @param skipNull indicates whether null values should be serialized or not.
   * @return a reference to this builder.
   */
  public GensonBuilder setSkipNull(boolean skipNull) {
    this.skipNull = skipNull;
    return this;
  }

  public boolean isSkipNull() {
    return skipNull;
  }

  /**
   * If true \,<,>,&,= characters will be replaced by \u0027, \u003c, \u003e, \u0026, \u003d
   *
   * @param htmlSafe indicates whether serialized data should be html safe.
   * @return a reference to this builder.
   */
  public GensonBuilder setHtmlSafe(boolean htmlSafe) {
    this.htmlSafe = htmlSafe;
    return this;
  }

  public boolean isHtmlSafe() {
    return htmlSafe;
  }

  /**
   * Indicates whether class metadata should be serialized and used during deserialization.
   *
   * @see com.owlike.genson.convert.ClassMetadataConverter ClassMetadataConverter
   */
  public GensonBuilder useClassMetadata(boolean enabled) {
    this.withClassMetadata = enabled;
    this.metadata = true;
    return this;
  }

  /**
   * Specifies the data format that should be used for java.util.Date serialization and
   * deserialization.
   *
   * @param dateFormat
   * @return a reference to this builder.
   */
  public GensonBuilder useDateFormat(DateFormat dateFormat) {
    this.dateFormat = dateFormat;
    return this;
  }

  public boolean isThrowExceptionOnNoDebugInfo() {
    return throwExcOnNoDebugInfo;
  }

  /**
   * Used in conjunction with {@link #useConstructorWithArguments(boolean)}. If true an exception
   * will be thrown when a class has been compiled without debug informations.
   *
   * @param throwExcOnNoDebugInfo
   * @return a reference to this builder.
   * @see com.owlike.genson.reflect.ASMCreatorParameterNameResolver ASMCreatorParameterNameResolver
   */
  public GensonBuilder setThrowExceptionIfNoDebugInfo(boolean throwExcOnNoDebugInfo) {
    this.throwExcOnNoDebugInfo = throwExcOnNoDebugInfo;
    return this;
  }

  /**
   * If true, getters and setters would be used during serialization/deserialization in favor of
   * fields. If there is not getter/setter for a field then the field will be used, except if you
   * specified that fields should not be used with {@link #useFields(boolean)}. By default getters,
   * setters and fields will be used.
   */
  public GensonBuilder useMethods(boolean enabled) {
    this.useGettersAndSetters = enabled;
    return this;
  }

  public GensonBuilder useMethods(boolean enabled, VisibilityFilter visibility) {
    useMethods(enabled);
    return setMethodFilter(visibility);
  }

  /**
   * If true, fields will be used when no getter/setter is available, except if you specified that
   * no getter/setter should be used with {@link #useMethods(boolean)}, in that case only fields
   * will be used. By default getters, setters and fields will be used.
   */
  public GensonBuilder useFields(boolean enabled) {
    this.useFields = enabled;
    return this;
  }

  public GensonBuilder useFields(boolean enabled, VisibilityFilter visibility) {
    useFields(enabled);
    return setFieldFilter(visibility);
  }

  /** If true {@link BeanView} mechanism will be enabled. */
  public GensonBuilder useBeanViews(boolean enabled) {
    this.withBeanViewConverter = enabled;
    return this;
  }

  /**
   * If true the concrete type of the serialized object will always be used. So if you have
   * List<Number> type it will not use the Number serializer but the one for the concrete type of
   * the current value.
   *
   * @param enabled
   * @return a reference to this builder.
   */
  public GensonBuilder useRuntimeType(boolean enabled) {
    this.useRuntimeTypeForSerialization = enabled;
    return this;
  }

  /**
   * If true constructor and method arguments name will be resolved from the generated debug symbols
   * during compilation. It is a very powerful feature from Genson, you should have a look at {@link
   * com.owlike.genson.reflect.ASMCreatorParameterNameResolver ASMCreatorParameterNameResolver}.
   *
   * @param enabled
   * @return a reference to this builder.
   * @see #setThrowExceptionIfNoDebugInfo(boolean)
   */
  public GensonBuilder useConstructorWithArguments(boolean enabled) {
    this.withDebugInfoPropertyNameResolver = enabled;
    return this;
  }

  public GensonBuilder setFieldFilter(VisibilityFilter propertyFilter) {
    this.propertyFilter = propertyFilter;
    return this;
  }

  public GensonBuilder setMethodFilter(VisibilityFilter methodFilter) {
    this.methodFilter = methodFilter;
    return this;
  }

  public GensonBuilder setConstructorFilter(VisibilityFilter constructorFilter) {
    this.constructorFilter = constructorFilter;
    return this;
  }

  public GensonBuilder useStrictDoubleParse(boolean strictDoubleParse) {
    this.strictDoubleParse = strictDoubleParse;
    return this;
  }

  /**
   * If true outputed json will be indented using two spaces, otherwise (by default) all is printed
   * on same line.
   */
  public GensonBuilder useIndentation(boolean indent) {
    this.indent = indent;
    return this;
  }

  public GensonBuilder useDateAsTimestamp(boolean enabled) {
    this.useDateAsTimestamp = enabled;
    return this;
  }

  public GensonBuilder useMetadata(boolean metadata) {
    this.metadata = metadata;
    return this;
  }

  public GensonBuilder useByteAsInt(boolean enable) {
    if (enable) {
      withConverters(DefaultConverters.ByteArrayAsIntArrayConverter.instance);
    }
    return this;
  }

  /**
   * If set to true, Genson will throw a JsonBindingException when it encounters a property in the
   * incoming json that does not match a property in the class. False by default.
   *
   * @param enable
   * @return
   */
  public GensonBuilder failOnMissingProperty(boolean enable) {
    this.failOnMissingProperty = enable;
    return this;
  }

  /**
   * If set to false, during serialization class metadata will be serialized only for types where
   * the runtime type differs from the static one. Ex:
   *
   * <pre>
   * class Person {
   *   public Address address;
   * }
   * </pre>
   *
   * Here if the concrete instance of address is Address then this type will not be serialized as
   * metadata, but if they differ then it is serialized. By default this option is true, all types
   * are serialized.
   *
   * @param enable
   * @return
   */
  public GensonBuilder useClassMetadataWithStaticType(boolean enable) {
    this.classMetadataWithStaticType = enable;
    return this;
  }

  /**
   * Wrap a single value into a list when a list is expected. Useful when dealing with APIs that
   * unwrap arrays containing a single value. Disabled by default.
   */
  public GensonBuilder acceptSingleValueAsList(boolean enable) {
    if (enable) withConverterFactory(DefaultConverters.SingleValueAsListFactory.instance);
    return this;
  }

  /** Uses the passed value as the default value for this type. */
  public GensonBuilder useDefaultValue(Object value, Class<?> targetType) {
    defaultValues.put(targetType, value);
    return this;
  }

  /**
   * Will wrap all the root objects under outputKey during serializaiton and unwrap the content
   * under inputKey during deserializaiton. For example: <code>
   *   Genson genson = new GensonBuilder().wrapRootValues("request", "response").create();
   *
   *   // would produce: {"response": {... person properties ...}}
   *   genson.serialize(person);
   *
   *   Person p = genson.deserialize("{\"request\":{...}}", Person.class);
   * </code> If you need this mechanism only for some types or using different root keys, then you
   * can register JaxbBundle with wrapRootValues(true) and annotate the specific classes with
   * XmlRootElement.
   */
  public GensonBuilder wrapRootValues(final String inputKey, final String outputKey) {
    return withConverterFactory(
        new ChainedFactory() {
          @Override
          protected Converter<?> create(Type type, Genson genson, Converter<?> nextConverter) {

            return new DefaultConverters.WrappedRootValueConverter<Object>(
                inputKey, outputKey, (Converter<Object>) nextConverter);
          }
        });
  }

  /**
   * False by default. When enabled a JsonBindingException will be thrown if null is encountered
   * during serialization (should never happen) or deserialization for a primitive type.
   */
  public GensonBuilder failOnNullPrimitive(boolean enabled) {
    this.failOnNullPrimitive = enabled;
    return this;
  }

  public GensonBuilder useRuntimePropertyFilter(RuntimePropertyFilter filter) {
    this.runtimePropertyFilter = filter;
    return this;
  }

  /**
   * Creates an instance of Genson. You may use this method as many times you want. It wont change
   * the state of the builder, in sense that the returned instance will have always the same
   * configuration.
   *
   * @return a new instance of Genson built for the current configuration.
   */
  public Genson create() {
    if (propertyNameResolver == null) propertyNameResolver = createPropertyNameResolver();
    if (mutatorAccessorResolver == null)
      mutatorAccessorResolver = createBeanMutatorAccessorResolver();

    List<Converter<?>> converters = getDefaultConverters();
    addDefaultSerializers(converters);
    addDefaultDeserializers(converters);
    addDefaultSerializers(getDefaultSerializers());
    addDefaultDeserializers(getDefaultDeserializers());

    List<Factory<? extends Converter<?>>> convFactories =
        new ArrayList<Factory<? extends Converter<?>>>();
    addDefaultConverterFactories(convFactories);
    converterFactories.addAll(convFactories);

    List<Factory<? extends Serializer<?>>> serializerFactories =
        new ArrayList<Factory<? extends Serializer<?>>>();
    addDefaultSerializerFactories(serializerFactories);
    converterFactories.addAll(serializerFactories);

    List<Factory<? extends Deserializer<?>>> deserializerFactories =
        new ArrayList<Factory<? extends Deserializer<?>>>();
    addDefaultDeserializerFactories(deserializerFactories);
    converterFactories.addAll(deserializerFactories);

    List<ContextualFactory<?>> defaultContextualFactories = new ArrayList<ContextualFactory<?>>();
    addDefaultContextualFactories(defaultContextualFactories);
    contextualFactories.addAll(defaultContextualFactories);

    beanDescriptorProvider = createBeanDescriptorProvider();

    if (withBeanViewConverter) {
      List<BeanMutatorAccessorResolver> resolvers = new ArrayList<BeanMutatorAccessorResolver>();
      resolvers.add(new BeanViewDescriptorProvider.BeanViewMutatorAccessorResolver());
      resolvers.add(mutatorAccessorResolver);
      beanViewDescriptorProvider =
          new BeanViewDescriptorProvider(
              new AbstractBeanDescriptorProvider.ContextualConverterFactory(contextualFactories),
              registeredViews,
              createBeanPropertyFactory(),
              new BeanMutatorAccessorResolver.CompositeResolver(resolvers),
              getPropertyNameResolver());
    }

    return create(createConverterFactory(), withClassAliases);
  }

  private void addDefaultSerializers(List<? extends Serializer<?>> serializers) {
    if (serializers != null) {
      for (Serializer<?> serializer : serializers) {
        Type typeOfConverter =
            TypeUtil.typeOf(0, TypeUtil.lookupGenericType(Serializer.class, serializer.getClass()));
        typeOfConverter = TypeUtil.expandType(typeOfConverter, serializer.getClass());
        if (!serializersMap.containsKey(typeOfConverter))
          serializersMap.put(typeOfConverter, serializer);
      }
    }
  }

  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);
      }
    }
  }

  /**
   * In theory this allows you to extend Genson class and to instantiate it, but actually you can
   * not do it as Genson class is final. If some uses cases are discovered it may change.
   *
   * @param converterFactory
   * @param classAliases
   * @return a new Genson instance.
   */
  protected Genson create(
      Factory<Converter<?>> converterFactory, Map<String, Class<?>> classAliases) {
    return new Genson(
        converterFactory,
        getBeanDescriptorProvider(),
        isSkipNull(),
        isHtmlSafe(),
        classAliases,
        withClassMetadata,
        strictDoubleParse,
        indent,
        metadata,
        failOnMissingProperty,
        defaultValues,
        runtimePropertyFilter);
  }

  /**
   * You should override this method if you want to add custom {@link
   * com.owlike.genson.convert.ChainedFactory ChainedFactory} or if you need to chain them
   * differently.
   *
   * @return the converter <u>factory instance that will be used to resolve <strong>ALL</strong>
   *     converters</u>.
   */
  protected Factory<Converter<?>> createConverterFactory() {
    ChainedFactory chainHead = new CircularClassReferenceConverterFactory();

    chainHead.append(new NullConverterFactory(failOnNullPrimitive));

    if (useRuntimeTypeForSerialization)
      chainHead.append(new RuntimeTypeConverter.RuntimeTypeConverterFactory());

    chainHead.append(
        new ClassMetadataConverter.ClassMetadataConverterFactory(classMetadataWithStaticType));

    if (customFactoryChain != null) chainHead.append(customFactoryChain);

    if (withBeanViewConverter)
      chainHead.append(
          new BeanViewConverter.BeanViewConverterFactory(getBeanViewDescriptorProvider()));

    ContextualFactoryDecorator ctxFactoryDecorator =
        new ContextualFactoryDecorator(
            new BasicConvertersFactory(
                getSerializersMap(),
                getDeserializersMap(),
                getFactories(),
                getBeanDescriptorProvider()));

    chainHead.append(ctxFactoryDecorator);

    return chainHead;
  }

  protected BeanMutatorAccessorResolver createBeanMutatorAccessorResolver() {
    List<BeanMutatorAccessorResolver> resolvers = new ArrayList<BeanMutatorAccessorResolver>();
    resolvers.add(new BeanMutatorAccessorResolver.GensonAnnotationsResolver());

    resolvers.add(
        new BeanMutatorAccessorResolver.StandardMutaAccessorResolver(
            propertyFilter, methodFilter, constructorFilter));

    return new BeanMutatorAccessorResolver.CompositeResolver(resolvers);
  }

  /**
   * You can override this method if you want to change the {@link
   * com.owlike.genson.reflect.PropertyNameResolver PropertyNameResolver} that are registered by
   * default. You can also simply replace the default PropertyNameResolver by setting another one
   * with {@link #set(PropertyNameResolver)}.
   *
   * @return the property name resolver to be used. It should be an instance of {@link
   *     com.owlike.genson.reflect.PropertyNameResolver.CompositePropertyNameResolver
   *     PropertyNameResolver.CompositePropertyNameResolver}, otherwise you will not be able to add
   *     others PropertyNameResolvers using {@link #with(PropertyNameResolver...)} method.
   */
  protected PropertyNameResolver createPropertyNameResolver() {
    List<PropertyNameResolver> resolvers = new ArrayList<PropertyNameResolver>();
    resolvers.add(new PropertyNameResolver.AnnotationPropertyNameResolver());
    resolvers.add(new PropertyNameResolver.ConventionalBeanPropertyNameResolver());
    if (withDebugInfoPropertyNameResolver)
      resolvers.add(new ASMCreatorParameterNameResolver(isThrowExceptionOnNoDebugInfo()));

    return new PropertyNameResolver.CompositePropertyNameResolver(resolvers);
  }

  /**
   * You can override this methods if you want to change the default converters (remove some, change
   * the order, etc).
   *
   * @return the default converters list, must be not null.
   */
  protected List<Converter<?>> getDefaultConverters() {
    List<Converter<?>> converters = new ArrayList<Converter<?>>();
    converters.add(DefaultConverters.StringConverter.instance);
    converters.add(DefaultConverters.NumberConverter.instance);
    converters.add(new DefaultConverters.DateConverter(dateFormat, useDateAsTimestamp));
    converters.add(DefaultConverters.URLConverter.instance);
    converters.add(DefaultConverters.URIConverter.instance);
    converters.add(DefaultConverters.TimestampConverter.instance);
    converters.add(DefaultConverters.BigDecimalConverter.instance);
    converters.add(DefaultConverters.BigIntegerConverter.instance);
    converters.add(DefaultConverters.UUIDConverter.instance);
    converters.add(DefaultConverters.FileConverter.instance);
    return converters;
  }

  /**
   * Override this method if you want to change the default converter factories.
   *
   * @param factories list, is not null.
   */
  protected void addDefaultConverterFactories(List<Factory<? extends Converter<?>>> factories) {
    factories.add(DefaultConverters.ArrayConverterFactory.instance);
    factories.add(DefaultConverters.CollectionConverterFactory.instance);
    factories.add(DefaultConverters.MapConverterFactory.instance);
    factories.add(DefaultConverters.EnumConverterFactory.instance);
    factories.add(DefaultConverters.PrimitiveConverterFactory.instance);
    factories.add(DefaultConverters.UntypedConverterFactory.instance);
    factories.add(
        new DefaultConverters.CalendarConverterFactory(
            new DefaultConverters.DateConverter(dateFormat, useDateAsTimestamp)));
  }

  protected void addDefaultContextualFactories(List<ContextualFactory<?>> factories) {
    factories.add(new DefaultConverters.DateContextualFactory());
    factories.add(new DefaultConverters.PropertyConverterFactory());
  }

  protected List<Serializer<?>> getDefaultSerializers() {
    return null;
  }

  protected void addDefaultSerializerFactories(
      List<Factory<? extends Serializer<?>>> serializerFactories) {}

  protected List<Deserializer<?>> getDefaultDeserializers() {
    return null;
  }

  protected void addDefaultDeserializerFactories(
      List<Factory<? extends Deserializer<?>>> deserializerFactories) {}

  /**
   * Creates the standard BeanDescriptorProvider that will be used to provide {@link
   * com.owlike.genson.reflect.BeanDescriptor BeanDescriptor} instances for
   * serialization/deserialization of all types that couldn't be handled by standard and custom
   * converters and converter factories.
   *
   * @return the BeanDescriptorProvider instance.
   */
  protected BeanDescriptorProvider createBeanDescriptorProvider() {

    ContextualConverterFactory contextualConverterFactory =
        new ContextualConverterFactory(contextualFactories);
    BeanPropertyFactory beanPropertyFactory = createBeanPropertyFactory();

    List<BeanDescriptorProvider> providers = new ArrayList<BeanDescriptorProvider>();
    for (GensonBundle bundle : _bundles) {
      BeanDescriptorProvider provider =
          bundle.createBeanDescriptorProvider(
              contextualConverterFactory,
              beanPropertyFactory,
              getMutatorAccessorResolver(),
              getPropertyNameResolver(),
              this);

      if (provider != null) providers.add(provider);
    }

    providers.add(
        new BaseBeanDescriptorProvider(
            new AbstractBeanDescriptorProvider.ContextualConverterFactory(contextualFactories),
            createBeanPropertyFactory(),
            getMutatorAccessorResolver(),
            getPropertyNameResolver(),
            useGettersAndSetters,
            useFields,
            true));

    return new CompositeBeanDescriptorProvider(providers);
  }

  protected BeanPropertyFactory createBeanPropertyFactory() {
    if (withBeanViewConverter)
      beanPropertyFactories.add(
          new BeanViewDescriptorProvider.BeanViewPropertyFactory(registeredViews));
    beanPropertyFactories.add(new BeanPropertyFactory.StandardFactory());
    return new BeanPropertyFactory.CompositeFactory(beanPropertyFactories);
  }

  protected final PropertyNameResolver getPropertyNameResolver() {
    return propertyNameResolver;
  }

  protected final BeanMutatorAccessorResolver getMutatorAccessorResolver() {
    return mutatorAccessorResolver;
  }

  protected final BeanDescriptorProvider getBeanDescriptorProvider() {
    return beanDescriptorProvider;
  }

  protected final BeanViewDescriptorProvider getBeanViewDescriptorProvider() {
    return beanViewDescriptorProvider;
  }

  public final List<Factory<?>> getFactories() {
    return Collections.unmodifiableList(converterFactories);
  }

  public final boolean isDateAsTimestamp() {
    return useDateAsTimestamp;
  }
}
  public void onComplexEvent(String theEvent) {
    DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance();
    String date = dateFormat.format(new Date());

    System.out.println("CEP: " + date + " " + theEvent);
  }
Exemplo n.º 19
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.umeng_fb_activity_conversation);
    agent = new FeedbackAgent(this);

    layoutBack = (LinearLayout) findViewById(R.id.umeng_left_layout);

    // backBtn = (ImageView) this.findViewById(com.umeng.fb.res.IdMapper.umeng_fb_back(this));
    // saveBtn = (ImageView) this.findViewById(com.umeng.fb.res.IdMapper.umeng_fb_save(this));
    // contactInfoEdit = (EditText)
    // this.findViewById(com.umeng.fb.res.IdMapper.umeng_fb_contact_info(this));
    contactInfoEdit = (EditText) findViewById(R.id.umeng_fb_reply_content);
    // lastUpdateAtText = (TextView)
    // this.findViewById(com.umeng.fb.res.IdMapper.umeng_fb_contact_update_at(this));
    lastUpdateAtText = (TextView) findViewById(R.id.umeng_fb_contact_update_at);
    try {
      String contact_info = agent.getUserInfo().getContact().get(KEY_UMENG_CONTACT_INFO_PLAIN_TEXT);
      contactInfoEdit.setText(contact_info);

      long time = agent.getUserInfoLastUpdateAt();

      if (time > 0) {
        Date date = new Date(time);
        // String prefix =
        // this.getResources().getString(com.umeng.fb.res.StringMapper.umeng_fb_contact_update_at(this));
        String prefix = this.getResources().getString(R.string.umeng_fb_contact_update_at);
        lastUpdateAtText.setText(prefix + SimpleDateFormat.getDateTimeInstance().format(date));
        lastUpdateAtText.setVisibility(View.VISIBLE);
      } else {
        lastUpdateAtText.setVisibility(View.GONE);
      }

      // If user has never entered any contact information, request focus
      // on the edittext on startup.
      if (Utility.isNullOrEmpty(contact_info)) {
        contactInfoEdit.requestFocus();
        InputMethodManager imm =
            (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
      }

    } catch (NullPointerException e) {
      e.printStackTrace();
    }

    layoutBack.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            back();
          }
        });
    saveBtn.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            try {
              UserInfo info = agent.getUserInfo();
              if (info == null) info = new UserInfo();
              Map<String, String> contact = info.getContact();
              if (contact == null) contact = new HashMap<String, String>();
              String contact_info = contactInfoEdit.getEditableText().toString();
              contact.put(KEY_UMENG_CONTACT_INFO_PLAIN_TEXT, contact_info);
              info.setContact(contact);

              //					Map<String, String> remark = info.getRemark();
              //					if (remark == null)
              //						remark = new HashMap<String, String>();
              //					remark.put("tag1", "game");
              //					info.setRemark(remark);

              agent.setUserInfo(info);

            } catch (Exception e) {
              e.printStackTrace();
            }
            back();
          }
        });
  }