Java Code Examples for com.alibaba.fastjson.JSONObject#getLongValue()

The following examples show how to use com.alibaba.fastjson.JSONObject#getLongValue() . 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: ElasticSearchUtil.java    From RCT with Apache License 2.0 6 votes vote down vote up
/**
 * 根据ID更新index
 *
 * @param index
 * @param type
 * @param id
 * @param document
 * @return
 * @throws Exception
 */
public static boolean updateIndex(String index, String type, String id, String document) throws Exception {
	StringEntity entity = new StringEntity(document, ContentType.APPLICATION_JSON);
	String result = httpPut(getUrl() + "/" + index + "/" + type + "/" + id + "?refresh=true", entity);
	try {
		JSONObject json = JSONObject.parseObject(result);
		if (json.containsKey("_shards")) {
			JSONObject shards = json.getJSONObject("_shards");
			if (shards.getLongValue("failed") == 0) {
				return true;
			}
		}
	} catch (Exception e) {
		throw new Exception(result);
	}
	return false;
}
 
Example 2
Source File: AbstractLiveMsgListener.java    From wakeup-qcloud-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public final QCloudMsgResponse doProcess(String jsonBody,Map<String,Object> urlParams,String key) {
	JSONObject jsonObject = JSON.parseObject(jsonBody);
	String sign = jsonObject.getString("sign");
	long t = jsonObject.getLongValue("t");
	if (!isValid(t, key, sign)) {
		return onInvalidMsg(jsonBody);
	}
	int eventType = jsonObject.getIntValue("event_type");
	switch (eventType) {
	case LiveMsgEventType.CUT_STREAM:
		return onCutStream(JSON.parseObject(jsonBody, LiveMsgStreamEventDO.class));
	case LiveMsgEventType.PUSH_STREAM:
		return onPushStream(JSON.parseObject(jsonBody, LiveMsgStreamEventDO.class));
	case LiveMsgEventType.RECORD_AV_CREATED:
		return onAvRecordCreated(JSON.parseObject(jsonBody, LiveMsgAvRecordCreatedDO.class));
	case LiveMsgEventType.SCREENSHOT_CREATED:
		return onScreenshotCreated(JSON.parseObject(jsonBody, LiveMsgScreenshotCreatedDO.class));
	default:
		break;
	}
	return LiveMsgResponse.FAILED;
}
 
Example 3
Source File: DSLSearchDocument.java    From DataLink with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * Description: 查询符合条件的文档条数
 * Created on 2016-7-21 上午10:07:23
 * @author  孔增([email protected])
 * @param vo
 * @return
 * @throws UnsupportedEncodingException
 */
public long dslSearchDocumentCount(DSLSearchVo vo) throws UnsupportedEncodingException {
	Assert.notNull(vo, "DSLSearchVo is requeired");
	
	vo.setMetaType("_count");
	
	byte [] bytes = null;
	if(vo.getCondition() != null) {
		bytes = vo.getCondition().getBytes("utf-8");
	}
	JSONObject json = JSONObject.parseObject(super.processRequest(vo, bytes));
	if(json == null) {
		return 0;
	}
	ProcessResult.checkError(json);
	return json.getLongValue(ParseHandler.COUNT_NAME);
}
 
Example 4
Source File: DSLSearchDocument.java    From DataLink with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * Description: 查询符合条件的文档条数
 * Created on 2016-7-21 上午10:07:23
 * @author  孔增([email protected])
 * @param vo
 * @return
 * @throws UnsupportedEncodingException
 */
public long dslSearchDocumentCount(DSLSearchVo vo) throws UnsupportedEncodingException {
	Assert.notNull(vo, "DSLSearchVo is requeired");
	
	vo.setMetaType("_count");
	
	byte [] bytes = null;
	if(vo.getCondition() != null) {
		bytes = vo.getCondition().getBytes("utf-8");
	}
	JSONObject json = JSONObject.parseObject(super.processRequest(vo, bytes));
	if(json == null) {
		return 0;
	}
	ProcessResult.checkError(json);
	return json.getLongValue(ParseHandler.COUNT_NAME);
}
 
Example 5
Source File: DSLSearchDocument.java    From DataLink with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * Description: 查询符合条件的文档条数
 * Created on 2016-7-21 上午10:07:23
 * @author  孔增([email protected])
 * @param vo
 * @return
 * @throws UnsupportedEncodingException
 */
public long dslSearchDocumentCount(DSLSearchVo vo) throws UnsupportedEncodingException {
	Assert.notNull(vo, "DSLSearchVo is requeired");
	
	vo.setMetaType("_count");
	
	byte [] bytes = null;
	if(vo.getCondition() != null) {
		bytes = vo.getCondition().getBytes("utf-8");
	}
	JSONObject json = JSONObject.parseObject(super.processRequest(vo, bytes));
	if(json == null) {
		return 0;
	}
	ProcessResult.checkError(json);
	return json.getLongValue(ParseHandler.COUNT_NAME);
}
 
Example 6
Source File: VideoDetails.java    From java-youtube-downloader with Apache License 2.0 6 votes vote down vote up
public VideoDetails(JSONObject json, String liveHLSUrl) {
    videoId = json.getString("videoId");
    title = json.getString("title");
    lengthSeconds = json.getIntValue("lengthSeconds");
    keywords = json.containsKey("keywords") ? json.getJSONArray("keywords").toJavaList(String.class) : new ArrayList<String>();
    shortDescription = json.getString("shortDescription");
    JSONArray jsonThumbnails = json.getJSONObject("thumbnail").getJSONArray("thumbnails");
    thumbnails = new ArrayList<>(jsonThumbnails.size());
    for (int i = 0; i < jsonThumbnails.size(); i++) {
        JSONObject jsonObject = jsonThumbnails.getJSONObject(i);
        if (jsonObject.containsKey("url"))
            thumbnails.add(jsonObject.getString("url"));
    }
    averageRating = json.getIntValue("averageRating");
    viewCount = json.getLongValue("viewCount");
    author = json.getString("author");
    isLiveContent = json.getBooleanValue("isLiveContent");
    isLive = json.getBooleanValue("isLive");
    liveUrl = liveHLSUrl;
}
 
Example 7
Source File: ElasticSearchUtil.java    From RCT with Apache License 2.0 6 votes vote down vote up
public static String getAll(String index, String type) throws Exception {
	String result = "";
	long size = count(index, type);
	try {
		result = httpGet(getUrl() + "/" + index + "/" + type + "/" + "_search?size=" + size);
		JSONObject json = JSONObject.parseObject(result);
		if (json.containsKey("_shards")) {
			JSONObject shards = json.getJSONObject("_shards");
			if (shards.getLongValue("failed") == 0) {
				return json.toJSONString();
			}
		}
	} catch (Exception e) {
		throw new Exception(result);
	}
	return result;
}
 
Example 8
Source File: ElasticSearchUtil.java    From RCT with Apache License 2.0 6 votes vote down vote up
/**
 * 指定字段排序查询所有的document
 *
 * @param index
 * @param type
 * @param sortName
 * @param isAsc
 * @return
 * @throws Exception
 */
public static String getAll(String index, String type, String sortName, boolean isAsc) throws Exception {
	String result = "";
	long size = count(index, type);
	try {
		result = httpGet(getUrl() + "/" + index + "/" + type + "/" + "_search?size=" + size + "&sort=" + sortName
				+ ":" + (isAsc ? "asc" : "desc"));
		JSONObject json = JSONObject.parseObject(result);
		if (json.containsKey("_shards")) {
			JSONObject shards = json.getJSONObject("_shards");
			if (shards.getLongValue("failed") == 0) {
				return json.toJSONString();
			}
		}
	} catch (Exception e) {
		throw new Exception(result);
	}
	return result;
}
 
Example 9
Source File: ElasticSearchUtil.java    From RCT with Apache License 2.0 6 votes vote down vote up
public static boolean postIndexDocument(String index, String type, String document) throws Exception {
	StringEntity entity = new StringEntity(document, ContentType.APPLICATION_JSON);
	String result = httpPost(getUrl() + "/" + index + "/" + type + "?refresh=true", entity);
	try {
		JSONObject json = JSONObject.parseObject(result);
		if (json.containsKey("_shards")) {
			JSONObject shards = json.getJSONObject("_shards");
			if (shards.getLongValue("failed") == 0) {
				return true;
			}
		}
	} catch (Exception e) {
		throw new Exception(result);
	}
	return false;
}
 
Example 10
Source File: JSONUtil.java    From easyweb-shiro with MIT License 5 votes vote down vote up
/**
 * 得到longValue类型的值
 */
public static long getLongValue(String json, String key) {
    long result = 0;
    try {
        JSONObject jsonObject = JSON.parseObject(json);
        result = jsonObject.getLongValue(key);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 11
Source File: ElasticSearchUtil.java    From RCT with Apache License 2.0 5 votes vote down vote up
public static long count(String index, String type) throws Exception {
	String result = httpGet(getUrl() + "/" + index + "/" + type + "/_count");
	long total = 0;
	JSONObject json = JSONObject.parseObject(result);
	if (json.containsKey("count")) {
		total = json.getLongValue("count");
	}
	return total;
}
 
Example 12
Source File: MaterialComponent.java    From weixin4j with Apache License 2.0 5 votes vote down vote up
/**
 * 新增临时素材
 *
 * @param mediaType 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
 * @param file form-data中媒体文件标识,有filename、filelength、content-type等信息
 * @return 上传成功返回素材Id,否则返回null
 * @throws org.weixin4j.WeixinException 微信操作异常
 * @since 0.1.4
 */
public Media upload(MediaType mediaType, File file) throws WeixinException {
    //创建请求对象
    HttpsClient http = new HttpsClient();
    //上传素材,返回JSON数据包
    String jsonStr = http.uploadHttps("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + weixin.getToken().getAccess_token() + "&type=" + mediaType.toString(), file);
    JSONObject jsonObj = JSONObject.parseObject(jsonStr);
    if (jsonObj != null) {
        if (Configuration.isDebug()) {
            System.out.println("新增临时素材返回json:" + jsonObj.toString());
        }
        Object errcode = jsonObj.get("errcode");
        if (errcode != null && !errcode.toString().equals("0")) {
            //返回异常信息
            throw new WeixinException(getCause(jsonObj.getIntValue("errcode")));
        } else {
            //转换为Media对象
            Media media = new Media();
            media.setMediaType(MediaType.valueOf(WordUtils.capitalize(jsonObj.getString("type"))));
            media.setMediaId(jsonObj.getString("media_id"));
            //转换为毫秒数
            long time = jsonObj.getLongValue("created_at") * 1000L;
            media.setCreatedAt(new Date(time));
            //返回多媒体文件id
            return media;
        }
    }
    return null;
}
 
Example 13
Source File: AbemaLiveService.java    From Alice-LiveMan with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public URI getLiveVideoInfoUrl(ChannelInfo channelInfo) throws Exception {
    String channelUrl = channelInfo.getChannelUrl();
    Matcher matcher = channelPattern.matcher(channelUrl);
    if (matcher.find()) {
        String channelId = matcher.group(1);
        String slotId = matcher.group(2);
        Map<String, String> requestProperties = new HashMap<>();
        requestProperties.put("Authorization", "bearer " + bearer);
        String slotInfo = HttpRequestUtil.downloadUrl(new URI("https://api.abema.io/v1/media/slots/" + slotId), channelInfo != null ? channelInfo.getCookies() : null, requestProperties, StandardCharsets.UTF_8);
        JSONObject slotInfoObj = JSON.parseObject(slotInfo);
        String seriesId = slotInfoObj.getJSONObject("slot").getJSONArray("programs").getJSONObject(0).getJSONObject("series").getString("id");
        Calendar japanCalendar = Calendar.getInstance(TimeZone.getTimeZone("JST"));
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        dateFormat.setCalendar(japanCalendar);
        long currentTimeMillis = System.currentTimeMillis();
        String formattedDate = dateFormat.format(currentTimeMillis);
        String timetableInfo = HttpRequestUtil.downloadUrl(new URI(String.format("https://api.abema.io/v1/media?dateFrom=%s&dateTo=%s&channelIds=%s", formattedDate, formattedDate, channelId)), channelInfo != null ? channelInfo.getCookies() : null, requestProperties, StandardCharsets.UTF_8);
        JSONArray channelSchedules = JSON.parseObject(timetableInfo).getJSONArray("channelSchedules");
        if (channelSchedules.isEmpty()) {
            return null;
        }
        JSONArray channelSlots = channelSchedules.getJSONObject(0).getJSONArray("slots");
        for (int i = 0; i < channelSlots.size(); i++) {
            JSONObject channelSlot = channelSlots.getJSONObject(i);
            if (channelSlot.getJSONArray("programs").getJSONObject(0).getJSONObject("series").getString("id").equals(seriesId)) {
                long startAt = channelSlot.getLongValue("startAt") * 1000;
                long endAt = channelSlot.getLongValue("endAt") * 1000;
                // 在节目播出时间内
                if (currentTimeMillis > startAt && currentTimeMillis < endAt) {
                    channelInfo.setStartAt(startAt);
                    channelInfo.setEndAt(endAt);
                    return new URI(NOW_ON_AIR_URL + channelId);
                }
            }
        }
    }
    return null;
}
 
Example 14
Source File: JobRoleHelperService.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 保持角色和菜单关系
 *
 * @param jobRole
 * @return
 */
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public boolean saveRoleAndMenu(JobRole jobRole) throws Exception {
    boolean ret = false;
    Long roleId = jobRole.getId();
    List<String> list = jobRole.getList();
    if (roleId == null || roleId <= 0) {
        return ret;
    }
    if (list == null || list.size() <= 0) {
        return ret;
    }
    int len = 0;
    len = list.size();
    List<JobMenuRole> menuRoleList = new ArrayList<>();
    for (int i = 0; i < len; i++) {
        String s = list.get(i).replace("[", "").replace("]", "");
        JSONObject jsonObject = JSONObject.parseObject(s);
        if (jsonObject == null) {
            continue;
        }
        JobMenuRole jobMenuRole = new JobMenuRole();
        long id = jsonObject.getLongValue("id");
        jobMenuRole.setMenuId(id);
        jobMenuRole.setRoleId(roleId);
        jobMenuRole.setRoleCode(jobRole.getRoleCode());
        menuRoleList.add(jobMenuRole);
    }
    if (menuRoleList.size() > 0) {
        jobMenuRoleHelperService.addTrainRecordBatch(menuRoleList);
        ret = true;
    }
    return ret;
}
 
Example 15
Source File: ComponentInfo.java    From Tangram-Android with MIT License 5 votes vote down vote up
public ComponentInfo(JSONObject json) {
    this.name = json.getString(NAME);
    this.id = json.getString(ID);
    this.type = json.getString(TYPE);
    this.version = json.getLongValue(VERSION);
    this.url = json.getString(URL);
}
 
Example 16
Source File: AnnouncementHelper.java    From NIM_Android_UIKit with MIT License 5 votes vote down vote up
public static List<Announcement> getAnnouncements(String teamId, String announce, int limit) {
    if (TextUtils.isEmpty(announce)) {
        return null;
    }

    List<Announcement> announcements = new ArrayList<>();
    try {
        int count = 0;
        JSONArray jsonArray = JSONArray.parseArray(announce);
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject json = jsonArray.getJSONObject(i);
            String id = json.getString(JSON_KEY_ID);
            String creator = json.getString(JSON_KEY_CREATOR);
            String title = json.getString(JSON_KEY_TITLE);
            long time = json.getLongValue(JSON_KEY_TIME);
            String content = json.getString(JSON_KEY_CONTENT);

            announcements.add(new Announcement(id, teamId, creator, title, time, content));

            if (++count >= limit) {
                break;
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return announcements;
}
 
Example 17
Source File: CheckStaffHasPropertyListener.java    From MicroCommunity with Apache License 2.0 4 votes vote down vote up
@Override
public void soService(ServiceDataFlowEvent event) {

    logger.debug("ServiceDataFlowEvent : {}",event);

    DataFlowContext dataFlowContext = event.getDataFlowContext();
    AppService service = event.getAppService();
    String paramIn = dataFlowContext.getReqData();
   /* Assert.isJsonObject(paramIn,"用户注册请求参数有误,不是有效的json格式 "+paramIn);
    Assert.jsonObjectHaveKey(paramIn,"userId","请求报文中未包含userId 节点请检查 " +paramIn);
    JSONObject paramObj = JSONObject.parseObject(paramIn);*/
    ResponseEntity responseEntity= null;

    HttpHeaders header = new HttpHeaders();
    for(String key : dataFlowContext.getRequestCurrentHeaders().keySet()){
        header.add(key,dataFlowContext.getRequestCurrentHeaders().get(key));
    }
    HttpEntity<String> httpEntity = new HttpEntity<String>(paramIn, header);
    super.doRequest(dataFlowContext, service, httpEntity);
    responseEntity = dataFlowContext.getResponseEntity();
    dataFlowContext.setResponseEntity(responseEntity);

    if(responseEntity.getStatusCode() != HttpStatus.OK){
        return ;
    }
    String resObj = responseEntity.getBody().toString();

    Assert.isJsonObject(resObj,"下游服务返回格式错误,不是有效json格式"+resObj);

    JSONObject resJson = JSONObject.parseObject(resObj);

    Assert.jsonObjectHaveKey(resJson,"count","下游服务返回格式错误,返回报文中未包含count"+resObj);

    long count = resJson.getLongValue("count");

    if(count < 1){
        throw  new ListenerExecuteException(ResponseConstant.RESULT_CODE_INNER_ERROR,"当前员工没有相关物业信息,数据异常请检查");
    }

    responseEntity = new ResponseEntity<String>("成功",HttpStatus.OK);


}
 
Example 18
Source File: ReliableTaildirEventReader.java    From uavstack with Apache License 2.0 4 votes vote down vote up
public void loadPositions(String json) {

        if (StringHelper.isEmpty(json)) {
            return;
        }

        Long inode = 0L, pos = 0L, number = 0L;
        String file = "";
        JSONArray positionRecords = JSONArray.parseArray(json);
        for (int i = 0; i < positionRecords.size(); i++) {
            JSONObject positionObject = (JSONObject) positionRecords.get(i);
            inode = positionObject.getLong("inode");
            pos = positionObject.getLong("pos");
            file = positionObject.getString("file");
            Long currentInode = 0L;
            try {
                currentInode = getInode(new File(file));
            }
            catch (IOException e1) {
                log.err(this, "TailFile updatePos FAILED,getInode Fail.", e1);
            }
            if (!currentInode.equals(inode)) {
                maybeReloadMap.remove(inode);
            }
            else {
                // add line number
                number = positionObject.getLongValue("num");
                for (Object v : Arrays.asList(inode, pos, file)) {
                    Preconditions.checkNotNull(v, "Detected missing value in position file. " + "inode: " + inode
                            + ", pos: " + pos + ", path: " + file);
                }
                TailFile tf = tailFiles.get(inode);
                try {
                    if (tf != null && tf.updatePos(file, inode, pos, number)) {
                        tailFiles.put(inode, tf);
                    }
                    else {
                        // add old tail file into memory
                        maybeReloadMap.put(inode, new Long[] { pos, number });
                        if (log.isDebugEnable()) {
                            log.debug(this, "add old&inInterrupt file: " + file + ", inode: " + inode + ", pos: " + pos);
                        }

                    }
                }
                catch (IOException e) {
                    log.err(this, "TailFile updatePos FAILED.", e);
                }
            }
        }
    }