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

The following examples show how to use com.google.gson.JsonObject#getAsJsonArray() . 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: DeprecatedMethodUtil.java    From PerWorldInventory with GNU General Public License v3.0 6 votes vote down vote up
public static FireworkMeta getFireworkMeta(JsonObject json) {
    FireworkMeta dummy = (FireworkMeta) new ItemStack(Material.FIREWORK).getItemMeta();

    if (json.has("power"))
        dummy.setPower(json.get("power").getAsInt());
    else
        dummy.setPower(1);

    JsonArray effects = json.getAsJsonArray("effects");
    for (int i = 0; i < effects.size() - 1; i++) {
        JsonObject effectDto = effects.get(i).getAsJsonObject();
        FireworkEffect effect = getFireworkEffect(effectDto);
        if (effect != null)
            dummy.addEffect(effect);
    }
    return dummy;
}
 
Example 2
Source File: KcaBattle.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
public static void calculateEnemyCombinedNightDamage(JsonObject api_data, int[] activedeck) {
    JsonArray at_eflag = api_data.getAsJsonArray("api_at_eflag");
    JsonArray df_list = api_data.getAsJsonArray("api_df_list");
    JsonArray df_damage = api_data.getAsJsonArray("api_damage");
    for (int i = 0; i < df_list.size(); i++) {
        int eflag = at_eflag.get(i).getAsInt();
        JsonArray target = df_list.get(i).getAsJsonArray();
        JsonArray target_dmg = df_damage.get(i).getAsJsonArray();
        for (int j = 0; j < target.size(); j++) {
            int target_val = cnv(target.get(j));
            int dmg_val = cnv(target_dmg.get(j));
            if (eflag == 0) {
                if (activedeck[1] == 1) reduce_value(false, enemyAfterHps, target_val, dmg_val, false);
                else reduce_value(false, enemyCbAfterHps, target_val - 6, dmg_val, true);
            } else {
                if (!isCombinedFleetInSortie()) reduce_value(true, friendAfterHps, target_val, dmg_val, false);
                else reduce_value(true, friendCbAfterHps, target_val - 6, dmg_val, true);
            }
        }
     }
}
 
Example 3
Source File: JobHelperv2.java    From repairnator with MIT License 6 votes vote down vote up
public Optional<List<JobV2>> allFromV2() {
    String url = "/" + TravisConstants.JOBS_ENDPOINT;
    try {
        String response = this.get(url, API_VERSION.v2, TravisConstants.DEFAULT_NUMBER_OF_RETRY);
        JsonObject jsonObj = getJsonFromStringContent(response);
        JsonArray jsonArray = jsonObj.getAsJsonArray("jobs");
        List<JobV2> result = new ArrayList<>();

        for (JsonElement jsonElement : jsonArray) {
            result.add(createGson().fromJson(jsonElement, JobV2.class));
        }

        return Optional.of(result);
    } catch (IOException |JsonSyntaxException e) {
        this.getLogger().error("Error while getting jobs from V2 API", e);
    }

    return Optional.empty();
}
 
Example 4
Source File: KcaBattle.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
public static void calculateHougekiDamage(JsonObject api_data) {
    JsonArray at_eflag = api_data.getAsJsonArray("api_at_eflag");
    JsonArray df_list = api_data.getAsJsonArray("api_df_list");
    JsonArray df_damage = api_data.getAsJsonArray("api_damage");
    for (int i = 0; i < df_list.size(); i++) {
        int eflag = at_eflag.get(i).getAsInt();
        JsonArray target = df_list.get(i).getAsJsonArray();
        JsonArray target_dmg = df_damage.get(i).getAsJsonArray();
        for (int j = 0; j < target.size(); j++) {
            int target_val = cnv(target.get(j));
            int dmg_val = cnv(target_dmg.get(j));
            if (eflag == 0) reduce_value(false, enemyAfterHps, target_val, dmg_val, false);
            else reduce_value(true, friendAfterHps, target_val, dmg_val, false);
        }
    }
}
 
Example 5
Source File: FunctionAppTest.java    From faas-tutorial with Apache License 2.0 6 votes vote down vote up
@Test
public void testFunction() {
  JsonObject args = new JsonObject();
  JsonArray splitStrings = new JsonArray();
  splitStrings.add("APPLE");
  splitStrings.add("ORANGE");
  splitStrings.add("BANANA");
  args.add("result", splitStrings);
  JsonObject response = FunctionApp.main(args);
  assertNotNull(response);
  JsonArray results = response.getAsJsonArray("result");
  assertNotNull(results);
  assertEquals(3, results.size());
  List<String> actuals = new ArrayList<>();
  results.forEach(j -> actuals.add(j.getAsString()));
  assertTrue(actuals.get(0).equals("APPLE"));
  assertTrue(actuals.get(1).equals("BANANA"));
  assertTrue(actuals.get(2).equals("ORANGE"));
}
 
Example 6
Source File: DeprecatedMethodUtil.java    From PerWorldInventory with GNU General Public License v3.0 6 votes vote down vote up
public static FireworkMeta getFireworkMeta(JsonObject json) {
    FireworkMeta dummy = (FireworkMeta) new ItemStack(Material.FIREWORK).getItemMeta();

    if (json.has("power"))
        dummy.setPower(json.get("power").getAsInt());
    else
        dummy.setPower(1);

    JsonArray effects = json.getAsJsonArray("effects");
    for (int i = 0; i < effects.size() - 1; i++) {
        JsonObject effectDto = effects.get(i).getAsJsonObject();
        FireworkEffect effect = getFireworkEffect(effectDto);
        if (effect != null)
            dummy.addEffect(effect);
    }
    return dummy;
}
 
Example 7
Source File: BlobContainerInventoryCollector.java    From pacbot with Apache License 2.0 5 votes vote down vote up
public List<BlobContainerVH> fetchBlobContainerDetails(SubscriptionVH subscription,Map<String, Map<String, String>> tagMap) {

		List<BlobContainerVH> blobContainerList = new ArrayList<BlobContainerVH>();
		String accessToken = azureCredentialProvider.getToken(subscription.getTenant());
		Azure azure = azureCredentialProvider.getClient(subscription.getTenant(),subscription.getSubscriptionId());
		PagedList<StorageAccount> storageAccounts = azure.storageAccounts().list();
		for (StorageAccount storageAccount : storageAccounts) {
			String url = String.format(apiUrlTemplate, URLEncoder.encode(subscription.getSubscriptionId()),
					URLEncoder.encode(storageAccount.resourceGroupName()), URLEncoder.encode(storageAccount.name()));
			try {
				String response = CommonUtils.doHttpGet(url, "Bearer", accessToken);
				JsonObject responseObj = new JsonParser().parse(response).getAsJsonObject();
				JsonArray blobObjects = responseObj.getAsJsonArray("value");
				for (JsonElement blobObjectElement : blobObjects) {
					Map<String, String> tags= new HashMap<String, String>();
					BlobContainerVH blobContainerVH = new BlobContainerVH();
					blobContainerVH.setSubscription(subscription.getSubscriptionId());
					blobContainerVH.setSubscriptionName(subscription.getSubscriptionName());
					JsonObject blobObject = blobObjectElement.getAsJsonObject();
					JsonObject properties = blobObject.getAsJsonObject("properties");
					blobContainerVH.setId(blobObject.get("id").getAsString());
					blobContainerVH.setName(blobObject.get("name").getAsString());
					blobContainerVH.setType(blobObject.get("type").getAsString());
					blobContainerVH.setTag(blobObject.get("etag").getAsString());
					blobContainerVH.setTags(Util.tagsList(tagMap, storageAccount.resourceGroupName(), tags));
					if (properties!=null) {
						HashMap<String, Object> propertiesMap = new Gson().fromJson(properties.toString(),
								HashMap.class);
						blobContainerVH.setPropertiesMap(propertiesMap);
					}
					blobContainerList.add(blobContainerVH);
				}
			} catch (Exception e) {
				log.error(" Error fetching blobcontainers for storage account {} Cause : {}" ,storageAccount.name(),e.getMessage());
		
			}
		}
		log.info("Target Type : {}  Total: {} ","Blob Container",blobContainerList.size());
		return blobContainerList;
	}
 
Example 8
Source File: JsonParser.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void reapComments(JsonObject object, Element context) {
	if (object.has("fhir_comments")) {
		JsonArray arr = object.getAsJsonArray("fhir_comments");
		for (JsonElement e : arr) {
			context.getComments().add(e.getAsString());
		}
	}
}
 
Example 9
Source File: KcaDevelopPopupService.java    From kcanotify with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("KCA-CPS", "onStartCommand");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && !Settings.canDrawOverlays(getApplicationContext())) {
        // Can not draw overlays: pass
        stopSelf();
    } else if (intent != null) {
        JsonObject data = null;
        if(intent.getAction() != null && intent.getAction().equals(DEV_DATA_ACTION)) {
            data = new JsonParser().parse(intent.getExtras().getString("data")).getAsJsonObject();
        } else {
            data = dbHelper.getJsonObjectValue(DB_KEY_LATESTDEV);
        }
        if (data != null) {
            ed_time.setText(data.get("time").getAsString());
            ed_ship.setText(KcaApiData.getShipTranslation(data.get("flagship").getAsString(), false));
            if (data.has("items")) {
                JsonArray arr = data.getAsJsonArray("items");
                for (int i = 0; i < arr.size(); i++) {
                    setItemLayout(i+1, arr.get(i).getAsJsonObject());
                }
            } else {
                setSingleItemLayout(data.getAsJsonObject());
            }
        }
    }
    return super.onStartCommand(intent, flags, startId);
}
 
Example 10
Source File: LiquidEngineTests.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static Stream<Arguments> data() throws ParserConfigurationException, SAXException, IOException {
  testdoc = (JsonObject) new com.google.gson.JsonParser().parse(TextFile.fileToString(TestingUtilities.resourceNameToFile("liquid", "liquid-tests.json")));
  JsonArray tests = testdoc.getAsJsonArray("tests");
  List<Arguments> objects = new ArrayList<>();
  for (JsonElement n : tests) {
    objects.add(Arguments.of(n));
  }
  return objects.stream();
}
 
Example 11
Source File: BilibiliExtractor.java    From ParsingPlayer with GNU Lesser General Public License v2.1 5 votes vote down vote up
@NonNull
private Map<Integer,Stream> getSegsMap(JsonObject data){
    HashMap<Integer,Stream> streamMap = new HashMap<>();
    List<Seg> segs;
    JsonArray qualityArray = data.getAsJsonArray("accept_quality");
    JsonObject dataTmp = null;
    for (JsonElement quality:qualityArray){
        segs = new ArrayList<>();
        if (quality.getAsInt() == 1){
            dataTmp = data;
        }else {
            String basicUrl = constructBasicUrl(quality.getAsInt());
            try {
                dataTmp = parseResponse(downloadData(basicUrl));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JsonArray durl = dataTmp.getAsJsonArray("durl");
        for (JsonElement urlPart:durl){
            String path = urlPart.getAsJsonObject().get("url").getAsString();
            double duration = urlPart.getAsJsonObject().get("length").getAsDouble() / 1000;
            Seg seg = new Seg(path,duration);
            segs.add(seg);
        }
        streamMap.put(quality.getAsInt(),new Stream(segs));
    }
    return streamMap;
}
 
Example 12
Source File: StringListItem.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
@Override
public void deserialize(JsonObject object) {
	List<String> list = Lists.newArrayList();
	JsonArray array = object.getAsJsonArray(getKey());
	for (JsonElement jsonElement : array) {
		if (jsonElement.isJsonPrimitive()) {
			list.add(jsonElement.getAsString());
		}
	}
	set(list);
}
 
Example 13
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
public static Set<String> getRouteTableId(String subnetId, String vpcId, String routetableEsURL, String type)
        throws Exception {
    String routetableid = null;
    JsonParser jsonParser = new JsonParser();
    Map<String, Object> mustFilter = new HashMap<>();
    Map<String, Object> mustNotFilter = new HashMap<>();
    HashMultimap<String, Object> shouldFilter = HashMultimap.create();
    Map<String, Object> mustTermsFilter = new HashMap<>();
    if (type.equals(PacmanRuleConstants.SUBNET)) {
        mustFilter.put(convertAttributetoKeyword(PacmanRuleConstants.SUBNETID), subnetId);
    } else {
        mustFilter.put(convertAttributetoKeyword(PacmanRuleConstants.VPC_ID), vpcId);
        mustFilter.put(PacmanRuleConstants.LATEST, true);
    }
    
    Set<String> routeTableIdList = new HashSet<>();
    
    JsonObject resultJson = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(routetableEsURL, mustFilter,
            mustNotFilter, shouldFilter, null, 0, mustTermsFilter, null,null);
    if (resultJson != null && resultJson.has(PacmanRuleConstants.HITS)) {
        JsonObject hitsJson = (JsonObject) jsonParser.parse(resultJson.get(PacmanRuleConstants.HITS).toString());
        JsonArray hitsArray = hitsJson.getAsJsonArray(PacmanRuleConstants.HITS);
        for (int i = 0; i < hitsArray.size(); i++) {
            JsonObject source = hitsArray.get(i).getAsJsonObject().get(PacmanRuleConstants.SOURCE)
                    .getAsJsonObject();
            routetableid = source.get(PacmanRuleConstants.ROUTE_TABLE_ID).getAsString();
            if (!org.apache.commons.lang.StringUtils.isEmpty(routetableid)) {
                routeTableIdList.add(routetableid);
               // return routetableid;
            }
        }
    }
    return routeTableIdList;
}
 
Example 14
Source File: OksusuSiteProcessor.java    From alltv with MIT License 4 votes vote down vote up
private boolean getEPGList() {

        Long ts = System.currentTimeMillis();
        String timestamp = ts.toString();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        String startTime = sdf.format(new Date());

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY, 6);
        String endTime = sdf.format(calendar.getTime());

        // http://www.oksusu.com/api/live/channel?startTime=2019072912&endTime=2019072915&_=1564372401994

        try {

            HttpRequest request = HttpRequest.get(getStringById(R.string.OKSUSU_EPG_URL), true,
                    "startTime", startTime, "endTime", endTime, "_", timestamp)
                    .userAgent(getStringById(R.string.USERAGENT));

            if(request == null || request.badRequest() || request.isBodyEmpty())
                return false;

            String resultJson = request.body();

            JsonParser jParser = new JsonParser();
            JsonArray jArray = jParser.parse(resultJson).getAsJsonObject().getAsJsonArray(getStringById(R.string.CHANNELS_STR));

            // Channels
            for (JsonElement arr : jArray) {
                JsonObject channelObj = arr.getAsJsonObject();

                if (channelObj.get(getStringById(R.string.AUTOURL_TAG)).isJsonNull())
                    continue;

                String serviceId = Utils.removeQuote(channelObj.get(getStringById(R.string.SERVICEID_TAG)).getAsString());

                ChannelData channelData = null;

                for(int i=0; i<mChannelDatas.size(); i++) {
                    if(mChannelDatas.get(i).getId().equals(serviceId)) {
                        channelData = mChannelDatas.get(i);
                        break;
                    }
                }

                if(channelData == null) {
    //                Log.e(TAG, serviceId + ", " + channelName);
                    continue;
                }

                JsonArray programs = channelObj.getAsJsonArray(getStringById(R.string.PROGRAMS_TAG));

                ArrayList<EPGData> epgData = new ArrayList<>();

                for (JsonElement arr1 : programs) {
                    JsonObject programObj = arr1.getAsJsonObject();

                    String programName;
                    Boolean adultContent = programObj.get(getStringById(R.string.ADULTCONTENT_TAG)).getAsBoolean();

                    if(adultContent)
                        programName = getStringById(R.string.adult_contents);
                    else
                        programName = Utils.removeHTMLTag(programObj.get(getStringById(R.string.PROGRAMNAME_TAG)).getAsString());

                    String stime = Utils.removeQuote(programObj.get("startTime").getAsString());
                    String etime = Utils.removeQuote(programObj.get("endTime").getAsString());

                    epgData.add(new EPGData(programName,
                                new Date(Long.parseLong(stime)),
                                new Date(Long.parseLong(etime)),
                                adultContent));
                }

                channelData.setEPG(epgData);
            }

        } catch (Exception ex) {
            return false;
        }

        return true;
    }
 
Example 15
Source File: BatchAccountInventoryCollector.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public List<BatchAccountVH> fetchBatchAccountDetails(SubscriptionVH subscription) throws Exception {

		List<BatchAccountVH> batchAccountList = new ArrayList<BatchAccountVH>();
		String accessToken = azureCredentialProvider.getToken(subscription.getTenant());

		String url = String.format(apiUrlTemplate, URLEncoder.encode(subscription.getSubscriptionId()));
		try {

			String response = CommonUtils.doHttpGet(url, "Bearer", accessToken);
			JsonObject responseObj = new JsonParser().parse(response).getAsJsonObject();
			JsonArray batchAccountObjects = responseObj.getAsJsonArray("value");
			if (batchAccountObjects != null) {
				for (JsonElement batchAccountElement : batchAccountObjects) {
					BatchAccountVH batchAccountVH = new BatchAccountVH();
					JsonObject batchAccountObject = batchAccountElement.getAsJsonObject();
					batchAccountVH.setSubscription(subscription.getSubscriptionId());
					batchAccountVH.setSubscriptionName(subscription.getSubscriptionName());
					batchAccountVH.setId(batchAccountObject.get("id").getAsString());
					batchAccountVH.setLocation(batchAccountObject.get("location").getAsString());
					batchAccountVH.setName(batchAccountObject.get("name").getAsString());
					batchAccountVH.setType(batchAccountObject.get("type").getAsString());
					JsonObject properties = batchAccountObject.getAsJsonObject("properties");
					JsonObject tags = batchAccountObject.getAsJsonObject("tags");
					if (properties != null) {
						HashMap<String, Object> propertiesMap = new Gson().fromJson(properties.toString(),
								HashMap.class);
						batchAccountVH.setProvisioningState(propertiesMap.get("provisioningState").toString());
						batchAccountVH.setAccountEndpoint(propertiesMap.get("accountEndpoint").toString());
						batchAccountVH.setPoolQuota(propertiesMap.get("poolQuota").toString());
						batchAccountVH.setPoolAllocationMode(propertiesMap.get("poolAllocationMode").toString());
						batchAccountVH.setDedicatedCoreQuotaPerVMFamily(propertiesMap.get("dedicatedCoreQuotaPerVMFamilyEnforced").toString());
						batchAccountVH.setDedicatedCoreQuota(propertiesMap.get("dedicatedCoreQuota").toString());
						batchAccountVH.setLowPriorityCoreQuota(propertiesMap.get("lowPriorityCoreQuota").toString());
						batchAccountVH.setActiveJobAndJobScheduleQuota(propertiesMap.get("activeJobAndJobScheduleQuota").toString());
						batchAccountVH.setAutoStorage((Map<String, Object>) propertiesMap.get("autoStorage"));
					}
					if (tags != null) {
						HashMap<String, Object> tagsMap = new Gson().fromJson(tags.toString(), HashMap.class);
						batchAccountVH.setTags(tagsMap);
						
						
						
					}

					batchAccountList.add(batchAccountVH);
				}
			}
		} catch (Exception e) {
			LOGGER.error("Error fetching BatchAccount",e);
		}

		LOGGER.info("Target Type : {}  Total: {} ","Batch Account",batchAccountList.size());
		return batchAccountList;
	}
 
Example 16
Source File: FixedChatSerializer.java    From Carbon-2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public IChatBaseComponent deserialize(JsonElement element, Type type, JsonDeserializationContext ctx) throws JsonParseException {
    if (element.isJsonPrimitive()) {
        return new ChatComponentText(element.getAsString());
    } else if (!element.isJsonObject()) {
        if (element.isJsonArray()) {
            JsonArray jsonArray = element.getAsJsonArray();
            IChatBaseComponent chatcomp = null;
            for (JsonElement jsonElement : jsonArray) {
                IChatBaseComponent innerchatcomp = deserialize(jsonElement, jsonElement.getClass(), ctx);
                if (chatcomp == null) {
                    chatcomp = innerchatcomp;
                } else {
                    chatcomp.addSibling(innerchatcomp);
                }
            }
            return chatcomp;
        } else {
            throw new JsonParseException("Don\'t know how to turn " + element.toString() + " into a Component");
        }
    } else {
        JsonObject jsonobject = element.getAsJsonObject();
        IChatBaseComponent resultComp;
        if (jsonobject.has("text")) {
            resultComp = new ChatComponentText(jsonobject.get("text").getAsString());
        } else if (jsonobject.has("translate")) {
            String translate = jsonobject.get("translate").getAsString();
            if (jsonobject.has("with")) {
                JsonArray withJsonArray = jsonobject.getAsJsonArray("with");
                Object[] array = new Object[withJsonArray.size()];

                for (int i = 0; i < array.length; ++i) {
                    array[i] = deserialize(withJsonArray.get(i), type, ctx);
                    if (array[i] instanceof ChatComponentText) {
                        ChatComponentText compText = (ChatComponentText) array[i];
                        if (compText.getChatModifier().g() && compText.a().isEmpty()) {
                            array[i] = compText.g();
                        }
                    }
                }

                resultComp = new ChatMessage(translate, array);
            } else {
                resultComp = new ChatMessage(translate);
            }
        } else if (jsonobject.has("score")) {
            JsonObject scoreJsonObject = jsonobject.getAsJsonObject("score");
            if (!scoreJsonObject.has("name") || !scoreJsonObject.has("objective")) {
                throw new JsonParseException("A score component needs a least a name and an objective");
            }

            resultComp = new ChatComponentScore(JsonHelper.getString(scoreJsonObject, "name"), JsonHelper.getString(scoreJsonObject, "objective"));
            if (scoreJsonObject.has("value")) {
                ((ChatComponentScore) resultComp).b(JsonHelper.getString(scoreJsonObject, "value"));
            }
        } else {
            if (!jsonobject.has("selector")) {
                throw new JsonParseException("Don\'t know how to turn " + element.toString() + " into a Component");
            }

            resultComp = new ChatComponentSelector(JsonHelper.getString(jsonobject, "selector"));
        }

        if (jsonobject.has("extra")) {
            JsonArray entryJsonArray = jsonobject.getAsJsonArray("extra");
            if (entryJsonArray.size() <= 0) {
                throw new JsonParseException("Unexpected empty array of components");
            }
            for (int i = 0; i < entryJsonArray.size(); ++i) {
                resultComp.addSibling(deserialize(entryJsonArray.get(i), type, ctx));
            }
        }

        resultComp.setChatModifier((ChatModifier) ctx.deserialize(element, ChatModifier.class));
        return resultComp;
    }
}
 
Example 17
Source File: AIResponseTest.java    From dialogflow-java-client with Apache License 2.0 4 votes vote down vote up
@Test
public void complexResponseTest(){
  final String responseJson = "{\n"
      + "  \"id\": \"b5765188-227c-465f-abc4-38674d18e1b6\",\n"
      + "  \"timestamp\": \"2017-07-19T21:24:40.661Z\",\n"
      + "  \"lang\": \"en\",\n"
      + "  \"result\": {\n"
      + "    \"source\": \"agent\",\n"
      + "    \"resolvedQuery\": \"hi\",\n"
      + "    \"action\": \"\",\n"
      + "    \"actionIncomplete\": false,\n"
      + "    \"parameters\": {},\n"
      + "    \"contexts\": [],\n"
      + "    \"metadata\": {\n"
      + "      \"intentId\": \"df4522d6-5222-4bab-96e1-2218b4a12561\",\n"
      + "      \"webhookUsed\": \"false\",\n"
      + "      \"webhookForSlotFillingUsed\": \"false\",\n"
      + "      \"intentName\": \"hi\"\n"
      + "    },\n"
      + "    \"fulfillment\": {\n"
      + "      \"speech\": \"Hi there!\",\n"
      + "      \"messages\": [\n"
      + "        {\n"
      + "          \"type\": 0,\n"
      + "          \"speech\": \"Hi there!\"\n"
      + "        },\n"
      + "        {\n"
      + "          \"type\": 4,\n"
      + "          \"payload\": {\n"
      + "            \"native-android\": {\n"
      + "              \"quick-responses\": [\n"
      + "                \"Yes\",\n"
      + "                \"No\",\n"
      + "                \"I don't know\"\n"
      + "              ]\n"
      + "            }\n"
      + "          }\n"
      + "        }\n"
      + "      ]\n"
      + "    },\n"
      + "    \"score\": 1\n"
      + "  },\n"
      + "  \"status\": {\n"
      + "    \"code\": 200,\n"
      + "    \"errorType\": \"success\"\n"
      + "  },\n"
      + "  \"sessionId\": \"9bdd9303-4937-4464-82f7-3d260d7283c3\"\n"
      + "}";

  final AIResponse aiResponse = gson.fromJson(responseJson, AIResponse.class);

  List<ResponseMessage> messages = aiResponse.getResult().getFulfillment().getMessages();

  for (ResponseMessage message : messages) {
    if (message instanceof ResponsePayload) {
      final ResponsePayload customPayload = (ResponsePayload)message;

      final JsonObject payload = customPayload.getPayload();

      final JsonObject androidPayload = payload.getAsJsonObject("native-android");
      final JsonArray quickResponses = androidPayload.getAsJsonArray("quick-responses");

      JsonElement firstReply = quickResponses.get(0);
      assertEquals("Yes", firstReply.getAsString());

      JsonElement secondReply = quickResponses.get(1);
      assertEquals("No", secondReply.getAsString());

      JsonElement thirdReply = quickResponses.get(2);
      assertEquals("I don't know", thirdReply.getAsString());
    }
  }
}
 
Example 18
Source File: KcaExpeditionCheckViewService.java    From kcanotify_h5-master with GNU General Public License v3.0 4 votes vote down vote up
private JsonObject getBonusInfo() {
    double bonus = 0.0;
    boolean kinu_exist = false;
    int drum_count = 0;
    int bonus_count = 0;
    int daihatsu_count = 0;
    int tank_count = 0;
    int amp_count = 0;
    int toku_count = 0;
    double bonus_level = 0.0;

    float total_firepower = 0;
    float total_asw = 0;
    float total_asw_bonus = 0;
    int total_los = 0;
    JsonObject result = new JsonObject();

    for (JsonObject obj : ship_data) {
        if (obj.get("ship_id").getAsInt() == 487) { // Kinu Kai Ni
            bonus += 5.0;
            kinu_exist = true;
        }

        total_firepower += obj.get("karyoku").getAsInt();
        total_asw += obj.get("taisen").getAsInt();
        total_los += obj.get("sakuteki").getAsInt();
        for (JsonElement itemobj : obj.getAsJsonArray("item")) {
            int type_t2 = itemobj.getAsJsonObject().getAsJsonArray("type").get(2).getAsInt();
            int slotitem_id = itemobj.getAsJsonObject().get("slotitem_id").getAsInt();
            int level = itemobj.getAsJsonObject().get("level").getAsInt();

            if (type_t2 == T2_GUN_MEDIUM || type_t2 == T2_GUN_LARGE || type_t2 == T2_GUN_LARGE_II) {
                total_firepower += Math.sqrt(level);
            }

            if (type_t2 == T2_SONAR || type_t2 == T2_SONAR_LARGE || type_t2 == T2_DEPTH_CHARGE ) {
                total_asw_bonus += Math.sqrt(level);
            }

            switch (slotitem_id) {
                case 75:
                    drum_count += 1;
                    break;
                case 68:
                    bonus += 5.0;
                    bonus_level += level;
                    bonus_count += 1.0;
                    daihatsu_count += 1;
                    break;
                case 166:
                    bonus += 2.0;
                    bonus_level += level;
                    bonus_count += 1.0;
                    tank_count += 1;
                    break;
                case 167:
                    bonus += 1.0;
                    bonus_level += level;
                    bonus_count += 1.0;
                    amp_count += 1;
                    break;
                case 193:
                    bonus += 5.0;
                    bonus_level += level;
                    bonus_count += 1.0;
                    toku_count += 1;
                    break;
                default:
                    break;
            }
        }
    }
    if (bonus_count > 0) bonus_level /= bonus_count;
    int left_count = bonus_count - toku_count;
    if (left_count > 4) left_count = 4;
    if (bonus > 20) bonus = 20.0;
    bonus += (100.0 + 0.2 * bonus_level);
    if (toku_count > 0) {
        int toku_idx;
        if (toku_count > 4) toku_idx = 3;
        else toku_idx = toku_count - 1;
        bonus += toku_bonus[toku_idx][left_count];
    }
    result.addProperty("kinu", kinu_exist);
    result.addProperty("drum", drum_count);
    result.addProperty("daihatsu", daihatsu_count);
    result.addProperty("tank", tank_count);
    result.addProperty("amp", amp_count);
    result.addProperty("toku", toku_count);
    result.addProperty("bonus", bonus);
    result.addProperty("firepower", (int) total_firepower);
    result.addProperty("asw", (int) (total_asw + total_asw_bonus * 2 / 3) );
    result.addProperty("los", total_los);
    return result;
}
 
Example 19
Source File: SitesInventoryCollector.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public List<SitesVH> fetchSitesDetails(SubscriptionVH subscription) throws Exception {

		List<SitesVH> sitesList = new ArrayList<SitesVH>();
		String accessToken = azureCredentialProvider.getToken(subscription.getTenant());

		String url = String.format(apiUrlTemplate, URLEncoder.encode(subscription.getSubscriptionId()));
		try {

			String response = CommonUtils.doHttpGet(url, "Bearer", accessToken);
			JsonObject responseObj = new JsonParser().parse(response).getAsJsonObject();
			JsonArray sitesObjects = responseObj.getAsJsonArray("value");
			if (sitesObjects != null) {
				for (JsonElement sitesElement : sitesObjects) {
					SitesVH sitesVH = new SitesVH();
					JsonObject sitesObject = sitesElement.getAsJsonObject();
					sitesVH.setSubscription(subscription.getSubscriptionId());
					sitesVH.setSubscriptionName(subscription.getSubscriptionName());
					sitesVH.setId(sitesObject.get("id").getAsString());
					sitesVH.setEtag(sitesObject.get("etag").getAsString());
					sitesVH.setLocation(sitesObject.get("location").getAsString());
					sitesVH.setName(sitesObject.get("name").getAsString());
					sitesVH.setType(sitesObject.get("type").getAsString());
					JsonObject properties = sitesObject.getAsJsonObject("properties");
					JsonObject tags = sitesObject.getAsJsonObject("tags");
					if (properties!=null) {
						HashMap<String, Object> propertiesMap = new Gson().fromJson(properties.toString(), HashMap.class);
						sitesVH.setProperties(propertiesMap);
					}
					if (tags!=null) {
						HashMap<String, Object> tagsMap = new Gson().fromJson(tags.toString(), HashMap.class);
						sitesVH.setTags(tagsMap);
					}
					

					sitesList.add(sitesVH);
				}
			}
		} catch (Exception e) {
			log.error("Error Collecting sites",e);
		}

		log.info("Target Type : {}  Total: {} ","Site",sitesList.size());
		return sitesList;
	}
 
Example 20
Source File: LocalUniResolver.java    From universal-resolver with Apache License 2.0 2 votes vote down vote up
public static LocalUniResolver fromConfigFile(String filePath) throws FileNotFoundException, IOException {

		final Gson gson = new Gson();

		Map<String, Driver> drivers = new HashMap<String, Driver> ();

		try (Reader reader = new FileReader(new File(filePath))) {

			JsonObject jsonObjectRoot  = gson.fromJson(reader, JsonObject.class);
			JsonArray jsonArrayDrivers = jsonObjectRoot.getAsJsonArray("drivers");

			int i = 0;

			for (Iterator<JsonElement> jsonElementsDrivers = jsonArrayDrivers.iterator(); jsonElementsDrivers.hasNext(); ) {

				i++;

				JsonObject jsonObjectDriver = (JsonObject) jsonElementsDrivers.next();

				String id = jsonObjectDriver.has("id") ? jsonObjectDriver.get("id").getAsString() : null;
				String pattern = jsonObjectDriver.has("pattern") ? jsonObjectDriver.get("pattern").getAsString() : null;
				String image = jsonObjectDriver.has("image") ? jsonObjectDriver.get("image").getAsString() : null;
				String imagePort = jsonObjectDriver.has("imagePort") ? jsonObjectDriver.get("imagePort").getAsString() : null;
				String imageProperties = jsonObjectDriver.has("imageProperties") ? jsonObjectDriver.get("imageProperties").getAsString() : null;
				String url = jsonObjectDriver.has("url") ? jsonObjectDriver.get("url").getAsString() : null;

				if (pattern == null) throw new IllegalArgumentException("Missing 'pattern' entry in driver configuration.");
				if (image == null && url == null) throw new IllegalArgumentException("Missing 'image' and 'url' entry in driver configuration (need either one).");

				HttpDriver driver = new HttpDriver();
				driver.setPattern(pattern);

				if (url != null) {

					driver.setResolveUri(url);
				} else {

					String httpDriverUri = image.substring(image.indexOf("/") + 1);
					if (httpDriverUri.contains(":")) httpDriverUri = httpDriverUri.substring(0, httpDriverUri.indexOf(":"));
					httpDriverUri = "http://" + httpDriverUri + ":" + (imagePort != null ? imagePort : "8080" ) + "/";

					driver.setResolveUri(httpDriverUri + "1.0/identifiers/$1");

					if ("true".equals(imageProperties)) {

						driver.setPropertiesUri(httpDriverUri + "1.0/properties");
					}
				}

				if (id == null) {

					id = "driver";
					if (image != null) id += "-" + image;
					if (image == null || drivers.containsKey(id)) id += "-" + Integer.toString(i);
				}

				drivers.put(id, driver);

				if (log.isInfoEnabled()) log.info("Added driver '" + id + "' at " + driver.getResolveUri() + " (" + driver.getPropertiesUri() + ")");
			}
		}

		LocalUniResolver localUniResolver = new LocalUniResolver();
		localUniResolver.setDrivers(drivers);

		return localUniResolver;
	}