Java Code Examples for com.google.gson.JsonParser

The following examples show how to use com.google.gson.JsonParser. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: pacbot   Source File: PacmanUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, String> getAmazonEC2ReservedInstanceLeaseExpiration(String checkId, String id,
        String esUrl, String region, String accountId) throws Exception {
    JsonParser jsonParser = new JsonParser();
    Map<String, String> data = new HashMap<>();
    String resourceinfo = getQueryDataForCheckid(checkId, esUrl, id, region, accountId);

    if (resourceinfo != null) {
        JsonObject resourceinfoJson = (JsonObject) jsonParser.parse(resourceinfo);
        String reservedInstanceId = resourceinfoJson.get("Reserved Instance ID").getAsString();
        if (!Strings.isNullOrEmpty(reservedInstanceId) && reservedInstanceId.equals(id)) {
            data.put(PacmanRuleConstants.EST_MONTHLY_SAVINGS,
                    resourceinfoJson.get(PacmanRuleConstants.ESTIMATED_MONTHLY_SAVINGS).getAsString());
            data.put(PacmanRuleConstants.REASON, resourceinfoJson.get(PacmanRuleConstants.ISSUE_REASON)
                    .getAsString());
            data.put("instanceCount", resourceinfoJson.get("Instance Count").getAsString());
            data.put(PacmanRuleConstants.STATUS, resourceinfoJson.get(PacmanRuleConstants.STATUS_CAP).getAsString());
            data.put("platform", resourceinfoJson.get("Platform").getAsString());
            data.put("currentMonthlyCost", resourceinfoJson.get("Current Monthly Cost").getAsString());
            data.put("expirationDate", resourceinfoJson.get("Expiration Date").getAsString());
            data.put(PacmanRuleConstants.INSTANCETYPE, resourceinfoJson.get(PacmanRuleConstants.INSTANCE_TYPE_CAP)
                    .getAsString());
            data.put("zone", resourceinfoJson.get("Zone").getAsString());
        }
    }
    return data;
}
 
Example 2
Source Project: LibreTrivia   Source File: ApiUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static ArrayList<TriviaQuestion> jsonToQuestionArray(String json) throws NoTriviaResultsException {
    JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();

    if (jsonObject.get("response_code").getAsInt() == 1) {
        throw new NoTriviaResultsException();
    }

    JsonArray jsonArray = jsonObject.getAsJsonArray("results");

    ArrayList<TriviaQuestion> questions = new ArrayList<>();

    for (JsonElement element : jsonArray) {
        JsonObject object = element.getAsJsonObject();
        TriviaType type = TriviaType.get(object.get("type").getAsString());

        if (type == TriviaType.MULTIPLE) {
            questions.add(TriviaQuestionMultiple.fromJson(object));
        } else {
            questions.add(TriviaQuestionBoolean.fromJson(object));
        }
    }

    return questions;
}
 
Example 3
Source Project: jumbune   Source File: ExportUtil.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 
 * @param worksheet
 * @param dvReportJson
 * @throws JumbuneException
 * @throws IOException
 */
public static void createDataQualityExcelReport(Worksheet worksheet, String dvReportJson) throws JumbuneException, IOException {
	Set<String> fileSet = new TreeSet<String>();
	
	List<String> row = new ArrayList<String>();
	// adding header to the rows
	String sheetName = UtilitiesConstants.DATA_VALIDATION_SHEET;
	addSheet(worksheet, sheetName);
	JsonElement jreportElement = new JsonParser().parse(dvReportJson);
	JsonObject dvReportObject = jreportElement.getAsJsonObject();
	if(!dvReportObject.getAsJsonObject("DVSUMMARY").toString().equals("{}")){
		row.add("TYPE");
		row.add(UtilitiesConstants.TOTAL_VIOLATIONS);
		Set<String> setOfTotalFiles = getFilesList(dvReportJson, fileSet);
		for (String string : setOfTotalFiles) {
			row.add("file : " + string);
		}
		addHeader(worksheet, sheetName, null, row);
		
		writeStatsRowByRowToFile(dvReportJson, setOfTotalFiles, worksheet, sheetName);
	}else{
		row.add("NO DATA VIOLATIONS FOUND");
		addHeader(worksheet, sheetName, null , row);
	}
}
 
Example 4
public HypixelAPIResponse(String response) {
	if (response == null) {
		success = false;
		return;
	}
	this.raw = response;
	JsonParser parser = new JsonParser();
	JsonElement element = parser.parse(response);
	if (!element.isJsonObject()) {
		throw new IllegalArgumentException();
	}
	this.response = element.getAsJsonObject();

	success = this.response.get("success").getAsBoolean();
	if (!success)
		cause = this.response.get("cause").getAsString();
}
 
Example 5
/**
 * Generate data validation report.
 *
 * @param dvReport the dv report
 * @return the string
 */
public String generateDataValidationReport(String dvReport) {
	JsonDataValidationDashBoardReport boardReport = new JsonDataValidationDashBoardReport();
	JsonElement jelement = new JsonParser().parse(dvReport);
	JsonObject jobject = jelement.getAsJsonObject();
	
	setNullViolations(jobject, boardReport);
	setRegexViolations(jobject, boardReport);
	setDataTypeChecks(jobject, boardReport);
	setSchemaViolations(jobject, boardReport);
	setMissingViolations(jobject, boardReport);
	
	JsonElement jsonElement = new Gson().toJsonTree(boardReport, JsonDataValidationDashBoardReport.class);
	jobject.add("DVSUMMARY", jsonElement);
	return jobject.toString();

}
 
Example 6
Source Project: java-trader   Source File: MarketDataImportAction.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 加载producer.json文件, 检测producer类型
 */
String detectProducerType(File producerDir) throws IOException
{
    String result = MarketDataProducer.PROVIDER_CTP;
    File producerJson = new File(producerDir, "producer.json");
    if (producerJson.exists()) {
        JsonObject json = (JsonObject) (new JsonParser()).parse(FileUtil.read(producerJson));
        JsonElement typeElem = json.get("type");
        if ( typeElem!=null ) {
            result = typeElem.getAsString();
        }
        JsonElement providerElem = json.get("provider");
        if ( providerElem!=null ) {
            result = providerElem.getAsString();
        }
    }
    return result;
}
 
Example 7
Source Project: MantaroBot   Source File: KitsuRetriever.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static List<AnimeData> searchAnime(String name) {
    try {
        Request request = new Request.Builder()
                .url(String.format("https://kitsu.io/api/edge/anime?filter[text]=%s", URLEncoder.encode(name, StandardCharsets.UTF_8)))
                .addHeader("User-Agent", MantaroInfo.USER_AGENT)
                .get()
                .build();

        Response response = httpClient.newCall(request).execute();
        String body = response.body().string();
        response.close();

        Type collectionType = new TypeToken<List<AnimeData>>() { }.getType();

        JsonObject json = JsonParser.parseString(body).getAsJsonObject();
        JsonArray jarr = json.getAsJsonObject().getAsJsonArray("data");
        return gson.fromJson(jarr, collectionType);
    } catch (IOException e) {
        return new ArrayList<>();
    }
}
 
Example 8
Source Project: weixin-java-tools   Source File: WxMpCardServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <pre>
 * 获得卡券api_ticket
 * 获得时会检查卡券apiToken是否过期,如果过期了,那么就刷新一下,否则就什么都不干
 *
 * 详情请见:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html#.E9.99.84.E5.BD
 * .954-.E5.8D.A1.E5.88.B8.E6.89.A9.E5.B1.95.E5.AD.97.E6.AE.B5.E5.8F.8A.E7.AD.BE.E5.90.8D.E7.94
 * .9F.E6.88.90.E7.AE.97.E6.B3.95
 * </pre>
 *
 * @param forceRefresh 强制刷新
 * @return 卡券api_ticket
 */
@Override
public String getCardApiTicket(boolean forceRefresh) throws WxErrorException {
  Lock lock = getWxMpService().getWxMpConfigStorage().getCardApiTicketLock();
  try {
    lock.lock();

    if (forceRefresh) {
      this.getWxMpService().getWxMpConfigStorage().expireCardApiTicket();
    }

    if (this.getWxMpService().getWxMpConfigStorage().isCardApiTicketExpired()) {
      String responseContent = this.wxMpService.execute(SimpleGetRequestExecutor.create(this.getWxMpService().getRequestHttp()), CARD_GET_TICKET, null);
      JsonElement tmpJsonElement = new JsonParser().parse(responseContent);
      JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject();
      String cardApiTicket = tmpJsonObject.get("ticket").getAsString();
      int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt();
      this.getWxMpService().getWxMpConfigStorage().updateCardApiTicket(cardApiTicket, expiresInSeconds);
    }
  } finally {
    lock.unlock();
  }
  return this.getWxMpService().getWxMpConfigStorage().getCardApiTicket();
}
 
Example 9
Source Project: BungeePerms   Source File: VersionCheck.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void checkForUpdate()
{
    try
    {
        //get current version
        int curVersion = BungeePerms.getInstance().getPlugin().getBuild();

        URL url = new URL("https://ci.wea-ondara.net/job/BungeePerms/api/json");
        URLConnection request = url.openConnection();
        request.connect();
        JsonParser jp = new JsonParser();
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
        JsonObject j = root.getAsJsonObject();
        int remoteVersion = j.getAsJsonObject("lastSuccessfulBuild").get("number").getAsInt();

        if (remoteVersion > curVersion)
        {
            BungeePerms.getInstance().getPlugin().getConsole().sendMessage("[BungeePerms] " + Lang.translate(Lang.MessageType.UPDATE_AVAILABLE));
        }
    }
    catch (Exception e)
    {
    }
}
 
Example 10
Source Project: datawave   Source File: JsonIngestFlattenerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFlattenGROUPED_AND_NORMAL() throws Exception {
    JsonObjectFlattener flattener = new JsonIngestFlattener.Builder().flattenMode(FlattenMode.GROUPED_AND_NORMAL).build();
    
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(json);
    Multimap<String,String> fieldMap = flattener.flatten(jsonElement.getAsJsonObject());
    
    // printJson(json);
    // printMap(fieldMap);
    
    Assert.assertEquals(74, fieldMap.keySet().size());
    Assert.assertEquals(74, fieldMap.values().size());
    
    Assert.assertEquals(1, fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_0.CHARACTER_0.NAME_0").size());
    Assert.assertEquals(1, fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_1.CHARACTER_0.NAME_0").size());
    Assert.assertEquals(1, fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_2.CHARACTER_0.NAME_0").size());
    Assert.assertEquals(1, fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_3.CHARACTER_0.NAME_0").size());
    
    Assert.assertEquals("Jerry Seinfeld", fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_0.CHARACTER_0.NAME_0").iterator().next());
    Assert.assertEquals("Cosmo Kramer", fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_1.CHARACTER_0.NAME_0").iterator().next());
    Assert.assertEquals("George Louis Costanza", fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_2.CHARACTER_0.NAME_0").iterator().next());
    Assert.assertEquals("Elaine Marie Benes", fieldMap.get("EMBEDDED_CAST_CHARACTER_NAME.EMBEDDED_0.CAST_3.CHARACTER_0.NAME_0").iterator().next());
    
}
 
Example 11
Source Project: The-5zig-Mod   Source File: SpotifyManager.java    License: MIT License 6 votes vote down vote up
private void loadCsrfToken(final Runnable runnable) {
	makeRequest(getURL("/simplecsrf/token.json"), Collections.<String, String>emptyMap(), originHeader, new HttpResponseCallback() {
		@Override
		public void call(String response, int responseCode, Throwable throwable) {
			if (throwable != null) {
				The5zigMod.logger.error("Could not load Spotify Csrf-Token!", throwable);
				reconnect();
			} else if (response != null) {
				JsonElement element = new JsonParser().parse(response);
				if (!parseError(element)) {
					if (element.isJsonObject() && element.getAsJsonObject().has("token") && element.getAsJsonObject().get("token").isJsonPrimitive()) {
						csrfToken = element.getAsJsonObject().get("token").getAsString();
						runnable.run();
					} else {
						The5zigMod.logger.error("Could not load Spotify Csrf-Token: " + response);
						reconnect();
					}
				}
			}
		}
	});
}
 
Example 12
Source Project: The-5zig-Mod   Source File: HypixelAPIResponse.java    License: MIT License 6 votes vote down vote up
public HypixelAPIResponse(String response) {
	if (response == null) {
		success = false;
		return;
	}
	this.raw = response;
	JsonParser parser = new JsonParser();
	JsonElement element = parser.parse(response);
	if (!element.isJsonObject()) {
		throw new IllegalArgumentException();
	}
	this.response = element.getAsJsonObject();

	success = this.response.get("success").getAsBoolean();
	if (!success)
		cause = this.response.get("cause").getAsString();
}
 
Example 13
Source Project: datawave   Source File: JsonObjectFlattenerImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFlattenWithWhitelist() throws Exception {
    JsonObjectFlattener flattener = new JsonObjectFlattenerImpl.Builder()
                    .mapKeyWhitelist(new HashSet<>(Arrays.asList("ROOTOBJECT.NUMBER2", "ROOTOBJECT.STRING2"))).pathDelimiter(".")
                    .mapKeyValueNormalizer(toUpperCaseNormalizer).build();
    
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(json);
    Multimap<String,String> fieldMap = flattener.flatten(jsonElement.getAsJsonObject());
    
    // printJson(json);
    // printMap(fieldMap);
    
    Assert.assertEquals(2, fieldMap.keySet().size());
    Assert.assertEquals(2, fieldMap.values().size());
    Assert.assertTrue(fieldMap.containsKey("ROOTOBJECT.NUMBER2") && fieldMap.containsKey("ROOTOBJECT.STRING2"));
}
 
Example 14
Source Project: wings   Source File: RunController.java    License: Apache License 2.0 6 votes vote down vote up
public String deleteRuns(String rjson, ServletContext context) {
  HashMap<String, Object> ret = new HashMap<String, Object>();
  ret.put("success", false);
  JsonElement listel = new JsonParser().parse(rjson);
  if (listel == null)
    return json.toJson(ret);
  
  if(listel.isJsonObject()) {
    return this.deleteRun(rjson, context);
  }
  
  ExecutionMonitorAPI monitor = config.getDomainExecutionMonitor();
  
  JsonArray list = listel.getAsJsonArray();
  for(int i=0; i<list.size(); i++) {
    JsonElement el = list.get(i);
    String runid = el.getAsJsonObject().get("id").getAsString();
    monitor.deleteRun(runid, config.isDeleteRunOutputs());
  }
  
  ret.put("success", true);
  return json.toJson(ret);
}
 
Example 15
/**
 * UnPack Map from byte array
 * 
 * @param b byte array
 * @return UnPacked Map
 */
@SuppressWarnings("unchecked")
public static Map unpack(byte[] b) {
	if (b != null) {
		String s = new String(b);

		try {
			Gson gson = new Gson();
			JsonParser parser = new JsonParser();
			JsonObject o = parser.parse(s).getAsJsonObject();
			Map<String, Object> map = new HashMap<String, Object>();
			
			map = (Map<String,Object>) gson.fromJson(o, map.getClass());
			
			return map;

		} catch (Throwable t) {
			t.printStackTrace();
		}

	}

	return null;
}
 
Example 16
Source Project: pacbot   Source File: AssetServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ResponseWithFieldsByTargetType getEditFieldsByTargetType(String resourceType) {

    List<String> editableFieldsList = new ArrayList<>();
    JsonParser jsonParser = new JsonParser();
    String field = null;

    String dataTypeInfo = repository.getDataTypeInfoByTargetType(resourceType);

    if (dataTypeInfo != null) {
        JsonObject datatypeInfoJson = (JsonObject) jsonParser.parse(dataTypeInfo);
        JsonObject dataTypes = datatypeInfoJson.get("dataTypes_info").getAsJsonObject();
        Iterator<String> it = dataTypes.keySet().iterator();
        while (it.hasNext()) {
            field = it.next();
            editableFieldsList.add(field);
        }
    }

    return new ResponseWithFieldsByTargetType(resourceType, editableFieldsList);
}
 
Example 17
private JsonObject getItemCount(Set<String> equip_id) {
    JsonArray user_equipment_data = dbHelper.getItemData();
    String filtcond = getStringPreferences(getApplicationContext(), PREF_EQUIPINFO_FILTCOND);
    JsonObject count_result = new JsonObject();
    for (String e: equip_id) {
        count_result.addProperty(e, 0);
    }

    for (JsonElement data: user_equipment_data) {
        JsonObject equip = data.getAsJsonObject();
        JsonObject value = new JsonParser().parse(equip.get("value").getAsString()).getAsJsonObject();
        String slotitem_id = value.get("api_slotitem_id").getAsString();
        int level = value.get("api_level").getAsInt();
        if (level == 0 && equip_id.contains(slotitem_id)) {
            count_result.addProperty(slotitem_id, count_result.get(slotitem_id).getAsInt() + 1);
        }
    }
    return count_result;
}
 
Example 18
private NewDexTicker getNewDexTicker(String coinmarket_id) throws Exception
    {
        StringBuilder req_url = new StringBuilder();


        String redis_key = Variables.redisKeyPrefixBlockchain+ Variables.redisKeyEosNewdexMid + coinmarket_id;
        NewDexTicker newDexTicker = redisService.get(redis_key, NewDexTicker.class);
        if(newDexTicker == null){
            try{
                req_url.append(Variables.NEWDEX_TICKER).append("?symbol=").append(coinmarket_id);
                String result = HttpClientUtils.ocGet(req_url.toString());
                JsonElement data = new JsonParser().parse(result);
                if(data.isJsonObject()){
                    newDexTicker = new Gson().fromJson(data.getAsJsonObject().get("data").toString(), NewDexTicker.class);
                    redisService.set(redis_key, newDexTicker, Variables.redisCacheTimeout);
                }
            }
            catch (Exception e)
            {
                //不再抛出错误,直接初始化为零
                newDexTicker = new NewDexTicker();
//                throw new ExceptionsChain(ErrorCodeEnumChain.unknown_new_dex_exception);
            }
        }
        return newDexTicker;
    }
 
Example 19
public static JsonObject getExpeditionInfo(int mission_no, String locale) {
    JsonObject data = null;
    int mission_key = mission_no;
    String key = String.valueOf(mission_key);
    if (!kcExpeditionData.has(key)) {
        if (mission_no % 2 == 1) key = "203";
        else key = "204";
    }
    JsonObject rawdata = kcExpeditionData.getAsJsonObject(String.valueOf(mission_key));
    data = new JsonParser().parse(rawdata.toString()).getAsJsonObject();
    JsonObject name = data.getAsJsonObject("name");
    if (name.has(locale)) {
        data.addProperty("name", name.get(locale).getAsString());
    } else {
        data.addProperty("name", name.get("en").getAsString());
    }
    return data;
}
 
Example 20
Source Project: openapi-style-validator   Source File: OptionManager.java    License: Apache License 2.0 6 votes vote down vote up
ValidatorParameters getOptionalValidatorParametersOrDefault(CommandLine commandLine) {
    ValidatorParameters parameters = new ValidatorParameters();
    if (commandLine.hasOption(OPTIONS_OPT_SHORT)) {
        try {
            String content = Utils.readFile(commandLine.getOptionValue(OPTIONS_OPT_SHORT), Charset.defaultCharset());
            JsonParser parser = new JsonParser();
            JsonElement jsonElement = parser.parse(content);
            fixConventionRenaming(jsonElement, "path");
            fixConventionRenaming(jsonElement, "parameter");
            fixConventionRenaming(jsonElement, "property");
            Gson gson = new GsonBuilder().create();
            parameters = gson.fromJson(jsonElement, ValidatorParameters.class);
        } catch (Exception ignored) {
            System.out.println("Invalid path to option files, using default.");
        }
    }
    return parameters;
}
 
Example 21
Source Project: AIDR   Source File: CrisisResource.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@POST
@Consumes( MediaType.APPLICATION_JSON )
@Produces( MediaType.APPLICATION_JSON )
@Path("/crises")
public Response getCrisesByCodes(String codes) {
	try {
		ObjectMapper objectMapper = new ObjectMapper();
		JsonParser jsonParser = new JsonParser();
		JsonArray jsonArr = (JsonArray)jsonParser.parse(codes);
           ArrayList<String> jsonObjList = new Gson().fromJson(jsonArr, ArrayList.class);
		HashMap<String, Integer> classifiersNumbers = crisisLocalEJB.countClassifiersByCrisisCodes(jsonObjList);
		String rv = objectMapper.writeValueAsString(classifiersNumbers);

		return Response.ok(classifiersNumbers).build();
	} catch (IOException e) {
		logger.error("Error while getting numbers of classifiers by crisis codes:", e);
		return Response.ok("Error while getting numbers of classifiers by crisis codes.").build();
	}
}
 
Example 22
Source Project: amadeus-java   Source File: HTTPClientTest.java    License: MIT License 6 votes vote down vote up
@Test public void testPage() throws ResponseException {
  Response response = mock(Response.class);
  Request request = mock(Request.class);

  JsonObject jsonObject = new JsonParser().parse("{ \"meta\": { "
          + "\"links\" : {\"next\": \"http://foobar.com?page=10\" } } }").getAsJsonObject();

  when(response.getResult()).thenReturn(jsonObject);
  when(response.getRequest()).thenReturn(request);
  when(request.getVerb()).thenReturn("GET");
  when(request.getPath()).thenReturn("/foo");
  when(request.getParams()).thenReturn(Params.with("foo", "bar"));

  when(client.request(anyString(), anyString(),
      any(Params.class), anyString())).thenReturn(response);
  client.accessToken = accessToken;
  when(accessToken.getBearerToken()).thenReturn("token");
  when(client.page("next", response)).thenCallRealMethod();

  Response nextResponse = client.page("next", response);
  assertNotNull(nextResponse);
}
 
Example 23
/**
 * Reads json file and generates data where needed.
 * Json file should indicate what data should be generated.
 * Format: %string%, %id%
 *
 * @param file
 * @return
 * @throws IOException
 */
public JsonObject readJsonAndGenerateData( File file )
    throws Exception
{
    return read( file ).replace( e -> {
        String json = e.toString();

        json = json.replaceAll( "%id%", new IdGenerator().generateUniqueId() );
        json = json.replaceAll( "%string%", DataGenerator.randomString() );

        return new JsonParser().parse( json );
    } ).get( JsonObject.class );
}
 
Example 24
Source Project: lsp4j   Source File: MessageTypeAdapter.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Convert the json input into the parameters object corresponding to the call
 * made by method.
 *
 * If the method is not known until after parsing, call
 * {@link #parseParams(Object, String)} on the return value of this call for a
 * second chance conversion.
 *
 * @param in
 *            json input to read from
 * @param method
 *            method name of request
 * @return correctly typed object if the correct expected type can be
 *         determined, or a JsonElement representing the parameters
 */
protected Object parseParams(JsonReader in, String method) throws IOException, JsonIOException {
	JsonToken next = in.peek();
	if (next == JsonToken.NULL) {
		in.nextNull();
		return null;
	}
	Type[] parameterTypes = getParameterTypes(method);
	if (parameterTypes.length == 1) {
		return fromJson(in, parameterTypes[0]);
	}
	if (parameterTypes.length > 1 && next == JsonToken.BEGIN_ARRAY) {
		List<Object> parameters = new ArrayList<Object>(parameterTypes.length);
		int index = 0;
		in.beginArray();
		while (in.hasNext()) {
			Type parameterType = index < parameterTypes.length ? parameterTypes[index] : null;
			Object parameter = fromJson(in, parameterType);
			parameters.add(parameter);
			index++;
		}
		in.endArray();
		while (index < parameterTypes.length) {
			parameters.add(null);
			index++;
		}
		return parameters;
	}
	JsonElement rawParams = new JsonParser().parse(in);
	if (method != null && parameterTypes.length == 0 && (
			rawParams.isJsonArray() && rawParams.getAsJsonArray().size() == 0
			|| rawParams.isJsonObject() && rawParams.getAsJsonObject().size() == 0)) {
		return null;
	}
	return rawParams;
}
 
Example 25
Source Project: micro-integrator   Source File: MessageProcessorResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the JSON payload of a given message.
 *
 * @param messageContext synapseMessageContext
 * @return JsonObject payload
 */
private JsonObject getJsonPayload(MessageContext messageContext) throws IOException {
    org.apache.axis2.context.MessageContext axis2MessageContext =
            ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    InputStream jsonStream = JsonUtil.getJsonPayload(axis2MessageContext);
    String jsonString = IOUtils.toString(jsonStream);
    return new JsonParser().parse(jsonString).getAsJsonObject();
}
 
Example 26
Source Project: monasca-common   Source File: HttpAuthClient.java    License: Apache License 2.0 5 votes vote down vote up
private String getAdminToken() throws ClientProtocolException {

    if (adminTokenExpiry != null) {
      if (isExpired(adminTokenExpiry)) {
        adminToken = null;
      }
    }

    if (adminToken == null) {

      String authUri = uri + "/v3/auth/tokens";
      HttpPost httpPost = new HttpPost(authUri);

      try {

        StringEntity params = getUnscopedV3AdminTokenRequest();
        httpPost.setHeader("Accept", APPLICATION_JSON);
        httpPost.setHeader("Content-Type", APPLICATION_JSON);
        httpPost.setEntity(params);
        HttpResponse response = sendPost(httpPost);
        adminToken = response.getFirstHeader(AUTH_SUBJECT_TOKEN).getValue();
        String json = parseResponse(response);
        JsonObject
            token =
            new JsonParser().parse(json).getAsJsonObject().get("token").getAsJsonObject();
        adminTokenExpiry = token.get("expires_at").getAsString();

      } finally {

        httpPost.releaseConnection();

      }
    }
    return adminToken;
  }
 
Example 27
Source Project: varOne   Source File: SparkEventLogParser.java    License: MIT License 5 votes vote down vote up
public SparkEventLogParser(List<String> eventNames){
	this.gson = new Gson();
	this.parser = new JsonParser();
	this.eventLogs = new SparkEventLogBean();
	this.eventNames = new ArrayList<String>(eventNames.size());
	for(String eventName: eventNames){
		this.eventNames.add(eventName);
	}
}
 
Example 28
Source Project: moip-sdk-java-le   Source File: RequestTest.java    License: MIT License 5 votes vote down vote up
protected JsonObject getJsonFileAsJsonObject(String file) {
	BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream ("/jsons/" + file)));
	JsonParser parser = new JsonParser();
	JsonObject json = parser.parse(br).getAsJsonObject();
	assertNotNull(json);
	return json;
}
 
Example 29
/**
 * Transforms a 412 and 409 response to respective exception type.
 *
 * @param exc the Throwable from the request
 */
protected static Throwable transformHttpException(Throwable exc) {

    if (exc instanceof MobileServiceException) {
        MobileServiceException msExcep = (MobileServiceException) exc;

        if (msExcep.getResponse() != null &&
                (msExcep.getResponse().getStatus().code == 412 ||
                        msExcep.getResponse().getStatus().code == 409)) {

            if (msExcep.getResponse().getStatus().code == 412) {
                String content = msExcep.getResponse().getContent();

                JsonObject serverEntity = null;

                if (content != null) {
                    try {
                        serverEntity = new JsonParser().parse(content).getAsJsonObject();
                    } catch (JsonSyntaxException ex) {
                    }
                }

                return new MobileServicePreconditionFailedExceptionJson(msExcep, serverEntity);
            }

            if (msExcep.getResponse().getStatus().code == 409) {
                return new MobileServiceConflictExceptionJson(msExcep, null);
            }
        }
    }

    return exc;
}
 
Example 30
private void initTwilio() {
    try {
        Twilio.init(TWILIO_SID, TWILIO_STOKEN);
        TWILIO_CLIENT = Twilio.getRestClient();
    }
    catch (AuthenticationException e) {
        logger.error("Failed authenticate on Twilio initialization: " + e.getMessage(), e);
        return;
    }

    if (Stream.of(TWILIO_SID, TWILIO_STOKEN, TWILIO_FROM_NUMBER).noneMatch(StringUtils::isEmpty)) {
        final String TWILIO_ACCOUNT_URL = String.format("/2010-04-01/Accounts/%s.json", TWILIO_SID);

        SystemResource.registerHealthcheck(new Healthcheck() {
            private final Gson gson = new GsonBuilder().setPrettyPrinting().create();

            @Override public String getName() {
                return "Twilio";
            }

            @Override protected Result check() throws Exception {
                JsonElement json = new JsonParser()
                        .parse(TWILIO_CLIENT.request(new Request(HttpMethod.GET, TWILIO_ACCOUNT_URL)).getContent());
                return Result.healthy(gson.toJson(json));
            }
        });
    }
}