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

The following examples show how to use com.ctrip.framework.apollo.core.utils.StringUtils#isBlank() . 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: 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 3
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 4
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 5
Source File: YamlParser.java    From apollo with 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 6
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 7
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 8
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 9
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 10
Source File: RemoteConfigLongPollService.java    From apollo with Apache License 2.0 4 votes vote down vote up
private void doLongPollingRefresh(String appId, String cluster, String dataCenter, String secret) {
  final Random random = new Random();
  ServiceDTO lastServiceDto = null;
  while (!m_longPollingStopped.get() && !Thread.currentThread().isInterrupted()) {
    if (!m_longPollRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) {
      //wait at most 5 seconds
      try {
        TimeUnit.SECONDS.sleep(5);
      } catch (InterruptedException e) {
      }
    }
    Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "pollNotification");
    String url = null;
    try {
      if (lastServiceDto == null) {
        List<ServiceDTO> configServices = getConfigServices();
        lastServiceDto = configServices.get(random.nextInt(configServices.size()));
      }

      url =
          assembleLongPollRefreshUrl(lastServiceDto.getHomepageUrl(), appId, cluster, dataCenter,
              m_notifications);

      logger.debug("Long polling from {}", url);

      HttpRequest request = new HttpRequest(url);
      request.setReadTimeout(LONG_POLLING_READ_TIMEOUT);
      if (!StringUtils.isBlank(secret)) {
        Map<String, String> headers = Signature.buildHttpHeaders(url, appId, secret);
        request.setHeaders(headers);
      }

      transaction.addData("Url", url);

      final HttpResponse<List<ApolloConfigNotification>> response =
          m_httpUtil.doGet(request, m_responseType);

      logger.debug("Long polling response: {}, url: {}", response.getStatusCode(), url);
      if (response.getStatusCode() == 200 && response.getBody() != null) {
        updateNotifications(response.getBody());
        updateRemoteNotifications(response.getBody());
        transaction.addData("Result", response.getBody().toString());
        notify(lastServiceDto, response.getBody());
      }

      //try to load balance
      if (response.getStatusCode() == 304 && random.nextBoolean()) {
        lastServiceDto = null;
      }

      m_longPollFailSchedulePolicyInSecond.success();
      transaction.addData("StatusCode", response.getStatusCode());
      transaction.setStatus(Transaction.SUCCESS);
    } catch (Throwable ex) {
      lastServiceDto = null;
      Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
      transaction.setStatus(ex);
      long sleepTimeInSecond = m_longPollFailSchedulePolicyInSecond.fail();
      logger.warn(
          "Long polling failed, will retry in {} seconds. appId: {}, cluster: {}, namespaces: {}, long polling url: {}, reason: {}",
          sleepTimeInSecond, appId, cluster, assembleNamespaces(), url, ExceptionUtil.getDetailMessage(ex));
      try {
        TimeUnit.SECONDS.sleep(sleepTimeInSecond);
      } catch (InterruptedException ie) {
        //ignore
      }
    } finally {
      transaction.complete();
    }
  }
}