Java Code Examples for com.alibaba.fastjson.JSONArray

The following examples show how to use com.alibaba.fastjson.JSONArray. These examples are extracted from open source projects. 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 Project: rebuild   Source File: LoginLogControll.java    License: GNU General Public License v3.0 6 votes vote down vote up
@RequestMapping("/admin/bizuser/online-users")
public void getOnlineUsers(HttpServletResponse response) throws IOException {
	JSONArray users = new JSONArray();
	for (HttpSession s : Application.getSessionStore().getAllSession()) {
		ID user = (ID) s.getAttribute(WebUtils.CURRENT_USER);
		if (user == null) continue;

		Object[] active = (Object[]) s.getAttribute(OnlineSessionStore.SK_LASTACTIVE);
		if (active == null) {
			active = new Object[] { "", "/dashboard/home" };
		} else {
			active = active.clone();
			active[0] = Moment.moment(new Date((Long) active[0])).fromNow();
		}

		JSONObject item = JSONUtils.toJSONObject(
				new String[] { "user", "fullName", "activeTime", "activeUrl" },
				new Object[] { user, UserHelper.getName(user), active[0], active[1] } );
		users.add(item);
	}
	writeSuccess(response, users);
}
 
Example 2
Source Project: AndNet   Source File: ListParser.java    License: Apache License 2.0 6 votes vote down vote up
public Result<List<T>> parse(String response) {
	Result<List<T>> result = new Result<List<T>>();
	try {
		JSONObject baseObject = JSON.parseObject(response);
		if(!baseObject.getBooleanValue("success")) {
			result.setMsg(baseObject.getString("message"));
		}else {
			JSONArray arr = baseObject.getJSONArray(mKey);
			Class<T> klass = Helper.generateType(getClass());
			List<T> t = JSON.parseArray(arr.toJSONString(), klass);
			result.setStatus(Result.SUCCESS);
			result.setResult(t);
			return result;
		}
	} catch (Exception e) {
		e.printStackTrace();
		result.setMsg(Net.ERR_PARSE_MSG);
	}
	
	result.setStatus(Result.ERROR);
		return result;
}
 
Example 3
Source Project: yuzhouwan   Source File: StrUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void compressionTest() throws Exception {
    String mysqlKeywords = compression(new String(Objects.requireNonNull(readFile(TEST_RESOURCES_PATH.concat("db/mysql_5.5_keywords.json")))));
    assertEquals("[\"ACCESSIBLE\",\"ADD\",\"ALL\",\"ALTER\",\"ANALYZE\",\"AND\",\"AS\",\"ASC\",\"ASENSITIVE\",\"BEFORE\",\"BETWEEN\",\"BIGINT\",\"BINARY\",\"BLOB\",\"BOTH\",\"BY\",\"CALL\",\"CASCADE\",\"CASE\",\"CHANGE\",\"CHAR\",\"CHARACTER\",\"CHECK\",\"COLLATE\",\"COLUMN\",\"CONDITION\",\"CONSTRAINT\",\"CONTINUE\",\"CONVERT\",\"CREATE\",\"CROSS\",\"CURRENT_DATE\",\"CURRENT_TIME\",\"CURRENT_TIMESTAMP\",\"CURRENT_USER\",\"CURSOR\",\"DATABASE\",\"DATABASES\",\"DAY_HOUR\",\"DAY_MICROSECOND\",\"DAY_MINUTE\",\"DAY_SECOND\",\"DEC\",\"DECIMAL\",\"DECLARE\",\"DEFAULT\",\"DELAYED\",\"DELETE\",\"DESC\",\"DESCRIBE\",\"DETERMINISTIC\",\"DISTINCT\",\"DISTINCTROW\",\"DIV\",\"DOUBLE\",\"DROP\",\"DUAL\",\"EACH\",\"ELSE\",\"ELSEIF\",\"ENCLOSED\",\"ESCAPED\",\"EXISTS\",\"EXIT\",\"EXPLAIN\",\"FALSE\",\"FETCH\",\"FLOAT\",\"FLOAT4\",\"FLOAT8\",\"FOR\",\"FORCE\",\"FOREIGN\",\"FROM\",\"FULLTEXT\",\"GRANT\",\"GROUP\",\"HAVING\",\"HIGH_PRIORITY\",\"HOUR_MICROSECOND\",\"HOUR_MINUTE\",\"HOUR_SECOND\",\"IF\",\"IGNORE\",\"IN\",\"INDEX\",\"INFILE\",\"INNER\",\"INOUT\",\"INSENSITIVE\",\"INSERT\",\"INT\",\"INT1\",\"INT2\",\"INT3\",\"INT4\",\"INT8\",\"INTEGER\",\"INTERVAL\",\"INTO\",\"IS\",\"ITERATE\",\"JOIN\",\"KEY\",\"KEYS\",\"KILL\",\"LEADING\",\"LEAVE\",\"LEFT\",\"LIKE\",\"LIMIT\",\"LINEAR\",\"LINES\",\"LOAD\",\"LOCALTIME\",\"LOCALTIMESTAMP\",\"LOCK\",\"LONG\",\"LONGBLOB\",\"LONGTEXT\",\"LOOP\",\"LOW_PRIORITY\",\"MASTER_SSL_VERIFY_SERVER_CERT\",\"MATCH\",\"MAXVALUE\",\"MEDIUMBLOB\",\"MEDIUMINT\",\"MEDIUMTEXT\",\"MIDDLEINT\",\"MINUTE_MICROSECOND\",\"MINUTE_SECOND\",\"MOD\",\"MODIFIES\",\"NATURAL\",\"NOT\",\"NO_WRITE_TO_BINLOG\",\"NULL\",\"NUMERIC\",\"ON\",\"OPTIMIZE\",\"OPTION\",\"OPTIONALLY\",\"OR\",\"ORDER\",\"OUT\",\"OUTER\",\"OUTFILE\",\"PRECISION\",\"PRIMARY\",\"PROCEDURE\",\"PURGE\",\"RANGE\",\"READ\",\"READS\",\"READ_WRITE\",\"REAL\",\"REFERENCES\",\"REGEXP\",\"RELEASE\",\"RENAME\",\"REPEAT\",\"REPLACE\",\"REQUIRE\",\"RESIGNAL\",\"RESTRICT\",\"RETURN\",\"REVOKE\",\"RIGHT\",\"RLIKE\",\"SCHEMA\",\"SCHEMAS\",\"SECOND_MICROSECOND\",\"SELECT\",\"SENSITIVE\",\"SEPARATOR\",\"SET\",\"SHOW\",\"SIGNAL\",\"SMALLINT\",\"SPATIAL\",\"SPECIFIC\",\"SQL\",\"SQLEXCEPTION\",\"SQLSTATE\",\"SQLWARNING\",\"SQL_BIG_RESULT\",\"SQL_CALC_FOUND_ROWS\",\"SQL_SMALL_RESULT\",\"SSL\",\"STARTING\",\"STRAIGHT_JOIN\",\"TABLE\",\"TERMINATED\",\"THEN\",\"TINYBLOB\",\"TINYINT\",\"TINYTEXT\",\"TO\",\"TRAILING\",\"TRIGGER\",\"TRUE\",\"UNDO\",\"UNION\",\"UNIQUE\",\"UNLOCK\",\"UNSIGNED\",\"UPDATE\",\"USAGE\",\"USE\",\"USING\",\"UTC_DATE\",\"UTC_TIME\",\"UTC_TIMESTAMP\",\"VALUES\",\"VARBINARY\",\"VARCHAR\",\"VARCHARACTER\",\"VARYING\",\"WHEN\",\"WHERE\",\"WHILE\",\"WITH\",\"WRITE\",\"XOR\",\"YEAR_MONTH\",\"ZEROFILL\",\"GENERAL\",\"IGNORE_SERVER_IDS\",\"MASTER_HEARTBEAT_PERIOD\",\"MAXVALUE\",\"RESIGNAL\",\"SIGNAL\",\"SLOW\"]",
            mysqlKeywords);
    String sqliteKeywords = compression(new String(Objects.requireNonNull(readFile(TEST_RESOURCES_PATH.concat("db/sqlite_keywords.json")))));
    assertEquals("[\"ABORT\",\"ADD\",\"AFTER\",\"ALL\",\"ALTER\",\"ANALYZE\",\"AND\",\"AS\",\"ASC\",\"ATTACH\",\"AUTOINCREMENT\",\"BEFORE\",\"BEGIN\",\"BETWEEN\",\"BY\",\"CASCADE\",\"CASE\",\"CAST\",\"CHECK\",\"COLLATE\",\"COMMIT\",\"CONFLICT\",\"CONSTRAINT\",\"CREATE\",\"CROSS\",\"CURRENT_DATE\",\"CURRENT_TIME\",\"CURRENT_TIMESTAMP\",\"DATABASE\",\"DEFAULT\",\"DEFERRABLE\",\"DEFERRED\",\"DELETE\",\"DESC\",\"DETACH\",\"DISTINCT\",\"DROP\",\"EACH\",\"ELSE\",\"END\",\"ESCAPE\",\"EXCEPT\",\"EXCLUSIVE\",\"EXPLAIN\",\"FAIL\",\"FOR\",\"FOREIGN\",\"FROM\",\"FULL\",\"GLOB\",\"GROUP\",\"HAVING\",\"IF\",\"IGNORE\",\"IMMEDIATE\",\"IN\",\"INDEX\",\"INITIALLY\",\"INNER\",\"INSERT\",\"INSTEAD\",\"INTERSECT\",\"INTO\",\"IS\",\"ISNULL\",\"JOIN\",\"KEY\",\"LEFT\",\"LIKE\",\"LIMIT\",\"MATCH\",\"NATURAL\",\"NOT\",\"NOTNULL\",\"NULL\",\"OF\",\"OFFSET\",\"ON\",\"OR\",\"ORDER\",\"OUTER\",\"PLAN\",\"PRAGMA\",\"PRIMARY\",\"QUERY\",\"RAISE\",\"REFERENCES\",\"REINDEX\",\"RENAME\",\"REPLACE\",\"RESTRICT\",\"RIGHT\",\"ROLLBACK\",\"ROW\",\"SELECT\",\"SET\",\"TABLE\",\"TEMP\",\"TEMPORARY\",\"THEN\",\"TO\",\"TRANSACTION\",\"TRIGGER\",\"UNION\",\"UNIQUE\",\"UPDATE\",\"USING\",\"VACUUM\",\"VALUES\",\"VIEW\",\"VIRTUAL\",\"WHEN\",\"WHERE\"]",
            sqliteKeywords);
    Collection<Object> mysqlArr = Arrays.asList(Objects.requireNonNull(JSON.parseArray(mysqlKeywords)).toArray());
    Set<String> mysqlSet = mysqlArr.stream().map(Object::toString).collect(Collectors.toCollection(LinkedHashSet::new));
    JSONArray sqliteArr = JSON.parseArray(sqliteKeywords);
    Set<String> sqliteSet = Objects.requireNonNull(sqliteArr).stream().map(Object::toString).collect(Collectors.toCollection(LinkedHashSet::new));
    Collection<String> intersection = CollectionUtils.intersection(mysqlSet, sqliteSet);
    mysqlSet.removeAll(intersection);   // in mysql, and not in sqlite
    assertEquals("[\"ACCESSIBLE\",\"ASENSITIVE\",\"BIGINT\",\"BINARY\",\"BLOB\",\"BOTH\",\"CALL\",\"CHANGE\",\"CHAR\",\"CHARACTER\",\"COLUMN\",\"CONDITION\",\"CONTINUE\",\"CONVERT\",\"CURRENT_USER\",\"CURSOR\",\"DATABASES\",\"DAY_HOUR\",\"DAY_MICROSECOND\",\"DAY_MINUTE\",\"DAY_SECOND\",\"DEC\",\"DECIMAL\",\"DECLARE\",\"DELAYED\",\"DESCRIBE\",\"DETERMINISTIC\",\"DISTINCTROW\",\"DIV\",\"DOUBLE\",\"DUAL\",\"ELSEIF\",\"ENCLOSED\",\"ESCAPED\",\"EXISTS\",\"EXIT\",\"FALSE\",\"FETCH\",\"FLOAT\",\"FLOAT4\",\"FLOAT8\",\"FORCE\",\"FULLTEXT\",\"GRANT\",\"HIGH_PRIORITY\",\"HOUR_MICROSECOND\",\"HOUR_MINUTE\",\"HOUR_SECOND\",\"INFILE\",\"INOUT\",\"INSENSITIVE\",\"INT\",\"INT1\",\"INT2\",\"INT3\",\"INT4\",\"INT8\",\"INTEGER\",\"INTERVAL\",\"ITERATE\",\"KEYS\",\"KILL\",\"LEADING\",\"LEAVE\",\"LINEAR\",\"LINES\",\"LOAD\",\"LOCALTIME\",\"LOCALTIMESTAMP\",\"LOCK\",\"LONG\",\"LONGBLOB\",\"LONGTEXT\",\"LOOP\",\"LOW_PRIORITY\",\"MASTER_SSL_VERIFY_SERVER_CERT\",\"MAXVALUE\",\"MEDIUMBLOB\",\"MEDIUMINT\",\"MEDIUMTEXT\",\"MIDDLEINT\",\"MINUTE_MICROSECOND\",\"MINUTE_SECOND\",\"MOD\",\"MODIFIES\",\"NO_WRITE_TO_BINLOG\",\"NUMERIC\",\"OPTIMIZE\",\"OPTION\",\"OPTIONALLY\",\"OUT\",\"OUTFILE\",\"PRECISION\",\"PROCEDURE\",\"PURGE\",\"RANGE\",\"READ\",\"READS\",\"READ_WRITE\",\"REAL\",\"REGEXP\",\"RELEASE\",\"REPEAT\",\"REQUIRE\",\"RESIGNAL\",\"RETURN\",\"REVOKE\",\"RLIKE\",\"SCHEMA\",\"SCHEMAS\",\"SECOND_MICROSECOND\",\"SENSITIVE\",\"SEPARATOR\",\"SHOW\",\"SIGNAL\",\"SMALLINT\",\"SPATIAL\",\"SPECIFIC\",\"SQL\",\"SQLEXCEPTION\",\"SQLSTATE\",\"SQLWARNING\",\"SQL_BIG_RESULT\",\"SQL_CALC_FOUND_ROWS\",\"SQL_SMALL_RESULT\",\"SSL\",\"STARTING\",\"STRAIGHT_JOIN\",\"TERMINATED\",\"TINYBLOB\",\"TINYINT\",\"TINYTEXT\",\"TRAILING\",\"TRUE\",\"UNDO\",\"UNLOCK\",\"UNSIGNED\",\"USAGE\",\"USE\",\"UTC_DATE\",\"UTC_TIME\",\"UTC_TIMESTAMP\",\"VARBINARY\",\"VARCHAR\",\"VARCHARACTER\",\"VARYING\",\"WHILE\",\"WITH\",\"WRITE\",\"XOR\",\"YEAR_MONTH\",\"ZEROFILL\",\"GENERAL\",\"IGNORE_SERVER_IDS\",\"MASTER_HEARTBEAT_PERIOD\",\"SLOW\"]",
            JSON.toJSONString(mysqlSet));
}
 
Example 4
Source Project: MicroCommunity   Source File: AddOwnerRoomBindingSMOImpl.java    License: Apache License 2.0 6 votes vote down vote up
private JSONObject getObj(JSONArray infos, String flowComponent) {

        JSONObject serviceInfo = null;

        for (int infoIndex = 0; infoIndex < infos.size(); infoIndex++) {

            Assert.hasKeyAndValue(infos.getJSONObject(infoIndex), "flowComponent", "未包含服务流程组件名称");

            if (flowComponent.equals(infos.getJSONObject(infoIndex).getString("flowComponent"))) {
                serviceInfo = infos.getJSONObject(infoIndex);
                Assert.notNull(serviceInfo, "未包含服务信息");
                return serviceInfo;
            }
        }

        throw new IllegalArgumentException("未找到组件编码为【" + flowComponent + "】数据");
    }
 
Example 5
Source Project: tephra   Source File: PptxReaderImpl.java    License: MIT License 6 votes vote down vote up
@Override
public JSONObject read(InputStream inputStream, MediaWriter mediaWriter) {
    JSONObject object = new JSONObject();
    try (XMLSlideShow xmlSlideShow = new XMLSlideShow(inputStream)) {
        parseSize(xmlSlideShow, object);
        ReaderContext readerContext = new ReaderContext(mediaWriter, xmlSlideShow);
        Map<String, Map<Integer, String>> layouts = new HashMap<>();
        JSONArray slides = new JSONArray();
        xmlSlideShow.getSlides().forEach(xslfSlide -> {
            readerContext.setXslfSlide(xslfSlide);
            JSONObject slide = new JSONObject();
            parseSlide(readerContext, slide, parseLayout(readerContext, layouts));
            slides.add(slide);
        });
        object.put("slides", slides);
        inputStream.close();
    } catch (Exception e) {
        logger.warn(e, "读取PPTX数据时发生异常!");
    }

    return object;
}
 
Example 6
/**
 * @Title: getProductMap
 * @Description: 获取所有产品信息
 * @return
 * @return: Map<String,String>
 */
public Map<String, String> getProductMap(String userMail){
	Map<String, String> productMap = new HashMap<String, String>();
	String cookie = getUserSign(userMail,"");
	if (isProjectInvolved()) {
		try {
			String getUrl = properties.getProperty("base_url") + properties.getProperty("product_get_url");
			String result = URLUtil.sendGet(getUrl, "", cookie);
			
			JSONArray jsonArray = JSONArray.parseArray(result);
			for (Object object : jsonArray) {
				JSONObject jsonObject = JSONObject.parseObject(object.toString());
				productMap.put(jsonObject.getString("id"), jsonObject.getString("name"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	proNameMap.putAll(productMap);
	return productMap;
}
 
Example 7
Source Project: yue-library   Source File: Convert.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 转换为 {@linkplain JSONArray}
 * 
 * @param value 被转换的值
 * @return JSON数组
 */
   @SuppressWarnings("unchecked")
public static JSONArray toJSONArray(Object value) {
       if (value instanceof JSONArray) {
           return (JSONArray) value;
       }
       
       if (value instanceof List) {
           return new JSONArray((List<Object>) value);
       }
       
	if (value instanceof String) {
		return JSONArray.parseArray((String) value);
	}
       
       return (JSONArray) toJSON(value);
   }
 
Example 8
Source Project: MicroCommunity   Source File: OrderProcessServiceSMOImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 处理同步业务
 *
 * @param dataFlow
 */
@Override
protected void doSynchronousBusinesses(IOrderDataFlowContext dataFlow) throws BusinessException {
    Date startDate = DateUtil.getCurrentDate();
    List<Business> synchronousBusinesses = OrderDataFlowContextFactory.getSynchronousBusinesses(dataFlow);

    if (synchronousBusinesses == null || synchronousBusinesses.size() == 0) {
        return;
    }
    JSONArray responseBusinesses = new JSONArray();

    //6.1处理同步服务 发起Business
    doSaveDataInfoToBusinessTable(dataFlow, synchronousBusinesses, responseBusinesses);

    OrderDataFlowContextFactory.addCostTime(dataFlow, "doSynchronousBusinesses", "同步调用业务系统总耗时", startDate);
}
 
Example 9
Source Project: Cynthia   Source File: BackRightController.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * @Title:initUserTemplateRight
 * @Type:BackRightController
 * @description:init user template rights
 * @date:2014-5-5 下午8:04:13
 * @version:v1.0
 * @param request
 * @param httpSession
 * @return
 * @throws Exception
 */
@ResponseBody
@RequestMapping("/initUserTemplateRight.do")
public String initUserTemplateRight(HttpServletRequest request,HttpSession httpSession) throws Exception {
	String userMail = request.getParameter("userMail");
	
	if (userMail == null || userMail.length() == 0) {
		Key key = (Key)httpSession.getAttribute("key");
		userMail = key.getUsername();
	}
	Map<String, String> temMap = new HashMap<String, String>();
	
	temMap = das.queryUserTemplateRights(userMail);
	
	return JSONArray.toJSONString(temMap);
}
 
Example 10
Source Project: MicroCommunity   Source File: DeleteStoreUserListener.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据删除信息 查出Instance表中数据 保存至business表 (状态写DEL) 方便撤单时直接更新回去
 * @param dataFlowContext 数据对象
 * @param business 当前业务对象
 */
@Override
protected void doSaveBusiness(DataFlowContext dataFlowContext, Business business) {
    JSONObject data = business.getDatas();

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


    //处理 businessStore 节点
    if(!data.containsKey(StoreUserPo.class.getSimpleName())){
        throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR,"没有businessStoreUser节点");
    }

    JSONArray businessStoreUsers = data.getJSONArray(StoreUserPo.class.getSimpleName());
    for(int bIndex = 0 ; bIndex < businessStoreUsers.size();bIndex++) {
        doBusinessStoreUser(business, businessStoreUsers.getJSONObject(bIndex));
    }
}
 
Example 11
Source Project: MicroCommunity   Source File: SaveCommunityInfoListener.java    License: 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 节点,或没有子节点需要处理");

    //处理 businessCommunity 节点
    if (data.containsKey(CommunityPo.class.getSimpleName())) {
        JSONObject businessCommunity = data.getJSONArray(CommunityPo.class.getSimpleName()).getJSONObject(0);
        doBusinessCommunity(business, businessCommunity);
        dataFlowContext.addParamOut("communityId", businessCommunity.getString("communityId"));
    }

    if (data.containsKey(CommunityAttrPo.class.getSimpleName())) {
        JSONArray businessCommunityAttrs = data.getJSONArray(CommunityAttrPo.class.getSimpleName());
        doSaveBusinessCommunityAttrs(business, businessCommunityAttrs);
    }

    if (data.containsKey(CommunityPhotoPo.class.getSimpleName())) {
        JSONArray businessCommunityPhotos = data.getJSONArray(CommunityPhotoPo.class.getSimpleName());
        doBusinessCommunityPhoto(business, businessCommunityPhotos);
    }


}
 
Example 12
Source Project: MongoDB-Plugin   Source File: ReadTextTool.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 功能:Java读取txt文件的内容
 * 步骤:1:先获得文件句柄
 * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
 * 3:读取到输入流后,需要读取生成字节流
 * 4:一行一行的输出。readline()。
 * 备注:需要考虑的是异常情况
 * @param filePath
 */
public static JSONArray readTxtFile(String filePath){
    try {
        String encoding="UTF-8";
        File file=new File(filePath);
        if(file.isFile() && file.exists()){ //判断文件是否存在
            InputStreamReader read = new InputStreamReader(
                    new FileInputStream(file),encoding);//考虑到编码格式
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            JSONArray jsonArray=new JSONArray();
            while((lineTxt = bufferedReader.readLine()) != null){
                jsonArray.add(lineTxt);
            }
            read.close();
            return jsonArray;
        }else{
            System.out.println("找不到指定的文件");
        }
    } catch (Exception e) {
        System.out.println("读取文件内容出错");
        e.printStackTrace();
    }

    return null;
}
 
Example 13
Source Project: rainbow   Source File: RwMain.java    License: Apache License 2.0 6 votes vote down vote up
private void savePipelineState(Pipeline pipeline, String state, String time) {
    State s = new State(time, state);
    Process p = searchProcessByPno(pipeline.getNo());
    if (p != null) {
        p.getPipelineState().add(s);
    } else {
        List<State> PipelineState = new ArrayList<>();
        PipelineState.add(s);
        p = new Process(pipeline.getNo(), PipelineState);
        SysConfig.ProcessList.add(p);
    }
    String processListJson = JSONArray.toJSONString(SysConfig.ProcessList);
    try {
        FileUtil.writeFile(processListJson, SysConfig.Catalog_Project + "cashe/process.txt");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 14
Source Project: rebuild   Source File: FlowNode.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取相关人员(提交人/审批人/抄送人)
 * 
 * @param operator
 * @param record
 * @return
 */
public Set<ID> getSpecUsers(ID operator, ID record) {
	JSONArray userDefs = getDataMap().getJSONArray("users");
	if (userDefs == null || userDefs.isEmpty()) {
		return Collections.emptySet();
	}

	String userType = userDefs.getString(0);
	if (USER_SELF.equalsIgnoreCase(userType)) {
		Set<ID> users = new HashSet<>();
		ID owning = Application.getRecordOwningCache().getOwningUser(record);
		users.add(owning);
		return users;
	}
	
	List<String> defsList = new ArrayList<>();
	for (Object o : userDefs) {
		defsList.add((String) o);
	}
	return UserHelper.parseUsers(defsList, null);
}
 
Example 15
Source Project: liteflow   Source File: UserGroupAuthMidServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void addAuth(Long taskId, String userAuthJson, int sourceType, int targetType) {
    if (StringUtils.isNotBlank(userAuthJson)) {
        JSONArray datas = JSON.parseArray(userAuthJson);
        if (datas != null && datas.size() > 0) {
            List<UserGroupAuthMid> userGroupAuthMids = new ArrayList<>();
            datas.forEach(obj -> {
                Long sourceId = (Long) ((JSONObject) obj).get("sourceId");
                Integer canEdit = (Integer) ((JSONObject) obj).get("canEdit");
                Integer canExecute = (Integer) ((JSONObject) obj).get("canExecute");

                UserGroupAuthMid model = new UserGroupAuthMid();
                model.setSourceId(sourceId);
                model.setTargetId(taskId);
                model.setSourceType(sourceType);
                model.setTargetType(targetType);
                model.setHasEditAuth(canEdit);
                model.setHasExecuteAuth(canExecute);
                userGroupAuthMids.add(model);
            });
            this.addBatch(userGroupAuthMids);
        }
    }

}
 
Example 16
Source Project: kafka-eagle   Source File: KafkaHubServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private File createKafkaTempJson(Map<TopicPartition, Seq<Object>> tuple) throws IOException {
	JSONObject object = new JSONObject();
	object.put("version", 1);
	JSONArray array = new JSONArray();
	for (Entry<TopicPartition, Seq<Object>> entry : JavaConversions.mapAsJavaMap(tuple).entrySet()) {
		List<Object> replicas = JavaConversions.seqAsJavaList(entry.getValue());
		JSONObject tpObject = new JSONObject();
		tpObject.put("topic", entry.getKey().topic());
		tpObject.put("partition", entry.getKey().partition());
		tpObject.put("replicas", replicas);
		array.add(tpObject);
	}
	object.put("partitions", array);
	File f = File.createTempFile("ke_reassignment_", ".json");
	FileWriter out = new FileWriter(f);
	out.write(object.toJSONString());
	out.close();
	f.deleteOnExit();
	return f;
}
 
Example 17
private void handleJsonToWorkCalendarHolidayRef(JSONObject object, Set<WorkCalendarHolidayRefDTO> workCalendarHolidayRefDTOS) {
    JSONObject result = JSON.parseObject(object.get("result").toString());
    JSONObject data = JSON.parseObject(result.get("data").toString());
    JSONArray holidayArray = JSON.parseArray(data.get("holiday_array").toString());
    for (int j = 0; j < holidayArray.size(); j++) {
        JSONObject jsonObject = holidayArray.getJSONObject(j);
        WorkCalendarHolidayRefDTO workCalendarHolidayRefDTO = new WorkCalendarHolidayRefDTO();
        workCalendarHolidayRefDTO.setName(jsonObject.get("name") == null ? null : jsonObject.get("name").toString());
        workCalendarHolidayRefDTO.setHoliday(jsonObject.get("festival").toString());
        workCalendarHolidayRefDTO.setStatus(0);
        workCalendarHolidayRefDTO.setYear(Integer.valueOf(workCalendarHolidayRefDTO.getHoliday().split("-")[0]));
        workCalendarHolidayRefDTOS.add(workCalendarHolidayRefDTO);
        List<DateStatus> list = JSON.parseArray(jsonObject.get("list").toString(), DateStatus.class).stream().filter(dateStatus -> !dateStatus.getDate().equals(workCalendarHolidayRefDTO.getHoliday())).collect(Collectors.toList());
        list.forEach(dateStatus -> {
            WorkCalendarHolidayRefDTO day = new WorkCalendarHolidayRefDTO();
            day.setHoliday(dateStatus.getDate());
            day.setYear(Integer.valueOf(day.getHoliday().split("-")[0]));
            //接口返回的数据中,补班是2,放假是1
            day.setStatus("1".equals(dateStatus.getStatus()) ? 0 : 1);
            workCalendarHolidayRefDTOS.add(day);
        });
    }
}
 
Example 18
Source Project: jeecg-cloud   Source File: SysGatewayRouteServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void updateAll(JSONArray array) {
    this.remove(new LambdaQueryWrapper<SysGatewayRoute>().eq(SysGatewayRoute::getStatus,1));
    List<SysGatewayRoute> ls = new ArrayList<>();
    for(int i =0;i<array.size();i++){
        JSONObject json = array.getJSONObject(i);
        SysGatewayRoute route = new SysGatewayRoute();
        route.setId(json.getString("id"));
        route.setName(json.getString("name"));
        route.setPredicates(json.getString("predicates"));
        route.setFilters(json.getString("filters"));
        route.setUri(json.getString("uri"));
        if(json.get("status")==null){
            route.setStatus(1);
        }else{
            route.setStatus(json.getInteger("status"));
        }
        ls.add(route);
    }
    this.saveBatch(ls);
    redisTemplate.opsForValue().set(CacheConstant.GATEWAY_ROUTES,  JSON.toJSONString(ls));
}
 
Example 19
Source Project: DimpleBlog   Source File: FrontController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get comment use info by QQNum
 */
@GetMapping("comment/qqNum/{qqNum}")
public AjaxResult getByQQNum(@PathVariable Long qqNum) {
    String json = HttpUtils.sendGet(QQ_QUERY_URL, "uins=" + qqNum, "GBK");
    Map<String, String> qqInfo = new HashMap<>();
    if (!StringUtils.isEmpty(json)) {
        json = json.replaceAll("portraitCallBack|\\\\s*|\\t|\\r|\\n", "");
        json = json.substring(1, json.length() - 1);
        JSONObject object = JSON.parseObject(json);
        JSONArray array = object.getJSONArray(String.valueOf(qqNum));
        qqInfo.put("avatar", "https://q1.qlogo.cn/g?b=qq&nk=" + qqNum + "&s=40");
        qqInfo.put("email", qqNum + "@qq.com");
        qqInfo.put("nickName", array.getString(6));
    }
    return AjaxResult.success(qqInfo);
}
 
Example 20
Source Project: sagacity-sqltoy   Source File: ElasticSearchUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @TODO 数据集合提取
 * @param result
 * @param rowJson
 * @param realFields
 */
private static void processRow(List result, JSONObject rowJson, String[] realFields, boolean isSuggest) {
	Object root = getRealJSONObject(rowJson, realFields, isSuggest);
	if (root instanceof JSONObject) {
		JSONObject json = (JSONObject) root;
		if ((json.containsKey("key") && json.containsKey("doc_count"))) {
			if (isRoot(json, realFields)) {
				addRow(result, json, realFields);
			} else {
				processRow(result, json, realFields, isSuggest);
			}
		} else {
			addRow(result, json, realFields);
		}
	} else if (root instanceof JSONArray) {
		JSONArray array = (JSONArray) root;
		for (Object tmp : array) {
			processRow(result, (JSONObject) tmp, realFields, isSuggest);
		}
	}
}
 
Example 21
Source Project: GOAi   Source File: BitfinexUtil.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 解析订单详情
 * [
 *  333168795,      ID	integer	Trade database id
 *  "tLTCUSD",      PAIR	string	Pair (BTCUSD, …)
 *  1547796266000,  MTS_CREATE	integer	Execution timestamp
 *  21597693840,    ORDER_ID	integer	Order id
 *  -0.4,           EXEC_AMOUNT	float	Positive means buy, negative means sell
 *  31.962,         EXEC_PRICE	float	Execution price
 *  null,           _PLACEHOLDER,
 *  null,           _PLACEHOLDER,
 *  -1,             MAKER	int	1 if true, -1 if false
 *  -0.0255696,     FEE	float	Fee
 *  "USD"           FEE_CURRENCY	string	Fee currency
 * ]
 * @param result 元素数据
 * @return 订单详情列表
 */
public static List<OrderDetail> parseOrderDetails(String result) {
    JSONArray r = JSON.parseArray(result);
    List<OrderDetail> details = new ArrayList<>(r.size());
    for (int i = 0; i < r.size(); i++) {
        JSONArray t = r.getJSONArray(i);

        String data = r.getString(i);
        Long time = t.getLong(2);
        String orderId = t.getString(3);
        String detailId = t.getString(0);
        BigDecimal price = t.getBigDecimal(5);
        BigDecimal amount = t.getBigDecimal(4).abs();
        BigDecimal fee = t.getBigDecimal(9).abs();
        String feeCurrency = t.getString(10);
        details.add(new OrderDetail(data, time, orderId, detailId, price, amount, fee, feeCurrency));
    }
    return details;
}
 
Example 22
Source Project: xian   Source File: ThreadPoolMonitorUnit.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public Single<Object> execute0() {
        return Single.just(UnitResponse.createSuccess(new JSONArray() {{
            add(new JSONObject() {{
                put("title", "线程池");
                put("value", ThreadPoolManager.activeCount());
                put("name", "activeCount");
                put("application", EnvUtil.getApplication());
                put("nodeId", LocalNodeManager.LOCAL_NODE_ID);
            }});
//            add(new JSONObject() {{
//                put("title", "线程池");
//                put("value", ThreadPoolManager.queueSize());
//                put("name", "queueSize");
//                put("application", EnvUtil.getApplication());
//                put("nodeId", LocalNodeManager.LOCAL_NODE_ID);
//            }});
//            add(new JSONObject() {{
//                put("title", "线程池");
//                put("value", ThreadPoolManager.poolSize());
//                put("name", "poolSize");
//                put("application", EnvironmentUtil.getApplication());
//                put("nodeId", LocalNodeManager.LOCAL_NODE_ID);
//            }});
        }}));
    }
 
Example 23
Source Project: aliyun-tsdb-java-sdk   Source File: TestTagResult.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testJSONToResult() {
    String json = "[{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1.012\"}]";

    try {
        JSONArray array = JSON.parseArray(json);
        // System.out.println(array);
        Assert.assertEquals(array.toString(),
                "[{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1.012\"}]");
        List<TagResult> arrayList = new ArrayList<TagResult>(array.size());

        Iterator<Object> iterator = array.iterator();
        while (iterator.hasNext()) {
            JSONObject object = (JSONObject) iterator.next();
            Set<Entry<String, Object>> entrySet = object.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                String key = entry.getKey();
                Assert.assertNotEquals(key, null);
                Object valueObject = entry.getValue();
                Assert.assertNotEquals(key, null);
                String value = valueObject.toString();
                TagResult tagResult = new TagResult(key, value);
                arrayList.add(tagResult);
                break;
            }
        }
        Assert.assertEquals(arrayList.size(), 3);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
 
Example 24
Source Project: rainbow   Source File: RwMain.java    License: Apache License 2.0 5 votes vote down vote up
private void saveCurLayout() {
    String aJson = JSONArray.toJSONString(SysConfig.CurLayout);
    try {
        FileUtil.writeFile(aJson, SysConfig.Catalog_Project + "cashe/curLayout.txt");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 25
/**
 * constructor.
 */
@Test(enabled = true, description = "Get asset issue list by name from confirmed by http")
public void test10GetAssetIssueListByNameFromConfirmed() {
  HttpMethed.waitToProduceOneBlockFromConfirmed(httpnode, httpConfirmednode);
  response = HttpMethed.getAssetIssueListByNameFromConfirmed(httpConfirmednode, name);
  responseContent = HttpMethed.parseResponseContent(response);
  HttpMethed.printJsonContent(responseContent);
  JSONArray jsonArray = JSONArray.parseArray(responseContent.get("assetIssue").toString());
  Assert.assertTrue(jsonArray.size() >= 2);
}
 
Example 26
Source Project: tephra   Source File: DataSourceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void onContextRefreshed() {
    if (validator.isEmpty(config))
        return;

    JSONArray array = JSON.parseArray(config);
    for (int i = 0; i < array.size(); i++)
        create(array.getJSONObject(i));
}
 
Example 27
@RequestMapping(value = "/admin/app/checkApp")
public void checkApplication(Model model, @RequestBody JSONArray jsonArray) {

	try {
		String userId = UserUtils.getCurrentUserId();
		StringUtils.isValidString(userId, "账号没有登录");

		StringUtils.isValidObject(jsonArray, "参数错误");

		List<Long> ids = new ArrayList<>(jsonArray.size());

		for (int i = 0; i < jsonArray.size(); i++) {
			ids.add(jsonArray.getJSONObject(i).getLong("id"));
		}
		
		log.debug("管理员["+userId+"]正在审核应用.");
		CommonResponseDto response = applicationService.checkApplication(
				userId, ids);
		
		if (response == null
				|| response.getResult() != UserConstant.SUCCESS) {
			throw new VerificationException(response.getErrorMessage());
		} else {
			model.addAttribute("success", true);
		}

	} catch (VerificationException e) {
		model.addAttribute("success", false);
		model.addAttribute("error", e.getMessage());
	}
}
 
Example 28
Source Project: MicroCommunity   Source File: MerchantDispatchListener.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 商户信息受理
 * @param event the event to respond to
 */
@Override
public void soDataService(AppMerchantEvent event) {
    //这里处理 商户相关信息

    AppContext context = event.getContext();

    //获取商户相关的信息
    JSONArray dataMerchantInfos = event.getData();

}
 
Example 29
Source Project: tephra   Source File: HbaseImpl.java    License: MIT License 5 votes vote down vote up
@Override
public JSONArray queryAsJson(HbaseQuery query) {
    JSONArray array = new JSONArray();
    if (isDisabled() || query == null)
        return array;

    if (validator.isEmpty(query.tableName)) {
        logger.warn(null, "表名称为空,检索失败!");

        return array;
    }

    try {
        Table table = getTable(query.getTableName());
        ResultScanner scanner = query(table, query.getFilter());
        scanner.forEach(result -> {
            JSONObject object = new JSONObject();
            setToJson(object, Bytes.toString(result.getRow()), result);
            array.add(object);
        });
        scanner.close();
        table.close();
    } catch (IOException e) {
        logger.warn(e, "检索HBase数据[{}]时发生异常!", query.getTableName());
    }

    return array;
}
 
Example 30
Source Project: MicroCommunity   Source File: SaveComplaintSMOImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected ResponseEntity<String> doBusinessProcess(IPageData pd, JSONObject paramIn) throws IOException {

    //查询用户ID
    paramIn.put("userId", pd.getUserId());
    //查询商户ID
    Map paramObj = new HashMap();
    paramObj.put("communityId", paramIn.getString("communityId"));
    paramObj.put("auditStatusCd", "1100");
    paramObj.put("memberTypeCd", "390001200002");
    paramObj.put("page", 1);
    paramObj.put("row", 1);
    String url = ServiceConstant.SERVICE_API_URL + "/api/store.listStoresByCommunity" + mapToUrlParam(paramObj);
    ResponseEntity<String> responseEntity = super.callCenterService(restTemplate, pd, "", url, HttpMethod.GET);
    if (responseEntity.getStatusCode() != HttpStatus.OK) {
        return responseEntity;
    }

    JSONObject storeObj = JSONObject.parseObject(responseEntity.getBody());
    JSONArray stores = storeObj.getJSONArray("stores");
    String storeId = stores.getJSONObject(0).getString("storeId");
    paramIn.put("storeId", storeId);
    url = ServiceConstant.SERVICE_API_URL + "/api/complaint.saveComplaint";
    responseEntity = super.callCenterService(restTemplate, pd, paramIn.toJSONString(), url, HttpMethod.POST);

    return responseEntity;
}