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

The following examples show how to use com.google.gson.JsonObject#getAsJsonPrimitive() . 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: ReplicatorDocument.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
private String getEndpointUrl(JsonElement element) {
    if (element == null) {
        return null;
    }
    JsonPrimitive urlString = null;
    if (element.isJsonPrimitive()) {
        urlString = element.getAsJsonPrimitive();
    } else {
        JsonObject replicatorEndpointObject = element.getAsJsonObject();
        urlString = replicatorEndpointObject.getAsJsonPrimitive("url");
    }
    if (urlString == null) {
        return null;
    }
    return urlString.getAsString();
}
 
Example 2
Source File: GoogleServicesTask.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Finds a service by name in the client object. Returns null if the service is not found
 * or if the service is disabled.
 *
 * @param clientObject the json object that represents the client.
 * @param serviceName the service name
 * @return the service if found.
 */
private JsonObject getServiceByName(JsonObject clientObject, String serviceName) {
    JsonObject services = clientObject.getAsJsonObject("services");
    if (services == null) return null;

    JsonObject service = services.getAsJsonObject(serviceName);
    if (service == null) return null;

    JsonPrimitive status = service.getAsJsonPrimitive("status");
    if (status == null) return null;

    String statusStr = status.getAsString();

    if (STATUS_DISABLED.equals(statusStr)) return null;
    if (!STATUS_ENABLED.equals(statusStr)) {
        getLogger().warn(String.format("Status with value '%1$s' for service '%2$s' is unknown",
                statusStr,
                serviceName));
        return null;
    }

    return service;
}
 
Example 3
Source File: TranslationMappings.java    From ViaVersion with MIT License 6 votes vote down vote up
@Override
public void processText(JsonElement element) {
    super.processText(element);
    if (element == null || !element.isJsonObject()) return;

    // Score components no longer contain value fields
    JsonObject object = element.getAsJsonObject();
    JsonObject score = object.getAsJsonObject("score");
    if (score == null || object.has("text")) return;

    JsonPrimitive value = score.getAsJsonPrimitive("value");
    if (value != null) {
        object.remove("score");
        object.add("text", value);
    }
}
 
Example 4
Source File: GoogleServicesTask.java    From play-services-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Finds a service by name in the client object. Returns null if the service is not found or if
 * the service is disabled.
 *
 * @param clientObject the json object that represents the client.
 * @param serviceName the service name
 * @return the service if found.
 */
private JsonObject getServiceByName(JsonObject clientObject, String serviceName) {
  JsonObject services = clientObject.getAsJsonObject("services");
  if (services == null) return null;

  JsonObject service = services.getAsJsonObject(serviceName);
  if (service == null) return null;

  JsonPrimitive status = service.getAsJsonPrimitive("status");
  if (status == null) return null;

  String statusStr = status.getAsString();

  if (STATUS_DISABLED.equals(statusStr)) return null;
  if (!STATUS_ENABLED.equals(statusStr)) {
    getLogger()
        .warn(
            String.format(
                "Status with value '%1$s' for service '%2$s' is unknown",
                statusStr, serviceName));
    return null;
  }

  return service;
}
 
Example 5
Source File: GoogleServicesTask.java    From play-services-plugins with Apache License 2.0 6 votes vote down vote up
/** Handle a client object for Google App Id. */
private void handleGoogleAppId(JsonObject clientObject, Map<String, String> resValues)
    throws IOException {
  JsonObject clientInfo = clientObject.getAsJsonObject("client_info");
  if (clientInfo == null) {
    // Should not happen
    throw new GradleException("Client does not have client info");
  }

  JsonPrimitive googleAppId = clientInfo.getAsJsonPrimitive("mobilesdk_app_id");

  String googleAppIdStr = googleAppId == null ? null : googleAppId.getAsString();
  if (Strings.isNullOrEmpty(googleAppIdStr)) {
    throw new GradleException(
        "Missing Google App Id. "
            + "Please follow instructions on https://firebase.google.com/ to get a valid "
            + "config file that contains a Google App Id");
  }

  resValues.put("google_app_id", googleAppIdStr);
}
 
Example 6
Source File: GoogleServicesTask.java    From play-services-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Handle a client object for analytics (@xml/global_tracker)
 *
 * @param clientObject the client Json object.
 * @throws IOException
 */
private void handleAnalytics(JsonObject clientObject, Map<String, String> resValues)
    throws IOException {
  JsonObject analyticsService = getServiceByName(clientObject, "analytics_service");
  if (analyticsService == null) return;

  JsonObject analyticsProp = analyticsService.getAsJsonObject("analytics_property");
  if (analyticsProp == null) return;

  JsonPrimitive trackingId = analyticsProp.getAsJsonPrimitive("tracking_id");
  if (trackingId == null) return;

  resValues.put("ga_trackingId", trackingId.getAsString());

  File xml = new File(intermediateDir, "xml");
  if (!xml.exists() && !xml.mkdirs()) {
    throw new GradleException("Failed to create folder: " + xml);
  }

  Files.asCharSink(new File(xml, "global_tracker.xml"), Charsets.UTF_8)
      .write(getGlobalTrackerContent(trackingId.getAsString()));
}
 
Example 7
Source File: GoogleServicesTask.java    From play-services-plugins with Apache License 2.0 6 votes vote down vote up
private String getAndroidApiKey(JsonObject clientObject) {
  JsonArray array = clientObject.getAsJsonArray("api_key");
  if (array != null) {
    final int count = array.size();
    for (int i = 0; i < count; i++) {
      JsonElement apiKeyElement = array.get(i);
      if (apiKeyElement == null || !apiKeyElement.isJsonObject()) {
        continue;
      }
      JsonObject apiKeyObject = apiKeyElement.getAsJsonObject();
      JsonPrimitive currentKey = apiKeyObject.getAsJsonPrimitive("current_key");
      if (currentKey == null) {
        continue;
      }
      return currentKey.getAsString();
    }
  }
  return null;
}
 
Example 8
Source File: JsonUtil.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public static Object getRawObject(JsonObject jsonObject, String memberName) {
  if (jsonObject == null || memberName == null) {
    return null;
  }

  Object rawValue = null;

  if (jsonObject.has(memberName)) {
    JsonPrimitive jsonPrimitive = null;

    try {
      jsonPrimitive = jsonObject.getAsJsonPrimitive(memberName);

    } catch (ClassCastException e) {
      LOG.logJsonException(e);
    }

    if (jsonPrimitive != null) {
      rawValue = asPrimitiveObject(jsonPrimitive);

    }
  }

  if (rawValue != null) {
    return rawValue;

  } else {
    return null;

  }
}
 
Example 9
Source File: EffectModel.java    From GlobalWarming with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean isEnabled(ClimateEffectType effectType) {
    JsonObject effect = effectMap.get(effectType);
    if (effect == null) {
        return false;
    } else {
        JsonPrimitive enabled = effect.getAsJsonPrimitive("enabled");
        if (enabled.isBoolean()) {
            return enabled.getAsBoolean();
        } else {
            return false;
        }
    }
}
 
Example 10
Source File: TestUtils.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
static JsonPrimitive childPrimitive(final JsonObject jsonObject, final String... names) {
    for (final String name : names) {
        final JsonPrimitive childJsonPrimitive = jsonObject.getAsJsonPrimitive(name);
        if (childJsonPrimitive != null) {
            return childJsonPrimitive;
        }
    }
    return null;
}
 
Example 11
Source File: HoverActionSerializer.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public HoverAction deserialize(JsonElement element, Type type, JsonDeserializationContext ctx) {
	JsonObject jsonObject = element.getAsJsonObject();
	JsonPrimitive actionJson = jsonObject.getAsJsonPrimitive("action");
	if (actionJson == null) {
		return null;
	}
	JsonElement valueJson = jsonObject.get("value");
	if (valueJson == null) {
		return null;
	}
	HoverAction.Type atype = HoverAction.Type.valueOf(actionJson.getAsString().toUpperCase());
	BaseComponent component = ctx.deserialize(valueJson, BaseComponent.class);
	return new HoverAction(atype, atype == HoverAction.Type.SHOW_TEXT ? ChatAPI.toJSON(component) : component.getValue());
}
 
Example 12
Source File: GoogleServicesTask.java    From play-services-plugins with Apache License 2.0 5 votes vote down vote up
private static void findStringByName(
    JsonObject jsonObject, String stringName, Map<String, String> resValues) {
  JsonPrimitive id = jsonObject.getAsJsonPrimitive(stringName);
  if (id != null) {
    resValues.put(stringName, id.getAsString());
  }
}
 
Example 13
Source File: GoogleServicesTask.java    From play-services-plugins with Apache License 2.0 5 votes vote down vote up
private void handleWebClientId(JsonObject clientObject, Map<String, String> resValues) {
  JsonArray array = clientObject.getAsJsonArray("oauth_client");
  if (array != null) {
    final int count = array.size();
    for (int i = 0; i < count; i++) {
      JsonElement oauthClientElement = array.get(i);
      if (oauthClientElement == null || !oauthClientElement.isJsonObject()) {
        continue;
      }
      JsonObject oauthClientObject = oauthClientElement.getAsJsonObject();
      JsonPrimitive clientType = oauthClientObject.getAsJsonPrimitive("client_type");
      if (clientType == null) {
        continue;
      }
      String clientTypeStr = clientType.getAsString();
      if (!OAUTH_CLIENT_TYPE_WEB.equals(clientTypeStr)) {
        continue;
      }
      JsonPrimitive clientId = oauthClientObject.getAsJsonPrimitive("client_id");
      if (clientId == null) {
        continue;
      }
      resValues.put("default_web_client_id", clientId.getAsString());
      return;
    }
  }
}
 
Example 14
Source File: ComputeSourceDir.java    From repairnator with MIT License 5 votes vote down vote up
private void computeMetricsOnCompleteRepo() {
    this.getLogger().debug("Compute the line of code of the project");
    ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh","-c",COMPUTE_TOTAL_CLOC)
            .directory(new File(this.getInspector().getRepoLocalPath()));

    try {
        Process p = processBuilder.start();
        BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
        p.waitFor();

        this.getLogger().debug("Get result from cloc process...");
        String processReturn = "";
        String line;
        while (stdin.ready() && (line = stdin.readLine()) != null) {
            processReturn += line;
        }

        Gson gson = new GsonBuilder().create();
        JsonObject json = gson.fromJson(processReturn, JsonObject.class);

        int numberLines = 0;
        if (json != null && json.getAsJsonObject("Java") != null) {
            JsonObject java = json.getAsJsonObject("Java");
            if (java.getAsJsonPrimitive("code") != null) {
                numberLines = java.getAsJsonPrimitive("code").getAsInt();
            }
        }

        this.getInspector().getJobStatus().getProperties().getProjectMetrics().setNumberLines(numberLines);
    } catch (IOException | InterruptedException e) {
        this.getLogger().error("Error while computing metrics on source code of the whole repo.", e);
    }
}
 
Example 15
Source File: GoogleServicesTask.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private static void findStringByName(JsonObject jsonObject, String stringName,
        Map<String, String> resValues) {
    JsonPrimitive id = jsonObject.getAsJsonPrimitive(stringName);
    if (id != null) {
        resValues.put(stringName, id.getAsString());
    }
}
 
Example 16
Source File: WxMpCardServiceImpl.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
/**
 * 卡券Code解码
 *
 * @param encryptCode 加密Code,通过JSSDK的chooseCard接口获得
 * @return 解密后的Code
 */
@Override
public String decryptCardCode(String encryptCode) throws WxErrorException {
  JsonObject param = new JsonObject();
  param.addProperty("encrypt_code", encryptCode);
  String responseContent = this.wxMpService.post(CARD_CODE_DECRYPT, param.toString());
  JsonElement tmpJsonElement = new JsonParser().parse(responseContent);
  JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject();
  JsonPrimitive jsonPrimitive = tmpJsonObject.getAsJsonPrimitive("code");
  return jsonPrimitive.getAsString();
}
 
Example 17
Source File: AuthTokenAdapter.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Override
public AuthToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject jsonObject =  json.getAsJsonObject();
    final JsonPrimitive jsonAuthType = jsonObject.getAsJsonPrimitive(AUTH_TYPE);
    final String authType = jsonAuthType.getAsString();
    final JsonElement jsonAuthToken = jsonObject.get(AUTH_TOKEN);
    return gson.fromJson(jsonAuthToken, authTypeRegistry.get(authType));
}
 
Example 18
Source File: ClickActionSerializer.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public ClickAction deserialize(JsonElement element, Type type, JsonDeserializationContext ctx) {
	JsonObject jsonObject = element.getAsJsonObject();
	JsonPrimitive actionJson = jsonObject.getAsJsonPrimitive("action");
	if (actionJson == null) {
		return null;
	}
	JsonElement valueJson = jsonObject.get("value");
	if (valueJson == null) {
		return null;
	}
	return new ClickAction(ClickAction.Type.valueOf(actionJson.getAsString().toUpperCase()), valueJson.getAsString());
}
 
Example 19
Source File: DropboxExceptionMappingService.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
private void parse(final StringBuilder buffer, final String message) {
    if(StringUtils.isBlank(message)) {
        return;
    }
    try {
        final JsonElement element = JsonParser.parseReader(new StringReader(message));
        if(element.isJsonObject()) {
            final JsonObject json = element.getAsJsonObject();
            final JsonObject error = json.getAsJsonObject("error");
            if(null == error) {
                this.append(buffer, message);
            }
            else {
                final JsonPrimitive tag = error.getAsJsonPrimitive(".tag");
                if(null == tag) {
                    this.append(buffer, message);
                }
                else {
                    this.append(buffer, StringUtils.replace(tag.getAsString(), "_", " "));
                }
            }
        }
        if(element.isJsonPrimitive()) {
            this.append(buffer, element.getAsString());
        }
    }
    catch(JsonParseException e) {
        // Ignore
    }
}
 
Example 20
Source File: Core.java    From ice with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This private operation creates an instance of the Message class from a
 * string using a JSON parser.
 *
 * This operation is synchronized so that the core can't be overloaded.
 *
 * @param messageString
 *            The original message, as a string
 * @return list list of built messages.
 */
private ArrayList<Message> buildMessagesFromString(String messageString) {

	// Create the ArrayList of messages
	ArrayList<Message> messages = new ArrayList<>();

	// Create the parser and gson utility
	JsonParser parser = new JsonParser();
	GsonBuilder builder = new GsonBuilder();
	Gson gson = builder.create();

	// Catch any exceptions and return the empty list
	try {

		// Make the string a json string
		JsonElement messageJson = parser.parse(messageString);
		JsonObject messageJsonObject = messageJson.getAsJsonObject();

		// Get the Item id from the json
		JsonPrimitive itemIdJson = messageJsonObject.getAsJsonPrimitive("item_id");
		int itemId = itemIdJson.getAsInt();

		// Get the array of posts from the message
		JsonArray jsonMessagesList = messageJsonObject.getAsJsonArray("posts");

		// Load the list
		for (int i = 0; i < jsonMessagesList.size(); i++) {
			// Get the message as a json element
			JsonElement jsonMessage = jsonMessagesList.get(i);
			// Marshal it into a message
			Message tmpMessage = gson.fromJson(jsonMessage, Message.class);
			// Set the item id
			if (tmpMessage != null) {
				tmpMessage.setItemId(itemId);
				// Put it in the list
				messages.add(tmpMessage);
			}
		}
	} catch (JsonParseException e) {
		// Log the message
		String err = "Core Message: " + "JSON parsing failed for message " + messageString;
		logger.error(getClass().getName() + " Exception!", e);
		logger.error(err);
	}

	return messages;
}