Java 类net.sf.json.JSONObject 实例源码

项目:PUC-INF1407    文件:BuscaVoo.java   
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    JSONObject voo = new JSONObject();
    voo.put("aircraft", "A320");
    voo.put("maxPax", 200);

    JSONObject piloto = new JSONObject();
    piloto.put("firstName", "John");
    piloto.put("lastName", "Doe");
    voo.put("pilot", piloto);

    voo.accumulate("passenger", "George");
    voo.accumulate("passenger", "Thomas");

    // enviar os dados no formato JSON
    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");
    out.println(voo.toString(2));
}
项目:private-WeChat    文件:AuthorizationService.java   
/**
 * 刷新网页授权凭证
 * @param appId
 * @param appSecret
 * @param code
 * @return
 */
public Oauth2Token refreshOauth2Token(String appId,String refreshToken){
    logger.info("refreshOauth2Token appId : {} , refreshToken : {} ", appId, refreshToken);
    Oauth2Token oauth2Token = null;
    String requestUrl = refresh_token_url.replace("APPID", appId).replace("REFRESH_TOKEN", refreshToken);
    JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
    if(null != jsonObject){
        try{
            oauth2Token = new Oauth2Token();
            oauth2Token.setAccessToken(jsonObject.getString("access_token"));
            oauth2Token.setExpiresIn(jsonObject.getInt("expires_in"));
            oauth2Token.setRefreshToken(jsonObject.getString("refresh_token"));
            oauth2Token.setOpenId(jsonObject.getString("openid"));
            oauth2Token.setScope(jsonObject.getString("scope"));
        }catch(Exception e){
            oauth2Token = null;
            int errCode = jsonObject.getInt("errcode");
            String errMsg = jsonObject.getString("errmsg");
            logger.error("刷新网页授权凭证失败 errCode : {} , errmsg : {} ", errCode,errMsg);
        }
    }
    logger.info("refreshOauth2Token => 返回 :" + com.alibaba.fastjson.JSONObject.toJSONString(oauth2Token)); 
    return oauth2Token;
}
项目:nightwatch    文件:JSONScheme.java   
@Override
public List<Object> deserialize(ByteBuffer ser) {
    String jsonStr = null;
    if (ser.hasArray()) {
        int base = ser.arrayOffset();
        jsonStr = new String(ser.array(), base + ser.position(), ser.remaining());
    } else {
        jsonStr = new String(Utils.toByteArray(ser), UTF8_CHARSET);
    }
    JSONObject jsonObject = JSONObject.fromObject(jsonStr);
    Values values = new Values();
    for (String outputField : outputFields) {
        if("jsonBody".equals(outputField)) {
            values.add(jsonStr);
        } else {
            if(!jsonObject.containsKey(outputField)) {
                JSONObject rcMsgpara = JSONObject.fromObject(jsonObject.get("rc_msg_para"));
                values.add(rcMsgpara.get(outputField));
            } else {
                values.add(jsonObject.get(outputField));
            }
        }
    }
    return values;
}
项目:jaffa-framework    文件:JSONHelper.java   
/**
 * Converts a Map Object into JSON string.
 * @param hm
 * @return
 */
public static String map2jsonConverter(Map hm) {
    if (hm==null || hm.size()==0) {
        return "{}";
    }
    JSONObject jo = new JSONObject();
    for (Iterator it = hm.keySet().iterator(); it.hasNext();) {
        Object k = it.next();
        if (hm.get(k)==null || hm.get(k) instanceof String) {
            jo.accumulate(k.toString(), hm.get(k));
        } else if (hm.get(k) instanceof Collection || hm.get(k).getClass().isArray()) {
            jo.accumulate(k.toString(), JSONArray.fromObject(hm.get(k)).toString());
        } else {
            log.debug("map2jsonConverter: "+hm.get(k).getClass().getName());
            jo.accumulate(k.toString(), JSONObject.fromObject(hm.get(k)).toString());
        }
    }
    return jo.toString();
}
项目:WebQQAPI    文件:Account.java   
public ArrayList<Group> getGroupList(){
    ArrayList<Group> groupsList=new ArrayList<Group>();
    JSONObject r=new JSONObject();
    r.put("vfwebqq",credential.getVfWebQQ());
    r.put("hash",credential.getHash());
    //构造一个请求表单,用于获取群列表

    //访问获取群信息的链接,并将结果解析为json
    JSONObject result=JSONObject.fromObject(utils.post(URL.URL_GET_GROUP_LIST,new PostParameter[]{new PostParameter("r",r.toString())},new HttpHeader[]{URL.URL_REFERER,credential.getCookie()}).getContent("UTF-8")).getJSONObject("result");
    //从结果取出群列表
    JSONArray groups=result.getJSONArray("gnamelist");
    //构造群对象
    for(int i=0;i<groups.size();i++){
        JSONObject tempInfo=JSONObject.fromObject(groups.get(i));
        //构造一个群对象,gid为群id,gcode用于获取成员,credential用于获取成员列表
        Group tempGroup=new Group(tempInfo.getLong("gid"),tempInfo.getLong("code"),credential);
        //设置群的名称
        tempGroup.setName(tempInfo.getString("name"));
        groupsList.add(tempGroup);
    }
    return groupsList;
}
项目:WebQQAPI    文件:Discuss.java   
public ArrayList<User> getDiscussUsers(){
    ArrayList<User> users=new ArrayList<User>();
    //用这个讨论组的did,以及vfwebqq合成一个完整的URL,并且将结果解析为json对象
    String url=URL.URL_GET_DISCUSS_INFO.replace("[var]",Long.toString(discussID)).replace("[var1]",credential.getVfWebQQ()).replace("[var2]",credential.getPsessionID());
    String info=utils.get(url,new HttpHeader[]{URL.URL_MESSAGE_REFERER,credential.getCookie()}).getContent("UTF-8");
    JSONObject result=JSONObject.fromObject(info).getJSONObject("result");
    //获取用户信息
    JSONArray usersInfo=result.getJSONArray("mem_info");
    //获取在线状态
    JSONArray usersStatus=result.getJSONArray("mem_status");
    //设置昵称,状态以及uin
    int tempIndex=0;
    for(int i=0;i<usersInfo.size();i++){
        JSONObject tempUserInfo=JSONObject.fromObject(usersInfo.get(i));
        User tempUser=new User(tempUserInfo.getLong("uin"));
        tempUser.setNickName(tempUserInfo.getString("nick"));
        if(tempIndex<usersStatus.size()&&tempUser.getUID()==JSONObject.fromObject(usersStatus.get(tempIndex)).getLong("uin")){
            tempUser.setOnlineStatus(true);
            tempIndex++;
    }
        users.add(tempUser);
    }
    return users;

}
项目:cjs_ssms    文件:SelectController.java   
/**
 * commonGridQuery 通用grid数据查询
 * key:查询条件书写规范: "UUserMapper_gridUsers"(Dao接口名_方法名)
 *
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/comGridQuery", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> commonGridQuery(HttpServletRequest request, HttpServletResponse response) throws Exception {

  HashMap<String, String> params = HttpReqsUtil.getRequestVals(request);
  log.debug("grid通用查询参数:==>" + String.valueOf(params));

  String data = params.get("data");
  JSONObject obj = JSONObject.fromObject(data);//查询条件
  HashMap<String, String> paramsMap = (HashMap<String, String>) JSONObject.toBean(JSONObject.fromObject(obj), HashMap.class);

  Map<String, Object> resultMap = null;

  /*分页*/
  int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
  int pageSize = Integer.parseInt(request.getParameter("pageSize"));
  /*字段排序*/
  String sortField = request.getParameter("sortField");
  String sortOrder = request.getParameter("sortOrder");

  resultMap = selectService.queryGridKey(pageIndex,pageSize,sortField,sortOrder,paramsMap);

  return resultMap;
}
项目:private-WeChat    文件:AuthorizationService.java   
/**
 * 刷新网页授权凭证
 * @param appId
 * @param appSecret
 * @param code
 * @return
 */
public Oauth2Token refreshOauth2Token(String appId,String refreshToken){
    logger.info("refreshOauth2Token appId : {} , refreshToken : {} ", appId, refreshToken);
    Oauth2Token oauth2Token = null;
    String requestUrl = refresh_token_url.replace("APPID", appId).replace("REFRESH_TOKEN", refreshToken);
    JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
    if(null != jsonObject){
        try{
            oauth2Token = new Oauth2Token();
            oauth2Token.setAccessToken(jsonObject.getString("access_token"));
            oauth2Token.setExpiresIn(jsonObject.getInt("expires_in"));
            oauth2Token.setRefreshToken(jsonObject.getString("refresh_token"));
            oauth2Token.setOpenId(jsonObject.getString("openid"));
            oauth2Token.setScope(jsonObject.getString("scope"));
        }catch(Exception e){
            oauth2Token = null;
            int errCode = jsonObject.getInt("errcode");
            String errMsg = jsonObject.getString("errmsg");
            logger.error("刷新网页授权凭证失败 errCode : {} , errmsg : {} ", errCode,errMsg);
        }
    }
    logger.info("refreshOauth2Token => 返回 :" + com.alibaba.fastjson.JSONObject.toJSONString(oauth2Token)); 
    return oauth2Token;
}
项目:WeiXing_xmu-2016-MrCode    文件:MessageSend.java   
@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception{
    /*for (int i = 0; i < 100; i++) {
        System.out.println(MessageSend.getVerificationCode());
    }*/

    JSONObject result = JSONObject.fromObject(DataUtils.getMap("res","123465461"));
    System.out.println(result.get("res"));
    /*try {
        String msg = MessageSend.sendDynamicVerification("546824", "15959277729");
        System.out.println(msg);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }*/
   }
项目:cjs_ssms    文件:SelectController.java   
/**
 * users gird表查询
 *
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/userGridQuery", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> usersGridQuery(HttpServletRequest request, HttpServletResponse response) throws Exception {

  HashMap<String, String> params = HttpReqsUtil.getRequestVals(request);
  log.debug("grid通用查询参数:==>" + String.valueOf(params));

  String data = params.get("data");
  JSONObject obj = JSONObject.fromObject(data);//查询条件
  HashMap<String, String> paramsMap = (HashMap<String, String>) JSONObject.toBean(JSONObject.fromObject(obj), HashMap.class);

  Map<String, Object> resultMap = null;

  /*分页*/
  int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));
  int pageSize = Integer.parseInt(request.getParameter("pageSize"));
  /*字段排序*/
  String sortField = request.getParameter("sortField");
  String sortOrder = request.getParameter("sortOrder");

  return  getGrids(pageIndex, pageSize, paramsMap);
}
项目:private-WeChat    文件:AuthorizationService.java   
/**
 * 获取网页授权凭证
 * @param appId
 * @param appSecret
 * @param code
 * @return
 */
public Oauth2Token getOauth2Token(String appId,String appSecret,String code){
    Oauth2Token oauth2Token = null;
    String requestUrl = access_token_url.replace("APPID", appId).replace("SECRET", appSecret).replace("CODE", code);
    logger.info("getOauth2Token => ###### requestUrl : " + requestUrl);
    JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
    if(null != jsonObject){
        try{
            oauth2Token = new Oauth2Token();
            oauth2Token.setAccessToken(jsonObject.getString("access_token"));
            oauth2Token.setExpiresIn(jsonObject.getInt("expires_in"));
            oauth2Token.setRefreshToken(jsonObject.getString("refresh_token"));
            oauth2Token.setOpenId(jsonObject.getString("openid"));
            oauth2Token.setScope(jsonObject.getString("scope"));
        }catch(Exception e){
            oauth2Token = null;
            int errCode = jsonObject.getInt("errcode");
            String errMsg = jsonObject.getString("errmsg");
            logger.error("获取网页授权凭证失败 errCode : {} , errmsg : {} ", errCode,errMsg);
        }
    }
    logger.info("getOauth2Token => 返回 :" + com.alibaba.fastjson.JSONObject.toJSONString(oauth2Token)); 
    return oauth2Token;
}
项目:WeiXing_xmu-2016-MrCode    文件:LoginPhoneAction.java   
/**
 * 发送短信验证码
 * 
 * @return
 */
@Action(value = "sendVerification")
public void sendVerification() throws Exception {
    String phone = getParameter("phone");
    System.out.println("CustomerAction.sendVerification()");
    // 1.生成验证码
    String verificationCode = MessageSend.getVerificationCode();
    try {
        JSONObject result = JSONObject
                .fromObject(MessageSend.sendDynamicVerification(
                        verificationCode, phone));
        if ("OK".equals(result.get("msg"))) {
            session.clear();
            session.put("verificationCode", verificationCode);
            writeStringToResponse("【ok】");
        }
    } catch (Exception e) {
        log.error("发送验证码失败!");
        e.printStackTrace();
    }

}
项目:kettle_support_kettle8.0    文件:JSONUtil.java   
/**
 * 从一个JSON 对象字符格式中得到一个java对象,形如: {"id" : idValue, "name" : nameValue,
 * "aBean" : {"aBeanId" : aBeanIdValue, ...}}
 * 
 * @param object
 * @param clazz
 * @return
 */
public static Object getDTO(String jsonString, Class<?> clazz) {
    JSONObject jsonObject = null;
    try {
        setDataFormat2JAVA();
        jsonObject = JSONObject.fromObject(jsonString);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return JSONObject.toBean(jsonObject, clazz);
}
项目:nem-apps    文件:NISQuery.java   
public static MosaicFeeInformation findMosaicFeeInformationByNIS(MosaicId mosaicId){
    String queryResult = HttpClientUtils.get(Constants.URL_NAMESPACE_MOSAIC_DEFINITION_PAGE + "?namespace=" + mosaicId.getNamespaceId().toString());
    JSONObject json = JSONObject.fromObject(queryResult);
    if(json==null || !json.containsKey("data") || json.getJSONArray("data").size()==0){
        return null;
    }
    JSONArray array = json.getJSONArray("data");
    for(int i=0;i<array.size();i++){
        JSONObject item = array.getJSONObject(i);
        JSONObject mosaic = item.getJSONObject("mosaic");
        JSONObject id = mosaic.getJSONObject("id");
        if(mosaicId.getName().equals(id.getString("name"))){
            JSONArray properties = mosaic.getJSONArray("properties");
            String initialSupply = "";
            String divisibility = "";
            for(int j=0;j<properties.size();j++){
                JSONObject property = properties.getJSONObject(j);
                if("initialSupply".equals(property.getString("name"))){
                    initialSupply = property.getString("value");
                } else if("divisibility".equals(property.getString("name"))){
                    divisibility = property.getString("value");
                }
            }
            if(!"".equals(initialSupply) && !"".equals(divisibility)){
                return new MosaicFeeInformation(Supply.fromValue(Long.valueOf(initialSupply)), Integer.valueOf(divisibility));
            }
        }
    }
    return null;
}
项目:kettle_support_kettle8.0    文件:JSONUtil.java   
/**
 * 从一个JSON数组得到一个java对象数组,形如: [{"id" : idValue, "name" : nameValue}, {"id" :
 * idValue, "name" : nameValue}, ...]
 * 
 * @param object
 * @param clazz
 * @return
 */
public static Object[] getDTOArray(String jsonString, Class<?> clazz) {
    setDataFormat2JAVA();
    JSONArray array = JSONArray.fromObject(jsonString);
    Object[] obj = new Object[array.size()];
    for (int i = 0; i < array.size(); i++) {
        JSONObject jsonObject = array.getJSONObject(i);
        obj[i] = JSONObject.toBean(jsonObject, clazz);
    }
    return obj;
}
项目:jaffa-framework    文件:ExcelExportService.java   
/**
 * Converts the input JSON structure into an instance of the beanClassName.
 * If the beanClassName is null, then an instance of org.apache.commons.beanutils.DynaBean will be returned.
 * 
 * @param input
 *            input as a JSON structure.
 * @param beanClassName
 *            the name of the bean class.
 * @return the input JSON structure as an instance of the beanClassName.
 * @throws ClassNotFoundException if the beanClassName is invalid.
 */
public static Object jsonToBean(String input, String beanClassName) throws ClassNotFoundException {
    if (log.isDebugEnabled())
        log.debug("Converting JSON '" + input + "' into an instance of " + beanClassName);
    registerCustomMorphers();
    Class beanClass = beanClassName != null ? Class.forName(beanClassName) : null;
    JSONObject jsonObject = JSONObject.fromObject(input);
    Object bean = JSONObject.toBean(jsonObject, createJsonConfig(beanClass));
    if (log.isDebugEnabled())
        log.debug("Converted to: " + bean);
    return bean;
}
项目:LibrarySystem    文件:BorrowAction.java   
public String  getBackInfoById(){
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("application/json;charset=utf-8");
    BackInfo backInfo = new BackInfo();
    backInfo.setBorrowId(borrowId);
    BackInfo newBackInfo = backService.getBackInfoById(backInfo);
    JsonConfig jsonConfig = new JsonConfig();
    jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
        public boolean apply(Object obj, String name, Object value) {
        if(obj instanceof Authorization||name.equals("authorization") || obj instanceof Set || name.equals("borrowInfos")){ 
            return true;
        }else{
            return false;
        }
       }
    });


    JSONObject jsonObject = JSONObject.fromObject(newBackInfo,jsonConfig);
    try {
        response.getWriter().print(jsonObject);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }
    return null;
}
项目:kettle_support_kettle8.0    文件:JSONUtil.java   
/**
 * 把数据对象转换成json字符串 DTO对象形如:{"id" : idValue, "name" : nameValue, ...}
 * 数组对象形如:[{}, {}, {}, ...] map对象形如:{key1 : {"id" : idValue, "name" :
 * nameValue, ...}, key2 : {}, ...}
 * 
 * @param object
 * @return
 */
public static String getJSONString(Object object) throws Exception {
    String jsonString = null;
    // 日期值处理器
    JsonConfig jsonConfig = new JsonConfig();
    if (object != null) {
        if (object instanceof Collection || object instanceof Object[]) {
            jsonString = JSONArray.fromObject(object, jsonConfig)
                    .toString();
        } else {
            jsonString = JSONObject.fromObject(object, jsonConfig)
                    .toString();
        }
    }
    return jsonString == null ? "{}" : jsonString;
}
项目:WeiXing_xmu-2016-MrCode    文件:BaseAction.java   
public void writeJsonToResponse(Object o, Map<String, Object> otherParams) {
    JsonConfig config = new JsonConfig();
    config.setExcludes(new String[] { "addTime" });// 除去dept属�?
    HashMap<String, Object> tempMap = new HashMap<String, Object>();
    tempMap.put("Model", o);
    if (otherParams != null) {
        Iterator<Entry<String, Object>> iter = otherParams.entrySet()
                .iterator();
        while (iter.hasNext()) {
            Entry<String, Object> entry = iter.next();
            tempMap.put(entry.getKey(), entry.getValue());
        }
    }
    JSONObject json = JSONObject.fromObject(tempMap, config);
    writeStringToResponse(json.toString());
}
项目:jaffa-framework    文件:ExcelExportService.java   
/**
 * Converts the input JSON structure into an instance of the beanClassName.
 * If the beanClassName is null, then an instance of org.apache.commons.beanutils.DynaBean will be returned.
 *
 * @param input
 *            input as a JSON structure.
 * @param beanClassName
 *            the name of the bean class.
 * @return the input JSON structure as an instance of the beanClassName.
 * @throws ClassNotFoundException if the beanClassName is invalid.
 */
public static Object jsonToBean(String input, String beanClassName) throws ClassNotFoundException {
    if (log.isDebugEnabled())
        log.debug("Converting JSON '" + input + "' into an instance of " + beanClassName);
    registerCustomMorphers();
    Class beanClass = beanClassName != null ? Class.forName(beanClassName) : null;
    JSONObject jsonObject = JSONObject.fromObject(input);
    Object bean = JSONObject.toBean(jsonObject, createJsonConfig(beanClass));
    if (log.isDebugEnabled())
        log.debug("Converted to: " + bean);
    return bean;
}
项目:anychat    文件:UserGroupData.java   
public UserGroupData(JSONObject userGroupData) {
    if (userGroupData.containsKey("userGroupId")) {
        this.userGroupId = userGroupData.getString("userGroupId");
    }
    if (userGroupData.containsKey("userGroupName")) {
        this.userGroupName = userGroupData.getString("userGroupName");
    }
}
项目:hippo-external-document-picker-example-implementation    文件:DocumentServiceFacade.java   
/**
 * This method sets what data form the external source should be stored on the document.
 * In this case it stores the entire json object as string
 *
 * @param context
 * @param exdocs
 */
@Override
public void setFieldExternalDocuments(ExternalDocumentServiceContext context, ExternalDocumentCollection<JSONObject> exdocs) {
    final String fieldName = context.getPluginConfig().getString(PARAM_EXTERNAL_DOCS_FIELD_NAME);

    if (StringUtils.isBlank(fieldName)) {
        throw new IllegalArgumentException("Invalid plugin configuration parameter for '" + PARAM_EXTERNAL_DOCS_FIELD_NAME + "': " + fieldName);
    }

    try {
        final Node contextNode = context.getContextModel().getNode();
        final List<String> docIds = new ArrayList<String>();

        for (Iterator<? extends JSONObject> it = exdocs.iterator(); it.hasNext(); ) {
            JSONObject doc = it.next();
            docIds.add(doc.toString());
        }

        contextNode.setProperty(fieldName, docIds.toArray(new String[docIds.size()]));
    } catch (RepositoryException e) {
        log.error("Failed to set related exdoc array field.", e);
    }
}
项目:anychat    文件:IdentityAction.java   
/**
 * 获取好友列表相当于组里的所有人
 * 
 * @param userGroupTopId
 *            组id
 * @param token
 *            身份
 * @return
 */
public static List<UserData> getFriendList(String userGroupTopId, String token) {
    JSONObject js = new JSONObject();
    js.put("hOpCode", "13");
    js.put("userGroupTopId", userGroupTopId);
    Map<String, String> header = new HashMap<>();
    header.put("hOpCode", "13");
    header.put("token", token);
    byte[] returnByte = HttpUtil.send(js.toString(), CommonConfigChat.IDENTITY_URL, header, HttpUtil.POST);
    if (returnByte != null) {
        String str = null;
        try {
            str = new String(returnByte, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            WSManager.log.error("返回字符串解析异常", e);
        }
        JSONObject returnjs = JSONObject.fromObject(str);
        // 如果返回的是错误类型,说明用户中心拦截器没通过
        if (returnjs.getString("hOpCode").equals("0")) {
            return null;
        }
        JSONArray jsArray = returnjs.getJSONArray("user");
        List<UserData> list = new ArrayList<>();
        for (int i = 0; i < jsArray.size(); i++) {
            JSONObject user = jsArray.getJSONObject(i);
            UserData userData = new UserData(user);
            list.add(userData);
        }
        return list;
    }
    return null;
}
项目:wangmarket    文件:SiteController.java   
/**
 * 删除当前网站内的文件,删除OSS存储的数据
 * @param fileName 传入oss的key,如345.html、news/asd.jpg
 */
@RequestMapping("deleteOssData")
public void deleteOssData(Model model,HttpServletResponse response,
        @RequestParam(value = "fileName", required = true) String fileName){
    fileName = filter(fileName);
    AttachmentFile.deleteObject("site/"+getSiteId()+"/"+fileName);

    AliyunLog.addActionLog(getSiteId(), "删除当前网站内存储的文件:"+fileName);

    JSONObject json = new JSONObject();
    json.put("result", "1");
    response.setCharacterEncoding("UTF-8");  
    response.setContentType("application/json; charset=utf-8");  
    PrintWriter out = null;  
    try { 
        out = response.getWriter();  
        out.append(json.toString());
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        if (out != null) {  
            out.close();  
        }  
    }  
}
项目:ibm-cloud-devops    文件:DeployableMappingNotificationExecution.java   
@Override
protected Void run() throws Exception {
    PrintStream printStream = listener.getLogger();
    String webhookUrl;

    if(Util.isNullOrEmpty(step.getWebhookUrl())){
        webhookUrl = Util.getWebhookUrl(envVars);
    } else {
        webhookUrl = step.getWebhookUrl();
    }

    String status = step.getStatus().trim();
    //check all the required env vars
    if (!Util.allNotNullOrEmpty(status)) {
        printStream.println("[IBM Cloud DevOps] Required parameter null or empty.");
        printStream.println("[IBM Cloud DevOps] Error: Failed to notify OTC.");
        return null;
    }

    if ("SUCCESS".equals(status)) { // send deployable mapping message on for successful builds
        JSONObject message = MessageHandler.buildDeployableMappingMessage(envVars, printStream);
        MessageHandler.postToWebhook(webhookUrl, true, message, printStream);
    }
    return null;
}
项目:ssm-demo    文件:ArticleController.java   
/**
 * 查找相应的数据集合
 * 
 * @param page
 * @param rows
 * @param article
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/list")
public String list(
        @RequestParam(value = "page", required = false) String page,
        @RequestParam(value = "rows", required = false) String rows,
        Article article, HttpServletResponse response) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();
    if (page != null && rows != null) {
        PageBean pageBean = new PageBean(Integer.parseInt(page),
                Integer.parseInt(rows));
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
    }
    if (article != null) {
        map.put("articleTitle",
                StringUtil.formatLike(article.getArticleTitle()));
    }
    List<Article> articleList = articleService.findArticle(map);
    Long total = articleService.getTotalArticle(map);
    JSONObject result = new JSONObject();
    JSONArray jsonArray = JSONArray.fromObject(articleList);
    result.put("rows", jsonArray);
    result.put("total", total);
    ResponseUtil.write(response, result);
    log.info("request: article/list , map: " + map.toString());
    return null;
}
项目:ssm-demo    文件:ArticleController.java   
/**
 * 保存或修改
 * 
 * @param article
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/save")
public String save(Article article, HttpServletResponse response)
        throws Exception {
    int resultTotal = 0;
    if (article.getId() == null) {
        article.setArticleCreateDate(DateUtil.getCurrentDateStr());
        resultTotal = articleService.addArticle(article);
    } else {
        resultTotal = articleService.updateArticle(article);
    }
    JSONObject result = new JSONObject();
    if (resultTotal > 0) {
        result.put("success", true);
    } else {
        result.put("success", false);
    }
    ResponseUtil.write(response, result);
    log.info("request: article/save , " + article.toString());
    return null;
}
项目:DanmuChat    文件:JsonObject.java   
public static JSONObject doGetJson(String url) {
    JSONObject jsonObject = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet= new HttpGet(url);
    try {
        HttpResponse response=httpClient.execute(httpGet);
        HttpEntity enyity=response.getEntity();
        if (enyity != null) {
            String result=EntityUtils.toString(enyity,"UTF-8");
            logger.info("JSONObject: {}",result);
            jsonObject=JSONObject.fromObject(result);
        }
        httpGet.releaseConnection();
    } catch (IOException e) {
        logger.error("方法doGetJson失败:{}", e.getMessage());
    }

    return jsonObject;
}
项目:DWSurvey    文件:MySurveyAction.java   
public String attrs() throws Exception {
    HttpServletRequest request=Struts2Utils.getRequest();
    HttpServletResponse response=Struts2Utils.getResponse();
    try{
        SurveyDirectory survey=surveyDirectoryManager.getSurvey(id);
        JsonConfig cfg = new JsonConfig();
        cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"});
        JSONObject jsonObject=JSONObject.fromObject(survey,cfg);
        response.getWriter().write(jsonObject.toString());
    }catch(Exception e){
        e.printStackTrace();
    }
    return null;
}
项目:IPCInvoker    文件:IPCInvokeTaskProcessor.java   
@Override
    public boolean process(AGContext context, JSONObject env, JavaFileObject javaFileObject, TypeDefineCodeBlock typeDefineCodeBlock, Set<? extends BaseStatement> set) {
        if (typeDefineCodeBlock.getAnnotation(IPCInvokeTaskManager.class.getSimpleName()) == null) {
            Log.i(TAG, "the TypeDefineCodeBlock do not contains 'IPCInvokeTaskManager' annotation.(%s)", javaFileObject.getFileName());
            return false;
        }
        if (set.isEmpty()) {
            Log.i(TAG, "containsSpecialAnnotationStatements is nil");
            return false;
        }
        final String outputDir = env.optString(EnvArgsConstants.KEY_OUTPUT_DIR);
        final String pkg = env.optString(EnvArgsConstants.KEY_PACKAGE);
        final String filePath = env.optString(EnvArgsConstants.KEY_FILE_PATH);

        if (Util.isNullOrNil(outputDir)) {
            Log.i(TAG, "process failed, outputDir is null or nil.(filePath : %s)", filePath);
            return false;
        }
        JSONObject args = new JSONObject();
//        args.put("template", "");
        args.put("templateTag", "ipc-invoker-gentask");
        args.put(ArgsConstants.EXTERNAL_ARGS_KEY_DEST_DIR, outputDir);
        args.put("toFile", Util.joint(File.separator, Util.exchangeToPath(pkg),
                String.format("%s$AG.java", typeDefineCodeBlock.getName().getName())));
        args.put("fileObject", javaFileObject.toJSONObject());
        args.put("methodSet", toJSONArray(set));
        context.execProcess("template-processor", args);
        return true;
    }
项目:ssm-demo    文件:StoreController.java   
/**
 * 开启书架继续放书
 *
 * @param id
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/openStore")
public String openStore(@RequestParam(value = "ids") String ids,
                        HttpServletResponse response) throws Exception {
    JSONObject result = new JSONObject();
    String[] idsStr = ids.split(",");
    Store temp = null;
    int resultTotal = 0;
    for (int i = 0; i < idsStr.length; i++) {
        temp = storeService.getStoreById(idsStr[i]);
        if (temp != null && temp.getStatus() != 0) {
            temp.setStatus(0);
            resultTotal += storeService.updStore(temp);
        }
    }
    if (resultTotal > 0)
        result.put("success", true);
    else
        result.put("success", false);
    ResponseUtil.write(response, result);
    log.info("request: store/openStore , ids: " + ids);
    return null;
}
项目:nem-apps    文件:CosignMultisigTransaction.java   
public String send_v2(String fee){
    // collect parameters
    TimeInstant timeInstant = new SystemTimeProvider().getCurrentTime();
    KeyPair senderKeyPair = new KeyPair(PrivateKey.fromHexString(this.privateKey));
    Account senderAccount = new Account(senderKeyPair);
    Account multisigAccount = new Account(Address.fromPublicKey(PublicKey.fromHexString(this.multisigPublicKey)));
    Hash otherTransactionHash = Hash.fromHexString(this.innerTransactionHash);
    // create multisig signature transaction
    MultisigSignatureTransaction multisigSignatureTransaction = new MultisigSignatureTransaction(
            timeInstant, senderAccount, multisigAccount, otherTransactionHash);
    if(fee==null){
        TransactionFeeCalculatorAfterForkForApp feeCalculator = new TransactionFeeCalculatorAfterForkForApp();
        multisigSignatureTransaction.setFee(feeCalculator.calculateMinimumFee(multisigSignatureTransaction));
    } else {
        multisigSignatureTransaction.setFee(Amount.fromNem(0));
    }
    multisigSignatureTransaction.setDeadline(timeInstant.addHours(23));
    multisigSignatureTransaction.sign();
    JSONObject params = new JSONObject();
    final byte[] data = BinarySerializer.serializeToBytes(multisigSignatureTransaction.asNonVerifiable());
    params.put("data", ByteUtils.toHexString(data));
    params.put("signature", multisigSignatureTransaction.getSignature().toString());
    return HttpClientUtils.post(Constants.URL_TRANSACTION_ANNOUNCE, params.toString());
}
项目:jmeter-bzm-plugins    文件:LoadosophiaAPIClient.java   
public LoadosophiaUploadResults sendFiles(File targetFile, LinkedList<String> perfMonFiles) throws IOException {
    notifier.notifyAbout("Starting upload to BM.Sense");
    LoadosophiaUploadResults results = new LoadosophiaUploadResults();
    LinkedList<FormBodyPart> partsList = getUploadParts(targetFile, perfMonFiles);

    JSONObject res = queryObject(createPost(address + "api/files", partsList), 201);

    int queueID = Integer.parseInt(res.getString("QueueID"));
    results.setQueueID(queueID);

    int testID = getTestByUpload(queueID);
    results.setTestID(testID);

    setTestTitleAndColor(testID, title.trim(), colorFlag);
    results.setRedirectLink(address + "gui/" + testID + "/");
    return results;
}
项目:jmeter-bzm-plugins    文件:LoadosophiaAPIClient.java   
private void setTestTitleAndColor(int testID, String title, String color) throws IOException {
    if (title.isEmpty() && (color.isEmpty() || color.equals(COLOR_NONE)) ) {
        return;
    }

    JSONObject data = new JSONObject();
    if (!title.isEmpty()) {
        data.put("title", title);
    }

    if (!title.isEmpty()) {
        data.put("colorFlag", color);
    }

    query(createPatch(address + "api/tests/" + testID, data), 200);
}
项目:Equella    文件:SpellcheckServlet.java   
@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
    String spellRequestJSON = req.getReader().readLine();

    JSONObject jsonReqObject = JSONObject.fromObject(spellRequestJSON);

    jsonReqObject.get("params");

    SpellcheckRequest spellRequest = new SpellcheckRequest();
    spellRequest.setId(jsonReqObject.getString("id"));
    spellRequest.setMethod(jsonReqObject.getString("method"));
    SpellcheckRequestParams params = new SpellcheckRequestParams();
    params.setLang(jsonReqObject.getJSONArray("params").getString(0));
    Object object = jsonReqObject.getJSONArray("params").get(1);
    if( object instanceof String )
    {
        params.setStringList(Collections.singletonList(object.toString()));
    }
    else if( object instanceof JSONArray )
    {
        params.setStringList((JSONArray) object);
    }
    spellRequest.setParams(params);

    SpellcheckResponse spellResponse = spellcheckService.service(spellRequest);

    resp.setHeader("Cache-Control", "no-cache, no-store"); //$NON-NLS-1$//$NON-NLS-2$
    resp.setContentType("application/json"); //$NON-NLS-1$
    resp.getWriter().write(parseResponseToJSON(spellResponse));
}
项目:jmeter-bzm-plugins    文件:WorkspaceTest.java   
@org.junit.Test
public void testFromJSON() throws Exception {
    StatusNotifierCallbackTest.StatusNotifierCallbackImpl notifier = new StatusNotifierCallbackTest.StatusNotifierCallbackImpl();
    BlazeMeterHttpUtilsEmul emul = new BlazeMeterHttpUtilsEmul(notifier, "test_address", "test_data_address", new BlazeMeterReport());
    JSONObject object = new JSONObject();
    object.put("id", "workspaceId");
    object.put("name", "workspaceName");
    Workspace workspace = Workspace.fromJSON(emul, object);
    assertEquals("workspaceId", workspace.getId());
    assertEquals("workspaceName", workspace.getName());
}
项目:aws-codecommit-trigger-plugin    文件:SQSScmConfig.java   
@Override
public SQSScmConfig newInstance(StaplerRequest req, @Nonnull JSONObject jsonObject) throws FormException {
    JSONObject json = jsonObject.getJSONObject("type");
    json.put("type", json.getString("value"));
    json.remove("value");
    return super.newInstance(req, json);//req.bindJSON(SQSScmConfig.class, json);
}
项目:jmeter-bzm-plugins    文件:UserTest.java   
@org.junit.Test
public void testFlow() throws Exception {
    StatusNotifierCallbackTest.StatusNotifierCallbackImpl notifier = new StatusNotifierCallbackTest.StatusNotifierCallbackImpl();
    BlazeMeterReport report = new BlazeMeterReport();

    BlazeMeterHttpUtilsEmul emul = new BlazeMeterHttpUtilsEmul(notifier, "test_address", "test_data_address", report);

    User user = new User(emul);
    emul.addEmul(new JSONObject());
    user.ping();

    JSONObject acc = new JSONObject();
    acc.put("id", "accountId");
    acc.put("name", "accountName");
    JSONArray result = new JSONArray();
    result.add(acc);
    result.add(acc);
    JSONObject response = new JSONObject();
    response.put("result", result);
    emul.addEmul(response);

    List<Account> accounts = user.getAccounts();
    assertEquals(2, accounts.size());
    for (Account account : accounts) {
        assertEquals("accountId", account.getId());
        assertEquals("accountName", account.getName());
    }
}
项目:Higher-Cloud-Computing-Project    文件:GetUserInfo.java   
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
  String userId = request.getParameter("user_id");
  DBcrud conn = new DBcrud();
  JSONObject jsa = new JSONObject();
  JSONArray um = new JSONArray();
  if (AuxiliaryTools.checkValidParameter(userId)){
    jsa = (conn.getUserInfor(userId));
    if ((um = conn.userMachine(userId)).size()>0) {
      jsa.put("machine_list",um);
    }
  }
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out;
    out = response.getWriter();
    out.println(jsa);
}
项目:jmeter-bzm-plugins    文件:Test.java   
/**
 * Start Anonymous External test
 * @return public link to the report
 */
public String startAnonymousExternal() throws IOException {
    JSONObject result = sendStartTest(httpUtils.getAddress() + "/api/v4/sessions", 201);
    setTestFields(result.getJSONObject("test"));
    reportURL = result.getString("publicTokenUrl");
    fillFields(result);
    return reportURL;
}