Esempio n. 1
0
 /**
  * 格式化是否赞
  *
  * @param userId
  * @param gds
  * @throws XueWenServiceException
  */
 public JSONArray formateGroupDynamic(String userId, JSONArray gds) throws XueWenServiceException {
   List<String> ss = new ArrayList<String>();
   for (int i = 0; i < gds.size(); i++) {
     JSONObject gd = gds.getJSONObject(i);
     String sourceId = gd.getString("sourceId");
     ss.add(sourceId);
   }
   List<String> ps = praiseService.findBySourseListAndUserIdRspSourceId(ss, userId);
   if (ps != null && ps.size() > 0) {
     for (int i = 0; i < gds.size(); i++) {
       JSONObject gd = gds.getJSONObject(i);
       String sourceId = gd.getString("sourceId");
       if (ps.contains(sourceId)) {
         gd.put("islike", true);
       } else {
         gd.put("islike", false);
       }
     }
   } else {
     for (int i = 0; i < gds.size(); i++) {
       JSONObject gd = gds.getJSONObject(i);
       gd.put("islike", false);
     }
   }
   return gds;
 }
Esempio n. 2
0
  @Override
  protected void updateConnectorDataHistory(UpdateInfo updateInfo)
      throws RateLimitReachedException, Exception {
    // taking care of resetting the data if things went wrong before
    if (!connectorUpdateService.isHistoryUpdateCompleted(updateInfo.apiKey, -1))
      apiDataService.eraseApiData(updateInfo.apiKey, -1);
    int retrievedItems = ITEMS_PER_PAGE;
    for (int page = 0; retrievedItems == ITEMS_PER_PAGE; page++) {
      JSONObject feed = retrievePhotoHistory(updateInfo, 0, System.currentTimeMillis(), page);
      if (feed.has("stat")) {
        String stat = feed.getString("stat");
        if (stat.equalsIgnoreCase("fail")) {
          String message = feed.getString("message");
          throw new RuntimeException("Could not retrieve Flickr history: " + message);
        }
      }
      JSONObject photosWrapper = feed.getJSONObject("photos");

      if (photosWrapper != null) {
        JSONArray photos = photosWrapper.getJSONArray("photo");
        retrievedItems = photos.size();
        apiDataService.cacheApiDataJSON(updateInfo, feed, -1, -1);
      } else break;
    }
  }
 private NexusDescriptor parse(JSONObject json) {
   return new NexusDescriptor(
       json.getString("name"),
       json.getString("url"),
       json.getString("user"),
       json.getString("password"));
 }
Esempio n. 4
0
    @Override
    protected void onTextMessage(CharBuffer message) throws IOException {
      String temp = message.toString();
      JSONObject json = (JSONObject) JSONSerializer.toJSON(temp);

      String type = json.getString("type").toLowerCase().replaceAll(" ", "");
      String location = json.getString("location");
      String lat = json.getString("lat");
      String lng = json.getString("lng");
      String radius = json.getString("radius");
      String keywords = json.getString("keywords");

      String result = null;
      try {
        if (type.equals("overview")) result = getOverViewData(location, lat, lng, radius, keywords);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        JSONObject jsonResult = new JSONObject();
        jsonResult.put("error", "true");
        result = jsonResult.toString();
      }
      if (result == null || result.equals("")) {
        JSONObject jsonResult = new JSONObject();
        jsonResult.put("error", "true");
        result = jsonResult.toString();
      }
      Charset charset = Charset.forName("ISO-8859-1");
      CharsetDecoder decoder = charset.newDecoder();
      CharsetEncoder encoder = charset.newEncoder();
      CharBuffer uCharBuffer = CharBuffer.wrap(result);
      ByteBuffer bbuf = encoder.encode(uCharBuffer);
      CharBuffer cbuf = decoder.decode(bbuf);
      getWsOutbound().writeTextMessage(cbuf);
    }
  public void execute(Tuple tuple) {
    JSONObject eventObj = (JSONObject) tuple.getValueByField("eventoutput");
    String session = eventObj.getString("sessionid");
    String eventType = eventObj.getString("event");

    if (eventType.equals("change")) {
      JSONObject payload = eventObj.getJSONObject("payload");

      if (payload.getString("field").equals("firstname")) {
        Long count = this.counts.get(session);
        if (count == null) {
          count = 0L;
        }
        count++;
        this.counts.put(session, count);

        if (count > 2) {
          String desc =
              "In the " + session + " : " + "firstname was changed more than " + count + "times";
          System.out.println(desc);
          eventType = "TooManyNameChange";
          eventObj.put("event", eventType);
          // this.collector.emit(new Values(eventObj, desc,"APPUI_ACCEPT_PASSPORT"));
          this.collector.emit(new Values(eventObj, desc, "TOOMANYNAMECHANGES"));
        }
      }
    }
  }
Esempio n. 6
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {

      try {
        JSONObject request =
            (JSONObject) JSONSerializer.toJSON(IOUtils.toString(arg0.getRequestBody()));
        String email = request.getString("email");
        String key = request.getString("key");

        for (int i = 0; i < jobs.size(); i++) {
          TnrsJob job = jobs.get(i);
          if (job.getRequest().getId().equals(key) && job.getRequest().getEmail().equals(email)) {
            JSONObject json = (JSONObject) JSONSerializer.toJSON(job.toJsonString());
            json.put("status", "incomplete");
            json.put("progress", job.progress());

            HandlerHelper.writeResponseRequest(arg0, 200, json.toString(), "application/json");
            return;
          }
        }
        if (JobHelper.jobFileExists(baseFolder, email, key)) {
          TnrsJob job = JobHelper.readJobInfo(baseFolder, email, key);

          HandlerHelper.writeResponseRequest(arg0, 200, job.toJsonString(), "application/json");
        } else {
          HandlerHelper.writeResponseRequest(
              arg0, 500, "No such job exists o it might have expired", "text/plain");
        }

      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        throw new IOException(ex);
      }
    }
Esempio n. 7
0
    /**
     * Parses the raw response from Google
     *
     * @param rawResponse The raw, unparsed response from Google
     * @return Returns the parsed response.
     */
    void parseResponse(String rawResponse, GoogleResponse googleResponse) {
        try {
            JSONObject json = JSONObject.fromObject(rawResponse);
            int status = json.getInt("status");

            if (status == 0) {
                JSONArray hypotheses = json.getJSONArray("hypotheses");

                for (int index = 0; index < hypotheses.size(); index++) {
                    JSONObject hypothese = (JSONObject) hypotheses.get(index);

                    if (hypothese.containsKey(CONFIDENCE)) {
                        googleResponse.setResponse(hypothese.getString("utterance"));
                        googleResponse.setConfidence(hypothese.getDouble(CONFIDENCE) + "");
                    } else {
                        googleResponse.getOtherPossibleResponses().add(hypothese.getString("utterance"));
                    }
                }
            } else {
                Logger.getLogger(Recognizer.class.getName()).log(Level.WARNING, "status: {0}", status);
            }
        } catch (JSONException e) {
            Logger.getLogger(Recognizer.class.getName()).log(Level.WARNING, e.getLocalizedMessage(), e);
        }
    }
 @RequestMapping("/member/info/{cardNo}")
 @ResponseBody
 public JSONObject getMemberInfo(@PathVariable("cardNo") String cardNo) {
   JSONObject json = new JSONObject();
   json.put("cardNo", cardNo);
   try {
     PrivateSignatureHandler handler = new PrivateSignatureHandler();
     handler.setCaller("sale-web");
     handler.setKeyFilePath(privateKeyPath);
     String goodsInfo =
         HttpRequester.httpPostString(host + "/" + getMemberInfo, handler.sign(json));
     JSONObject info = JSONObject.fromObject(goodsInfo);
     Boolean success = info.getBoolean("success");
     if (success) {
       json.put("success", true);
       json.put("member", info.getString("member"));
     } else {
       json.put("success", false);
       json.put("errorCode", info.getString("errorCode"));
       json.put("message", info.getString("message"));
     }
   } catch (IOException
       | InvalidKeySpecException
       | CallerNotFoundException
       | HttpRequestException
       | URISyntaxException e) {
     json.put("success", false);
     json.put("errorCode", 500);
     json.put("message", "服务器调用异常,请稍后再试!");
     logger.error("服务器异常!", e);
   }
   logger.debug("返回的数据:{}", json.toString());
   return json;
 }
 @RequestMapping("/employee/list")
 @ResponseBody
 public String getEmployee() {
   JSONObject json = new JSONObject();
   try {
     PrivateSignatureHandler handler = new PrivateSignatureHandler();
     handler.setCaller("sale-web");
     handler.setKeyFilePath(privateKeyPath);
     JSONObject result =
         JSONObject.fromObject(
             HttpRequester.httpPostString(
                 host + "/" + getEmployeeList, handler.sign(new JSONObject())));
     Boolean success = result.getBoolean("success");
     if (success) {
       json.put("success", true);
       json.put("employees", result.get("employees"));
     } else {
       json.put("success", false);
       json.put("errorCode", result.getString("errorCode"));
       json.put("message", result.getString("message"));
     }
   } catch (IOException
       | InvalidKeySpecException
       | CallerNotFoundException
       | HttpRequestException
       | URISyntaxException e) {
     json.put("success", false);
     json.put("errorCode", 500);
     json.put("message", "服务器调用异常,请稍后再试!");
     logger.error("服务器异常!", e);
   }
   logger.debug("返回数据为:{}", json);
   return json.toString();
 }
  public JSONObject objectForTargetXPath(JSONObject object, String xpath) {
    System.out.println("objectForTargetXPath: " + object.getString("name") + " - " + xpath);

    if (xpath.startsWith("/")) {
      xpath = xpath.replaceFirst("/", "");
    }
    String[] tokens = xpath.split("/");
    if (tokens.length > 0) {
      log.debug("looking path:" + xpath + " in object:" + object);
      if (object.has("name")) {
        if (tokens[0].equals(object.getString("name"))) {
          if (tokens.length == 1) {
            return object;
          } else {
            String path = tokens[1];
            for (int i = 2; i < tokens.length; i++) {
              path += "/" + tokens[i];
            }

            if (path.startsWith("@")) {
              if (object.has("attributes")) {
                return this.objectForTargetXPath(object.getJSONArray("attributes"), path);
              }
            } else {
              if (object.has("children")) {
                return this.objectForTargetXPath(object.getJSONArray("children"), path);
              }
            }
          }
        }
      }
    }

    return null;
  }
Esempio n. 11
0
 public static Namelist fromJSONtoNamelist(JSONObject jsonObj) {
   logger.info("Convert json object to namelist...");
   if (jsonObj != null) {
     String name = jsonObj.getString("_name");
     String species = jsonObj.getString("_species");
     if (species == null) {
       JSONObject metadataJSONObj = jsonObj.getJSONObject("metadata");
       if (metadataJSONObj != null) {
         species = metadataJSONObj.getString("species");
       }
     }
     int size = jsonObj.getInt("_size");
     JSONArray data =
         jsonObj.containsKey("_data")
             ? jsonObj.getJSONArray("_data")
             : jsonObj.getJSONArray("gaggle-data");
     String[] names = new String[data.size()];
     for (int i = 0; i < data.size(); i++) {
       logger.info("Data item: " + data.getString(i));
       names[i] = data.getString(i);
     }
     logger.info("Species: " + species + " Names: " + names);
     Namelist nl = new Namelist(name, species, names);
     return nl;
   }
   return null;
 }
  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();
  }
  /** Tests {@link ExternalResource#toJson()}. */
  @PrepareForTest(Hudson.class)
  @Test
  public void testToJson() {
    Hudson hudson = MockUtils.mockHudson();
    MockUtils.mockMetadataValueDescriptors(hudson);

    String name = "name";
    String description = "description";
    String id = "id";
    ExternalResource resource =
        new ExternalResource(name, description, id, true, new LinkedList<MetadataValue>());
    String me = "me";
    resource.setReserved(
        new StashInfo(
            StashInfo.StashType.INTERNAL, me, new Lease(Calendar.getInstance(), "iso"), "key"));
    TreeStructureUtil.addValue(resource, "value", "descript", "some", "path");

    JSONObject json = resource.toJson();
    assertEquals(name, json.getString(JsonUtils.NAME));
    assertEquals(id, json.getString(JSON_ATTR_ID));
    assertTrue(json.getBoolean(JSON_ATTR_ENABLED));
    assertTrue(json.getJSONObject(JSON_ATTR_LOCKED).isNullObject());
    JSONObject reserved = json.getJSONObject(JSON_ATTR_RESERVED);
    assertNotNull(reserved);
    assertEquals(StashInfo.StashType.INTERNAL.name(), reserved.getString(Constants.JSON_ATTR_TYPE));
    assertEquals(me, reserved.getString(Constants.JSON_ATTR_STASHED_BY));
    assertEquals(1, json.getJSONArray(JsonUtils.CHILDREN).size());
  }
Esempio n. 14
0
  public static String chat(String msg) {
    String url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=关键词";
    try {
      url = url.replace("关键词", java.net.URLEncoder.encode(msg, "UTF-8"));
      String json = FaceService.httpRequest(url);
      JSONObject jsobject = JSONObject.fromObject(json);
      String result = jsobject.getString("result");
      String content = jsobject.getString("content");
      if (result.equals("0")) {
        content = content.replace("{br}", "");
        content = content.replace("。", "。" + "\n");
        content = content.replace(":", ":");

        // content=content.replace("。", "\n");
        return content;
      } else {
        return "请您发送文明消息,做文明市民~";
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return "请您发送文明消息,做文明市民~";
  }
 @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);
 }
Esempio n. 16
0
 @RequestMapping("/goods/info/{goodsSn}")
 @ResponseBody
 public JSONObject getGoodsInfo(@PathVariable("goodsSn") String goodsSn) {
   JSONObject json = new JSONObject();
   json.put("goodsSn", goodsSn);
   json.put("storeSid", 1);
   try {
     PrivateSignatureHandler handler = new PrivateSignatureHandler();
     handler.setCaller("sale-web");
     handler.setKeyFilePath(privateKeyPath);
     String goodsInfo =
         HttpRequester.httpPostString(host + "/" + getGoodsInfo, handler.sign(json));
     JSONObject goods = JSONObject.fromObject(goodsInfo);
     Boolean success = goods.getBoolean("success");
     if (success) {
       json.put("success", true);
       json.put("price", goods.getString("price"));
     } else {
       json.put("success", false);
       json.put("errorCode", goods.getString("errorCode"));
       json.put("message", goods.getString("message"));
     }
   } catch (IOException
       | InvalidKeySpecException
       | CallerNotFoundException
       | HttpRequestException
       | URISyntaxException e) {
     json.put("success", false);
     json.put("errorCode", 500);
     json.put("message", "服务器调用异常,请稍后再试!");
     logger.error("服务器异常!", e);
   }
   return json;
 }
Esempio n. 17
0
  protected AccessTokenResponse getAccessToken(
      Client client, PartnerConfiguration partnerConfiguration)
      throws UnsupportedEncodingException {
    String tokenParams =
        String.format(
            "grant_type=client_credentials&scope=all&client_id=%s&client_secret=%s",
            partnerConfiguration.userName, partnerConfiguration.password);

    ClientResponse postResponse =
        client
            .resource(TOKEN_URL)
            .entity(tokenParams, MediaType.APPLICATION_FORM_URLENCODED_TYPE)
            .header(
                "Authorization",
                basic(partnerConfiguration.userName, partnerConfiguration.password))
            .post(ClientResponse.class);

    String json = postResponse.getEntity(String.class);
    JSONObject accessToken = (JSONObject) JSONSerializer.toJSON(json);

    AccessTokenResponse response = new AccessTokenResponse();
    response.setAccessToken(accessToken.getString("access_token"));
    response.setExpiresIn(accessToken.getLong("expires_in"));
    response.setRefreshToken(accessToken.getString("refresh_token"));
    response.setTokenType(accessToken.getString("token_type"));

    return response;
  }
 public void reloadFiltreBase(String filtreString) {
   if (filtreString != null) {
     filtreJson = JSONObject.fromObject(filtreString);
     if (filtreJson.containsKey("Nom")) {
       setFiltreNomBase(filtreJson.getString("Nom"));
     }
     if (filtreJson.containsKey("Environnement")) {
       for (Environnement env : listEnvironnement) {
         if (env.getEnvironnement().equalsIgnoreCase(filtreJson.getString("Environnement"))) {
           setFiltreEnvironnementBase(env.getId());
         }
       }
     }
     if (filtreJson.containsKey("Date de début")) {
       setFiltreDateDebutBase(filtreJson.getString("Date de début"));
     }
     if (filtreJson.containsKey("Criticité")) {
       for (Checklist_Criticite crit : listCriticite) {
         if (crit.getLibelle().equalsIgnoreCase(filtreJson.getString("Criticité"))) {
           setFiltreCriticiteBase(crit.getId());
         }
       }
     }
     if (validForm == 0) {
       setFiltreNom(filtreNomBase);
       setFiltreEnvironnement(filtreEnvironnementBase);
       setFiltreDateDebut(filtreDateDebutBase);
       setFiltreCriticite(filtreCriticiteBase);
     }
   }
 }
Esempio n. 19
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {
      try {
        String jsons = IOUtils.toString(arg0.getRequestBody());

        JSONObject json = (JSONObject) JSONSerializer.toJSON(jsons);
        if (!json.containsKey("valid")) return;
        Email response = new SimpleEmail();
        response.setHostName(properties.getProperty("org.iplantc.tnrs.mail.host"));
        response.setSmtpPort(
            Integer.parseInt(properties.getProperty("org.iplantc.tnrs.mail.port")));
        response.setFrom("*****@*****.**");
        response.setSubject("TNRS support Ticket");
        response.setMsg(
            "TNRS support ticket from: "
                + json.getString("name")
                + " ("
                + json.getString("email")
                + "). "
                + "\n\n\n"
                + json.getString("contents"));
        response.addTo("*****@*****.**");
        response.send();
      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        throw new IOException(ex);
      }
    }
  /**
   * * Simula el monto de disposicion de un credito 24x7
   *
   * @param request Datos de entrada de la peticion, se recibe un json
   * @param response Datos de salida de la petcion
   * @return regresa la respuesta del servicio en formato json
   */
  public ModelAndView simularDisposicion(HttpServletRequest request, HttpServletResponse response) {

    JSONResponseBean responseBean = new JSONResponseBean();

    try {
      JSONObject jsonObject = getJSONRequestObject(request);
      CreditoConsumoBean credito = new CreditoConsumoBean();
      ClienteBean cliente = (ClienteBean) request.getSession().getAttribute("cliente");
      BitacoraBean bitacora = getBitacoraBean(request);
      CreditoConsumoBean simulacion = null;

      credito.setNumCredito(jsonObject.getString("numeroCredito"));
      credito.setSaldos(new SaldosCreditoBean());
      credito.getSaldos().setLineaCredito(jsonObject.getString("monto"));

      simulacion = lineas24x7Service.simularDisposicion(credito, cliente, bitacora);
      responseBean.setDto(JSONObject.fromBean(simulacion).toString());
      responseBean.setError(ErrorBean.SUCCESS);
    } catch (BusinessException e) {
      responseBean.setError(e.getError());
    } catch (Exception e) {
      responseBean.setError(e.getMessage());
    }

    return getResponseView(responseBean);
  }
  public static Map<String, String> getParam(
      String appId, String appSecret, String requestUrl, String queryString) {
    if (token == null) {
      token = CommonUtil.getToken(appId, appSecret);
      jsapi_ticket = CommonUtil.getJsApiTicket(token.getAccessToken());
      time = getTime();
    } else {
      if (!time.substring(0, 13).equals(getTime().substring(0, 13))) {
        token = null;
        token = CommonUtil.getToken(appId, appSecret);
        jsapi_ticket = CommonUtil.getJsApiTicket(token.getAccessToken());
        time = getTime();
      }
    }
    String url = getUrl(requestUrl, queryString);
    Map<String, String> params = sign(jsapi_ticket, url);
    params.put("appid", appId);
    JSONObject jsonObject = JSONObject.fromObject(params);
    String jsonStr = jsonObject.toString();
    Map<String, String> map = new HashMap<>();
    map.put("timestamp", jsonObject.getString("timestamp"));
    map.put("appid", jsonObject.getString("appid"));
    map.put("nonceStr", jsonObject.getString("nonceStr"));
    map.put("jsapi_ticket", jsonObject.getString("jsapi_ticket"));
    map.put("signature", jsonObject.getString("signature"));
    System.out.println(jsonStr);

    return map;
  }
Esempio n. 22
0
  @Override
  @SuppressWarnings({"rawtypes", "unchecked"})
  @Post
  public Representation post(Representation entity) {

    Form form = new Form(entity);
    String operation = null;
    int start = 0;
    int limit = 50;
    try {
      operation = URLDecoder.decode(form.getQueryString(), "utf-8");
      operation = new String(operation.getBytes("iso-8859-1"), "utf-8");
      JSONObject json = JSONObject.fromObject(operation);
      start =
          json.containsKey("start") == false ? start : Integer.parseInt(json.getString("start"));
      limit =
          json.containsKey("limit") == false ? limit : Integer.parseInt(json.getString("limit"));
    } catch (Exception e) {
      // e.printStackTrace();
    }
    List<Role> list = service.getAllRole(start, limit);
    Page page = new Page(list);
    page.setStart(start);
    page.setPageSize(limit);
    int totalCount = service.getCountRole();
    page.setTotalCount(totalCount);
    return new JsonRepresentation(JSONObject.fromObject(page));
  }
 @Override
 public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
   cssUrl = formData.getString("cssUrl");
   jsUrl = formData.getString("jsUrl");
   save();
   return super.configure(req, formData);
 }
  @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);
  }
  /**
   * Accept a POST request.
   *
   * @param entity the representation of a new entry.
   * @throws ResourceException thrown when unable to accept representation.
   */
  @Override
  public void acceptRepresentation(final Representation entity) throws ResourceException {
    String json;
    try {
      json = entity.getText();
      log.debug("RecommendationsCollectionResource POST" + json);

      JSONObject jsonReco = JSONObject.fromObject(json);
      JSONObject jsonAuthor = jsonReco.getJSONObject(AUTHOR_KEY);
      JSONObject jsonSubject = jsonReco.getJSONObject(SUBJECT_KEY);
      Recommendation recommendation =
          new Recommendation(
              jsonSubject.getString(ID_KEY),
              jsonAuthor.getString(ID_KEY),
              jsonReco.getString(TEXT_KEY));

      getRecommendationMapper().insert(recommendation);

      Map<String, Person> people = getPeopleInfoForRecommendations(recommendation);

      JSONObject recoJSON =
          convertRecoToJSON(
              recommendation,
              people.get(recommendation.getAuthorOpenSocialId()),
              people.get(recommendation.getSubjectOpenSocialId()));

      getAdaptedResponse().setEntity(recoJSON.toString(), MediaType.APPLICATION_JSON);
    } catch (IOException e) {
      log.error("POST to RecommendationsCollection failed", e);
      throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST);
    }

    log.debug("RecommendationsCollectionResource POST " + entity.toString());
  }
Esempio n. 26
0
  @Override
  protected JSONObject doService(HttpSession session, JSONObject param, JSONObject result) {

    Object login = session.getAttribute("login");
    if (session != null && login != null) {
      logger.debug(login);
      result.put("state", true);
    }
    String name = param.has("name") ? param.getString("name") : null;
    String password = param.has("password") ? param.getString("password") : null;
    if (name != null && password != null) {
      User user = oservice.getUserByName(name);
      if (user == null) {
        user = oservice.loginByTel(name, password);
        if (user != null) {
          session.setAttribute("login", user.getName());
          session.setAttribute("loginTime", System.currentTimeMillis());
          result.put(GlobalContants.key_state_code, GlobalContants.STATE_CODE_OK);
        } else {
          result.put(GlobalContants.key_state_code, GlobalContants.state_code_not_user);
        }
      } else if (user.getPwd().equals(password)) {
        session.setAttribute("login", name);
        session.setAttribute("loginTime", System.currentTimeMillis());
        result.put(GlobalContants.key_state_code, GlobalContants.STATE_CODE_OK);
      } else {
        result.put(GlobalContants.key_state_code, GlobalContants.state_code_password_fail);
      }

    } else {
      result.put(GlobalContants.key_state_code, GlobalContants.state_code_not_user);
    }
    return result;
  }
Esempio n. 27
0
  @Override
  public void updateConnectorData(UpdateInfo updateInfo) throws Exception {
    int retrievedItems = ITEMS_PER_PAGE;
    long lastUploadTime = getLastUploadTime(updateInfo);
    for (int page = 0; retrievedItems == ITEMS_PER_PAGE; page++) {
      JSONObject feed =
          retrievePhotoHistory(updateInfo, lastUploadTime, System.currentTimeMillis(), page);

      if (!(feed.getString("stat").equalsIgnoreCase("ok"))) {
        String message = "n/a";
        if (feed.containsKey("message")) message = feed.getString("message");
        throw new Exception("There was an error calling the Flickr API: " + message);
      }

      JSONObject photosWrapper = feed.getJSONObject("photos");

      if (photosWrapper != null) {
        if (photosWrapper.containsKey("photo")) {
          JSONArray photos = photosWrapper.getJSONArray("photo");
          retrievedItems = photos.size();
          apiDataService.cacheApiDataJSON(updateInfo, feed, -1, -1);
        } else break;
      } else break;
    }
  }
Esempio n. 28
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());
    }
  }
 @Override
 public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
   setTenantRepositoryDirPattern(formData.getString("tenantRepositoryDirPattern"));
   setPreConfiguredMvnRepoArchive(formData.getString("preConfiguredMvnRepoArchive"));
   save();
   return super.configure(req, formData);
 }
Esempio n. 30
0
  @Override
  public WeiboUser fetchUser(OAuthTokenPair accessTokenPair) {
    Map<String, String> additionalParams = new HashMap<String, String>();
    additionalParams.put("format", "json");
    WeiboResponse response = null;
    try {
      response = this.protocal.get(USER_INFO_URL, additionalParams, accessTokenPair);
      if (response.isStatusOK()) {
        JSONObject obj =
            JSONObject.fromObject(response.getHttpResponseText()).getJSONObject("data");
        WeiboUser user = new WeiboUser(accessTokenPair);
        user.setNickName(obj.getString("nick"));
        user.setImgUrl(obj.getString("head") + "/180"); // 修正腾讯微博头像url无法访问
        user.setUid(obj.getString("openid"));

        String name = obj.getString("name");
        user.setProfileUrl("http://t.qq.com/" + name + "?preview");

        return user;
      }
    } catch (Exception ex) {
      response.setLocalError(ex);
    }

    log.error("error to get user, resp: " + response);
    return null;
  }