Java Code Examples for com.ctrip.framework.apollo.core.utils.StringUtils

The following examples show how to use com.ctrip.framework.apollo.core.utils.StringUtils. These examples are extracted from open source projects. 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 Project: apollo   Source File: AuthConfiguration.java    License: Apache License 2.0 7 votes vote down vote up
@Bean
public FilterBasedLdapUserSearch userSearch() {
  if (ldapExtendProperties.getGroup() == null || StringUtils
      .isBlank(ldapExtendProperties.getGroup().getGroupSearch())) {
    FilterBasedLdapUserSearch filterBasedLdapUserSearch = new FilterBasedLdapUserSearch("",
        ldapProperties.getSearchFilter(), ldapContextSource);
    filterBasedLdapUserSearch.setSearchSubtree(true);
    return filterBasedLdapUserSearch;
  }

  FilterLdapByGroupUserSearch filterLdapByGroupUserSearch = new FilterLdapByGroupUserSearch(
      ldapProperties.getBase(), ldapProperties.getSearchFilter(), ldapExtendProperties.getGroup().getGroupBase(),
      ldapContextSource, ldapExtendProperties.getGroup().getGroupSearch(),
      ldapExtendProperties.getMapping().getRdnKey(),
      ldapExtendProperties.getGroup().getGroupMembership(),ldapExtendProperties.getMapping().getLoginId());
  filterLdapByGroupUserSearch.setSearchSubtree(true);
  return filterLdapByGroupUserSearch;
}
 
Example 2
Source Project: java-tutorial   Source File: ParameterRequestWrapper.java    License: 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 3
Source Project: apollo   Source File: EnvUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Env transformEnv(String envName) {
  if (StringUtils.isBlank(envName)) {
    return Env.UNKNOWN;
  }
  switch (envName.trim().toUpperCase()) {
    case "LPT":
      return Env.LPT;
    case "FAT":
    case "FWS":
      return Env.FAT;
    case "UAT":
      return Env.UAT;
    case "PRO":
    case "PROD": //just in case
      return Env.PRO;
    case "DEV":
      return Env.DEV;
    case "LOCAL":
      return Env.LOCAL;
    case "TOOLS":
      return Env.TOOLS;
    default:
      return Env.UNKNOWN;
  }
}
 
Example 4
Source Project: apollo   Source File: ItemController.java    License: Apache License 2.0 6 votes vote down vote up
private void doSyntaxCheck(NamespaceTextModel model) {
  if (StringUtils.isBlank(model.getConfigText())) {
    return;
  }

  // only support yaml syntax check
  if (model.getFormat() != ConfigFileFormat.YAML && model.getFormat() != ConfigFileFormat.YML) {
    return;
  }

  // use YamlPropertiesFactoryBean to check the yaml syntax
  YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
  yamlPropertiesFactoryBean.setResources(new ByteArrayResource(model.getConfigText().getBytes()));
  // this call converts yaml to properties and will throw exception if the conversion fails
  yamlPropertiesFactoryBean.getObject();
}
 
Example 5
Source Project: apollo   Source File: ConsumerController.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional
@PreAuthorize(value = "@permissionValidator.isSuperAdmin()")
@PostMapping(value = "/consumers")
public ConsumerToken createConsumer(@RequestBody Consumer consumer,
                                    @RequestParam(value = "expires", required = false)
                                    @DateTimeFormat(pattern = "yyyyMMddHHmmss") Date
                                        expires) {

  if (StringUtils.isContainEmpty(consumer.getAppId(), consumer.getName(),
                                 consumer.getOwnerName(), consumer.getOrgId())) {
    throw new BadRequestException("Params(appId、name、ownerName、orgId) can not be empty.");
  }

  Consumer createdConsumer = consumerService.createConsumer(consumer);

  if (Objects.isNull(expires)) {
    expires = DEFAULT_EXPIRES;
  }

  return consumerService.generateAndSaveConsumerToken(createdConsumer, expires);
}
 
Example 6
Source Project: apollo   Source File: SpringSecurityUserService.java    License: 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 7
Source Project: apollo   Source File: Env.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * add an environment
 * @param name
 * @return
 */
public static Env addEnvironment(String name) {
    if (StringUtils.isBlank(name)) {
        throw new RuntimeException("Cannot add a blank environment: " + "[" + name + "]");
    }

    name = getWellFormName(name);
    if(STRING_ENV_MAP.containsKey(name)) {
        // has been existed
        logger.debug("{} already exists.", name);
    } else {
        // not existed
        STRING_ENV_MAP.put(name, new Env(name));
    }
    return STRING_ENV_MAP.get(name);
}
 
Example 8
Source Project: apollo   Source File: ReleaseService.java    License: 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 9
Source Project: apollo   Source File: FileTextResolver.java    License: 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 10
Source Project: apollo   Source File: ItemsComparator.java    License: 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 11
Source Project: apollo   Source File: NamespaceBranchController.java    License: Apache License 2.0 6 votes vote down vote up
@PreAuthorize(value = "@consumerPermissionValidator.hasCreateNamespacePermission(#request, #appId)")
@PostMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches")
public OpenNamespaceDTO createBranch(@PathVariable String appId,
                                     @PathVariable String env,
                                     @PathVariable String clusterName,
                                     @PathVariable String namespaceName,
                                     @RequestParam("operator") String operator,
                                     HttpServletRequest request) {
    RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(operator),"operator can not be empty");

    if (userService.findByUserId(operator) == null) {
        throw new BadRequestException("operator " + operator + " not exists");
    }

    NamespaceDTO namespaceDTO = namespaceBranchService.createBranch(appId, Env.valueOf(env.toUpperCase()), clusterName, namespaceName, operator);
    if (namespaceDTO == null) {
        return null;
    }
    return BeanUtils.transform(OpenNamespaceDTO.class, namespaceDTO);
}
 
Example 12
Source Project: apollo   Source File: NamespaceBranchController.java    License: Apache License 2.0 6 votes vote down vote up
@PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)")
@PutMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/rules")
public void updateBranchRules(@PathVariable String appId, @PathVariable String env,
                              @PathVariable String clusterName, @PathVariable String namespaceName,
                              @PathVariable String branchName, @RequestBody OpenGrayReleaseRuleDTO rules,
                              @RequestParam("operator") String operator,
                              HttpServletRequest request) {
    RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(operator),"operator can not be empty");

    if (userService.findByUserId(operator) == null) {
        throw new BadRequestException("operator " + operator + " not exists");
    }

    rules.setAppId(appId);
    rules.setClusterName(clusterName);
    rules.setNamespaceName(namespaceName);
    rules.setBranchName(branchName);

    GrayReleaseRuleDTO grayReleaseRuleDTO = OpenApiBeanUtils.transformToGrayReleaseRuleDTO(rules);
    namespaceBranchService
            .updateBranchGrayRules(appId, Env.valueOf(env.toUpperCase()), clusterName, namespaceName, branchName, grayReleaseRuleDTO, operator);

}
 
Example 13
Source Project: apollo   Source File: ReleaseController.java    License: Apache License 2.0 6 votes vote down vote up
@PreAuthorize(value = "@consumerPermissionValidator.hasReleaseNamespacePermission(#request, #appId, #namespaceName, #env)")
@PostMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases")
public OpenReleaseDTO createRelease(@PathVariable String appId, @PathVariable String env,
                                    @PathVariable String clusterName,
                                    @PathVariable String namespaceName,
                                    @RequestBody NamespaceReleaseDTO model,
                                    HttpServletRequest request) {
  RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(model.getReleasedBy(), model
          .getReleaseTitle()),
      "Params(releaseTitle and releasedBy) can not be empty");

  if (userService.findByUserId(model.getReleasedBy()) == null) {
    throw new BadRequestException("user(releaseBy) not exists");
  }

  NamespaceReleaseModel releaseModel = BeanUtils.transform(NamespaceReleaseModel.class, model);

  releaseModel.setAppId(appId);
  releaseModel.setEnv(Env.fromString(env).toString());
  releaseModel.setClusterName(clusterName);
  releaseModel.setNamespaceName(namespaceName);

  return OpenApiBeanUtils.transformFromReleaseDTO(releaseService.publish(releaseModel));
}
 
Example 14
Source Project: apollo   Source File: ReleaseController.java    License: Apache License 2.0 6 votes vote down vote up
@PreAuthorize(value = "@consumerPermissionValidator.hasReleaseNamespacePermission(#request, #appId, #namespaceName, #env)")
@PostMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/merge")
public OpenReleaseDTO merge(@PathVariable String appId, @PathVariable String env,
                        @PathVariable String clusterName, @PathVariable String namespaceName,
                        @PathVariable String branchName, @RequestParam(value = "deleteBranch", defaultValue = "true") boolean deleteBranch,
                        @RequestBody NamespaceReleaseDTO model, HttpServletRequest request) {
    RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(model.getReleasedBy(), model
                    .getReleaseTitle()),
            "Params(releaseTitle and releasedBy) can not be empty");

    if (userService.findByUserId(model.getReleasedBy()) == null) {
        throw new BadRequestException("user(releaseBy) not exists");
    }

    ReleaseDTO mergedRelease = namespaceBranchService.merge(appId, Env.valueOf(env.toUpperCase()), clusterName, namespaceName, branchName,
            model.getReleaseTitle(), model.getReleaseComment(),
            model.isEmergencyPublish(), deleteBranch, model.getReleasedBy());

    return OpenApiBeanUtils.transformFromReleaseDTO(mergedRelease);
}
 
Example 15
Source Project: apollo   Source File: ReleaseController.java    License: Apache License 2.0 6 votes vote down vote up
@PreAuthorize(value = "@consumerPermissionValidator.hasReleaseNamespacePermission(#request, #appId, #namespaceName, #env)")
@PostMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/releases")
public OpenReleaseDTO createGrayRelease(@PathVariable String appId,
                                    @PathVariable String env, @PathVariable String clusterName,
                                    @PathVariable String namespaceName, @PathVariable String branchName,
                                    @RequestBody NamespaceReleaseDTO model,
                                    HttpServletRequest request) {
    RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(model.getReleasedBy(), model
                    .getReleaseTitle()),
            "Params(releaseTitle and releasedBy) can not be empty");

    if (userService.findByUserId(model.getReleasedBy()) == null) {
        throw new BadRequestException("user(releaseBy) not exists");
    }

    NamespaceReleaseModel releaseModel = BeanUtils.transform(NamespaceReleaseModel.class, model);

    releaseModel.setAppId(appId);
    releaseModel.setEnv(Env.fromString(env).toString());
    releaseModel.setClusterName(branchName);
    releaseModel.setNamespaceName(namespaceName);

    return OpenApiBeanUtils.transformFromReleaseDTO(releaseService.publish(releaseModel));
}
 
Example 16
Source Project: apollo   Source File: ReleaseController.java    License: Apache License 2.0 6 votes vote down vote up
@PreAuthorize(value = "@consumerPermissionValidator.hasReleaseNamespacePermission(#request, #appId, #namespaceName, #env)")
@PostMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/gray-del-releases")
public OpenReleaseDTO createGrayDelRelease(@PathVariable String appId,
                                           @PathVariable String env, @PathVariable String clusterName,
                                           @PathVariable String namespaceName, @PathVariable String branchName,
                                           @RequestBody NamespaceGrayDelReleaseDTO model,
                                           HttpServletRequest request) {
    RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(model.getReleasedBy(), model
                    .getReleaseTitle()),
            "Params(releaseTitle and releasedBy) can not be empty");
    RequestPrecondition.checkArguments(model.getGrayDelKeys() != null,
            "Params(grayDelKeys) can not be null");

    if (userService.findByUserId(model.getReleasedBy()) == null) {
        throw new BadRequestException("user(releaseBy) not exists");
    }

    NamespaceGrayDelReleaseModel releaseModel = BeanUtils.transform(NamespaceGrayDelReleaseModel.class, model);
    releaseModel.setAppId(appId);
    releaseModel.setEnv(env.toUpperCase());
    releaseModel.setClusterName(branchName);
    releaseModel.setNamespaceName(namespaceName);

    return OpenApiBeanUtils.transformFromReleaseDTO(releaseService.publish(releaseModel, releaseModel.getReleasedBy()));
}
 
Example 17
Source Project: apollo   Source File: ReleaseController.java    License: Apache License 2.0 6 votes vote down vote up
@PutMapping(path = "/releases/{releaseId}/rollback")
public void rollback(@PathVariable String env,
    @PathVariable long releaseId, @RequestParam String operator, HttpServletRequest request) {
  RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(operator),
      "Param operator can not be empty");

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

  ReleaseDTO release = releaseService.findReleaseById(Env.fromString(env), releaseId);

  if (release == null) {
    throw new BadRequestException("release not found");
  }

  if (!consumerPermissionValidator.hasReleaseNamespacePermission(request,release.getAppId(), release.getNamespaceName(), env)) {
    throw new AccessDeniedException("Forbidden operation. you don't have release permission");
  }

  releaseService.rollback(Env.fromString(env), releaseId, operator);

}
 
Example 18
Source Project: apollo   Source File: AppNamespaceController.java    License: 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 19
Source Project: apollo-use-cases   Source File: EncryptUtil.java    License: 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 20
Source Project: apollo   Source File: YamlParser.java    License: Apache License 2.0 5 votes vote down vote up
private void buildFlattenedMap(Map<String, Object> result, Map<String, Object> source, String path) {
  for (Map.Entry<String, Object> entry : source.entrySet()) {
    String key = entry.getKey();
    if (!StringUtils.isBlank(path)) {
      if (key.startsWith("[")) {
        key = path + key;
      } else {
        key = path + '.' + key;
      }
    }
    Object value = entry.getValue();
    if (value instanceof String) {
      result.put(key, value);
    } else if (value instanceof Map) {
      // Need a compound key
      @SuppressWarnings("unchecked")
      Map<String, Object> map = (Map<String, Object>) value;
      buildFlattenedMap(result, map, key);
    } else if (value instanceof Collection) {
      // Need a compound key
      @SuppressWarnings("unchecked")
      Collection<Object> collection = (Collection<Object>) value;
      int count = 0;
      for (Object object : collection) {
        buildFlattenedMap(result, Collections.singletonMap("[" + (count++) + "]", object), key);
      }
    } else {
      result.put(key, (value != null ? value.toString() : ""));
    }
  }
}
 
Example 21
Source Project: apollo   Source File: StringUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEqualsIgnoreCase() {
  Assert.assertFalse(StringUtils.equalsIgnoreCase(",", "foo"));
  Assert.assertFalse(StringUtils.equalsIgnoreCase(null, "??"));
  Assert.assertTrue(StringUtils.equalsIgnoreCase(null, null));
  Assert.assertTrue(StringUtils.equalsIgnoreCase("foo", "Foo"));
}
 
Example 22
Source Project: apollo   Source File: StringUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsContainEmpty() {
  Assert.assertFalse(StringUtils.isContainEmpty(null));
  Assert.assertFalse(StringUtils.isContainEmpty(new String[] {}));
  Assert.assertFalse(StringUtils.isContainEmpty(new String[] {"1"}));
  Assert.assertTrue(StringUtils.isContainEmpty(new String[] {null}));
}
 
Example 23
Source Project: apollo   Source File: ItemService.java    License: 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 24
Source Project: apollo   Source File: ReleaseService.java    License: 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 25
Source Project: apollo   Source File: UserInfoController.java    License: Apache License 2.0 5 votes vote down vote up
@PreAuthorize(value = "@permissionValidator.isSuperAdmin()")
@PostMapping("/users")
public void createOrUpdateUser(@RequestBody UserPO user) {
  if (StringUtils.isContainEmpty(user.getUsername(), user.getPassword())) {
    throw new BadRequestException("Username and password can not be empty.");
  }

  if (userService instanceof SpringSecurityUserService) {
    ((SpringSecurityUserService) userService).createOrUpdate(user);
  } else {
    throw new UnsupportedOperationException("Create or update user operation is unsupported");
  }

}
 
Example 26
Source Project: apollo   Source File: Env.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * logic same as
 * @see com.ctrip.framework.apollo.core.enums.EnvUtils transformEnv
 * @param envName
 * @return
 */
public static Env transformEnv(String envName) {
    if(Env.exists(envName)) {
        return Env.valueOf(envName);
    }
    if (StringUtils.isBlank(envName)) {
        return Env.UNKNOWN;
    }
    switch (envName.trim().toUpperCase()) {
        case "LPT":
            return Env.LPT;
        case "FAT":
        case "FWS":
            return Env.FAT;
        case "UAT":
            return Env.UAT;
        case "PRO":
        case "PROD": //just in case
            return Env.PRO;
        case "DEV":
            return Env.DEV;
        case "LOCAL":
            return Env.LOCAL;
        case "TOOLS":
            return Env.TOOLS;
        default:
            return Env.UNKNOWN;
    }
}
 
Example 27
Source Project: apollo   Source File: ItemService.java    License: 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 28
Source Project: apollo   Source File: NamespaceService.java    License: 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 29
Source Project: apollo   Source File: NamespaceService.java    License: 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 30
Source Project: apollo   Source File: NamespaceBranchController.java    License: Apache License 2.0 5 votes vote down vote up
@PreAuthorize(value = "@consumerPermissionValidator.hasModifyNamespacePermission(#request, #appId, #namespaceName, #env)")
@DeleteMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}")
public void deleteBranch(@PathVariable String appId,
                         @PathVariable String env,
                         @PathVariable String clusterName,
                         @PathVariable String namespaceName,
                         @PathVariable String branchName,
                         @RequestParam("operator") String operator,
                         HttpServletRequest request) {
    RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(operator),"operator can not be empty");

    if (userService.findByUserId(operator) == null) {
        throw new BadRequestException("operator " + operator + " not exists");
    }

    boolean canDelete = consumerPermissionValidator.hasReleaseNamespacePermission(request, appId, namespaceName, env) ||
        (consumerPermissionValidator.hasModifyNamespacePermission(request, appId, namespaceName, env) &&
            releaseService.loadLatestRelease(appId, Env.valueOf(env), branchName, namespaceName) == null);

    if (!canDelete) {
        throw new AccessDeniedException("Forbidden operation. "
            + "Caused by: 1.you don't have release permission "
            + "or 2. you don't have modification permission "
            + "or 3. you have modification permission but branch has been released");
    }
    namespaceBranchService.deleteBranch(appId, Env.valueOf(env.toUpperCase()), clusterName, namespaceName, branchName, operator);

}