示例#1
0
  public static void parseSortAndFilter(BasePageDTO pageDto) throws Exception {
    if (!ClassTool.isNullObj(pageDto)) {
      String sort = pageDto.getSort();
      if (!StringTool.isEmpty(sort) && sort.startsWith("[{") && sort.endsWith("}]")) {
        sort = StringTool.trimSpecialCharactor(sort, "[");
        sort = StringTool.trimSpecialCharactor(sort, "]");
        JSONObject jsonObj = JSONObject.fromObject(sort);
        sort = (String) jsonObj.get("property");
        String dir = (String) jsonObj.get("direction");

        pageDto.setSort(sort);
        pageDto.setDir(dir);
      }

      String filter = pageDto.getFilter();
      if (!StringTool.isEmpty(filter) && filter.startsWith("[{") && filter.endsWith("}]")) {
        filter = StringTool.trimSpecialCharactor(filter, "[");
        filter = StringTool.trimSpecialCharactor(filter, "]");
        JSONObject jsonObj = JSONObject.fromObject(filter);
        filter = (String) jsonObj.get("property");
        String filterValue = (String) jsonObj.get("value");

        pageDto.setFilter(filter);
        pageDto.setFilterValue(filterValue);
      }

      pageDto.setSort(StringTool.translateToDBColumn(pageDto.getSort()));
      pageDto.setFilter(StringTool.translateToDBColumn(pageDto.getFilter()));
    } else {
    }
  }
示例#2
0
  /**
   * <校验淘宝订单> @创建时间 2015-4-23 下午1:53:38  @创建人:胡翔宇
   *
   * @param taobaoSid
   * @return
   * @throws Exception
   * @see [类、类#方法、类#成员]
   */
  public boolean checkTaoBaoOrderIsPayed(String taobaoSid) {

    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("userName", USERNAME));
    params.add(new BasicNameValuePair("taobaoSid", taobaoSid));
    // b782a88ea4d9cdf786ba0e1e1638258f
    String sign = taobaoSid + USERNAME + KEY;
    sign = MD5.doit(sign.toLowerCase());
    params.add(new BasicNameValuePair("sign", sign));
    try {
      JSONObject obj = postExecute(params);

      if (obj.get("data") != null) {
        JSONObject jsonDataObject = (JSONObject) obj.get("data");

        if (jsonDataObject.get("status") != null && jsonDataObject.get("status").equals("PAY")) {
          return true;
        } else return false;
      } else {
        return false;
      }
    } catch (Exception e) {
      logger.error("获取淘宝订单状态失败", e);
    }
    return false;
  }
示例#3
0
文件: GetHaoYouLB.java 项目: weiyk/ES
 public List<List> getHaoYou(String yhbh, String key) {
   web = new HttpWebs();
   web.init();
   list = new ArrayList<List>();
   GetUrl getUrl = new GetUrl();
   String url = getUrl.getUrl("findFriend_url");
   Map<String, String> parmMap = new HashMap<String, String>();
   parmMap.put("uid", yhbh);
   parmMap.put("key", key);
   String sb = web.callByGet(url, parmMap);
   JSONArray array = JSONArray.fromObject("[" + Base64Util.decrypt(sb) + "]");
   JSONObject jsonObject = array.getJSONObject(0);
   String msgCode = jsonObject.get("msgCode").toString();
   try {
     if ("1".equals(msgCode)) {
       String uids = jsonObject.get("uids").toString();
       String[] uidlist = uids.split(",");
       for (int i = 0; i < uidlist.length; i++) {
         String uid = uidlist[i];
         printHtml(uid);
       }
     }
     return list;
   } catch (SQLException e) {
     e.printStackTrace();
     return list;
   }
 }
示例#4
0
  public void pick() throws IOException {
    while (true) {
      pickUrl =
          String.format(
              "http://web.im.baidu.com/pick?v=30&session=&source=22&type=23&flag=1&seq=%d&ack=%s&guid=%s",
              sequence, ack, guid);

      HttpGet getRequest = new HttpGet(pickUrl);
      HttpResponse pickRes = httpClient.execute(getRequest);
      String entityStr = EntityUtils.toString(pickRes.getEntity());
      System.out.println("Pick result:" + entityStr);
      EntityUtils.consume(pickRes.getEntity());

      JSONObject jsonObject = JSONObject.fromObject(entityStr);
      JSONObject content = jsonObject.getJSONObject("content");
      if (content != null && content.get("ack") != null) {
        ack = (String) content.get("ack");
        JSONArray fields = content.getJSONArray("fields");
        JSONObject o = fields.getJSONObject(0);
        String fromUser = (String) o.get("from");
        System.out.println("++++Message from: " + fromUser);
      }
      updateSequence();

      if (sequence > 4) {
        break;
      }
    }
  }
示例#5
0
  /**
   * 接收解密方法:发送不加密,接收解密
   *
   * @param json
   * @param url
   * @param privatekey
   * @param publickey
   * @return
   * @throws Exception
   */
  public static String sendRequest(String json, String url, String privatekey, String publickey)
      throws Exception {

    try {

      logger.debug("----------------sendRequest--------------------");
      logger.debug("----->>>>>发送url:" + url);
      logger.debug("----->>>>>发送json:" + json);

      // 发送
      json = sendPost(url, setParameterValue(json));

      JSONObject jsonMap = JSONObject.fromObject(json);

      String merchantaccount =
          jsonMap.get("merchantcode") != null
              ? jsonMap.getString("merchantcode")
              : jsonMap.get("merchantaccount") != null ? jsonMap.getString("merchantaccount") : "";

      // 解密
      json = decodeParamJson(json, privatekey, publickey, merchantaccount);

      logger.debug("----->>>>>返回内容:" + json);
      logger.debug("----------------sendRequest--------------------");

      return json;

    } catch (Exception e) {
      logger.error("调用接口错误!", e);
      throw new Exception(e.getLocalizedMessage());
    }
  }
示例#6
0
  /**
   * 获取jsapi_ticket
   *
   * @param accesstoken
   * @return
   */
  public static void getjsTicket(String accesstoken) {

    String jsapi_ticketUrl =
        "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
    String url = jsapi_ticketUrl.replace("ACCESS_TOKEN", accesstoken);
    System.out.println("查看js_url:" + url);

    try {
      if (jsTicket.equals("")) {
        String result = HttpUtil.getInstance().execGet(url);
        logger.debug("result==" + result);

        JSONObject obj = JSONObject.fromObject(result);

        if (obj.containsKey("ticket")) {
          jsTicket = obj.get("ticket").toString();
          System.out.println("ticket====" + obj.get("ticket"));
        } else {
          getAccessToken();
          getjsTicket(accessToken);
          return;
        }
      } else {

      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * 查询所有分组
   *
   * @return 分组列表
   */
  public static List<UserGroup> getGroup() {

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

    String url = GET_GROUP_URL.replace("ACCESS_TOKEN", WeixinUtil.getToken());

    JSONObject jsonObject = WeixinUtil.httpsRequest(url, "POST", null);
    if (null != jsonObject) {
      if (StringUtil.isNotEmpty(jsonObject.get("errcode")) && jsonObject.get("errcode") != "0") {
        log.error(
            "获取分组失败,errcode:"
                + jsonObject.getInt("errcode")
                + ",errmsg:"
                + jsonObject.getString("errmsg"));
      } else {
        JSONArray arr = jsonObject.getJSONArray("groups");
        for (int i = 0; i < arr.size(); i++) {
          UserGroup group = new UserGroup();
          group.setId(arr.getJSONObject(i).getString("id"));
          group.setName(arr.getJSONObject(i).getString("name"));
          group.setCount(arr.getJSONObject(i).getInt("count"));
          list.add(group);
        }
      }
    }
    return list;
  }
示例#8
0
  public static int getPoiCount(String region, String POI) throws Exception {
    int count = 0;
    String url =
        "http://api.map.baidu.com/place/v2/search?q="
            + POI
            + "&region="
            + region
            + "&page_num=0&output=json&ak=fvFz2VvvNxePX1xY4QblStYl";
    String json = null;
    JSONObject obj = null;
    while (true) {
      try {
        json = loadJSON(url);
        obj = JSONObject.fromObject(json);

      } catch (net.sf.json.JSONException e) {
        continue;
      }
      break;
    }
    if (obj.get("status").toString().equals("0")) {
      count = Integer.parseInt(obj.get("total").toString());
    } else {
      throw new Exception("未找到匹配地点信息");
    }
    return count;
  }
 /**
  * 保存鹏元返回的数据
  *
  * @param queryType
  * @param jsonObject
  */
 public void savePyInfos(
     QueryConditionEntity queryConditionEntity, JSONObject jsonObject, ResultEntity resultEntity) {
   QueryParameterEntity queryParameterEntity = queryConditionEntity.getQueryParas();
   String batchNo = queryParameterEntity.getSendCode();
   String queryType = queryConditionEntity.getQueryType();
   String createDate = DateUtil.getDateTime("yyyyMMddHHmmss", new Date());
   if (queryType.equals(PyConstants.PY_QUERYTYPE_90035)) {
     List<CisCropExtendInfo> cisCropExtendInfos = new ArrayList<CisCropExtendInfo>();
     JSONArray jsonArray = (JSONArray) jsonObject.get("manageContactInfosList");
     if (null != jsonArray) {
       for (Object jsonOb : jsonArray) {
         JSONObject jsonObject2 = (JSONObject) jsonOb;
         CisCropExtendInfo a = (CisCropExtendInfo) getBean(jsonObject2, CisCropExtendInfo.class);
         a.setCorpName(queryParameterEntity.getCorpName());
         a.setBatchNo(batchNo);
         a.setCreationDate(createDate);
         cisCropExtendInfos.add(a);
       }
       resultEntity.setReturnCode(PyConstants.PY_RECODE_001);
       cisCropExtendInfoService.saveCropExtendInfos(cisCropExtendInfos);
     }
   } else if (queryType.equals(PyConstants.PY_QUERYTYPE_21603)) {
     List<CisTelCheckInfo> cisTelCheckInfos = new ArrayList<CisTelCheckInfo>();
     JSONArray jsonArray = (JSONArray) jsonObject.get("telCheckInfos");
     if (null != jsonArray) {
       for (Object jsonOb : jsonArray) {
         JSONObject jsonObject2 = (JSONObject) jsonOb;
         CisTelCheckInfo cisTelCheckInfo =
             (CisTelCheckInfo) getBean(jsonObject2, CisTelCheckInfo.class);
         cisTelCheckInfo.setTelePhone(queryParameterEntity.getTelephone());
         cisTelCheckInfo.setBatchNo(batchNo);
         cisTelCheckInfo.setCreationDate(createDate);
         cisTelCheckInfos.add(cisTelCheckInfo);
       }
       resultEntity.setReturnCode(PyConstants.PY_RECODE_001);
       cisTelCheckInfoDao.saveTelCheckInfos(cisTelCheckInfos);
     }
   } else if (queryType.equals(PyConstants.PY_QUERYTYPE_21303)) {
     List<CisArtificialPersonInfo> cisArtificialPersonInfos =
         new ArrayList<CisArtificialPersonInfo>();
     JSONArray jsonArray = (JSONArray) jsonObject.get("artificialNationalInfoList");
     if (null != jsonArray) {
       for (Object jsonOb : jsonArray) {
         JSONObject jsonObject2 = (JSONObject) jsonOb;
         CisArtificialPersonInfo a =
             (CisArtificialPersonInfo) getBean(jsonObject2, CisArtificialPersonInfo.class);
         a.setBatchNo(batchNo);
         a.setIdType(queryParameterEntity.getIdType());
         a.setIdNumber(queryParameterEntity.getIdNumber());
         a.setPersonName(queryParameterEntity.getPersonName());
         a.setCreationDate(createDate);
         cisArtificialPersonInfos.add(a);
       }
       resultEntity.setReturnCode(PyConstants.PY_RECODE_001);
       cisArtificialPersonInfoService.saveArtificialPersonInfos(cisArtificialPersonInfos);
     }
   }
 }
示例#10
0
  @Test
  public void testGetAsJSON() throws Exception {
    JSON json = getAsJSON("/rest/workspaces/sf/wmslayers/states.json");
    JSONObject featureType = ((JSONObject) json).getJSONObject("wmsLayer");
    assertNotNull(featureType);

    assertEquals("states", featureType.get("name"));
    assertEquals(CRS.decode("EPSG:4326").toWKT(), featureType.get("nativeCRS"));
    assertEquals("EPSG:4326", featureType.get("srs"));
  }
示例#11
0
 public static String getStrByKey(String mapjson, String key) {
   // TODO Auto-generated method stub
   String str = "";
   if (mapjson != null && !"".equals(mapjson)) {
     JSONObject j = JSONObject.fromObject(mapjson);
     if (j.get(key) != null) {
       str = j.get(key).toString();
     }
   }
   return str;
 }
  @RequestMapping(value = "/generateHistoryFile", method = RequestMethod.POST)
  @ResponseBody
  public void generateHistoryFile(HttpServletRequest request, HttpServletResponse response) {
    String foldername = request.getParameter("foldername");
    String reqstate = request.getParameter("reqstate");
    if (reqstate.equalsIgnoreCase("success")) {
      JSONArray ja = JSONArray.fromObject(request.getParameter("testresultitemcollectionjson"));
      for (int i = 0; i < ja.length(); i++) {
        TestResultItem tri = new TestResultItem();
        try {
          JSONObject itemobj = ja.getJSONObject(i);
          String result = itemobj.getString("result");
          tri.setResult(result);
          if (!result.equals(TestStatus.exception)) {
            Set<CheckPointItem> cps = new HashSet<CheckPointItem>();

            tri.setTime(itemobj.getString("time"));
            tri.setRequestInfo(itemobj.getString("requestInfo"));
            tri.setResponseInfo(itemobj.getString("responseInfo"));
            tri.setDuration(itemobj.getString("duration"));

            Object[] callbackarr = JSONArray.fromObject(itemobj.get("callback")).toArray();
            tri.setCallback(new HashSet(Arrays.asList(callbackarr)));
            JSONArray jsonarr = JSONArray.fromObject(itemobj.get("checkPoint"));
            for (int j = 0; j < jsonarr.length(); j++) {
              CheckPointItem item =
                  (CheckPointItem)
                      JSONObject.toBean(jsonarr.getJSONObject(j), CheckPointItem.class);
              cps.add(item);
            }
            tri.setCheckPoint(cps);
          } else tri.setComment(itemobj.getString("comment"));
        } catch (Exception e) {
          tri.setDuration("");
          tri.setResult(TestStatus.exception);
          tri.setComment(e.getClass().toString() + ": " + e.getMessage());
        } finally {
          testExecuteService.generateHistoryFile(foldername, tri);
        }
      }
    } else {
      TestResultItem tri = new TestResultItem();
      tri.setDuration("");
      tri.setResult(TestStatus.exception);
      String comment = "";
      String json = request.getParameter("obj");
      if (json.startsWith("{") && json.endsWith("}"))
        comment = JSONObject.fromObject(json).get("comment").toString();
      else if (json.startsWith("[") && json.endsWith("]"))
        comment = JSONArray.fromObject(json).getJSONObject(0).get("comment").toString();
      tri.setComment(comment);
      testExecuteService.generateHistoryFile(foldername, tri);
    }
  }
示例#13
0
 /**
  * Private method helps to generate the viewport of the given JSONObject
  *
  * @param data the JSONObject
  * @return the viewport for parsing the bound, null if the parsing fails.
  */
 private static JSONObject getViewport(JSONObject data) {
   try {
     JSONArray results = data.getJSONArray("results");
     JSONObject address = results.getJSONObject(0);
     JSONObject geometry = (JSONObject) address.get("geometry");
     JSONObject viewport = (JSONObject) geometry.get("viewport");
     return viewport;
   } catch (NullPointerException npe) {
     npe.printStackTrace();
   }
   return null;
 }
示例#14
0
 /**
  * Private method helps to generate the location of the given JSONObject
  *
  * @param data the JSONObject
  * @return the viewport for parsing the bound, null if the parsing fails.
  */
 private static JSONObject getLocationObj(JSONObject data) {
   try {
     JSONArray results = data.getJSONArray("results");
     JSONObject address = results.getJSONObject(0);
     JSONObject geometry = (JSONObject) address.get("geometry");
     JSONObject location = (JSONObject) geometry.get("location");
     return location;
   } catch (NullPointerException npe) {
     npe.printStackTrace();
   }
   return null;
 }
示例#15
0
    public Response(WS.HttpResponse response) {
      this.httpResponse = response;

      JSONObject queryJson = JSONObject.fromObject(response.getString());
      if (queryJson != null) {
        this.accessToken = queryJson.get("access_token").toString();
        this.uid = queryJson.get("uid").toString();
        this.error = null;
      } else {
        this.accessToken = null;
        this.uid = null;
        this.error = Error.oauth2(response);
      }
    }
示例#16
0
  @Test
  public void testPutAsJSON() throws Exception {
    String inputJson =
        "{'settings':{'workspace':{'name':'sf'},"
            + "'contact':{'addressCity':'Cairo','addressCountry':'Egypt','addressType':'Work',"
            + "'contactEmail':'*****@*****.**','contactOrganization':'The ancient geographes INC',"
            + "'contactPerson':'Claudius Ptolomaeus','contactPosition':'Chief geographer'},"
            + "'charset':'UTF-8','numDecimals':8,'onlineResource':'http://geoserver2.org',"
            + "'proxyBaseUrl':'http://proxy2.url','verbose':true,'verboseExceptions':'true'}}";

    MockHttpServletResponse response =
        putAsServletResponse("/rest/workspaces/sf/settings", inputJson, "text/json");
    assertEquals(200, response.getStatusCode());
    JSON jsonMod = getAsJSON("/rest/workspaces/sf/settings.json");
    JSONObject jsonObject = (JSONObject) jsonMod;
    assertNotNull(jsonObject);
    JSONObject settings = jsonObject.getJSONObject("settings");
    assertNotNull(settings);
    JSONObject workspace = settings.getJSONObject("workspace");
    assertNotNull(workspace);
    assertEquals("sf", workspace.get("name"));
    assertEquals("8", settings.get("numDecimals").toString().trim());
    assertEquals("http://geoserver2.org", settings.get("onlineResource"));
    assertEquals("http://proxy2.url", settings.get("proxyBaseUrl"));
    assertEquals("true", settings.get("verbose").toString().trim());
    assertEquals("true", settings.get("verboseExceptions").toString().trim());
    JSONObject contact = settings.getJSONObject("contact");
    assertNotNull(contact);
    assertEquals("Claudius Ptolomaeus", contact.get("contactPerson"));
    assertEquals("Cairo", contact.get("addressCity"));
  }
示例#17
0
 @Test
 public void testCreateAsJSON() throws Exception {
   GeoServer geoServer = getGeoServer();
   geoServer.remove(geoServer.getSettings(geoServer.getCatalog().getWorkspaceByName("sf")));
   String json =
       "{'settings':{'workspace':{'name':'sf'},"
           + "'contact':{'addressCity':'Alexandria','addressCountry':'Egypt','addressType':'Work',"
           + "'contactEmail':'*****@*****.**','contactOrganization':'The ancient geographes INC',"
           + "'contactPerson':'Claudius Ptolomaeus','contactPosition':'Chief geographer'},"
           + "'charset':'UTF-8','numDecimals':10,'onlineResource':'http://geoserver.org',"
           + "'proxyBaseUrl':'http://proxy.url','verbose':false,'verboseExceptions':'true'}}";
   MockHttpServletResponse response =
       putAsServletResponse("/rest/workspaces/sf/settings", json, "text/json");
   assertEquals(200, response.getStatusCode());
   JSON jsonMod = getAsJSON("/rest/workspaces/sf/settings.json");
   JSONObject jsonObject = (JSONObject) jsonMod;
   assertNotNull(jsonObject);
   JSONObject settings = jsonObject.getJSONObject("settings");
   assertNotNull(settings);
   JSONObject workspace = settings.getJSONObject("workspace");
   assertNotNull(workspace);
   assertEquals("sf", workspace.get("name"));
   assertEquals("10", settings.get("numDecimals").toString().trim());
   assertEquals("http://geoserver.org", settings.get("onlineResource"));
   assertEquals("http://proxy.url", settings.get("proxyBaseUrl"));
   JSONObject contact = settings.getJSONObject("contact");
   assertEquals("Claudius Ptolomaeus", contact.get("contactPerson"));
   assertEquals("The ancient geographes INC", contact.get("contactOrganization"));
   assertEquals("Work", contact.get("addressType"));
   assertEquals("*****@*****.**", contact.get("contactEmail"));
 }
示例#18
0
 /** @author 目录排序 */
 @ResponseBody
 @RequestMapping(value = "/sort.json", method = RequestMethod.POST)
 public JsonVo<String> delete(@RequestParam(value = "sortJson") String sortJson) {
   JsonVo<String> json = new JsonVo<String>();
   JSONArray array = JSONArray.fromObject(sortJson);
   for (int i = 0; i < array.size(); i++) {
     JSONObject folder = array.getJSONObject(i);
     String folderId = folder.get("folderId").toString();
     String sort = folder.get("sort").toString();
     folderService.updateSort(Long.parseLong(folderId), Integer.parseInt(sort));
   }
   json.setResult(true);
   return json;
 }
  LayerInfo layer(JSONObject json) throws IOException {
    CatalogFactory f = importer.getCatalog().getFactory();

    if (json.has("layer")) {
      json = json.getJSONObject("layer");
    }

    ResourceInfo r = f.createFeatureType();
    if (json.has("name")) {
      r.setName(json.getString("name"));
    }
    if (json.has("nativeName")) {
      r.setNativeName(json.getString("nativeName"));
    }
    if (json.has("srs")) {
      r.setSRS(json.getString("srs"));
      try {
        r.setNativeCRS(CRS.decode(json.getString("srs")));
      } catch (Exception e) {
        // should fail later
      }
    }
    if (json.has("bbox")) {
      r.setNativeBoundingBox(bbox(json.getJSONObject("bbox")));
    }

    LayerInfo l = f.createLayer();
    l.setResource(r);
    // l.setName(); don't need to this, layer.name just forwards to name of underlying resource

    if (json.has("style")) {
      JSONObject sobj = new JSONObject();
      sobj.put("defaultStyle", json.get("style"));

      JSONObject lobj = new JSONObject();
      lobj.put("layer", sobj);

      LayerInfo tmp = fromJSON(lobj, LayerInfo.class);
      if (tmp.getDefaultStyle() != null) {
        l.setDefaultStyle(tmp.getDefaultStyle());
      } else {
        sobj = new JSONObject();
        sobj.put("style", json.get("style"));

        l.setDefaultStyle(fromJSON(sobj, StyleInfo.class));
      }
    }
    return l;
  }
示例#20
0
 /**
  * Get the northeast bound of the given address. If the JSONObject is not the given format, the
  * method would probably throw a NullPointerException.
  *
  * @param data the JSONObject
  * @return the Double array of northeast bound. null if the parsing fails
  */
 public static double[] getNorthEast(JSONObject data) {
   try {
     double[] northeastresult = new double[2];
     JSONObject viewport = getViewport(data);
     JSONObject northeast = (JSONObject) viewport.get("northeast");
     Double lat = (double) northeast.get("lat");
     Double lng = (double) northeast.get("lng");
     northeastresult[0] = lat;
     northeastresult[1] = lng;
     return northeastresult;
   } catch (NullPointerException npe) {
     npe.printStackTrace();
   }
   return null;
 }
示例#21
0
    @Override
    public HygieiaPublisher newInstance(StaplerRequest sr, JSONObject json) {

      HygieiaBuild hygieiaBuild =
          sr.bindJSON(HygieiaBuild.class, (JSONObject) json.get("hygieiaBuild"));
      HygieiaArtifact hygieiaArtifact =
          sr.bindJSON(HygieiaArtifact.class, (JSONObject) json.get("hygieiaArtifact"));
      HygieiaTest hygieiaTest =
          sr.bindJSON(HygieiaTest.class, (JSONObject) json.get("hygieiaTest"));
      HygieiaSonar hygieiaSonar =
          sr.bindJSON(HygieiaSonar.class, (JSONObject) json.get("hygieiaSonar"));
      HygieiaDeploy hygieiaDeploy =
          sr.bindJSON(HygieiaDeploy.class, (JSONObject) json.get("hygieiaDeploy"));
      return new HygieiaPublisher(
          hygieiaBuild, hygieiaTest, hygieiaArtifact, hygieiaSonar, hygieiaDeploy);
    }
  /** Web method to handle the approval action submitted by the user. */
  public void doApprove(
      StaplerRequest req,
      StaplerResponse rsp,
      @AncestorInPath PromotionProcess promotionProcess,
      @AncestorInPath AbstractBuild<?, ?> build)
      throws IOException, ServletException {

    JSONObject formData = req.getSubmittedForm();

    if (canApprove(promotionProcess, build)) {
      List<ParameterValue> paramValues = new ArrayList<ParameterValue>();

      if (parameterDefinitions != null && !parameterDefinitions.isEmpty()) {
        JSONArray a = JSONArray.fromObject(formData.get("parameter"));

        for (Object o : a) {
          JSONObject jo = (JSONObject) o;
          String name = jo.getString("name");

          ParameterDefinition d = getParameterDefinition(name);
          if (d == null)
            throw new IllegalArgumentException("No such parameter definition: " + name);

          paramValues.add(d.createValue(req, jo));
        }
      }
      approve(build, promotionProcess, paramValues);
    }

    rsp.sendRedirect2("../../../..");
  }
示例#23
0
  @SuppressWarnings("unchecked")
  public String decorate(TableContext context, Integer index, FilterData filterData, DataItem item)
      throws Exception {
    Div div = new Div();

    JSONObject obj = this.getJsonValues(parameters);
    if (obj != null) {
      Iterator iterator = obj.keys();
      while (iterator.hasNext()) {
        Object key = iterator.next();
        Object value = obj.get(key);

        Input radio = new Input();
        radio.setName("filterData.items[" + index + "].value");
        radio.setType("radio");

        radio.setTagText(this.getText(context, value.toString()));
        radio.setValue(key.toString());

        radio.setChecked(this.isSelected(filterData, item, key));
        div.addElement(radio);
      }
    }
    return this.addHiddenValues(index, item) + div.toString();
  }
  @Override
  public Builder newInstance(StaplerRequest req, JSONObject formData) throws FormException {
    String execDefIds = formData.getString("execDefIds"); // $NON-NLS-1$
    int projectId = formData.getInt("projectId"); // $NON-NLS-1$
    int delay = getOptionalIntValue(formData.getString("delay"), 0); // $NON-NLS-1$
    boolean contOnErr = formData.getBoolean("continueOnError"); // $NON-NLS-1$
    boolean collectResults = formData.getBoolean("collectResults"); // $NON-NLS-1$
    boolean ignoreSetupCleanup = formData.getBoolean("ignoreSetupCleanup"); // $NON-NLS-1$
    String jobName = ""; // $NON-NLS-1$
    JSONObject buildNumberUsageOption =
        (JSONObject) formData.get("buildNumberUsageOption"); // $NON-NLS-1$
    int optValue;
    if (buildNumberUsageOption == null) optValue = SCTMExecutor.OPT_NO_BUILD_NUMBER;
    else optValue = buildNumberUsageOption.getInt("value"); // $NON-NLS-1$

    String version = null;
    switch (optValue) {
      case SCTMExecutor.OPT_USE_SPECIFICJOB_BUILDNUMBER:
        jobName = buildNumberUsageOption.getString("jobName"); // $NON-NLS-1$
      case SCTMExecutor.OPT_USE_LATEST_SCTM_BUILDNUMBER:
      case SCTMExecutor.OPT_USE_THIS_BUILD_NUMBER:
        version = buildNumberUsageOption.getString("productVersion"); // $NON-NLS-1$
    }

    return new SCTMExecutor(
        projectId,
        execDefIds,
        delay,
        optValue,
        jobName,
        contOnErr,
        collectResults,
        ignoreSetupCleanup,
        version);
  }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {

    String code = request.getParameter("code");
    String Token = (String) request.getSession().getAttribute("accessToken");
    System.out.println("accessToken" + Token);
    String requestUrl =
        "https://graph.renren.com/oauth/token?grant_type=authorization_code&client_id="
            + client_ID
            + "&redirect_uri=http://other.internetrt.org:8080/renrent/home&client_secret="
            + client_SECRET
            + "&code="
            + code;
    String result = httpClientPost(requestUrl);

    System.out.println("[HomeServlet : doPost]" + result);
    try {
      JSONObject json = JSONObject.fromString(result);
      String sessionKey = (String) json.get("access_token");
      System.out.println("[HomeServlet : doPost]: " + "renrenSessionKey: " + sessionKey);
      request.setAttribute("sessionkeyfromrenren", sessionKey);
      System.out.println("[HomeServlet : doPost]: " + "renrenSessionKey" + sessionKey);
      ApiInitListener.feedstub.addFeedUser(sessionKey, Token);
    } catch (Exception err) {
      err.printStackTrace();
      System.out.println("[HomeServlet : doPost] json串问题");
    }

    RequestDispatcher welcomeDispatcher = request.getRequestDispatcher("/views/home.jsp");
    welcomeDispatcher.forward(request, response);
  }
示例#26
0
  /**
   * Get the southwest bound of the given address. If the JSONObject is not the given format, the
   * method would probably throw a NullPointerException.
   *
   * @param data the JSONObject
   * @return the Double array of southwest bound. null if the parsing fails
   */
  public static double[] getSouthWest(JSONObject data) {
    try {
      double[] southwestresult = new double[2];
      JSONObject viewport = getViewport(data);
      JSONObject southwest = (JSONObject) viewport.get("southwest");
      Double lat = (double) southwest.get("lat");
      Double lng = (double) southwest.get("lng");
      southwestresult[0] = lat;
      southwestresult[1] = lng;
      return southwestresult;

    } catch (NullPointerException npe) {
      npe.printStackTrace();
    }
    return null;
  }
示例#27
0
  /**
   * Saves the form to the configuration and disk.
   *
   * @param req StaplerRequest
   * @param rsp StaplerResponse
   * @throws ServletException if something unfortunate happens.
   * @throws IOException if something unfortunate happens.
   * @throws InterruptedException if something unfortunate happens.
   */
  public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp)
      throws ServletException, IOException, InterruptedException {
    getProject().checkPermission(AbstractProject.BUILD);
    if (isRebuildAvailable()) {
      if (!req.getMethod().equals("POST")) {
        // show the parameter entry form.
        req.getView(this, "index.jelly").forward(req, rsp);
        return;
      }
      build = req.findAncestorObject(AbstractBuild.class);
      ParametersDefinitionProperty paramDefProp =
          build.getProject().getProperty(ParametersDefinitionProperty.class);
      List<ParameterValue> values = new ArrayList<ParameterValue>();
      ParametersAction paramAction = build.getAction(ParametersAction.class);
      JSONObject formData = req.getSubmittedForm();
      if (!formData.isEmpty()) {
        JSONArray a = JSONArray.fromObject(formData.get("parameter"));
        for (Object o : a) {
          JSONObject jo = (JSONObject) o;
          String name = jo.getString("name");
          ParameterValue parameterValue =
              getParameterValue(paramDefProp, name, paramAction, req, jo);
          if (parameterValue != null) {
            values.add(parameterValue);
          }
        }
      }

      CauseAction cause = new CauseAction(new RebuildCause(build));
      Hudson.getInstance()
          .getQueue()
          .schedule(build.getProject(), 0, new ParametersAction(values), cause);
      rsp.sendRedirect("../../");
    }
  }
示例#28
0
  /**
   * Generates base64 representation of JWT token sign using "RS256" algorithm
   *
   * <p>getHeader().toBase64UrlEncode() + "." + getClaim().toBase64UrlEncode() + "." + sign
   *
   * @return base64 representation of JWT token
   */
  public String sign() {
    for (JwtTokenDecorator decorator : JwtTokenDecorator.all()) {
      decorator.decorate(this);
    }

    /**
     * kid might have been set already by using {@link #header} or {@link JwtTokenDecorator}, if
     * present use it otherwise use the default kid
     */
    String keyId = (String) header.get(HeaderParameterNames.KEY_ID);
    if (keyId == null) {
      keyId = DEFAULT_KEY_ID;
    }

    JwtRsaDigitalSignatureKey rsaDigitalSignatureConfidentialKey =
        new JwtRsaDigitalSignatureKey(keyId);

    try {
      return rsaDigitalSignatureConfidentialKey.sign(claim);
    } catch (JoseException e) {
      String msg = "Failed to sign JWT token: " + e.getMessage();
      logger.error(msg);
      throw new ServiceException.UnexpectedErrorException(msg, e);
    }
  }
 @Override
 public boolean configure(final StaplerRequest req, final JSONObject json) throws FormException {
   JSONObject selectedJson = json.getJSONObject("searchBackend");
   if (selectedJson.containsKey(SOLR_URL)) {
     String solrUrl = selectedJson.getString(SOLR_URL);
     ensureNotError(doCheckSolrUrl(solrUrl), SOLR_URL);
     try {
       setSolrUrl(makeSolrUrl(solrUrl));
     } catch (IOException e) {
       // Really shouldn't be possible, but this is the correct action, should it ever happen
       throw new FormException("Incorrect freetext config", SOLR_URL);
     }
   }
   if (selectedJson.containsKey(SOLR_COLLECTION)) {
     String solrCollection = selectedJson.getString(SOLR_COLLECTION);
     ensureNotError(doCheckSolrCollection(solrCollection, getSolrUrl()), SOLR_COLLECTION);
     setSolrCollection(solrCollection);
   }
   if (selectedJson.containsKey(LUCENE_PATH)) {
     String lucenePath = selectedJson.getString(LUCENE_PATH);
     ensureNotError(doCheckLucenePath(lucenePath), LUCENE_PATH);
     setLucenePath(new File(lucenePath));
   }
   if (json.containsKey(USE_SECURITY)) {
     setUseSecurity(json.getBoolean(USE_SECURITY));
   }
   setSearchBackend(SearchBackendEngine.valueOf(json.get("").toString()));
   reconfigure();
   return super.configure(req, json);
 }
示例#30
0
  public static Map getRecursiveMapFromJson(String jsonString) {
    setDataFormat2JAVA();
    JSONObject jsonObject = JSONObject.fromObject(jsonString);

    Map map = new HashMap();
    String key = "", value = "";
    Map subMap = null;
    for (Iterator iter = jsonObject.keys(); iter.hasNext(); ) {
      key = (String) iter.next();
      value = jsonObject.get(key) + "";
      if (isJson(value)) {
        if (SSO.tioe(value)) {
          continue;
        }

        value = value.trim();

        if (value.startsWith("[") && value.endsWith("]")) {
          value = value.substring(1, value.length() - 1);
        }
        subMap = getRecursiveMapFromJson(value);
        map.put(key, subMap);
      } else {
        map.put(key, value);
      }
    }

    return map;
  }