Java Code Examples for com.ctrip.framework.apollo.core.utils.StringUtils#isEmpty()

The following examples show how to use com.ctrip.framework.apollo.core.utils.StringUtils#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: ParameterRequestWrapper.java    From java-tutorial with MIT License 6 votes vote down vote up
/**
 * 重写getInputStream方法  post类型的请求参数必须通过流才能获取到值
 *
 * @return
 * @throws IOException
 */
@Override
public ServletInputStream getInputStream() throws IOException {
    //非json类型,直接返回
    if (!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
        return super.getInputStream();
    }
    //为空直接返回
    String json = IOUtil.streamToString(super.getInputStream());
    if (StringUtils.isEmpty(json)) {
        return super.getInputStream();
    }
    log.info("转换前参数:{}", JSONUtil.toJsonStr(json));
    Map<String, Object> map = IOUtil.jsonToMap(json, true);
    log.info("转换后参数:{}", JSONUtil.toJsonStr(map));
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(JSONUtil.toJsonStr(map).getBytes("utf-8"));
    return new ParamsServletInputStream(byteArrayInputStream);
}
 
Example 2
Source File: AppNamespaceController.java    From apollo with Apache License 2.0 6 votes vote down vote up
@PostMapping("/apps/{appId}/appnamespaces")
public AppNamespaceDTO create(@RequestBody AppNamespaceDTO appNamespace,
                              @RequestParam(defaultValue = "false") boolean silentCreation) {

  AppNamespace entity = BeanUtils.transform(AppNamespace.class, appNamespace);
  AppNamespace managedEntity = appNamespaceService.findOne(entity.getAppId(), entity.getName());

  if (managedEntity == null) {
    if (StringUtils.isEmpty(entity.getFormat())){
      entity.setFormat(ConfigFileFormat.Properties.getValue());
    }

    entity = appNamespaceService.createAppNamespace(entity);
  } else if (silentCreation) {
    appNamespaceService.createNamespaceForAppNamespaceInAllCluster(appNamespace.getAppId(), appNamespace.getName(),
        appNamespace.getDataChangeCreatedBy());

    entity = managedEntity;
  } else {
    throw new BadRequestException("app namespaces already exist.");
  }

  return BeanUtils.transform(AppNamespaceDTO.class, entity);
}
 
Example 3
Source File: ItemsComparator.java    From apollo with Apache License 2.0 6 votes vote down vote up
private List<ItemDTO> filterBlankAndCommentItem(List<ItemDTO> items){

    List<ItemDTO> result = new LinkedList<>();

    if (CollectionUtils.isEmpty(items)){
      return result;
    }

    for (ItemDTO item: items){
      if (!StringUtils.isEmpty(item.getKey())){
        result.add(item);
      }
    }

    return result;
  }
 
Example 4
Source File: FileTextResolver.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Override
public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) {
  ItemChangeSets changeSets = new ItemChangeSets();
  if (CollectionUtils.isEmpty(baseItems) && StringUtils.isEmpty(configText)) {
    return changeSets;
  }
  if (CollectionUtils.isEmpty(baseItems)) {
    changeSets.addCreateItem(createItem(namespaceId, 0, configText));
  } else {
    ItemDTO beforeItem = baseItems.get(0);
    if (!configText.equals(beforeItem.getValue())) {//update
      changeSets.addUpdateItem(createItem(namespaceId, beforeItem.getId(), configText));
    }
  }

  return changeSets;
}
 
Example 5
Source File: SpringSecurityUserService.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Override
public List<UserInfo> searchUsers(String keyword, int offset, int limit) {
  List<UserPO> users;
  if (StringUtils.isEmpty(keyword)) {
    users = userRepository.findFirst20ByEnabled(1);
  } else {
    users = userRepository.findByUsernameLikeAndEnabled("%" + keyword + "%", 1);
  }

  List<UserInfo> result = Lists.newArrayList();
  if (CollectionUtils.isEmpty(users)) {
    return result;
  }

  result.addAll(users.stream().map(UserPO::toUserInfo).collect(Collectors.toList()));

  return result;
}
 
Example 6
Source File: ReleaseService.java    From apollo with Apache License 2.0 6 votes vote down vote up
public ReleaseDTO publish(NamespaceReleaseModel model) {
  Env env = model.getEnv();
  boolean isEmergencyPublish = model.isEmergencyPublish();
  String appId = model.getAppId();
  String clusterName = model.getClusterName();
  String namespaceName = model.getNamespaceName();
  String releaseBy = StringUtils.isEmpty(model.getReleasedBy()) ?
                     userInfoHolder.getUser().getUserId() : model.getReleasedBy();

  ReleaseDTO releaseDTO = releaseAPI.createRelease(appId, env, clusterName, namespaceName,
                                                   model.getReleaseTitle(), model.getReleaseComment(),
                                                   releaseBy, isEmergencyPublish);

  Tracer.logEvent(TracerEventType.RELEASE_NAMESPACE,
                  String.format("%s+%s+%s+%s", appId, env, clusterName, namespaceName));

  return releaseDTO;
}
 
Example 7
Source File: EncryptUtil.java    From apollo-use-cases with Apache License 2.0 5 votes vote down vote up
/**
 * 替换制表符、空格、换行符
 *
 * @param str
 * @return
 */
private static String replaceBlank(String str) {
    String dest = "";
    if (!StringUtils.isEmpty(str)) {
        Matcher matcher = BLANK_PATTERN.matcher(str);
        dest = matcher.replaceAll("");
    }
    return dest;
}
 
Example 8
Source File: NamespaceUnlockAspect.java    From apollo with Apache License 2.0 5 votes vote down vote up
private boolean hasNormalItems(List<Item> items) {
  for (Item item : items) {
    if (!StringUtils.isEmpty(item.getKey())) {
      return true;
    }
  }

  return false;
}
 
Example 9
Source File: ItemController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)")
@PostMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items")
public OpenItemDTO createItem(@PathVariable String appId, @PathVariable String env,
                              @PathVariable String clusterName, @PathVariable String namespaceName,
                              @RequestBody OpenItemDTO item, HttpServletRequest request) {

  RequestPrecondition.checkArguments(
      !StringUtils.isContainEmpty(item.getKey(), item.getDataChangeCreatedBy()),
      "key and dataChangeCreatedBy should not be null or empty");

  if (userService.findByUserId(item.getDataChangeCreatedBy()) == null) {
    throw new BadRequestException("User " + item.getDataChangeCreatedBy() + " doesn't exist!");
  }

  if(!StringUtils.isEmpty(item.getComment()) && item.getComment().length() > 64){
    throw new BadRequestException("Comment length should not exceed 64 characters");
  }

  ItemDTO toCreate = OpenApiBeanUtils.transformToItemDTO(item);

  //protect
  toCreate.setLineNum(0);
  toCreate.setId(0);
  toCreate.setDataChangeLastModifiedBy(toCreate.getDataChangeCreatedBy());
  toCreate.setDataChangeLastModifiedTime(null);
  toCreate.setDataChangeCreatedTime(null);

  ItemDTO createdItem = itemService.createItem(appId, Env.fromString(env),
      clusterName, namespaceName, toCreate);
  return OpenApiBeanUtils.transformFromItemDTO(createdItem);
}
 
Example 10
Source File: NamespaceService.java    From apollo with Apache License 2.0 5 votes vote down vote up
private ItemBO transformItem2BO(ItemDTO itemDTO, Map<String, String> releaseItems) {
  String key = itemDTO.getKey();
  ItemBO itemBO = new ItemBO();
  itemBO.setItem(itemDTO);
  String newValue = itemDTO.getValue();
  String oldValue = releaseItems.get(key);
  //new item or modified
  if (!StringUtils.isEmpty(key) && (oldValue == null || !newValue.equals(oldValue))) {
    itemBO.setModified(true);
    itemBO.setOldValue(oldValue == null ? "" : oldValue);
    itemBO.setNewValue(newValue);
  }
  return itemBO;
}
 
Example 11
Source File: NamespaceService.java    From apollo with Apache License 2.0 5 votes vote down vote up
public NamespaceDTO createNamespace(Env env, NamespaceDTO namespace) {
  if (StringUtils.isEmpty(namespace.getDataChangeCreatedBy())) {
    namespace.setDataChangeCreatedBy(userInfoHolder.getUser().getUserId());
  }
  namespace.setDataChangeLastModifiedBy(userInfoHolder.getUser().getUserId());
  NamespaceDTO createdNamespace = namespaceAPI.createNamespace(env, namespace);

  Tracer.logEvent(TracerEventType.CREATE_NAMESPACE,
      String.format("%s+%s+%s+%s", namespace.getAppId(), env, namespace.getClusterName(),
          namespace.getNamespaceName()));
  return createdNamespace;
}
 
Example 12
Source File: ItemService.java    From apollo with Apache License 2.0 5 votes vote down vote up
private boolean isModified(String sourceValue, String targetValue, String sourceComment, String targetComment) {

    if (!sourceValue.equals(targetValue)) {
      return true;
    }

    if (sourceComment == null) {
      return !StringUtils.isEmpty(targetComment);
    }
    if (targetComment != null) {
      return !sourceComment.equals(targetComment);
    }
    return false;
  }
 
Example 13
Source File: ReleaseService.java    From apollo with Apache License 2.0 5 votes vote down vote up
private Map<String, String> getNamespaceItems(Namespace namespace) {
  List<Item> items = itemService.findItemsWithOrdered(namespace.getId());
  Map<String, String> configurations = new LinkedHashMap<>();
  for (Item item : items) {
    if (StringUtils.isEmpty(item.getKey())) {
      continue;
    }
    configurations.put(item.getKey(), item.getValue());
  }

  return configurations;
}
 
Example 14
Source File: ItemService.java    From apollo with Apache License 2.0 5 votes vote down vote up
private boolean checkItemValueLength(long namespaceId, String value) {
  int limit = getItemValueLengthLimit(namespaceId);
  if (!StringUtils.isEmpty(value) && value.length() > limit) {
    throw new BadRequestException("value too long. length limit:" + limit);
  }
  return true;
}
 
Example 15
Source File: AppNamespaceService.java    From apollo with Apache License 2.0 4 votes vote down vote up
@Transactional
public AppNamespace createAppNamespaceInLocal(AppNamespace appNamespace, boolean appendNamespacePrefix) {
  String appId = appNamespace.getAppId();

  //add app org id as prefix
  App app = appService.load(appId);
  if (app == null) {
    throw new BadRequestException("App not exist. AppId = " + appId);
  }

  // public namespaces only allow properties format
  if (appNamespace.isPublic()) {
    appNamespace.setFormat(ConfigFileFormat.Properties.getValue());
  }

  StringBuilder appNamespaceName = new StringBuilder();
  //add prefix postfix
  appNamespaceName
      .append(appNamespace.isPublic() && appendNamespacePrefix ? app.getOrgId() + "." : "")
      .append(appNamespace.getName())
      .append(appNamespace.formatAsEnum() == ConfigFileFormat.Properties ? "" : "." + appNamespace.getFormat());
  appNamespace.setName(appNamespaceName.toString());

  if (appNamespace.getComment() == null) {
    appNamespace.setComment("");
  }

  if (!ConfigFileFormat.isValidFormat(appNamespace.getFormat())) {
   throw new BadRequestException("Invalid namespace format. format must be properties、json、yaml、yml、xml");
  }

  String operator = appNamespace.getDataChangeCreatedBy();
  if (StringUtils.isEmpty(operator)) {
    operator = userInfoHolder.getUser().getUserId();
    appNamespace.setDataChangeCreatedBy(operator);
  }

  appNamespace.setDataChangeLastModifiedBy(operator);

  // globally uniqueness check for public app namespace
  if (appNamespace.isPublic()) {
    checkAppNamespaceGlobalUniqueness(appNamespace);
  } else {
    // check private app namespace
    if (appNamespaceRepository.findByAppIdAndName(appNamespace.getAppId(), appNamespace.getName()) != null) {
      throw new BadRequestException("Private AppNamespace " + appNamespace.getName() + " already exists!");
    }
    // should not have the same with public app namespace
    checkPublicAppNamespaceGlobalUniqueness(appNamespace);
  }

  AppNamespace createdAppNamespace = appNamespaceRepository.save(appNamespace);

  roleInitializationService.initNamespaceRoles(appNamespace.getAppId(), appNamespace.getName(), operator);
  roleInitializationService.initNamespaceEnvRoles(appNamespace.getAppId(), appNamespace.getName(), operator);

  return createdAppNamespace;
}
 
Example 16
Source File: ItemService.java    From apollo with Apache License 2.0 4 votes vote down vote up
private boolean checkItemKeyLength(String key) {
  if (!StringUtils.isEmpty(key) && key.length() > bizConfig.itemKeyLengthLimit()) {
    throw new BadRequestException("key too long. length limit:" + bizConfig.itemKeyLengthLimit());
  }
  return true;
}
 
Example 17
Source File: ItemController.java    From apollo with Apache License 2.0 4 votes vote down vote up
@PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)")
@PutMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key:.+}")
public void updateItem(@PathVariable String appId, @PathVariable String env,
                       @PathVariable String clusterName, @PathVariable String namespaceName,
                       @PathVariable String key, @RequestBody OpenItemDTO item,
                       @RequestParam(defaultValue = "false") boolean createIfNotExists, HttpServletRequest request) {

  RequestPrecondition.checkArguments(item != null, "item payload can not be empty");

  RequestPrecondition.checkArguments(
      !StringUtils.isContainEmpty(item.getKey(), item.getDataChangeLastModifiedBy()),
      "key and dataChangeLastModifiedBy can not be empty");

  RequestPrecondition.checkArguments(item.getKey().equals(key), "Key in path and payload is not consistent");

  if (userService.findByUserId(item.getDataChangeLastModifiedBy()) == null) {
    throw new BadRequestException("user(dataChangeLastModifiedBy) not exists");
  }

  if(!StringUtils.isEmpty(item.getComment()) && item.getComment().length() > 64){
    throw new BadRequestException("Comment length should not exceed 64 characters");
  }

  try {
    ItemDTO toUpdateItem = itemService
        .loadItem(Env.fromString(env), appId, clusterName, namespaceName, item.getKey());
    //protect. only value,comment,lastModifiedBy can be modified
    toUpdateItem.setComment(item.getComment());
    toUpdateItem.setValue(item.getValue());
    toUpdateItem.setDataChangeLastModifiedBy(item.getDataChangeLastModifiedBy());

    itemService.updateItem(appId, Env.fromString(env), clusterName, namespaceName, toUpdateItem);
  } catch (Throwable ex) {
    if (ex instanceof HttpStatusCodeException) {
      // check createIfNotExists
      if (((HttpStatusCodeException) ex).getStatusCode().equals(HttpStatus.NOT_FOUND) && createIfNotExists) {
        createItem(appId, env, clusterName, namespaceName, item, request);
        return;
      }
    }
    throw ex;
  }
}
 
Example 18
Source File: InputValidator.java    From apollo with Apache License 2.0 4 votes vote down vote up
public static boolean isValidClusterNamespace(String name) {
  if (StringUtils.isEmpty(name)){
    return false;
  }
  return CLUSTER_NAMESPACE_PATTERN.matcher(name).matches();
}
 
Example 19
Source File: ConfigChangeContentBuilder.java    From apollo with Apache License 2.0 4 votes vote down vote up
public ConfigChangeContentBuilder createItem(Item item) {
  if (!StringUtils.isEmpty(item.getKey())){
    createItems.add(cloneItem(item));
  }
  return this;
}
 
Example 20
Source File: InputValidator.java    From apollo with Apache License 2.0 4 votes vote down vote up
public static boolean isValidAppNamespace(String name){
  if (StringUtils.isEmpty(name)){
    return false;
  }
  return APP_NAMESPACE_PATTERN.matcher(name).matches();
}