Java Code Examples for com.alibaba.fastjson.JSONObject#entrySet()

The following examples show how to use com.alibaba.fastjson.JSONObject#entrySet() . 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: ParamUtils.java    From http-api-invoker with MIT License 6 votes vote down vote up
/**
 * convert param object to query string
 * <p>
 * collection fields will be convert to a form of duplicated key such as id=1&amp;id=2&amp;id=3
 *
 * @param arg the param args
 * @return query string
 */
public static String toQueryString(Object arg) {
    if (arg == null) {
        return "";
    }
    StringBuilder qs = new StringBuilder("?");
    JSONObject obj = JSON.parseObject(JSON.toJSONString(arg));
    for (Map.Entry<String, Object> entry : obj.entrySet()) {
        if (isCollection(entry.getValue())) {
            qs.append(collectionToQueryString(obj, entry));
        } else {
            String value = entry.getValue() == null ? "" : entry.getValue().toString();
            try {
                value = URLEncoder.encode(value, "UTF-8");
            } catch (UnsupportedEncodingException ignored) {
            }
            qs.append(entry.getKey()).append("=").append(value).append("&");
        }
    }
    return qs.substring(0, qs.length() - 1);
}
 
Example 2
Source File: BasePlatform.java    From blog-hunter with MIT License 6 votes vote down vote up
protected final HunterConfig get(String url) {

        String host = PlatformUtil.getHost(url);
        String domain = PlatformUtil.getDomain(url);

        String platformConfig = HunterConfigTemplate.getConfig(platform);
        JSONObject platformObj = JSONObject.parseObject(platformConfig);
        String br = "\r\n", header = null;
        Set<Map.Entry<String, Object>> entries = platformObj.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            if ("header".equals(entry.getKey())) {
                header = "Host=" + host + br + "Referer=" + domain;
                entry.setValue(header);
            } else if ("entryUrls".equals(entry.getKey())) {
                entry.setValue(Collections.singletonList(url));
            } else {
                if (platform.equals(Platform.ITEYE.getPlatform()) && "domain".equals(entry.getKey())) {
                    entry.setValue(host);
                }
            }
        }
        HunterConfig config = JSONObject.toJavaObject(platformObj, HunterConfig.class);
        config.setSingle(true);
        return config;
    }
 
Example 3
Source File: RedisController.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
@RequestMapping
public String index(HttpServletRequest request, Model model) {
    JSONObject redisInfo = sysCommonService.getRedisInfo();
    JSONObject jsonObject =null;
    if(redisInfo!=null)
    {
        jsonObject=redisInfo.getJSONObject("info");
    }
    Set<Map.Entry<String, Object>> entries =null;
    if(jsonObject!=null)
    {
        entries = jsonObject.entrySet();
    }
    model.addAttribute("list", entries);
    return "redis/redis-index";
}
 
Example 4
Source File: TagResult.java    From aliyun-tsdb-java-sdk with Apache License 2.0 6 votes vote down vote up
public static List<TagResult> parseList(String json) {
    JSONArray array = JSON.parseArray(json);
    List<TagResult> arrayList = new ArrayList<TagResult>(array.size());

    Iterator<Object> iterator = array.iterator();
    while (iterator.hasNext()) {
        JSONObject object = (JSONObject) iterator.next();
        Set<Entry<String, Object>> entrySet = object.entrySet();
        for (Entry<String, Object> entry : entrySet) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            TagResult tagResult = new TagResult(key, value);
            arrayList.add(tagResult);
            break;
        }
    }

    return arrayList;
}
 
Example 5
Source File: ParseLogJob.java    From 163-bigdate-note with GNU General Public License v3.0 6 votes vote down vote up
public static LogGenericWritable parseLog(String row) throws ParseException {
    String[] logPart = StringUtils.split(row, "\u1111");
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    long timeTag = dateFormat.parse(logPart[0]).getTime();

    String activeName = logPart[1];

    JSONObject bizData = JSON.parseObject(logPart[2]);
    LogGenericWritable logData = new LogWritable();
    logData.put("time_tag", new LogFieldWritable(timeTag));
    logData.put("active_name", new LogFieldWritable(activeName));
    for (Map.Entry<String, Object> entry : bizData.entrySet()) {
        logData.put(entry.getKey(), new LogFieldWritable(entry.getValue()));
    }

    return logData;
}
 
Example 6
Source File: ParseLogJob.java    From 163-bigdate-note with GNU General Public License v3.0 6 votes vote down vote up
public static LogGenericWritable parseLog(String row) throws Exception {
    String[] logPart = StringUtils.split(row, "\u1111");
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    long timeTag = dateFormat.parse(logPart[0]).getTime();

    String activeName = logPart[1];

    JSONObject bizData = JSON.parseObject(logPart[2]);
    LogGenericWritable logData = new LogWritable();
    logData.put("time_tag", new LogFieldWritable(timeTag));
    logData.put("active_name", new LogFieldWritable(activeName));
    for (Map.Entry<String, Object> entry : bizData.entrySet()) {
        logData.put(entry.getKey(), new LogFieldWritable(entry.getValue()));
    }

    return logData;
}
 
Example 7
Source File: JsonParser.java    From SprintNBA with Apache License 2.0 6 votes vote down vote up
public static NewsItem parseNewsItem(String jsonStr) {
    NewsItem newsItem = new NewsItem();
    JSONObject data = JSON.parseObject(JsonParser.parseBase(newsItem, jsonStr)); // articleIds=    NullPoint
    List<NewsItem.NewsItemBean> list = new ArrayList<NewsItem.NewsItemBean>();
    //Set<String> keySet = data.keySet();
    for (Map.Entry<String, Object> item : data.entrySet()) {
        Gson gson = new Gson();
        NewsItem.NewsItemBean bean = gson.fromJson(item.getValue().toString(), NewsItem.NewsItemBean.class);
        bean.index = item.getKey();
        list.add(bean);
    }
    // 由于fastjson获取出来的entrySet是乱序的  所以这边重新排序
    Collections.sort(list, new Comparator<NewsItem.NewsItemBean>() {
        @Override
        public int compare(NewsItem.NewsItemBean lhs, NewsItem.NewsItemBean rhs) {
            return rhs.index.compareTo(lhs.index);
        }
    });
    newsItem.data = list;
    return newsItem;
}
 
Example 8
Source File: SimpleHintParser.java    From tddl with Apache License 2.0 5 votes vote down vote up
private static ExtraCmdRouteCondition decodeExtra(JSONObject jsonObject) throws JSONException {
    ExtraCmdRouteCondition rc = new ExtraCmdRouteCondition();
    String extraCmd = containsKvNotBlank(jsonObject, EXTRACMD);
    if (StringUtils.isNotEmpty(extraCmd)) {
        JSONObject extraCmds = JSON.parseObject(extraCmd);
        for (Map.Entry<String, Object> entry : extraCmds.entrySet()) {
            rc.getExtraCmds().put(StringUtils.upperCase(entry.getKey()), entry.getValue());
        }
    }
    return rc;
}
 
Example 9
Source File: TestTagResult.java    From aliyun-tsdb-java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testJSONToResult() {
    String json = "[{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1.012\"}]";

    try {
        JSONArray array = JSON.parseArray(json);
        // System.out.println(array);
        Assert.assertEquals(array.toString(),
                "[{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1.012\"}]");
        List<TagResult> arrayList = new ArrayList<TagResult>(array.size());

        Iterator<Object> iterator = array.iterator();
        while (iterator.hasNext()) {
            JSONObject object = (JSONObject) iterator.next();
            Set<Entry<String, Object>> entrySet = object.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                String key = entry.getKey();
                Assert.assertNotEquals(key, null);
                Object valueObject = entry.getValue();
                Assert.assertNotEquals(key, null);
                String value = valueObject.toString();
                TagResult tagResult = new TagResult(key, value);
                arrayList.add(tagResult);
                break;
            }
        }
        Assert.assertEquals(arrayList.size(), 3);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
 
Example 10
Source File: SearchAliasParseHandler.java    From EserKnife with Apache License 2.0 5 votes vote down vote up
@Override
public List<SearchAliasReslut> parseData(JSONObject json) {

    List<SearchAliasReslut> list = new ArrayList<SearchAliasReslut>();

    if(json == null) {
        return list;
    }

    for (Map.Entry<String, Object> entry : json.entrySet()) {
        String index = entry.getKey();
        JSONObject obj = json.getJSONObject(index).getJSONObject("aliases");
        if (obj.size() == 0) {
            continue;
        }
        SearchAliasReslut sar = new SearchAliasReslut(index);
        List<AliasInfo> aliasList = new ArrayList<AliasInfo>();
        sar.setAliases(aliasList);
        for (Map.Entry<String, Object> aliasEntry : obj.entrySet()) {
            aliasList.add(new AliasInfo(aliasEntry.getKey(), String.valueOf(aliasEntry.getValue())));
        }

        list.add(sar);

    }

    return list;
}
 
Example 11
Source File: AVACL.java    From java-unified-sdk with Apache License 2.0 5 votes vote down vote up
public AVACL(JSONObject json) {
  if (null != json) {
    Set<Map.Entry<String, Object>> entries = json.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
      Object v = entry.getValue();
      if (null != v && v instanceof HashMap) {
        permissionsById.put(entry.getKey(), new Permissions((HashMap<String, Object>) entry.getValue()));
      }
    }
  }
}
 
Example 12
Source File: CouchDBTest.java    From julongchain with Apache License 2.0 5 votes vote down vote up
/**
    * 根据id查询文档,查询结果为object,id可以拷贝库中任意doc的id
    * @throws Exception
    */
   @Test
   public void readDocTest() throws Exception{
       CouchDbClient db = creatConnectionDB();
       CouchDB couchDB = new CouchDB();
       String id = "3";//id可以拷贝库中任意doc的id
       JSONObject object = couchDB.readDoc(db, id);
	JSONObject attachments = object.getJSONObject("_attachments");
	for (Map.Entry<String, Object> entry : attachments.entrySet()) {
		System.out.println(entry.getKey());
		System.out.println(entry.getValue());
	}
}
 
Example 13
Source File: MetricbeatMetricReader.java    From sofa-lookout with Apache License 2.0 5 votes vote down vote up
private void dfs(String prefix, List<Metric> base, JSONObject json) {
    for (Map.Entry<String, Object> e : json.entrySet()) {
        String key = e.getKey();
        String mergedKey = prefix.isEmpty() ? key : (prefix + "." + key);
        Object value = e.getValue();
        if (value instanceof JSONObject) {
            dfs(mergedKey, base, (JSONObject) value);
        } else if (value instanceof Number) {
            Metric m = new Metric();
            m.setName(mergedKey);
            m.setValue(((Number) value).doubleValue());
            base.add(m);
        }
    }
}
 
Example 14
Source File: Admin.java    From dbys with GNU General Public License v3.0 5 votes vote down vote up
@PostMapping("/admin/config")
public BaseResult updataConfig(String data, HttpServletRequest request) {
    if (adminService.isAdmin(request)) {
        JSONObject jsonObject = JSON.parseObject(data);
        List<Config> cs = new ArrayList<>();
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            cs.add(new Config(entry.getKey(), (String) entry.getValue()));
        }
        adminService.updataAllConfig(cs);
        return ResultUtil.successOk();
    }
    return ResultUtil.error("权限不足");
}
 
Example 15
Source File: WXDomStatement.java    From weex with Apache License 2.0 5 votes vote down vote up
/**
 * Put the map info in the JSONObject to the container.
 * This method check for null value in the JSONObject
 * and won't put the null value in the container.
 * As {@link ConcurrentHashMap#putAll(Map)} will throws an exception if the key or value to
 * be put is null, it is necessary to invoke this method as replacement of
 * {@link Map#putAll(Map)}
 * @param container container to contain the JSONObject.
 * @param rawValue jsonObject, contains map info.
 */
private static void putAll(Map<String, Object> container, JSONObject rawValue) {
  String key;
  Object value;
  for (Map.Entry<String, Object> entry : rawValue.entrySet()) {
    key = entry.getKey();
    value = entry.getValue();
    if (key != null && value != null) {
      container.put(key, value);
    }
  }
}
 
Example 16
Source File: SmsTencentStrategy.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
@Override
protected SmsResult send(SmsDO smsDO) {
    try {
        //初始化单发
        SmsSingleSender singleSender = new SmsSingleSender(Convert.toInt(smsDO.getAppId(), 0), smsDO.getAppSecret());

        String paramStr = smsDO.getTemplateParams();

        JSONObject param = JSONObject.parseObject(paramStr, Feature.OrderedField);

        Set<Map.Entry<String, Object>> sets = param.entrySet();

        ArrayList<String> paramList = new ArrayList<>();
        for (Map.Entry<String, Object> val : sets) {
            paramList.add(val.getValue().toString());
        }

        SmsSingleSenderResult singleSenderResult = singleSender.sendWithParam("86", smsDO.getPhone(),
                Convert.toInt(smsDO.getTemplateCode()), paramList, smsDO.getSignName(), "", "");
        log.info("tencent result={}", singleSenderResult.toString());
        return SmsResult.build(ProviderType.TENCENT, String.valueOf(singleSenderResult.result),
                singleSenderResult.sid, singleSenderResult.ext,
                ERROR_CODE_MAP.getOrDefault(String.valueOf(singleSenderResult.result), singleSenderResult.errMsg), singleSenderResult.fee);
    } catch (Exception e) {
        log.error(e.getMessage());
        return SmsResult.fail(e.getMessage());
    }
}
 
Example 17
Source File: FormParamsExtractAction2.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@Override
public Status act(UpstreamJob job, JSONObject jsonObject) {
    for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
        if (entry.getValue() instanceof String) {
            job.addFormParam(entry.getKey(), (String) entry.getValue());
        } else if (entry.getValue() instanceof Number) {
            job.addFormParam(entry.getKey(), entry.getValue().toString());
        } else {
            job.addFormParam(entry.getKey(), JsonUtils.toJsonString(entry.getValue()));
        }
    }
    FormParamsExtractAction.appendContextInFormParams(job);
    return Status.CONTINUE;
}
 
Example 18
Source File: DeployService.java    From PeonyFramwork with Apache License 2.0 4 votes vote down vote up
private static void doDeployToServer(JSONObject object,String projectUrl,DeployServer deployServer,DeployState deployState,boolean restart){
        Session session = null;
        try{
            object.put("st","1"); // 开始连接
            // 连接
//                    Session session  = this.connect("localhost","郑玉振elex",22,"zhengyuzhen");
//                    Session session  = connect("47.93.249.150","root",22,"Zyz861180416");
            session  = connect(deployServer.getSshIp(),deployServer.getSshUser(),22,deployServer.getSshPassword());
            //            Session session  = this.connect(deployServer.getSshIp(),deployServer.getSshUser(),22,deployServer.getSshPassword());
            System.out.println("isConnected:"+session!=null);

            // 创建目录
            object.put("st","2");// 正在上传

            StringBuilder uploadCmds = new StringBuilder();
            uploadCmds.append("mkdir -p "+deployServer.getPath().trim()+" \n");
            uploadCmds.append("cd "+deployServer.getPath().trim()+" \n");
            execCmd(session,uploadCmds.toString(),object,deployState);
            // 上传
            upload(session,deployServer.getPath().trim()+"/target.tar.gz",projectUrl+"/build/target.tar.gz",new DeployProgressSetter(deployState,deployServer.getId()));

            // 解压并执行
            object.put("st","3"); // 解压并执行
            StringBuilder execCmds = new StringBuilder();
            execCmds.append("cd "+deployServer.getPath().trim()+" \n");
            execCmds.append("tar -xzvf target.tar.gz --strip-components 2 ./target\n");
//                    execCmds.append("cd target \n");
            // sed -r 's/^\s*serverId\s*=.*/serverId=3/g'
//                    RegExp regExp = new RegExp("");
            // 修改参数
            if(StringUtils.isNotEmpty(deployServer.getConfig())){
                JSONObject configObject = JSONObject.parseObject(deployServer.getConfig());
                for(Map.Entry<String,Object> entry : configObject.entrySet()){
                    // 这个sed命令在mac上有问题,需要在-i 后面加个空字符串参数:''
                    String replaceCmd = "sed -i 's#^\\s*"+ Util.regReplace(entry.getKey())+"\\s*=.*#"+Util.regReplace(entry.getKey()+"="+entry.getValue())+"#g' config/mmserver.properties \n";
                    execCmds.append(replaceCmd);
                }
            }
//            boolean restart = deployType.getRestart()>0;
            if(restart){
                execCmds.append("echo begin start server \n");
                execCmds.append("sh start.sh \n");
            }else{
                execCmds.append("echo no need restart server \n");
            }
            execCmd(session,execCmds.toString(),restart,object,deployState);
            // 断开
//                    session.disconnect();
            //
        }catch (Throwable e){
            logger.error("deploy server error! server id={} ",deployServer.getId(),e);
            object.put("error",e.getMessage());
        }finally {
            if(session!= null){
                session.disconnect();
            }
            deployState.logPre.remove();
        }
    }
 
Example 19
Source File: LindenDocumentBuilder.java    From linden with Apache License 2.0 4 votes vote down vote up
public static LindenField buildDynamicField(JSONObject jsonElement) throws IOException {
  LindenField field = new LindenField();
  // default field type is STRING
  // Linden dynamic field is always indexed and stored
  LindenFieldSchema fieldSchema = new LindenFieldSchema().setType(LindenType.STRING).setIndexed(true).setStored(true);
  for (Map.Entry<String, Object> entry : jsonElement.entrySet()) {
    String key = entry.getKey();
    String value = String.valueOf(entry.getValue());
    switch (key.toLowerCase()) {
      case "_tokenize":
        fieldSchema.setTokenized(value.equalsIgnoreCase("true"));
        break;
      case "_omitnorms":
        fieldSchema.setOmitNorms(value.equalsIgnoreCase("true"));
        break;
      case "_snippet":
        fieldSchema.setSnippet(value.equalsIgnoreCase("true"));
        break;
      case "_docvalues":
        fieldSchema.setDocValues(value.equalsIgnoreCase("true"));
        break;
      case "_multi":
        fieldSchema.setMulti(value.equalsIgnoreCase("true"));
        break;
      case "_omitfreqs":
        fieldSchema.setOmitFreqs(value.equalsIgnoreCase("true"));
        break;
      case "_type":
        switch (value.toLowerCase()) {
          case "int":
            fieldSchema.setType(LindenType.INTEGER);
            break;
          default:
            fieldSchema.setType(LindenType.valueOf(value.toUpperCase()));
            break;
        }
        break;
      default:
        if (fieldSchema.isSetName()) {
          throw new IOException(
              "Dynamic field name has already been set to " + fieldSchema.getName() + ", it can not be set to "
              + key);
        }
        fieldSchema.setName(key);
        field.setValue(value);
        break;
    }
  }
  LindenSchemaBuilder.verifyFieldSchema(fieldSchema);
  return field.setSchema(fieldSchema);
}
 
Example 20
Source File: ElasticSearchConfig.java    From OpenFalcon-SuitAgent with Apache License 2.0 4 votes vote down vote up
private static String getNodeNameOrId(int pid,int type) throws IOException {
    String selfNodeId = "";
    String selfNodeName = "";
    String netWorkHost = getNetworkHost(pid);
    int port = getHttpPort(pid);
    String url = getConnectionUrl(pid) + "/_nodes";
    String responseText;
    try {
        responseText = HttpUtil.get(url).getResult();
    } catch (IOException e) {
        log.error("访问{}异常",url,e);
        return "";
    }
    JSONObject responseJSON = JSONObject.parseObject(responseText);
    JSONObject nodes = responseJSON.getJSONObject("nodes");
    if(nodes != null){
        for (Map.Entry<String, Object> entry : nodes.entrySet()) {
            String nodeId = entry.getKey();
            JSONObject nodeInfo = (JSONObject) entry.getValue();
            String nodeName = nodeInfo.getString("name");
            String http_address = nodeInfo.getString("http_address");
            if("127.0.0.1".equals(netWorkHost) || "localhost".equals(netWorkHost)){
                if(http_address.contains("127.0.0.1:" + port) || http_address.contains("localhost:" + port)){
                    selfNodeId = nodeId;
                    selfNodeName = nodeName;
                }
            }else{
                if(http_address.contains(netWorkHost + ":" + port)){
                    selfNodeId = nodeId;
                    selfNodeName = nodeName;
                }
            }
        }
    }else{
        log.error("elasticSearch json结果解析失败:{}",responseText);
    }
    switch (type){
        case 1:
            return selfNodeId;
        case 2:
            return selfNodeName;
        default:
            return "";
    }
}