org.apache.commons.lang3.StringUtils.trimToEmpty()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(15.9k)|赞(0)|评价(0)|浏览(181)

本文整理了Java中org.apache.commons.lang3.StringUtils.trimToEmpty()方法的一些代码示例,展示了StringUtils.trimToEmpty()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。StringUtils.trimToEmpty()方法的具体详情如下:
包路径:org.apache.commons.lang3.StringUtils
类名称:StringUtils
方法名:trimToEmpty

StringUtils.trimToEmpty介绍

[英]Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty ("") after the trim or if it is null.

The String is trimmed using String#trim(). Trim removes start and end characters <= 32. To strip whitespace use #stripToEmpty(String).

StringUtils.trimToEmpty(null)          = "" 
StringUtils.trimToEmpty("")            = "" 
StringUtils.trimToEmpty("     ")       = "" 
StringUtils.trimToEmpty("abc")         = "abc" 
StringUtils.trimToEmpty("    abc    ") = "abc"

[中]从该字符串的两端删除控制字符(char<=32),如果修剪后的字符串为空(“”)或为空,则返回空字符串(“”)。
使用字符串#trim()修剪字符串。Trim删除起始字符和结束字符<=32。要去除空白,请使用#stripToEmpty(字符串)。

StringUtils.trimToEmpty(null)          = "" 
StringUtils.trimToEmpty("")            = "" 
StringUtils.trimToEmpty("     ")       = "" 
StringUtils.trimToEmpty("abc")         = "abc" 
StringUtils.trimToEmpty("    abc    ") = "abc"

代码示例

代码示例来源:origin: liuyangming/ByteTCC

public File getDefaultDirectory() {
  String address = StringUtils.trimToEmpty(this.endpoint);
  File directory = new File(String.format("bytetcc/%s", address.replaceAll("\\W", "_")));
  if (directory.exists() == false) {
    try {
      directory.mkdirs();
    } catch (SecurityException ex) {
      logger.error("Error occurred while creating directory {}!", directory.getAbsolutePath(), ex);
    }
  }
  return directory;
}

代码示例来源:origin: pmd/pmd

/**
   * Reads the file, which contains the filelist. This is used for the
   * command line arguments --filelist/-filelist for both PMD and CPD.
   * The separator in the filelist is a command and/or newlines.
   * 
   * @param filelist the file which contains the list of path names
   * @return a comma-separated list of file paths
   * @throws IOException if the file couldn't be read
   */
  public static String readFilelist(File filelist) throws IOException {
    String filePaths = FileUtils.readFileToString(filelist);
    filePaths = StringUtils.trimToEmpty(filePaths);
    filePaths = filePaths.replaceAll("\\r?\\n", ",");
    filePaths = filePaths.replaceAll(",+", ",");
    return filePaths;
  }
}

代码示例来源:origin: apache/geode

@Override
 public String toString() {
  return StringUtils.trimToEmpty(name);
 }
}

代码示例来源:origin: simpligility/android-maven-plugin

/**
 * Helper method to build a comma separated string from a list.
 * Blank strings are filtered out
 *
 * @param lines A list of strings
 * @return Comma separated String from given list
 */
protected static String buildCommaSeparatedString( List<String> lines )
{
  if ( lines == null || lines.size() == 0 )
  {
    return null;
  }
  List<String> strings = new ArrayList<String>( lines.size() );
  for ( String str : lines )
  { // filter out blank strings
    if ( StringUtils.isNotBlank( str ) )
    {
      strings.add( StringUtils.trimToEmpty( str ) );
    }
  }
  return StringUtils.join( strings, "," );
}

代码示例来源:origin: org.apache.commons/commons-lang3

@Test
public void testTrimToEmpty() {
  assertEquals(FOO, StringUtils.trimToEmpty(FOO + "  "));
  assertEquals(FOO, StringUtils.trimToEmpty(" " + FOO + "  "));
  assertEquals(FOO, StringUtils.trimToEmpty(" " + FOO));
  assertEquals(FOO, StringUtils.trimToEmpty(FOO + ""));
  assertEquals("", StringUtils.trimToEmpty(" \t\r\n\b "));
  assertEquals("", StringUtils.trimToEmpty(StringUtilsTest.TRIMMABLE));
  assertEquals(StringUtilsTest.NON_TRIMMABLE, StringUtils.trimToEmpty(StringUtilsTest.NON_TRIMMABLE));
  assertEquals("", StringUtils.trimToEmpty(""));
  assertEquals("", StringUtils.trimToEmpty(null));
}

代码示例来源:origin: liuyangming/ByteTCC

private Object createDataSourceWrapperIfNecessary(Object bean, String beanName) {
  if (DataSource.class.isInstance(bean) == false) {
    return bean;
  } else if (LocalXADataSource.class.isInstance(bean)) {
    return bean;
  }
  String value = StringUtils.trimToEmpty(this.environment.getProperty(CONSTANT_AUTO_CONFIG));
  if (StringUtils.isNotBlank(value) && Boolean.valueOf(value) == false) {
    return bean;
  }
  DataSource delegate = (DataSource) bean;
  LocalXADataSource dataSource = new LocalXADataSource();
  dataSource.setDataSource(delegate);
  dataSource.setBeanName(beanName);
  dataSource.setTransactionManager(this.transactionManager);
  return dataSource;
}

代码示例来源:origin: apache/nifi

Matcher m = regexAttributesToSend.matcher("");
for (Map.Entry<String, String> entry : attributes.entrySet()) {
  String headerKey = trimToEmpty(entry.getKey());
    String headerVal = trimToEmpty(entry.getValue());
    requestBuilder = requestBuilder.addHeader(headerKey, headerVal);

代码示例来源:origin: apache/nifi

@Override
public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue, final String newValue) {
  if (descriptor.isDynamic()) {
    final Set<String> newDynamicPropertyNames = new HashSet<>(dynamicPropertyNames);
    if (newValue == null) {
      newDynamicPropertyNames.remove(descriptor.getName());
    } else if (oldValue == null) {    // new property
      newDynamicPropertyNames.add(descriptor.getName());
    }
    this.dynamicPropertyNames = Collections.unmodifiableSet(newDynamicPropertyNames);
  } else {
    // compile the attributes-to-send filter pattern
    if (PROP_ATTRIBUTES_TO_SEND.getName().equalsIgnoreCase(descriptor.getName())) {
      if (newValue == null || newValue.isEmpty()) {
        regexAttributesToSend = null;
      } else {
        final String trimmedValue = StringUtils.trimToEmpty(newValue);
        regexAttributesToSend = Pattern.compile(trimmedValue);
      }
    }
  }
}

代码示例来源:origin: apache/nifi

@Override
public void onPropertyModified(final PropertyDescriptor descriptor, final String oldValue,
                final String newValue) {
  if (descriptor.isDynamic()) {
    final Set<String> newDynamicPropertyNames = new HashSet<>(dynamicPropertyNames);
    if (newValue == null) {
      newDynamicPropertyNames.remove(descriptor.getName());
    } else if (oldValue == null) {    // new property
      newDynamicPropertyNames.add(descriptor.getName());
    }
    this.dynamicPropertyNames = Collections.unmodifiableSet(newDynamicPropertyNames);
  } else {
    // compile the attributes-to-send filter pattern
    if (PROP_ATTRIBUTES_TO_SEND.getName().equalsIgnoreCase(descriptor.getName())) {
      if (newValue == null || newValue.isEmpty()) {
        regexAttributesToSend = null;
      } else {
        final String trimmedValue = StringUtils.trimToEmpty(newValue);
        regexAttributesToSend = Pattern.compile(trimmedValue);
      }
    }
  }
}

代码示例来源:origin: liuyangming/ByteTCC

private void initializeRemoteParticipantIfNecessary(final String system) throws RpcException {
  RemoteCoordinatorRegistry participantRegistry = RemoteCoordinatorRegistry.getInstance();
  final String application = StringUtils.trimToEmpty(system).intern();
  RemoteCoordinator remoteParticipant = participantRegistry.getParticipant(application);
  if (remoteParticipant == null) {
    synchronized (application) {
      RemoteCoordinator participant = participantRegistry.getParticipant(application);
      if (participant == null) {
        this.processInitRemoteParticipantIfNecessary(application);
      }
    } // end-synchronized (target)
  } // end-if (remoteParticipant == null)
}

代码示例来源:origin: liuyangming/ByteTCC

private void initializeRemoteParticipantIfNecessary(final String system) throws RpcException {
  RemoteCoordinatorRegistry participantRegistry = RemoteCoordinatorRegistry.getInstance();
  final String application = StringUtils.trimToEmpty(system).intern();
  RemoteCoordinator remoteParticipant = participantRegistry.getParticipant(application);
  if (remoteParticipant == null) {
    synchronized (application) {
      RemoteCoordinator participant = participantRegistry.getParticipant(application);
      if (participant == null) {
        this.processInitRemoteParticipantIfNecessary(application);
      }
    } // end-synchronized (target)
  } // end-if (remoteParticipant == null)
}

代码示例来源:origin: apache/nifi

protected GenericApiGatewayRequest configureRequest(final ProcessContext context,
                          final ProcessSession session,
                          final String resourcePath,
                          final FlowFile requestFlowFile) {
  String method = trimToEmpty(
      context.getProperty(PROP_METHOD).evaluateAttributeExpressions(requestFlowFile)
          .getValue()).toUpperCase();
  HttpMethodName methodName = HttpMethodName.fromValue(method);
  return configureRequest(context, session, resourcePath,requestFlowFile, methodName);
}

代码示例来源:origin: apache/nifi

private void setAuthenticator(OkHttpClient.Builder okHttpClientBuilder, ProcessContext context) {
  final String authUser = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_USERNAME).getValue());
  // If the username/password properties are set then check if digest auth is being used
  if (!authUser.isEmpty() && "true".equalsIgnoreCase(context.getProperty(PROP_DIGEST_AUTH).getValue())) {
    final String authPass = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_PASSWORD).getValue());
    /*
     * OkHttp doesn't have built-in Digest Auth Support. A ticket for adding it is here[1] but they authors decided instead to rely on a 3rd party lib.
     *
     * [1] https://github.com/square/okhttp/issues/205#issuecomment-154047052
     */
    final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
    com.burgstaller.okhttp.digest.Credentials credentials = new com.burgstaller.okhttp.digest.Credentials(authUser, authPass);
    final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);
    okHttpClientBuilder.interceptors().add(new AuthenticationCacheInterceptor(authCache));
    okHttpClientBuilder.authenticator(new CachingAuthenticatorDecorator(digestAuthenticator, authCache));
  }
}

代码示例来源:origin: apache/nifi

private void initalizeEndpointOverride(final ProcessContext context, final AmazonS3Client s3) {
  // if ENDPOINT_OVERRIDE is set, use PathStyleAccess
  if(StringUtils.trimToEmpty(context.getProperty(ENDPOINT_OVERRIDE).evaluateAttributeExpressions().getValue()).isEmpty() == false){
    final S3ClientOptions s3Options = new S3ClientOptions();
    s3Options.setPathStyleAccess(true);
    s3.setS3ClientOptions(s3Options);
  }
}

代码示例来源:origin: apache/nifi

private void setAuthenticator(OkHttpClient.Builder okHttpClientBuilder, ConfigurationContext context) {
  final String authUser = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_USERNAME).evaluateAttributeExpressions().getValue());
  this.basicUser = authUser;
  isDigest = context.getProperty(PROP_DIGEST_AUTH).asBoolean();
  final String authPass = trimToEmpty(context.getProperty(PROP_BASIC_AUTH_PASSWORD).evaluateAttributeExpressions().getValue());
  this.basicPass = authPass;
  // If the username/password properties are set then check if digest auth is being used
  if (!authUser.isEmpty() && isDigest) {
    /*
     * OkHttp doesn't have built-in Digest Auth Support. A ticket for adding it is here[1] but they authors decided instead to rely on a 3rd party lib.
     *
     * [1] https://github.com/square/okhttp/issues/205#issuecomment-154047052
     */
    final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();
    com.burgstaller.okhttp.digest.Credentials credentials = new com.burgstaller.okhttp.digest.Credentials(authUser, authPass);
    final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(credentials);
    okHttpClientBuilder.interceptors().add(new AuthenticationCacheInterceptor(authCache));
    okHttpClientBuilder.authenticator(new CachingAuthenticatorDecorator(digestAuthenticator, authCache));
  }
}

代码示例来源:origin: liuyangming/ByteTCC

public Result providerInvokeForKey(Invoker<?> invoker, Invocation invocation) throws RpcException {
  CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
  CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
  RemoteCoordinator transactionCoordinator = (RemoteCoordinator) beanFactory.getCompensableNativeParticipant();
  String instanceId = StringUtils.trimToEmpty(invocation.getAttachment(RemoteCoordinator.class.getName()));
  this.registerRemoteParticipantIfNecessary(instanceId);
  RpcResult result = new RpcResult();
  CompensableServiceFilter.InvocationResult wrapped = new CompensableServiceFilter.InvocationResult();
  wrapped.setVariable(RemoteCoordinator.class.getName(), transactionCoordinator.getIdentifier());
  result.setException(null);
  result.setValue(wrapped);
  return result;
}

代码示例来源:origin: liuyangming/ByteTCC

public Result providerInvokeForKey(Invoker<?> invoker, Invocation invocation) throws RpcException {
  CompensableBeanRegistry beanRegistry = CompensableBeanRegistry.getInstance();
  CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
  RemoteCoordinator transactionCoordinator = (RemoteCoordinator) beanFactory.getCompensableNativeParticipant();
  String instanceId = StringUtils.trimToEmpty(invocation.getAttachment(RemoteCoordinator.class.getName()));
  this.registerRemoteParticipantIfNecessary(instanceId);
  RpcResult result = new RpcResult();
  CompensableServiceFilter.InvocationResult wrapped = new CompensableServiceFilter.InvocationResult();
  wrapped.setVariable(RemoteCoordinator.class.getName(), transactionCoordinator.getIdentifier());
  result.setException(null);
  result.setValue(wrapped);
  return result;
}

代码示例来源:origin: apache/incubator-gobblin

@Override
public FileStatus getFileStatus(Path path) throws IOException {
 ChannelSftp channelSftp = null;
 ChannelExec channelExec1 = null;
 ChannelExec channelExec2 = null;
 try {
  channelSftp = this.fsHelper.getSftpChannel();
  SftpATTRS sftpAttrs = channelSftp.stat(HadoopUtils.toUriPath(path));
  FsPermission permission = new FsPermission((short) sftpAttrs.getPermissions());
  channelExec1 = this.fsHelper.getExecChannel("id " + sftpAttrs.getUId());
  String userName = IOUtils.toString(channelExec1.getInputStream());
  channelExec2 = this.fsHelper.getExecChannel("id " + sftpAttrs.getGId());
  String groupName = IOUtils.toString(channelExec2.getInputStream());
  FileStatus fs =
    new FileStatus(sftpAttrs.getSize(), sftpAttrs.isDir(), 1, 0l, sftpAttrs.getMTime(), sftpAttrs.getATime(),
      permission, StringUtils.trimToEmpty(userName), StringUtils.trimToEmpty(groupName), path);
  return fs;
 } catch (SftpException e) {
  throw new IOException(e);
 } finally {
  safeDisconnect(channelSftp);
  safeDisconnect(channelExec1);
  safeDisconnect(channelExec2);
 }
}

代码示例来源:origin: liuyangming/ByteTCC

private void invokeAfterRecvResponse(ClientHttpResponse httpResponse, boolean serverFlag) throws IOException {
  RemoteCoordinatorRegistry participantRegistry = RemoteCoordinatorRegistry.getInstance();
  SpringBootBeanRegistry beanRegistry = SpringBootBeanRegistry.getInstance();
  CompensableBeanFactory beanFactory = beanRegistry.getBeanFactory();
  TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();
  HttpHeaders respHeaders = httpResponse.getHeaders();
  String respTransactionStr = respHeaders.getFirst(HEADER_TRANCACTION_KEY);
  String respPropagationStr = respHeaders.getFirst(HEADER_PROPAGATION_KEY);
  String instanceId = StringUtils.trimToEmpty(respPropagationStr);
  RemoteAddr remoteAddr = CommonUtils.getRemoteAddr(instanceId);
  RemoteNode remoteNode = CommonUtils.getRemoteNode(instanceId);
  if (remoteAddr != null && remoteNode != null) {
    participantRegistry.putRemoteNode(remoteAddr, remoteNode);
  }
  String transactionText = StringUtils.trimToNull(respTransactionStr);
  byte[] byteArray = StringUtils.isBlank(transactionText) ? null : Base64.getDecoder().decode(transactionText);
  TransactionContext serverContext = byteArray == null || byteArray.length == 0 //
      ? null : (TransactionContext) SerializeUtils.deserializeObject(byteArray);
  TransactionResponseImpl txResp = new TransactionResponseImpl();
  txResp.setTransactionContext(serverContext);
  RemoteCoordinator serverCoordinator = beanRegistry.getConsumeCoordinator(instanceId);
  txResp.setSourceTransactionCoordinator(serverCoordinator);
  txResp.setParticipantDelistFlag(serverFlag ? false : true);
  transactionInterceptor.afterReceiveResponse(txResp);
}

代码示例来源:origin: apache/nifi

protected void initializeRegionAndEndpoint(ProcessContext context) {
  // if the processor supports REGION, get the configured region.
  if (getSupportedPropertyDescriptors().contains(REGION)) {
    final String region = context.getProperty(REGION).getValue();
    if (region != null) {
      this.region = Region.getRegion(Regions.fromName(region));
      client.setRegion(this.region);
    } else {
      this.region = null;
    }
  }
  // if the endpoint override has been configured, set the endpoint.
  // (per Amazon docs this should only be configured at client creation)
  if (getSupportedPropertyDescriptors().contains(ENDPOINT_OVERRIDE)) {
    final String urlstr = StringUtils.trimToEmpty(context.getProperty(ENDPOINT_OVERRIDE).evaluateAttributeExpressions().getValue());
    if (!urlstr.isEmpty()) {
      getLogger().info("Overriding endpoint with {}", new Object[]{urlstr});
      if (urlstr.endsWith(".vpce.amazonaws.com")) {
        String region = parseRegionForVPCE(urlstr);
        this.client.setEndpoint(urlstr, this.client.getServiceName(), region);
      } else {
        this.client.setEndpoint(urlstr);
      }
    }
  }
}

相关文章

微信公众号

最新文章

更多

StringUtils类方法