Exemplo n.º 1
0
 private MetricBuilder() {
   GsonBuilder builder = new GsonBuilder();
   builder.registerTypeAdapter(CustomAggregator.class, new CustomAggregatorSerializer());
   builder.registerTypeAdapter(CustomGrouper.class, new CustomGrouperSerializer());
   builder.registerTypeAdapter(DataPoint.class, new DataPointSerializer());
   mapper = builder.create();
 }
 public static GsonBuilder registerTypeAdapters(GsonBuilder builder) {
   builder.registerTypeAdapter(StringFilter.FilterSet.class, new FilterSetAdapter());
   builder.registerTypeAdapter(StringFilter.WhiteList.class, new PatternListAdapter());
   builder.registerTypeAdapter(StringFilter.BlackList.class, new PatternListAdapter());
   builder.registerTypeAdapter(StringFilter.class, new GeneralAdapter());
   return builder;
 }
Exemplo n.º 3
0
 public static Gson create() {
   GsonBuilder gsonBuilder = new GsonBuilder();
   gsonBuilder.registerTypeAdapter(DateTime.class, new DateTimeDeserializer());
   gsonBuilder.registerTypeAdapter(RestResponse.class, new UserRestResponseConverter());
   // gsonBuilder.registerTypeAdapter(User.class, new UserGsonConverter());
   return gsonBuilder.create();
 }
Exemplo n.º 4
0
 private static Gson createGson() {
   GsonBuilder gsonBuilder = new GsonBuilder();
   gsonBuilder.registerTypeAdapter(Category.class, new CategoryDeserializer());
   gsonBuilder.registerTypeAdapter(Question.class, new QuestionDeserializer());
   gsonBuilder.registerTypeAdapter(Choice.class, new ChoiceDeserializer());
   return gsonBuilder.create();
 }
  /** @param args */
  public static void main(String[] args) {
    AssignedLabel al = new AssignedLabel("foo", "bar", "baz");
    System.out.println(al);
    String json = al.toString();
    GsonBuilder builder = new GsonBuilder();

    Type type = new TypeToken<AssignedLabel>() {}.getType();
    Type ctype = new TypeToken<CorrectLabel>() {}.getType();
    Type atype = new TypeToken<Collection<AssignedLabel>>() {}.getType();
    Type cattype = new TypeToken<Category>() {}.getType();
    Type catstype = new TypeToken<Collection<Category>>() {}.getType();
    Type mattype = new TypeToken<MultinomialConfusionMatrix>() {}.getType();

    builder.registerTypeAdapter(type, AssignedLabel.deserializer);
    builder.registerTypeAdapter(ctype, CorrectLabel.deserializer);
    builder.registerTypeAdapter(cattype, Category.deserializer);
    builder.registerTypeAdapter(mattype, MultinomialConfusionMatrix.deserializer);

    Gson gson = builder.create();
    System.out.println(gson.fromJson(json, type));
    System.out.println(gson.fromJson(json, type).getClass());
    CorrectLabel cl = new CorrectLabel("foo", "bar");
    System.out.println(cl);
    String t = cl.toString();
    System.out.println(gson.fromJson(t, ctype));
    System.out.println(gson.fromJson(t, ctype).getClass());

    Collection<AssignedLabel> col = new HashSet<AssignedLabel>();
    for (int i = 0; i < 10; i++) {
      String foo = i + "";
      col.add(new AssignedLabel(foo, foo, foo));
    }
    String tmp = gson.toJson(col);
    System.out.println(gson.fromJson(tmp, atype).getClass());

    Collection<Category> cats = new HashSet<Category>();
    for (int i = 0; i < 5; i++) {
      cats.add(new Category("" + i));
    }

    System.out.println(gson.toJson(cats));
    String foo = gson.toJson(cats);
    System.out.println(gson.fromJson(foo, catstype).getClass());

    Datum datum = new Datum("foo", new HashSet<Category>(cats));

    System.out.println(datum);

    Worker worker = new Worker("foo", new HashSet<Category>(cats));

    System.out.println(worker);

    ConfusionMatrix mat = new MultinomialConfusionMatrix(cats);
    String matrix = gson.toJson(mat);
    System.out.println(matrix);
    ConfusionMatrix mat2 = gson.fromJson(matrix, mattype);
    System.out.println(mat2.getClass());
  }
 private Gson getGson() {
   GsonBuilder builder = new GsonBuilder();
   builder.registerTypeAdapter(Integer.class, new IntegerDeserializer());
   builder.registerTypeAdapter(Faction.class, new FactionDeserializer());
   builder.registerTypeAdapter(CardSet.class, new CardSetDeserializer());
   builder.registerTypeAdapter(CardSet.class, new CardSetSerializer());
   builder.registerTypeAdapter(CardType.class, new CardTypeDeserializer());
   builder.registerTypeAdapter(Side.class, new SideDeserializer());
   Gson gson = builder.create();
   return gson;
 }
Exemplo n.º 7
0
 public static void init() {
   if (gson == null) {
     GsonBuilder gsonB = new GsonBuilder();
     gsonB
         .excludeFieldsWithoutExposeAnnotation(); // only fields marked with @Expose will only be
                                                  // considered
     gsonB.registerTypeAdapter(Exception.class, ExceptionTypeAdapter.FACTORY);
     gsonB.registerTypeAdapter(UUID.class, UUIDTypeAdapter.FACTORY);
     gsonB.registerTypeAdapter(
         JsonRequest.class, JsonRequestDefaultToStringDataDeserializer.FACTORY);
     gsonB.setDateFormat("d MMM yyyy"); // "1 Jan 2012"  based on java.text.DateFormat
     gson = gsonB.create();
   }
 }
 /**
  * Convenience method for returning a Gson object with a registered GSon TypeAdaptor i.e. custom
  * deserializer.
  *
  * @return A Gson object that can be used to convert Json into a {@link Event}.
  */
 public static Gson getGsonBuilder(Context context) {
   GsonBuilder gsonBuilder = new GsonBuilder();
   gsonBuilder.registerTypeAdapter(
       new TypeToken<Map<Event, Collection<Team>>>() {}.getType(),
       new EventsDeserializer(context));
   return gsonBuilder.create();
 }
 @Override
 public String asJsonString() {
   GsonBuilder builder = new GsonBuilder();
   builder.registerTypeAdapter(Model.class, new JsonModelAdapter());
   Gson gson = builder.create();
   return gson.toJson(this, modelType);
 }
Exemplo n.º 10
0
 public static GsonBuilder getBuilder(AbstractDeserializer... deserializers) {
   GsonBuilder builder = new GsonBuilder();
   for (AbstractDeserializer deserializer : deserializers) {
     builder.registerTypeAdapter(deserializer.getClazz(), deserializer);
   }
   return builder;
 }
Exemplo n.º 11
0
 public ConnectorStore() {
   GsonBuilder gsonBuilder = new GsonBuilder();
   gsonBuilder.registerTypeAdapter(UpdateInfo.class, new UpdateInfoSerializer());
   gson = gsonBuilder.create();
   mapper.setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
   mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
 }
Exemplo n.º 12
0
  private Note getNote(String key) throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();
    Gson gson =
        gsonBuilder.registerTypeAdapter(Date.class, new NotebookImportDeserializer()).create();

    S3Object s3object;
    try {
      s3object = s3client.getObject(new GetObjectRequest(bucketName, key));
    } catch (AmazonClientException ace) {
      throw new IOException("Unable to retrieve object from S3: " + ace, ace);
    }

    Note note;
    try (InputStream ins = s3object.getObjectContent()) {
      String json = IOUtils.toString(ins, conf.getString(ConfVars.ZEPPELIN_ENCODING));
      note = gson.fromJson(json, Note.class);
    }

    for (Paragraph p : note.getParagraphs()) {
      if (p.getStatus() == Status.PENDING || p.getStatus() == Status.RUNNING) {
        p.setStatus(Status.ABORT);
      }
    }

    return note;
  }
Exemplo n.º 13
0
 private <T> JsonResponse<T> commandResponse(String command, Type type) throws Exception {
   URI uri = this.getServerUri(command);
   //		URI uri = new URI( serverUri.toString() + URLEncoder.encode(command) );
   HttpURLConnection server = null;
   if (https) {
     server = (HttpsURLConnection) uri.toURL().openConnection();
   } else {
     server = (HttpURLConnection) uri.toURL().openConnection();
   }
   server.setConnectTimeout(30000);
   BufferedReader reader = new BufferedReader(new InputStreamReader(server.getInputStream()));
   // TypeToken cannot figure out T so instead it must be supplied
   // Type type = new TypeToken< JSONResponse<T> >() {}.getType();
   GsonBuilder build = new GsonBuilder();
   StringBuilder sBuild = new StringBuilder();
   String input;
   while ((input = reader.readLine()) != null) sBuild.append(input);
   reader.close();
   input = sBuild.toString();
   build.registerTypeAdapter(JsonBoolean.class, new JsonBooleanDeserializer());
   JsonResponse<T> response = null;
   try {
     response = build.create().fromJson(input, type);
     tryExtractError(response);
     return response;
   } catch (Exception e) {
     // well something messed up
     // if this part messes up then something REALLY bad happened
     response = build.create().fromJson(input, new TypeToken<JsonResponse<Object>>() {}.getType());
     tryExtractError(response);
     // DO NOT RETURN AN ACTUAL OBJECT!!!!!
     // this makes the code in the UI confused
     return null;
   }
 }
Exemplo n.º 14
0
  /**
   * import JSON as a new note.
   *
   * @param sourceJson - the note JSON to import
   * @param noteName - the name of the new note
   * @return notebook ID
   * @throws IOException
   */
  public Note importNote(String sourceJson, String noteName, AuthenticationInfo subject)
      throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();

    Gson gson =
        gsonBuilder.registerTypeAdapter(Date.class, new NotebookImportDeserializer()).create();
    JsonReader reader = new JsonReader(new StringReader(sourceJson));
    reader.setLenient(true);
    Note newNote;
    try {
      Note oldNote = gson.fromJson(reader, Note.class);
      newNote = createNote(subject);
      if (noteName != null) newNote.setName(noteName);
      else newNote.setName(oldNote.getName());
      List<Paragraph> paragraphs = oldNote.getParagraphs();
      for (Paragraph p : paragraphs) {
        newNote.addCloneParagraph(p);
      }

      newNote.persist(subject);
    } catch (IOException e) {
      logger.error(e.toString(), e);
      throw e;
    }

    return newNote;
  }
Exemplo n.º 15
0
  private void initRequestHelpers() {
    queue = Volley.newRequestQueue(this);

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Game.class, new TwitchResultItemParser());
    gson = builder.create();
  }
Exemplo n.º 16
0
 @Override
 public void register(GsonBuilder builder) {
   builder.registerTypeAdapter(Segment.class, this);
   new Getter.Serializer().register(builder);
   new Volume.Serializer().register(builder);
   new FlagType.Serializer().register(builder);
 }
Exemplo n.º 17
0
  public RESTServiceConnector(
      final RESTValidationStrategy validationStrategy,
      final List<Class<?>> classList,
      final List<JsonDeserializer<?>> deserializerList) {
    validation = validationStrategy;
    client = createHttpClient();
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    try {
      // Cast to ProtocolSocketFactory to avoid the deprecated constructor with the
      // SecureProtocolSocketFactory parameter
      Protocol.registerProtocol(
          HTTPS,
          new Protocol(
              HTTPS, (ProtocolSocketFactory) new TrustingProtocolSocketFactory(), HTTPS_PORT));
    } catch (final IOException e) {
      s_logger.warn(
          "Failed to register the TrustingProtocolSocketFactory, falling back to default SSLSocketFactory",
          e);
    }

    final GsonBuilder gsonBuilder = new GsonBuilder();
    if (classList != null && deserializerList != null) {
      for (int i = 0; i < classList.size() && i < deserializerList.size(); i++) {
        gsonBuilder.registerTypeAdapter(classList.get(i), deserializerList.get(i));
      }
    }
    gson = gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
  }
Exemplo n.º 18
0
  /**
   * Writes configuration.
   *
   * @param writeType write type
   * @throws IOException when write fails
   */
  public static void writeProfessionConfig(ProfessionConfiguration config, WriteReadType writeType)
      throws IOException {

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Ability.class, new AbilityDeserializer());
    Gson gson = gsonBuilder.create();
    writeConfig(gson.toJson(config), writeType, ConfigType.PROFESSION.getFileName());
  }
Exemplo n.º 19
0
  /**
   * Writes configuration.
   *
   * @param name name
   * @param writeType write type
   * @throws IOException when write fails
   */
  public static void writeAbilityConfig(String name, Ability config, WriteReadType writeType)
      throws IOException {

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Ability.class, new AbilityDeserializer());
    Gson gson = gsonBuilder.create();
    writeConfig(gson.toJson(config), writeType, name + IOConstants.FILE_EXTENTENSION);
  }
Exemplo n.º 20
0
 /**
  * Create a new instance of Gson and tack on all our custom deserializers
  *
  * @return a Gson instance
  */
 public static Gson getGsonInstance() {
   if (gson == null) {
     GsonBuilder builder = new GsonBuilder();
     builder.registerTypeAdapter(Event.class, new EventDeserializer());
     gson = builder.create();
   }
   return gson;
 }
Exemplo n.º 21
0
  public ProjectManager(Data data) {
    this.data = data;

    // hang the custom serializer/deserializer
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(this.project, new ProjectDeserializer());

    this.gson = builder.create();
  }
Exemplo n.º 22
0
 private static void init() {
   if (builder == null) {
     builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation();
     builder.registerTypeAdapter(Datum.class, new DatumAdapter());
   }
   if (gson == null) {
     gson = builder.create();
   }
 }
Exemplo n.º 23
0
  /**
   * Reads configuration.
   *
   * @param name name
   * @return configuration
   * @throws JsonSyntaxException when parse fails
   * @throws IOException when read fails
   */
  public static Ability readAbilityConfig(String name) throws JsonParseException, IOException {

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Ability.class, new AbilityDeserializer());
    Gson gson = gsonBuilder.create();
    return gson.fromJson(
        readConfig(WriteReadType.ABILITY_NORMAL, name + IOConstants.FILE_EXTENTENSION),
        Ability.class);
  }
 private String convertSearchResultToJson(final Object object) {
   final GsonBuilder gsonBuilder = new GsonBuilder();
   final Gson gson =
       gsonBuilder
           .registerTypeAdapter(SearchResult.class, new ApplicationSearchAdaptor())
           .create();
   final String json = gson.toJson(object);
   return json;
 }
Exemplo n.º 25
0
 /**
  * @param object
  * @return
  */
 private Object toJSON(final Object object) {
   final GsonBuilder gsonBuilder = new GsonBuilder();
   final Gson gson =
       gsonBuilder
           .registerTypeAdapter(DCBReportResult.class, new DCBReportHelperAdaptor())
           .create();
   final String json = gson.toJson(object);
   return json;
 }
Exemplo n.º 26
0
 public HashMap<AMQPProperties, String> initRemoteAMQP() {
   gb = new GsonBuilder();
   gb.registerTypeAdapter(TrainInfoUpdate.class, new TrainInfoUpdateSerializer());
   g = gb.create();
   HashMap<AMQPProperties, String> p = new HashMap<>();
   p.put(AMQPProperties.EXCHANGENAME, "logs");
   p.put(AMQPProperties.HOSTNAME, "118.138.243.151");
   return p;
 }
  public static Gson getGson() {
    if (GSON == null) {
      final GsonBuilder gsonBuilder = new GsonBuilder();
      gsonBuilder.registerTypeAdapter(Date.class, new DateTypeAdapter());
      GSON = gsonBuilder.excludeFieldsWithModifiers(Modifier.TRANSIENT).create();
    }

    return GSON;
  }
Exemplo n.º 28
0
  /**
   * Parses the collection info
   *
   * @param json
   * @return
   */
  public static State parse(String json) {

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    gsonBuilder.registerTypeAdapter(State.class, new StateDeserializer());
    Gson gson = gsonBuilder.create();
    State state = gson.fromJson(json, State.class);
    return state;
  }
Exemplo n.º 29
0
  public static SignedEncrypted deserialize(String signedEncrypted) {
    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(SignedEncrypted.class, new SignedEncryptedCustomDeserializer());

    try {
      return gson.create().fromJson(signedEncrypted, SignedEncrypted.class);
    } catch (JsonParseException e) {
      return null;
    }
  }
Exemplo n.º 30
0
  /**
   * Reads configuration.
   *
   * @param settlementId faction ID
   * @throws JsonSyntaxException when parse fails
   * @throws IOException when read fails
   */
  public static ChunkGroup readChunkGroup(String settlementId)
      throws JsonParseException, IOException {

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ChunkGroup.class, new ChunkGroupDeserializer());
    Gson gson = gsonBuilder.create();
    return gson.fromJson(
        readConfig(WriteReadType.SETTLEMENT_NORMAL, settlementId + IOConstants.FILE_EXTENTENSION),
        ChunkGroup.class);
  }