Java Code Examples for net.sf.json.JSONObject#fromObject()

The following examples show how to use net.sf.json.JSONObject#fromObject() . 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 File: UserClient.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ユーザ情報を作成します。<br/>
 * aliasパラメータを必ず指定する必要があります。<br/>
 * 既に存在するユーザのaliasを指定した場合、例外をスローします。
 *
 * @param param {@link UserCreateParam}
 * @return 作成されたユーザ情報のuseridのリスト
 */
@SuppressWarnings("unchecked")
public List<String> create(UserCreateParam param) {
    if (param.getAlias() == null || param.getAlias().length() == 0) {
        throw new IllegalArgumentException("alias is required.");
    }
    if (accessor.checkVersion("2.0") >= 0) {
        if (param.getPasswd() == null || param.getPasswd().length() == 0) {
            throw new IllegalArgumentException("passwd is required.");
        }

        if (param.getUsrgrps() == null || param.getUsrgrps().isEmpty()) {
            throw new IllegalArgumentException("usrgrps is required.");
        }
    }

    JSONObject params = JSONObject.fromObject(param, defaultConfig);
    JSONObject result = (JSONObject) accessor.execute("user.create", params);

    JSONArray userids = result.getJSONArray("userids");
    JsonConfig config = defaultConfig.copy();
    config.setCollectionType(List.class);
    config.setRootClass(String.class);
    return (List<String>) JSONArray.toCollection(userids, config);
}
 
Example 2
Source File: JwDataCubeAPI.java    From jeewx-api with Apache License 2.0 6 votes vote down vote up
/**
 * 获取消息发送月数据
 * @param bDate 起始时间
 * @param eDate 结束时间
 * @return
 * @throws WexinReqException
 */
public static List<WxDataCubeStreamMsgMonthInfo> getWxDataCubeStreamMsgMonthInfo(String accesstoken,String bDate,String eDate) throws WexinReqException {
	if (accesstoken != null) {
		
		// 封装请求参数
		WxDataCubeStreamMsgMonthParam msgParam = new WxDataCubeStreamMsgMonthParam();
		msgParam.setAccess_token(accesstoken);
		msgParam.setBegin_date(bDate);
		msgParam.setEnd_date(eDate);
		
		// 调用接口
		String requestUrl = GETUPSTREAMMSGMONTH_URL.replace("ACCESS_TOKEN", accesstoken);
		JSONObject obj = JSONObject.fromObject(msgParam);
		JSONObject result = WxstoreUtils.httpRequest(requestUrl, "POST", obj.toString());
		Object error = result.get("errcode");

		// 无错误消息时 返回数据对象
		JSONArray arrayResult = result.getJSONArray("list");
		// 正常返回
		List<WxDataCubeStreamMsgMonthInfo> msgInfoList = null;
		msgInfoList=JSONHelper.toList(arrayResult, WxDataCubeStreamMsgMonthInfo.class);
		return msgInfoList;
	}
	return null;
}
 
Example 3
Source File: Json.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public void replaceValue(String path, String newValue) {
    String[] split = path.split("\\.");
    JSONObject jsonObject = JSONObject.fromObject(value);
    if (split.length == 1) {
        jsonObject.put(split[0], newValue);
    }

    JSONObject object = jsonObject;
    for (int i = 0; i < split.length - 1; i++) {
        object = object.getJSONObject(split[i]);
    }
    object.put(split[split.length - 1], newValue);
    value = jsonObject.toString();
}
 
Example 4
Source File: RulesDbClientImpl.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public List<String> listWorkflows() {
    List<String> ls = new ArrayList<>();
    try (InputStream is = httpClient.getHttpRequest(new HistoDbUrl(config, ".json", Collections.emptyMap()))) {
        String json = new String(ByteStreams.toByteArray(is), StandardCharsets.UTF_8);
        JSONObject jsonObj = JSONObject.fromObject(json);
        for (Object name : jsonObj.names()) {
            if (((String) name).startsWith(RULES_PREFIX)) {
                String workflowId = ((String) name).substring(RULES_PREFIX.length());
                ls.add(workflowId);
            }
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
    return ls;
}
 
Example 5
Source File: MarathonBuilderImplTest.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Test that existing "env" section is not deleted or overwritten on subsequence builds.
 */
@Test
public void testExistingEnv() throws IOException {
    final String     jsonString = TestUtils.loadFixture("env.json");
    final JSONObject json       = JSONObject.fromObject(jsonString);
    final MockConfig config     = new MockConfig();

    // add to the env
    config.env.add(new MarathonVars("example", "test"));
    // build
    MarathonBuilder builder = new MarathonBuilderImpl(config).setJson(json).build();

    assertEquals("bar", builder.getApp().getEnv().get("foo"));
    assertEquals("buzz", builder.getApp().getEnv().get("fizz"));
    assertEquals("test", builder.getApp().getEnv().get("example"));
}
 
Example 6
Source File: GeoServerListFeatureLayersCommand.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
public String computeResults(final OperationParams params) throws Exception {
  final Response listLayersResponse =
      geoserverClient.getFeatureLayers(workspace, datastore, geowaveOnly);

  if (listLayersResponse.getStatus() == Status.OK.getStatusCode()) {
    final JSONObject listObj = JSONObject.fromObject(listLayersResponse.getEntity());
    return "\nGeoServer layer list: " + listObj.toString(2);
  }
  final String errorMessage =
      "Error getting GeoServer layer list: "
          + listLayersResponse.readEntity(String.class)
          + "\nGeoServer Response Code = "
          + listLayersResponse.getStatus();
  return handleError(listLayersResponse, errorMessage);
}
 
Example 7
Source File: StandardStats.java    From cachecloud with Apache License 2.0 6 votes vote down vote up
public Map<String, Object> getClusterInfoMap() {
    if (clusterInfoMap != null) {
        return clusterInfoMap;
    } else {
        if (StringUtils.isNotBlank(clusterInfoJson)) {
            JSONObject jsonObject;
            try {
                jsonObject = JSONObject.fromObject(clusterInfoJson);
                Map<String, Object> map = transferMapByJson(jsonObject);
                clusterInfoMap = map;
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
    }
    return clusterInfoMap;
}
 
Example 8
Source File: DeflakeAction.java    From flaky-test-handler-plugin with Apache License 2.0 5 votes vote down vote up
private static ParameterValue getBooleanParam(JSONObject formData, String paramName) {
  JSONObject paramObj = JSONObject.fromObject(formData.get(paramName));
  String name = paramObj.getString("name");
  FlakyTestResultAction.logger.log(Level.FINE,
      "Param: " + name + " with value: " + paramObj.getBoolean("value"));
  return new BooleanParameterValue(name, paramObj.getBoolean("value"));
}
 
Example 9
Source File: StringUtil.java    From Leo with Apache License 2.0 5 votes vote down vote up
/**
 * 把json串中的uncode编码转换为字符串显示,转换失败返回原json串
 * @param jsonStr
 * @return String
 */
public static String getStrFromJson(String jsonStr) {
	try {
		JSONObject tempJSON = JSONObject.fromObject(jsonStr);
		return tempJSON.toString();
	} catch (Exception e) {
		return jsonStr;
	}

}
 
Example 10
Source File: DeflakeAction.java    From flaky-test-handler-plugin with Apache License 2.0 5 votes vote down vote up
private static ParameterValue getStringParam(JSONObject formData, String paramName) {
  JSONObject paramObj = JSONObject.fromObject(formData.get(paramName));
  String name = paramObj.getString("name");
  FlakyTestResultAction.logger.log(Level.FINE,
      "Param: " + name + " with value: " + paramObj.getString("value"));
  return new StringParameterValue(name, paramObj.getString("value"));
}
 
Example 11
Source File: OHDSIApis.java    From Criteria2Query with Apache License 2.0 5 votes vote down vote up
public static JSONObject querybyconceptSetid(int conceptid){
	System.out.println("===>querybyconceptSetid");
	JSONObject jot=new JSONObject();
   	String re2=HttpUtil.doGet(conceptseturl+conceptid);
   	JSONObject jore2=JSONObject.fromObject(re2);
   	System.out.println("jore2="+jore2);
   	jot.accumulateAll(jore2);
   	String re3=HttpUtil.doGet(conceptseturl+conceptid+"/expression");
   	
   	JSONObject expression=JSONObject.fromObject(re3);
   	jot.accumulate("expression",expression);
   	
   	return jot;
}
 
Example 12
Source File: MarathonBuilderImplTest.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Test container type detection within template JSON
 */
@Test
public void testSimpleContainerTypeDetection() throws IOException {
    final String     jsonString = TestUtils.loadFixture("mesos-containertype.json");
    final JSONObject json       = JSONObject.fromObject(jsonString);
    final MockConfig config     = new MockConfig();

    MarathonBuilder builder = new MarathonBuilderImpl(config).setJson(json).build();

    assertEquals("MESOS", builder.getApp().getContainer().getType());
}
 
Example 13
Source File: StudentManageAction.java    From OnLineTest with Apache License 2.0 5 votes vote down vote up
public String getStudent(){
	HttpServletResponse response = ServletActionContext.getResponse();
	response.setContentType("application/json;charset=utf-8");
	Student student = new Student();
	student.setStudentId(studentId);
	Student newStudent = studentService.getStudentById(student);
	JSONObject jsonObject = JSONObject.fromObject(newStudent);
	try {
		response.getWriter().print(jsonObject);
	} catch (IOException e) {
		throw new RuntimeException(e.getMessage());
	}
	return null;
}
 
Example 14
Source File: ProxyClient.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
/**
 * プロキシ情報を取得します。<br/>
 * プロキシ情報が存在しない場合、空のリストを返します。
 *
 * @param param {@link ProxyGetParam}
 * @return 取得したプロキシ情報のリスト
 */
@SuppressWarnings("unchecked")
public List<Proxy> get(ProxyGetParam param) {
    JSONObject params = JSONObject.fromObject(param, defaultConfig);
    JSONArray result = (JSONArray) accessor.execute("proxy.get", params);

    JsonConfig config = defaultConfig.copy();
    config.setCollectionType(List.class);
    config.setRootClass(Proxy.class);
    return (List<Proxy>) JSONArray.toCollection(result, config);
}
 
Example 15
Source File: PushAndPullRequestPayload.java    From DotCi with MIT License 4 votes vote down vote up
public PushAndPullRequestPayload(final String payload) {
    this.payloadJson = JSONObject.fromObject(payload);
}
 
Example 16
Source File: StatusJsonActionTest.java    From gitlab-plugin with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected void assertNotFoundBuild(ByteArrayOutputStream out, StaplerResponse response) {
    JSONObject object = JSONObject.fromObject(new String(out.toByteArray()));
    assertThat(object.getString("sha"), is(commitSha1));
    assertThat(object.getString("status"), is("not_found"));
}
 
Example 17
Source File: JSONHelper.java    From jeewx-api with Apache License 2.0 4 votes vote down vote up
/***
 * 将JSON文本反序列化为主从关系的实体
 * 
 * @param <T>
 *            泛型T 代表主实体类型
 * @param <D>
 *            泛型D 代表从实体类型
 * @param jsonString
 *            JSON文本
 * @param mainClass
 *            主实体类型
 * @param detailName
 *            从实体类在主实体类中的属性名称
 * @param detailClass
 *            从实体类型
 * @return
 */
public static <T, D> T toBean(String jsonString, Class<T> mainClass,
		String detailName, Class<D> detailClass) {
	JSONObject jsonObject = JSONObject.fromObject(jsonString);
	JSONArray jsonArray = (JSONArray) jsonObject.get(detailName);

	T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
	List<D> detailList = JSONHelper.toList(jsonArray, detailClass);

	try {
		BeanUtils.setProperty(mainEntity, detailName, detailList);
	} catch (Exception ex) {
		throw new RuntimeException("主从关系JSON反序列化实体失败!");
	}

	return mainEntity;
}
 
Example 18
Source File: JwtAuthenticationServiceImplTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
    public void anonymousUserToken() throws Exception{
        j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
        JenkinsRule.WebClient webClient = j.createWebClient();
        String token = getToken(webClient);
        Assert.assertNotNull(token);


        JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);

        Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);

        JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;


        String kid = jsw.getHeader("kid");

        Assert.assertNotNull(kid);

        Page page = webClient.goTo("jwt-auth/jwks/"+kid+"/", "application/json");

//        for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
//            System.out.println(valuePair);
//        }

        JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
        RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject,null);

        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setRequireExpirationTime() // the JWT must have an expiration time
            .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
            .setRequireSubject() // the JWT must have a subject claim
            .setVerificationKey(rsaJsonWebKey.getKey()) // verify the sign with the public key
            .build(); // create the JwtConsumer instance

        JwtClaims claims = jwtConsumer.processToClaims(token);
        Assert.assertEquals("anonymous",claims.getSubject());

        Map<String,Object> claimMap = claims.getClaimsMap();

        Map<String,Object> context = (Map<String, Object>) claimMap.get("context");
        Map<String,String> userContext = (Map<String, String>) context.get("user");
        Assert.assertEquals("anonymous", userContext.get("id"));
    }
 
Example 19
Source File: WebSocketServer.java    From wangmarket with Apache License 2.0 4 votes vote down vote up
/**
	 * 收到客户端消息后调用的方法
	 * @param message 客户端发送过来的消息
	 * @param session 可选的参数
	 * @throws IOException 
	 */
	@OnMessage
	public void onMessage(String message, Session session) throws IOException {
		JSONObject json = JSONObject.fromObject(message);
		Message msg = new Message();
		msg.setContent(StringUtil.filterXss(json.getJSONObject("mine").getString("content")));
		msg.setSendAvatar(StringUtil.filterXss(json.getJSONObject("mine").getString("avatar")));
		msg.setSendId(json.getJSONObject("mine").getLong("id"));
		msg.setSendUserName(StringUtil.filterXss(json.getJSONObject("mine").getString("username")));
		
		msg.setSocketId(this.id);
		msg.setSocketUuid(this.uuid);
		
		if(json.getJSONObject("to") != null){
			JSONObject to = json.getJSONObject("to");
			if(to.get("avatar") != null){
				msg.setReceiveAvatar(StringUtil.filterXss(to.getString("avatar")));
			}
			if(to.get("id") != null){
				msg.setReceiveId(to.getLong("id"));
			}
			if(to.get("type") != null){
				msg.setReceiveType(StringUtil.filterXss(to.getString("type")));
			}
			if(to.get("username") != null){
				msg.setReceiveUserName(StringUtil.filterXss(to.getString("username")));
			}
			if(to.get("name") != null){
				msg.setReceiveUserName(StringUtil.filterXss(to.getString("name")));
			}
		}
		
		//记录信息
		KefuLog.insert(msg);
		
		//收到消息后,向目标方发送消息
		//首先查找目标方是否在socket链接
		WebSocketServer socket = Global.socketMap.get(msg.getReceiveId());
		if(socket == null){
			//对方已下线,那么进行判断,对方是游客还是网站用户若是注册用户的话,需要进行邮件发送提醒
			if(msg.getReceiveId() < Integer.MAX_VALUE){
				//是注册用户,那么从缓存中取接收方用户设置的Im
				Im im = Global.imMap.get(msg.getReceiveId());
				if(im == null){
					//缓存中没有记录,那么从数据库中取
//					Map<String, String> map = null;
//					try {
//						map = DB.getValue("SELECT auto_reply,use_off_line_email,email FROM im WHERE userid = "+ msg.getReceiveId());
//					} catch (SQLException e) {
//						e.printStackTrace();
//					}
					List<Im> imList = Sql.getSqlService().findByProperty(Im.class, "userid", msg.getReceiveId());
					if(imList.size() > 0){
						//有,用户设置了自己的自动回复策略
						im = imList.get(0);
					}else{
						//没有这个id得SiteIm设置,那么就是此用户没有设置自己的自动回复策略
						im = new Im();
						im.setHaveImSet(false);
					}
					
//					im = new Im();
//					if(map == null || map.size() == 0){
//						//没有这个id得SiteIm设置,那么就是此用户没有设置自己的自动回复策略
//						im.setHaveImSet(false);
//					}else{
//						//有,用户设置了自己的自动回复策略
//						im.setHaveImSet(true);
//						im.setEmail(map.get("email"));
//						im.setUseOffLineEmail(map.get("use_off_line_email") != null && map.get("use_off_line_email").equals("1"));
//						im.setAutoReply(map.get("auto_reply"));
//					}
					//将im缓存
					Global.imMap.put(msg.getReceiveId(), im);
				}
				
				if(im.isHaveImSet()){
					//使用自动回复策略
					//进行自动回复
					sendReply(im.getAutoReply(), msg);
					//进行邮件提醒
					if(im.isUseOffLineEmail()){
						sendMail(msg, im.getEmail());
					}
				}
			}else{
				//若没有设置自动回复策略,则回复默认的文字
				sendReply("抱歉,对方已下线!", msg);
			}
		}else{
			socket.sendMessageContent(msg.getContent(), msg);
		}
		
	}
 
Example 20
Source File: Common.java    From pdf-extract with GNU General Public License v3.0 4 votes vote down vote up
public JSONObject getJSONFormat(String sData) {
	if (sData == null || sData.trim().length() == 0)
		return null;
	else
		return JSONObject.fromObject(sData);
}