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: GsonBodyReaderWriterTest.java View source code
@Path("/readerwritertest")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public JsonArray map(@QueryParam("data") JsonObject data, JsonArray elements) {
    JsonArray array = new JsonArray();
    array.add(new JsonPrimitive("Doing map for " + data.get("name").getAsString()));
    for (JsonElement el : elements) {
        final int newValue = el.getAsJsonObject().get("value").getAsInt() * 2;
        el.getAsJsonObject().addProperty("value", newValue);
        array.add(el);
    }
    return array;
}
Example 3
Project: expenditures-master  File: CompleteMissionAdapter.java View source code
private static JsonObject toJson(final MissionItem item) {
    final JsonObject o = new JsonObject();
    o.addProperty("item", item.getLocalizedName());
    o.addProperty("description", item.getItemDescription());
    o.addProperty("cost", item.getPrevisionaryCosts().toFormatString());
    final JsonArray participants = item.getPeopleSet().stream().map(CompleteMissionAdapter::toJson).collect(toJsonArray());
    o.add("participants", participants);
    final JsonArray financers = item.getMissionItemFinancersSet().stream().map(CompleteMissionAdapter::toJson).collect(toJsonArray());
    o.add("financers", financers);
    return o;
}
Example 4
Project: aokp-gerrit-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<>((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 5
Project: AIDR-master  File: DeserializeFilters.java View source code
public JsonQueryList deserializeConstraints(final String queryString) {
    Gson jsonObject = new GsonBuilder().serializeNulls().disableHtmlEscaping().serializeSpecialFloatingPointValues().create();
    if (!StringUtils.isEmpty(queryString)) {
        JsonParser parser = new JsonParser();
        JsonObject obj = (JsonObject) parser.parse(queryString);
        JsonArray constraintsArray = null;
        if (obj.has("constraints")) {
            // should always be true
            constraintsArray = obj.get("constraints") != null ? obj.get("constraints").getAsJsonArray() : new JsonArray();
        //logger.debug("constraints: " + constraintsArray);
        }
        JsonQueryList queryList = new JsonQueryList();
        if (constraintsArray.size() > 0) {
            for (int i = 0; i < constraintsArray.size(); i++) {
                try {
                    JsonElement q = constraintsArray.get(i);
                    //System.out.println("constraint " + i + ": " + q);
                    GenericInputQuery constraint = jsonObject.fromJson(q, GenericInputQuery.class);
                    queryList.createConstraint(constraint);
                } catch (Exception e) {
                    logger.error("Error in deserializing received constraints", e);
                    return null;
                }
            }
        }
        logger.debug("Output: deserialized queryList: " + queryList);
        return queryList;
    }
    logger.debug("Output: deserialized queryList: null");
    return null;
}
Example 6
Project: sosies-generator-master  File: CustomSerializerTest.java View source code
public void testSubClassSerializerInvokedForBaseClassFieldsHoldingArrayOfSubClassInstances() {
    fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testSubClassSerializerInvokedForBaseClassFieldsHoldingArrayOfSubClassInstances");
    Gson gson = new GsonBuilder().registerTypeAdapter(TestTypes.Base.class, new TestTypes.BaseSerializer()).registerTypeAdapter(TestTypes.Sub.class, new TestTypes.SubSerializer()).create();
    TestTypes.ClassWithBaseArrayField target = new TestTypes.ClassWithBaseArrayField(new TestTypes.Base[] { new TestTypes.Sub(), new TestTypes.Sub() });
    JsonObject json = ((JsonObject) (gson.toJsonTree(target)));
    JsonArray array = json.get("foo").getAsJsonArray();
    for (JsonElement element : array) {
        JsonElement serializerKey = element.getAsJsonObject().get(TestTypes.Base.SERIALIZER_KEY);
        fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1097, com.google.gson.common.TestTypes.SubSerializer.NAME);
        fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 1099, serializerKey, 1098, serializerKey.getAsString());
    }
    fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}
Example 7
Project: fenixedu-cms-master  File: ComponentDescriptor.java View source code
public JsonObject toJson(Page page) {
    JsonObject json = new JsonObject();
    json.addProperty("key", parameter.getName());
    json.addProperty("title", ann.value());
    json.addProperty("type", type.name());
    json.addProperty("required", ann.required());
    JsonArray values = new JsonArray();
    Iterable<?> possibleValues = getPossibleValues(page);
    for (Object value : possibleValues) {
        JsonObject obj = new JsonObject();
        obj.addProperty("value", type.stringify(value));
        obj.addProperty("label", provider.present(value));
        values.add(obj);
    }
    json.add("values", values);
    return json;
}
Example 8
Project: enviroCar-app-master  File: UserStatisticDeserializer.java View source code
@Override
public UserStatistics deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final JsonArray statistics = json.getAsJsonObject().get(User.KEY_STATISTICS).getAsJsonArray();
    Map<String, Phenomenon> statisticMap = new HashMap<>();
    // Iterate through the array of phenomenons and its values.
    for (int i = 0; i < statistics.size(); i++) {
        // Create a new phenomenon holder.
        Phenomenon holder = new PhenomenonImpl();
        // Get the values of the phenomenon.
        JsonObject statisticObject = statistics.get(i).getAsJsonObject();
        holder.setMaxValue(statisticObject.get(User.KEY_STATISTICS_MAX).getAsDouble());
        holder.setMinValue(statisticObject.get(User.KEY_STATISTICS_MIN).getAsDouble());
        holder.setAvgValue(statisticObject.get(User.KEY_STATISTICS_AVG).getAsDouble());
        // Get the phenomenon name and unit.
        JsonObject phenomenonObject = statisticObject.get(User.KEY_STATISTICS_PHENOMENON).getAsJsonObject();
        holder.setPhenomenonName(phenomenonObject.get(User.KEY_STATISTICS_PHENOMENON_NAME).getAsString());
        holder.setPhenomenonUnit(phenomenonObject.get(User.KEY_STATISTICS_PHENOMENON_UNIT).getAsString());
        // Add the phenomenon to the map.
        statisticMap.put(holder.getPhenomenonName(), holder);
    }
    UserStatistics userStatistics = new UserStatisticsImpl();
    userStatistics.setStatistics(statisticMap);
    return userStatistics;
}
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: ViewEstimatePhotographController.java View source code
@RequestMapping(value = "/view", method = RequestMethod.GET)
public String viewMilestoneTemplate(@RequestParam final Long lineEstimateDetailsId, final Model model, final HttpServletRequest request) throws ApplicationException {
    final Long ledId = Long.valueOf(request.getParameter("lineEstimateDetailsId"));
    final List<EstimatePhotographs> photographsBefore = estimatePhotographService.getEstimatePhotographsByEstimatePhotographStageAndLineEstimateDetails(WorkProgress.BEFORE, ledId);
    final List<EstimatePhotographs> photographsAfter = estimatePhotographService.getEstimatePhotographsByEstimatePhotographStageAndLineEstimateDetails(WorkProgress.AFTER, ledId);
    final List<EstimatePhotographs> photographsOnProcess = estimatePhotographService.getEstimatePhotographsByEstimatePhotographStageAndLineEstimateDetails(WorkProgress.DURING, ledId);
    JsonObject photographStages = new JsonObject();
    JsonArray array = new JsonArray();
    for (EstimatePhotographs ep : photographsBefore) {
        JsonObject before = new JsonObject();
        before.addProperty("name", ep.getFileStore().getFileName());
        before.addProperty("type", "image/jpg");
        before.addProperty("file", "/egi/downloadfile?fileStoreId=" + ep.getFileStore().getFileStoreId() + "&moduleName=WMS");
        before.addProperty("key", ep.getFileStore().getId());
        array.add(before);
    }
    photographStages.add("before", array);
    array = new JsonArray();
    for (EstimatePhotographs ep : photographsAfter) {
        JsonObject after = new JsonObject();
        after.addProperty("name", ep.getFileStore().getFileName());
        after.addProperty("type", "image/jpg");
        after.addProperty("file", "/egi/downloadfile?fileStoreId=" + ep.getFileStore().getFileStoreId() + "&moduleName=WMS");
        after.addProperty("key", ep.getFileStore().getId());
        array.add(after);
    }
    photographStages.add("after", array);
    array = new JsonArray();
    for (EstimatePhotographs ep : photographsOnProcess) {
        JsonObject during = new JsonObject();
        during.addProperty("name", ep.getFileStore().getFileName());
        during.addProperty("type", "image/jpg");
        during.addProperty("file", "/egi/downloadfile?fileStoreId=" + ep.getFileStore().getFileStoreId() + "&moduleName=WMS");
        during.addProperty("key", ep.getFileStore().getId());
        array.add(during);
    }
    photographStages.add("during", array);
    final LineEstimateDetails lineEstimateDetails = lineEstimateDetailService.getById(ledId);
    final WorkOrder workOrder = letterOfAcceptanceService.getWorkOrderByEstimateNumber(lineEstimateDetails.getEstimateNumber());
    final AbstractEstimate abstractEstimate = estimateService.getAbstractEstimateByEstimateNumber(lineEstimateDetails.getEstimateNumber());
    model.addAttribute("abstractEstimate", abstractEstimate);
    model.addAttribute("workOrder", workOrder);
    model.addAttribute("lineEstimateDetails", lineEstimateDetails);
    model.addAttribute("photographStages", photographStages);
    return "estimatePhotographs-view";
}
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: FilteredChangesResource.java View source code
@Override
public void post(Representation entity) {
    try {
        final InputStream inStream;
        try {
            inStream = entity.getStream();
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
        final Reader body = new InputStreamReader(inStream);
        final JsonParser parser = new JsonParser();
        final JsonElement messageJson = parser.parse(body);
        final Set<ObjectId> tracked = new HashSet<ObjectId>();
        RepositoryFilter filter = new RepositoryFilter();
        ObjectId commitId = ObjectId.NULL;
        if (messageJson.isJsonObject()) {
            final JsonObject message = messageJson.getAsJsonObject();
            final JsonArray trackedArray;
            if (message.has("tracked") && message.get("tracked").isJsonArray()) {
                trackedArray = message.get("tracked").getAsJsonArray();
            } else {
                trackedArray = new JsonArray();
            }
            if (message.has("commitId") && message.get("commitId").isJsonPrimitive()) {
                commitId = ObjectId.valueOf(message.get("commitId").getAsJsonPrimitive().getAsString());
            } else {
                commitId = ObjectId.NULL;
            }
            for (final JsonElement e : trackedArray) {
                if (e.isJsonPrimitive()) {
                    tracked.add(ObjectId.valueOf(e.getAsJsonPrimitive().getAsString()));
                }
            }
            if (message.has("filter") && message.get("filter").isJsonArray()) {
                JsonArray filterArray = message.get("filter").getAsJsonArray();
                for (final JsonElement e : filterArray) {
                    if (e.isJsonObject()) {
                        JsonObject filterObject = e.getAsJsonObject();
                        String featureType = null;
                        String filterType = null;
                        String filterText = null;
                        if (filterObject.has("featurepath") && filterObject.get("featurepath").isJsonPrimitive()) {
                            featureType = filterObject.get("featurepath").getAsJsonPrimitive().getAsString();
                        }
                        if (filterObject.has("type") && filterObject.get("type").isJsonPrimitive()) {
                            filterType = filterObject.get("type").getAsJsonPrimitive().getAsString();
                        }
                        if (filterObject.has("filter") && filterObject.get("filter").isJsonPrimitive()) {
                            filterText = filterObject.get("filter").getAsJsonPrimitive().getAsString();
                        }
                        if (featureType != null && filterType != null && filterText != null) {
                            filter.addFilter(featureType, filterType, filterText);
                        }
                    }
                }
            }
        }
        final GeoGIG ggit = getGeogig(getRequest()).get();
        final Repository repository = ggit.getRepository();
        RevCommit commit = repository.getCommit(commitId);
        ObjectId parent = ObjectId.NULL;
        if (commit.getParentIds().size() > 0) {
            parent = commit.getParentIds().get(0);
        }
        Iterator<DiffEntry> changes = ggit.command(DiffOp.class).setNewVersion(commit.getId()).setOldVersion(parent).setReportTrees(true).call();
        FilteredDiffIterator filteredChanges = new FilteredDiffIterator(changes, repository, filter) {

            @Override
            protected boolean trackingObject(ObjectId objectId) {
                return tracked.contains(objectId);
            }

            @Override
            public boolean isAutoIngesting() {
                return false;
            }
        };
        getResponse().setEntity(new FilteredDiffIteratorRepresentation(new BinaryPackedChanges(repository), filteredChanges));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
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: EventMessageBundleGsonAdaptor.java View source code
@Override
public JsonElement serialize(EventMessageBundle src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    JsonArray events = new JsonArray();
    for (Event event : src.getEvents()) {
        try {
            events.add(EventSerializer.serialize(event, context));
        } catch (EventSerializationException e) {
            throw new JsonParseException(e);
        }
    }
    result.add(EVENTS_TAG, events);
    result.add(WAVELET_TAG, context.serialize(src.getWaveletData()));
    result.add(BLIPS_TAG, context.serialize(src.getBlipData()));
    result.add(THREADS_TAG, context.serialize(src.getThreads()));
    result.addProperty(ROBOT_ADDRESS_TAG, src.getRobotAddress());
    String proxyingFor = src.getProxyingFor();
    if (proxyingFor != null && !proxyingFor.isEmpty()) {
        result.addProperty(PROXYING_FOR_TAG, proxyingFor);
    }
    String rpcServerUrl = src.getRpcServerUrl();
    if (rpcServerUrl != null && !rpcServerUrl.isEmpty()) {
        result.addProperty(RPC_SERVER_URL_TAG, rpcServerUrl);
    }
    return result;
}
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: FieldDTO.java View source code
public ArrayList<HashSet<FieldDTO>> getMultipleCompound() {
    Gson gson = new Gson();
    ArrayList<HashSet<FieldDTO>> fields = new ArrayList<HashSet<FieldDTO>>();
    JsonArray array = value.getAsJsonArray();
    Iterator<JsonElement> iter = array.iterator();
    while (iter.hasNext()) {
        JsonObject elem = (JsonObject) iter.next();
        HashSet<FieldDTO> elemFields = new HashSet<FieldDTO>();
        fields.add(elemFields);
        Set<Map.Entry<String, JsonElement>> set = elem.entrySet();
        Iterator<Map.Entry<String, JsonElement>> setIter = set.iterator();
        while (setIter.hasNext()) {
            Map.Entry<String, JsonElement> entry = setIter.next();
            FieldDTO field = gson.fromJson(entry.getValue(), FieldDTO.class);
            elemFields.add(field);
        }
    }
    return fields;
}
Example 20
Project: wave-protocol-master  File: EventMessageBundleGsonAdaptor.java View source code
@Override
public JsonElement serialize(EventMessageBundle src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    JsonArray events = new JsonArray();
    for (Event event : src.getEvents()) {
        try {
            events.add(EventSerializer.serialize(event, context));
        } catch (EventSerializationException e) {
            throw new JsonParseException(e);
        }
    }
    result.add(EVENTS_TAG, events);
    result.add(WAVELET_TAG, context.serialize(src.getWaveletData()));
    result.add(BLIPS_TAG, context.serialize(src.getBlipData()));
    result.add(THREADS_TAG, context.serialize(src.getThreads()));
    result.addProperty(ROBOT_ADDRESS_TAG, src.getRobotAddress());
    String proxyingFor = src.getProxyingFor();
    if (proxyingFor != null && !proxyingFor.isEmpty()) {
        result.addProperty(PROXYING_FOR_TAG, proxyingFor);
    }
    String rpcServerUrl = src.getRpcServerUrl();
    if (rpcServerUrl != null && !rpcServerUrl.isEmpty()) {
        result.addProperty(RPC_SERVER_URL_TAG, rpcServerUrl);
    }
    return result;
}
Example 21
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 22
Project: incubator-wave-master  File: EventMessageBundleGsonAdaptor.java View source code
@Override
public JsonElement serialize(EventMessageBundle src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    JsonArray events = new JsonArray();
    for (Event event : src.getEvents()) {
        try {
            events.add(EventSerializer.serialize(event, context));
        } catch (EventSerializationException e) {
            throw new JsonParseException(e);
        }
    }
    result.add(EVENTS_TAG, events);
    result.add(WAVELET_TAG, context.serialize(src.getWaveletData()));
    result.add(BLIPS_TAG, context.serialize(src.getBlipData()));
    result.add(THREADS_TAG, context.serialize(src.getThreads()));
    result.addProperty(ROBOT_ADDRESS_TAG, src.getRobotAddress());
    String proxyingFor = src.getProxyingFor();
    if (proxyingFor != null && !proxyingFor.isEmpty()) {
        result.addProperty(PROXYING_FOR_TAG, proxyingFor);
    }
    String rpcServerUrl = src.getRpcServerUrl();
    if (rpcServerUrl != null && !rpcServerUrl.isEmpty()) {
        result.addProperty(RPC_SERVER_URL_TAG, rpcServerUrl);
    }
    return result;
}
Example 23
Project: newFunf-master  File: JsonUtils.java View source code
/**
	 * Sort all elements in Json objects, to ensure that they are identically serialized.
	 * @param el
	 * @return
	 */
public static JsonElement deepSort(JsonElement el) {
    if (el == null) {
        return null;
    } else if (el.isJsonArray()) {
        JsonArray sortedArray = new JsonArray();
        for (JsonElement subEl : (JsonArray) el) {
            sortedArray.add(deepSort(subEl));
        }
        return sortedArray;
    } else if (el.isJsonObject()) {
        List<Entry<String, JsonElement>> entrySet = new ArrayList<Entry<String, JsonElement>>(((JsonObject) el).entrySet());
        Collections.sort(entrySet, JSON_OBJECT_ENTRY_SET_COMPARATOR);
        JsonObject sortedObject = new JsonObject();
        for (Entry<String, JsonElement> entry : entrySet) {
            sortedObject.add(entry.getKey(), deepSort(entry.getValue()));
        }
        return sortedObject;
    } else {
        return el;
    }
}
Example 24
Project: platform-api-master  File: ServerDtoTest.java View source code
@Test
public void testListSimpleDtoDeserializer() throws Exception {
    final String fooString_1 = "Something 1";
    final int fooId_1 = 1;
    final String _default_1 = "test_default_keyword_1";
    final String fooString_2 = "Something 2";
    final int fooId_2 = 2;
    final String _default_2 = "test_default_keyword_2";
    JsonObject json1 = new JsonObject();
    json1.add("name", new JsonPrimitive(fooString_1));
    json1.add("id", new JsonPrimitive(fooId_1));
    json1.add("default", new JsonPrimitive(_default_1));
    JsonObject json2 = new JsonObject();
    json2.add("name", new JsonPrimitive(fooString_2));
    json2.add("id", new JsonPrimitive(fooId_2));
    json2.add("default", new JsonPrimitive(_default_2));
    JsonArray jsonArray = new JsonArray();
    jsonArray.add(json1);
    jsonArray.add(json2);
    org.eclipse.che.dto.shared.JsonArray<SimpleDto> listDtoFromJson = dtoFactory.createListDtoFromJson(jsonArray.toString(), SimpleDto.class);
    Assert.assertEquals(listDtoFromJson.get(0).getName(), fooString_1);
    Assert.assertEquals(listDtoFromJson.get(0).getId(), fooId_1);
    Assert.assertEquals(listDtoFromJson.get(0).getDefault(), _default_1);
    Assert.assertEquals(listDtoFromJson.get(1).getName(), fooString_2);
    Assert.assertEquals(listDtoFromJson.get(1).getId(), fooId_2);
    Assert.assertEquals(listDtoFromJson.get(1).getDefault(), _default_2);
}
Example 25
Project: edx-app-android-master  File: UserAPI.java View source code
@NonNull
public List<EnrolledCoursesResponse> getUserEnrolledCourses(@NonNull String username, String org, boolean tryCache) throws Exception {
    String json = null;
    final String cacheKey = getUserEnrolledCoursesURL(username);
    // try to get from cache if we should
    if (tryCache) {
        try {
            json = cache.get(cacheKey);
        } catch (IOException e) {
            logger.debug(e.toString());
        }
    }
    // if we don't have a json yet, get it from userService
    if (json == null) {
        Response<ResponseBody> response = userService.getUserEnrolledCourses(username, org).execute();
        if (response.isSuccessful()) {
            json = userService.getUserEnrolledCourses(username, org).execute().body().string();
            // cache result
            try {
                cache.put(cacheKey, json);
            } catch (IOException e) {
                logger.debug(e.toString());
            }
        } else {
            // can't be established, so throw an exception.
            if (tryCache)
                throw new HttpResponseStatusException(response.code());
            // Otherwise fall back to fetching from the cache
            try {
                json = cache.get(cacheKey);
            } catch (IOException e) {
                logger.debug(e.toString());
                throw new HttpResponseStatusException(response.code());
            }
            // If the cache is empty, then throw an exception.
            if (json == null)
                throw new HttpResponseStatusException(response.code());
        }
    }
    // We aren't use TypeToken here because it throws NoClassDefFoundError
    final JsonArray ary = gson.fromJson(json, JsonArray.class);
    final List<EnrolledCoursesResponse> ret = new ArrayList<>(ary.size());
    for (int cnt = 0; cnt < ary.size(); ++cnt) {
        ret.add(gson.fromJson(ary.get(cnt), EnrolledCoursesResponse.class));
    }
    return ret;
}