com.alibaba.fastjson.JSONObject Java Examples

The following examples show how to use com.alibaba.fastjson.JSONObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SaveAdvertInfoListener.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * business 数据转移到 instance
 *
 * @param dataFlowContext 数据对象
 * @param business        当前业务对象
 */
@Override
protected void doBusinessToInstance(DataFlowContext dataFlowContext, Business business) {
    JSONObject data = business.getDatas();

    Map info = new HashMap();
    info.put("bId", business.getbId());
    info.put("operate", StatusConstant.OPERATE_ADD);

    //广告信息信息
    List<Map> businessAdvertInfo = advertServiceDaoImpl.getBusinessAdvertInfo(info);
    if (businessAdvertInfo != null && businessAdvertInfo.size() > 0) {
        reFreshShareColumn(info, businessAdvertInfo.get(0));
        advertServiceDaoImpl.saveAdvertInfoInstance(info);
        if (businessAdvertInfo.size() == 1) {
            dataFlowContext.addParamOut("advertId", businessAdvertInfo.get(0).get("advert_id"));
        }
    }
}
 
Example #2
Source File: TTLDataConverse.java    From RCT with Apache License 2.0 6 votes vote down vote up
private Map<String, ReportData> toReportDataMap(Set<String> newSetData){
    Map<String, ReportData> reportDataHashMap = new HashMap<String, ReportData>(100);
    if(null != newSetData) {
        JSONObject jsonObject = null;
        String prefix = null;
        ReportData reportData = null;
        for(String object : newSetData) {
            jsonObject = JSON.parseObject(object);
            prefix = jsonObject.getString("prefix");
            reportData = reportDataHashMap.get(prefix);
            if(null == reportData) {
                reportData = new ReportData();
                reportData.setCount(Long.parseLong(jsonObject.getString("noTTL")));
                reportData.setBytes(Long.parseLong(jsonObject.getString("TTL")));
                reportData.setKey(prefix);
            }
            else {
                reportData.setCount(Long.parseLong(jsonObject.getString("noTTL")) + reportData.getCount());
                reportData.setBytes(Long.parseLong(jsonObject.getString("TTL")) + reportData.getBytes());
            }
            reportDataHashMap.put(prefix, reportData);
        }
    }
    return reportDataHashMap;
}
 
Example #3
Source File: RemoveUserInfoListener.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 修改用户信息至 business表中
 *
 * @param dataFlowContext 数据对象
 * @param business        当前业务对象
 */
@Override
protected void doSaveBusiness(DataFlowContext dataFlowContext, Business business) {
    JSONObject data = business.getDatas();

    Assert.notEmpty(data, "没有datas 节点,或没有子节点需要处理");

    Assert.jsonObjectHaveKey(data, UserPo.class.getSimpleName(), "datas 节点下没有包含 businessUser 节点");

    JSONObject businessUser = data.getJSONArray(UserPo.class.getSimpleName()).getJSONObject(0);

    Assert.jsonObjectHaveKey(businessUser, "userId", "businessUser 节点下没有包含 userId 节点");

    if (businessUser.getString("userId").startsWith("-")) {
        throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "userId 错误,不能自动生成(必须已经存在的userId)" + businessUser);
    }

    //自动插入DEL
    autoSaveDelBusinessUser(business, businessUser);
}
 
Example #4
Source File: JwtRealm.java    From zhcc-server with Apache License 2.0 6 votes vote down vote up
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    /*********************************************
     * RestfulPermissionFilter 过滤器说明:
     * Actions representing HTTP Method values (GET -> read, POST -> create, etc)
     * private static final String CREATE_ACTION = "create";
     * private static final String READ_ACTION = "read";
     * private static final String UPDATE_ACTION = "update";
     * private static final String DELETE_ACTION = "delete";
     *********************************************/
    // 如果不为securityManager配置缓存管理器,该方法在每次鉴权前都会从数据库中查询权限数据。
    // 分布式环境下,建议将权限保存在redis中,避免每次从数据库中加载。
    //JSONObject json = JSONObject.parseObject(principals.toString());
    Claims claims = jwtUtils.parseJWT(principals.toString());
    JSONObject json = JSONObject.parseObject(claims.getSubject());
    // 得到用户的权限code
    List<String> permissionCodeList = resourceService.listPermissionCodeByUserId(json.getIntValue("userId"));
    SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
    for (String permissionCode : permissionCodeList) {
        if (permissionCode != null && !permissionCode.trim().equals("")) {
            simpleAuthorInfo.addStringPermission(permissionCode);
        }
        // 如果要添加基于角色的鉴权,可调用simpleAuthorInfo.addRole("role_name")添加用户所属角色。
    }
    return simpleAuthorInfo;
}
 
Example #5
Source File: QuestionManager.java    From leetcode-editor with Apache License 2.0 6 votes vote down vote up
private static List<Tag> parseList(String str) {
    List<Tag> tags = new ArrayList<Tag>();

    if (StringUtils.isNotBlank(str)) {

        JSONArray jsonArray = JSONArray.parseArray(str);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            Tag tag = new Tag();
            tag.setSlug(object.getString("id"));
            tag.setType(object.getString("type"));
            String name = object.getString("name");
            if (StringUtils.isBlank(name)) {
                name = object.getString("name");
            }
            tag.setName(name);
            JSONArray questionArray = object.getJSONArray("questions");
            for (int j = 0; j < questionArray.size(); j++) {
                tag.addQuestion(questionArray.getInteger(j).toString());
            }
            tags.add(tag);
        }
    }
    return tags;
}
 
Example #6
Source File: UpdateVisitInfoListener.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * business to instance 过程
 *
 * @param dataFlowContext 数据对象
 * @param business        当前业务对象
 */
@Override
protected void doBusinessToInstance(DataFlowContext dataFlowContext, Business business) {

    JSONObject data = business.getDatas();

    Map info = new HashMap();
    info.put("bId", business.getbId());
    info.put("operate", StatusConstant.OPERATE_ADD);

    //访客信息信息
    List<Map> businessVisitInfos = visitServiceDaoImpl.getBusinessVisitInfo(info);
    if (businessVisitInfos != null && businessVisitInfos.size() > 0) {
        for (int _visitIndex = 0; _visitIndex < businessVisitInfos.size(); _visitIndex++) {
            Map businessVisitInfo = businessVisitInfos.get(_visitIndex);
            flushBusinessVisitInfo(businessVisitInfo, StatusConstant.STATUS_CD_VALID);
            visitServiceDaoImpl.updateVisitInfoInstance(businessVisitInfo);
            if (businessVisitInfo.size() == 1) {
                dataFlowContext.addParamOut("vId", businessVisitInfo.get("v_id"));
            }
        }
    }

}
 
Example #7
Source File: WeiXinController.java    From javabase with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/weixin/auth")
	public String weiXinAuth(Model model, String code, String token) throws Exception {
		String url = String.format(weiXinConfig.getAccessTokenUrl(), weiXinConfig.getAppid(), weiXinConfig.getSecret(), code);
		String result = Request.Get(url).execute().returnContent().asString();
		if (StringUtils.isNotEmpty(result)) {
			JSONObject jsonObject = JSONObject.parseObject(result);
			if (!jsonObject.containsKey("errcode")) {
				String openid = jsonObject.getString("openid");
				String accessToken = jsonObject.getString("access_token");
				String userInfoUrl = String.format(weiXinConfig.getUserinfoUrl(), accessToken, openid);
				String userInfoResult = Request.Get(userInfoUrl).execute().returnContent()
						.asString(Charset.forName("utf-8"));
				log.info("userInfoResult=" + userInfoResult);
				redisTemplate.opsForValue().set(token, "1",2, TimeUnit.MINUTES);
				redisTemplate.opsForValue().set(token + "info", userInfoResult, 30, TimeUnit.MINUTES);
				model.addAttribute("result","登录成功!");
			}else{
				model.addAttribute("result","登录失败!");
			}
		}
//		return "weixin/loginResult";
		return "redirect:https://ggj2010.bid/tiebaimage";
	}
 
Example #8
Source File: WebAuthWeixinApi.java    From jeewx-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 获取用户信息
 * @param openid
 * @param accessToken
 * @return
 */
public static JSONObject getWebAuthUserInfo(String openid,String accessToken){
	try {
		if(StringUtils.isEmpty(openid)){
			logger.info("openid为空");
			return null;
		}
		if(StringUtils.isEmpty(accessToken)){
			logger.info("accessToken为空");
			return null;
		}
		return httpRequest(getUserInfoUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid), "GET", null);
	} catch (Exception e) {
		logger.error("获取用户信息异常",e);
	}
	return null;
}
 
Example #9
Source File: HuobiProExchange.java    From GOAi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 获取account id
 * @param access access
 * @param secret secret
 * @return account id
 */
private String getAccountId(String access, String secret) {
    String id = this.getCache().get(access);
    if (!useful(id)) {
        String result = this.getAccounts(access, secret);
        if (useful(result)) {
            JSONObject r = JSON.parseObject(result);
            if (r.containsKey(STATUS) && OK.equals(r.getString(STATUS))) {
                JSONArray data = r.getJSONArray(DATA);
                for (int i = 0, s = data.size(); i < s; i++) {
                    JSONObject t = data.getJSONObject(i);
                    String accountId = t.getString("id");
                    String type = t.getString("type");
                    if ("spot".equals(type)) {
                        id = accountId;
                        this.getCache().set(access, id);
                        return id;
                    }
                }
            }
        }
        throw new ExchangeException(super.name.getName() + " " + Seal.seal(access)
                + " account_id: result is " + result);
    }
    return id;
}
 
Example #10
Source File: NginxController.java    From Jpom with MIT License 6 votes vote down vote up
/**
     * 获取配置文件信息页面
     *
     * @param path 白名单路径
     * @param name 名称
     * @return 页面
     */
    @RequestMapping(value = "item_data", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String itemData(String path, String name) {
        String newName = pathSafe(name);
        if (whitelistDirectoryService.checkNgxDirectory(path)) {
            File file = FileUtil.file(path, newName);
            JSONObject jsonObject = new JSONObject();
            String string = FileUtil.readUtf8String(file);
            jsonObject.put("context", string);
            String rName = StringUtil.delStartPath(file, path, true);
            // nginxService.paresName(path, file.getAbsolutePath())
            jsonObject.put("name", rName);
            jsonObject.put("whitePath", path);
            return JsonMessage.getString(200, "", jsonObject);
//            setAttribute("data", jsonObject);
        }
        return JsonMessage.getString(400, "错误");
    }
 
Example #11
Source File: ApplicationKeyBMOImpl.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 添加物业费用
 *
 * @param paramInJson     接口调用放传入入参
 * @param dataFlowContext 数据上下文
 * @return 订单服务能够接受的报文
 */
public void addOwnerKeyPhoto(JSONObject paramInJson, DataFlowContext dataFlowContext) {


    JSONObject businessUnit = new JSONObject();
    businessUnit.put("fileRelId", "-1");
    businessUnit.put("relTypeCd", "10000");
    businessUnit.put("saveWay", "table");
    businessUnit.put("objId", paramInJson.getString("memberId"));
    businessUnit.put("fileRealName", paramInJson.getString("ownerPhotoId"));
    businessUnit.put("fileSaveName", paramInJson.getString("fileSaveName"));

    FileRelPo fileRelPo = BeanConvertUtil.covertBean(businessUnit, FileRelPo.class);

    super.insert(dataFlowContext, fileRelPo, BusinessTypeConstant.BUSINESS_TYPE_SAVE_FILE_REL);

}
 
Example #12
Source File: RDBAnalyzeController.java    From RCT with Apache License 2.0 6 votes vote down vote up
/**
 * 动态改变属性值
 * 
 * 目前接受更改的属性值有: {@link Analyzer#FILTER_Bytes} {@link Analyzer#FILTER_ItemCount}
 * 
 * <code>
 * {
 *    "filterBytes": 1024,
 *    "filterItemCount": 10,
 *    "useCustomAlgo": boolean,
 *    "includeNoMatchPrefixKey": boolean,
 *    "maxEsSenderThreadNum": 2,
 *    "maxQueueSize": 1000,
 *    "maxMapSize": 1000
 * }
 * </code>
 * 
 * @param json
 * @return
 */
@RequestMapping(value = "/properties", method = RequestMethod.POST)
@ResponseBody
public String dynamicSetting(@RequestBody JSONObject json) {
	if (json.containsKey("filterBytes")) {
		Analyzer.FILTER_Bytes = json.getLong("filterBytes");
	}
	if (json.containsKey("filterItemCount")) {
		Analyzer.FILTER_ItemCount = json.getInteger("filterItemCount");
	}
	if (json.containsKey("useCustomAlgo")) {
		Analyzer.USE_Custom_Algo = json.getBoolean("useCustomAlgo");
	}
	if (json.containsKey("includeNoMatchPrefixKey")) {
		Analyzer.INCLUDE_NoMatchPrefixKey = json.getBoolean("includeNoMatchPrefixKey");
	}
	if (json.containsKey("maxEsSenderThreadNum")) {
		Analyzer.MAX_EsSenderThreadNum = json.getInteger("maxEsSenderThreadNum");
		AnalyzerWorker.workerNumChanged();
	}
	if (json.containsKey("maxQueueSize")) {
		Analyzer.MAX_QUEUE_SIZE = json.getInteger("maxQueueSize");
	}

	return this.settingObj().toJSONString();
}
 
Example #13
Source File: SysDepartRoleController.java    From teaching with Apache License 2.0 6 votes vote down vote up
/**
 * 保存数据规则至角色菜单关联表
 */
@PostMapping(value = "/datarule")
public Result<?> saveDatarule(@RequestBody JSONObject jsonObject) {
 try {
	 String permissionId = jsonObject.getString("permissionId");
	 String roleId = jsonObject.getString("roleId");
	 String dataRuleIds = jsonObject.getString("dataRuleIds");
	 log.info("保存数据规则>>"+"菜单ID:"+permissionId+"角色ID:"+ roleId+"数据权限ID:"+dataRuleIds);
	 LambdaQueryWrapper<SysDepartRolePermission> query = new LambdaQueryWrapper<SysDepartRolePermission>()
			 .eq(SysDepartRolePermission::getPermissionId, permissionId)
			 .eq(SysDepartRolePermission::getRoleId,roleId);
	 SysDepartRolePermission sysRolePermission = sysDepartRolePermissionService.getOne(query);
	 if(sysRolePermission==null) {
		 return Result.error("请先保存角色菜单权限!");
	 }else {
		 sysRolePermission.setDataRuleIds(dataRuleIds);
		 this.sysDepartRolePermissionService.updateById(sysRolePermission);
	 }
 } catch (Exception e) {
	 log.error("SysRoleController.saveDatarule()发生异常:" + e.getMessage(),e);
	 return Result.error("保存失败");
 }
 return Result.ok("保存成功!");
}
 
Example #14
Source File: DataParser.java    From EasyML with Apache License 2.0 6 votes vote down vote up
/**
 * Parse csv data to json object
 * 
 * @param datas  csv data list
 * @param columns   csv data column
 * @return
 */
public static List<JSONObject> parseCsvToJson(List<String> datas,List<String> columns)
{
	int startIndex = 0;
	List<JSONObject> results = new ArrayList<JSONObject>();
	for(int i = startIndex ; i<datas.size(); i++)
	{
		if(datas.get(i) == null || datas.get(i).equals(""))
		{
			results.add(null);
			continue;
		}
		String[] colDatas = datas.get(i).split(",");
		if(columns.get(0).equals(colDatas[0]))
			continue;
		JSONObject obj = new JSONObject();
		for(int k=0;k<colDatas.length;k++)
		{
			String colName = columns.get(k);
			String colValue = colDatas[k];
			obj.put(colName, colValue);
		}
		results.add(obj);
	}
	return results;
}
 
Example #15
Source File: WXDomStatement.java    From weex with Apache License 2.0 6 votes vote down vote up
/**
 * Create a command object for scroll the given view to the specified position.
 * @param ref {@link WXDomObject#ref} of the dom.
 * @param options the specified position
 */
void scrollToDom(final String ref, final JSONObject options) {
  if (mDestroy) {
    return;
  }
  WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(mInstanceId);

  mNormalTasks.add(new IWXRenderTask() {

    @Override
    public void execute() {
      mWXRenderManager.scrollToComponent(mInstanceId, ref, options);
    }
  });

  mDirty = true;
  if (instance != null) {
    instance.commitUTStab(WXConst.DOM_MODULE, WXErrorCode.WX_SUCCESS);
  }
}
 
Example #16
Source File: JedisScoredQueueStore.java    From vscrawler with Apache License 2.0 6 votes vote down vote up
@Override
public boolean addLast(String queueID, ResourceItem e) {
    if (!lockQueue(queueID)) {
        return false;
    }
    remove(queueID, e.getKey());
    Jedis jedis = jedisPool.getResource();
    try {
        jedis.rpush(makePoolQueueKey(queueID), e.getKey());
        jedis.hset(makeDataKey(queueID), e.getKey(), JSONObject.toJSONString(e));
    } finally {
        IOUtils.closeQuietly(jedis);
        unLockQueue(queueID);
    }
    return true;
}
 
Example #17
Source File: PopupProperty.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> getPropertyJson() {
	Map<String,Object> map = new HashMap<>();
	map.put("key",getKey());
	JSONObject prop = getCommonJson();
	if(code!=null) {
		prop.put("code",code);
	}
	if(destFields!=null) {
		prop.put("destFields",destFields);
	}
	if(orgFields!=null) {
		prop.put("orgFields",orgFields);
	}
	map.put("prop",prop);
	return map;
}
 
Example #18
Source File: AVNotificationManager.java    From java-unified-sdk with Apache License 2.0 6 votes vote down vote up
static Date getExpiration(String msg) {
  String result = "";
  try {
    JSONObject object = JSON.parseObject(msg);
    result = object.getString("_expiration_time");
  } catch (JSONException e) {
    // LogUtil.avlog.i(e);
    // 不应该当做一个Error发出来,既然expire仅仅是一个option的数据
    // Log.e(LOGTAG, "Get expiration date error.", e);
  }
  if (StringUtil.isEmpty(result)) {
    return null;
  }
  Date date = StringUtil.dateFromString(result);
  return date;
}
 
Example #19
Source File: ChatBotUtil.java    From ns4_gear_watchdog with Apache License 2.0 6 votes vote down vote up
/**
 * 发送消息
 * @param message 消息内容
 * @return
 */
public static String send(BotMessage message) {
    if (URL.equals("")) {
        init();
    }

    String  valid = validMessage(message);
    if (!StringUtils.isEmpty(valid)) {
        return valid;
    }

    HashMap<String,String> param = convertHashMap(message);

    return JSONObject.toJSONString(HttpClientUtil.doUmpHttp_HttpClient(param , URL));

}
 
Example #20
Source File: OrderServiceSMOImpl.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 保存耗时信息
 *
 * @param dataFlow
 */
private void saveCostTimeLogMessage(DataFlow dataFlow) {
    try {
        if (MappingConstant.VALUE_ON.equals(MappingCache.getValue(MappingConstant.KEY_COST_TIME_ON_OFF))) {
            List<DataFlowLinksCost> dataFlowLinksCosts = dataFlow.getLinksCostDates();
            JSONObject costDate = new JSONObject();
            JSONArray costDates = new JSONArray();
            JSONObject newObj = null;
            for (DataFlowLinksCost dataFlowLinksCost : dataFlowLinksCosts) {
                newObj = JSONObject.parseObject(JSONObject.toJSONString(dataFlowLinksCost));
                newObj.put("dataFlowId", dataFlow.getDataFlowId());
                newObj.put("transactionId", dataFlow.getTransactionId());
                costDates.add(newObj);
            }
            costDate.put("costDates", costDates);

            KafkaFactory.sendKafkaMessage(KafkaConstant.TOPIC_COST_TIME_LOG_NAME, "", costDate.toJSONString());
        }
    } catch (Exception e) {
        logger.error("报错日志出错了,", e);
    }
}
 
Example #21
Source File: AbstractCommunityBusinessServiceDataFlowListener.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 当修改数据时,查询instance表中的数据 自动保存删除数据到business中
 *
 * @param business      当前业务
 * @param communityAttr 小区属性
 */
protected void autoSaveDelBusinessCommunityAttr(Business business, JSONObject communityAttr) {
    Map info = new HashMap();
    info.put("attrId", communityAttr.getString("attrId"));
    info.put("communityId", communityAttr.getString("communityId"));
    info.put("statusCd", StatusConstant.STATUS_CD_VALID);
    List<Map> currentCommunityAttrs = getCommunityServiceDaoImpl().getCommunityAttrs(info);
    if (currentCommunityAttrs == null || currentCommunityAttrs.size() != 1) {
        throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info);
    }
    Map currentCommunityAttr = currentCommunityAttrs.get(0);
    currentCommunityAttr.put("bId", business.getbId());
    currentCommunityAttr.put("attrId", currentCommunityAttr.get("attr_id"));
    currentCommunityAttr.put("communityId", currentCommunityAttr.get("community_id"));
    currentCommunityAttr.put("specCd", currentCommunityAttr.get("spec_cd"));
    currentCommunityAttr.put("operate", StatusConstant.OPERATE_DEL);
    getCommunityServiceDaoImpl().saveBusinessCommunityAttr(currentCommunityAttr);
    for(Object key : currentCommunityAttr.keySet()) {
        if(communityAttr.get(key) == null) {
            communityAttr.put(key.toString(), currentCommunityAttr.get(key));
        }
    }
}
 
Example #22
Source File: DingtalkChatbotClient.java    From app-version with Apache License 2.0 6 votes vote down vote up
public SendResult send(String webhook, Message message) throws IOException {
    HttpPost httppost = new HttpPost(webhook);
    httppost.addHeader("Content-Type", "application/json; charset=utf-8");
    StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
    httppost.setEntity(se);
    SendResult sendResult = new SendResult();
    HttpResponse response = this.httpclient.execute(httppost);
    if (response.getStatusLine().getStatusCode() == 200) {
        String result = EntityUtils.toString(response.getEntity());
        JSONObject obj = JSONObject.parseObject(result);
        Integer errcode = obj.getInteger("errcode");
        sendResult.setErrorCode(errcode);
        sendResult.setErrorMsg(obj.getString("errmsg"));
        sendResult.setIsSuccess(errcode.equals(0));
    }

    return sendResult;
}
 
Example #23
Source File: SaveWorkflowInfoListener.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * business 数据转移到 instance
 *
 * @param dataFlowContext 数据对象
 * @param business        当前业务对象
 */
@Override
protected void doBusinessToInstance(DataFlowContext dataFlowContext, Business business) {
    JSONObject data = business.getDatas();

    Map info = new HashMap();
    info.put("bId", business.getbId());
    info.put("operate", StatusConstant.OPERATE_ADD);

    //工作流信息
    List<Map> businessWorkflowInfo = workflowServiceDaoImpl.getBusinessWorkflowInfo(info);
    if (businessWorkflowInfo != null && businessWorkflowInfo.size() > 0) {
        reFreshShareColumn(info, businessWorkflowInfo.get(0));
        workflowServiceDaoImpl.saveWorkflowInfoInstance(info);
        if (businessWorkflowInfo.size() == 1) {
            dataFlowContext.addParamOut("flowId", businessWorkflowInfo.get(0).get("flow_id"));
        }
    }
}
 
Example #24
Source File: SinkerWriteBolt.java    From DBus with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Tuple input) {
    List<DBusConsumerRecord<String, byte[]>> data = (List<DBusConsumerRecord<String, byte[]>>) input.getValueByField("data");
    try {
        if (isCtrl(data)) {
            JSONObject json = JSON.parseObject(new String(data.get(0).value(), "utf-8"));
            logger.info("[write bolt] received reload message .{} ", json);
            Long id = json.getLong("id");
            if (ctrlMsgId == id) {
                logger.info("[write bolt] ignore duplicate ctrl messages . {}", json);
            } else {
                ctrlMsgId = id;
                processCtrlMsg(json);
            }
        } else {
            sendData(data);
        }
        collector.ack(input);
    } catch (Exception e) {
        logger.error("[write bolt] execute error.", e);
        collector.fail(input);
    }
}
 
Example #25
Source File: ClassificationDataTest.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void execute() {
    Map<String, String> reqParams = new HashMap<>();
    reqParams.put("entity", "TestAllFields");
    reqParams.put("field", "CLASSIFICATION");
    ApiContext apiContext = new ApiContext(reqParams, null);

    JSONObject ret = (JSONObject) new ClassificationData().execute(apiContext);
    System.out.println(JSONUtils.prettyPrint(ret));
    Assert.assertNotNull(ret.get("error_code"));
}
 
Example #26
Source File: NormalTransformer.java    From ES-Fastloader with Apache License 2.0 5 votes vote down vote up
@Override
public JSONObject tranform(List<Object> valueList) throws HCatException {
    JSONObject data = new JSONObject();

    for(int i=0; i<typeList.size(); i++) {
        typeList.get(i).addField(data, valueList.get(i));
    }

    return data;
}
 
Example #27
Source File: CenterApi.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 这里预校验,请求报文中不能有 dataFlowId
 * @param orderInfo
 */
private void preValiateOrderInfo(String orderInfo) {

    Assert.jsonObjectHaveKey(orderInfo,"orders","请求报文中未包含orders节点,"+orderInfo);

    Assert.jsonObjectHaveKey(orderInfo,"business","请求报文中未包含business节点,"+orderInfo);

    if(JSONObject.parseObject(orderInfo).getJSONObject("orders").containsKey("dataFlowId")){
        throw new BusinessException(ResponseConstant.RESULT_CODE_ERROR,"报文中不能存在dataFlowId节点");
    }
}
 
Example #28
Source File: AuthPinterestRequest.java    From JustAuth with MIT License 5 votes vote down vote up
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
    String response = doPostAuthorizationCode(authCallback.getCode());
    JSONObject accessTokenObject = JSONObject.parseObject(response);
    this.checkResponse(accessTokenObject);
    return AuthToken.builder()
        .accessToken(accessTokenObject.getString("access_token"))
        .tokenType(accessTokenObject.getString("token_type"))
        .build();
}
 
Example #29
Source File: EntityConfig.java    From Vert.X-generator with MIT License 5 votes vote down vote up
/**
 * 将对象转换为JSONObject
 * 
 * @return
 */
public JSONObject toJson() {
	JSONObject result = new JSONObject();
	result.put("templateName", templateName);
	result.put("fieldCamel", fieldCamel);
	result.put("overrideFile", overrideFile);
	return result;
}
 
Example #30
Source File: TokenDemo.java    From ais-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * 扭曲矫正,使用Base64编码后的文件方式,使用Token认证方式访问服务
 * @param token 
 * 			token认证串
 * @param formFile 
 * 			文件路径
 * @throws IOException
 */
public static void requestModerationDistortionCorrectBase64(String token, String formFile) throws IOException {
	String url = ServiceAccessBuilder.getCurrentEndpoint(projectName)+"/v1.0/moderation/image/distortion-correct";
	Header[] headers = new Header[] {new BasicHeader("X-Auth-Token", token) ,new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString())};
	try {
		byte[] fileData = FileUtils.readFileToByteArray(new File(formFile));
		String fileBase64Str = Base64.encodeBase64String(fileData);
		JSONObject json = new JSONObject();
		json.put("image", fileBase64Str);
		json.put("correction", true);
		StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");
		
		HttpResponse response = HttpClientUtils.post(url, headers, stringEntity, connectionTimeout, connectionRequestTimeout, socketTimeout);
		
		if(ResponseProcessUtils.isRespondedOK(response)) {
			ResponseProcessUtils.processResponseWithImage(response, "data/moderation-distortion.corrected.jpg");
		} else {
			// 处理服务返回的字符流,输出识别结果。
			ResponseProcessUtils.processResponseStatus(response);
			String content = IOUtils.toString(response.getEntity().getContent());
			System.out.println(content);
		}
		
		
	} catch (Exception e) {
		e.printStackTrace();
	}
}