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

The following examples show how to use com.ctrip.framework.apollo.core.utils.StringUtils. 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: AuthConfiguration.java    From apollo with 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 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 #3
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 #4
Source File: ConsumerController.java    From apollo with 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 #5
Source File: Env.java    From apollo with 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 #6
Source File: ItemController.java    From apollo with 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 #7
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 #8
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 #9
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 #10
Source File: NamespaceBranchController.java    From apollo with 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 #11
Source File: NamespaceBranchController.java    From apollo with 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 #12
Source File: ReleaseController.java    From apollo with 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 #13
Source File: ReleaseController.java    From apollo with 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 #14
Source File: ReleaseController.java    From apollo with 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 #15
Source File: ReleaseController.java    From apollo with 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 File: ReleaseController.java    From apollo with 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 #17
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 #18
Source File: EnvUtils.java    From apollo with 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 #19
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 #20
Source File: TitanCondition.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
  if (!StringUtils.isEmpty(context.getEnvironment().getProperty("fat.titan.url"))) {
    return true;
  }
  if (!StringUtils.isEmpty(context.getEnvironment().getProperty("uat.titan.url"))) {
    return true;
  }
  if (!StringUtils.isEmpty(context.getEnvironment().getProperty("pro.titan.url"))) {
    return true;
  }
  return false;
}
 
Example #21
Source File: Env.java    From apollo with 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 #22
Source File: ClientAuthenticationFilter.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
    throws IOException, ServletException {
  HttpServletRequest request = (HttpServletRequest) req;
  HttpServletResponse response = (HttpServletResponse) resp;

  String appId = accessKeyUtil.extractAppIdFromRequest(request);
  if (StringUtils.isBlank(appId)) {
    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidAppId");
    return;
  }

  List<String> availableSecrets = accessKeyUtil.findAvailableSecret(appId);
  if (!CollectionUtils.isEmpty(availableSecrets)) {
    String timestamp = request.getHeader(Signature.HTTP_HEADER_TIMESTAMP);
    String authorization = request.getHeader(Signature.HTTP_HEADER_AUTHORIZATION);

    // check timestamp, valid within 1 minute
    if (!checkTimestamp(timestamp)) {
      logger.warn("Invalid timestamp. appId={},timestamp={}", appId, timestamp);
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "RequestTimeTooSkewed");
      return;
    }

    // check signature
    String path = request.getServletPath();
    String query = request.getQueryString();
    if (!checkAuthorization(authorization, availableSecrets, timestamp, path, query)) {
      logger.warn("Invalid authorization. appId={},authorization={}", appId, authorization);
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
      return;
    }
  }

  chain.doFilter(request, response);
}
 
Example #23
Source File: NamespaceUnlockAspect.java    From apollo with Apache License 2.0 5 votes vote down vote up
private Map<String, String> generateMapFromItems(List<Item> items, Map<String, String> configurationFromItems) {
  for (Item item : items) {
    String key = item.getKey();
    if (StringUtils.isBlank(key)) {
      continue;
    }
    configurationFromItems.put(key, item.getValue());
  }

  return configurationFromItems;
}
 
Example #24
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 #25
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 #26
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 #27
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 #28
Source File: AppController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@GetMapping("/apps")
public List<AppDTO> find(@RequestParam(value = "name", required = false) String name,
                         Pageable pageable) {
  List<App> app = null;
  if (StringUtils.isBlank(name)) {
    app = appService.findAll(pageable);
  } else {
    app = appService.findByName(name);
  }
  return BeanUtils.batchTransform(AppDTO.class, app);
}
 
Example #29
Source File: ClusterController.java    From apollo with Apache License 2.0 5 votes vote down vote up
@PreAuthorize(value = "@consumerPermissionValidator.hasCreateClusterPermission(#request, #appId)")
@PostMapping(value = "apps/{appId}/clusters")
public OpenClusterDTO createCluster(@PathVariable String appId, @PathVariable String env,
    @Valid @RequestBody OpenClusterDTO cluster, HttpServletRequest request) {

  if (!Objects.equals(appId, cluster.getAppId())) {
    throw new BadRequestException(String.format(
        "AppId not equal. AppId in path = %s, AppId in payload = %s", appId, cluster.getAppId()));
  }

  String clusterName = cluster.getName();
  String operator = cluster.getDataChangeCreatedBy();

  RequestPrecondition.checkArguments(!StringUtils.isContainEmpty(clusterName, operator),
      "name and dataChangeCreatedBy should not be null or empty");

  if (!InputValidator.isValidClusterNamespace(clusterName)) {
    throw new BadRequestException(
        String.format("Invalid ClusterName format: %s", InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE));
  }

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

  ClusterDTO toCreate = OpenApiBeanUtils.transformToClusterDTO(cluster);
  ClusterDTO createdClusterDTO = clusterService.createCluster(Env.fromString(env), toCreate);

  return OpenApiBeanUtils.transformFromClusterDTO(createdClusterDTO);
}
 
Example #30
Source File: NamespaceBranchController.java    From apollo with 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);

}