com.jeesuite.common.json.JsonUtils Java Examples

The following examples show how to use com.jeesuite.common.json.JsonUtils. 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: WxUserController.java    From oneplatform with Apache License 2.0 6 votes vote down vote up
/**
 * <pre>
 * 获取用户绑定手机号信息
 * </pre>
 */
@GetMapping("/phone")
@ApiPermOptions(perms = PermissionType.Logined)
public String phone(@PathVariable String appid, String sessionKey, String signature,
                    String rawData, String encryptedData, String iv) {
    final WxMaService wxService = weixinAppManager.getMaService(appid);

    // 用户信息校验
    if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
        return "user check failed";
    }

    // 解密
    WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

    return JsonUtils.toJson(phoneNoInfo);
}
 
Example #2
Source File: ZkJobRegistry.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@Override
public void setStoping(String jobName, Date nextFireTime, Exception e) {
	updatingStatus = false;
	try {
		JobConfig config = getConf(jobName, false);
		config.setRunning(false);
		config.setNextFireTime(nextFireTime);
		config.setModifyTime(Calendar.getInstance().getTimeInMillis());
		config.setErrorMsg(e == null ? null : e.getMessage());
		// 更新本地
		schedulerConfgs.put(jobName, config);
		try {
			if (zkAvailabled)
				zkClient.writeData(getPath(config), JsonUtils.toJson(config));
		} catch (Exception ex) {
			checkZkAvailabled();
			logger.warn(String.format("Job[{}] setStoping error...", jobName), ex);
		}
	} finally {
		updatingStatus = false;
	}

}
 
Example #3
Source File: ZkJobRegistry.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@Override
public void setRuning(String jobName, Date fireTime) {
	updatingStatus = false;
	try {
		JobConfig config = getConf(jobName, false);
		config.setRunning(true);
		config.setLastFireTime(fireTime);
		config.setModifyTime(Calendar.getInstance().getTimeInMillis());
		config.setErrorMsg(null);
		// 更新本地
		schedulerConfgs.put(jobName, config);
		try {
			if (zkAvailabled)
				zkClient.writeData(getPath(config), JsonUtils.toJson(config));
		} catch (Exception e) {
			checkZkAvailabled();
			logger.warn(String.format("Job[{}] setRuning error...", jobName), e);
		}
	} finally {
		updatingStatus = false;
	}
}
 
Example #4
Source File: ErrorMessageProcessor.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
private void retry(){
	if(retryCount == maxReties){
		if(retryErrorHandler != null){
			try {
				retryErrorHandler.process(ConsumerContext.getInstance().getGroupId(),message.topic(), message);
			} catch (Exception e) {
				logger.warn("persistHandler error,topic["+message.topic()+"]",e);
			}
		}else{					
			logger.warn("retry_skip process message[{}] maxReties over {} time error!!!",JsonUtils.toJson(message),maxReties);
		}
		return;
	}
	nextFireTime = nextFireTime + retryCount * retryPeriodUnit;
	//重新放入任务队列
	taskQueue.add(this);
	logger.debug("retry_resubmit mssageId[{}] task to queue,next fireTime:{}",this.message.getMsgId(),nextFireTime);
}
 
Example #5
Source File: ConfigStateHolder.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
public void publishChangeConfig(Map<String, String> changeConfigs){
	if(changeConfigs.isEmpty())return;
	if(!SYNC_TYPE_HTTP.equals(syncType)){
		ZkClient zkClient = getZkClient(env);
		if(zkClient.countChildren(zkPath) == 0){
			return;
		}
		zkClient.writeData(zkPath, JsonUtils.toJson(changeConfigs));
	}else{
		waitingSyncConfigs.putAll(changeConfigs);
		List<ConfigState> list = configStates.get(appName + "#" + env);
		for (ConfigState configState : list) {
			configState.existWaitSyncConfig = true;
		}
	}
}
 
Example #6
Source File: ConfigParseUtils.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static void parseConfigToKVMap(Map<String, Object> result, AppconfigEntity config) {
	if(config.getType() == 1){
		if(config.getName().toLowerCase().endsWith(".xml")){
			parseDataFromXML(result,config.getContents());
		}else if(config.getName().toLowerCase().endsWith(".yml") || config.getName().toLowerCase().endsWith(".yaml")){
			parseDataFromYaml(result,config.getContents());
		}else{				
			parseFromProps(result, config.getContents());
		}
	}else if(config.getType() == 2){
		result.put(config.getName(), config.getContents());
	}else if(config.getType() == 3){
		Map<String,Object> configs = JsonUtils.toObject(config.getContents(), Map.class);
		result.putAll(configs);
	}
	
	//替换引用
	String value;
	for (String key : result.keySet()) {
		value =  StringUtils.trimToEmpty(result.get(key).toString());
		if(value.contains("${")){
			setReplaceHolderRefValue(result,key,value);
		}
	}
}
 
Example #7
Source File: ZkClientProxy.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
public void subscribeDataChanges(ConfigcenterContext context,String dataPath) {
	zkClient.subscribeDataChanges(dataPath, new IZkDataListener() {
		@Override
		public void handleDataDeleted(String arg0) throws Exception {}
		
		@Override
		public void handleDataChange(String path, Object data) throws Exception {
			if(data == null || StringUtils.isBlank(data.toString()))return;
			try {						
				Map<String, Object> changeDatas = JsonUtils.toObject(data.toString(),Map.class);
				context.updateConfig(changeDatas);
			} catch (Exception e) {
				logger.error("updateConfig error",e);
			}
		}
	});
}
 
Example #8
Source File: WebUtils.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
public static  void responseOutJsonp(HttpServletResponse response,String callbackFunName,Object jsonObject) {  
    //将实体对象转换为JSON Object转换  
    response.setCharacterEncoding("UTF-8");  
    response.setContentType("text/plain; charset=utf-8");  
    PrintWriter out = null;  
    
    String json = (jsonObject instanceof String) ? jsonObject.toString() : JsonUtils.toJson(jsonObject);
    String content = callbackFunName + "("+json+")";
    try {  
        out = response.getWriter();  
        out.append(content);  
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        if (out != null) {  
            out.close();  
        }  
    }  
}
 
Example #9
Source File: WxUserController.java    From oneplatform with Apache License 2.0 6 votes vote down vote up
/**
 * <pre>
 * 获取用户信息接口
 * </pre>
 */
@GetMapping("/info")
@ApiPermOptions(perms = PermissionType.Logined)
public String info(@PathVariable String appid, String sessionKey,
                   String signature, String rawData, String encryptedData, String iv) {
    final WxMaService wxService = weixinAppManager.getMaService(appid);

    // 用户信息校验
    if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
        return "user check failed";
    }

    // 解密用户信息
    WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

    return JsonUtils.toJson(userInfo);
}
 
Example #10
Source File: PermissionController.java    From oneplatform with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "perm/batch_create", method = RequestMethod.POST)
public @ResponseBody WrapperResponse<String> batchCreatePermResources(HttpServletRequest request,@RequestBody BatchCreateResourceParam param){
	String[] menuNames = StringUtils.splitByWholeSeparator(param.getMenuName(), ">");
	if(param.getApis() == null)throw new JeesuiteBaseException(400,"请填写关联接口");
	for (int i = 0; i < param.getApis().size(); i++) {
		ApiDefine apiDefine = param.getApis().get(i);
		if(StringUtils.isAnyBlank(apiDefine.getMethod(),apiDefine.getName(),apiDefine.getUri())){
			param.getApis().remove(i);
			i--;
		}
	}
	if(param.getApis().isEmpty())throw new JeesuiteBaseException(400,"请完整填写关联接口");
	
	permissionService.batchCreatePermResources(param.getPlatformType(), menuNames, param.getMenuUri(), param.getApis());
	
	boolean jsonSubmit = Boolean.parseBoolean(request.getParameter("jsonSubmit"));
	return new WrapperResponse<>(jsonSubmit == false ? JsonUtils.toPrettyJson(param) : null);
}
 
Example #11
Source File: ConfigcenterContext.java    From jeesuite-config with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String,Object> fetchConfigFromServer(){
	Map<String,Object> result = null;
	String errorMsg = null;
       for (String apiBaseUrl : apiBaseUrls) {
       	String url = buildTokenParameter(String.format("%s/api/fetch_all_configs?appName=%s&env=%s&version=%s", apiBaseUrl,app,env,version));
   		System.out.println("fetch configs url:" + url);
   		String jsonString = null;
   		try {
   			HttpResponseEntity response = HttpUtils.get(url);
       		if(response.isSuccessed()){
       			jsonString = response.getBody();
       			result = JsonUtils.toObject(jsonString, Map.class);
       			if(result.containsKey("code")){
       				errorMsg = result.get("msg").toString();
       				System.err.println("fetch error:"+errorMsg);
       				result = null;
       			}else{
       				break;
       			}
       		}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
       //
       if(result == null){
       	System.out.println(">>>>>remote Config fecth error, load from local Cache");
       	result = LocalCacheUtils.read();
       }else{
       	LocalCacheUtils.write(result);
       }
       return result;
}
 
Example #12
Source File: ExcelTest.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
/**
 * @param args
 * @throws IOException
 * @throws InvalidFormatException
 */
public static void main(String[] args) throws InvalidFormatException, IOException {
	//普通方式读取
	String excelFilePath = "/Users/jiangwei/Desktop/invorderdet_template.xlsx";

	//大文件读取防止内存溢出
	List<SimpleSalaryInfo> list = new ExcelPerfModeReader(excelFilePath).read(SimpleSalaryInfo.class);

	System.out.println(JsonUtils.toPrettyJson(list));

}
 
Example #13
Source File: SchedulerMonitor.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public JobGroupInfo getJobGroupInfo(String groupName){

		if(StringUtils.isBlank(groupName)){
			logger.warn("getJobGroupInfo groupName is required");
			return null;
		}
		JobGroupInfo groupInfo = new JobGroupInfo();
		groupInfo.setName(groupName);
        if(asyncEventBus != null){
        	groupInfo.setJobs(JobContext.getContext().getRegistry().getAllJobs());
        	return groupInfo;
        }
		//
		String path = ZkJobRegistry.ROOT + groupName;
		List<String> children = zkClient.getChildren(path);
		for (String child : children) {
			if("nodes".equals(child)){
				path = ZkJobRegistry.ROOT + groupName + "/nodes";
				groupInfo.setClusterNodes(zkClient.getChildren(path));
			}else{
				path = ZkJobRegistry.ROOT + groupName + "/" + child;
				Object data = zkClient.readData(path);
				if(data != null){						
					JobConfig jobConfig = JsonUtils.toObject(data.toString(), JobConfig.class);
					groupInfo.getJobs().add(jobConfig);
				}
			}
		}
		
		if(groupInfo.getClusterNodes().size() > 0){				
			return groupInfo;
		}
		
		return null;
	
	}
 
Example #14
Source File: SchedulerMonitor.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	SchedulerMonitor monitor = new SchedulerMonitor("zookeeper", "127.0.0.1:2181");
	
	List<JobGroupInfo> groups = monitor.getAllJobGroups();
	System.out.println(JsonUtils.toJson(groups));
	
	monitor.close();
}
 
Example #15
Source File: SerliazePerfTest.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	JavaSerializer javaSerializer = new JavaSerializer();
	List<User> users = new ArrayList<>();
	for (int i = 0; i < 10; i++) {
		users.add(new User(i+1000, "user"+i));
	}
	
	byte[] bytes = javaSerializer.serialize(users);
	System.out.println(bytes.length);
	System.out.println(SerializeUtils.serialize(users).length);
	System.out.println(JsonUtils.toJson(users).getBytes().length);
	
	
}
 
Example #16
Source File: BeanUtilTest.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	User user = new User();
	user.setName("小伙子");
	user.setMobile("13800138000");
	user.setFather(new User(1000, "你爹"));
	
	BaseUser user2 = BeanUtils.copy(user, BaseUser.class);
	System.out.println(JsonUtils.toPrettyJson(user2));
}
 
Example #17
Source File: User.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	
	User user = new User();
	user.setId(100);
	user.setName("jack");
	
	DefaultMessage message = new DefaultMessage(user).consumerAckRequired(true).header("key1", "value1");
	String json = JsonUtils.toJson(message);
	System.out.println(json);
	
	message = JsonUtils.toObject(json,DefaultMessage.class);
	System.out.println(message);
}
 
Example #18
Source File: ProducerSimpleClient.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Test
	public void testPublish() throws InterruptedException{
        //默认模式(异步/ )发送
		for (int i = 0; i < 5; i++) {	
			User user = new User();
			user.setId(100+i);
			user.setName("jack");
			topicProducer.publish("app-union-logs", new DefaultMessage(JsonUtils.toJson(user)).sendBodyOnly(true));
			//topicProducer.publish("demo-topic2", new DefaultMessage(user));
			//topicProducer.publishNoWrapperMessage("streams-plaintext-input", "hello " + i);
		}
//		
//		DefaultMessage msg = new DefaultMessage("hello,man")
//		            .header("headerkey1", "headerval1")//写入header信息
//		            .header("headerkey1", "headerval1")//写入header信息
//		            .partitionFactor(1000) //分区因子,譬如userId=1000的将发送到同一分区、从而发送到消费者的同一节点(有状态)
//		            .consumerAck(true);// 已消费回执(未发布)
//		
		
//		User user = new User();
//		user.setAge(17);
//		user.setId(1);
//		user.setName("kafka");
//		//异步发送
//		topicProducer.publishNoWrapperMessage("demo-topic", JsonUtils.toJson(user),true);
		
		Thread.sleep(5000);
				
	}
 
Example #19
Source File: KafkaMonitor.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
private synchronized void fetchProducerStatFromZK(){
	Map<String,List<ProducerStat>> currentStats = new HashMap<>();
	List<String> groups = zkClient.getChildren(SendCounterHandler.ROOT);
	if(groups == null)return ;
	
	List<String> nodes;
	List<ProducerStat> stats;
	String groupPath,topicPath,nodePath;
	for (String group : groups) {
		stats = currentStats.get(group);
		if(stats == null){
			stats = new ArrayList<>();
			currentStats.put(group, stats);
		}
		groupPath = SendCounterHandler.ROOT + "/" + group;
		List<String> topics = zkClient.getChildren(groupPath);
		for (String topic : topics) {				
			topicPath = groupPath + "/" + topic;
			nodes = zkClient.getChildren(topicPath);
			for (String node : nodes) {
				nodePath = topicPath + "/" + node;
				Object data = zkClient.readData(nodePath);
				if(data != null){
					ProducerStat stat = JsonUtils.toObject(data.toString(), ProducerStat.class);
					stat.setSource(node);
					stats.add(stat);
				}
			}
		}
	}
	producerStats = currentStats;
}
 
Example #20
Source File: UploadTokenParam.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
public String getCallbackRuleAsJson(){
	if(StringUtils.isAnyBlank(callbackBody,callbackHost,callbackUrl))return null;
	Map<String, String> map = new HashMap<>(4);
	map.put("callbackBody", callbackBody);
	map.put("callbackHost", callbackHost);
	map.put("callbackUrl", callbackUrl);
	map.put("callbackBodyType", getCallbackBodyType());
	return JsonUtils.toJson(map);
}
 
Example #21
Source File: JsonMessageSerializer.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
/**
 * serialize
 *
 * @param topic topic associated with data
 * @param data  typed data
 * @return serialized bytes
 */
@Override
public byte[] serialize(String topic, Serializable data) {
    try {
        if (data == null)
            return null;
        else{     
        	String toString = isSimpleDataType(data) ? data.toString() : JsonUtils.toJson(data);
        	return  toString.getBytes(StandardCharsets.UTF_8.name());
        }
    } catch (UnsupportedEncodingException e) {
        throw new SerializationException("Error when serializing string to byte[] due to unsupported encoding UTF-8");
    }

}
 
Example #22
Source File: EurekaRegistry.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
private void waitForRegistrationWithEureka() {
      long startTime = System.currentTimeMillis();
      new Thread(new Runnable() {
	@Override
	public void run() {
		while (true) {
        	if(System.currentTimeMillis() - startTime > VERIFY_WAIT_MILLIS){
        		log.warn(" >>>> service registration status not verify,please check it!!!!");
        		return;
        	}
            try {
            	List<InstanceInfo> serverInfos = eurekaClient.getInstancesByVipAddress(vipAddress, false);
            	for (InstanceInfo nextServerInfo : serverInfos) {
            		if(nextServerInfo.getIPAddr().equals(IpUtils.LOCAL_BACK_IP) || 
                    		nextServerInfo.getIPAddr().equals(IpUtils.getLocalIpAddr())){
            			String instanceInfoJson = JsonUtils.getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(nextServerInfo);
						log.info("verifying service registration with eureka finished,instance:\n{}",instanceInfoJson);
            			return;
            		}
				}
            } catch (Throwable e) {}
            try {Thread.sleep(5000);} catch (Exception e1) {}
        	log.info("Waiting 5s... verifying service registration with eureka ...");
        }
	}
}).start();
  }
 
Example #23
Source File: SendCounterHandler.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
private void commitToZK(){
	if(commited.get())return;
	Set<Entry<String, AtomicLong[]>> entrySet = producerStats.entrySet();
	for (Entry<String, AtomicLong[]> entry : entrySet) {
		AtomicLong[] nums = entry.getValue();
		ProducerStat stat = new ProducerStat(entry.getKey(), producerGroup, nums[0], nums[1], nums[2], nums[3]);
		zkClient.writeData(statPaths.get(entry.getKey()), JsonUtils.toJson(stat));
	}
	commited.set(true);
}
 
Example #24
Source File: CustomRouteLocator.java    From oneplatform with Apache License 2.0 5 votes vote down vote up
@Override  
  protected Map<String, ZuulProperties.ZuulRoute> locateRoutes() {  
      LinkedHashMap<String, ZuulProperties.ZuulRoute> routesMap = new LinkedHashMap<>();  
      
      routesMap.putAll(super.locateRoutes());  
      
      ModuleEntityMapper entityMapper = null;
      try {entityMapper = InstanceFactory.getInstance(ModuleEntityMapper.class);} catch (Exception e) {}
      if(entityMapper == null)return routesMap;
      
      List<ModuleEntity> serviceModules = entityMapper.findAllEnabled();
      
      String path = null;
      ZuulProperties.ZuulRoute zuulRoute = null;
      for (ModuleEntity module : serviceModules) {
      	if(module.getEnabled() == false 
      			|| module.getServiceId().equalsIgnoreCase(GlobalContants.MODULE_NAME) 
      			|| ModuleType.plugin.name().equals(module.getModuleType()))continue;
      	path = String.format("/%s/**", module.getRouteName());
      	
      	zuulRoute = new ZuulProperties.ZuulRoute();  
      	zuulRoute.setPath(path);
      	zuulRoute.setId(module.getRouteName());
      	zuulRoute.setServiceId(module.getServiceId());
      	
      	routesMap.put(path, zuulRoute);
      	registryRouteIds.add(module.getRouteName());
      	
      	logger.info("add new Route:{} = {}",path,JsonUtils.toJson(zuulRoute));
}

      return routesMap;  
  }
 
Example #25
Source File: ConfigParseUtils.java    From jeesuite-config with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
 String content = FileUtils.readFileToString(new File("/Users/jiangwei/tikv-docker-compose.yml"));
 Map<String, Object> result = new HashMap<>();
 parseDataFromYaml(result, content);
 
 System.out.println(JsonUtils.toPrettyJson(result));
}
 
Example #26
Source File: CacheHandler.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
/**
 * 生成查询缓存key
 * @param cacheInfo
 * @param param
 * @return
 */
@SuppressWarnings("unchecked")
private String genarateQueryCacheKey(String keyPattern,Object param){
	String text;
	try {
		Object[] args;
		if(param instanceof Map){
			Map<String, Object> map = (Map<String, Object>) param;
			if(map.containsKey(STR_PARAM + "1")){
				args = new String[map.size()/2];
				for (int i = 0; i < args.length; i++) {
					args[i] = CacheKeyUtils.objcetToString(map.get(STR_PARAM + (i+1)));
				}
			}else{
				args = new String[]{CacheKeyUtils.objcetToString(map)};
			}
		}else if(param instanceof BaseEntity){
			Serializable id = ((BaseEntity)param).getId();
			if(id != null && !"0".equals(id.toString())){	
				args = new String[]{(((BaseEntity)param).getId()).toString()};
			}else{
				args = new String[]{CacheKeyUtils.objcetToString(param)};
			}
		}else if(param instanceof Object[]){
			args = (Object[])param;
		}else if(param == null){
			args = new Object[0];
		}else{
			args = new String[]{CacheKeyUtils.objcetToString(param)};
		}
		
		text = StringUtils.join(args,"-");
	} catch (Exception e) {
		text = JsonUtils.toJson(param);
		e.printStackTrace();
	}
	if(text.length() > 64)text = DigestUtils.md5(text);

	return String.format(keyPattern, text);
}
 
Example #27
Source File: AuthController.java    From jeesuite-config with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "login", method = RequestMethod.POST)
public ResponseEntity<WrapperResponseEntity> login(HttpServletRequest request,@RequestBody Map<String, String> params){
	String userName = StringUtils.trimToEmpty(params.get("userName"));
	String password = StringUtils.trimToEmpty(params.get("password"));
	
	UserEntity userEntity = FormatValidateUtils.isMobile(userName) ? userMapper.findByMobile(userName) : userMapper.findByName(userName);
	if(userEntity == null || !userEntity.getPassword().equals(UserEntity.encryptPassword(password))){
		return new ResponseEntity<WrapperResponseEntity>(new WrapperResponseEntity(4001, "账号或密码错误"),HttpStatus.OK);
	}
	
	LoginUserInfo loginUserInfo = new LoginUserInfo(userEntity.getName());
	loginUserInfo.setSuperAdmin(userEntity.getType().intValue() == 1);
	loginUserInfo.setId(userEntity.getId());
	if(!loginUserInfo.isSuperAdmin()){	
		if(userEntity.getStatus() != 1){
			throw new JeesuiteBaseException(1001, "该账号已停用");
		}
		//加载权限
		List<UserPermissionEntity> userPermissions = userPermissionMapper.findByUserId(userEntity.getId());
		List<String> permCodes;
		for (UserPermissionEntity entity : userPermissions) {
			permCodes = loginUserInfo.getPermissonData().get(entity.getEnv());
			if(permCodes == null){
				loginUserInfo.getPermissonData().put(entity.getEnv(), permCodes = new ArrayList<>());
			}
			permCodes.add(entity.toPermissionCode());
			//
			if(!loginUserInfo.getGrantAppIds().contains(entity.getAppId())){
				loginUserInfo.getGrantAppIds().add(entity.getAppId());
			}
		}
	}

	request.getSession().setAttribute(Constants.LOGIN_SESSION_KEY, loginUserInfo);
	logger.info(">>PermissonData:{}", JsonUtils.toJson(loginUserInfo.getPermissonData()));
	return new ResponseEntity<WrapperResponseEntity>(new WrapperResponseEntity(loginUserInfo),HttpStatus.OK);
}
 
Example #28
Source File: LocalCacheUtils.java    From jeesuite-config with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Map<String, Object> read() {
	try {
		File dir = new File(localStorageDir);
		if (!dir.exists())
			dir.mkdirs();
		File file = new File(dir, "config-cache.json");
		if (!file.exists()) {
			return null;
		}

		StringBuilder buffer = new StringBuilder();
		InputStream is = new FileInputStream(file);
		String line;
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		line = reader.readLine();
		while (line != null) { 
			buffer.append(line); 
			line = reader.readLine();
		}
		reader.close();
		is.close();
		return JsonUtils.toObject(buffer.toString(), Map.class);
	} catch (Exception e) {
		
	}
	return null;
}
 
Example #29
Source File: LocalCacheUtils.java    From jeesuite-config with Apache License 2.0 5 votes vote down vote up
public static void write(Map<String, Object> datas) {
	try {
		File dir = new File(localStorageDir);
		if (!dir.exists())
			dir.mkdirs();
		File file = new File(dir, "config-cache.json");
		if (!file.exists()) {
			file.createNewFile();
		}
		FileWriter fileWritter = new FileWriter(file.getName(), false);
		fileWritter.write(JsonUtils.toJson(datas));
		fileWritter.close();
	} catch (Exception e) {
	}
}
 
Example #30
Source File: CustomResponseErrorHandler.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Override
public void handleError(ClientHttpResponse response) throws IOException {
	int code = response.getRawStatusCode();
	String content = CharStreams.toString(new InputStreamReader(response.getBody(), StandardCharsets.UTF_8));
	
	Map<?, ?> responseItmes = null;
	if(code == 404 && StringUtils.isNotBlank(content)){
		responseItmes = JsonUtils.toObject(content, Map.class);
		throw new JeesuiteBaseException(404, "Page Not Found["+responseItmes.get("path")+"]");
	}

	int errorCode = 500;
	String errorMsg = content;
	try {responseItmes = JsonUtils.toObject(content, Map.class);} catch (Exception e) {}
	if(responseItmes != null){
		if(responseItmes.containsKey("code")){
			errorCode = Integer.parseInt(responseItmes.get("code").toString());
		}
		if(responseItmes.containsKey("msg")){
			errorMsg = responseItmes.get("msg").toString();
		}else if(responseItmes.containsKey("message")){
			errorMsg = responseItmes.get("message").toString();
		}
	}
	
	if(StringUtils.isBlank(errorMsg)){
		errorMsg = DEFAULT_ERROR_MSG;
	}
	
	throw new JeesuiteBaseException(errorCode, errorMsg + "(Remote)");
}