Java Examples for com.google.gson.JsonArray

The following java examples will help you to understand the usage of com.google.gson.JsonArray. These source code samples are taken from different open source projects.

Example 1
Project: SimpleNews-master  File: WeatherJsonUtils.java View source code
/**
     * 获取天气信息
     * @param json
     * @return
     */
public static List<WeatherBean> getWeatherInfo(String json) {
    List<WeatherBean> list = new ArrayList<WeatherBean>();
    if (TextUtils.isEmpty(json)) {
        return list;
    }
    JsonParser parser = new JsonParser();
    JsonObject jsonObj = parser.parse(json).getAsJsonObject();
    String status = jsonObj.get("status").getAsString();
    if ("1000".equals(status)) {
        JsonArray jsonArray = jsonObj.getAsJsonObject("data").getAsJsonArray("forecast");
        for (int i = 0; i < jsonArray.size(); i++) {
            WeatherBean weatherBean = getWeatherBeanFromJson(jsonArray.get(i).getAsJsonObject());
            list.add(weatherBean);
        }
    }
    return list;
}
Example 2
Project: bennu-master  File: OAuthServletTest.java View source code
@Test
public void testServiceApplicationOAuthAccessProvider() {
    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();
    User user = createUser("testServiceApplicationOAuthAccessProvider", "John", "Doe", "John Doe", "[email protected]");
    ServiceApplication serviceApplication = new ServiceApplication();
    serviceApplication.setAuthor(user1);
    serviceApplication.addScopes(serviceApplicationOAuthAccessProvider);
    serviceApplication.addScopes(loggedScope);
    req.addParameter("client_id", serviceApplication.getExternalId());
    req.addParameter("client_secret", serviceApplication.getSecret());
    req.addParameter("grant_type", "client_credentials");
    req.setMethod("POST");
    req.setPathInfo("/access_token");
    try {
        oauthServlet.service(req, res);
        Assert.assertEquals("must return status OK", 200, res.getStatus());
        String tokenJson = res.getContentAsString();
        final String serviceAccessToken = new JsonParser().parse(tokenJson).getAsJsonObject().get("access_token").getAsString();
        String result = target("oauth").path("provider").path(serviceApplication.getExternalId()).path(user.getUsername()).queryParam("access_token", serviceAccessToken).request().post(null, String.class);
        Authenticate.unmock();
        final String userAccessToken = new JsonParser().parse(result).getAsJsonObject().get("access_token").getAsString();
        result = target("bennu-oauth").path("test").path("test-scope-with-logged-user").queryParam("access_token", userAccessToken).request().get(String.class);
        Assert.assertEquals("this is an endpoint with TEST scope: testServiceApplicationOAuthAccessProvider", result);
        Authenticate.mock(user);
        JsonArray authorizations = target("bennu-oauth").path("authorizations").request().get(JsonElement.class).getAsJsonArray();
        Assert.assertEquals("no authorizations because it is a service application", 0, authorizations.size());
    } catch (ServletExceptionIOException |  e) {
        Assert.fail(e.getMessage());
    } finally {
        serviceApplication.removeScope(serviceApplicationOAuthAccessProvider);
        serviceApplication.removeScope(loggedScope);
    }
}
Example 3
Project: expenditures-master  File: MissionResponsibilityController.java View source code
private void findUnits(JsonArray result, String[] input) {
    final OrganizationalModel model = MissionSystem.getInstance().getOrganizationalModel();
    final Set<AccountabilityType> typesSet = model.getAccountabilityTypesSet();
    model.getPartiesSet().forEach( p -> findUnits(result, input, typesSet, p));
}
Example 4
Project: aokp-gerrit-master  File: QueryShell.java View source code
/**
   * Outputs a result set to stdout in Json format.
   *
   * @param rs ResultSet to show.
   * @param alreadyOnRow true if rs is already on the first row. false
   *     otherwise.
   * @param start Timestamp in milliseconds when executing the statement
   *     started. This timestamp is used to compute statistics about the
   *     statement. If no statistics should be shown, set it to 0.
   * @param show Functions to map columns
   * @throws SQLException
   */
private void showResultSetJson(final ResultSet rs, boolean alreadyOnRow, long start, Function... show) throws SQLException {
    JsonArray collector = new JsonArray();
    final ResultSetMetaData meta = rs.getMetaData();
    final Function[] columnMap;
    if (show != null && 0 < show.length) {
        columnMap = show;
    } else {
        final int colCnt = meta.getColumnCount();
        columnMap = new Function[colCnt];
        for (int colId = 0; colId < colCnt; colId++) {
            final int p = colId + 1;
            final String name = meta.getColumnLabel(p);
            columnMap[colId] = new Identity(p, name);
        }
    }
    int rowCnt = 0;
    while (alreadyOnRow || rs.next()) {
        final JsonObject row = new JsonObject();
        final JsonObject cols = new JsonObject();
        for (Function function : columnMap) {
            String v = function.apply(rs);
            if (v == null) {
                continue;
            }
            cols.addProperty(function.name.toLowerCase(), v);
        }
        row.addProperty("type", "row");
        row.add("columns", cols);
        switch(outputFormat) {
            case JSON:
                println(row.toString());
                break;
            case JSON_SINGLE:
                collector.add(row);
                break;
            default:
                final JsonObject obj = new JsonObject();
                obj.addProperty("type", "error");
                obj.addProperty("message", "Unsupported Json variant");
                println(obj.toString());
                return;
        }
        alreadyOnRow = false;
        rowCnt++;
    }
    JsonObject tail = null;
    if (start != 0) {
        tail = new JsonObject();
        tail.addProperty("type", "query-stats");
        tail.addProperty("rowCount", rowCnt);
        final long ms = TimeUtil.nowMs() - start;
        tail.addProperty("runTimeMilliseconds", ms);
    }
    switch(outputFormat) {
        case JSON:
            if (tail != null) {
                println(tail.toString());
            }
            break;
        case JSON_SINGLE:
            if (tail != null) {
                collector.add(tail);
            }
            println(collector.toString());
            break;
        default:
            final JsonObject obj = new JsonObject();
            obj.addProperty("type", "error");
            obj.addProperty("message", "Unsupported Json variant");
            println(obj.toString());
    }
}
Example 5
Project: AIDR-master  File: JsonDeserializer.java View source code
public ClassifiedTweet getClassifiedTweet(String line, String collectionCode, boolean removeRetweet) {
    ClassifiedTweet tweet = new ClassifiedTweet();
    try {
        StringReader reader = new StringReader(line.trim());
        JsonReader jsonReader = new JsonReader(reader);
        jsonReader.setLenient(true);
        //Gson jsonObject = new GsonBuilder().serializeNulls().disableHtmlEscaping().serializeSpecialFloatingPointValues().create();
        JsonParser parser = new JsonParser();
        JsonObject jsonObj = (JsonObject) parser.parse(jsonReader);
        if (removeRetweet && jsonObj.get("retweeted_status") != null) {
            return null;
        }
        if (jsonObj.get("id_str") != null) {
            tweet.setTweetID(jsonObj.get("id_str").getAsString());
        }
        if (jsonObj.get("text") != null) {
            tweet.setMessage(jsonObj.get("text").getAsString());
        }
        if (jsonObj.get("created_at") != null) {
            tweet.setCreatedAtString(jsonObj.get("created_at").getAsString());
            tweet.setCreateAt(new Date(tweet.getTimestamp()));
        }
        JsonObject jsonUserObj = null;
        if (jsonObj.get("user") != null) {
            jsonUserObj = jsonObj.get("user").getAsJsonObject();
            if (jsonUserObj.get("id") != null) {
                tweet.setUserID(jsonUserObj.get("id").getAsString());
            }
            if (jsonUserObj.get("screen_name") != null) {
                tweet.setUserName(jsonUserObj.get("screen_name").getAsString());
                tweet.setTweetURL("https://twitter.com/" + tweet.getUserName() + "/status/" + tweet.getTweetID());
            }
            if (jsonUserObj.get("url") != null) {
                tweet.setUserURL(jsonUserObj.get("url").toString());
            }
        }
        JsonObject aidrObject = null;
        if (jsonObj.get("aidr") != null) {
            aidrObject = jsonObj.get("aidr").getAsJsonObject();
            if (aidrObject.get("crisis_name") != null) {
                tweet.setCrisisName(aidrObject.get("crisis_name").getAsString());
            }
            if (aidrObject.get("crisis_code") != null) {
                tweet.setCrisisCode(aidrObject.get("crisis_code").getAsString());
            }
            if (aidrObject.has("nominal_labels") && (aidrObject.get("nominal_labels") != null)) {
                // JSONArray nominalLabels = (JSONArray)
                // aidrObject.get("nominal_labels");
                JsonArray nominalLabels = aidrObject.get("nominal_labels").getAsJsonArray();
                StringBuffer allAttributeNames = new StringBuffer();
                StringBuffer allAttributeCodes = new StringBuffer();
                StringBuffer allLabelNames = new StringBuffer();
                StringBuffer allLabelCodes = new StringBuffer();
                StringBuffer allLabelDescriptions = new StringBuffer();
                StringBuffer allConfidences = new StringBuffer();
                StringBuffer humanLabeled = new StringBuffer();
                for (int i = 0; i < nominalLabels.size(); i++) {
                    // JSONObject label = (JSONObject) nominalLabels.get(i);
                    JsonObject label = nominalLabels.get(i).getAsJsonObject();
                    allAttributeNames.append(!label.get("attribute_name").isJsonNull() ? label.get("attribute_name").getAsString() : "null");
                    allAttributeCodes.append(!label.get("attribute_code").isJsonNull() ? label.get("attribute_code").getAsString() : "null");
                    allLabelNames.append(!label.get("label_name").isJsonNull() ? label.get("label_name").getAsString() : "null");
                    allLabelCodes.append(!label.get("label_code").isJsonNull() ? label.get("label_code").getAsString() : "null");
                    allLabelDescriptions.append(!label.get("label_description").isJsonNull() ? label.get("label_description").getAsString() : "null");
                    allConfidences.append(!label.get("confidence").isJsonNull() ? label.get("confidence").getAsFloat() : 0);
                    humanLabeled.append(!label.get("from_human").isJsonNull() ? label.get("from_human").getAsBoolean() : false);
                    // Added by koushik
                    NominalLabel nLabel = new NominalLabel();
                    nLabel.attribute_code = (label.has("attribute_code") && !label.get("attribute_code").isJsonNull()) ? label.get("attribute_code").getAsString() : "null";
                    nLabel.label_code = (label.has("label_code") && !label.get("label_code").isJsonNull()) ? label.get("label_code").getAsString() : "null";
                    nLabel.confidence = (label.has("confidence") && !label.get("confidence").isJsonNull()) ? Float.parseFloat(label.get("confidence").getAsString()) : 0;
                    nLabel.attribute_name = (label.has("attribute_name") && !label.get("attribute_name").isJsonNull()) ? label.get("attribute_name").getAsString() : "null";
                    nLabel.label_name = (label.has("label_name") && !label.get("label_name").isJsonNull()) ? label.get("label_name").getAsString() : "null";
                    nLabel.attribute_description = (label.has("attribute_description") && !label.get("attribute_description").isJsonNull()) ? label.get("attribute_description").getAsString() : "null";
                    nLabel.label_description = (label.has("label_description") && !label.get("label_description").isJsonNull()) ? label.get("label_description").getAsString() : "null";
                    nLabel.from_human = (label.has("from_human") && !label.get("from_human").isJsonNull()) ? Boolean.parseBoolean(label.get("from_human").getAsString()) : false;
                    tweet.getNominalLabels().add(nLabel);
                    // remove the ugly ';' from end-of-list
                    if (i < nominalLabels.size() - 1) {
                        allAttributeNames.append(";");
                        allAttributeCodes.append(";");
                        allLabelNames.append(";");
                        allLabelDescriptions.append(";");
                        allConfidences.append(";");
                        humanLabeled.append(";");
                    }
                }
                tweet.setAttributeName_1(allAttributeNames.toString());
                tweet.setAttributeCode_1(allAttributeCodes.toString());
                tweet.setLabelName_1(allLabelNames.toString());
                tweet.setLabelDescription_1(allLabelDescriptions.toString());
                tweet.setConfidence_1(allConfidences.toString());
                tweet.setHumanLabeled_1(humanLabeled.toString());
            } else {
                tweet.createDummyNominalLabels(collectionCode);
            }
        } else {
            tweet.createDummyNominalLabels(collectionCode);
        }
        return tweet;
    } catch (Exception ex) {
        logger.error("Exception while parsing the json to classiffied tweet for the collection: " + collectionCode + "\t" + ex);
        return null;
    }
}
Example 6
Project: sosies-generator-master  File: DefaultTypeAdaptersTest.java View source code
@Test(timeout = 1000)
public void testJsonArraySerialization_add1060() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testJsonArraySerialization_add1060");
    JsonArray array = new JsonArray();
    array.add(new com.google.gson.JsonPrimitive(1));
    array.add(new com.google.gson.JsonPrimitive(1));
    array.add(new com.google.gson.JsonPrimitive(2));
    array.add(new com.google.gson.JsonPrimitive(3));
    fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1293, gson, 1292, gson.toJson(array, com.google.gson.JsonElement.class));
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 7
Project: fenixedu-cms-master  File: AdminThemes.java View source code
private JsonObject generateMetadata(Node node) {
    JsonObject obj = new JsonObject();
    obj.addProperty("name", node.getNodeName());
    NamedNodeMap map = node.getAttributes();
    if (map != null) {
        // print attribute values
        int length = map.getLength();
        for (int i = 0; i < length; i++) {
            Node attr = map.item(i);
            obj.addProperty(attr.getNodeName(), attr.getNodeValue());
        }
    }
    Node child = node.getFirstChild();
    if (child == null) {
        return obj;
    }
    JsonArray array = new JsonArray();
    while (child != null) {
        JsonObject kid = generateMetadata(child);
        array.add(kid);
        child = child.getNextSibling();
    }
    obj.add("children", array);
    return obj;
}
Example 8
Project: enviroCar-app-master  File: TrackSerializer.java View source code
@Override
public JsonElement serialize(Track src, Type typeOfSrc, JsonSerializationContext context) {
    LOG.info("serialize() track");
    // set the properties of the json object
    JsonObject trackProperties = new JsonObject();
    trackProperties.addProperty(Track.KEY_TRACK_PROPERTIES_NAME, src.getName());
    trackProperties.addProperty(Track.KEY_TRACK_PROPERTIES_DESCRIPTION, src.getDescription());
    trackProperties.addProperty(Track.KEY_TRACK_PROPERTIES_SENSOR, src.getCar().getId());
    try {
        if (src.getMetadata() != null) {
            JSONObject json = src.getMetadata().toJson();
            JSONArray names = json.names();
            for (int i = 0; i < names.length(); i++) {
                trackProperties.addProperty(names.get(i).toString(), json.getString(names.get(i).toString()));
            }
        } else {
            LOG.warn("The track does not provide metadata!");
        }
    } catch (JSONException e) {
        LOG.severe("Error while parsing metadata of track", e);
    }
    // serialize the array of features.
    JsonArray trackFeatures = new JsonArray();
    List<Measurement> measurements = src.getMeasurements();
    if (measurements == null || measurements.isEmpty()) {
        LOG.severe("Track did not contain any non obfuscated measurements.");
        return null;
    }
    try {
        for (Measurement measurement : measurements) {
            JsonElement measurementJson = createMeasurementProperties(measurement, src.getCar());
            trackFeatures.add(measurementJson);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    JsonObject result = new JsonObject();
    result.addProperty(Track.KEY_TRACK_TYPE, "FeatureCollection");
    //TODO result.addProperty(Track.KEY_TRACK_PROPERTIES_LENGTH, src.getLengthOfTrack());
    result.add(Track.KEY_TRACK_PROPERTIES, trackProperties);
    result.add(Track.KEY_TRACK_FEATURES, trackFeatures);
    return result;
}
Example 9
Project: polly-master  File: SectorJsonHandler.java View source code
@Override
public FromClientSector deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final JsonObject obj = json.getAsJsonObject();
    final String self = this.getMemberOrThrow(obj, SELF).getAsString();
    final String quadName = this.getMemberOrThrow(obj, QUAD_NAME).getAsString();
    final int x = this.getMemberOrThrow(obj, X).getAsInt();
    final int y = this.getMemberOrThrow(obj, Y).getAsInt();
    final int attacker = this.getMemberOrThrow(obj, ATTACKER).getAsInt();
    final int defender = this.getMemberOrThrow(obj, DEFENDER).getAsInt();
    final int guard = this.getMemberOrThrow(obj, GUARD).getAsInt();
    final String typeName = this.getMemberOrDefault(obj, TYPE_NAME, //$NON-NLS-1$
    new JsonPrimitive("")).getAsString();
    final SectorType type = SectorType.byName(typeName);
    final JsonArray production = this.getMemberOrDefault(obj, PRODUCTION, new JsonArray()).getAsJsonArray();
    final List<Production> productionC = new ArrayList<>(production.size());
    for (int i = 0; i < production.size(); ++i) {
        final Production prod = this.productionHandler.deserialize(production.get(i), ProductionJsonHandler.PRODUCTION_TYPE, context);
        productionC.add(prod);
    }
    final boolean shareFleets = this.getMemberOrDefault(obj, SHARE_FLEET_POSITION, new JsonPrimitive(true)).getAsBoolean();
    final Sector s = new DefaultSector(quadName, x, y, attacker, defender, guard, type, productionC);
    final List<Fleet> ownFleets = this.readFleets(s, obj.get(OWN_FLEETS));
    final List<Fleet> fleets = this.readFleets(s, obj.get(FLEETS));
    final List<Portal> personal = this.readPortals(s, PortalType.PRIVATE, obj.get(PERSONAL_PORTALS));
    final List<Portal> clan = this.readPortals(s, PortalType.CLAN, obj.get(CLAN_PORTALS));
    return new FromClientSector(s, self, null, shareFleets, ownFleets, fleets, clan, personal);
}
Example 10
Project: LanternServer-master  File: JsonTranslator.java View source code
private Object fromJson(@Nullable DataView container, JsonElement json) {
    if (json.isJsonObject()) {
        if (container == null) {
            container = new MemoryDataContainer(DataView.SafetyMode.NO_DATA_CLONED);
        }
        for (Entry<String, JsonElement> en : json.getAsJsonObject().entrySet()) {
            final String key = en.getKey();
            final JsonElement element = en.getValue();
            if (element.isJsonObject()) {
                fromJson(container.createView(DataQuery.of(key)), element);
            } else {
                container.set(DataQuery.of(key), fromJson(null, json));
            }
        }
        return container;
    } else if (json.isJsonArray()) {
        final JsonArray array = json.getAsJsonArray();
        final List<Object> objects = Lists.newArrayListWithCapacity(array.size());
        int ints = 0;
        int bytes = 0;
        for (int i = 0; i < array.size(); i++) {
            final Object object = fromJson(null, array.get(i));
            objects.add(object);
            if (object instanceof Integer) {
                ints++;
            }
            if (object instanceof Byte) {
                bytes++;
            }
        }
        if (bytes == objects.size()) {
            final Byte[] array0 = new Byte[bytes];
            for (int i = 0; i < bytes; i++) {
                array0[i] = (Byte) objects.get(i);
            }
            return array0;
        } else if (ints == objects.size()) {
            final Integer[] array0 = new Integer[ints];
            for (int i = 0; i < bytes; i++) {
                array0[i] = (Integer) objects.get(i);
            }
            return array0;
        } else {
            return objects;
        }
    } else if (json.isJsonPrimitive()) {
        final String value = json.getAsString();
        if (DOUBLE.matcher(value).matches()) {
            return Double.parseDouble(value.substring(0, value.length() - 1));
        } else if (FLOAT.matcher(value).matches()) {
            return Float.parseFloat(value.substring(0, value.length() - 1));
        } else if (LONG.matcher(value).matches()) {
            return Long.parseLong(value.substring(0, value.length() - 1));
        } else if (SHORT.matcher(value).matches()) {
            return Short.parseShort(value.substring(0, value.length() - 1));
        } else if (BYTE.matcher(value).matches()) {
            return Byte.parseByte(value.substring(0, value.length() - 1));
        } else if (INTEGER.matcher(value).matches()) {
            return Integer.parseInt(value);
        } else if (DOUBLE_UNTYPED.matcher(value).matches()) {
            return Double.parseDouble(value);
        } else {
            if ("true".equalsIgnoreCase(value)) {
                return true;
            } else if ("false".equalsIgnoreCase(value)) {
                return false;
            }
            return value;
        }
    }
    return json;
}
Example 11
Project: FeedMeAndroid-master  File: EventDataDeserializer.java View source code
private Object[] deserializeJsonArray(JsonArray arr) {
    Object[] elems = new Object[arr.size()];
    Iterator<JsonElement> elemIter = arr.iterator();
    int i = 0;
    while (elemIter.hasNext()) {
        JsonElement elem = elemIter.next();
        elems[++i] = deserializeJsonElement(elem);
    }
    return elems;
}
Example 12
Project: eGov-master  File: ComplaintController.java View source code
// --------------------------------------------------------------------------------//
/**
     * This will returns all complaint types
     *
     * @return ComplaintType
     */
@RequestMapping(value = { ApiUrl.COMPLAINT_TYPES_BY_CATEGORIES }, method = GET, produces = { MediaType.TEXT_PLAIN_VALUE })
public ResponseEntity<String> getAllComplaintCategories() {
    try {
        final List<ComplaintTypeCategory> complaintCategories = complaintTypeCategoryService.findAll();
        final JsonArray jAryComplaintCategories = new JsonArray();
        for (final ComplaintTypeCategory complaintTypeCategory : complaintCategories) {
            final JsonObject jComplaintCategory = new JsonObject();
            jComplaintCategory.addProperty("categoryId", complaintTypeCategory.getId());
            jComplaintCategory.addProperty("categoryName", complaintTypeCategory.getName());
            final List<ComplaintType> complaintTypes = complaintTypeService.findActiveComplaintTypesByCategory(complaintTypeCategory.getId());
            final JsonArray jAryComplaintTypes = new JsonArray();
            for (final ComplaintType complaintType : complaintTypes) {
                final JsonObject jComplaintType = new JsonObject();
                jComplaintType.addProperty("id", complaintType.getId());
                jComplaintType.addProperty("name", complaintType.getName());
                jComplaintType.addProperty("description", complaintType.getDescription());
                jAryComplaintTypes.add(jComplaintType);
            }
            jComplaintCategory.add("complaintTypes", jAryComplaintTypes);
            jAryComplaintCategories.add(jComplaintCategory);
        }
        final JsonObject jresp = new JsonObject();
        jresp.add("complaintCategories", jAryComplaintCategories);
        return getResponseHandler().success(jresp);
    } catch (final Exception e) {
        LOGGER.error("EGOV-API ERROR ", e);
        return getResponseHandler().error(getMessage("server.error"));
    }
}
Example 13
Project: mini-git-server-master  File: EditDeserializer.java View source code
public Edit deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonNull()) {
        return null;
    }
    if (!json.isJsonArray()) {
        throw new JsonParseException("Expected array for Edit type");
    }
    final JsonArray o = (JsonArray) json;
    final int cnt = o.size();
    if (cnt < 4 || cnt % 4 != 0) {
        throw new JsonParseException("Expected array of 4 for Edit type");
    }
    if (4 == cnt) {
        return new Edit(get(o, 0), get(o, 1), get(o, 2), get(o, 3));
    }
    List<Edit> l = new ArrayList<Edit>((cnt / 4) - 1);
    for (int i = 4; i < cnt; ) {
        int as = get(o, i++);
        int ae = get(o, i++);
        int bs = get(o, i++);
        int be = get(o, i++);
        l.add(new Edit(as, ae, bs, be));
    }
    return new ReplaceEdit(get(o, 0), get(o, 1), get(o, 2), get(o, 3), l);
}
Example 14
Project: GeoGig-master  File: HttpMappedRemoteRepo.java View source code
private JsonObject createFetchMessage(ObjectId commitId, List<ObjectId> tracked) {
    JsonObject message = new JsonObject();
    JsonArray trackedArray = new JsonArray();
    for (ObjectId id : tracked) {
        trackedArray.add(new JsonPrimitive(id.toString()));
    }
    message.add("commitId", new JsonPrimitive(commitId.toString()));
    message.add("tracked", trackedArray);
    JsonArray filterArray = new JsonArray();
    ImmutableList<FilterDescription> repoFilters = filter.getFilterDescriptions();
    for (FilterDescription description : repoFilters) {
        JsonObject typeFilter = new JsonObject();
        typeFilter.add("featurepath", new JsonPrimitive(description.getFeaturePath()));
        typeFilter.add("type", new JsonPrimitive(description.getFilterType()));
        typeFilter.add("filter", new JsonPrimitive(description.getFilter()));
        filterArray.add(typeFilter);
    }
    message.add("filter", filterArray);
    return message;
}
Example 15
Project: android-money-manager-ex-master  File: YqlSecurityPriceUpdaterRetrofit.java View source code
private List<SecurityPriceModel> getPricesFromJson(JsonObject root) {
    ArrayList<SecurityPriceModel> result = new ArrayList<>();
    // check whether there is only one item or more
    JsonElement results = root.get("query").getAsJsonObject().get("results");
    if (results == null)
        return null;
    JsonObject resultsJson = results.getAsJsonObject();
    if (resultsJson == null)
        return null;
    JsonElement quoteElement = resultsJson.get("quote");
    if (quoteElement instanceof JsonArray) {
        JsonArray quotes = quoteElement.getAsJsonArray();
        for (int i = 0; i < quotes.size(); i++) {
            JsonObject quote = quotes.get(i).getAsJsonObject();
            // process individual quote
            SecurityPriceModel priceModel = getSecurityPriceFor(quote);
            if (priceModel == null)
                continue;
            result.add(priceModel);
        }
    } else {
        // Single quote
        JsonObject quote = quoteElement.getAsJsonObject();
        SecurityPriceModel priceModel = getSecurityPriceFor(quote);
        if (priceModel != null) {
            result.add(priceModel);
        }
    }
    return result;
}
Example 16
Project: RoboBuggy-master  File: SensorPlayer.java View source code
@Override
public void run() {
    Gson translator = new GsonBuilder().create();
    try {
        JsonObject logFile = Util.readJSONFile(path);
        if (!PlayBackUtil.validateLogFileMetadata(logFile)) {
            new RobobuggyLogicNotification("Log file doesn't have the proper header metadata!", RobobuggyMessageLevel.EXCEPTION);
            return;
        }
        long prevSensorTime = -1;
        JsonArray sensorDataArray = logFile.getAsJsonArray("sensor_data");
        for (JsonElement sensorAsJElement : sensorDataArray) {
            // spin in a tight loop until we've unpaused
            while (isPaused) {
                Thread.sleep(100);
            }
            boolean waitForTimeDiff = true;
            if (sensorAsJElement.isJsonObject()) {
                JsonObject sensorDataJson = sensorAsJElement.getAsJsonObject();
                String versionID = sensorDataJson.get("VERSION_ID").getAsString();
                Message transmitMessage = null;
                switch(versionID) {
                    case BrakeControlMessage.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, BrakeControlMessage.class);
                        break;
                    case BrakeMessage.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, BrakeMessage.class);
                        break;
                    case MagneticMeasurement.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, MagneticMeasurement.class);
                        break;
                    case DriveControlMessage.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, DriveControlMessage.class);
                        break;
                    case EncoderMeasurement.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, EncoderMeasurement.class);
                        break;
                    case FingerPrintMessage.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, FingerPrintMessage.class);
                        break;
                    case GpsMeasurement.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, GpsMeasurement.class);
                        break;
                    case GuiLoggingButtonMessage.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, GuiLoggingButtonMessage.class);
                        break;
                    case ImuMeasurement.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, ImuMeasurement.class);
                        break;
                    case GPSPoseMessage.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, GPSPoseMessage.class);
                        break;
                    case RemoteWheelAngleRequest.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, RemoteWheelAngleRequest.class);
                        break;
                    case ResetMessage.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, ResetMessage.class);
                        break;
                    case RobobuggyLogicNotificationMeasurement.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, RobobuggyLogicNotificationMeasurement.class);
                        break;
                    case StateMessage.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, StateMessage.class);
                        break;
                    case SteeringMeasurement.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, SteeringMeasurement.class);
                        break;
                    case WheelAngleCommandMeasurement.VERSION_ID:
                        transmitMessage = translator.fromJson(sensorDataJson, WheelAngleCommandMeasurement.class);
                        break;
                    case TERMINATING_VERSION_ID:
                        new RobobuggyLogicNotification("Stopping playback, hit a STOP", RobobuggyMessageLevel.NOTE);
                        return;
                    default:
                        waitForTimeDiff = false;
                        break;
                }
                if (!waitForTimeDiff) {
                    continue;
                }
                getNewPlaybackSpeed();
                BaseMessage timeMessage = (BaseMessage) transmitMessage;
                if (timeMessage == null) {
                    continue;
                }
                if (prevSensorTime == -1) {
                    prevSensorTime = timeMessage.getTimestamp().getTime();
                } else {
                    long currentSensorTime = timeMessage.getTimestamp().getTime();
                    long timeDiff = currentSensorTime - prevSensorTime;
                    if (timeDiff > 10) {
                        Thread.sleep((long) (timeDiff / playbackSpeed));
                    }
                    prevSensorTime = currentSensorTime;
                }
                switch(versionID) {
                    case BrakeMessage.VERSION_ID:
                        brakePub.publish(transmitMessage);
                        break;
                    case EncoderMeasurement.VERSION_ID:
                        encoderPub.publish(transmitMessage);
                        break;
                    case GpsMeasurement.VERSION_ID:
                        gpsPub.publish(transmitMessage);
                        break;
                    case GuiLoggingButtonMessage.VERSION_ID:
                        loggingButtonPub.publish(transmitMessage);
                        break;
                    case ImuMeasurement.VERSION_ID:
                        imuPub.publish(transmitMessage);
                        break;
                    case RobobuggyLogicNotificationMeasurement.VERSION_ID:
                        logicNotificationPub.publish(transmitMessage);
                        break;
                    case SteeringMeasurement.VERSION_ID:
                        steeringPub.publish(transmitMessage);
                        break;
                    case MagneticMeasurement.VERSION_ID:
                        magPub.publish(transmitMessage);
                        break;
                    default:
                        break;
                }
            }
        }
    } catch (FileNotFoundException e) {
        new RobobuggyLogicNotification("SensorPlayer couldn't find log file!", RobobuggyMessageLevel.EXCEPTION);
    } catch (InterruptedException e) {
        new RobobuggyLogicNotification("SensorPlayer was interrupted", RobobuggyMessageLevel.WARNING);
    } catch (UnsupportedEncodingException e) {
        new RobobuggyLogicNotification("Log file had unsupported encoding", RobobuggyMessageLevel.EXCEPTION);
    }
}
Example 17
Project: WaveInCloud-master  File: AbstractRobotTest.java View source code
public void refactor_testServiceEventMessageBundleRequest() throws Exception {
    final List<EventType> calledEvents = new ArrayList<EventType>();
    AbstractRobot robot = new AbstractRobot() {

        @Override
        protected String getRobotName() {
            return "Foo";
        }

        @Override
        public String getRobotProfilePageUrl() {
            return "http://code.google.com/apis/wave/";
        }

        @Override
        public void onBlipSubmitted(BlipSubmittedEvent e) {
            calledEvents.add(e.getType());
        }

        @Override
        public void onDocumentChanged(DocumentChangedEvent e) {
            calledEvents.add(e.getType());
        }

        @Override
        public void onWaveletTagsChanged(WaveletTagsChangedEvent e) {
            calledEvents.add(e.getType());
        }

        @Override
        protected String computeHash() {
            return "hash1";
        }
    };
    WaveletData waveletData = new WaveletData("google.com!wave1", "google.com!conv+root", "blip1", null);
    waveletData.addParticipant("[email protected]");
    BlipSubmittedEvent event1 = new BlipSubmittedEvent(null, null, "[email protected]", 1l, "blip1");
    DocumentChangedEvent event2 = new DocumentChangedEvent(null, null, "[email protected]", 1l, "blip1");
    WaveletTagsChangedEvent event3 = new WaveletTagsChangedEvent(null, null, "[email protected]", 1l, "blip1");
    EventMessageBundle bundle = new EventMessageBundle("Foo", "http://gmodules.com/api/rpc");
    bundle.addEvent(event1);
    bundle.addEvent(event2);
    bundle.addEvent(event3);
    bundle.setWaveletData(waveletData);
    String json = new GsonFactory().create().toJson(bundle);
    MockWriter mockWriter = new MockWriter();
    robot.doPost(makeMockRequest(JSONRPC_PATH, new BufferedReader(new StringReader(json))), makeMockResponse(mockWriter));
    assertEquals(3, calledEvents.size());
    assertEquals(EventType.BLIP_SUBMITTED, calledEvents.get(0));
    assertEquals(EventType.DOCUMENT_CHANGED, calledEvents.get(1));
    assertEquals(EventType.WAVELET_TAGS_CHANGED, calledEvents.get(2));
    // Assert that the outgoing operation bundle contains robot.notify() op.
    JsonParser jsonParser = new JsonParser();
    JsonArray ops = jsonParser.parse(mockWriter.getString()).getAsJsonArray();
    assertEquals(1, ops.size());
    JsonObject op = ops.get(0).getAsJsonObject();
    assertEquals(OperationType.ROBOT_NOTIFY.method(), op.get(RequestProperty.METHOD.key()).getAsString());
    JsonObject params = op.get(RequestProperty.PARAMS.key()).getAsJsonObject();
    assertEquals("0.22", params.get(ParamsProperty.PROTOCOL_VERSION.key()).getAsString());
    assertEquals("hash1", params.get(ParamsProperty.CAPABILITIES_HASH.key()).getAsString());
}
Example 18
Project: rascal-master  File: Settings.java View source code
IList getLocs(String accessor, IList def) {
    String names[] = accessor.split("\\.");
    JsonElement current = jobject;
    for (int i = 0; i < names.length; i++) {
        if (i == names.length - 1) {
            JsonArray locs = current.getAsJsonObject().getAsJsonArray(names[i]);
            if (locs == null) {
                return def;
            }
            IListWriter w = vf.listWriter();
            for (JsonElement loc : locs) {
                try {
                    w.append(vf.sourceLocation("file", "", loc.getAsString()));
                } catch (FactTypeUseExceptionURISyntaxException |  e) {
                    e.printStackTrace();
                }
            }
            return w.done();
        }
        current = current.getAsJsonObject().get(names[i]);
        if (current == null) {
            return def;
        }
    }
    return def;
}
Example 19
Project: dataverse-master  File: ShibServiceBean.java View source code
public String getAffiliation(String shibIdp, DevShibAccountType devShibAccountType) {
    JsonArray emptyJsonArray = new JsonArray();
    String discoFeedJson = emptyJsonArray.toString();
    String discoFeedUrl;
    if (devShibAccountType.equals(DevShibAccountType.PRODUCTION)) {
        discoFeedUrl = systemConfig.getDataverseSiteUrl() + "/Shibboleth.sso/DiscoFeed";
    } else {
        String devUrl = "http://localhost:8080/resources/dev/sample-shib-identities.json";
        discoFeedUrl = devUrl;
    }
    logger.fine("Trying to get affiliation from disco feed URL: " + discoFeedUrl);
    URL url = null;
    try {
        url = new URL(discoFeedUrl);
    } catch (MalformedURLException ex) {
        logger.info(ex.toString());
        return null;
    }
    if (url == null) {
        logger.info("url object was null after parsing " + discoFeedUrl);
        return null;
    }
    HttpURLConnection discoFeedRequest = null;
    try {
        discoFeedRequest = (HttpURLConnection) url.openConnection();
    } catch (IOException ex) {
        logger.info(ex.toString());
        return null;
    }
    if (discoFeedRequest == null) {
        logger.info("disco feed request was null");
        return null;
    }
    try {
        discoFeedRequest.connect();
    } catch (IOException ex) {
        logger.info(ex.toString());
        return null;
    }
    JsonParser jp = new JsonParser();
    JsonElement root = null;
    try {
        root = jp.parse(new InputStreamReader((InputStream) discoFeedRequest.getInputStream()));
    } catch (IOException ex) {
        logger.info(ex.toString());
        return null;
    }
    if (root == null) {
        logger.info("root was null");
        return null;
    }
    JsonArray rootArray = root.getAsJsonArray();
    if (rootArray == null) {
        logger.info("Couldn't get JSON Array from URL");
        return null;
    }
    discoFeedJson = rootArray.toString();
    logger.fine("Dump of disco feed:" + discoFeedJson);
    String affiliation = ShibUtil.getDisplayNameFromDiscoFeed(shibIdp, discoFeedJson);
    if (affiliation != null) {
        return affiliation;
    } else {
        logger.info("Couldn't find an affiliation from  " + shibIdp);
        return null;
    }
}
Example 20
Project: android-platform-tools-base-master  File: GoogleServicesTask.java View source code
/**
     * find an item in the "client" array that match the package name of the app
     * @param jsonObject the root json object.
     * @return a JsonObject representing the client entry or null if no match is found.
     */
private JsonObject getClientForPackageName(JsonObject jsonObject) {
    JsonArray array = jsonObject.getAsJsonArray("client");
    if (array != null) {
        final int count = array.size();
        for (int i = 0; i < count; i++) {
            JsonElement clientElement = array.get(i);
            if (clientElement == null || !clientElement.isJsonObject()) {
                continue;
            }
            JsonObject clientObject = clientElement.getAsJsonObject();
            JsonObject clientInfo = clientObject.getAsJsonObject("client_info");
            if (clientInfo == null)
                continue;
            JsonObject androidClientInfo = clientInfo.getAsJsonObject("android_client_info");
            if (androidClientInfo == null)
                continue;
            JsonPrimitive clientPackageName = androidClientInfo.getAsJsonPrimitive("package_name");
            if (clientPackageName == null)
                continue;
            if (packageName.equals(clientPackageName.getAsString())) {
                return clientObject;
            }
        }
    }
    return null;
}
Example 21
Project: incubator-wave-master  File: SolrWaveIndexerImpl.java View source code
private void postUpdateToSolr(ReadableWaveletData wavelet, JsonArray docsJson) {
    PostMethod postMethod = new PostMethod(solrBaseUrl + "/update/json?commit=true");
    try {
        RequestEntity requestEntity = new StringRequestEntity(docsJson.toString(), "application/json", "UTF-8");
        postMethod.setRequestEntity(requestEntity);
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(postMethod);
        if (statusCode != HttpStatus.SC_OK) {
            throw new IndexException(wavelet.getWaveId().serialise());
        }
    } catch (IOException e) {
        throw new IndexException(String.valueOf(wavelet.getWaveletId()), e);
    } finally {
        postMethod.releaseConnection();
    }
}
Example 22
Project: newFunf-master  File: TypeAdapters.java View source code
@Override
public JsonElement read(JsonReader in) throws IOException {
    switch(in.peek()) {
        case STRING:
            return new JsonPrimitive(in.nextString());
        case NUMBER:
            String number = in.nextString();
            return new JsonPrimitive(new LazilyParsedNumber(number));
        case BOOLEAN:
            return new JsonPrimitive(in.nextBoolean());
        case NULL:
            in.nextNull();
            return JsonNull.INSTANCE;
        case BEGIN_ARRAY:
            JsonArray array = new JsonArray();
            in.beginArray();
            while (in.hasNext()) {
                array.add(read(in));
            }
            in.endArray();
            return array;
        case BEGIN_OBJECT:
            JsonObject object = new JsonObject();
            in.beginObject();
            while (in.hasNext()) {
                object.add(in.nextName(), read(in));
            }
            in.endObject();
            return object;
        case END_DOCUMENT:
        case NAME:
        case END_OBJECT:
        case END_ARRAY:
        default:
            throw new IllegalArgumentException();
    }
}
Example 23
Project: platform-api-master  File: DtoTemplate.java View source code
private void emitPreamble(StringBuilder builder) {
    builder.append("/*******************************************************************************\n");
    builder.append(" * Copyright (c) 2012-2014 Codenvy, S.A.\n");
    builder.append(" * All rights reserved. This program and the accompanying materials\n");
    builder.append(" * are made available under the terms of the Eclipse Public License v1.0\n");
    builder.append(" * which accompanies this distribution, and is available at\n");
    builder.append(" * http://www.eclipse.org/legal/epl-v10.html\n");
    builder.append(" *\n");
    builder.append(" * Contributors:\n");
    builder.append(" * Codenvy, S.A. - initial API and implementation\n");
    builder.append(" *******************************************************************************/\n\n\n");
    builder.append("// GENERATED SOURCE. DO NOT EDIT.\npackage ");
    builder.append(packageName);
    builder.append(";\n\n");
    if ("server".equals(implType)) {
        builder.append("import org.eclipse.che.dto.server.JsonSerializable;\n");
        builder.append("\n");
        builder.append("import com.google.gson.Gson;\n");
        builder.append("import com.google.gson.GsonBuilder;\n");
        builder.append("import com.google.gson.JsonArray;\n");
        builder.append("import com.google.gson.JsonElement;\n");
        builder.append("import com.google.gson.JsonNull;\n");
        builder.append("import com.google.gson.JsonObject;\n");
        builder.append("import com.google.gson.JsonParser;\n");
        builder.append("import com.google.gson.JsonPrimitive;\n");
        builder.append("\n");
        builder.append("import java.util.List;\n");
        builder.append("import java.util.Map;\n");
    }
    if ("client".equals(implType)) {
        builder.append("import org.eclipse.che.ide.dto.ClientDtoFactoryVisitor;\n");
        builder.append("import org.eclipse.che.ide.dto.DtoFactoryVisitor;\n");
        builder.append("import org.eclipse.che.ide.dto.JsonSerializable;\n");
        builder.append("import com.google.gwt.json.client.*;\n");
        builder.append("import com.google.inject.Singleton;\n");
    }
    builder.append("\n\[email protected]({\"unchecked\", \"cast\"})\n");
    if ("client".equals(implType)) {
        builder.append("@Singleton\n");
        builder.append("@ClientDtoFactoryVisitor\n");
    }
    // Note that we always use fully qualified path names when referencing Types
    // so we need not add any import statements for anything.
    builder.append("public class ");
    builder.append(className);
    if ("server".equals(implType)) {
        builder.append(" implements ").append(DtoFactoryVisitor.class.getCanonicalName());
    }
    if ("client".equals(implType)) {
        builder.append(" implements ").append("DtoFactoryVisitor");
    }
    builder.append(" {\n\n");
    if ("server".equals(implType)) {
        builder.append("  private static final Gson gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create();\n\n");
        builder.append("  @Override\n" + "  public void accept(org.eclipse.che.dto.server.DtoFactory dtoFactory) {\n");
        for (DtoImpl dto : getDtoInterfaces()) {
            String dtoInterface = dto.getDtoInterface().getCanonicalName();
            builder.append("    dtoFactory.registerProvider(").append(dtoInterface).append(".class").append(", ").append("new org.eclipse.che.dto.server.DtoProvider<").append(dtoInterface).append(">() {\n");
            builder.append("        public Class<? extends ").append(dtoInterface).append("> getImplClass() {\n").append("            return ").append(dto.getImplClassName()).append(".class;\n");
            builder.append("        }\n\n");
            builder.append("        public ").append(dtoInterface).append(" newInstance() {\n").append("            return ").append(dto.getImplClassName()).append(".make();\n");
            builder.append("        }\n\n");
            builder.append("        public ").append(dtoInterface).append(" fromJson(String json) {\n").append("            return ").append(dto.getImplClassName()).append(".fromJsonString(json);\n");
            builder.append("        }\n\n");
            builder.append("        public ").append(dtoInterface).append(" fromJson(com.google.gson.JsonElement json) {\n").append("            return ").append(dto.getImplClassName()).append(".fromJsonElement(json);\n");
            builder.append("        }\n\n");
            builder.append("        public ").append(dtoInterface).append(" clone(").append(dtoInterface).append(" origin) {\n").append("            return new ").append(dto.getImplClassName()).append("(origin);\n");
            builder.append("        }\n");
            builder.append("    });\n");
        }
        builder.append("  }\n\n");
    }
    if ("client".equals(implType)) {
        builder.append("  @Override\n").append("  public void accept(org.eclipse.che.ide.dto.DtoFactory dtoFactory) {\n");
        for (DtoImpl dto : getDtoInterfaces()) {
            String dtoInterface = dto.getDtoInterface().getCanonicalName();
            builder.append("    dtoFactory.registerProvider(").append(dtoInterface).append(".class").append(", ").append("new org.eclipse.che.ide.dto.DtoProvider<").append(dtoInterface).append(">() {\n");
            builder.append("        public Class<? extends ").append(dtoInterface).append("> getImplClass() {\n").append("            return ").append(dto.getImplClassName()).append(".class;\n");
            builder.append("        }\n\n");
            builder.append("        public ").append(dtoInterface).append(" newInstance() {\n").append("            return ").append(dto.getImplClassName()).append(".make();\n");
            builder.append("        }\n\n");
            builder.append("        public ").append(dtoInterface).append(" fromJson(String json) {\n").append("            return ").append(dto.getImplClassName()).append(".fromJsonString(json);\n");
            builder.append("        }\n");
            builder.append("    });\n");
        }
        builder.append("  }\n\n");
    }
}
Example 24
Project: edx-app-android-master  File: ConfigTests.java View source code
@Test
public void testZeroRatingConfig() {
    JsonObject configBase = new JsonObject();
    JsonObject zeroRatingConfig = new JsonObject();
    zeroRatingConfig.add(ENABLED, new JsonPrimitive(true));
    configBase.add(ZERO_RATING, zeroRatingConfig);
    ArrayList<String> carrierList = new ArrayList<String>();
    carrierList.add("12345");
    carrierList.add("foo");
    JsonArray carriers = new JsonArray();
    for (String carrier : carrierList) {
        carriers.add(new JsonPrimitive(carrier));
    }
    zeroRatingConfig.add(CARRIERS, carriers);
    ArrayList<String> domainList = new ArrayList<>();
    domainList.add("domain1");
    domainList.add("domain2");
    JsonArray domains = new JsonArray();
    for (String domain : domainList) {
        domains.add(new JsonPrimitive(domain));
    }
    zeroRatingConfig.add(WHITE_LIST_OF_DOMAINS, domains);
    Config config = new Config(configBase);
    assertTrue(config.getZeroRatingConfig().isEnabled());
    assertEquals(carrierList, config.getZeroRatingConfig().getCarriers());
    assertEquals(domainList, config.getZeroRatingConfig().getWhiteListedDomains());
}
Example 25
Project: openmuc-master  File: ToJson.java View source code
public void addDeviceScanInfoList(List<DeviceScanInfo> deviceScanInfoList) {
    JsonArray jsa = new JsonArray();
    for (DeviceScanInfo deviceScanInfo : deviceScanInfoList) {
        JsonObject jso = new JsonObject();
        jso.addProperty(Const.ID, deviceScanInfo.getId());
        jso.addProperty(Const.DEVICEADDRESS, deviceScanInfo.getDeviceAddress());
        jso.addProperty(Const.SETTINGS, deviceScanInfo.getSettings());
        jso.addProperty(Const.DESCRIPTION, deviceScanInfo.getDescription());
        jsa.add(jso);
    }
    jsonObject.add(Const.DEVICES, jsa);
}
Example 26
Project: financius-public-master  File: BackupDataImporter.java View source code
private void importCurrencies(JsonObject json) {
    final List<ContentValues> valuesList = new ArrayList<>();
    final JsonArray modelsJson = json.getAsJsonArray("currencies");
    final Currency model = new Currency();
    for (int i = 0, size = modelsJson.size(); i < size; i++) {
        final JsonObject modelJson = modelsJson.get(i).getAsJsonObject();
        updateBaseModel(model, modelJson);
        model.setCode(modelJson.get("code").getAsString());
        model.setSymbol(modelJson.get("symbol").getAsString());
        model.setSymbolPosition(SymbolPosition.fromInt(modelJson.get("symbol_position").getAsInt()));
        model.setDecimalSeparator(DecimalSeparator.fromSymbol(modelJson.get("decimal_separator").getAsString()));
        model.setGroupSeparator(GroupSeparator.fromSymbol(modelJson.get("group_separator").getAsString()));
        model.setDecimalCount(modelJson.get("decimal_count").getAsInt());
        model.setDefault(modelJson.get("is_default").getAsBoolean());
        model.setExchangeRate(modelJson.get("exchange_rate").getAsDouble());
        valuesList.add(model.asValues());
    }
    insert(valuesList, CurrenciesProvider.uriCurrencies());
}
Example 27
Project: ohmagePhone-master  File: ProbeUploadService.java View source code
public void upload() {
    uploadStarted();
    Cursor observersCursor = getContentResolver().query(getContentURI(), new String[] { "distinct " + getNameColumn(), getVersionColumn() }, BaseProbeColumns.USERNAME + "=?", new String[] { mAccount.getUsername() }, null);
    HashMap<String, String> observers = new HashMap<String, String>();
    while (observersCursor.moveToNext()) {
        observers.put(observersCursor.getString(0), observersCursor.getString(1));
    }
    observersCursor.close();
    for (String currentObserver : observers.keySet()) {
        String currentVersion = observers.get(currentObserver);
        Cursor c = getContentResolver().query(getContentURI(), getProjection(), BaseProbeColumns.USERNAME + "=? AND " + getNameColumn() + "=? AND " + getVersionColumn() + "=?", new String[] { mAccount.getUsername(), currentObserver, currentVersion }, null);
        JsonArray probes = new JsonArray();
        ArrayList<Long> delete = new ArrayList<Long>();
        StringBuilder deleteString = new StringBuilder();
        int payloadSize = 0;
        for (int i = 0; i < c.getCount() + 1; i++) {
            try {
                c.moveToPosition(i);
            } catch (IllegalStateException e) {
                Log.e(TAG, "illegal state exception moving to " + i + " of " + (c.getCount() + 1));
                upload();
                return;
            }
            // the points we have so far
            if (payloadSize > BATCH_SIZE || c.isAfterLast()) {
                Log.d(TAG, "total payload for " + currentObserver + "=" + payloadSize);
                if (!upload(probes, currentObserver, currentVersion)) {
                    c.close();
                    return;
                }
                // maximum expression tree depth of 1000
                for (int batch = 0; batch < delete.size(); batch++) {
                    if (deleteString.length() != 0)
                        deleteString.append(" OR ");
                    deleteString.append(BaseColumns._ID + "=" + delete.get(batch));
                    // point, delete them
                    if ((batch != 0 && batch % (1000 - 2) == 0) || batch == delete.size() - 1) {
                        getContentResolver().delete(getContentURI(), deleteString.toString(), null);
                        deleteString = new StringBuilder();
                    }
                }
                delete.clear();
                if (c.isAfterLast())
                    break;
                payloadSize = 0;
                probes = new JsonArray();
            }
            payloadSize += addProbe(probes, c);
            delete.add(c.getLong(0));
        }
        c.close();
    }
    uploadFinished();
}
Example 28
Project: cdt-master  File: ArduinoManager.java View source code
public Collection<ArduinoLibrary> getLibraries(IProject project) throws CoreException {
    initInstalledLibraries();
    IEclipsePreferences settings = getSettings(project);
    //$NON-NLS-1$
    String librarySetting = settings.get(LIBRARIES, "[]");
    JsonArray libArray = new JsonParser().parse(librarySetting).getAsJsonArray();
    List<ArduinoLibrary> libraries = new ArrayList<>(libArray.size());
    for (JsonElement libElement : libArray) {
        if (libElement.isJsonPrimitive()) {
            String libName = libElement.getAsString();
            ArduinoLibrary lib = installedLibraries.get(libName);
            if (lib != null) {
                libraries.add(lib);
            }
        } else {
            JsonObject libObj = libElement.getAsJsonObject();
            String packageName = //$NON-NLS-1$
            libObj.get("package").getAsString();
            String platformName = //$NON-NLS-1$
            libObj.get("platform").getAsString();
            String libName = //$NON-NLS-1$
            libObj.get("library").getAsString();
            ArduinoPackage pkg = getPackage(packageName);
            if (pkg != null) {
                ArduinoPlatform platform = pkg.getInstalledPlatform(platformName);
                if (platform != null) {
                    ArduinoLibrary lib = platform.getLibrary(libName);
                    if (lib != null) {
                        libraries.add(lib);
                    }
                }
            }
        }
    }
    return libraries;
}
Example 29
Project: NucleusFramework-master  File: JsonDataNode.java View source code
@Override
public boolean set(String keyPath, @Nullable Object value) {
    keyPath = getFullPath(keyPath);
    String[] path = TextUtils.PATTERN_DOT.split(keyPath);
    if (!keyPath.isEmpty())
        removeKey(path);
    if (value != null) {
        if (value instanceof IDataNodeSerializable) {
            IDataNode node = getNode(keyPath);
            IDataNodeSerializable serializable = (IDataNodeSerializable) value;
            serializable.serialize(node);
            markDirty();
            return true;
        }
        if (keyPath.isEmpty())
            return false;
        if (value instanceof UUID) {
            value = String.valueOf(value);
        } else if (value instanceof Date) {
            value = ((Date) value).getTime();
        } else if (value instanceof Location) {
            value = LocationUtils.serialize((Location) value, 2);
        } else if (value instanceof ItemStack) {
            value = ItemStackUtils.serialize((ItemStack) value);
        } else if (value instanceof ItemStack[]) {
            value = ItemStackUtils.serialize((ItemStack[]) value);
        } else if (value instanceof Enum<?>) {
            Enum<?> e = (Enum<?>) value;
            value = e.name();
        } else if (value instanceof Collection) {
            Collection collection = (Collection) value;
            String[] array = new String[collection.size()];
            int i = 0;
            for (Object elm : collection) {
                array[i] = elm == null ? null : String.valueOf(elm);
                i++;
            }
            value = array;
        } else if (value.getClass().isArray() && !(value instanceof String[])) {
            int size = Array.getLength(value);
            String[] array = new String[size];
            for (int i = 0; i < size; i++) {
                Object elm = Array.get(value, i);
                array[i] = elm == null ? null : String.valueOf(elm);
            }
            value = array;
        } else if (value instanceof CharSequence) {
            value = value.toString();
        }
        if (value instanceof String[]) {
            String[] array = (String[]) value;
            JsonArray jsonArray = new JsonArray();
            for (String string : array) {
                jsonArray.add(_gson.toJsonTree(string));
            }
            value = jsonArray;
        }
        addKey(path, value);
    }
    markDirty();
    return true;
}
Example 30
Project: CDDA-Tileset-Editor-master  File: AsciiEntry.java View source code
private static void parseJson(JsonElement elem, HashMap<String, AsciiEntry> map) {
    if (elem.isJsonArray()) {
        JsonArray array = elem.getAsJsonArray();
        for (int i = 0; i < array.size(); ++i) {
            parseJson(array.get(i), map);
        }
    } else if (elem.isJsonObject()) {
        JsonObject obj = elem.getAsJsonObject();
        if (obj.has("id") && obj.has("symbol") && obj.has("color")) {
            // vp_
            String id = obj.get("id").getAsString();
            String symbol = obj.get("symbol").getAsString();
            String color = obj.get("color").getAsString();
            if ("vehicle_part".equalsIgnoreCase(obj.get("type").getAsString())) {
                id = "vp_" + id;
                String flags = "";
                if (obj.has("flags")) {
                    flags = obj.getAsJsonArray("flags").toString();
                }
                // symbol gets overridden based on which VP is it
                boolean frame = false;
                if (obj.has("location")) {
                    if ("structure".equalsIgnoreCase(obj.get("location").getAsString())) {
                        frame = true;
                    }
                    int tileID = -1;
                    // _nw - top left corner
                    if (id.endsWith("_nw")) {
                        tileID = frame ? 201 : 218;
                    }
                    // _ne - top right corner
                    if (id.endsWith("_ne")) {
                        tileID = frame ? 187 : 191;
                    }
                    // _sw - bottom left corner
                    if (id.endsWith("_sw")) {
                        tileID = frame ? 200 : 192;
                    }
                    // _se - bottom right corner
                    if (id.endsWith("_se")) {
                        tileID = frame ? 188 : 217;
                    }
                    // _vertical or _vertical_2 - vertical (duh)
                    if (id.endsWith("_vertical") || id.endsWith("_vertical_2")) {
                        tileID = frame ? 215 : 179;
                    }
                    // _horizontal or _horizontal_2 - horizontal (duuuh)
                    if (id.endsWith("_horizontal") || id.endsWith("_horizontal_2")) {
                        tileID = frame ? 216 : 196;
                    }
                    // _cross - internal cross
                    if (id.endsWith("_cross")) {
                        tileID = frame ? 206 : 197;
                    }
                    // here and set the ID back to -1 if it's needed
                    if (flags.indexOf("CARGO") >= 0 || flags.indexOf("AISLE") >= 0 || flags.indexOf("PROTRUSION") >= 0) {
                        tileID = -1;
                    }
                    if (tileID > 0) {
                        symbol = new String(new char[] { (char) tileID });
                    }
                }
            }
            if (symbol.length() > 1) {
                // if((symbol=="LINE_XOXO") || (symbol=="LINE_OXOX")){
                // going multitile
                // in vanilla this is just the walls, so we can fudge it a
                // little here
                map.put(id, new AsciiEntry(id, color, "#", true, false));
            } else {
                if (obj.has("broken_symbol") && obj.has("broken_color")) {
                    map.put(id, new AsciiEntry(id, color, symbol, obj.get("broken_color").getAsString(), obj.get("broken_symbol").getAsString()));
                } else {
                    map.put(id, new AsciiEntry(id, color, symbol));
                }
            }
        }
        for (Map.Entry<String, JsonElement> entry : obj.entrySet()) {
            parseJson(entry.getValue(), map);
        }
    }
}
Example 31
Project: Protocoder-master  File: PNetwork.java View source code
@ProtocoderScript
@APIMethod(description = "Simple http post request. It needs an object to be sent. If an element of the object contains the key file then it will try to upload the resource indicated in the value as Uri ", example = "")
@APIParam(params = { "url", "params", "function(responseString)" })
public void httpPost(String url, Object object, final HttpPostCB callbackfn) {
    final HttpClient httpClient = new DefaultHttpClient();
    final HttpContext localContext = new BasicHttpContext();
    final HttpPost httpPost = new HttpPost(url);
    Gson g = new Gson();
    JsonArray q = g.toJsonTree(object).getAsJsonArray();
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int i = 0; i < q.size(); i++) {
        Set<Entry<String, JsonElement>> set = q.get(i).getAsJsonObject().entrySet();
        // go through elements
        String name = "";
        String content = "";
        String type = "";
        for (Object element : set) {
            Entry<String, JsonElement> entry = (Entry<String, JsonElement>) element;
            if (entry.getKey().equals("name")) {
                name = entry.getValue().getAsString();
            } else if (entry.getKey().equals("content")) {
                content = entry.getValue().getAsString();
            } else if (entry.getKey().equals("type")) {
                type = entry.getValue().getAsString();
            }
        }
        // create the multipart
        if (type.contains("file")) {
            File f = new File(ProjectManager.getInstance().getCurrentProject().getStoragePath() + "/" + content);
            ContentBody cbFile = new FileBody(f);
            entity.addPart(name, cbFile);
        } else if (type.contains("text")) {
            // Normal string data
            try {
                entity.addPart(name, new StringBody(content));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
    // send
    httpPost.setEntity(entity);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                HttpResponse response = httpClient.execute(httpPost, localContext);
                callbackfn.event(response.getStatusLine().toString());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}