Java Code Examples for com.google.gson.JsonObject#remove()

The following examples show how to use com.google.gson.JsonObject#remove() . 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: Gateway.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void appendLogEntry(ILoggingEvent event) {
   JsonObject object = new JsonObject();
   for(Map.Entry<String, String> e: event.getMDCPropertyMap().entrySet()) {
      object.addProperty(e.getKey(), e.getValue());
   }

   object.addProperty("ts", event.getTimeStamp());
   object.addProperty("lvl", event.getLevel().toString());
   object.addProperty("thd", event.getThreadName());
   object.addProperty("log", event.getLoggerName());
   object.addProperty("msg", event.getFormattedMessage());

   IThrowableProxy thrw = event.getThrowableProxy();
   if (thrw != null) {
      String stackTrace = converter.convert(event);
      object.addProperty("exc", stackTrace);
   } else {
      object.remove("exc");
   }

   if (!bufferedLogMessages.offer(object)) {
      log.trace("log message dropped because queue overflowed");
   }
}
 
Example 2
Source File: ToolkitRemoteContext.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
/**
 * Create a Job Config Overlays structure if it does not exist.
 * Set the deployment from the graph config.
 */
public static void setupJobConfigOverlays(JsonObject deploy, JsonObject graph) {
    JsonArray jcos = array(deploy, JOB_CONFIG_OVERLAYS);
    if (jcos == null) {
        deploy.add(JOB_CONFIG_OVERLAYS, jcos = new JsonArray());
        jcos.add(new JsonObject());
    }
    JsonObject jco = jcos.get(0).getAsJsonObject();
    
    JsonObject graphDeployment = GsonUtilities.object(graph, "config", DEPLOYMENT_CONFIG);
    
    if (!jco.has(DEPLOYMENT_CONFIG)) {
         jco.add(DEPLOYMENT_CONFIG, graphDeployment);
         return;
    }
    
    JsonObject deployment = object(jco, DEPLOYMENT_CONFIG);
    
    // Need to merge with the graph taking precedence.
    addAll(deployment, graphDeployment);
    
    if ("legacy".equals(GsonUtilities.jstring(deployment, "fusionScheme "))) {
        if (deployment.has("fusionTargetPeCount"))
            deployment.remove("fusionTargetPeCount");
    }
}
 
Example 3
Source File: OptionSetTests.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void shouldRemoveOptions()
{
    // arrange
    createOption( createdOptionSet );
    ApiResponse response = optionActions.optionSetActions.get( createdOptionSet );

    JsonObject object = response.getBody();
    object.remove( "options" );

    // act
    response = optionActions.optionSetActions.update( createdOptionSet, object );
    response.validate()
        .statusCode( 200 );

    // assert
    response = optionActions.optionSetActions.get( createdOptionSet );
    response.validate()
        .statusCode( 200 )
        .body( "options", hasSize( 0 ) );
}
 
Example 4
Source File: AutoMatterTypeAdapter.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void write(final JsonWriter out, final T value) throws IOException {
  final JsonElement tree = delegate.toJsonTree(value);
  if (tree.isJsonObject()) {
    for (Map.Entry<String, List<String>> entry : serializedNameMethods.entrySet()) {
      final String fieldName = entry.getKey();
      final List<String> alternatives = entry.getValue();
      final JsonObject asJsonObject = tree.getAsJsonObject();
      final JsonElement element = asJsonObject.get(fieldName);
      if (element != null) {
        asJsonObject.remove(fieldName);
        asJsonObject.add(alternatives.get(0), element);
      }
    }
  }
  elementAdapter.write(out, tree);
}
 
Example 5
Source File: Tester.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private static void removeComments(JsonObject json) {
	if (json.has("fhir_comments"))
		json.remove("fhir_comments");
  for (Entry<String, JsonElement> p : json.entrySet()) {
  	if (p.getValue() instanceof JsonObject) 
  		removeComments((JsonObject) p.getValue());
  	if (p.getValue() instanceof JsonArray) 
  		removeComments((JsonArray) p.getValue());
  }

}
 
Example 6
Source File: IrisLayout.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public String doLayout(ILoggingEvent event) {
   if (!isJson) {
      return super.doLayout(event);
   }

   JsonObject object = new JsonObject();
   for(Map.Entry<String, String> e: event.getMDCPropertyMap().entrySet()) {
      object.addProperty(e.getKey(), e.getValue());
   }

   object.addProperty("ts", event.getTimeStamp());
   object.addProperty("sev", event.getLevel().toString());
   object.addProperty("host", IrisApplicationInfo.getHostName());
   if (IrisApplicationInfo.getContainerName() != null) {
      object.addProperty("ctn", IrisApplicationInfo.getContainerName());
   }
   object.addProperty("svc", IrisApplicationInfo.getApplicationName());
   object.addProperty("svr", IrisApplicationInfo.getApplicationVersion());
   object.addProperty("thd", event.getThreadName());
   object.addProperty("log", event.getLoggerName());
   object.addProperty("msg", event.getFormattedMessage());

   IThrowableProxy thrw = event.getThrowableProxy();
   if (thrw != null) {
      String stackTrace = converter.convert(event);
      object.addProperty("exc", stackTrace);
   } else {
      object.remove("exc");
   }

   String json = GSON.toJson(object);
   if (isJsonString) {
      json = GSON.toJson(json);
   }

   return json + "\n";
}
 
Example 7
Source File: SOARPlugin.java    From cst with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void removeBranchFromJson(String pathToOldBranch, JsonObject json) {
    String[] oldNodes = pathToOldBranch.split("\\.");
    if (oldNodes.length > 1) {
        if (json.has(oldNodes[0])) {
            removeBranchFromJson(pathToOldBranch.substring(oldNodes[0].length() + 1), json.getAsJsonObject(oldNodes[0]));
        }
    } else {
        json.remove(oldNodes[0]);
    }
}
 
Example 8
Source File: PropertiesSerializer4GitRepository.java    From repairnator with MIT License 5 votes vote down vote up
@Override
public void serialize() {
    Gson gson = new GsonBuilder().registerTypeAdapter(Properties.class, new PropertiesSerializerAdapter()).create();
    JsonObject element = (JsonObject)gson.toJsonTree(inspector.getJobStatus().getProperties());
    
    element.add("reproductionBuggyRepository", element.get("reproductionBuggyBuild"));
    element.remove("reproductionBuggyBuild");
    
    element.addProperty("runId", RepairnatorConfig.getInstance().getRunId());
    Date reproductionDateBeginning = inspector.getJobStatus().getProperties().getReproductionBuggyBuild().getReproductionDateBeginning();
    reproductionDateBeginning = reproductionDateBeginning == null ? new Date() : reproductionDateBeginning;
    this.addDate(element, "reproductionDate", reproductionDateBeginning);
    element.addProperty("buggyId", inspector.getProjectIdToBeInspected());
    if (inspector.getPatchedBuild() != null) {
        element.addProperty("patchedBuildId", inspector.getPatchedBuild().getId());
    }
    element.addProperty("status", getPrettyPrintState(inspector));

    JsonObject elementFreeMemory = new JsonObject();
    Map<String, Long> freeMemoryByStep = inspector.getJobStatus().getFreeMemoryByStep();
    for (Map.Entry<String, Long> stepFreeMemory : freeMemoryByStep.entrySet()) {
        elementFreeMemory.addProperty(stepFreeMemory.getKey(), stepFreeMemory.getValue());
    }
    element.add("freeMemoryByStep", elementFreeMemory);

    List<SerializedData> dataList = new ArrayList<>();

    dataList.add(new SerializedData(new ArrayList<>(), element));

    for (SerializerEngine engine : this.getEngines()) {
        engine.serialize(dataList, this.getType());
    }
}
 
Example 9
Source File: MCRWCMSDefaultNavigationProvider.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private JsonObject add(MCRNavigationBaseItem item, JsonArray hierarchy, JsonArray items) {
    int id = items.size();
    JsonObject jsonItem = gson.toJsonTree(item).getAsJsonObject();
    jsonItem.addProperty(JSON_WCMS_ID, id);
    jsonItem.remove(JSON_CHILDREN);
    WCMSType type = null;
    String href = null;
    if (item instanceof MCRNavigation) {
        type = WCMSType.root;
        href = ((MCRNavigation) item).getHrefStartingPage();
    } else if (item instanceof MCRNavigationMenuItem) {
        type = WCMSType.menu;
        href = ((MCRNavigationMenuItem) item).getDir();
    } else if (item instanceof MCRNavigationItem) {
        type = WCMSType.item;
        href = ((MCRNavigationItem) item).getHref();
    } else if (item instanceof MCRNavigationInsertItem) {
        type = WCMSType.insert;
    } else if (item instanceof MCRNavigationGroup) {
        type = WCMSType.group;
    } else {
        LOGGER.warn("Unable to set type for item {}", id);
    }
    jsonItem.addProperty(JSON_WCMS_TYPE, type.name());
    if (href != null) {
        jsonItem.add("access", getAccess(href));
    }
    items.add(jsonItem);
    // create hierarchy for root
    JsonObject hierarchyObject = new JsonObject();
    hierarchyObject.addProperty(JSON_WCMS_ID, id);
    hierarchy.add(hierarchyObject);
    return hierarchyObject;
}
 
Example 10
Source File: DatabaseObjectCommon.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
public static JsonObject getApiFriendlyJsonObject_CorrectTimesAndTimeUnits(JsonObject jsonObject, String time_FieldName, String timeUnit_FieldName) {
    
    if (jsonObject == null) {
        return null;
    }
    
    try {
        JsonElement time_jsonElement = jsonObject.get(time_FieldName);
        JsonElement timeUnit_JsonElement = jsonObject.get(timeUnit_FieldName);

        if ((time_jsonElement != null) && (timeUnit_JsonElement != null)) {
            long currentField_JsonElement_Long = time_jsonElement.getAsLong();
            int timeUnit_Int = timeUnit_JsonElement.getAsInt();
            BigDecimal time_BigDecimal = DatabaseObjectCommon.getValueForTimeFromMilliseconds(currentField_JsonElement_Long, timeUnit_Int);
            
            jsonObject.remove(time_FieldName);
            JsonBigDecimal time_JsonBigDecimal = new JsonBigDecimal(time_BigDecimal);
            jsonObject.addProperty(time_FieldName, time_JsonBigDecimal);
            
            jsonObject.remove(timeUnit_FieldName);
            jsonObject.addProperty(timeUnit_FieldName, DatabaseObjectCommon.getTimeUnitStringFromCode(timeUnit_Int, false));
        }
        else if (time_jsonElement != null) {
            jsonObject.remove(time_FieldName);
        }
        else if (timeUnit_JsonElement != null) {
            jsonObject.remove(timeUnit_FieldName);
        }
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    }
    
    return jsonObject;
}
 
Example 11
Source File: KmsEvent.java    From openvidu with Apache License 2.0 5 votes vote down vote up
public JsonObject toJson() {
	JsonObject json = JsonUtils.toJsonObject(event);
	json.remove("tags");
	json.remove("timestampMillis");
	json.addProperty("timestamp", timestamp);
	json.addProperty("sessionId", participant.getSessionId());
	json.addProperty("user", participant.getFinalUserId());
	json.addProperty("connection", participant.getParticipantPublicId());
	json.addProperty("endpoint", this.endpoint);
	json.addProperty("msSinceEndpointCreation", msSinceCreation);
	return json;
}
 
Example 12
Source File: AwqlReportQueryTest.java    From adwords-alerting with Apache License 2.0 5 votes vote down vote up
/**
* Test the AWQL query generation from JSON config.
*/
@Test
public void testReportQueryGeneration() {
  // Test full AWQL query
  JsonObject jsonConfig = TestEntitiesGenerator.getTestReportQueryConfig();
  AwqlReportQuery reportQuery1 = new AwqlReportQuery(jsonConfig);
  String expectedAwqlStr1 = "SELECT ExternalCustomerId,AccountDescriptiveName,Cost "
                          + "FROM ACCOUNT_PERFORMANCE_REPORT "
                          + "WHERE Impressions > 100 "
                          + "DURING THIS_MONTH";

  assertEquals(
      "Verify report type of case 1", "ACCOUNT_PERFORMANCE_REPORT", reportQuery1.getReportType());
  assertEquals("Verify AWQL query of case 1", expectedAwqlStr1, reportQuery1.generateAWQL());

  // Test AWQL query without "WHERE" clause
  jsonConfig.remove("Conditions");
  AwqlReportQuery reportQuery2 = new AwqlReportQuery(jsonConfig);
  String expectedAwqlStr2 = "SELECT ExternalCustomerId,AccountDescriptiveName,Cost "
                          + "FROM ACCOUNT_PERFORMANCE_REPORT "
                          + "DURING THIS_MONTH";

  assertEquals(
      "Verify report type of case 2", "ACCOUNT_PERFORMANCE_REPORT", reportQuery2.getReportType());
  assertEquals("Verify AWQL query of case 2", expectedAwqlStr2, reportQuery2.generateAWQL());

  // Test AWQL query without "DURING" clause
  jsonConfig.remove("DateRange");
  AwqlReportQuery reportQuery3 = new AwqlReportQuery(jsonConfig);
  String expectedAwqlStr3 = "SELECT ExternalCustomerId,AccountDescriptiveName,Cost "
                          + "FROM ACCOUNT_PERFORMANCE_REPORT";

  assertEquals(
      "Verify report type of case 3", "ACCOUNT_PERFORMANCE_REPORT", reportQuery3.getReportType());
  assertEquals("Verify AWQL query of case 3", expectedAwqlStr3, reportQuery3.generateAWQL());
}
 
Example 13
Source File: GsonFactory.java    From dialogflow-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public JsonElement serialize(ResponseChatBubble src, Type typeOfSrc, JsonSerializationContext context) {
  JsonObject result = (JsonObject)SIMPLIFIED_GSON.toJsonTree(src, ResponseMessage.class);
  JsonArray items = result.getAsJsonArray("items");
  if ((items != null) && (items.size() == 1)) {
    JsonObject item = (JsonObject)items.get(0);
    result.add("textToSpeech", item.get("textToSpeech"));
    result.add("ssml", item.get("ssml"));
    result.add("displayText", item.get("displayText"));
    result.remove("items");
  }
  return result;
}
 
Example 14
Source File: NPMPackageGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static NPMPackageGenerator subset(NPMPackageGenerator master, String destFile, String id, String name) throws FHIRException, IOException {
  JsonObject p = master.packageJ.deepCopy();
  p.remove("name");
  p.addProperty("name", id);
  p.remove("type");
  p.addProperty("type", PackageType.SUBSET.getCode());    
  p.remove("title");
  p.addProperty("title", name);    
  return new NPMPackageGenerator(destFile, p);
}
 
Example 15
Source File: TextToSpeechWebSocketListener.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the start message.
 *
 * @param options the options
 * @return the request
 */
private String buildStartMessage(SynthesizeOptions options) {
  Gson gson =
      new GsonBuilder()
          .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
          .create();
  JsonObject startMessage = new JsonParser().parse(gson.toJson(options)).getAsJsonObject();

  // remove options that are already in query string
  startMessage.remove(VOICE);
  startMessage.remove(CUSTOMIZATION_ID);

  startMessage.addProperty(ACTION, START);
  return startMessage.toString();
}
 
Example 16
Source File: NPMPackageGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static NPMPackageGenerator subset(NPMPackageGenerator master, String destFile, String id, String name, Date date) throws FHIRException, IOException {
  JsonObject p = master.packageJ.deepCopy();
  p.remove("name");
  p.addProperty("name", id);
  p.remove("type");
  p.addProperty("type", PackageType.SUBSET.getCode());    
  p.remove("title");
  p.addProperty("title", name);

  return new NPMPackageGenerator(destFile, p, date);
}
 
Example 17
Source File: ImportJobSerializer.java    From modernmt with Apache License 2.0 5 votes vote down vote up
@Override
public JsonElement serialize(ImportJob src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject json = (JsonObject) JSONSerializer.toJSON(src, Object.class, false);

    if (src != null && src.getMemory() == 0L)
        json.remove("memory");

    return json;
}
 
Example 18
Source File: MobileServiceTableBase.java    From azure-mobile-apps-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the JsonObject to have an id property
 *
 * @param json the element to evaluate
 */
protected void updateIdProperty(final JsonObject json) throws IllegalArgumentException {
    for (Entry<String, JsonElement> entry : json.entrySet()) {
        String key = entry.getKey();

        if (key.equalsIgnoreCase("id")) {
            JsonElement element = entry.getValue();

            if (isValidTypeId(element)) {
                if (!key.equals("id")) {
                    // force the id name to 'id', no matter the casing
                    json.remove(key);
                    // Create a new id property using the given property
                    // name

                    JsonPrimitive value = entry.getValue().getAsJsonPrimitive();
                    if (value.isNumber()) {
                        json.addProperty("id", value.getAsLong());
                    } else {
                        json.addProperty("id", value.getAsString());
                    }
                }

                return;
            } else {
                throw new IllegalArgumentException("The id must be numeric or string");
            }
        }
    }
}
 
Example 19
Source File: MCRSolrConfigReloader.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * processes a single SOLR config update command
 * @param coreURL - the URL of the core
 * @param command - the command in JSON syntax
 */
private static void processConfigCommand(String coreURL, JsonElement command, JsonObject currentSolrConfig,
    List<String> observedTypes) {
    if (command.isJsonObject()) {
        try {
            //get first and only? property of the command object
            final JsonObject commandJsonObject = command.getAsJsonObject();
            Entry<String, JsonElement> commandObject = commandJsonObject.entrySet().iterator().next();
            final String configCommand = commandObject.getKey();
            final String configType = StringUtils.substringAfter(configCommand, "add-");

            if (isKnownSolrConfigCommmand(configCommand)) {

                if (observedTypes.contains(configType) && configCommand.startsWith("add-") &&
                    commandObject.getValue() instanceof JsonObject) {
                    final JsonElement configCommandName = commandObject.getValue().getAsJsonObject().get("name");
                    if (isConfigTypeAlreadyAdded(configType, configCommandName, currentSolrConfig)) {
                        LOGGER.info("Current configuration has already an " + configCommand
                            + " with name " + configCommandName.getAsString()
                            + ". Rewrite config command as update-"
                            + configType);
                        commandJsonObject.add("update-" + configType, commandJsonObject.get(configCommand));
                        commandJsonObject.remove(configCommand);
                    }
                }
                executeSolrCommand(coreURL, commandJsonObject.toString());
            }
        } catch (IOException e) {
            LOGGER.error(e);
        }
    }

}
 
Example 20
Source File: QueryBuilder.java    From sherlock with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param object   query json object whose interval to set
 * @param interval druid time interval string
 */
protected static void setObjectInterval(JsonObject object, String interval) {
    object.remove(QueryConstants.INTERVALS);
    object.addProperty(QueryConstants.INTERVALS, interval);
}