Пример #1
0
  /**
   * 递归地将JSONArray转换为List对象,将JSONObject转换为Map对象
   *
   * @param obj
   * @return
   */
  private static Object parseJSONObj(Object obj) {

    Object result = null;
    if (obj == null) {
      // error
      return null;
    } else {
      if (obj instanceof JSONArray) {
        JSONArray arrayObj = (JSONArray) obj;
        List<Object> list = new ArrayList<Object>();
        for (Object element : arrayObj.toArray()) {
          list.add(JsonUtil.parseJSONObj(element));
        }
        result = list;
      } else if (obj instanceof JSONObject) {
        JSONObject jsonObj = (JSONObject) obj;
        Map<String, Object> map = new HashMap<String, Object>();
        for (Object key : jsonObj.keySet()) {
          map.put(key.toString(), JsonUtil.parseJSONObj(jsonObj.get(key.toString())));
        }
        return map;
      } else {
        result = obj;
      }
    }
    return result;
  }
Пример #2
0
 /**
  * @param jsonObject
  * @param foundFields
  * @param pathStack
  */
 public void visit(
     JSONObject jsonObject, HashMap<String, CandidateField> foundFields, Stack<Object> pathStack) {
   for (Object key : jsonObject.keySet()) {
     Object obj = jsonObject.get(key);
     pathStack.push(key);
     visitAny(obj, foundFields, pathStack);
     pathStack.pop();
   }
 }
Пример #3
0
 public static Map<String, Object> reflect(JSONObject json) {
   Map<String, Object> map = new HashMap<String, Object>();
   Set<?> keys = json.keySet();
   for (Object key : keys) {
     Object o = json.get(key);
     if (o instanceof JSONArray) map.put((String) key, reflect((JSONArray) o));
     else if (o instanceof JSONObject) map.put((String) key, reflect((JSONObject) o));
     else map.put((String) key, o);
   }
   return map;
 }
 // 根据json格式的字符串进行构造
 public QueryTranslateWeight(String basicHql, String condition) {
   this.basicQry = basicHql;
   if (!StringHelp.isEmpty(condition)) {
     JSONObject jsonObject = JSONObject.fromObject(condition);
     for (Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext(); ) {
       conditions.add(
           (Condition)
               JSONObject.toBean(
                   jsonObject.getJSONObject(iterator.next().toString()), Condition.class));
     }
   }
 }
Пример #5
0
 /**
  * Get the Key-Set
  *
  * @param resourceType
  * @return the Key-Set
  */
 public Set<?> returnPinYinKeys(ResourceType resourceType) {
   JSONObject jsonObject = null;
   switch (resourceType) {
     case LOADPINYINMAP:
       jsonObject = getPinYinSource();
       break;
     case LOADSOUNMARK:
       jsonObject = getSoundMarkSource();
       break;
     default:
       throw new ChinesePinYinException("Nonsupport 'ResourceType !'");
   }
   return jsonObject.keySet();
 }
Пример #6
0
 public static HttpParameter setParameterValue(String json) throws Exception {
   JSONObject jsonMap = JSONObject.fromObject(json);
   @SuppressWarnings("unchecked")
   Set<String> set = jsonMap.keySet();
   HttpParameter httpParameter = new HttpParameter();
   String value = "";
   for (String key : set) {
     value = jsonMap.get(key) == null ? "" : jsonMap.getString(key);
     if (StringUtils.isNotBlank(value)) {
       httpParameter.add(key, value);
     }
   }
   return httpParameter;
 }
Пример #7
0
  public static String getJSONuiLabel(HttpServletRequest request, HttpServletResponse response) {
    String requiredLabels = request.getParameter("requiredLabel");

    JSONObject uiLabelObject = null;
    if (UtilValidate.isNotEmpty(requiredLabels)) {
      // Transform JSON String to Object
      uiLabelObject = (JSONObject) JSONSerializer.toJSON(requiredLabels);
    }

    JSONArray jsonUiLabel = new JSONArray();
    Locale locale = request.getLocale();
    if (!uiLabelObject.isEmpty()) {
      Set<String> resourceSet = UtilGenerics.checkSet(uiLabelObject.keySet());
      // Iterate over the resource set
      // here we need a keySet because we don't now which label resource to load
      // the key set should have the size one, if greater or empty error should returned
      if (UtilValidate.isEmpty(resourceSet)) {
        Debug.logError("No resource and labels found", module);
        return "error";
      } else if (resourceSet.size() > 1) {
        Debug.logError(
            "More than one resource found, please use the method: getJSONuiLabelArray", module);
        return "error";
      }

      for (String resource : resourceSet) {
        String label = uiLabelObject.getString(resource);
        if (UtilValidate.isEmail(label)) {
          continue;
        }

        String receivedLabel = UtilProperties.getMessage(resource, label, locale);
        jsonUiLabel.add(receivedLabel);
      }
    }

    writeJSONtoResponse(jsonUiLabel, response);
    return "success";
  }
Пример #8
0
  public static String getJSONuiLabelArray(
      HttpServletRequest request, HttpServletResponse response) {
    String requiredLabels = request.getParameter("requiredLabels");

    JSONObject uiLabelObject = null;
    if (UtilValidate.isNotEmpty(requiredLabels)) {
      // Transform JSON String to Object
      uiLabelObject = (JSONObject) JSONSerializer.toJSON(requiredLabels);
    }

    JSONObject jsonUiLabel = new JSONObject();
    Locale locale = request.getLocale();
    if (!uiLabelObject.isEmpty()) {
      Set<String> resourceSet = UtilGenerics.checkSet(uiLabelObject.keySet());
      // Iterate over the resouce set
      for (String resource : resourceSet) {
        JSONArray labels = uiLabelObject.getJSONArray(resource);
        if (labels.isEmpty() || labels == null) {
          continue;
        }

        // Iterate over the uiLabel List
        Iterator<String> jsonLabelIterator = UtilGenerics.cast(labels.iterator());
        JSONArray resourceLabelList = new JSONArray();
        while (jsonLabelIterator.hasNext()) {
          String label = jsonLabelIterator.next();
          String receivedLabel = UtilProperties.getMessage(resource, label, locale);
          if (UtilValidate.isNotEmpty(receivedLabel)) {
            resourceLabelList.add(receivedLabel);
          }
        }
        jsonUiLabel.element(resource, resourceLabelList);
      }
    }

    writeJSONtoResponse(jsonUiLabel, response);
    return "success";
  }
Пример #9
0
 private void initialiserMap(Map<String, Integer> var, JSONObject json) {
   for (Object s : json.keySet()) {
     var.put(s.toString(), json.getInt(s.toString()));
   }
 }
Пример #10
0
  public Map<Date, AlipayBizPo> getAlipayBizPoByTime(Date start, Date end) {
    StringBuilder sb = new StringBuilder(url);
    try {
      sb.append("&")
          .append("key=" + URLEncoder.encode(key, "gbk"))
          .append("&startTime=")
          .append(URLEncoder.encode(format.format(start), "gbk"))
          .append("&endTime=")
          .append(URLEncoder.encode(format.format(end), "gbk"))
          .append("&")
          .append("descriptions=" + URLEncoder.encode(descriptions, "gbk"))
          .append("&")
          .append("fields=" + URLEncoder.encode(fields, "gbk"))
          .append("&")
          .append("expressions=" + URLEncoder.encode(expressions, "gbk"));
    } catch (UnsupportedEncodingException e) {
      logger.warn(
          "getAlipayBizPoByTime urlEncode exception,url=" + url + ",start=" + start + ",end=" + end,
          e);
    }

    HttpClient httpClient = new HttpClient();
    GetMethod getMethod = new GetMethod(sb.toString());

    try {
      // 使用系统提供的默认的恢复策略
      getMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      getMethod.addRequestHeader("Accept", "text/plain");
      // 设置超时时间
      httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
      httpClient.getHttpConnectionManager().getParams().setSoTimeout(5000);

      int statusCode = httpClient.executeMethod(getMethod);
      if (statusCode == HttpStatus.SC_OK) {
        String response = getMethod.getResponseBodyAsString(); // 读取内容
        JSONObject jsonObject = JSONObject.fromObject(response);

        JSONObject data = JSONObject.fromObject(jsonObject.get("datas"));
        Map<Date, AlipayBizPo> map = new HashMap<Date, AlipayBizPo>();
        Calendar c = Calendar.getInstance();
        for (Object key : data.keySet()) {
          JSONArray jsonArray = JSONArray.fromObject(data.get(key));
          AlipayBizPo alipayBizDo = getAlipayBizPoFromJsonArray(jsonArray);
          if (alipayBizDo == null) {
            continue;
          }
          c.setTimeInMillis(Long.parseLong(String.valueOf(key)));
          alipayBizDo.setTime(c.getTime());
          map.put(c.getTime(), alipayBizDo);
        }
        return map;
      } else {
        logger.warn("getAlipayBizPoByTime statusCode=" + statusCode + ",url=" + sb.toString());
      }
    } catch (Exception e) {
      logger.warn("getAlipayBizPoByTime exception,url=" + sb.toString(), e);
    } finally {
      getMethod.releaseConnection();
    }
    return null;
  }
  private void init(Schema input, JSONObject mapping, JSONObject output) {
    this.templateCache = null;
    this.groupsCache.clear();
    this.elementCache.clear();
    this.parentCache.clear();

    this.setInputSchema(input);

    // targetDefinitionFile = new File(output);
    if (targetDefinitionFile != null) {
      this.inputFileName = targetDefinitionFile.getParent() + "/input.xml";
    }

    if (mapping != null) {
      targetDefinition = mapping;
      JSONArray groups = mapping.getJSONArray("groups");
      for (int i = 0; i < groups.size(); i++) {
        JSONObject group = groups.getJSONObject(i);
        JSONObject contents = group.getJSONObject("contents");
        String element = group.getString("element");
        this.groupsCache.put(element, contents);
        this.cacheElements(contents);
      }
    } else if (output != null) {
      targetDefinition = output;
      JSONArray groups = output.getJSONArray("groups");
      for (int i = 0; i < groups.size(); i++) {
        JSONObject group = groups.getJSONObject(i);
        if (group.has("contents")) {
          JSONObject contents = group.getJSONObject("contents");
          String element = group.getString("element");
          this.groupsCache.put(element, contents);
          this.cacheElements(contents);
        }
      }
    }

    // initialise namespaces
    if (this.targetDefinition.has("namespaces")) {
      JSONObject object = this.targetDefinition.getJSONObject("namespaces");
      HashMap<String, String> map = new HashMap<String, String>();

      if (mapping != null) {
        for (Object entry : object.keySet()) {
          String key = (String) entry;
          String value = object.getString(key);
          map.put(value, key);
        }

      } else {
        for (Object entry : object.keySet()) {
          String key = (String) entry;
          String value = object.getString(key);
          map.put(key, value);
        }
      }

      this.getXSDParser().setNamespaces(map);
    }

    // initialise mapping definition
    this.targetDefinition = this.getTargetDefinition();

    // set namespaces
    JSONObject namespaces = new JSONObject();

    // xsd schema namespaces
    Map<String, String> acc = this.getXSDParser().getNamespaces();
    for (Entry<String, String> entry : acc.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();

      namespaces = namespaces.element(value, key);
    }

    this.targetDefinition = this.targetDefinition.element("namespaces", namespaces);

    // cache template
    JSONObject template = null;
    if (!this.targetDefinition.has("template")
        || this.targetDefinition.getJSONObject("template").isEmpty()) {
      template =
          this.buildTemplate(this.targetDefinition.getJSONObject("item").getString("element"));
      this.targetDefinition = this.targetDefinition.element("template", template);
    } else {
      template = targetDefinition.getJSONObject("template");
    }

    this.templateCache = template;
    this.cacheElements(this.templateCache);

    this.saveMappings();
  }
Пример #12
0
  public JSONObject httpPost(JSONObject requestJson, String url, String charset) {
    JSONObject resultJson = null;
    AbstractHttpClient httpclient = null;
    try {
      HttpPost httpRequest = new HttpPost(url);
      List<NameValuePair> params = new ArrayList<NameValuePair>();

      Iterator<?> it = requestJson.keySet().iterator();
      while (it.hasNext()) {
        Object nextObj = it.next();
        if (nextObj != null) {
          String name = nextObj.toString();
          params.add(new BasicNameValuePair(name, requestJson.getString(name)));
        }
      }

      HttpEntity httpentity = new UrlEncodedFormEntity(params, charset);
      httpRequest.setHeader("accept", "*/*");
      httpRequest.setHeader("connection", "Keep-Alive");
      httpRequest.setEntity(httpentity);

      // 设置超时 毫秒为单位,重连机制
      HttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
      HttpConnectionParams.setSoTimeout(httpParams, 45 * 1000);
      HttpConnectionParams.setTcpNoDelay(httpParams, true);
      HttpClientParams.setRedirecting(httpParams, false);

      httpclient = new DefaultHttpClient(httpParams);
      HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(3, true);
      httpclient.setHttpRequestRetryHandler(retryHandler);

      HttpResponse httpResponse = httpclient.execute(httpRequest);

      if (httpResponse.getStatusLine().getStatusCode()
          == HttpStatus.SC_OK) { // HttpStatus.SC_OK表示连接成功
        String httpResult = EntityUtils.toString(httpResponse.getEntity(), charset);

        resultJson = JSONUtils.getJsonFromString(httpResult);
        //				LogUtil.log(CT.LOG_CATEGORY_COMMUNICATION,"HttpApacheClient  httpPost 请求成功 --> " +
        // resultJson,
        //						null, LogUtilMg.LOG_INFO, CT.LOG_PATTERN_COMMUNICATION);
      } else {
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        LogUtil.log(
            CT.LOG_CATEGORY_COMMUNICATION,
            "HttpApacheClient httpPost返回相应码 --> " + statusCode,
            null,
            LogUtilMg.LOG_INFO,
            CT.LOG_PATTERN_COMMUNICATION);
      }
    } catch (Exception e) {
      LogUtil.log(
          CT.LOG_CATEGORY_ERR, "httpPost 请求失败 ", e, LogUtilMg.LOG_ERROR, CT.LOG_PATTERN_ERR);
    } finally {
      if (httpclient != null) {
        httpclient.getConnectionManager().shutdown();
      }
    }
    return resultJson;
  }