/** * Parse through the JSON string received from the server and translate into GameModelJSON object * * @param json String received from the server API * @return The now parsed GameModelJSON object. * @throws GeneralPlayerException * @throws InvalidTurnStatusException * @throws TurnIndexException */ private CatanModel _deserialize(String json) throws TurnIndexException, InvalidTurnStatusException, GeneralPlayerException { JsonElement jelement = new JsonParser().parse(json); JsonObject jobject = jelement.getAsJsonObject(); JsonObject deck = jobject.getAsJsonObject("deck"); JsonObject bank = jobject.getAsJsonObject("bank"); JsonObject chat = jobject.getAsJsonObject("chat"); JsonObject log = jobject.getAsJsonObject("log"); JsonObject map = jobject.getAsJsonObject("map"); JsonArray players = jobject.getAsJsonArray("players"); JsonObject tradeOffer = jobject.getAsJsonObject("tradeOffer"); JsonObject turnTracker = jobject.getAsJsonObject("turnTracker"); int version = jobject.getAsJsonPrimitive("version").getAsInt(); int winner = jobject.getAsJsonPrimitive("winner").getAsInt(); SetResourceManager(bank, players, tradeOffer); SetDevCardManager(players, deck); SetPlayerManager(players, turnTracker); SetMapManager(map); SetChatManager(chat, log); SetTurnManager(turnTracker); return catanModel = new CatanModel( resourceManager, devCardManager, playerManager, mapManager, chatManager, version); }
/** Load the configuration file for our server. This method is thread-safe. */ public static synchronized void load() { // # Ensure config file not already loaded... if (configLoaded) { return; } // # Read configuration file, and assign it to our configuration JSONObject try { configuration = (JsonObject) new JsonParser().parse(readFile("config.json").toString()); } catch (JsonParseException e) { // # Someone must have modified (poorly) the JSON configuration file. Logger.log("Malformed JSON in the configuration file.", Logger.CRITICAL); } catch (FileNotFoundException e) { // # Couldn't find the config file, so we write our default one. Logger.log( "Cannot find the configuration file. Creating default config file.", Logger.CRITICAL); configuration = (JsonObject) new JsonParser().parse(create().toString()); } // # Go ahead and assign these values. This is more for developers of SmartSocket than end-user // use. try { Config.autoUpdate = configuration.getAsJsonObject("auto-update"); Config.crossdomainPolicyFile = configuration.getAsJsonObject("crossdomain-policy-file"); Config.tcpExtensions = configuration.getAsJsonObject("tcp-extensions"); Config.udpExtensions = configuration.getAsJsonObject("udp-extensions"); } catch (Exception e) { } Logger.log("Configuration loading is complete.", Logger.CRITICAL); configLoaded = true; }
public static ArrayList<Meetup> jsonToMeetups(JsonObject json) { ArrayList<Meetup> meetups = new ArrayList<>(); JsonArray events = json.getAsJsonArray("events"); for (int x = 0; x < events.size(); x++) { String orgString; String dateString; String nameString; JsonObject event = events.get(x).getAsJsonObject(); try { JsonObject info = event.getAsJsonObject("info"); nameString = info.getAsJsonObject().getAsJsonPrimitive("name").getAsString(); dateString = info.getAsJsonObject().getAsJsonPrimitive("start_date").getAsString(); } catch (Exception e) { nameString = ""; dateString = ""; } try { JsonObject org = event.getAsJsonObject("org"); orgString = org.getAsJsonObject().getAsJsonPrimitive("name").getAsString(); } catch (Exception e) { orgString = ""; } meetups.add(new Meetup(orgString, nameString, dateString)); } return meetups; }
private Geofences.Geofence makeGeofence(JsonObject geofenceJson) { String locationId = geofenceJson.get(JSONKEY_LOCATIONID).getAsString(); String subtitle = geofenceJson.get(JSONKEY_UUID).getAsString(); JsonObject location = geofenceJson.getAsJsonObject(JSONKEY_LOCATION); JsonObject basicAuth = geofenceJson.getAsJsonObject(JSONKEY_BASICAUTH); JsonObject triggerOnLeave = geofenceJson.getAsJsonObject(JSONKEY_TRIGGERONLEAVE); JsonObject triggerOnArrival = geofenceJson.getAsJsonObject(JSONKEY_TRIGGERONARRIVAL); int triggers = createTrigger(triggerOnLeave, triggerOnArrival); float lat = location.get(JSONKEY_LAT).getAsFloat(); float lon = location.get(JSONKEY_LONG).getAsFloat(); int radius = location.get(JSONKEY_RADIUS).getAsInt(); return new Geofences.Geofence( "0", subtitle, locationId, triggers, lat, lon, radius, basicAuth.get(JSONKEY_ENABLED).getAsBoolean() ? 1 : 0, basicAuth.get(JSONKEY_USERNAME).getAsString(), basicAuth.get(JSONKEY_PASSWORD).getAsString(), triggerOnArrival.get(JSONKEY_METHOD).getAsInt(), triggerOnArrival.get(JSONKEY_URL).getAsString(), triggerOnLeave.get(JSONKEY_METHOD).getAsInt(), triggerOnLeave.get(JSONKEY_URL).getAsString()); }
public HalResource deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context, Class<?> targetType) throws JsonParseException { // Das Objekt mal von Gson deserialiseren lassen HalResource result = context.deserialize(json, targetType); // Es handelt sich um ein JSON-Objekt. JsonObject jsonObject = json.getAsJsonObject(); // Nodes mit den Links und den eingebetteten Resourcen auslesen JsonObject linkRoot = jsonObject.getAsJsonObject(HalConstants.LINK_ROOT); JsonObject embeddedRoot = jsonObject.getAsJsonObject(HalConstants.EMBEDDED_ROOT); // Die Felder nach Links und eingebetteten Resourcen absuchen List<Field> fields = HalReflectionHelper.getAllFields(targetType); for (Field field : fields) { // Ist es ein Link? if (HalReflectionHelper.isLink(field) && linkRoot != null) { // Metadaten auslesen HalReferenceMetaData metaData = HalReflectionHelper.getReferenceMetaData(field); // Im JSON danach suchen JsonElement jsonField = linkRoot.get(metaData.getName()); // Wenn im JSON kein Feld gefunden wurde, müssen wir auch nichts machen if (jsonField == null) { continue; } // Wert aus dem Json zurück in das Objekt schreiben writeLink(result, field, jsonField, context); } // Ist es eine Resource? if (HalReflectionHelper.isResource(field) && embeddedRoot != null) { // Name der Resouce auslesen String resName = HalReflectionHelper.getResourceName(field); // Im JSON danach suchen JsonElement jsonField = embeddedRoot.get(resName); // Wenn im JSON kein entsprechendes Feld gefunden wurde, können wir auch nichts machen if (jsonField == null) { continue; } // Werte aus dem Json zurück ins Objekt schreiben writeResource(result, field, jsonField, context); } } return result; }
protected void deserialize( @Nonnull JsonObject object, @Nonnull BaseComponent component, @Nonnull JsonDeserializationContext context) { if (object.has("color")) { component.setColor(ChatColor.valueOf(object.get("color").getAsString().toUpperCase())); } if (object.has("bold")) { component.setBold(object.get("bold").getAsBoolean()); } if (object.has("italic")) { component.setItalic(object.get("italic").getAsBoolean()); } if (object.has("underlined")) { component.setUnderlined(object.get("underlined").getAsBoolean()); } if (object.has("strikethrough")) { component.setUnderlined(object.get("strikethrough").getAsBoolean()); } if (object.has("obfuscated")) { component.setUnderlined(object.get("obfuscated").getAsBoolean()); } if (object.has("extra")) { component.setExtra( Arrays.asList( context.<BaseComponent[]>deserialize(object.get("extra"), BaseComponent[].class))); } // Events if (object.has("clickEvent")) { JsonObject event = object.getAsJsonObject("clickEvent"); component.setClickEvent( new ClickEvent( ClickEvent.Action.valueOf(event.get("action").getAsString().toUpperCase()), event.get("value").getAsString())); } if (object.has("hoverEvent")) { JsonObject event = object.getAsJsonObject("hoverEvent"); BaseComponent[] res; if (event.get("value").isJsonArray()) { res = context.deserialize(event.get("value"), BaseComponent[].class); } else { res = new BaseComponent[] { context.<BaseComponent>deserialize(event.get("value"), BaseComponent.class) }; } component.setHoverEvent( new HoverEvent( HoverEvent.Action.valueOf(event.get("action").getAsString().toUpperCase()), res)); } }
private PillarsConfig() { String configText; JsonElement root; JsonObject rootObj; JsonObject pillarsObj; try { configText = Utils.getFileFromConfig(CORE_FILE_NAME, false); root = new JsonParser().parse(configText); rootObj = root.getAsJsonObject(); pillarsObj = rootObj.getAsJsonObject(KEY_PILLARS); for (Entry<String, JsonElement> entry : pillarsObj.entrySet()) { String name = entry.getKey(); if (name == null || name.equals("")) { System.out.println("Pillar name cant be null"); continue; } if (nameToPillar.containsKey(name)) { System.out.println("Pillar " + name + " allready registered"); continue; } processPillar(name, entry.getValue().getAsJsonObject()); } nameOrderedBySize = new ArrayList<String>(nameToPillar.size()); for (Entry<String, Pillar> entry : nameToPillar.entrySet()) { orderMap(entry.getValue()); } /*for(String s : nameOrderedBySize){ System.out.println("........................ "+s); }*/ } catch (Exception e) { e.printStackTrace(); } }
/** * Queries a view for pagination, returns a next or a previous page, this method figures out which * page to return based on the given param that is generated by an earlier call to this method, * quering the first page is done by passing a {@code null} param. * * @param <T> Object type T * @param rowsPerPage The number of rows per page. * @param param The request parameter to use to query a page, or {@code null} to return the first * page. * @param classOfT The class of type T. * @return {@link Page} */ public <T> Page<T> queryPage(int rowsPerPage, String param, Class<T> classOfT) { if (param == null) { // assume first page return queryNextPage(rowsPerPage, null, null, null, null, classOfT); } String currentStartKey; String currentStartKeyDocId; String startKey; String startKeyDocId; String action; try { // extract fields from the returned HEXed JSON object final JsonObject json = new JsonParser() .parse(new String(Base64.decodeBase64(param.getBytes()))) .getAsJsonObject(); if (log.isDebugEnabled()) { log.debug("Paging Param Decoded = " + json); } final JsonObject jsonCurrent = json.getAsJsonObject(CURRENT_KEYS); currentStartKey = jsonCurrent.get(CURRENT_START_KEY).getAsString(); currentStartKeyDocId = jsonCurrent.get(CURRENT_START_KEY_DOC_ID).getAsString(); startKey = json.get(START_KEY).getAsString(); startKeyDocId = json.get(START_KEY_DOC_ID).getAsString(); action = json.get(ACTION).getAsString(); } catch (Exception e) { throw new CouchDbException("could not parse the given param!", e); } if (PREVIOUS.equals(action)) { // previous return queryPreviousPage( rowsPerPage, currentStartKey, currentStartKeyDocId, startKey, startKeyDocId, classOfT); } else { // next return queryNextPage( rowsPerPage, currentStartKey, currentStartKeyDocId, startKey, startKeyDocId, classOfT); } }
@NonNull public static JsonObject getFullJsonObject(@NonNull Context context, @NonNull String id) { JsonObject json = getFullJsonObject(context); JsonObject reward = json.getAsJsonObject("reward"); reward.addProperty("id", id); return json; }
/** * Validate put request Json object for HostAddressResource * * @param requestBody the request Json object * @return true, if successful */ private boolean validatePut(final JsonObject requestBody) { LOG.trace("Start HostAddressResourceValidator#validatePut()"); boolean isValid = false; setInvalidParameter(VtnServiceJsonConsts.IPADDRESS); if (requestBody.has(VtnServiceJsonConsts.IPADDRESS) && requestBody.get(VtnServiceJsonConsts.IPADDRESS).isJsonObject()) { final JsonObject ipaddr = requestBody.getAsJsonObject(VtnServiceJsonConsts.IPADDRESS); // validation for mandatory keys: ipaddr setInvalidParameter(VtnServiceJsonConsts.IPADDR); if (ipaddr.has(VtnServiceJsonConsts.IPADDR) && ipaddr.getAsJsonPrimitive(VtnServiceJsonConsts.IPADDR).getAsString() != null) { isValid = validator.isValidIpV4( ipaddr.getAsJsonPrimitive(VtnServiceJsonConsts.IPADDR).getAsString().trim()); } if (isValid) { // validation for mandatory keys: netmask setInvalidParameter(VtnServiceJsonConsts.PREFIX); if (ipaddr.has(VtnServiceJsonConsts.PREFIX) && ipaddr.getAsJsonPrimitive(VtnServiceJsonConsts.PREFIX).getAsString() != null) { isValid = validator.isValidRange( ipaddr.getAsJsonPrimitive(VtnServiceJsonConsts.PREFIX).getAsString().trim(), VtnServiceJsonConsts.VAL_1, VtnServiceJsonConsts.VAL_30); } else { isValid = false; } } } LOG.trace("Complete HostAddressResourceValidator#validatePut()"); return isValid; }
public static HashMap<String, Integer> getAnimeSearchedMAL( String username, String password, String anime) { HashMap<String, Integer> map = new HashMap<String, Integer>(); JSONObject xmlJSONObj; String json = ""; String xml = ""; try { xml = searchAnimeMAL(username, password, anime); xmlJSONObj = XML.toJSONObject(xml); json = xmlJSONObj.toString(4); } catch (Exception e) { MAMUtil.writeLog(e); e.printStackTrace(); } JsonParser parser = new JsonParser(); JsonObject root = parser.parse(json).getAsJsonObject(); if (root.has("anime") && root.get("anime").getAsJsonObject().get("entry").isJsonArray()) { JsonArray searchedAnime = root.get("anime").getAsJsonObject().get("entry").getAsJsonArray(); for (JsonElement obj : searchedAnime) { String name = obj.getAsJsonObject().get("title").getAsString(); int id = obj.getAsJsonObject().get("id").getAsInt(); map.put(name, id); } } else if (root.has("anime")) { JsonObject obj = root.get("anime").getAsJsonObject().get("entry").getAsJsonObject(); int id = obj.getAsJsonObject().get("id").getAsInt(); map.put(anime, id); } return map; }
@Override public JsonObject upgrade( JsonObject agentUnitConfig, Map<File, JsonObject> dbSnapshot, Map<String, Map<File, DatabaseEntryDescriptor>> globalDbSnapshots) throws CouldNotPerformException { if (unitScopeIdMap.isEmpty()) { globalDbSnapshots .get(DAL_UNIT_CONFIG_DB_ID) .values() .stream() .map((dalUnitConfigDesriptor) -> dalUnitConfigDesriptor.getEntry()) .filter( (dalUnitConfig) -> !(!dalUnitConfig.has(ID_FIELD) || !dalUnitConfig.has(SCOPE_FIELD))) .forEach( (dalUnitConfig) -> { String id = dalUnitConfig.get(ID_FIELD).getAsString(); JsonObject scope = dalUnitConfig.getAsJsonObject(SCOPE_FIELD); if (!(!scope.has(COMPONENT_FIELD))) { JsonArray scopeComponents = scope.getAsJsonArray(COMPONENT_FIELD); String scopeAsString = "/"; for (JsonElement component : scopeComponents) { scopeAsString += component.getAsString() + "/"; } unitScopeIdMap.put(scopeAsString, id); } }); } boolean isPowerStateSynchroniserAgent = false; boolean isAmbientColorAgent = false; if (agentUnitConfig.has(LABEL_FIELD)) { String label = agentUnitConfig.get(LABEL_FIELD).getAsString(); if (label.contains(POWER_STATE_SYNCHRONISER_IDENTIFIER)) { isPowerStateSynchroniserAgent = true; } else if (label.contains(AMBIENT_COLOR_AGENT_IDE_AGENT_IDENTIFIER)) { isAmbientColorAgent = true; } } if (isPowerStateSynchroniserAgent || isAmbientColorAgent) { if (agentUnitConfig.has(META_CONFIG_FIELD)) { JsonObject metaConfig = agentUnitConfig.getAsJsonObject(META_CONFIG_FIELD); if (metaConfig.has(ENTRY_FIELD)) { JsonArray metaConfigEntries = metaConfig.getAsJsonArray(ENTRY_FIELD); if (isPowerStateSynchroniserAgent) { updatePowerStateSynchroniserAgentMetaConfig( metaConfigEntries, globalDbSnapshots.get(DAL_UNIT_CONFIG_DB_ID)); } else if (isAmbientColorAgent) { updateAmbientColorAgentMetaConfig( metaConfigEntries, globalDbSnapshots.get(DAL_UNIT_CONFIG_DB_ID)); } } } } return agentUnitConfig; }
public static String Group(String user, String channel) { String group = "None :<"; try { Perms perm = Main.map.get(channel); if (perm.getPermission().getMods().contains(user)) group = "Moderator"; if (perm.getPermission().getAdmins().contains(user)) group = "Admin"; String Exec = JsonUtils.getStringFromFile(Main.jsonFilePath.toString()); JsonObject exec = JsonUtils.getJsonObject(Exec); for (String users : exec.getAsJsonObject("Perms") .get("Exec") .toString() .replaceAll("[\\[\\]\"]", "") .split(",")) { if (users.equalsIgnoreCase(user)) return "Exec"; } } catch (IOException e) { e.printStackTrace(); } return group; }
/** * Creates a User based on a Microsoft Azure Mobile Service JSON object containing a UserId and * Authentication Token * * @param json JSON object used to create the User * @return The created user if it is a valid JSON object. Null otherwise * @throws MobileServiceException */ private MobileServiceUser createUserFromJSON(JsonObject json) throws MobileServiceException { if (json == null) { throw new IllegalArgumentException("json can not be null"); } // If the JSON object is valid, create a MobileServiceUser object if (json.has(USER_JSON_PROPERTY)) { JsonObject jsonUser = json.getAsJsonObject(USER_JSON_PROPERTY); if (!jsonUser.has(USERID_JSON_PROPERTY)) { throw new JsonParseException(USERID_JSON_PROPERTY + " property expected"); } String userId = jsonUser.get(USERID_JSON_PROPERTY).getAsString(); MobileServiceUser user = new MobileServiceUser(userId); if (!json.has(TOKEN_JSON_PARAMETER)) { throw new JsonParseException(TOKEN_JSON_PARAMETER + " property expected"); } user.setAuthenticationToken(json.get(TOKEN_JSON_PARAMETER).getAsString()); return user; } else { // If the JSON contains an error property show it, otherwise raise // an error with JSON content if (json.has("error")) { throw new MobileServiceException(json.get("error").getAsString()); } else { throw new JsonParseException(json.toString()); } } }
/** * Validate post request Json object for FlowFilterEntriesResource. * * @param requestBody the request Json object * @return true, if successful */ private boolean validatePost(final JsonObject requestBody) { LOG.trace("Start FlowFilterEntriesResourceValidator#validatePost()"); boolean isValid = false; setInvalidParameter(VtnServiceJsonConsts.FLOWFILTERENTRY); if (requestBody.has(VtnServiceJsonConsts.FLOWFILTERENTRY) && requestBody.get(VtnServiceJsonConsts.FLOWFILTERENTRY).isJsonObject()) { final JsonObject ffEntry = requestBody.getAsJsonObject(VtnServiceJsonConsts.FLOWFILTERENTRY); // validation for mandatory key: seqnum setInvalidParameter(VtnServiceJsonConsts.SEQNUM); if (ffEntry.has(VtnServiceJsonConsts.SEQNUM) && ffEntry.getAsJsonPrimitive(VtnServiceJsonConsts.SEQNUM).getAsString() != null && !ffEntry .getAsJsonPrimitive(VtnServiceJsonConsts.SEQNUM) .getAsString() .trim() .isEmpty()) { isValid = validator.isValidRange( ffEntry.getAsJsonPrimitive(VtnServiceJsonConsts.SEQNUM).getAsString().trim(), VtnServiceJsonConsts.VAL_1, VtnServiceJsonConsts.VAL_65535); } else { isValid = false; } if (isValid) { isValid = validator.isValidFlowFilterEntry(requestBody); } } LOG.trace("Complete FlowFilterEntriesResourceValidator#validatePost()"); return isValid; }
private List<Object> prepareArgumentValues( Method executedMethod, JsonObject request, Session session) { List<WebsocketParameterDescriptor> descriptors = getArguments(executedMethod); List<Object> values = new ArrayList<>(descriptors.size()); for (WebsocketParameterDescriptor descriptor : descriptors) { Type type = descriptor.getType(); if (Session.class.equals(type)) { values.add(session); } else { String name = descriptor.getName(); if (JsonObject.class.equals(type)) { values.add(name != null ? request.getAsJsonObject(name) : request); } else { Preconditions.checkNotNull(name); Gson gson = descriptor.getPolicy() == null ? GsonFactory.createGson() : GsonFactory.createGson(descriptor.getPolicy()); values.add(gson.fromJson(request.get(name), type)); } } } return values; }
public void parseJsonData(JsonObject jsonObject) { if (jsonObject == null) { return; } if (jsonObject.has(KEY_LOGGED_IN_USER)) { JsonObject loggedInUserObject = jsonObject.getAsJsonObject(KEY_LOGGED_IN_USER); firstName = loggedInUserObject.get(KEY_FIRST_NAME).getAsString(); preferenceClass.saveFirstName(firstName); lastName = loggedInUserObject.get(KEY_LAST_NAME).getAsString(); preferenceClass.saveLastName(lastName); gender = loggedInUserObject.get(KEY_GENDER).getAsString(); userEmail = loggedInUserObject.get(KEY_EMAIL).getAsString(); preferenceClass.saveLastUserEmail(userEmail); preferenceClass.saveUserEmail(userEmail); phoneNo = loggedInUserObject.get(KEY_PHONE_NO).getAsString(); preferenceClass.saveUserPhoneNo(phoneNo); userType = loggedInUserObject.get(KEY_USER_TYPE).getAsString(); if (loggedInUserObject.get(KEY_PROFILE_PIC).getAsString() != null) { imageURL = loggedInUserObject.get(KEY_PROFILE_PIC).getAsString(); } preferenceClass.saveProfileImageUrl(KEY_UAT_BASE_URL + imageURL); if (loggedInUserObject.has(KEY_USER_TYPE_OBJECT)) { JsonObject userTypeObject = loggedInUserObject.getAsJsonObject(KEY_USER_TYPE_OBJECT); userId = userTypeObject.get(KEY_ID).getAsString(); preferenceClass.saveCustomerId(userId); } } if (jsonObject.has(KEY_LOGIN_STATUS)) { if (jsonObject.get(KEY_LOGIN_STATUS).getAsBoolean() && userType.contentEquals("packrboy")) { Intent intent = new Intent(LoginActivity.this, TaskActivity.class); startActivity(intent); finish(); } else { Log.e("error2", "Invalid credentials"); hideKeyboard(); Snackbar.make( loginLayout, "Sorry you do not have an account with us. Go ahead create one and make life easy :)", Snackbar.LENGTH_LONG) .show(); } } }
/** * Annotate the number of columns and rows of the validation data set in the job parameter JSON * @return JsonObject annotated with num_cols and num_rows of the validation data set */ @Override protected JsonObject toJSON() { JsonObject jo = super.toJSON(); if (validation != null) { jo.getAsJsonObject("validation").addProperty("num_cols", validation.numCols()); jo.getAsJsonObject("validation").addProperty("num_rows", validation.numRows()); } return jo; }
private void updateVariableEnvironmentSensors() { Map<String, Object> env = getClient().getApplicationEnvironment(applicationName); JsonObject envTree = new Gson().toJsonTree(env).getAsJsonObject(); getEntity() .setAttribute( CloudFoundryWebApp.VCAP_SERVICES, envTree.getAsJsonObject("system_env_json").getAsJsonObject("VCAP_SERVICES").toString()); }
/** * Annotate the number of columns and rows of the training data set in the job parameter JSON * @return JsonObject annotated with num_cols and num_rows of the training data set */ @Override protected JsonObject toJSON() { JsonObject jo = super.toJSON(); if (source != null) { jo.getAsJsonObject("source").addProperty("num_cols", source.numCols()); jo.getAsJsonObject("source").addProperty("num_rows", source.numRows()); } return jo; }
public static void main(String[] args) throws FileNotFoundException, InterruptedException { File jsonFile; JsonParser jParser; JsonReader jReader; JsonObject jItem; Scanner scanner; String jItemString; String itemId, itemName; String twoHanded, itemType, damageRange, armor; JsonArray jPrimaryAttr; Iterator itr; String primaryAttr; jItemString = ""; jsonFile = new File(SPECIFIC_DIRECTORY + "\\items-" + item_file_to_parse + ".json"); jParser = new JsonParser(); scanner = new Scanner(jsonFile); while (scanner.hasNextLine()) { jItemString = scanner.nextLine(); jItem = jParser.parse(jItemString).getAsJsonObject(); itemId = jItem.get("id").toString(); itemName = jItem.get("name").toString(); twoHanded = jItem.getAsJsonObject("type").get("twoHanded").toString(); itemType = jItem.getAsJsonObject("type").get("id").toString(); damageRange = jItem.get("damageRange").toString().replace("–", "-"); try { armor = jItem.getAsJsonObject("armor").get("min").toString(); // min and max will be the same } catch (NullPointerException e) { armor = ""; } System.out.println("string: " + jItemString); System.out.println("itemId : " + itemId); System.out.println("itemName : " + itemName); System.out.println("twoHanded : " + twoHanded); System.out.println("itemType : " + itemType); System.out.println("damageRange : " + damageRange); System.out.println("armor : " + armor); jPrimaryAttr = jItem.getAsJsonArray("primary"); itr = jPrimaryAttr.iterator(); while (itr.hasNext()) {} System.out.println(" "); Thread.sleep(2000); } }
private static void readLabelsToScores(Map<String, Double> obj, JsonObject json) { if (json.has(LABEL_SCORE_MAP)) { JsonObject map = json.getAsJsonObject(LABEL_SCORE_MAP); for (Entry<String, JsonElement> e : map.entrySet()) { obj.put(e.getKey(), e.getValue().getAsDouble()); } } }
private static void readAttributes(HasAttributes obj, JsonObject json) { if (json.has("properties")) { JsonObject properties = json.getAsJsonObject("properties"); for (Entry<String, JsonElement> entry : properties.entrySet()) { obj.addAttribute(entry.getKey(), entry.getValue().getAsString()); } } }
private SegmentTileEntity deserializeTileEntity( JsonObject json, JsonDeserializationContext context) { SegmentTileEntity segment = new SegmentTileEntity(); segment.retainsOwner = json.getAsJsonObject().get("retainsOwner").getAsBoolean(); json.remove("retainsOwner"); return segment; }
private static Pair<Pair<String, Double>, int[]> readSentences(JsonObject json) { JsonObject object = json.getAsJsonObject("sentences"); String generator = readString("generator", object); double score = readDouble("score", object); int[] endPositions = readIntArray("sentenceEndPositions", object); return new Pair<>(new Pair<>(generator, score), endPositions); }
public static void filterFile(String directoryPath, String[] filePaths) throws IOException { List<List<String>> list = new LinkedList<>(); for (String filePath : filePaths) { String line = null; try (BufferedReader br = new BufferedReader(new FileReader(directoryPath + "/" + filePath))) { while ((line = br.readLine()) != null) { JsonObject tweet = new JsonParser().parse(line).getAsJsonObject(); JsonArray hashtagsElem = tweet.getAsJsonObject("entities").getAsJsonArray("hashtags"); Set<String> uniqueHashtags = new HashSet<>(); for (JsonElement hashtagElem : hashtagsElem) { String hashtag = hashtagElem.getAsJsonObject().get("text").getAsString(); uniqueHashtags.add(hashtag.toLowerCase()); } List<String> hashtags = new ArrayList<>(uniqueHashtags); Collections.sort(hashtags); if (!list.contains(hashtags)) { list.add(hashtags); } } } catch (Exception ex) { // System.err.println(line); } System.out.println("Parsed: " + filePath); } Map<String, Integer> map = new HashMap<>(); for (List<String> strings : list) { for (int i = 0; i < strings.size(); i++) { for (int j = i + 1; j < strings.size(); j++) { String key = strings.get(i) + " " + strings.get(j); Integer weight = map.get(key); if (weight == null) { map.put(key, 1); } else { map.put(key, weight + 1); } } } } File file = new File(directoryPath + "/graph"); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); for (Map.Entry<String, Integer> entry : map.entrySet()) { bw.write(entry.getKey() + " " + entry.getValue()); bw.newLine(); } bw.close(); }
public JsonObject toJSON() { final String json = new String(writeJSON(new AutoBuffer()).buf()); if (json.length() == 0) return new JsonObject(); JsonObject jo = (JsonObject) new JsonParser().parse(json); if (jo.has("model")) jo.getAsJsonObject("model").addProperty("model_category", this.model_category.toString()); return jo; }
/** * Annotate the name of the response column in the job parameter JSON * @return JsonObject annotated with the name of the response column */ @Override protected JsonObject toJSON() { JsonObject jo = super.toJSON(); int idx = source.find(response); if( idx == -1 ) { Vec vm = response.masterVec(); if( vm != null ) idx = source.find(vm); } jo.getAsJsonObject("response").add("name", new JsonPrimitive(idx == -1 ? "null" : source._names[idx])); return jo; }
public RollupTask parseRollupTask(JsonObject rollupTask, String context) throws BeanValidationException, QueryException { RollupTask task = m_gson.fromJson(rollupTask.getAsJsonObject(), RollupTask.class); validateObject(task); JsonArray rollups = rollupTask.getAsJsonObject().getAsJsonArray("rollups"); if (rollups != null) { for (int j = 0; j < rollups.size(); j++) { JsonObject rollupObject = rollups.get(j).getAsJsonObject(); Rollup rollup = m_gson.fromJson(rollupObject, Rollup.class); context = context + "rollup[" + j + "]"; validateObject(rollup, context); JsonObject queryObject = rollupObject.getAsJsonObject("query"); List<QueryMetric> queries = parseQueryMetric(queryObject, context); for (int k = 0; k < queries.size(); k++) { QueryMetric query = queries.get(k); context += ".query[" + k + "]"; validateHasRangeAggregator(query, context); // Add aggregators needed for rollups SaveAsAggregator saveAsAggregator = (SaveAsAggregator) m_aggregatorFactory.createAggregator("save_as"); saveAsAggregator.setMetricName(rollup.getSaveAs()); TrimAggregator trimAggregator = (TrimAggregator) m_aggregatorFactory.createAggregator("trim"); trimAggregator.setTrim(TrimAggregator.Trim.LAST); query.addAggregator(saveAsAggregator); query.addAggregator(trimAggregator); } rollup.addQueries(queries); task.addRollup(rollup); } } return task; }
@Override public BlockDefinition getBlockDefinitionForSection(JsonObject json, String sectionName) { if (json.has(sectionName) && json.get(sectionName).isJsonObject()) { JsonObject sectionJson = json.getAsJsonObject(sectionName); json.remove(sectionName); JsonMergeUtil.mergeOnto(json, sectionJson); return createBlockDefinition(sectionJson); } return null; }