Java Code Examples for com.google.gson.Gson#toJson()

The following examples show how to use com.google.gson.Gson#toJson() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TinkererSDK.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * Send shell command as http request to the Tinkerer and get back the result as synced response.
 *
 * @param agentId   id of the agent to send command
 * @param testPlanId    The test plan id
 * @param instantName   The instant name
 * @param command   command to execute
 * @return  Response handler as Sync response
 */
public SyncCommandResponse executeCommandSync(String agentId, String testPlanId, String instantName,
                                              String command) {
    Client client = ClientBuilder.newClient();
    String operationId = UUID.randomUUID().toString();
    OperationRequest operationRequest = new OperationRequest(command,
            OperationRequest.OperationCode.SHELL, agentId);
    operationRequest.setOperationId(operationId);
    Gson gson = new Gson();
    String jsonRequest = gson.toJson(operationRequest);
    logger.info("Sending sync commands to " + this.tinkererHost + " agent " + agentId);
    Response response = client.target(this.tinkererHost + "test-plan/" + testPlanId
            + "/agent/" + instantName)
            .path("operation")
            .request()
            .header(HttpHeaders.AUTHORIZATION, this.authenticationToken)
            .post(Entity.entity(jsonRequest,
                    MediaType.APPLICATION_JSON));
    OperationSegment operationSegment = new Gson().
            fromJson(response.readEntity(String.class), OperationSegment.class);
    SyncCommandResponse syncCommandResponse = new SyncCommandResponse();
    syncCommandResponse.setResponse(operationSegment.getResponse());
    syncCommandResponse.setExitValue(operationSegment.getExitValue());
    return syncCommandResponse;
}
 
Example 2
Source File: DMDBTask.java    From iBeebo with GNU General Public License v3.0 6 votes vote down vote up
public static void add(DMUserListBean list, String accountId) {

        if (list == null || list.getSize() == 0) {
            return;
        }

        clear(accountId);

        Gson gson = new Gson();

        ContentValues cv = new ContentValues();
        cv.put(DMTable.MBLOGID, list.getItem(0).getId());
        cv.put(DMTable.ACCOUNTID, accountId);
        String json = gson.toJson(list);
        cv.put(DMTable.JSONDATA, json);
        getWsd().insert(DMTable.TABLE_NAME, DMTable.ID, cv);
    }
 
Example 3
Source File: DataTagQualityImplTest.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testJsonSerializationDeserialization() {
  Gson gson = GsonFactory.createGson();
  DataTagQuality validTagQuality = new DataTagQualityImpl();
  validTagQuality.validate();
  
  String gsonMessage = gson.toJson(validTagQuality);
  DataTagQuality deserializedQuality = gson.fromJson(gsonMessage, DataTagQualityImpl.class);
  assertTrue(deserializedQuality.isValid());
  assertEquals(0, deserializedQuality.getInvalidQualityStates().size());
  
  DataTagQuality invalidTagQuality = new DataTagQualityImpl();
  String equipmentDown = "Equipment down";
  invalidTagQuality.setInvalidStatus(TagQualityStatus.EQUIPMENT_DOWN, equipmentDown);
  String outOfBounds = "Value is out of bounds";
  invalidTagQuality.addInvalidStatus(TagQualityStatus.VALUE_OUT_OF_BOUNDS, outOfBounds);
  assertFalse(invalidTagQuality.isValid());
  assertTrue(invalidTagQuality.isInitialised());
  
  gsonMessage = gson.toJson(invalidTagQuality);
  deserializedQuality = gson.fromJson(gsonMessage, DataTagQualityImpl.class);
  assertFalse(deserializedQuality.isValid());
  assertTrue(deserializedQuality.isInitialised());
  assertTrue(deserializedQuality.isInvalidStatusSet(TagQualityStatus.EQUIPMENT_DOWN));
  assertEquals(equipmentDown, deserializedQuality.getInvalidQualityStates().get(TagQualityStatus.EQUIPMENT_DOWN));
  assertTrue(deserializedQuality.isInvalidStatusSet(TagQualityStatus.VALUE_OUT_OF_BOUNDS));
  assertEquals(outOfBounds, deserializedQuality.getInvalidQualityStates().get(TagQualityStatus.VALUE_OUT_OF_BOUNDS));
}
 
Example 4
Source File: ElasticSearchRepository.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param dataSource
 * @param targetType
 * @param mustFilter
 * @param mustNotFilter
 * @param shouldFilter
 * @param fields
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public List<Map<String, Object>> getSortedDataFromES(String dataSource, String targetType,
		Map<String, Object> mustFilter, final Map<String, Object> mustNotFilter,
		final HashMultimap<String, Object> shouldFilter, List<String> fields, Map<String, Object> mustTermsFilter,
		List<Map<String, Object>> sortFieldMapList) throws Exception {

	Long totalDocs = getTotalDocumentCountForIndexAndType(dataSource, targetType, mustFilter, mustNotFilter,
			shouldFilter, null, mustTermsFilter);
	// if filter is not null apply filter, this can be a multi value filter
	// also if from and size are -1 -1 send all the data back and do not
	// paginate
	StringBuilder urlToQueryBuffer = new StringBuilder(esUrl).append(FORWARD_SLASH).append(dataSource);
	if (!Strings.isNullOrEmpty(targetType)) {
		urlToQueryBuffer.append(FORWARD_SLASH).append(targetType);
	}
	urlToQueryBuffer.append(FORWARD_SLASH).append(_SEARCH);

	String urlToQuery = urlToQueryBuffer.toString();
	// paginate for breaking the response into smaller chunks
	Map<String, Object> requestBody = new HashMap<String, Object>();
	requestBody.put(SIZE, ES_PAGE_SIZE);
	if (totalDocs < ES_PAGE_SIZE) {
		requestBody.put(SIZE, totalDocs);
	}
	requestBody.put(QUERY, buildQuery(mustFilter, mustNotFilter, shouldFilter, null, mustTermsFilter,null));

	if (null != sortFieldMapList && !sortFieldMapList.isEmpty()) {
		requestBody.put(SORT, sortFieldMapList);
	}
	requestBody.put(_SOURCE, fields);
	Gson serializer = new GsonBuilder().disableHtmlEscaping().create();
	String request = serializer.toJson(requestBody);

	return prepareResultsUsingScroll(0, totalDocs, urlToQuery, request);
}
 
Example 5
Source File: Main.java    From BusyBox with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
  Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
  List<Binary> binaries = new ArrayList<>();

  for (String version : COMPILED_VERSION) {
    File directory = new File(BUSYBOX_COMPILER_DIRECTORY, "compiled-" + version);
    for (String abi : ABIS) {
      for (String flavor : FLAVORS) {
        try {
          File busybox = new File(directory, abi + separator + flavor + separator + "bin" + separator + "busybox");
          byte[] bytes = Files.readAllBytes(Paths.get(busybox.getAbsolutePath()));
          byte[] hash = MessageDigest.getInstance("MD5").digest(bytes);
          Binary binary = new Binary();
          binary.name = "BusyBox " + version;
          binary.filename = busybox.getName();
          binary.abi = abi;
          binary.md5sum = DatatypeConverter.printHexBinary(hash).toUpperCase();
          binary.size = busybox.length();
          binary.flavor = flavor;
          if (version.equals(LATEST_VERSION) && abi.equals("arm") && !flavor.equals("static")) {
            // nopie and pie are included in the app's assets directory
            binary.url = "busybox/" + abi + "/" + flavor + "/busybox";
          } else {
            binary.url = String.format(DOWNLOAD_URL, version, abi, flavor);
          }
          binaries.add(binary);
        } catch (IOException | NoSuchAlgorithmException e) {
          e.printStackTrace();
        }
      }
    }
  }

  String json = gson.toJson(binaries);
  Files.write(Paths.get(BINARIES_JSON_FILE.getAbsolutePath()), json.getBytes());
}
 
Example 6
Source File: StorageUtil.java    From AudioAnchor with GNU General Public License v3.0 5 votes vote down vote up
void storeAudioIds(ArrayList<Integer> arrayList) {
    preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = preferences.edit();
    Gson gson = new Gson();
    String json = gson.toJson(arrayList);
    editor.putString("audioList", json);
    editor.apply();
}
 
Example 7
Source File: StateServer.java    From bireme with Apache License 2.0 5 votes vote down vote up
/**
 * Get the State.
 *
 * @param format if not null, format the output string in a pretty style
 * @return the state
 */
public String fetchState(String format) {
  String result;
  Gson gson = null;

  if (format != null) {
    gson = new GsonBuilder()
               .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
               .setPrettyPrinting()
               .create();
  } else {
    gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
  }

  if (source == null) {
    StringBuilder sb = new StringBuilder();

    for (SourceConfig conf : cxt.conf.sourceConfig.values()) {
      sb.append(gson.toJson(getSourceState(conf.name), Source.class));
    }

    result = sb.toString();
  } else {
    result = gson.toJson(getSourceState(source.name), Source.class);
  }

  return result;
}
 
Example 8
Source File: ConvertersTest.java    From gson-javatime-serialisers with MIT License 5 votes vote down vote up
/**
 * Tests that deserialising from JSON works.
 */
@Test
public void testDeserialisation() throws Exception
{
  final Gson gson = Converters.registerAll(new GsonBuilder()).create();

  final Container container = new Container();
  container.ld = LocalDate.of(1969, 7, 21);
  container.lt = LocalTime.of(12, 56, 0);
  container.ldt = LocalDateTime.of(container.ld, container.lt);
  container.odt = OffsetDateTime.of(container.ld, container.lt, ZoneOffset.ofHours(10));
  container.ot = OffsetTime.of(container.lt, ZoneOffset.ofHours(10));
  container.zdt = ZonedDateTime.of(container.ld, container.lt, ZoneId.of("Australia/Brisbane"));
  container.i = container.odt.toInstant();
  
  final JsonObject serialized = new JsonObject();
  serialized.add("ld", new JsonPrimitive("1969-07-21"));
  serialized.add("lt", new JsonPrimitive("12:56:00"));
  serialized.add("ldt", new JsonPrimitive("1969-07-21T12:56:00"));
  serialized.add("odt", new JsonPrimitive("1969-07-21T12:56:00+10:00"));
  serialized.add("ot", new JsonPrimitive("12:56:00+10:00"));
  serialized.add("zdt", new JsonPrimitive("1969-07-21T12:56:00+10:00[Australia/Brisbane]"));
  serialized.add("i", new JsonPrimitive("1969-07-21T02:56:00Z"));

  final String jsonString = gson.toJson(serialized);
  final Container deserialised = gson.fromJson(jsonString, Container.class);
  
  assertThat(deserialised.ld, is(container.ld));
  assertThat(deserialised.ldt, is(container.ldt));
  assertThat(deserialised.lt, is(container.lt));
  assertThat(deserialised.odt, is(container.odt));
  assertThat(deserialised.ot, is(container.ot));
  assertThat(deserialised.zdt, is(container.zdt));
  assertThat(deserialised.i, is(container.i));
}
 
Example 9
Source File: GPlusUserDataProvider.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve current profile status for a list of accounts.
 * @param args args
 * @throws Exception Exception
 */
public static void main(String[] args) throws Exception {

  MatcherAssert.assertThat(args.length, Matchers.greaterThanOrEqualTo(2));

  String configfile = args[0];
  String outfile = args[1];

  File file = new File(configfile);
  assert (file.exists());

  Config conf = ConfigFactory.parseFileAnySyntax(file, ConfigParseOptions.defaults().setAllowMissing(false));
  StreamsConfigurator.addConfig(conf);

  StreamsConfiguration streamsConfiguration = StreamsConfigurator.detectConfiguration();
  GPlusUserDataProviderConfiguration config = new ComponentConfigurator<>(GPlusUserDataProviderConfiguration.class).detectConfiguration();
  GPlusUserDataProvider provider = new GPlusUserDataProvider(config);

  Gson gson = new Gson();

  PrintStream outStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(outfile)));
  provider.prepare(config);
  provider.startStream();
  do {
    Uninterruptibles.sleepUninterruptibly(streamsConfiguration.getBatchFrequencyMs(), TimeUnit.MILLISECONDS);
    for (StreamsDatum datum : provider.readCurrent()) {
      String json;
      if (datum.getDocument() instanceof String) {
        json = (String) datum.getDocument();
      } else {
        json = gson.toJson(datum.getDocument());
      }
      outStream.println(json);
    }
  }
  while ( provider.isRunning());
  provider.cleanUp();
  outStream.flush();
}
 
Example 10
Source File: JsonAdapterAnnotationOnFieldsTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testClassAnnotationAdapterFactoryTakesPrecedenceOverDefault() {
  Gson gson = new Gson();
  String json = gson.toJson(new Gizmo(new Part("Part")));
  assertEquals("{\"part\":\"GizmoPartTypeAdapterFactory\"}", json);
  Gizmo computer = gson.fromJson("{'part':'Part'}", Gizmo.class);
  assertEquals("GizmoPartTypeAdapterFactory", computer.part.name);
}
 
Example 11
Source File: StatsExtended.java    From vk-java-sdk with MIT License 4 votes vote down vote up
@Override
public String toString() {
    final Gson gson = new Gson();
    return gson.toJson(this);
}
 
Example 12
Source File: ReadExecutionTagHistory.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
private JSONObject convertApplicationToJSONObject(Application app) throws JSONException {

        Gson gson = new Gson();
        JSONObject result = new JSONObject(gson.toJson(app));
        return result;
    }
 
Example 13
Source File: ReadTag.java    From cerberus-source with GNU General Public License v3.0 4 votes vote down vote up
private JSONObject convertTagToJSONObject(Tag tag) throws JSONException {

        Gson gson = new Gson();
        JSONObject result = new JSONObject(gson.toJson(tag));
        return result;
    }
 
Example 14
Source File: MobileNotificationService.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param message           The message to send
 * @param useSound          If a sound should be used on the mobile device.
 * @param resultHandler     The result of the send operation (sent on a custom thread)
 * @param errorHandler      Carries the throwable if an error occurred at sending (sent on a custom thread)
 * @return Returns true if the message was sent. It does not reflect if the sending was successful.
 *                          The result and error handlers carry that information.
 * @throws Exception
 */
private boolean sendMessage(MobileMessage message,
                            boolean useSound,
                            Consumer<String> resultHandler,
                            Consumer<Throwable> errorHandler) throws Exception {
    if (mobileModel.getKey() == null)
        return false;

    boolean doSend;
    switch (message.getMobileMessageType()) {
        case SETUP_CONFIRMATION:
            doSend = true;
            break;
        case OFFER:
        case TRADE:
        case DISPUTE:
            doSend = useTradeNotificationsProperty.get();
            break;
        case PRICE:
            doSend = usePriceNotificationsProperty.get();
            break;
        case MARKET:
            doSend = useMarketNotificationsProperty.get();
            break;
        case ERASE:
            doSend = true;
            break;
        default:
            doSend = false;
    }

    if (!doSend)
        return false;

    log.info("Send message: '{}'", message.getMessage());


    log.info("sendMessage message={}", message);
    Gson gson = new Gson();
    String json = gson.toJson(message);
    log.info("json " + json);

    StringBuilder padded = new StringBuilder(json);
    while (padded.length() % 16 != 0) {
        padded.append(" ");
    }
    json = padded.toString();

    // generate 16 random characters for iv
    String uuid = UUID.randomUUID().toString();
    uuid = uuid.replace("-", "");
    String iv = uuid.substring(0, 16);

    String cipher = mobileMessageEncryption.encrypt(json, iv);
    log.info("key = " + mobileModel.getKey());
    log.info("iv = " + iv);
    log.info("encryptedJson = " + cipher);

    doSendMessage(iv, cipher, useSound, resultHandler, errorHandler);
    return true;
}
 
Example 15
Source File: GetCommentsResponse.java    From vk-java-sdk with MIT License 4 votes vote down vote up
@Override
public String toString() {
    final Gson gson = new Gson();
    return gson.toJson(this);
}
 
Example 16
Source File: SearchTransacion.java    From OnlineShoppingSystem with MIT License 4 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    int transactionId = Integer.parseInt(request.getParameter("searchtran"));

    String comment = request.getParameter("searchtran");

    AdminService service = new AdminServiceImpl();
    ArrayList<Transaction> transactions = service.SearchTransaction(transactionId, comment);

    Gson gson = new Gson();
    String gsontransaction = gson.toJson(transactions);

    response.setCharacterEncoding("utf-8");
    System.out.println(gsontransaction);
    response.getWriter().append(gsontransaction);

}
 
Example 17
Source File: Error.java    From vk-java-sdk with MIT License 4 votes vote down vote up
@Override
public String toString() {
    final Gson gson = new Gson();
    return gson.toJson(this);
}
 
Example 18
Source File: LongpollMessages.java    From vk-java-sdk with MIT License 4 votes vote down vote up
@Override
public String toString() {
    final Gson gson = new Gson();
    return gson.toJson(this);
}
 
Example 19
Source File: OscarWriter.java    From neoscada with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Write out the data as JSON encoded data
 * <p>
 * The stream is not closed
 * </p>
 * 
 * @param data
 *            the data to write
 * @param stream
 *            the stream to write to
 * @throws IOException
 */
public static void writeData ( final Map<String, Map<String, Map<String, String>>> data, final OutputStream stream ) throws IOException
{
    final BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( stream, "UTF-8" ) );
    final Gson g = new GsonBuilder ().setPrettyPrinting ().create ();
    g.toJson ( data, writer );
    writer.flush ();
}
 
Example 20
Source File: ObfuscatorController.java    From genesis with GNU General Public License v3.0 3 votes vote down vote up
/**
 * This method returns all obfuscation profiles that reside within Genesis
 * (as specified in
 * <code>model.obfuscator.generic.ObfuscatorProfile</code>).
 *
 * This method is a only reachable when a GET request is sent to the API
 * base (as specified in <code>controller.RestConfig.java</code>), after
 * which the path for this class (as specified above in <code>@Path</code>)
 * needs to be appended. Additionally, the method's <code>@Path</code> needs
 * to be appended.
 *
 * An example of this is: <code>api/v1/obfuscator/profiles</code>
 *
 * If the operating is successful, a HTTP OK (200) status is returned,
 * together with a JSON array that contains all profiles, where each profile
 * is a string.
 *
 * @return all obfuscation profiles within Genesis, in JSON format
 */
@GET
@Path("profiles")
@Produces(MediaType.APPLICATION_JSON)
public Response getObfuscatorProfiles() {
    //Creates a new gson object
    Gson gson = new Gson();
    //Creates a new obfuscator service instance
    ObfuscatorService obfuscatorService = new ObfuscatorService();
    //Get all obfuscator profiles in JSON format
    String json = gson.toJson(obfuscatorService.getObfuscatorProfiles());
    //Send a HTTP OK (200) status with the JSON array of the obfuscator profiles as a response
    return Response.status(Response.Status.OK).entity(json).build();
}