public void setXPathMapping(String xpath, String type, JSONObject target, int index) {
    JSONArray mappings = target.getJSONArray("mappings");
    JSONObject mapping = null;

    target.remove("warning");

    if (index > -1) {
      mapping = mappings.getJSONObject(index);
      mapping.put("type", "xpath");
      mapping.put("value", xpath);
    } else {
      mapping = new JSONObject();
      mapping.put("type", "xpath");
      mapping.put("value", xpath);
      mappings.add(mapping);
    }

    if (mapping != null) {
      if (target.has("type") && type != null && type.length() > 0) {
        if (target.getString("type").equalsIgnoreCase("dateUnion")) {
          if (!type.equalsIgnoreCase("date")
              && !type.equalsIgnoreCase("dateTime")
              && !type.equalsIgnoreCase("dateUnion")) {
            target.element("warning", type);
          }
        } else if (!target.getString("type").equalsIgnoreCase(type)
            || (mappings.size() > 1 && !type.equalsIgnoreCase("string"))) {
          target.element("warning", type);
        }
      }
    }

    // mappings.clear();
  }
  public JSONObject removeNode(String id) {
    JSONObject result = new JSONObject();
    JSONObject targetElement = this.elementCache.get(id);
    JSONObject parent = this.parentCache.get(id);

    JSONArray children = parent.getJSONArray("children");
    if (children != null && !children.isEmpty()) {
      int targetIndex = -1;
      int targetCount = 0;
      for (int i = 0; i < children.size(); i++) {
        JSONObject child = (JSONObject) children.get(i);
        if (child.getString("id").equals(id)) {
          targetIndex = i;
        }
      }

      if (targetIndex >= 0) {
        children.remove(targetIndex);
        this.elementCache.remove(id);
        this.parentCache.remove(id);
      }

      result = result.element("id", id);
    } else {
      result = result.element("error", "could not find target element");
    }

    this.saveMappings();

    return result;
  }
Пример #3
0
  public String showJson() {
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.registerJsonBeanProcessor(
        Sucursal.class,
        new JsonBeanProcessor() {

          @Override
          public JSONObject processBean(Object bean, JsonConfig jsonConfig) {
            Sucursal sucursal = (Sucursal) bean;
            JSONObject row = new JSONObject();
            row.element("id", sucursal.getId());

            JSONArray cell = new JSONArray();
            cell.add(sucursal.getNombre());
            cell.add(sucursal.getDireccion());
            cell.add(sucursal.getTelefono());

            row.element("cell", cell);

            return row;
          }
        });

    JSONObject rootObj = new JSONObject();
    JSONArray jrows = (JSONArray) JSONSerializer.toJSON(sucursales, jsonConfig);

    rootObj.element("rows", jrows);
    rootObj.element("records", sucursales.size());
    rootObj.element("total", Math.ceil((double) sucursales.size() / rows));
    rootObj.element("page", page);

    writeResponse(rootObj);
    return JSON;
  }
Пример #4
0
 public JSONObject jsonify() {
   JSONObject ret = super.jsonify();
   ret.element("type", "monthly");
   ret.element("dayOfWeek", getDayOfWeek());
   ret.element("weekOfMonth", getWeekOfMonth());
   return ret;
 }
 @ResponseBody
 @RequestMapping(value = "/getWxUsers", method = RequestMethod.POST)
 public String getWxUsers() {
   JSONObject userJson = new JSONObject();
   userJson.element("header", wxUserService.getWxUsersTitle());
   userJson.element("content", wxUserService.getWxUsersContent());
   return userJson.toString();
 }
  /* (non-Javadoc)
   * @see com.funambol.json.converter.Converter#toJSON(java.lang.Object)
   */
  public String toJSON(JsonAuthResponse jsonAuthResponse) {
    JSONObject jsonRoot = new JSONObject();
    JSONObject jsonData = new JSONObject();

    jsonData.element(JsonAuthResponseModel.SESSIONID.getValue(), jsonAuthResponse.getSessionID());
    jsonRoot.element(JsonAuthResponseModel.DATA.getValue(), jsonData);

    return jsonRoot.toString();
  }
  public JSONObject getDocumentation(String id) {
    JSONObject result = new JSONObject();
    JSONObject targetElement = this.elementCache.get(id);

    String key = targetElement.getString("name");
    result.element("title", key);
    result.element("documentation", this.getDocumentationForKey(key));

    return result;
  }
Пример #8
0
  public static void appadd() {

    try {
      // 创建连接
      URL url = new URL(ADD_URL);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setDoOutput(true);
      connection.setDoInput(true);
      connection.setRequestMethod("POST");
      connection.setUseCaches(false);
      connection.setInstanceFollowRedirects(true);
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

      connection.connect();

      // POST请求
      DataOutputStream out = new DataOutputStream(connection.getOutputStream());
      JSONObject obj = new JSONObject();
      obj.element("app_name", "asdf");
      obj.element("app_ip", "10.21.243.234");
      obj.element("app_port", 8080);
      obj.element("app_type", "001");
      obj.element("app_area", "asd");

      out.writeBytes(obj.toString());
      out.flush();
      out.close();

      // 读取响应
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String lines;
      StringBuffer sb = new StringBuffer("");
      while ((lines = reader.readLine()) != null) {
        lines = new String(lines.getBytes(), "utf-8");
        sb.append(lines);
      }
      System.out.println(sb);
      reader.close();
      // 断开连接
      connection.disconnect();
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Пример #9
0
  public String getByID() throws Exception {
    System.out.println("hello");
    System.out.println("通过ID查找对象");
    String cid = this.request.getParameter("chID");
    int id = Integer.parseInt(cid);
    System.out.println(id);
    Channel cen = (Channel) channelDao.findObjectById(Channel.class, id);
    System.out.println(cen);
    ChannelVo vo = new ChannelVo();
    BeanUtils.copyProperties(vo, cen);
    System.out.println(vo);
    JSONObject obj = new JSONObject();
    System.out.println(cen.getId());
    if (cen.getParentChannel() == null) {

    } else {
      vo.setParentChannel(cen.getParentChannel().getId());
      vo.setParentName(cen.getParentChannel().getName());
    }

    obj.element("chan", vo);
    PrintWriter out = this.response.getWriter();
    out.write(obj.toString());
    System.out.println(obj.toString());
    out.flush();
    return null;
  }
  public JSONObject mappingElementsUsedInMapping() {
    JSONObject result = new JSONObject();
    JSONArray used = new JSONArray();
    JSONArray not_used = new JSONArray();
    JSONArray parent_used = new JSONArray();

    JSONObject mappings = this.getTargetDefinition();
    Map<String, MappingElement> map = this.inputSchema.getMap();
    Collection<String> list = MappingSummary.getMappedXPathList(mappings);

    Iterator<String> keys = map.keySet().iterator();

    while (keys.hasNext()) {
      String id = keys.next();
      String xpath = map.get(id).getXPath();
      for (String xp : list) {
        if (xp.length() > xpath.length() && xp.indexOf(xpath) > -1) {
          parent_used.add(id);
          break;
        }
      }
      if (list.contains(xpath)) {
        used.add(id);

      } else {
        not_used.add(id);
      }
    }
    return result
        .element("used", used)
        .element("not_used", not_used)
        .element("parent_used", parent_used);
  }
Пример #11
0
  private static JSONObject recursive(Element parentElement) {
    List<Element> childElements = parentElement.elements();

    JSONObject jsonObject = new JSONObject();
    for (Element childElement : childElements) {

      String attributeValue = childElement.attributeValue(CLASS);
      if (LIST_CLASS_ATTRIBUTE.contains(attributeValue)) {
        List<Element> elements = childElement.elements();

        JSONArray jsonArray = new JSONArray();
        for (Element element : elements) {
          jsonArray.add(recursive(element));
        }
        jsonObject.element(childElement.getName(), jsonArray);
      } else {
        if (!childElement.elements().isEmpty()) {
          JSONObject recursive = recursive(childElement);
          jsonObject.accumulate(childElement.getName(), recursive);
        } else {
          jsonObject.accumulate(childElement.getName(), childElement.getTextTrim());
        }
      }
    }
    return jsonObject;
  }
 /**
  * Check whether the "incorrect version" msg should be displayed, and returns what the currently
  * configured version is, in a json.
  */
 public void doVersionCheck(StaplerRequest req, StaplerResponse rsp, @QueryParameter String url)
     throws IOException {
   rsp.setContentType("text/plain;charset=UTF-8");
   JSONObject versionJSON = new JSONObject();
   String error_display_style = "none";
   if (!isGoodCNVersion(url)) {
     error_display_style = "inline";
   }
   versionJSON.element("error_display_style", error_display_style);
   VersionNumber version = getVersion(url);
   if (version != null) {
     versionJSON.element("version", version.toString());
   } else {
     versionJSON.element("version", "unknown");
   }
   rsp.getWriter().print(versionJSON.toString());
 }
  public JSONObject previewTransform() {
    JSONObject preview = new JSONObject();

    XSLTGenerator xslt = new XSLTGenerator();

    String templateMatch = "/";
    String mappings = this.getTargetDefinition().toString();

    // System.out.println("First 1000 caracters mappings = " + mappings.substring(0, 1000));
    xslt.setTemplateMatch(templateMatch);
    System.out.println("**** XSLT  = " + xslt.generateFromString(mappings));

    String xsl = XMLFormatter.format(xslt.generateFromString(mappings));

    preview.element("json", "\n" + mappings);
    preview.element("xsl", xsl);

    return preview;
  }
Пример #14
0
 private PersistenceManager doJob(PersistenceManager pm, Object req) {
   JSONObject response = null;
   if (req instanceof AccessLog) {
     executeInsert(pm, (AccessLog) req);
     return pm;
   }
   RequestInfo requestInfo = (RequestInfo) req;
   switch (requestInfo.type) {
     case TYPE_QUERY_DELTE:
       requestInfo.ids = queryAccessLog(pm, requestInfo.query);
     case TYPE_LIST_DELTE:
       response = new JSONObject();
       response.element("command", "listDelete");
       response.element("result", "success");
       executeDelete(pm, requestInfo.ids);
       break;
     case TYPE_QUERY_EXPORT:
       requestInfo.ids = queryAccessLog(pm, requestInfo.query);
     case TYPE_LIST_EXPORT:
       try {
         File exportFile = executeExport(pm, requestInfo.ids);
         Blob exportBlob = Blob.create(exportFile, true);
         requestInfo.peer.download(exportBlob);
       } catch (IOException e) {
         response = new JSONObject();
         response.element("command", "listExport");
         response.element("result", "fail");
         logger.warn("failt to export", e);
       } catch (Throwable t) {
         response = new JSONObject();
         response.element("command", "listExport");
         response.element("result", "fail");
         logger.error("failt to export", t);
       }
       break;
     case TYPE_IMPORT:
       try {
         pm = null;
         executeImport(requestInfo.importBlob, requestInfo.peer);
       } catch (IOException e) {
         logger.warn("failt to import", e);
         response = new JSONObject();
         response.element("command", "import");
         response.element("result", "fail");
       }
       break;
   }
   if (requestInfo.peer != null && response != null) {
     requestInfo.peer.message(response);
   }
   return pm;
 }
  public JSONObject setFixed(JSONObject object, boolean fixed) {
    if (fixed) {
      if (!object.has("fixed")) {
        object = object.element("fixed", "");
      }
    } else {
      if (object.has("fixed")) {
        object.remove("fixed");
      }
    }

    return object;
  }
  public JSONObject mappingSummary() {
    JSONObject object = new JSONObject();
    //		DataUpload du = DB.getDataUploadDAO().findById(Long.parseLong(this.dataUploadId), false);
    String mappings = this.getTargetDefinition().toString();

    Collection<String> missing = MappingSummary.getMissingMappings(mappings);
    //		Collection<String> invalid = MappingSummary.getInvalidXPaths(du, mappings);
    Collection<String> invalid = new ArrayList<String>();
    Map<String, String> mapped = MappingSummary.getMappedItems(mappings);
    //		Map<String, String> summary = MappingSummary.getSummary(mappings);
    //		JSONObject tree_usage = this.mappingElementsUsedInMapping();

    object = object.element("missing", missing);
    object = object.element("invalid", invalid);
    object = object.element("mapped", mapped);
    //		object = object.element("used", tree_usage.getJSONArray("used"));
    //		object = object.element("not_used", tree_usage.getJSONArray("not_used"));
    // object = object.element("summary", summary);

    // log.debug(object);

    return object;
  }
  private void addConditionClause(JSONArray clauses, String path, boolean complex) {
    JSONObject clause = new JSONObject();

    if (complex) {
      clause.element("logicalop", "AND");
      JSONArray array = new JSONArray();
      array.add(new JSONObject());
      clause.element("clauses", array);
    }

    if (path.length() == 0) {
      clauses.add(clause);
    } else {
      if (path.contains(".")) {
        String[] parts = path.split("\\.", 2);
        System.out.println("'" + path + "' '" + parts[0] + "' '" + parts[1] + "'");
        int index = Integer.parseInt(parts[0]);
        addConditionClause(clauses.getJSONObject(index), parts[1], complex);
      } else {
        int index = Integer.parseInt(path);
        addConditionClause(clauses.getJSONObject(index), "", complex);
      }
    }
  }
Пример #18
0
  public JSONObject getJSON(JSONObject jo) {
    Problem p = null;
    try {
      p = ProblemMgr.getProblem(getProbId());
    } catch (SQLException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }

    if (p != null && p.isQuickAuth() && p.isMultiChoice()) {
      jo.element(letter, val);
    }

    return jo;
  }
 public String getConfig(JSONObject jsonObject) {
   String areaId = jsonObject.getString("areaId");
   WorldServer worldServer = worldServerDao.get("areaid", areaId);
   JSONObject json = new JSONObject();
   json.element("port", worldServer.getPort());
   json.element("adminport", worldServer.getAdminport());
   json.element("publicip", worldServer.getPublicip());
   json.element("httpport", worldServer.getHttpport());
   json.element("authport", worldServer.getAuthport());
   json.element("areaid", worldServer.getAreaid());
   json.element("machinecode", worldServer.getMachinecode());
   json.element("serverType", worldServer.getServerType());
   return json.toString();
 }
Пример #20
0
 @Override
 public void onBufferEnd(Object userContext) {
   endBuffer(currentZe);
   Iterator<String> itr = refDigests.iterator();
   while (itr.hasNext()) {
     StoreManager.ref(itr.next());
   }
   itr = addDigests.iterator();
   while (itr.hasNext()) {
     StoreManager.unref(itr.next());
   }
   JSONObject response = new JSONObject();
   response.element("command", "import");
   response.element("result", "success");
   peer.message(response);
 }
  // 列出此课程中所有学生
  private void list(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    int courseId =
        Integer.parseInt((String) request.getSession().getAttribute(ServletUtil.COURSE_ID));
    List<Student> students = studentService.getStudentsInTheCourse(courseId);

    if (students != null && students.size() > 0) {
      JSONObject jo = new JSONObject();
      jo.element("students", students);

      PrintWriter writer = response.getWriter();
      writer.write(jo.toString());
      writer.close();
    } else {
      // 此课程中没有学生
    }
  }
 private void setConditionClauseKey(JSONObject condition, String path, String key, String value) {
   if (path.length() == 0) {
     if (condition.has(key)) {
       condition.remove(key);
     }
     condition.element(key, value);
   } else {
     if (condition.has("clauses")) {
       JSONArray clauses = condition.getJSONArray("clauses");
       if (path.contains(".")) {
         String[] parts = path.split("\\.", 2);
         int index = Integer.parseInt(parts[0]);
         setConditionClauseKey(clauses.getJSONObject(index), parts[1], key, value);
       } else {
         int index = Integer.parseInt(path);
         setConditionClauseKey(clauses.getJSONObject(index), "", key, value);
       }
     }
   }
 }
  /**
   * Retrieve the details about a product which exists on the Wish platform. You must have the
   * unique product Id that was returned upon product creation.
   *
   * @param productId id
   * @param apiKey apiKey
   * @return JSONObject
   */
  public JSONObject retrieveProductVariationJSONObject(String productId, String apiKey) {
    String url =
        PropertiesUtil.getRetrieveProductVariation()
            .replace("product_id", productId)
            .replace("an_example_api_key", apiKey);
    // 发起POST请求
    JSONObject jsonObject = CommonUtil.httpsRequest(url, "GET", null);

    if (null != jsonObject) {
      int code = jsonObject.getInt("code");
      if (0 == code) {
        return jsonObject;
      } else {
        JSONObject errorJsonObject = new JSONObject();
        return errorJsonObject.element("message", jsonObject.getString("message"));
      }
    } else {
      return null;
    }
  }
  public String serializeSystemData(SystemData systemData) {
    JSONObject json = new JSONObject();

    json.element("apiKey", systemData.getApiKey());
    json.element("osArch", systemData.getOsArch());
    json.element("osName", systemData.getOsName());
    json.element("osVersion", systemData.getOsVersion());
    json.element("javaVendor", systemData.getJavaVendor());
    json.element("javaVersion", systemData.getJavaVersion());
    json.element("type", systemData.getType());

    json.elementOpt("serverVersion", systemData.getServerVersion().orNull());

    return json.toString();
  }
Пример #25
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";
  }
  public JSONObject initComplexCondition(String id) {
    String defaultLogicalOp = "AND";
    boolean conditionInit = false;

    JSONObject targetElement = this.elementCache.get(id);

    if (targetElement.has("condition")) {
      JSONObject condition = targetElement.getJSONObject("condition");
      if (!condition.has("logicalop")) {
        condition.element("logicalop", defaultLogicalOp);
        JSONArray clauses = new JSONArray();
        JSONObject clause = new JSONObject();
        if (condition.has("xpath") && condition.getString("xpath").length() > 0) {
          clause.element("xpath", condition.getString("xpath"));
        }
        if (condition.has("value") && condition.getString("value").length() > 0) {
          clause.element("value", condition.getString("value"));
        }
        if (condition.has("relationalop")) {
          clause.element("relationalop", condition.getString("="));
        }
        clauses.add(clause);
        condition.element("clauses", clauses);

        conditionInit = true;
      }
    } else {
      targetElement.element(
          "condition",
          new JSONObject()
              .element("logicalop", defaultLogicalOp)
              .element("clauses", new JSONArray()));
      conditionInit = true;
    }

    if (conditionInit) {
      saveMappings();
    }

    return targetElement.getJSONObject("condition");
  }
  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();
  }