/**
  * 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();
 }
 protected String generateRequestBody() {
   final GsonBuilder builder = new GsonBuilder();
   final Gson gson = builder.create();
   Map<String, Boolean> deployMap = new HashMap<String, Boolean>();
   deployMap.put("enabled", enabled);
   return gson.toJson(deployMap);
 }
 @Override
 public String asJsonString() {
   GsonBuilder builder = new GsonBuilder();
   builder.registerTypeAdapter(Model.class, new JsonModelAdapter());
   Gson gson = builder.create();
   return gson.toJson(this, modelType);
 }
Пример #4
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);
 }
Пример #5
0
 public static GsonBuilder getBuilder(AbstractDeserializer... deserializers) {
   GsonBuilder builder = new GsonBuilder();
   for (AbstractDeserializer deserializer : deserializers) {
     builder.registerTypeAdapter(deserializer.getClazz(), deserializer);
   }
   return builder;
 }
 public boolean terminateInstance(String instanceId) {
   try {
     if (log.isDebugEnabled()) {
       log.debug(String.format("Terminate instance: [instance-id] %s", instanceId));
     }
     URI uri = new URIBuilder(endpoint + INSTANCES_CONTEXT + instanceId).build();
     org.apache.stratos.mock.iaas.client.rest.HttpResponse response = doDelete(uri);
     if (response != null) {
       if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) {
         return true;
       } else {
         GsonBuilder gsonBuilder = new GsonBuilder();
         Gson gson = gsonBuilder.create();
         org.apache.stratos.mock.iaas.domain.ErrorResponse errorResponse =
             gson.fromJson(
                 response.getContent(), org.apache.stratos.mock.iaas.domain.ErrorResponse.class);
         if (errorResponse != null) {
           throw new RuntimeException(errorResponse.getErrorMessage());
         }
       }
     }
     throw new RuntimeException("An unknown error occurred");
   } catch (Exception e) {
     String message = "Could not start mock instance";
     throw new RuntimeException(message, e);
   }
 }
Пример #7
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;
  }
 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;
 }
Пример #9
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;
   }
 }
 // TODO - get the GsonBuilder working for us. Much better than using our own code
 public static String WrapAndStringify(ResultBase result) {
   RawSubmitResultContainer toSubmit = new RawSubmitResultContainer();
   toSubmit.jsonResult = RawStringify(result);
   GsonBuilder gsonBuilder = new GsonBuilder();
   Gson gson = gsonBuilder.create();
   return gson.toJson(toSubmit);
 }
Пример #11
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();
 }
Пример #12
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;
  }
  /**
   * Execute the Request for myLocation
   *
   * @param _url
   * @return Return the Search Response
   * @throws Exception
   */
  private SearchMyLocationResponse requestSearchMyLocation(String _url) throws Exception {
    SearchMyLocationResponse sResponse = null;
    final HttpClient client = new DefaultHttpClient();
    final HttpGet request = new HttpGet(_url);
    request.setHeader("Accept", "application/json");

    Log.i(logTag, "Executing requestSearchMyLocation");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
      InputStream stream = entity.getContent();
      BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
      stream.close();
      String responseString = sb.toString();

      GsonBuilder builder = new GsonBuilder();
      Gson gson = builder.create();
      JSONObject json = new JSONObject(responseString);
      sResponse = gson.fromJson(json.toString(), SearchMyLocationResponse.class);
    }

    /* Return */
    Log.i(logTag, "Finish request my_location");
    return sResponse;
  }
Пример #14
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.creat_ad);

    SharedPreferences sharedPreferences = getSharedPreferences(SignUp.SAVE_TEXT, 0);
    String save = sharedPreferences.getString("user", null);

    editTextName = (EditText) findViewById(R.id.editTextNameB);
    editTextDateStart = (EditText) findViewById(R.id.editTextDateStart);
    editTextDateEnd = (EditText) findViewById(R.id.editTextDateEnd);

    editTextCityStart = (EditText) findViewById(R.id.editTextCityStart);
    editTextCityEnd = (EditText) findViewById(R.id.editTextCityEnd);
    editTextAbout = (EditText) findViewById(R.id.editTextAbout);
    editTextPrice = (EditText) findViewById(R.id.editTextPrice);
    editTextCountSits = (EditText) findViewById(R.id.editTextCountSits);
    editTextDateStart = (EditText) findViewById(R.id.editTextDateStart);
    editTextTimeStart = (EditText) findViewById(R.id.editTextTimeStart);
    editTextTimeEnd = (EditText) findViewById(R.id.editTextTimeEnd);

    editTextCurrency = (EditText) findViewById(R.id.editTextCurrency);

    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    user = gson.fromJson(save, User.class);
  }
Пример #15
0
 /*
  * Finds recipe task for machine if it has been already created otherwise makes a new one and adds it into the DAG
  */
 private static RunRecipeTask makeRecipeTaskIfNotExist(
     String recipeName,
     MachineRuntime machine,
     ClusterStats clusterStats,
     JsonObject chefJson,
     TaskSubmitter submitter,
     String cookbookId,
     String cookbookName,
     Map<String, RunRecipeTask> allRecipeTasks,
     Dag dag)
     throws DagConstructionException {
   String recId = RunRecipeTask.makeUniqueId(machine.getId(), recipeName);
   RunRecipeTask runRecipeTask = allRecipeTasks.get(recId);
   if (!allRecipeTasks.containsKey(recId)) {
     ChefJsonGenerator.addRunListForRecipe(chefJson, recipeName);
     GsonBuilder builder = new GsonBuilder();
     builder.disableHtmlEscaping();
     Gson gson = builder.setPrettyPrinting().create();
     String jsonString = gson.toJson(chefJson);
     runRecipeTask =
         new RunRecipeTask(
             machine, clusterStats, recipeName, jsonString, submitter, cookbookId, cookbookName);
     dag.addTask(runRecipeTask);
   }
   allRecipeTasks.put(recId, runRecipeTask);
   return runRecipeTask;
 }
Пример #16
0
 @Override
 public String encode(Student student) throws EncodeException {
   GsonBuilder builder = new GsonBuilder();
   Gson gson = builder.create();
   System.out.println("JSONEncoder....encode.." + gson.toJson(student));
   return gson.toJson(student);
 }
Пример #17
0
 static {
   GsonBuilder var0 = new GsonBuilder();
   var0.registerTypeHierarchyAdapter(IChatComponent.class, new IChatComponent.Serializer());
   var0.registerTypeHierarchyAdapter(ChatStyle.class, new ChatStyle.Serializer());
   var0.registerTypeAdapterFactory(new EnumTypeAdapterFactory());
   GSON = var0.create();
 }
  @Override
  public boolean parse(
      @NonNull String line,
      @NonNull OutputLineReader reader,
      @NonNull List<Message> messages,
      @NonNull ILogger logger)
      throws ParsingFailedException {
    Matcher m = MSG_PATTERN.matcher(line);
    if (!m.matches()) {
      return false;
    }
    String json = m.group(1);
    if (json.trim().isEmpty()) {
      return false;
    }

    GsonBuilder gsonBuilder = new GsonBuilder();
    MessageJsonSerializer.registerTypeAdapters(gsonBuilder);
    Gson gson = gsonBuilder.create();
    try {
      Message msg = gson.fromJson(json, Message.class);
      messages.add(msg);
      return true;
    } catch (JsonParseException e) {
      throw new ParsingFailedException(e);
    }
  }
Пример #19
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();
 }
Пример #20
0
  private OkHttpClientManager() {
    mOkHttpClient = new OkHttpClient();
    // cookie enabled
    mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
    mDelivery = new Handler(Looper.getMainLooper());

    final int sdk = Build.VERSION.SDK_INT;
    if (sdk >= 23) {
      GsonBuilder gsonBuilder =
          new GsonBuilder()
              .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC);
      mGson = gsonBuilder.create();
    } else {
      mGson = new Gson();
    }

    // just for test
    if (false) {
      mOkHttpClient.setHostnameVerifier(
          new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
              return true;
            }
          });
    }
  }
Пример #21
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();
 }
  /**
   * Converts the properties object into a JSON string.
   *
   * @param properties The properties object to convert.
   * @param envelope Envelope for resulting JSON object. Null if not needed.
   * @return A JSON string representing the object.
   */
  public static String toJson(PropertiesConfiguration properties, String envelope) {
    JsonObject json = new JsonObject();
    Iterator<String> i = properties.getKeys();

    while (i.hasNext()) {
      final String key = i.next();
      final String value = properties.getString(key);
      if (value.equals("true") || value.equals("false")) {
        json.addProperty(key.toString(), Boolean.parseBoolean(value));
      } else if (PATTERN_INTEGER.matcher(value).matches()) {
        json.addProperty(key.toString(), Integer.parseInt(value));
      } else if (PATTERN_FLOAT.matcher(value).matches()) {
        json.addProperty(key.toString(), Float.parseFloat(value));
      } else {
        json.addProperty(key.toString(), value);
      }
    }

    GsonBuilder gsonBuilder = new GsonBuilder().disableHtmlEscaping();
    Gson gson = gsonBuilder.create();
    String _json = gson.toJson(json);
    if (envelope != null && !envelope.isEmpty()) {
      _json = envelope(_json, envelope);
    }
    return _json;
  }
Пример #23
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();
  }
Пример #24
0
  private void initRequestHelpers() {
    queue = Volley.newRequestQueue(this);

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Game.class, new TwitchResultItemParser());
    gson = builder.create();
  }
Пример #25
0
  public void onClickCreat(View view) {

    CurrencyAd ad =
        new CurrencyAd(
            editTextName.getText().toString(),
            editTextCurrency.getText().toString(),
            editTextCountSits.getText().toString(),
            null,
            editTextPrice.getText().toString(),
            user.getEmail(),
            editTextAbout.getText().toString(),
            editTextCityEnd.getText().toString(),
            editTextCityStart.getText().toString(),
            editTextDateEnd.getText().toString(),
            editTextDateStart.getText().toString(),
            editTextTimeEnd.getText().toString(),
            editTextTimeStart.getText().toString());
    GsonBuilder builder1 = new GsonBuilder();
    Gson gson1 = builder1.create();
    String a = gson1.toJson(ad);
    try {
      sent = new CreatAdAsyncTask().execute(gson1.toJson(ad)).get(5, TimeUnit.SECONDS);
      startActivity(new Intent(this, MainActivity.class));
      Toast.makeText(this, "Ваша заявка создана!", Toast.LENGTH_LONG).show();

    } catch (InterruptedException e) {
      Logger.getAnonymousLogger().warning(e.getMessage());
    } catch (ExecutionException e) {
      Logger.getAnonymousLogger().warning(e.getMessage());
    } catch (TimeoutException e) {
      Toast.makeText(this, "Oooops!", Toast.LENGTH_SHORT).show();
    }
  }
Пример #26
0
 @Provides
 @Singleton
 Gson provideGson() {
   GsonBuilder gsonBuilder = new GsonBuilder();
   gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
   return gsonBuilder.create();
 }
Пример #27
0
  static {
    gsonBuilder = new GsonBuilder();
    gsonBuilder.setDateFormat(DateUtils.DATE_PATTERN);

    gsonBuilderWithDateTimeFormat = new GsonBuilder();
    gsonBuilderWithDateTimeFormat.setDateFormat(DateUtils.DATE_TIME_PATTERN);
  }
Пример #28
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;
 }
Пример #29
0
 public static GsonBuilder initGsonBuilder(
     int listBufferSize, AbstractValuesAdapter contentValuesAdapter) {
   GsonBuilder gsonBuilder = new GsonBuilder();
   gsonBuilder.registerTypeHierarchyAdapter(ContentValues.class, contentValuesAdapter);
   gsonBuilder.registerTypeAdapterFactory(
       new ArrayAdapterFactory(listBufferSize, contentValuesAdapter));
   return gsonBuilder;
 }
Пример #30
0
 @GET
 public Response getAllJarsInfo() {
   List<JarInfo> jarInfo = getJarInfo();
   GsonBuilder gsonBuilder = new GsonBuilder().serializeNulls();
   Gson gson = gsonBuilder.create();
   String propsJson = gson.toJson(new KaryonAdminResponse(jarInfo));
   return Response.ok(propsJson).build();
 }