com.google.gson.JsonElement Java Examples

The following examples show how to use com.google.gson.JsonElement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: o2oa   Author: o2oa   File: AttendanceStatisticShowAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "列示根据过滤条件的组织月份统计数据,上一页", action = ActionListStmForUnitPrevWithFilter.class)
@PUT
@Path("filter/unitMonth/list/{id}/prev/{count}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listStmForUnitPrevWithFilter(@Suspended final AsyncResponse asyncResponse,
		@Context HttpServletRequest request, @JaxrsParameterDescribe("上一页最后一条信息ID") @PathParam("id") String id,
		@JaxrsParameterDescribe("每页显示信息条目数量") @PathParam("count") Integer count, JsonElement jsonElement) {
	ActionResult<List<ActionListStmForUnitPrevWithFilter.Wo>> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	Boolean check = true;

	if (check) {
		try {
			result = new ActionListStmForUnitPrevWithFilter().execute(request, effectivePerson, id, count,
					jsonElement);
		} catch (Exception e) {
			result = new ActionResult<>();
			Exception exception = new ExceptionAttendanceSettingProcess(e, "获取所有数据统计信息列表时发生异常!");
			result.error(exception);
			logger.error(e, effectivePerson, request, null);
		}
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example #2
Source Project: o2oa   Author: o2oa   File: ReviewAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "列示当前用户创建的工作的参阅,上一页.", action = V2ListCreatePrev.class)
@POST
@Path("v2/list/create/{id}/prev/{count}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void V2ListCreatePrev(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		@JaxrsParameterDescribe("参阅标识") @PathParam("id") String id,
		@JaxrsParameterDescribe("数量") @PathParam("count") Integer count, JsonElement jsonElement) {
	ActionResult<List<V2ListCreatePrev.Wo>> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new V2ListCreatePrev().execute(effectivePerson, id, count, jsonElement);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, jsonElement);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example #3
Source Project: synopsys-detect   Author: blackducksoftware   File: NpmCliParser.java    License: Apache License 2.0 6 votes vote down vote up
public NpmParseResult convertNpmJsonFileToCodeLocation(final String npmLsOutput) {
    final JsonObject npmJson = new JsonParser().parse(npmLsOutput).getAsJsonObject();
    final MutableDependencyGraph graph = new MutableMapDependencyGraph();

    final JsonElement projectNameElement = npmJson.getAsJsonPrimitive(JSON_NAME);
    final JsonElement projectVersionElement = npmJson.getAsJsonPrimitive(JSON_VERSION);
    String projectName = null;
    String projectVersion = null;
    if (projectNameElement != null) {
        projectName = projectNameElement.getAsString();
    }
    if (projectVersionElement != null) {
        projectVersion = projectVersionElement.getAsString();
    }

    populateChildren(graph, null, npmJson.getAsJsonObject(JSON_DEPENDENCIES), true);

    final ExternalId externalId = externalIdFactory.createNameVersionExternalId(Forge.NPMJS, projectName, projectVersion);

    final CodeLocation codeLocation = new CodeLocation(graph, externalId);

    return new NpmParseResult(projectName, projectVersion, codeLocation);

}
 
Example #4
Source Project: o2oa   Author: o2oa   File: ActionListMyFilterPaging.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, Integer page, Integer size, JsonElement jsonElement)
		throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		Business business = new Business(emc);
		ActionResult<List<Wo>> result = new ActionResult<>();
		Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
		if (wi == null) {
			wi = new Wi();
		}
		Integer adjustPage = this.adjustPage(page);
		Integer adjustPageSize = this.adjustSize(size);
		List<TaskCompleted> os = this.list(effectivePerson, business, adjustPage, adjustPageSize, wi);
		List<Wo> wos = Wo.copier.copy(os);
		result.setData(wos);
		result.setCount(this.count(effectivePerson, business, wi));
		return result;
	}
}
 
Example #5
Source Project: o2oa   Author: o2oa   File: WorkAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@POST
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
@Path("process/{processFlag}/force")
@JaxrsMethodDescribe(value = "创建工作(强制创建存在的流程).", action = ActionCreateForce.class)
public void createForce(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
				   @JaxrsParameterDescribe("流程标识") @PathParam("processFlag") String processFlag, JsonElement jsonElement) {
	ActionResult<List<ActionCreateForce.Wo>> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionCreateForce().execute(effectivePerson, processFlag, jsonElement);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, jsonElement);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example #6
Source Project: packagedrone   Author: eclipse   File: DeployGroupTypeAdapter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public JsonElement serialize ( final DeployGroup group, final Type type, final JsonSerializationContext ctx )
{
    final JsonObject obj = new JsonObject ();

    obj.addProperty ( "id", group.getId () );
    obj.addProperty ( "name", group.getName () );

    final JsonObject keys = new JsonObject ();
    obj.add ( "keys", keys );

    for ( final DeployKey key : group.getKeys () )
    {
        final JsonObject ok = new JsonObject ();
        ok.addProperty ( "name", key.getName () );
        ok.addProperty ( "key", key.getKey () );
        ok.add ( "timestamp", ctx.serialize ( Date.from ( key.getCreationTimestamp () ), Date.class ) );
        keys.add ( key.getId (), ok );
    }

    return obj;
}
 
Example #7
Source Project: o2oa   Author: o2oa   File: ProjectTemplateAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "根据ID列表查询项目组信息列表.", action = ActionListWithFilter.class)
@PUT
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listWithIds(@Suspended final AsyncResponse asyncResponse, 
		@Context HttpServletRequest request, 
		@JaxrsParameterDescribe("传入的ID列表") JsonElement jsonElement ) {
	ActionResult<List<ActionListWithFilter.Wo>> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionListWithFilter().execute(request, effectivePerson, jsonElement);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example #8
Source Project: o2oa   Author: o2oa   File: ConfigAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "更新人员设置.", action = ActionSetPerson.class)
@PUT
@Path("person")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void setPerson(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		JsonElement jsonElement) {
	ActionResult<ActionSetPerson.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionSetPerson().execute(effectivePerson, jsonElement);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, jsonElement);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example #9
Source Project: PYX-Reloaded   Author: devgianlu   File: GithubAuthHelper.java    License: Apache License 2.0 6 votes vote down vote up
public GithubProfileInfo info(@NotNull String accessToken, @NotNull GithubEmails emails) throws IOException, GithubException {
    HttpGet get = new HttpGet(USER);
    get.addHeader("Authorization", "token " + accessToken);

    try {
        HttpResponse resp = client.execute(get);

        HttpEntity entity = resp.getEntity();
        if (entity == null) throw new IOException(new NullPointerException("HttpEntity is null"));

        JsonElement element = parser.parse(new InputStreamReader(entity.getContent()));
        if (!element.isJsonObject()) throw new IOException("Response is not of type JsonObject");

        JsonObject obj = new JsonObject();
        if (obj.has("message")) throw GithubException.fromMessage(obj);
        else return new GithubProfileInfo(element.getAsJsonObject(), emails);
    } catch (JsonParseException | NullPointerException ex) {
        throw new IOException(ex);
    } finally {
        get.releaseConnection();
    }
}
 
Example #10
Source Project: o2oa   Author: o2oa   File: ActionFire.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		ActionResult<Wo> result = new ActionResult<>();
		Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
		if (effectivePerson.isNotManager()) {
			throw new ExceptionAccessDenied(effectivePerson);
		}
		Application application = ThisApplication.context().applications().get(wi.getApplication(), wi.getNode());
		ScheduleRequest request = null;

		for (ScheduleRequest o : application.getScheduleRequestList()) {
			if (StringUtils.equalsIgnoreCase(wi.getClassName(), o.getClassName())) {
				request = o;
				break;
			}
		}
		this.fire(effectivePerson, application, request);
		Wo wo = new Wo();
		wo.setValue(true);
		result.setData(wo);
		return result;
	}
}
 
Example #11
Source Project: o2oa   Author: o2oa   File: DataAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "根据路径获取指定work的data数据.", action = ActionGetWithJobPath5.class)
@GET
@Path("job/{job}/{path0}/{path1}/{path2}/{path3}/{path4}/{path5}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void getWithJobPath5(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		@JaxrsParameterDescribe("标识") @PathParam("job") String job,
		@JaxrsParameterDescribe("0级路径") @PathParam("path0") String path0,
		@JaxrsParameterDescribe("1级路径") @PathParam("path1") String path1,
		@JaxrsParameterDescribe("2级路径") @PathParam("path2") String path2,
		@JaxrsParameterDescribe("3级路径") @PathParam("path3") String path3,
		@JaxrsParameterDescribe("4级路径") @PathParam("path4") String path4,
		@JaxrsParameterDescribe("5级路径") @PathParam("path5") String path5) {
	ActionResult<JsonElement> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionGetWithJobPath5().execute(effectivePerson, job, path0, path1, path2, path3, path4,
				path5);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, null);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example #12
Source Project: o2oa   Author: o2oa   File: TranslateTaskIdentityTools.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private static List<String> duty(AeiObjects aeiObjects, Manual manual) throws Exception {
	List<String> list = new ArrayList<>();
	if (StringUtils.isNotEmpty(manual.getTaskDuty())) {
		JsonArray array = XGsonBuilder.instance().fromJson(manual.getTaskDuty(), JsonArray.class);
		Iterator<JsonElement> iterator = array.iterator();
		while (iterator.hasNext()) {
			JsonObject o = iterator.next().getAsJsonObject();
			String name = o.get("name").getAsString();
			String code = o.get("code").getAsString();
			CompiledScript compiledScript = aeiObjects.business().element()
					.getCompiledScript(aeiObjects.getActivity(), Business.EVENT_TASKDUTY, name, code);
			Object objectValue = compiledScript.eval(aeiObjects.scriptContext());
			List<String> ds = ScriptFactory.asDistinguishedNameList(objectValue);
			if (ListTools.isNotEmpty(ds)) {
				for (String str : ds) {
					List<String> os = aeiObjects.business().organization().unitDuty()
							.listIdentityWithUnitWithName(str, name);
					if (ListTools.isNotEmpty(os)) {
						list.addAll(os);
					}
				}
			}
		}
	}
	return ListTools.trim(list, true, true);
}
 
Example #13
Source Project: o2oa   Author: o2oa   File: TaskAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "保存并继续流转.", action = ActionProcessing.class)
@PUT
@Path("{id}/processing")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void processing(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
		@JaxrsParameterDescribe("标识") @PathParam("id") String id, JsonElement jsonElement) {
	ActionResult<ActionProcessing.Wo> result = new ActionResult<>();
	EffectivePerson effectivePerson = this.effectivePerson(request);
	try {
		result = new ActionProcessing().execute(effectivePerson, id, jsonElement);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, jsonElement);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example #14
Source Project: o2oa   Author: o2oa   File: ZhengwuDingdingAction.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@JaxrsMethodDescribe(value = "发送一个拉入同步请求.", action = ActionSyncOrganizationCallback.class)
@POST
@Path("sync/organization/callback")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void syncOrganizationCallback(@Suspended final AsyncResponse asyncResponse,
		@Context HttpServletRequest request, JsonElement jsonElement) {
	EffectivePerson effectivePerson = this.effectivePerson(request);
	ActionResult<ActionSyncOrganizationCallback.Wo> result = new ActionResult<>();
	try {
		result = new ActionSyncOrganizationCallback().execute(effectivePerson, jsonElement);
	} catch (Exception e) {
		logger.error(e, effectivePerson, request, jsonElement);
		result.error(e);
	}
	asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
 
Example #15
Source Project: o2oa   Author: o2oa   File: ActionListWithName.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<Wo> execute(EffectivePerson effectivePerson, JsonElement jsonElement) throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
		ActionResult<Wo> result = new ActionResult<>();
		Business business = new Business(emc);
		String cacheKey = ApplicationCache.concreteCacheKey(this.getClass(),
				StringUtils.join(wi.getNameList(), ","));
		Element element = cache.get(cacheKey);
		if (null != element && (null != element.getObjectValue())) {
			result.setData((Wo) element.getObjectValue());
		} else {
			Wo wo = this.list(business, wi);
			cache.put(new Element(cacheKey, wo));
			result.setData(wo);
		}
		return result;
	}
}
 
Example #16
Source Project: incubator-gobblin   Author: apache   File: JsonRecordGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public JsonElement getRecord(String id, PayloadType payloadType) {
  Object testObject;
  switch (payloadType) {
    case STRING: {
      testObject = new TestObject(id, TestUtils.generateRandomAlphaString(20));
      break;
    }
    case LONG: {
      testObject = new TestObject(id, TestUtils.generateRandomLong());
      break;
    }
    case MAP: {
      testObject = new TestObject(id, Collections.EMPTY_MAP);
      break;
    }
    default:
      throw new RuntimeException("Do not know how to handle this type of payload");
  }
  JsonElement jsonElement = gson.toJsonTree(testObject);
  return jsonElement;
}
 
Example #17
Source Project: olca-app   Author: GreenDelta   File: JsonUtil.java    License: Mozilla Public License 2.0 6 votes vote down vote up
private static boolean equal(String property, JsonArray a1, JsonArray a2, ElementFinder finder) {
	if (a1.size() != a2.size())
		return false;
	Iterator<JsonElement> it1 = a1.iterator();
	Set<Integer> used = new HashSet<>();
	while (it1.hasNext()) {
		JsonElement e1 = it1.next();
		int index = finder.find(property, e1, a2, used);
		if (index == -1)
			return false;
		JsonElement e2 = a2.get(index);
		if (!equal(property, e1, e2, finder))
			return false;
		used.add(index);
	}
	return true;
}
 
Example #18
Source Project: unitime   Author: UniTime   File: EventsExportEventsToJSON.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void print(ExportHelper helper, EventLookupRpcRequest request, List<EventInterface> events, int eventCookieFlags, EventMeetingSortBy sort, boolean asc) throws IOException {
	helper.setup("application/json", reference(), false);
	
   	Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
		@Override
		public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
			return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
		}
	})
	.setFieldNamingStrategy(new FieldNamingStrategy() {
		Pattern iPattern = Pattern.compile("i([A-Z])(.*)");
		@Override
		public String translateName(Field f) {
			Matcher matcher = iPattern.matcher(f.getName());
			if (matcher.matches())
				return matcher.group(1).toLowerCase() + matcher.group(2);
			else
				return f.getName();
		}
	})
	.setPrettyPrinting().create();
   	
   	helper.getWriter().write(gson.toJson(events));
}
 
Example #19
Source Project: o2oa   Author: o2oa   File: ActionGetDataPath0.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<JsonElement> execute(String appDictFlag, String appInfoFlag, String path0)
		throws Exception {
	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		Business business = new Business(emc);
		ActionResult<JsonElement> result = new ActionResult<>();
		AppInfo appInfo = business.getAppInfoFactory().pick(appInfoFlag);
		if (null == appInfo) {
			throw new ExceptionAppInfoNotExist(appInfoFlag);
		}
		String id = business.getAppDictFactory().getWithAppInfoWithUniqueName(appInfo.getId(),
				appDictFlag);
		if (StringUtils.isEmpty(id)) {
			throw new ExceptionAppDictNotExist(appInfoFlag);
		}
		AppDict dict = emc.find(id, AppDict.class);
		JsonElement wrap = this.get(business, dict, path0);
		result.setData(wrap);
		return result;
	}
}
 
Example #20
Source Project: o2oa   Author: o2oa   File: ActionUpdateDataPath5.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
ActionResult<Wo> execute(String applicationDictFlag, String applicationFlag, String path0, String path1,
		String path2, String path3, String path4, String path5, JsonElement jsonElement) throws Exception {

	ActionResult<Wo> result = new ActionResult<>();
	String id = null;

	try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
		Business business = new Business(emc);
		Application application = business.application().pick(applicationFlag);
		if (null == application) {
			throw new ExceptionApplicationNotExist(applicationFlag);
		}
		id = business.applicationDict().getWithApplicationWithUniqueName(application.getId(), applicationDictFlag);
		if (StringUtils.isEmpty(id)) {
			throw new ExceptionApplicationDictNotExist(applicationFlag);
		}
	}
	Wo wo = ThisApplication.context().applications().putQuery(x_processplatform_service_processing.class,
			Applications.joinQueryUri("applicationdict", id, path0, path1, path2, path3, path4, path5, "data"),
			jsonElement, id).getData(Wo.class);
	result.setData(wo);
	return result;
}
 
Example #21
Source Project: olca-app   Author: GreenDelta   File: JsonLoader.java    License: Mozilla Public License 2.0 6 votes vote down vote up
private void splitExchanges(JsonObject obj) {
	JsonArray exchanges = obj.getAsJsonArray("exchanges");
	JsonArray inputs = new JsonArray();
	JsonArray outputs = new JsonArray();
	if (exchanges != null)
		for (JsonElement elem : exchanges) {
			JsonObject e = elem.getAsJsonObject();
			JsonElement isInput = e.get("input");
			if (isInput.isJsonPrimitive() && isInput.getAsBoolean())
				inputs.add(e);
			else
				outputs.add(e);
		}
	obj.remove("exchanges");
	obj.add("inputs", inputs);
	obj.add("outputs", outputs);
}
 
Example #22
Source Project: gson   Author: google   File: MapTypeAdapterFactory.java    License: Apache License 2.0 6 votes vote down vote up
private String keyToString(JsonElement keyElement) {
  if (keyElement.isJsonPrimitive()) {
    JsonPrimitive primitive = keyElement.getAsJsonPrimitive();
    if (primitive.isNumber()) {
      return String.valueOf(primitive.getAsNumber());
    } else if (primitive.isBoolean()) {
      return Boolean.toString(primitive.getAsBoolean());
    } else if (primitive.isString()) {
      return primitive.getAsString();
    } else {
      throw new AssertionError();
    }
  } else if (keyElement.isJsonNull()) {
    return "null";
  } else {
    throw new AssertionError();
  }
}
 
Example #23
Source Project: HAPP   Author: timomer   File: APSResultSerializer.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public JsonElement serialize(APSResult src, Type typeOfSrc, JsonSerializationContext context) {
    final JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("action", src.getAction());
    jsonObject.addProperty("reason", src.getReason());
    jsonObject.addProperty("tempSuggested", src.getTempSuggested());
    jsonObject.addProperty("eventualBG", src.getEventualBG());
    jsonObject.addProperty("snoozeBG", src.getSnoozeBG());
    jsonObject.addProperty("timestamp", src.getTimestamp().getTime());
    jsonObject.addProperty("rate", src.getRate());
    jsonObject.addProperty("duration", src.getDuration());
    jsonObject.addProperty("basal_adjustemnt", src.getBasal_adjustemnt());
    jsonObject.addProperty("accepted", src.getAccepted());
    jsonObject.addProperty("aps_algorithm", src.getAps_algorithm());
    jsonObject.addProperty("aps_mode", src.getAps_mode());
    jsonObject.addProperty("current_pump_basal", src.getCurrent_pump_basal());
    jsonObject.addProperty("aps_loop", src.getAps_loop());
    return jsonObject;
}
 
Example #24
Source Project: ha-bridge   Author: bwssytems   File: FieldDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Field deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx)
{
    JsonObject obj = json.getAsJsonObject();
    String theKey;

    fields = new HashMap<String, JsonElement>();
    for(Entry<String, JsonElement> entry:obj.entrySet()){
    	theKey = entry.getKey();
        JsonElement theRawDetail = obj.get(theKey);
        fields.put(theKey, theRawDetail);
    }
    
    return new Field(fields);
}
 
Example #25
Source Project: java-asana   Author: Asana   File: ProjectsBase.java    License: MIT License 5 votes vote down vote up
/**
* Delete a project
* A specific, existing project can be deleted by making a DELETE request on the URL for that project.  Returns an empty data record.
    * @param projectGid Globally unique identifier for the project. (required)
    * @param optFields Defines fields to return. Some requests return *compact* representations of objects in order to conserve resources and complete the request more efficiently. Other times requests return more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options. (optional)
    * @param optPretty Provides “pretty” output. Provides the response in a “pretty” format. In the case of JSON this means doing proper line breaking and indentation to make it readable. This will take extra time and increase the response size so it is advisable only to use this during debugging. (optional)
* @return ItemRequest(JsonElement)
* @throws IOException If we fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ItemRequest<JsonElement> deleteProject(String projectGid, List<String> optFields, Boolean optPretty) throws IOException {
    String path = "/projects/{project_gid}".replace("{project_gid}", projectGid);

    ItemRequest<JsonElement> req = new ItemRequest<JsonElement>(this, JsonElement.class, path, "DELETE")
        .query("opt_pretty", optPretty)
        .query("opt_fields", optFields);

    return req;
}
 
Example #26
Source Project: QuickDevFramework   Author: lx8421bcd   File: GsonParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JSONObject deserialize(JsonElement json, Type typeOfT,
                              JsonDeserializationContext context) throws JsonParseException {
    try {
        return new JSONObject(json.toString());
    } catch (JSONException e) {
        Log.w(TAG, "err, string = " + json.toString());
    }
    return null;
}
 
Example #27
Source Project: Diorite   Author: Diorite   File: JsonDeserializationData.java    License: MIT License 5 votes vote down vote up
@Override
public <T, C extends Collection<T>> void getAsCollection(String key, Class<T> type, C collection)
{
    JsonElement element = this.getElement(this.element, key);
    if (element == null)
    {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }
    if (element.isJsonArray())
    {
        JsonArray jsonArray = element.getAsJsonArray();
        for (JsonElement jsonElement : jsonArray)
        {
            collection.add(this.deserializeSpecial(type, jsonElement, null));
        }
    }
    else if (element.isJsonObject())
    {
        JsonObject jsonObject = element.getAsJsonObject();
        for (Entry<String, JsonElement> entry : jsonObject.entrySet())
        {
            collection.add(this.deserializeSpecial(type, entry.getValue(), null));
        }
    }
    else
    {
        throw new DeserializationException(type, this, "Can't find valid value for key: " + key);
    }
}
 
Example #28
Source Project: azure-mobile-apps-android-client   Author: Azure   File: MobileServiceTableBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Validates if the object represents a string value.
 *
 * @param o
 * @return
 */
protected boolean isStringType(Object o) {
    boolean result = (o instanceof String);

    if (o instanceof JsonElement) {
        JsonElement json = (JsonElement) o;

        if (json.isJsonPrimitive()) {
            JsonPrimitive primitive = json.getAsJsonPrimitive();
            result = primitive.isString();
        }
    }

    return result;
}
 
Example #29
Source Project: o2oa   Author: o2oa   File: BaseAction.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
JsonElement get(Business business, ApplicationDict applicationDict, String... paths) throws Exception {
	List<ApplicationDictItem> list = business.applicationDictItem()
			.listWithApplicationDictWithPath(applicationDict.getId(), paths);
	DataItemConverter<ApplicationDictItem> converter = new DataItemConverter<>(ApplicationDictItem.class);
	JsonElement jsonElement = converter.assemble(list, paths.length);
	return jsonElement;
}
 
Example #30
Source Project: camunda-bpm-platform   Author: camunda   File: JsonArrayOfObjectsConverter.java    License: Apache License 2.0 5 votes vote down vote up
public List<T> toObject(JsonArray jsonArray) {
  List<T> result = new ArrayList<T>();
  for (JsonElement jsonElement : jsonArray) {
    T object = objectConverter.toObject(JsonUtil.getObject(jsonElement));
    result.add(object);
  }

  return result;
}