com.alibaba.fastjson.JSONArray Java Examples

The following examples show how to use com.alibaba.fastjson.JSONArray. 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: ReadTextTool.java    From MongoDB-Plugin with 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 #2
Source File: SysGatewayRouteServiceImpl.java    From jeecg-cloud with 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 #3
Source File: BitfinexUtil.java    From GOAi with 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 #4
Source File: FrontController.java    From DimpleBlog with 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 #5
Source File: ListParser.java    From AndNet with 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 #6
Source File: ElasticSearchUtils.java    From sagacity-sqltoy with 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 #7
Source File: StrUtilsTest.java    From yuzhouwan with 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 #8
Source File: JuheWorkCalendarServiceImpl.java    From agile-service-old with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: ThreadPoolMonitorUnit.java    From xian with 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 #10
Source File: AddOwnerRoomBindingSMOImpl.java    From MicroCommunity with 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 #11
Source File: PptxReaderImpl.java    From tephra with 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 #12
Source File: ProjectInvolveManager.java    From Cynthia with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @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 #13
Source File: Convert.java    From yue-library with 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 #14
Source File: KafkaHubServiceImpl.java    From kafka-eagle with 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 #15
Source File: OrderProcessServiceSMOImpl.java    From MicroCommunity with 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 #16
Source File: BackRightController.java    From Cynthia with 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 #17
Source File: UserGroupAuthMidServiceImpl.java    From liteflow with 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 #18
Source File: FlowNode.java    From rebuild with 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 #19
Source File: RwMain.java    From rainbow with 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 #20
Source File: DeleteStoreUserListener.java    From MicroCommunity with 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 #21
Source File: SaveCommunityInfoListener.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 节点,或没有子节点需要处理");

    //处理 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 #22
Source File: JSONFunction.java    From kafka-eagle with Apache License 2.0 5 votes vote down vote up
/** Parse a JSONArray. */
public String JSONS(String jsonArray, String key) {
	JSONArray object = com.alibaba.fastjson.JSON.parseArray(jsonArray);
	JSONArray target = new JSONArray();
	for (Object tmp : object) {
		JSONObject result = (JSONObject) tmp;
		JSONObject value = new JSONObject();
		value.put(key, result.getString(key));
		target.add(value);
	}
	return target.toJSONString();
}
 
Example #23
Source File: NacosDiscoveryEndpoint.java    From nacos-spring-boot-project with Apache License 2.0 5 votes vote down vote up
@ReadOperation
public Map<String, Object> invoke() {
	Map<String, Object> result = new HashMap<>(8);

	result.put("nacosDiscoveryGlobalProperties",
			PropertiesUtils.extractSafeProperties(applicationContext.getBean(
					DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class)));

	NacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory
			.getSingleton();

	JSONArray array = new JSONArray();
	for (NamingService namingService : nacosServiceFactory.getNamingServices()) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("servicesOfServer",
					namingService.getServicesOfServer(0, PAGE_SIZE));
			jsonObject.put("subscribeServices", namingService.getSubscribeServices());
			array.add(jsonObject);
		}
		catch (Exception e) {
			jsonObject.put("serverStatus", namingService.getServerStatus() + ": "
					+ NacosUtils.SEPARATOR + e.getMessage());
		}
	}

	result.put("namingServersStatus", array);
	return result;
}
 
Example #24
Source File: MaterialService.java    From jshERP with GNU General Public License v3.0 5 votes vote down vote up
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
public int insertMaterial(String beanJson, HttpServletRequest request)throws Exception {
    Material m = JSONObject.parseObject(beanJson, Material.class);
    m.setEnabled(true);
    try{
        Long mId = null;
        materialMapper.insertSelective(m);
        List<Material> materials = getMaterialListByParam(m.getName(),m.getModel(),m.getColor(),
                m.getStandard(), m.getMfrs(),m.getUnit(),m.getUnitid());
        if(materials!=null && materials.size()>0) {
            mId = materials.get(0).getId();
        }
        JSONObject mObj = JSON.parseObject(beanJson);
        materialExtendService.saveDetials(mObj.getString("inserted"), mObj.getString("deleted"), mObj.getString("updated"),mObj.getString("sortList"), mId);
        if(mObj.get("stock")!=null) {
            String stockStr = mObj.getString("stock");
            JSONArray stockArr = JSONArray.parseArray(stockStr);
            for(Object object: stockArr) {
                JSONObject jsonObj = (JSONObject)object;
                if(jsonObj.get("depotId")!=null && jsonObj.get("number")!=null) {
                    String number = jsonObj.getString("number");
                    Long depotId = jsonObj.getLong("depotId");
                    if(number!=null && Double.valueOf(number)>0) {
                        insertStockByMaterialAndDepot(depotId, mId, parseBigDecimalEx(number));
                    }
                }
            }
        }
        logService.insertLog("商品",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(m.getName()).toString(), request);
        return 1;
    }catch(Exception e){
        JshException.writeFail(logger, e);
        return 0;
    }
}
 
Example #25
Source File: NodeIndexController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "node_status", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Feature(method = MethodFeature.LIST)
public String nodeStatus() {
    long timeMillis = System.currentTimeMillis();
    JSONObject jsonObject = NodeForward.requestData(getNode(), NodeUrl.Status, getRequest(), JSONObject.class);
    if (jsonObject == null) {
        return JsonMessage.getString(500, "获取信息失败");
    }
    JSONArray jsonArray = new JSONArray();
    jsonObject.put("timeOut", System.currentTimeMillis() - timeMillis);
    jsonArray.add(jsonObject);
    return JsonMessage.getString(200, "", jsonArray);
}
 
Example #26
Source File: TagController.java    From Cynthia with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @description:get all tas of user
 * @date:2014-5-5 下午8:40:55
 * @version:v1.0
 * @param request
 * @param response
 * @param session
 * @return
 * @throws Exception
 */
@RequestMapping("/getAllTag.do")
@ResponseBody
public String getAllTag(HttpServletRequest request, HttpServletResponse response ,HttpSession session) throws Exception {
	if (session.getAttribute("userName") == null) {
		return "";
	}
	
	String userName = session.getAttribute("userName").toString();
	
	List<TagBean> allTagList = das.getAllTag(userName);
	return JSONArray.toJSONString(allTagList);
}
 
Example #27
Source File: JsonHelperImpl.java    From ucar-weex-core with Apache License 2.0 5 votes vote down vote up
@Override
public JSONArray decodeArray(String json) throws JsonException {
    try {
        return JSON.parseArray(json);
    } catch (Throwable ex) {
        throw new JsonException(ex);
    }
}
 
Example #28
Source File: SocialFriendAdapter.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 
 * 点赞
 * 
 */
public void setGood(String sID, TextView tv_good, JSONArray jsons,
        LinearLayout ll_goodmembers_temp, View view, int cSize) {
    // 即时改变当前UI
    JSONObject json = new JSONObject();
    json.put("userID", myuserID);
    jsons.add(json);
    setGoodTextClick(tv_good, jsons, ll_goodmembers_temp, view, cSize);
    // 更新后台
    Map<String, String> map = new HashMap<String, String>();
    map.put("sID", sID);

    map.put("userID", myuserID);

    SocialApiTask task = new SocialApiTask(context,
            Constant.URL_SOCIAL_GOOD, map);
    task.getData(new DataCallBack() {

        @Override
        public void onDataCallBack(JSONObject data) {
            // dialog.dismiss();
            if (data == null) {
                Log.e("hideCommentEditText()-->>>>",
                        "hideCommentEditText()-----ERROR");
                return;
            }
            int code = data.getInteger("code");
            if (code == 1000) {
                Log.e("hideCommentEditText()-->>>>",
                        "hideCommentEditText()-----SUCCESS");
            } else {
                Log.e("hideCommentEditText()-->>>>",
                        "hideCommentEditText()-----ERROR_2");

            }
        }
    });

}
 
Example #29
Source File: BinanceExchange.java    From GOAi with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected Depth transformDepth(List<String> results, ExchangeInfo info) {
    String result = results.get(0);
    if (useful(result)) {
        JSONObject r = JSONObject.parseObject(result);
        JSONArray asks = r.getJSONArray("asks");
        JSONArray bids = r.getJSONArray("bids");
        Long time = System.currentTimeMillis();
        return CommonUtil.parseDepthByIndex(time, asks, bids);
    }
    return null;
}
 
Example #30
Source File: HBaseUtil.java    From DataLink with Apache License 2.0 5 votes vote down vote up
public static List<HBaseRange> generateHBaseSplitInfo(MediaSourceInfo info, String tableName, int splitCount) {
    checkHbase(info);
    HBaseMediaSrcParameter parameter = info.getParameterObj();
    long zkId = parameter.getZkMediaSourceId();
    String znode = parameter.getZnodeParent();
    MediaSourceInfo zkInfo = dao.findMediaSourceById(zkId);
    checkZookeepr(zkInfo);
    ZkMediaSrcParameter zkParameter = zkInfo.getParameterObj();

    HBaseParameterVO vo = new HBaseParameterVO();
    vo.setTableName(tableName);
    vo.setZkAddress(zkParameter.getServers());
    vo.setPort(zkParameter.parsePort() + "");
    vo.setZnode(parameter.getZnodeParent());
    vo.setSplitCount(splitCount);
    vo.setHbaseParameter(parameter);
    String json = execute(vo, GENERATE_SPLIT_INFO);
    Map<String, Object> map = JSONObject.parseObject(json, Map.class);
    JSONArray array = (JSONArray) map.get("range");
    Object[] obj_arr = array.toArray();
    List<HBaseRange> list = new ArrayList<>();
    for (Object o : obj_arr) {
        String str = JSONObject.toJSONString(o);
        HBaseRange hr = JSONObject.parseObject(str, HBaseRange.class);
        list.add(hr);
    }
    return list;
}