Java Code Examples for org.apache.commons.lang3.StringUtils.removeStart()

The following are Jave code examples for showing how to use removeStart() of the org.apache.commons.lang3.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: graphium   File: TestWaySegmentResultSetExtractor.java   View Source Code Vote up 6 votes
@Test
public void testParseConString() {
	String serializedCon = "(100000833,960301,101021339,\"{15,4,22,2,9,19,11,13,12,1,10,3}\",24)";
	
	String stripedSerializedCon = StringUtils.removeStart(serializedCon, "(");
	stripedSerializedCon = StringUtils.removeEnd(stripedSerializedCon, ")");
	stripedSerializedCon = stripedSerializedCon.substring(0, stripedSerializedCon.indexOf("}"));
	stripedSerializedCon = stripedSerializedCon.replace("\"", ""); //100000833,960301,101021339,{15,4,22,2,9,19,11,13,12,1,10,3,24
	String[] splitCons = stripedSerializedCon.split("\\{"); //[100000833,960301,101021339,, 15,4,22,2,9,19,11,13,12,1,10,3,24]
	String[] tokens = splitCons[0].split(",");
	String[] accessTypeIdsArray = splitCons[1].split(","); //[15, 4, 22, 2, 9, 19, 11, 13, 12, 1, 10, 3, 24] 

	System.out.println("tokens:");
	for (String token : tokens) {
		System.out.println(token);
	}

	System.out.println("\naccessTypes:");
	for (String accessTypeId : accessTypeIdsArray) {
		System.out.println(accessTypeId);
	}

}
 
Example 2
Project: circus-train   File: S3S3Copier.java   View Source Code Vote up 6 votes
private void startAllCopyJobs() {
  AmazonS3URI sourceBase = toAmazonS3URI(sourceBaseLocation.toUri());
  AmazonS3URI targetBase = toAmazonS3URI(replicaLocation.toUri());
  srcClient = s3ClientFactory.newInstance(sourceBase, s3s3CopierOptions);
  targetClient = s3ClientFactory.newInstance(targetBase, s3s3CopierOptions);
  transferManager = transferManagerFactory.newInstance(targetClient, s3s3CopierOptions);
  if (sourceSubLocations.isEmpty()) {
    copy(sourceBase, targetBase);
  } else {
    for (Path path : sourceSubLocations) {
      AmazonS3URI subLocation = toAmazonS3URI(path.toUri());
      String partitionKey = StringUtils.removeStart(subLocation.getKey(), sourceBase.getKey());
      partitionKey = StringUtils.removeStart(partitionKey, "/");
      AmazonS3URI targetS3Uri = toAmazonS3URI(new Path(replicaLocation, partitionKey).toUri());
      LOG.debug("Starting copyJob from {} to {}", subLocation, targetS3Uri);
      copy(subLocation, targetS3Uri);
    }
  }
}
 
Example 3
Project: xm-commons   File: TimelineEventProducer.java   View Source Code Vote up 5 votes
private static String getResourceName(String path) {
    String name = StringUtils.removeStart(path, "/api/");
    if (StringUtils.startsWith(name, "_search")) {
        name = StringUtils.substringAfter(name, "/");
    }
    return StringUtils.defaultIfBlank(StringUtils.substringBefore(name, "/"), "unknown");
}
 
Example 4
Project: graphium   File: WaySegmentResultSetExtractor.java   View Source Code Vote up 5 votes
private IWaySegmentConnection parseSerializedCon(String serializedCon) { // (100000833,960301,101021339,"{15,4,22,2,9,19,11,13,12,1,10,3}",24)
		if (serializedCon == null) {
			return null;
		}
		
		String stripedSerializedCon = StringUtils.removeStart(serializedCon, "(");
		stripedSerializedCon = StringUtils.removeEnd(stripedSerializedCon, ")");
		stripedSerializedCon = stripedSerializedCon.substring(0, stripedSerializedCon.indexOf("}")); // ignore everything after access types
		stripedSerializedCon = stripedSerializedCon.replace("\"", ""); //100000833,960301,101021339,{15,4,22,2,9,19,11,13,12,1,10,3,24
		String[] splitCons = stripedSerializedCon.split("\\{"); //[100000833,960301,101021339,, 15,4,22,2,9,19,11,13,12,1,10,3,24]
		String[] tokens = splitCons[0].split(ARRAYVALUESEP);
		String[] accessTypeIdsArray = splitCons[1].split(ARRAYVALUESEP); //[15, 4, 22, 2, 9, 19, 11, 13, 12, 1, 10, 3, 24] 

//		String s1 = StringUtils.removePattern(stripedSerializedCon, "\\\"\\{[0-9,]*\\}\\\"");
		int[] accessTypeIds = new int[accessTypeIdsArray.length];
		int i = 0;
		for (String accessTypeId : accessTypeIdsArray) {
			accessTypeIds[i++] = Integer.parseInt(accessTypeId);
		}
		Set<Access> accessTypesTow = Access.getAccessTypes(accessTypeIds);

		return new WaySegmentConnection(
				Long.parseLong(tokens[0]), 
				Long.parseLong(tokens[1]),
				Long.parseLong(tokens[2]),
				accessTypesTow);	
	}
 
Example 5
Project: circus-train   File: S3S3Copier.java   View Source Code Vote up 5 votes
private void submitCopyJobsFromListing(
    AmazonS3URI sourceS3Uri,
    final AmazonS3URI targetS3Uri,
    ListObjectsRequest request,
    ObjectListing listing) {
  LOG.debug("Found objects to copy {}, for request {}/{}", listing.getObjectSummaries(), request.getBucketName(),
      request.getPrefix());
  List<S3ObjectSummary> objectSummaries = listing.getObjectSummaries();
  for (final S3ObjectSummary s3ObjectSummary : objectSummaries) {
    String fileName = StringUtils.removeStart(s3ObjectSummary.getKey(), sourceS3Uri.getKey());
    final String targetKey = Strings.nullToEmpty(targetS3Uri.getKey()) + fileName;
    LOG.info("copying object from '{}/{}' to '{}/{}'", s3ObjectSummary.getBucketName(), s3ObjectSummary.getKey(),
        targetS3Uri.getBucket(), targetKey);

    CopyObjectRequest copyObjectRequest = new CopyObjectRequest(s3ObjectSummary.getBucketName(),
        s3ObjectSummary.getKey(), targetS3Uri.getBucket(), targetKey);

    TransferStateChangeListener stateChangeListener = new TransferStateChangeListener() {

      @Override
      public void transferStateChanged(Transfer transfer, TransferState state) {
        if (state == TransferState.Completed) {
          // NOTE: running progress doesn't seem to be reported correctly.
          // transfer.getProgress().getBytesTransferred() is always 0. Unsure what is the cause of this at this moment
          // so just printing total bytes when completed.
          LOG.debug("copied object from '{}/{}' to '{}/{}': {} bytes transferred", s3ObjectSummary.getBucketName(),
              s3ObjectSummary.getKey(), targetS3Uri.getBucket(), targetKey,
              transfer.getProgress().getTotalBytesToTransfer());
        }
      }
    };
    Copy copy = transferManager.copy(copyObjectRequest, srcClient, stateChangeListener);
    totalBytesToReplicate += copy.getProgress().getTotalBytesToTransfer();
    copyJobs.add(copy);
  }
}
 
Example 6
Project: cyberduck   File: TerminalHelpFormatter.java   View Source Code Vote up 5 votes
protected StringBuffer renderWrappedText(final StringBuffer sb, final int width, int nextLineTabStop, String text) {
    int pos = findWrapPos(text, width, 0);
    if(pos == -1) {
        sb.append(rtrim(text));

        return sb;
    }
    sb.append(rtrim(text.substring(0, pos))).append(getNewLine());
    if(nextLineTabStop >= width) {
        // stops infinite loop happening
        nextLineTabStop = 1;
    }
    // all following lines must be padded with nextLineTabStop space characters
    final String padding = createPadding(nextLineTabStop);
    while(true) {
        text = padding + StringUtils.removeStart(text.substring(pos), StringUtils.SPACE);
        pos = findWrapPos(text, width, 0);
        if(pos == -1) {
            sb.append(text);
            return sb;
        }
        if((text.length() > width) && (pos == nextLineTabStop - 1)) {
            pos = width;
        }
        sb.append(rtrim(text.substring(0, pos))).append(getNewLine());
    }
}
 
Example 7
Project: mensa-api   File: LabelCache.java   View Source Code Vote up 5 votes
private String removeStopWords(String text) {
    String cleanText = text;
    for (String stopword : config.getStopwords()) {
        cleanText = StringUtils.removeStart(cleanText, stopword + " ");
    }
    return cleanText;
}
 
Example 8
Project: plugin-vm-vcloud   File: VCloudPluginResource.java   View Source Code Vote up 5 votes
/**
 * Return/execute a vCloud resource. Return <code>null</code> when the
 * resource is not found. Authentication should be proceeded before for
 * authenticated query.
 */
protected String execute(final CurlProcessor processor, final String method, final String url, final String resource) {
	// Get the resource using the preempted authentication
	final CurlRequest request = new CurlRequest(method, StringUtils.appendIfMissing(url, "/") + StringUtils.removeStart(resource, "/"),
			null);
	request.setSaveResponse(true);

	// Execute the requests
	processor.process(request);
	processor.close();
	return request.getResponse();
}
 
Example 9
Project: HL7Receiver   File: Message.java   View Source Code Vote up 5 votes
private static Seperators detectSeperators(String messageText) throws ParseException {
    Seperators seperators = new Seperators();

    String firstLine = StringUtils.split(messageText, seperators.getLineSeperator())[FIRST];

    if (!firstLine.startsWith(MSH_SEGMENT_NAME))
        throw new ParseException("message does not start with " + MSH_SEGMENT_NAME + " segment");

    String firstLineWithoutSegmentName = StringUtils.removeStart(firstLine, MSH_SEGMENT_NAME);

    if (firstLineWithoutSegmentName.length() < 5)
        throw new ParseException(MSH_SEGMENT_NAME + " does not encoding characters");

    seperators
            .setFieldSeperator(firstLineWithoutSegmentName.substring(0, 1))
            .setComponentSeperator(firstLineWithoutSegmentName.substring(1, 2))
            .setRepetitionSeperator(firstLineWithoutSegmentName.substring(2, 3))
            .setEscapeCharacter(firstLineWithoutSegmentName.substring(3, 4))
            .setSubcomponentSeperator(firstLineWithoutSegmentName.substring(4, 5));

    if (!seperators.areSeperatorsUnique())
        throw new ParseException("Seperators are not unique");

    if (!messageText.contains(seperators.getFieldSeperator()))
        throw new ParseException("Field seperator does not appear to be correct");

    return seperators;
}
 
Example 10
Project: yadaframework   File: YadaLocalePathVariableFilter.java   View Source Code Vote up 5 votes
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest) servletRequest;
	String url = request.getRequestURI().substring(request.getContextPath().length());
	// Do we handle the locale path variable?
	if (!config.isLocalePathVariableEnabled()) {
		filterChain.doFilter(request, response);
		return;
	}
	// Have we been called already?
	if (request.getAttribute(CALLED_FLAG)!=null) {
		filterChain.doFilter(request, response);
		return;
	}
	request.setAttribute(CALLED_FLAG, true); // Called once per request
			
	// Check and set the locale
    String[] variables = url.split("/", 3);

    if (variables.length > 1 && isLocale(variables[1])) {
    	String requestLocale = variables[1]; // either "en" or "en_US"
    	boolean languageOnly = !requestLocale.contains("_");
    	if (languageOnly && config.isLocaleAddCountry()) {
    		String country = config.getCountryForLanguage(requestLocale);
    		if (country!=null) {
    			requestLocale += "_" + country;
    		}
    	}
    	request.setAttribute(YadaLocalePathChangeInterceptor.LOCALE_ATTRIBUTE_NAME, requestLocale);
        request.setAttribute(ORIGINAL_REQUEST, request); // To be used in case of authorization failure that requires a login
        String newUrl = StringUtils.removeStart(url, '/' + variables[1]); // TODO don't we need the context path at the start?
        RequestDispatcher dispatcher = request.getRequestDispatcher(newUrl);
        dispatcher.forward(request, response);
    } else {
        filterChain.doFilter(request, response);
    }
}
 
Example 11
Project: Alpine   File: AlpineResource.java   View Source Code Vote up 4 votes
/**
 * Accepts the result from one of the many validation methods available and
 * returns a List of ValidationErrors. If the size of the List is 0, no errors
 * were encounter during validation.
 *
 * Usage:
 * <pre>
 *     Validator validator = getValidator();
 *     List&lt;ValidationError&gt; errors = contOnValidationError(
 *         validator.validateProperty(myObject, "uuid"),
 *         validator.validateProperty(myObject, "name")
 *      );
 *      // If validation fails, this line will be reached.
 * </pre>
 *
 * @param violationsArray a Set of one or more ConstraintViolations
 * @return a List of zero or more ValidationErrors
 * @since 1.0.0
 */
@SafeVarargs
protected final List<ValidationError> contOnValidationError(final Set<ConstraintViolation<Object>>... violationsArray) {
    final List<ValidationError> errors = new ArrayList<>();
    for (Set<ConstraintViolation<Object>> violations : violationsArray) {
        for (ConstraintViolation violation : violations) {
            if (violation.getPropertyPath().iterator().next().getName() != null) {
                final String path = violation.getPropertyPath() != null ? violation.getPropertyPath().toString() : null;
                final String message = violation.getMessage() != null ? StringUtils.removeStart(violation.getMessage(), path + ".") : null;
                final String messageTemplate = violation.getMessageTemplate();
                final String invalidValue = violation.getInvalidValue() != null ? violation.getInvalidValue().toString() : null;
                final ValidationError error = new ValidationError(message, messageTemplate, path, invalidValue);
                errors.add(error);
            }
        }
    }
    return errors;
}
 
Example 12
Project: cyberduck   File: TildeExpander.java   View Source Code Vote up 4 votes
public String abbreviate(final String name) {
    if(StringUtils.startsWith(name, preferences.getProperty("local.user.home"))) {
        return Local.HOME + StringUtils.removeStart(name, preferences.getProperty("local.user.home"));
    }
    return name;
}
 
Example 13
Project: cyberduck   File: DictionaryLicense.java   View Source Code Vote up 4 votes
protected void verify(final NSDictionary dictionary, final String publicKey) throws InvalidLicenseException {
    if(null == dictionary) {
        throw new InvalidLicenseException();
    }
    final NSData signature = (NSData) dictionary.objectForKey("Signature");
    if(null == signature) {
        log.warn(String.format("Missing key 'Signature' in dictionary %s", dictionary));
        throw new InvalidLicenseException();
    }
    // Append all values
    StringBuilder values = new StringBuilder();
    final ArrayList<String> keys = new ArrayList<>(dictionary.keySet());
    // Sort lexicographically by key
    Collections.sort(keys, new NaturalOrderComparator());
    for(String key : keys) {
        if("Signature".equals(key)) {
            continue;
        }
        values.append(dictionary.objectForKey(key).toString());
    }
    byte[] signaturebytes = signature.bytes();
    byte[] plainbytes = values.toString().getBytes(Charset.forName("UTF-8"));
    try {
        final BigInteger modulus = new BigInteger(StringUtils.removeStart(publicKey, "0x"), 16);
        final BigInteger exponent = new BigInteger(Base64.decodeBase64("Aw=="));
        final KeySpec spec = new RSAPublicKeySpec(modulus, exponent);

        final PublicKey rsa = KeyFactory.getInstance("RSA").generatePublic(spec);
        final Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsaCipher.init(Cipher.DECRYPT_MODE, rsa);
        final MessageDigest sha1Digest = MessageDigest.getInstance("SHA1");
        if(!Arrays.equals(rsaCipher.doFinal(signaturebytes), sha1Digest.digest(plainbytes))) {
            throw new InvalidLicenseException();
        }
    }
    catch(NoSuchPaddingException
            | BadPaddingException
            | IllegalBlockSizeException
            | InvalidKeyException
            | InvalidKeySpecException
            | NoSuchAlgorithmException e) {
        log.warn(String.format("Signature verification failure for key %s", file));
        throw new InvalidLicenseException();
    }
    if(log.isInfoEnabled()) {
        log.info(String.format("Valid key in %s", file));
    }
}
 
Example 14
Project: bootstrap   File: HtmlProxyFilter.java   View Source Code Vote up 4 votes
/**
 * Return the base name of resource from the request.
 */
private String getBaseName(final ServletRequest request) {
	final String servletPath = ((HttpServletRequest) request).getServletPath();
	final String base = StringUtils.removeStart(servletPath, "/");
	return getBaseName(base.isEmpty() ? "index.html" : base);
}
 
Example 15
Project: vscrawler   File: RemoveStart.java   View Source Code Vote up 4 votes
@Override
protected String handle(String input, String second) {
    return StringUtils.removeStart(input, second);
}
 
Example 16
Project: xm-commons   File: XmLepScriptConfigServerResourceLoader.java   View Source Code Vote up 2 votes
/**
 * Get LEP script resource.
 *
 * @param location {@code /config/tenant/{tenant-key}/{ms-name}/lep/a/b/c/SomeScript.groovy}
 * @return the LEP script resource
 */
@Override
public Resource getResource(String location) {
    String cfgPath = StringUtils.removeStart(location, XM_MS_CONFIG_URL_PREFIX);
    return scriptResources.getOrDefault(cfgPath, XmLepScriptResource.nonExist());
}
 
Example 17
Project: bootstrap   File: AuthorizingFilter.java   View Source Code Vote up 2 votes
/**
 * Return the full request without query and without context path. Servlet path is kept. The returned path does not
 * starts with '/'.
 */
private String getFullRequest(final HttpServletRequest httpRequest) {
	return StringUtils.removeStart(httpRequest.getRequestURI().substring(this.getServletContext().getContextPath().length()), "/");
}
 
Example 18
Project: yadaframework   File: YadaSql.java   View Source Code Vote up 2 votes
/**
 * Returns the "where" section of the query, not starting with "where"
 * @return
 */
public String getWhere() {
	return StringUtils.removeStart(whereConditions.toString(), "where ");
}