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

The following examples show how to use com.alibaba.fastjson.JSONObject#isEmpty() . 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: SmsTemplateServiceImpl.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
private static String getParamByContent(String content, String regEx) {
    //编译正则表达式
    Pattern pattern = Pattern.compile(regEx);
    //忽略大小写的写法:
    Matcher matcher = pattern.matcher(content);

    // 查找字符串中是否有匹配正则表达式的字符/字符串//有序, 目的是为了兼容 腾讯云参数
    JSONObject obj = new JSONObject(true);
    while (matcher.find()) {
        String key = matcher.group(1);
        obj.put(key, "");
    }
    if (obj.isEmpty()) {
        throw BizException.wrap("模板内容解析失败,请认真详细内容格式");
    }

    return obj.toString();
}
 
Example 2
Source File: EsReader.java    From DataLink with Apache License 2.0 6 votes vote down vote up
private void retrieveIndexMapping(List<String> columns) {
    MappingIndexVo vo = new MappingIndexVo();
    vo.setIndex(this.esIndex);
    vo.setType(this.esType);
    vo.setMetaType("_mapping");
    String response = EsClient.viewMappingIndex(vo);
    JSONObject mappings = JSON.parseObject(response);
    if (mappings.isEmpty()) {
        throw DataXException.asDataXException(EsReaderErrorCode.MAPPING_NOT_FOUND, response);
    }

    mappings = ((JSONObject) mappings.values().iterator().next()).getJSONObject("mappings");
    mappings = ((JSONObject) mappings.values().iterator().next()).getJSONObject("properties");
    this.columns = Maps.newLinkedHashMap(); // 有序的map
    for (String column : columns) {
        JSONObject mapping = mappings.getJSONObject(column);
        this.columns.put(column, DataType.parse(mapping.getString("type")));
    }
}
 
Example 3
Source File: PptxReaderImpl.java    From tephra with MIT License 6 votes vote down vote up
private void parseBackground(ReaderContext readerContext, XSLFBackground xslfBackground, JSONObject slide,
                             Map<Integer, String> layout) {
    JSONObject background = layout.containsKey(0) ? json.toObject(layout.get(0)) : new JSONObject();
    parser.parseShape(readerContext, xslfBackground, background);
    background.remove("anchor");

    if (xslfBackground.getFillColor() != null)
        background.put("color", officeHelper.colorToJson(xslfBackground.getFillColor()));

    if (background.isEmpty())
        return;

    if (readerContext.isLayout())
        layout.put(0, json.toString(background));
    else
        slide.put("background", background);
}
 
Example 4
Source File: SmsTemplateServiceImpl.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
private static String getParamByContent(String content, String regEx) {
    //编译正则表达式
    Pattern pattern = Pattern.compile(regEx);
    //忽略大小写的写法:
    Matcher matcher = pattern.matcher(content);

    // 查找字符串中是否有匹配正则表达式的字符/字符串//有序, 目的是为了兼容 腾讯云参数
    JSONObject obj = new JSONObject(true);
    while (matcher.find()) {
        String key = matcher.group(1);
        obj.put(key, "");
    }
    if (obj.isEmpty()) {
        throw BizException.wrap("模板内容解析失败,请认真详细内容格式");
    }

    return obj.toString();
}
 
Example 5
Source File: AclUtils.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public static RPCHook getAclRPCHook(String fileName) {
    JSONObject yamlDataObject = null;
    try {
        yamlDataObject = AclUtils.getYamlDataObject(fileName,
            JSONObject.class);
    } catch (Exception e) {
        log.error("Convert yaml file to data object error, ", e);
        return null;
    }

    if (yamlDataObject == null || yamlDataObject.isEmpty()) {
        log.warn("Cannot find conf file :{}, acl isn't be enabled.", fileName);
        return null;
    }

    String accessKey = yamlDataObject.getString(AclConstants.CONFIG_ACCESS_KEY);
    String secretKey = yamlDataObject.getString(AclConstants.CONFIG_SECRET_KEY);

    if (StringUtils.isBlank(accessKey) || StringUtils.isBlank(secretKey)) {
        log.warn("AccessKey or secretKey is blank, the acl is not enabled.");

        return null;
    }
    return new AclClientRPCHook(new SessionCredentials(accessKey, secretKey));
}
 
Example 6
Source File: ChartData.java    From rebuild with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取过滤 SQL
 * 
 * @return
 */
protected String getFilterSql() {
	String previewFilter = StringUtils.EMPTY;
	// 限制预览数据量
	if (isFromPreview() && getSourceEntity().containsField(EntityHelper.AutoId)) {
		String maxAidSql = String.format("select max(%s) from %s", EntityHelper.AutoId, getSourceEntity().getName());
		Object[] o = Application.createQueryNoFilter(maxAidSql).unique();
		long maxAid = ObjectUtils.toLong(o[0]);
		if (maxAid > 5000) {
			previewFilter = String.format("(%s >= %d) and ", EntityHelper.AutoId, Math.max(maxAid - 2000, 0));
		}
	}
	
	JSONObject filterExp = config.getJSONObject("filter");
	if (filterExp == null || filterExp.isEmpty()) {
		return previewFilter + "(1=1)";
	}
	
	AdvFilterParser filterParser = new AdvFilterParser(filterExp);
	String sqlWhere = filterParser.toSqlWhere();
	if (sqlWhere != null) {
		sqlWhere = previewFilter + sqlWhere;
	}
	return StringUtils.defaultIfBlank(sqlWhere, "(1=1)");
}
 
Example 7
Source File: AbstractServiceApiPlusListener.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 调用下游服务
 *
 * @param context
 * @return
 */
public ResponseEntity<String> callOrderService(DataFlowContext context, JSONObject paramIn) {

    context.getRequestCurrentHeaders().put(CommonConstant.HTTP_ORDER_TYPE_CD, "D");
    ResponseEntity responseEntity = null;
    if (paramIn == null || paramIn.isEmpty()) {
        paramIn = context.getReqJson();
    }
    String serviceUrl = ORDER_SERVICE_URL;
    HttpEntity<String> httpEntity = null;
    HttpHeaders header = new HttpHeaders();
    for (String key : context.getRequestCurrentHeaders().keySet()) {
        if (CommonConstant.HTTP_SERVICE.toLowerCase().equals(key.toLowerCase())) {
            continue;
        }
        header.add(key, context.getRequestCurrentHeaders().get(key));
    }
    try {
        httpEntity = new HttpEntity<String>(JSONObject.toJSONString(paramIn), header);
        responseEntity = restTemplate.exchange(serviceUrl, HttpMethod.POST, httpEntity, String.class);
    } catch (HttpStatusCodeException e) { //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常,需要重新封装一下
        responseEntity = new ResponseEntity<String>(e.getResponseBodyAsString(), e.getStatusCode());
    }
    return responseEntity;
}
 
Example 8
Source File: TableImpl.java    From tephra with MIT License 6 votes vote down vote up
private void parseBorder(XSLFTableCell xslfTableCell, JSONObject cell) {
    JSONObject border = new JSONObject();
    for (TableCell.BorderEdge edge : TableCell.BorderEdge.values()) {
        Double width = xslfTableCell.getBorderWidth(edge);
        if (width == null || width <= 0.0D)
            continue;

        JSONObject object = new JSONObject();
        object.put("width", width);
        object.put("color", officeHelper.colorToJson(xslfTableCell.getBorderColor(edge)));
        object.put("style", xslfTableCell.getBorderStyle(edge));
        border.put(edge.name(), object);
        System.out.println("11:" + xslfTableCell.getBorderStyle(edge));
        System.out.println("22:" + xslfTableCell.getBorderStyle(edge).getLineCap());
        System.out.println("22:" + xslfTableCell.getBorderStyle(edge).getLineCap());
        System.out.println("33:" + xslfTableCell.getBorderStyle(edge).getLineDash());
        System.out.println("44:" + xslfTableCell.getBorderStyle(edge).getLineCompound());
    }

    if (!border.isEmpty())
        cell.put("border", border);
}
 
Example 9
Source File: LocalFileDataConfigSource.java    From litchi with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(Litchi litchi) {
    JSONObject config = litchi.config(Constants.Component.DATA_CONFIG);
    if (config == null) {
        LOGGER.error("'dataConfig' node not found in litchi.json");
        return;
    }

    String dataSourceKey = config.getString("dataSource");
    JSONObject fileConfig = config.getJSONObject(dataSourceKey);

    if (fileConfig == null || fileConfig.isEmpty()) {
        LOGGER.error("'dataConfig' node is null. check litchi.json please.");
        return;
    }

    this.filePath = FileUtils.combine(litchi.getRootConfigPath(), fileConfig.getString("filePath"));

    this.reloadFlushTime = fileConfig.getInteger("reloadFlushTime");

    this.litchi = litchi;

    this.fileDir = new File(this.filePath);
    if (!this.fileDir.isDirectory()) {
        LOGGER.error("current data config path is not directory: path:{}", this.filePath);
        return;
    }

    try {
        reloadMonitor = new FileAlterationMonitor(this.reloadFlushTime, createFileObserver());
        reloadMonitor.start();

        LOGGER.info("local data config flush monitor is start!");
        LOGGER.info("path:{}, flushTime:{}ms", this.filePath, this.reloadFlushTime);
    } catch (Exception ex) {
        LOGGER.error("{}", ex);
    }
}
 
Example 10
Source File: FullPullService.java    From DBus with Apache License 2.0 5 votes vote down vote up
private String getMonitorNodePath(String dsName, JSONObject reqJson) {
    String monitorRoot = Constants.FULL_PULL_MONITOR_ROOT;
    String dbNameSpace = buildSlashedNameSpace(dsName, reqJson);
    String monitorNodePath;
    JSONObject projectJson = reqJson.getJSONObject("project");
    if (projectJson != null && !projectJson.isEmpty()) {
        int projectId = projectJson.getIntValue("id");
        String projectName = projectJson.getString("name");
        monitorNodePath = String.format("%s/%s/%s_%s/%s", monitorRoot, "Projects", projectName, projectId, dbNameSpace);
    } else {
        monitorNodePath = buildZkPath(monitorRoot, dbNameSpace);
    }
    return monitorNodePath;
}
 
Example 11
Source File: MultiTenancyHelper.java    From DBus with Apache License 2.0 5 votes vote down vote up
public static boolean isMultiTenancy(JSONObject reqJson) {
    JSONObject projectJson = reqJson.getJSONObject(FullPullConstants.REQ_PROJECT);
    if (projectJson != null && !projectJson.isEmpty()) {
        return true;
    }
    return false;
}
 
Example 12
Source File: MultiTenancyHelper.java    From DBus with Apache License 2.0 5 votes vote down vote up
public static boolean isMultiTenancy(String reqString) {
    JSONObject reqJson = JSONObject.parseObject(reqString);
    JSONObject projectJson = reqJson.getJSONObject(FullPullConstants.REQ_PROJECT);
    if (projectJson != null && !projectJson.isEmpty()) {
        return true;
    }
    return false;
}
 
Example 13
Source File: ZKMonitorHelper.java    From DBus with Apache License 2.0 5 votes vote down vote up
public static String getCurrentPendingZKNodePath(String monitorRoot, String dsName, JSONObject reqJson) {
    JSONObject projectJson = reqJson.getJSONObject(FullPullConstants.REQ_PROJECT);
    String pendingZKNodePath;
    if (projectJson != null && !projectJson.isEmpty()) {
        String projectName = projectJson.getString(FullPullConstants.REQ_PROJECT_NAME);
        String projectId = projectJson.getString(FullPullConstants.REQ_PROJECT_ID);
        pendingZKNodePath = FullPullConstants.FULL_PULL_PROJECTS_MONITOR_ROOT + "/" + projectName + "_" + projectId + "/" + dsName;
    } else {
        pendingZKNodePath = monitorRoot + "/" + dsName;
    }
    return pendingZKNodePath;
}
 
Example 14
Source File: MetaSchemaGenerator.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param field
 * @return
 */
private JSON performField(Field field) {
	final JSONObject schemaField = new JSONObject(true);
	final EasyMeta easyField = EasyMeta.valueOf(field);
	final DisplayType dt = easyField.getDisplayType();
	
	schemaField.put("field", easyField.getName());
	schemaField.put("fieldLabel", easyField.getLabel());
	schemaField.put("displayType", dt.name());
	if (easyField.getComments() != null) {
		schemaField.put("comments", easyField.getComments());
	}
	schemaField.put("nullable", field.isNullable());
	schemaField.put("updatable", field.isUpdatable());
	schemaField.put("repeatable", field.isRepeatable());
	Object defaultVal = field.getDefaultValue();
	if (defaultVal != null && StringUtils.isNotBlank((String) defaultVal)) {
		schemaField.put("defaultValue", defaultVal);
	}
	
	if (dt == DisplayType.REFERENCE) {
		schemaField.put("refEntity", field.getReferenceEntity().getName());
		schemaField.put("refEntityLabel", EasyMeta.getLabel(field.getReferenceEntity()));
	} else if (dt == DisplayType.PICKLIST) {
		schemaField.put("items", performPickList(field));
	}
	
	JSONObject extConfig = easyField.getExtraAttrs(true);
	if (!extConfig.isEmpty()) {
		schemaField.put("extConfig", extConfig);
	}
	
	return schemaField;
}
 
Example 15
Source File: FlipImpl.java    From tephra with MIT License 5 votes vote down vote up
@Override
public void parseShape(ReaderContext readerContext, XSLFSimpleShape xslfSimpleShape, JSONObject shape) {
    JSONObject flip = new JSONObject();
    CTSphereCoords ctSphereCoords = getScene3D(xslfSimpleShape);
    if (xslfSimpleShape.getFlipHorizontal() || (ctSphereCoords != null && ctSphereCoords.getLat() == 10800000))
        flip.put("horizontal", true);
    if (xslfSimpleShape.getFlipVertical() || (ctSphereCoords != null && ctSphereCoords.getLon() == 10800000))
        flip.put("vertical", true);
    if (!flip.isEmpty())
        shape.put("flip", flip);
}
 
Example 16
Source File: WXDomStatement.java    From weex-uikit with MIT License 5 votes vote down vote up
/**
 * Update styles according to the given style. Then creating a
 * command object for updating corresponding view and put the command object in the queue.
 * @param ref Reference of the dom.
 * @param style the new style. This style is only a part of the full style, and will be merged
 *              into styles
 * @param byPesudo updateStyle by pesduo class
 * @see #updateAttrs(String, JSONObject)
 */
void updateStyle(String ref, JSONObject style, boolean byPesudo) {
  if (mDestroy || style == null) {
    return;
  }
  WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(mInstanceId);
  WXDomObject domObject = mRegistry.get(ref);
  if (domObject == null) {
    if (instance != null) {
      instance.commitUTStab(IWXUserTrackAdapter.DOM_MODULE, WXErrorCode.WX_ERR_DOM_UPDATESTYLE);
    }
    return;
  }

  Map<String, Object> animationMap= new ArrayMap<>(2);
  animationMap.put(WXDomObject.TRANSFORM, style.remove(WXDomObject.TRANSFORM));
  animationMap.put(WXDomObject.TRANSFORM_ORIGIN, style.remove(WXDomObject.TRANSFORM_ORIGIN));
  animations.add(new Pair<>(ref, animationMap));

  if(!style.isEmpty()){
    domObject.updateStyle(style, byPesudo);
    domObject.traverseTree(ApplyStyleConsumer.getInstance());
    updateStyle(domObject, style);
  }
  mDirty = true;

  if (instance != null) {
    instance.commitUTStab(IWXUserTrackAdapter.DOM_MODULE, WXErrorCode.WX_SUCCESS);
  }
}
 
Example 17
Source File: DbDelete.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
* 删除-安全的
   * <p>数据删除前会先进行条数确认
   * 
   * @param tableName	表名
   * @param id     	主键id
   */
  public void deleteSafe(String tableName, Long id) {
// 1. 确认数据
  	JSONObject data = getById(tableName, id);
if (data == null || data.isEmpty()) {
	throw new DbException("执行单行删除命令失败,数据结构异常,可能原因是:数据不存在或存在多条数据", true);
}

// 2. 删除数据
delete(tableName, id);
  }
 
Example 18
Source File: PptxReaderImpl.java    From tephra with MIT License 4 votes vote down vote up
private void add(JSONArray shapes, JSONObject shape) {
    if (shape.isEmpty() || (shape.size() == 1 && shape.containsKey("anchor")))
        return;

    shapes.add(shape);
}
 
Example 19
Source File: FieldAggregation.java    From rebuild with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void execute(OperatingContext operatingContext) throws TriggerException {
	Integer depth = TRIGGER_CHAIN_DEPTH.get();
	if (depth == null) {
		depth = 1;
	}
	if (depth > maxTriggerDepth) {
		throw new TriggerException("Too many trigger-chain with triggers : " + depth);
	}
	
	this.prepare(operatingContext);
	if (this.targetRecordId == null) {  // 无目标记录
		return;
	}
	
	// 如果当前用户对目标记录无修改权限
	if (!allowNoPermissionUpdate
               && !Application.getSecurityManager().allow(operatingContext.getOperator(), targetRecordId, BizzPermission.UPDATE)) {
	    LOG.warn("No privileges to update record of target: " + this.targetRecordId);
	    return;
	}

	// 聚合数据过滤
       JSONObject dataFilter = ((JSONObject) context.getActionContent()).getJSONObject("dataFilter");
	String dataFilterSql = null;
	if (dataFilter != null && !dataFilter.isEmpty()) {
           dataFilterSql = new AdvFilterParser(dataFilter).toSqlWhere();
       }

       Record targetRecord = EntityHelper.forUpdate(targetRecordId, UserService.SYSTEM_USER, false);
	buildTargetRecord(targetRecord, dataFilterSql);

	// 不含 ID
	if (targetRecord.getAvailableFields().size() > 1) {
		if (allowNoPermissionUpdate) {
			PrivilegesGuardInterceptor.setNoPermissionPassOnce(targetRecordId);
		}

		// 会关联触发下一触发器(如有)
		TRIGGER_CHAIN_DEPTH.set(depth + 1);
		Application.getEntityService(targetEntity.getEntityCode()).update(targetRecord);
	}
}
 
Example 20
Source File: ElasticSearchUtils.java    From sagacity-sqltoy with Apache License 2.0 4 votes vote down vote up
/**
 * @todo 执行实际查询处理
 * @param sqlToyContext
 * @param sqlToyConfig
 * @param sql
 * @param resultClass
 * @return
 * @throws Exception
 */
public static DataSetResult executeQuery(SqlToyContext sqlToyContext, SqlToyConfig sqlToyConfig, String sql,
		Class resultClass) throws Exception {
	NoSqlConfigModel noSqlModel = sqlToyConfig.getNoSqlConfigModel();
	ElasticEndpoint esConfig = sqlToyContext.getElasticEndpoint(noSqlModel.getEndpoint());
	// 原生sql支持(7.5.1 还未支持分页)
	boolean nativeSql = (esConfig.isNativeSql() && noSqlModel.isSqlMode());
	// 执行请求并返回json结果
	JSONObject json = HttpClientUtils.doPost(sqlToyContext, noSqlModel, esConfig, sql);
	if (json == null || json.isEmpty()) {
		return new DataSetResult();
	}
	String[] fields = noSqlModel.getFields();
	if (fields == null) {
		if (json.containsKey("columns")) {
			JSONArray cols = json.getJSONArray("columns");
			fields = new String[cols.size()];
			int index = 0;
			for (Object col : cols) {
				fields[index] = ((JSONObject) col).getString("name");
				index++;
			}
		} else if (resultClass != null) {
			Class superClass = resultClass.getSuperclass();
			if (!resultClass.equals(ArrayList.class) && !resultClass.equals(List.class)
					&& !resultClass.equals(Collection.class) && !resultClass.equals(HashMap.class)
					&& !resultClass.equals(ConcurrentHashMap.class) && !resultClass.equals(Map.class)
					&& !HashMap.class.equals(superClass) && !Map.class.equals(superClass)
					&& !LinkedHashMap.class.equals(superClass) && !ConcurrentHashMap.class.equals(superClass)) {
				fields = BeanUtil.matchSetMethodNames(resultClass);
			}
		}
	}

	DataSetResult resultSet = null;
	if (nativeSql) {
		resultSet = extractSqlFieldValue(sqlToyContext, sqlToyConfig, json, fields);
	} else {
		resultSet = extractFieldValue(sqlToyContext, sqlToyConfig, json, fields);
	}
	MongoElasticUtils.processTranslate(sqlToyContext, sqlToyConfig, resultSet.getRows(), resultSet.getLabelNames());

	// 不支持指定查询集合的行列转换
	ResultUtils.calculate(sqlToyConfig, resultSet, null);

	// 将结果数据映射到具体对象类型中
	resultSet.setRows(ResultUtils.wrapQueryResult(resultSet.getRows(),
			StringUtil.humpFieldNames(resultSet.getLabelNames()), resultClass));
	return resultSet;
}