Java Code Examples for com.google.gson.JsonObject

The following are top voted examples for showing how to use com.google.gson.JsonObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: fingerblox   File: ImageDisplayActivity.java   View source code 8 votes vote down vote up
public String keypointsToJSON(MatOfKeyPoint kps){
    Gson gson = new Gson();

    JsonArray jsonArr = new JsonArray();

    KeyPoint[] kpsArray = kps.toArray();
    for(KeyPoint kp : kpsArray){
        JsonObject obj = new JsonObject();

        obj.addProperty("class_id", kp.class_id);
        obj.addProperty("x", kp.pt.x);
        obj.addProperty("y", kp.pt.y);
        obj.addProperty("size", kp.size);
        obj.addProperty("angle", kp.angle);
        obj.addProperty("octave", kp.octave);
        obj.addProperty("response", kp.response);

        jsonArr.add(obj);
    }

    return gson.toJson(jsonArr);
}
 
Example 2
Project: filestack-java   File: Client.java   View source code 7 votes vote down vote up
/**
 * Gets contents of a user's cloud "drive". If the user has not authorized for the provider, the
 * response will contain an OAuth URL that should be opened in a browser.
 *
 * @param providerName one of the static CLOUD constants in this class
 * @param next         pagination token returned in previous response
 *
 * @throws HttpException on error response from backend
 * @throws IOException           on network failure
 */
@SuppressWarnings("ConstantConditions")
public CloudResponse getCloudItems(String providerName, String path, String next)
    throws IOException {

  JsonObject params = makeCloudParams(providerName, path, next);
  Response<JsonObject> response = Networking.getCloudService().list(params).execute();
  Util.checkResponseAndThrow(response);
  JsonObject base = response.body();

  if (base.has("token")) {
    sessionToken = base.get("token").getAsString();
  }

  JsonElement provider = base.get(providerName);
  Gson gson = new Gson();
  return gson.fromJson(provider, CloudResponse.class);
}
 
Example 3
Project: BaseClient   File: AnimationMetadataSectionSerializer.java   View source code 6 votes vote down vote up
private AnimationFrame parseAnimationFrame(int p_110492_1_, JsonElement p_110492_2_)
{
    if (p_110492_2_.isJsonPrimitive())
    {
        return new AnimationFrame(JsonUtils.getInt(p_110492_2_, "frames[" + p_110492_1_ + "]"));
    }
    else if (p_110492_2_.isJsonObject())
    {
        JsonObject jsonobject = JsonUtils.getJsonObject(p_110492_2_, "frames[" + p_110492_1_ + "]");
        int i = JsonUtils.getInt(jsonobject, "time", -1);

        if (jsonobject.has("time"))
        {
            Validate.inclusiveBetween(1L, 2147483647L, (long)i, "Invalid frame time");
        }

        int j = JsonUtils.getInt(jsonobject, "index");
        Validate.inclusiveBetween(0L, 2147483647L, (long)j, "Invalid frame index");
        return new AnimationFrame(j, i);
    }
    else
    {
        return null;
    }
}
 
Example 4
Project: gw4e.project   File: GW4EProjectTestCase.java   View source code 6 votes vote down vote up
private void assertFileInCache (File file,String key) throws IOException {
	 InputStream in = new FileInputStream(file);
	 try {
		Reader reader = new InputStreamReader(in);
		String text = CharStreams.toString(reader);
		JsonParser jp = new JsonParser();
		JsonElement je = jp.parse(text);
		JsonObject jsonCache = je.getAsJsonObject();
		JsonElement elt = jsonCache.get(key);
		JsonObject generatedObj = elt.getAsJsonObject();
		boolean generated = generatedObj.get("generated").getAsBoolean();
		assertTrue("Test not generated", generated);
	} finally {
		if (in!=null) in.close();
	}
}
 
Example 5
Project: raven   File: Notification.java   View source code 6 votes vote down vote up
public JsonElement toJSON() {
    JsonObject json = new JsonObject();
    if (null != alert) {
        if(alert instanceof JsonObject) {
            json.add(PlatformNotification.ALERT, (JsonObject) alert);
        } else if (alert instanceof IosAlert) {
            json.add(PlatformNotification.ALERT, ((IosAlert) alert).toJSON());
        } else {
            json.add(PlatformNotification.ALERT, new JsonPrimitive(alert.toString()));
        }
    }
    if (null != notifications) {
        for (PlatformNotification pn : notifications) {
            if (this.alert != null && pn.getAlert() == null) {
                pn.setAlert(this.alert);
            }
            
            Preconditions.checkArgument(! (null == pn.getAlert()),
                    "For any platform notification, alert field is needed. It can be empty string.");

            json.add(pn.getPlatform(), pn.toJSON());
        }
    }
    return json;
}
 
Example 6
Project: spring-data-hana   File: HanaDBTemplate.java   View source code 6 votes vote down vote up
public HanaDBTemplate() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Point.class, (JsonSerializer<Point>) (Point src, Type type, JsonSerializationContext context) -> {
        JsonObject obj = new JsonObject();
        // serialize it all to strings for reasons..
        obj.addProperty("ZEITREIHE", src.getTimeseries());
        obj.addProperty("TIME", String.valueOf(src.getTimestamp()));
        obj.addProperty("VALUE", src.getValue().toString());
        return obj;
    });
    gson = builder.create();

    OkHttpClient.Builder okHBuilder = new OkHttpClient.Builder();
    okHBuilder.readTimeout(30, TimeUnit.SECONDS);
    okHBuilder.writeTimeout(30, TimeUnit.SECONDS);
    okHttpClient = okHBuilder.build();
}
 
Example 7
Project: yyox   File: PackagePresenter.java   View source code 6 votes vote down vote up
/**
 * 上传包裹截图
 *
 * @param mImage1
 * @param mImage2
 * @param mImage3
 */
public void putPackageImage(String mImage1, String mImage2, String mImage3) {

    mModel.putPackageImage(mImage1, mImage2, mImage3)
            .subscribeOn(Schedulers.io())
            .retryWhen(new RetryWithDelay(3, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
            .subscribeOn(AndroidSchedulers.mainThread())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(RxUtils.<BaseJson<JsonObject>>bindToLifecycle(mRootView))//使用RXlifecycle,使subscription和activity一起销毁
            .subscribe(new ErrorHandleSubscriber<BaseJson<JsonObject>>(mErrorHandler) {

                @Override
                public void onNext(BaseJson<JsonObject> jsonObjectBaseJson) {
                    if (jsonObjectBaseJson.getStatus() == 0) {
                        mRootView.packageImage(jsonObjectBaseJson.getStatus());
                    } else {
                        mRootView.showMessage(jsonObjectBaseJson.getMsgs());
                        mRootView.packageImage(jsonObjectBaseJson.getStatus());
                    }
                }
            });
}
 
Example 8
Project: restheart-java-client   File: RestHeartClientApi.java   View source code 6 votes vote down vote up
private RestHeartClientResponse extractFromResponse(final CloseableHttpResponse httpResponse) {
    RestHeartClientResponse response = null;
    JsonObject responseObj = null;
    if (httpResponse != null) {
        StatusLine statusLine = httpResponse.getStatusLine();
        Header[] allHeaders = httpResponse.getAllHeaders();
        HttpEntity resEntity = httpResponse.getEntity();
        if (resEntity != null) {
            try {
                String responseStr = IOUtils.toString(resEntity.getContent(), "UTF-8");
                if (responseStr != null && !responseStr.isEmpty()) {
                    JsonParser parser = new JsonParser();
                    responseObj = parser.parse(responseStr).getAsJsonObject();
                }
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, "Was unable to extract response body", e);
            }
        }

        response = new RestHeartClientResponse(statusLine, allHeaders, responseObj);
    }
    return response;
}
 
Example 9
Project: ja-micro   File: RpcReadExceptionTest.java   View source code 6 votes vote down vote up
public void testBodyReading(String first, String second) throws IOException {
    ServletInputStream x = (ServletInputStream) new RpcHandlerTest_InputStream(second);
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Map<String, Set<String>> headers = new TreeMap<>();
    when(request.getHeaderNames())
            .thenReturn(
                    new RpcReadExceptionTest.RpcHandlerTest_IteratorEnumeration<>(headers.keySet().iterator())
            );

    when(request.getInputStream()).thenReturn(x);
    when(request.getRequestURL())
            .thenReturn(new StringBuffer("http://fizz.buzz"));

    RpcReadException rpcReadException = new RpcReadException(first.getBytes(), x, "i am a message");
    String json = rpcReadException.toJson(request);

    try {
        JsonElement root = new JsonParser().parse(json);
        JsonObject jsob = root.getAsJsonObject();
        JsonElement b = jsob.get("request_body");
        Assert.assertNotNull(b);
        Assert.assertEquals(first+second, this.decode(b.getAsString()));
    } catch (Exception ex) {
        Assert.fail(ex.toString());
    }
}
 
Example 10
Project: backend.ai-client-java   File: ExecutionResult.java   View source code 6 votes vote down vote up
public ExecutionResult(JsonObject jsonResult) {
    this.jsonResult = jsonResult;
    try {
        JsonObject result = jsonResult.get("result").getAsJsonObject();
        JsonArray console = result.get("console").getAsJsonArray();
        this.status = RunStatus.get(result.get("status").getAsString());
        for (int i = 0; i < console.size(); i++) {
            JsonArray a = console.get(i).getAsJsonArray();
            String type = a.get(0).getAsString();
            if(type.equals("stdout")) {
                this.stdout = a.get(1).getAsString();
            } else if (type.equals("stderr")) {
                this.stderr = a.get(1).getAsString();
            }
        }
    } catch (NullPointerException e) {
    }
}
 
Example 11
Project: graphql_java_gen   File: GeneratedMinimal.java   View source code 6 votes vote down vote up
public QueryRoot(JsonObject fields) throws SchemaViolationError {
    for (Map.Entry<String, JsonElement> field : fields.entrySet()) {
        String key = field.getKey();
        String fieldName = getFieldName(key);
        switch (fieldName) {
            case "version": {
                String optional1 = null;
                if (!field.getValue().isJsonNull()) {
                    optional1 = jsonAsString(field.getValue(), key);
                }

                responseData.put(key, optional1);

                break;
            }

            case "__typename": {
                responseData.put(key, jsonAsString(field.getValue(), key));
                break;
            }
            default: {
                throw new SchemaViolationError(this, key, field.getValue());
            }
        }
    }
}
 
Example 12
Project: TLIVideoConferencingv2   File: UserSession.java   View source code 6 votes vote down vote up
public void receiveVideoFrom(UserSession sender, String sdpOffer) throws IOException {
  log.info("USER {}: connecting with {} in room {}", this.name, sender.getName(), this.roomName);

  log.trace("USER {}: SdpOffer for {} is {}", this.name, sender.getName(), sdpOffer);

  final String ipSdpAnswer = this.getEndpointForUser(sender).processOffer(sdpOffer);
  final JsonObject scParams = new JsonObject();
  scParams.addProperty("id", "receiveVideoAnswer");
  scParams.addProperty("name", sender.getName());
  scParams.addProperty("sdpAnswer", ipSdpAnswer);

  log.trace("USER {}: SdpAnswer for {} is {}", this.name, sender.getName(), ipSdpAnswer);
  this.sendMessage(scParams);
  log.debug("gather candidates");
  this.getEndpointForUser(sender).gatherCandidates();
}
 
Example 13
Project: iotgateway   File: JsonTuples.java   View source code 6 votes vote down vote up
/**
     * Create a JsonObject wrapping a raw {@code Pair<Long msec,T reading>>} sample.
     * @param <T> Tuple type
     * @param sample the raw sample
     * @param id the sensor's Id
     * @return the wrapped sample
     */
    public static <T> JsonObject wrap(Pair<Long,T> sample, String id) {
        JsonObject jo = new JsonObject();
        jo.addProperty(KEY_ID, id);
        jo.addProperty(KEY_TS, sample.getFirst());
        T value = sample.getSecond();
        if (value instanceof Number)
            jo.addProperty(KEY_READING, (Number)sample.getSecond());
        else if (value instanceof String)
            jo.addProperty(KEY_READING, (String)sample.getSecond());
        else if (value instanceof Boolean)
            jo.addProperty(KEY_READING, (Boolean)sample.getSecond());
//        else if (value instanceof array) {
//            // TODO cvt to JsonArray
//        }
//        else if (value instanceof Object) {
//            // TODO cvt to JsonObject
//        }
        else {
            Class<?> clazz = value != null ? value.getClass() : Object.class;
            throw new IllegalArgumentException("Unhandled value type: "+ clazz);
        }
        return jo;
    }
 
Example 14
Project: raven   File: Options.java   View source code 6 votes vote down vote up
@Override
public JsonElement toJSON() {
    JsonObject json = new JsonObject();
    if (sendno > 0) {
        json.add(SENDNO, new JsonPrimitive(sendno));
    }
    if (overrideMsgId > 0) {
        json.add(OVERRIDE_MSG_ID, new JsonPrimitive(overrideMsgId));
    }
    if (timeToLive >= 0) {
        json.add(TIME_TO_LIVE, new JsonPrimitive(timeToLive));
    }
    
    json.add(APNS_PRODUCTION, new JsonPrimitive(apnsProduction));
    
    if (bigPushDuration > 0) {
    	json.add(BIG_PUSH_DURATION,  new JsonPrimitive(bigPushDuration));
    }
    
    return json;
}
 
Example 15
Project: SurvivalAPI   File: EntityDropModule.java   View source code 6 votes vote down vote up
@Override
public Map<String, Object> buildFromJson(Map<String, JsonElement> configuration) throws Exception
{
    if (configuration.containsKey("drops"))
    {
        JsonArray dropsJson = configuration.get("drops").getAsJsonArray();

        for (int i = 0; i < dropsJson.size(); i++)
        {
            JsonObject dropJson = dropsJson.get(i).getAsJsonObject();

            EntityType entityType = EntityType.valueOf(dropJson.get("entity").getAsString().toUpperCase());
            JsonArray stacksJson = dropJson.get("stacks").getAsJsonArray();
            ItemStack[] stacks = new ItemStack[stacksJson.size()];

            for (int j = 0; j < stacksJson.size(); j++)
                stacks[j] = ItemUtils.strToStack(stacksJson.get(i).getAsString());

            this.addCustomDrops(entityType, stacks);
        }
    }

    return this.build();
}
 
Example 16
Project: DiscordDevRant   File: DevRant.java   View source code 6 votes vote down vote up
/**
 * Log in to devRant.
 *
 * @param username The username.
 * @param password The password.
 * @throws AuthenticationException If the login data is invalid.
 */
public void login(String username, char[] password) throws AuthenticationException {
    if (auth != null)
        throw new IllegalStateException("A user is already logged in.");

    JsonObject json = post(API_AUTH_TOKEN,
            new BasicNameValuePair("username", username),
            new BasicNameValuePair("password", String.valueOf(password))
    );

    // Clear the password.
    for (int i = 0; i < password.length; i++)
        password[i] = 0;

    if (!Util.jsonSuccess(json))
        throw new AuthenticationException();

    auth = Auth.fromJson(json);
}
 
Example 17
Project: logviewer   File: GistCreator.java   View source code 6 votes vote down vote up
/**
 * Call the API to create gist and return the http url if any
 */
private String callGistApi(String gistJson, GistListener listener) {
    try {
        CloseableHttpClient httpclient = createDefault();
        HttpPost httpPost = new HttpPost(GIST_API);
        httpPost.setHeader("Accept", "application/vnd.github.v3+json");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(gistJson, ContentType.APPLICATION_JSON));

        CloseableHttpResponse response = httpclient.execute(httpPost);

        HttpEntity responseEntity = response.getEntity();
        JsonObject result = (JsonObject) new JsonParser().parse(EntityUtils.toString(responseEntity));

        EntityUtils.consume(responseEntity);
        response.close();

        httpclient.close();
        return result.getAsJsonPrimitive("html_url").getAsString();
    } catch (Exception ex) {
    }
    return null;
}
 
Example 18
Project: CTUConference   File: FriendshipMessageReceiver.java   View source code 6 votes vote down vote up
@Override
 public void handleMessage(String messageType, JsonObject jsonMessageData, WebSocketSession session) throws IOException, Exception {
     switch(messageType) {
case "friendship.suggest":
	suggestFriendships(jsonMessageData, session);
	break;
case "friendship.request":
	requestFriendship(jsonMessageData, session);
	break;
case "friendship.accept":
             acceptFriendship(jsonMessageData, session);
             break;
case "friendship.reject":
	rejectFriendship(jsonMessageData, session);
	break;
case "friendship.leave":
	leaveFriendship(jsonMessageData, session);
	break;
     }
 }
 
Example 19
Project: TeamNote   File: CooperateController.java   View source code 6 votes vote down vote up
@RequestMapping("/getGroupChat")
@ResponseBody
public String getGroupChat(@RequestParam("notebookId") int notebookId, @RequestParam("lastChat") int lastChat) {
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String username = userDetails.getUsername();
    UserInfo userInfo = userBasicService.getUserInfoByUsername(username);
    int userId = userInfo.getUserId();

    int length = cooperateService.getGroupChat(notebookId).size();
    if(lastChat == -1) lastChat = length - 1;
    String resultList = cooperateService.getGroupChatChunk(notebookId, lastChat);
    lastChat = lastChat >= 10 ? lastChat - 10 : -2;
    JsonObject json = new JsonObject();
    json.addProperty("result", resultList);
    json.addProperty("currentUser", userId);
    json.addProperty("lastChat", lastChat);
    return json.toString();
}
 
Example 20
Project: just-ask   File: EnrollServlet.java   View source code 6 votes vote down vote up
private StringEntity getJsonAsEntity(String host, int port) throws UnsupportedEncodingException {
    try {
        InputStream isr = Thread.currentThread().getContextClassLoader().getResourceAsStream("ondemand.json");
        String string = IOUtils.toString(new InputStreamReader(isr));
        JsonObject ondemand = new JsonParser().parse(string).getAsJsonObject();
        int maxSession =ConfigReader.getInstance().getMaxSession();
        JsonArray capsArray = ondemand.get("capabilities").getAsJsonArray();
        for (int i=0; i < capsArray.size(); i++) {
            capsArray.get(i).getAsJsonObject().addProperty("maxInstances", maxSession);
        }
        JsonObject configuration = ondemand.get("configuration").getAsJsonObject();
        configuration.addProperty("maxSession", maxSession);
        configuration.addProperty("hub", String.format("http://%s:%d", host, port));
        string = ondemand.toString();
        return new StringEntity(string);
    } catch (IOException e) {
        throw new GridException(e.getMessage(), e);
    }
}
 
Example 21
Project: google-actions   File: Oauth2Error.java   View source code 5 votes vote down vote up
@Override
public JsonElement serialize(Oauth2Error arg0, Type arg1, JsonSerializationContext arg2) {
	final JsonObject jsonObject = new JsonObject();
	jsonObject.addProperty("error", arg0.getError());
	jsonObject.addProperty("error_desc", arg0.getDesc());
	return jsonObject;
}
 
Example 22
Project: BaseClient   File: BlockFaceUV.java   View source code 5 votes vote down vote up
protected int parseRotation(JsonObject p_178291_1_)
{
    int i = JsonUtils.getInt(p_178291_1_, "rotation", 0);

    if (i >= 0 && i % 90 == 0 && i / 90 <= 3)
    {
        return i;
    }
    else
    {
        throw new JsonParseException("Invalid rotation " + i + " found, only 0/90/180/270 allowed");
    }
}
 
Example 23
Project: li-android-sdk-core   File: LiBaseResponse.java   View source code 5 votes vote down vote up
private List<LiBaseModel> singleEntityOrListFromJson(final JsonElement node, final String objectNamePlural,
                                                     final String objectName, final Class<? extends LiBaseModel> baseModelClass, final Gson gson) throws LiRestResponseException {
    if (node != null && node.getAsJsonObject().has(DATA)) {
        JsonObject response = node.getAsJsonObject().get(DATA).getAsJsonObject();
        if (!response.has(TYPE)) {
            throw LiRestResponseException.jsonSerializationError("Required data type not found in response");
        }

        String type = response.get(TYPE).getAsString();
        if (!type.equalsIgnoreCase(objectName) && !type.equalsIgnoreCase(objectNamePlural)) {
            throw LiRestResponseException.illegalArgumentError("Required object type not found in response");
        }

        if (type.equalsIgnoreCase(objectNamePlural) && response.get(ITEMS).isJsonArray()) {
            JsonArray jsonArray = response.get(ITEMS).getAsJsonArray();
            List<LiBaseModel> elementList = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JsonObject element = jsonArray.get(i).getAsJsonObject();
                try {
                    elementList.add(gson.fromJson(element, baseModelClass));
                } catch (IllegalStateException | JsonSyntaxException exception) {
                    throw LiRestResponseException.jsonSerializationError("Bad json response:" + exception.getMessage());
                }
            }
            return elementList;
        } else if (type.equalsIgnoreCase(objectName) && response.get(ITEM).isJsonObject()) {
            final List<LiBaseModel> objects = new ArrayList<>();
            objects.add(gson.fromJson(response.get(ITEM).getAsJsonObject(), baseModelClass));
            return objects;
        } else {
            throw LiRestResponseException.jsonSerializationError("Unable to parse " + objectName + " or " +
                    objectNamePlural + " from json:" + node);
        }
    } else {
        throw LiRestResponseException.jsonSerializationError("Server Error. Please check logs");
    }
}
 
Example 24
Project: civify-app   File: AchievementAdapterImplTest.java   View source code 5 votes vote down vote up
@Test
public void testInvalidGetAchievements() {
    JsonObject body = new JsonObject();
    body.addProperty("message", "Doesn’t exists record");
    MockResponse mockResponse = new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_NOT_FOUND)
            .setBody(body.toString());
    mMockWebServer.enqueue(mockResponse);
    ListAchievementsSimpleCallback mockCallback = mock(ListAchievementsSimpleCallback.class);

    mAchievementAdapter.getAchievements(mockCallback);

    verify(mockCallback, timeout(1000)).onFailure();
}
 
Example 25
Project: easyprefs   File: MorePrefs.java   View source code 5 votes vote down vote up
@Override
public String put(JsonObject jsonObject) {
    if (jsonObject == null) {
        return null;
    }
    return jsonObject.toString();
}
 
Example 26
Project: filestack-java   File: FileLink.java   View source code 5 votes vote down vote up
/**
 * Determines if an image FileLink is "safe for work" using the Google Vision API.
 *
 * @throws HttpException on error response from backend
 * @throws IOException           on network failure
 *
 * @see <a href="https://www.filestack.com/docs/tagging"></a>
 */
public boolean imageSfw() throws IOException {
  if (!config.hasSecurity()) {
    throw new IllegalStateException("Security must be set in order to tag an image");
  }

  ImageTransform transform = new ImageTransform(config, handle, false);
  transform.addTask(new ImageTransformTask("sfw"));
  JsonObject json = transform.getContentJson();

  return json.get("sfw").getAsBoolean();
}
 
Example 27
Project: buckaroo   File: DependencyGroupSerializer.java   View source code 5 votes vote down vote up
@Override
public JsonElement serialize(final DependencyGroup dependencyGroup, final Type type, final JsonSerializationContext context) {

    Preconditions.checkNotNull(dependencyGroup);
    Preconditions.checkNotNull(type);
    Preconditions.checkNotNull(context);

    final JsonObject jsonObject = new JsonObject();

    for (final Dependency i : dependencyGroup.entries()) {
        jsonObject.addProperty(i.project.encode(), i.requirement.encode());
    }

    return jsonObject;
}
 
Example 28
Project: ULCRS   File: DataParse.java   View source code 5 votes vote down vote up
/**
 * Parse courses. This depends on shifts.
 *
 * @param input - JsonObject response from ULC to parse into ULCRS data.
 * @param shifts - HashMap of shifts for easy lookup for already-parsed shifts.
 * @return HashMap - return HashMap of id:course for courses parsed from input.
 */
private static HashMap<Integer, Course> parseCourses(JsonObject input, HashMap<Integer, Shift> shifts) {
    // Get course JsonArray from JsonObject
    JsonArray coursesJson = input.get(COURSES_KEY).getAsJsonArray();
    JsonArray courseRequirementsJson = input.get(COURSE_REQUIREMENTS_KEY).getAsJsonArray();

    List<ULCCourse> ulcCourses = new Gson().fromJson(coursesJson, new TypeToken<List<ULCCourse>>() {
    }.getType());
    List<ULCCourseRequirements> ulcCourseRequirementsList = new Gson().fromJson(courseRequirementsJson, new TypeToken<List<ULCCourseRequirements>>() {
    }.getType());

    // Map course id to ULCCourseRequirements object for that course
    Map<Integer, ULCCourseRequirements> courseIdToULCCourseRequirements = ulcCourseRequirementsList.stream()
            .collect(Collectors.toMap(ULCCourseRequirements::getCourseId, item -> item));

    // Transform json courses into Course objects
    HashMap<Integer, Course> courses = new HashMap<>();
    ulcCourses.forEach(ulcCourse -> {
        ULCCourseRequirements ulcCourseRequirement = courseIdToULCCourseRequirements.get(ulcCourse.getId());
        if (ulcCourseRequirement != null) {
            CourseRequirements courseRequirement = ulcCourseRequirement.toCourseRequirements(shifts);
            Course course = ulcCourse.toCourse(courseRequirement);
            courses.put(course.getId(), course);
        }
    });

    return courses;
}
 
Example 29
Project: cyp2sql   File: CypherTranslator.java   View source code 5 votes vote down vote up
/**
 * Takes token list of JSON based properties string, and converts this to an actual JSON object.
 *
 * @param propsString Token list in form similar to ["{", "key", ":", "value", "}"]
 * @return JSONObject matching the propsString argument.
 */
private static JsonObject getJSONProps(List<String> propsString) {
    StringBuilder json = new StringBuilder();
    json.append("{");

    boolean listSyntax = propsString.contains("[");

    int i = 0;

    for (String a : propsString) {
        if (a.equals(",")) {
            continue;
        } else if (a.equals("[")) {
            json.append("[");
            continue;
        } else if (a.equals("]")) {
            json.setLength(json.length() - 2);
            json.append("]").append(", ");
        } else if (i % 3 == 0) {
            json.append("\"").append(a).append("\"");
        } else if (i % 3 == 1) {
            json.append(":");
        } else if (i % 3 == 2) {
            json.append(a).append(", ");
            if (listSyntax) continue;
        }
        i++;
    }

    // remove trailing comma
    json.setLength(json.length() - 2);
    json.append("}");
    return parser.parse(json.toString()).getAsJsonObject();
}
 
Example 30
Project: TextDisplayer   File: Message.java   View source code 5 votes vote down vote up
public Message(JsonObject object) {
    this.name = object.has("name") ? object.get("name").getAsString() : MessageHelper.getRandomString(20);
    this.message = object.has("message") && !object.get("message").getAsString().isEmpty() ? object.get("message").getAsString() : "unknown";
    this.isChroma = object.has("usechroma") && object.get("usechroma").getAsBoolean();
    this.useShadow = object.has("useshadow") && object.get("useshadow").getAsBoolean();
    this.a = object.has("a") && object.get("a").getAsBoolean();
    this.b = !object.has("b") || object.get("b").getAsBoolean();
    this.c = !object.has("c") || object.get("c").getAsBoolean();
    this.scale = object.has("scale") ? MessageHelper.cap(object.get("scale").getAsFloat(), 1, 2) : 1;
    this.x = object.has("x") ? object.get("x").getAsInt() : 0;
    this.y = object.has("y") ? object.get("y").getAsInt() : 0;

    this.fileLocation = TextDisplayerMod.getInstance().getLoader().getMainDir().getPath() + "\\" + formatName(this.name).toLowerCase() + ".info";
}
 
Example 31
Project: gcp   File: Spark8Organized.java   View source code 5 votes vote down vote up
private static PairFunction<Tuple2<String, ExampleXML>, Object, JsonObject> prepToBq() {
  return tuple -> {
    JsonObject json = new JsonObject();
    json.addProperty("property1", tuple._2().getProperty1());
    json.addProperty("insertId", tuple._1());
    return new Tuple2<>(null, json);
  };
}
 
Example 32
Project: pnc-repressurized   File: AmadronOfferSettings.java   View source code 5 votes vote down vote up
@Override
protected void readFromJson(JsonObject json) {
    maxTradesPerPlayer = json.get("maxTradesPerPlayer").getAsInt();
    notifyOfTradeAddition = json.get("notifyOfTradeAddition").getAsBoolean();
    notifyOfTradeRemoval = json.get("notifyOfTradeRemoval").getAsBoolean();
    notifyOfDealMade = json.get("notifyOfDealMade").getAsBoolean();
}
 
Example 33
Project: ultimate-geojson   File: FeatureDeserializer.java   View source code 5 votes vote down vote up
@Override
public FeatureDto deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {

	FeatureDto dto = new FeatureDto();

	JsonObject asJsonObject = json.getAsJsonObject();
	JsonElement geometryElement = asJsonObject.get("geometry");
	if (geometryElement != null) {
		String typeOfGeometry = geometryElement.getAsJsonObject().get("type").getAsString();
		GeoJSONObjectTypeEnum typeEnum = GeoJSONObjectTypeEnum.valueOf(typeOfGeometry);
		GeometryDto geometryDto = context.deserialize(geometryElement, typeEnum.getDtoClass());
		dto.setGeometry(geometryDto);

	}

	JsonElement propertiesJsonElement = asJsonObject.get("properties");
	if (propertiesJsonElement != null) {
		dto.setProperties(propertiesJsonElement.toString());
	}

	JsonElement idJsonElement = asJsonObject.get("id");
	if (idJsonElement != null) {
		dto.setId(idJsonElement.getAsString());
	}

	dto.setBbox(BoundingBoxParser.parseBbox(asJsonObject, context));

	return dto;
}
 
Example 34
Project: bStats-Metrics   File: Metrics.java   View source code 5 votes vote down vote up
@Override
public JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, Map<String, Integer>> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    boolean reallyAllSkipped = true;
    for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
        JsonObject value = new JsonObject();
        boolean allSkipped = true;
        for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
            value.addProperty(valueEntry.getKey(), valueEntry.getValue());
            allSkipped = false;
        }
        if (!allSkipped) {
            reallyAllSkipped = false;
            values.add(entryValues.getKey(), value);
        }
    }
    if (reallyAllSkipped) {
        // Null = skip the chart
        return null;
    }
    data.add("values", values);
    return data;
}
 
Example 35
Project: BaseClient   File: ItemTransformVec3f.java   View source code 5 votes vote down vote up
private Vector3f parseVector3f(JsonObject jsonObject, String key, Vector3f defaultValue)
{
    if (!jsonObject.has(key))
    {
        return defaultValue;
    }
    else
    {
        JsonArray jsonarray = JsonUtils.getJsonArray(jsonObject, key);

        if (jsonarray.size() != 3)
        {
            throw new JsonParseException("Expected 3 " + key + " values, found: " + jsonarray.size());
        }
        else
        {
            float[] afloat = new float[3];

            for (int i = 0; i < afloat.length; ++i)
            {
                afloat[i] = JsonUtils.getFloat(jsonarray.get(i), key + "[" + i + "]");
            }

            return new Vector3f(afloat[0], afloat[1], afloat[2]);
        }
    }
}
 
Example 36
Project: civify-app   File: EventAdapterImplTest.java   View source code 5 votes vote down vote up
@Test
public void testInvalidGetAchievement() {
    JsonObject body = new JsonObject();
    body.addProperty("message", "Doesn’t exists record");
    MockResponse mockResponse = new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_NOT_FOUND)
            .setBody(body.toString());
    mMockWebServer.enqueue(mockResponse);
    EventSimpleCallback mockCallback = mock(EventSimpleCallback.class);

    mEventAdapter.getEvent(mEvent.getToken(), mockCallback);

    verify(mockCallback, timeout(1000)).onFailure();
}
 
Example 37
Project: skywalking-mock-collector   File: ValidateDataSerializer.java   View source code 5 votes vote down vote up
@Override
public JsonElement serialize(ValidateData src, Type typeOfSrc, JsonSerializationContext context) {
    Gson gson = new GsonBuilder().registerTypeAdapter(RegistryItem.class, new RegistryItemSerializer())
        .registerTypeAdapter(SegmentItems.class, new SegmentItemsSerializer()).create();

    JsonObject jsonObject = new JsonObject();
    jsonObject.add("registryItems", gson.toJsonTree(src.getRegistryItem()));
    jsonObject.add("segmentItems", gson.toJsonTree(src.getSegmentItem()));
    return jsonObject;
}
 
Example 38
Project: BaseClient   File: BlockFaceUV.java   View source code 5 votes vote down vote up
private float[] parseUV(JsonObject p_178292_1_)
{
    if (!p_178292_1_.has("uv"))
    {
        return null;
    }
    else
    {
        JsonArray jsonarray = JsonUtils.getJsonArray(p_178292_1_, "uv");

        if (jsonarray.size() != 4)
        {
            throw new JsonParseException("Expected 4 uv values, found: " + jsonarray.size());
        }
        else
        {
            float[] afloat = new float[4];

            for (int i = 0; i < afloat.length; ++i)
            {
                afloat[i] = JsonUtils.getFloat(jsonarray.get(i), "uv[" + i + "]");
            }

            return afloat;
        }
    }
}
 
Example 39
Project: Phoenix-for-VK   File: AttachmentsEntryDtoAdapter.java   View source code 5 votes vote down vote up
private VKApiAttachment parse(String type, JsonObject root, JsonDeserializationContext context){
    JsonElement o = root.get(type);

    //{"type":"photos_list","photos_list":["406536042_456239026"]}

    if (VkApiAttachments.TYPE_PHOTO.equals(type)) {
        return context.deserialize(o, VKApiPhoto.class);
    } else if (VkApiAttachments.TYPE_VIDEO.equals(type)) {
        return context.deserialize(o, VKApiVideo.class);
    } else if (VkApiAttachments.TYPE_AUDIO.equals(type)) {
        return context.deserialize(o, VKApiAudio.class);
    } else if (VkApiAttachments.TYPE_DOC.equals(type)) {
        return context.deserialize(o, VkApiDoc.class);
    } else if (VkApiAttachments.TYPE_POST.equals(type)) {
        return context.deserialize(o, VKApiPost.class);
        //} else if (VkApiAttachments.TYPE_POSTED_PHOTO.equals(type)) {
        //    return context.deserialize(o, VKApiPostedPhoto.class);
    } else if (VkApiAttachments.TYPE_LINK.equals(type)) {
        return context.deserialize(o, VKApiLink.class);
        //} else if (VkApiAttachments.TYPE_NOTE.equals(type)) {
        //    return context.deserialize(o, VKApiNote.class);
        //} else if (VkApiAttachments.TYPE_APP.equals(type)) {
        //    return context.deserialize(o, VKApiApplicationContent.class);
    } else if (VkApiAttachments.TYPE_POLL.equals(type)) {
        return context.deserialize(o, VKApiPoll.class);
    } else if (VkApiAttachments.TYPE_WIKI_PAGE.equals(type)) {
        return context.deserialize(o, VKApiWikiPage.class);
    } else if (VkApiAttachments.TYPE_ALBUM.equals(type)) {
        return context.deserialize(o, VKApiPhotoAlbum.class);
    } else if (VkApiAttachments.TYPE_STICKER.equals(type)) {
        return context.deserialize(o, VKApiSticker.class);
    }

    return null;
}
 
Example 40
Project: DecompiledMinecraft   File: ModelBlockDefinition.java   View source code 5 votes vote down vote up
protected List<ModelBlockDefinition.Variants> parseVariantsList(JsonDeserializationContext p_178334_1_, JsonObject p_178334_2_)
{
    JsonObject jsonobject = JsonUtils.getJsonObject(p_178334_2_, "variants");
    List<ModelBlockDefinition.Variants> list = Lists.<ModelBlockDefinition.Variants>newArrayList();

    for (Entry<String, JsonElement> entry : jsonobject.entrySet())
    {
        list.add(this.parseVariants(p_178334_1_, entry));
    }

    return list;
}