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

The following are Jave code examples for showing how to use removeEnd() 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: plugin-km-confluence   File: ConfluencePluginResource.java   View Source Code Vote up 6 votes
/**
 * Map API JSON Space and history values to a bean.
 */
private Space toSpace(final String baseUrl, final Map<String, Object> spaceRaw, final String history, final CurlProcessor processor)
		throws MalformedURLException {
	final Space space = toSpaceLight(spaceRaw);
	final String hostUrl = StringUtils.removeEnd(baseUrl, new java.net.URL(baseUrl).getPath());

	// Check the activity if available
	final Matcher matcher = ACTIVITY_PATTERN.matcher(StringUtils.defaultString(history));
	if (matcher.find()) {
		// Activity has been found
		final SpaceActivity activity = new SpaceActivity();
		getAvatar(processor, activity, hostUrl + matcher.group(1));
		activity.setAuthor(toSimpleUser(matcher.group(2), matcher.group(3)));
		activity.setPageUrl(hostUrl + matcher.group(4));
		activity.setPage(matcher.group(5));
		activity.setMoment(matcher.group(6));
		space.setActivity(activity);
	}
	return space;
}
 
Example 2
Project: plugin-km-confluence   File: ConfluencePluginResource.java   View Source Code Vote up 6 votes
/**
 * Validate the space configuration and return the corresponding details.
 * 
 * @param parameters
 *            the space parameters.
 * @return Space's details.
 */
protected Space validateSpace(final Map<String, String> parameters) throws IOException {
	final String baseUrl = StringUtils.removeEnd(parameters.get(PARAMETER_URL), "/");

	CurlRequest[] requests = null;

	try {
		// Validate the space key and get activity
		requests = validateSpaceInternal(parameters, "/rest/api/space/",
				"/plugins/recently-updated/changes.action?theme=social&pageSize=1&spaceKeys=");

		// Parse the space details
		final Map<String, Object> details = objectMapper.readValue(requests[0].getResponse(), TYPE_SPACE_REF);

		// Build the full space object
		return toSpace(baseUrl, details, requests[1].getResponse(), requests[0].getProcessor());
	} finally {
		// Close the processor
		closeQuietly(requests);
	}
}
 
Example 3
Project: plugin-km-confluence   File: ConfluencePluginResource.java   View Source Code Vote up 6 votes
/**
 * Validate the space configuration and return the corresponding details.
 */
protected CurlRequest[] validateSpaceInternal(final Map<String, String> parameters, final String... partialRequests) {
	final String url = StringUtils.removeEnd(parameters.get(PARAMETER_URL), "/");
	final String space = ObjectUtils.defaultIfNull(parameters.get(PARAMETER_SPACE), "0");
	final CurlRequest[] result = new CurlRequest[partialRequests.length];
	for (int i = 0; i < partialRequests.length; i++) {
		result[i] = new CurlRequest(HttpMethod.GET, url + partialRequests[i] + space, null);
		result[i].setSaveResponse(true);
	}

	// Prepare the sequence of HTTP requests to Confluence
	final ConfluenceCurlProcessor processor = new ConfluenceCurlProcessor();
	authenticate(parameters, processor);

	// Execute the requests
	processor.process(result);

	// Get the space if it exists
	if (result[0].getResponse() == null) {
		// Invalid couple PKEY and id
		throw new ValidationJsonException(PARAMETER_SPACE, "confluence-space", parameters.get(PARAMETER_SPACE));
	}
	return result;
}
 
Example 4
Project: springboot-shiro-cas-mybatis   File: RegexUtils.java   View Source Code Vote up 5 votes
/**
 * Concatenate all elements in the given collection to form a regex pattern.
 *
 * @param requiredValues  the required values
 * @param caseInsensitive the case insensitive
 * @return the pattern
 */
public static Pattern concatenate(final Collection<String> requiredValues, final boolean caseInsensitive) {
    final StringBuilder builder = new StringBuilder(requiredValues.size());
    for (final String requiredValue : requiredValues) {
        builder.append('(').append(requiredValue).append(")|");
    }
    final String pattern = StringUtils.removeEnd(builder.toString(), "|");
    if (isValidRegex(pattern)) {
        return Pattern.compile(pattern, caseInsensitive ? Pattern.CASE_INSENSITIVE : 0);
    }
    return null;
}
 
Example 5
Project: solo-spring   File: ArticleController.java   View Source Code Vote up 5 votes
/**
 * Gets the request author id from the specified request URI.
 *
 * @param requestURI
 *            the specified request URI
 * @return author id
 */
private static String getAuthorsArticlesPagedAuthorId(final String requestURI) {
	String authorIdAndPageNum = requestURI.substring((Latkes.getContextPath() + "/articles/authors/").length());

	if (authorIdAndPageNum.endsWith("/")) {
		authorIdAndPageNum = StringUtils.removeEnd(authorIdAndPageNum, "/");
	}

	return StringUtils.substringBefore(authorIdAndPageNum, "/");
}
 
Example 6
Project: TITAN   File: ValidatorUtil.java   View Source Code Vote up 5 votes
/**
 * @desc 根据BindingResult获取数据校验信息
 *
 * @author liuliang
 *
 * @param br
 * @return
 */
public static Result getValidResult(BindingResult br){
   	if(!br.hasErrors()){
   		 return ResultUtil.success(new Result());
   	}else{
   		List<FieldError> list = br.getFieldErrors();
   		StringBuilder sb = new StringBuilder();
   		for (FieldError e: list) {
   			sb.append(e.getField()).append(":").append(e.getDefaultMessage()).append(";");
   		}
   		String errorMessage = StringUtils.removeEnd(sb.toString(),";");
   		logger.error("参数异常,errorMessage:{}",errorMessage);
   		return ResultUtil.fail(ErrorCode.REQUEST_PARA_ERROR,errorMessage,new Result());
   	}
   }
 
Example 7
Project: aceql-http   File: StatementAnalyzer.java   View Source Code Vote up 5 votes
/**
 * Remove all trailing ";" from SQL command
 * 
 * @param sql
 *            the sql command
 * @return the sql command without the trailing ";"
 */
private String removeTrailingSemicolons(String sql) {
	sql = sql.trim();
	// Remove the trailing ";", there may be some blanks, so we always trim
	while (sql.endsWith(";")) {
		sql = StringUtils.removeEnd(sql, ";");
		sql = sql.trim();
	}
	return sql;
}
 
Example 8
Project: nixmash-blog   File: AdminPostsController.java   View Source Code Vote up 5 votes
private String cleanContentTailHtml(String content) {
    String[] tags = {"<p>\r\n</p>", "<p></p>", "<p><br></p>", "<br>"};
    String result = content;
    for (String t :
            tags) {
        result = StringUtils.removeEnd(result, t);
    }
    return result;

}
 
Example 9
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 10
Project: plugin-km-confluence   File: ConfluencePluginResource.java   View Source Code Vote up 5 votes
/**
 * Return a Jenkins's resource. Return <code>null</code> when the resource
 * is not found.
 */
protected String getConfluenceResource(final CurlProcessor processor, final String url, final String resource) {
	// Get the resource using the preempted authentication
	final CurlRequest request = new CurlRequest(HttpMethod.GET, StringUtils.removeEnd(url, "/") + resource, null);
	request.setSaveResponse(true);

	// Execute the requests
	processor.process(request);
	processor.close();
	return request.getResponse();
}
 
Example 11
Project: sling-org-apache-sling-testing-clients   File: SlingClient.java   View Source Code Vote up 5 votes
/**
 * Extracts the node from path
 *
 * @param path string containing the path
 * @return the node without parent path
 */
protected String getNodeNameFromPath(final String path) {
    // TODO define the output for all the cases (e.g. paths with trailing slash)
    final String normalizedPath = StringUtils.removeEnd(path, "/");  // remove trailing slash in case of folders
    final int pos = normalizedPath.lastIndexOf('/');
    if (pos != -1) {
        return normalizedPath.substring(pos + 1, normalizedPath.length());
    }
    return normalizedPath;
}
 
Example 12
Project: cas-server-4.2.1   File: RegexUtils.java   View Source Code Vote up 5 votes
/**
 * Concatenate all elements in the given collection to form a regex pattern.
 *
 * @param requiredValues  the required values
 * @param caseInsensitive the case insensitive
 * @return the pattern
 */
public static Pattern concatenate(final Collection<String> requiredValues, final boolean caseInsensitive) {
    final StringBuilder builder = new StringBuilder(requiredValues.size());
    for (final String requiredValue : requiredValues) {
        builder.append('(').append(requiredValue).append(")|");
    }
    final String pattern = StringUtils.removeEnd(builder.toString(), "|");
    if (isValidRegex(pattern)) {
        return Pattern.compile(pattern, caseInsensitive ? Pattern.CASE_INSENSITIVE : 0);
    }
    return null;
}
 
Example 13
Project: cyberduck   File: DefaultTemporaryFileServiceTest.java   View Source Code Vote up 5 votes
@Test
public void testCreateContainer() throws Exception {
    final String temp = StringUtils.removeEnd(System.getProperty("java.io.tmpdir"), File.separator);
    final String s = System.getProperty("file.separator");
    final Path file = new Path("/container", EnumSet.of(Path.Type.directory));
    file.attributes().setRegion("region");
    assertEquals(String.format("%s%su%sregion%scontainer", temp, s, s, s),
            new DefaultTemporaryFileService().create("u", file).getAbsolute());
}
 
Example 14
Project: cyberduck   File: DefaultTemporaryFileServiceTest.java   View Source Code Vote up 5 votes
@Test
public void testPathTooLong() {
    final String temp = StringUtils.removeEnd(System.getProperty("java.io.tmpdir"), File.separator);
    final String testPathDirectory = "/Lorem/ipsum/dolor/sit/amet/consetetur/sadipscing/elitr/sed/diam/nonumy/eirmod/tempor/invidunt/ut/labore/et/dolore/magna/aliquyam/erat/sed/diam/voluptua/At/vero/eos/et/accusam/et/justo/duo/dolores/et/ea/rebum/Stet/clita/kasd/gubergren/no/sea";
    final String testPathFile = "takimata.sanc";
    final String testPath = String.format("%s/%s", testPathDirectory, testPathFile);
    final String testPathMD5 = DigestUtils.md5Hex(testPathDirectory);

    final Path file = new Path(testPath, EnumSet.of(Path.Type.file));
    file.attributes().setVersionId("2");
    final Local local = new DefaultTemporaryFileService().create("UID", file);
    final String localFile = local.getAbsolute();
    assertNotEquals(String.format("%s/%s%s/2/%s", temp, "UID", testPathDirectory, testPathFile).replace('/', File.separatorChar), localFile);
    assertEquals(String.format("%s/%s/%s/2/%s", temp, "UID", testPathMD5, testPathFile).replace('/', File.separatorChar), localFile);
}
 
Example 15
Project: yadaframework   File: YadaConfiguration.java   View Source Code Vote up 5 votes
/**
 * Return the server address without a trailing slash. E.g. http://col.letturedametropolitana.it
 * @return
 */
public String getServerAddress() {
	if (serverAddress==null) {
		serverAddress = StringUtils.removeEnd(configuration.getString("config/paths/serverAddress", "serverAddressUnset"), "/");
	}
	return serverAddress;
}
 
Example 16
Project: bootstrap   File: Template.java   View Source Code Vote up 5 votes
/**
 * Find and check the next tag marker, validate the syntax, find the corresponding {@link Processor} and return the
 * corresponding context of this match.Is <code>null</code> when no tag has been found.
 */
private TagContext getNextTag(final Map<String, Processor<?>> tags, final int start, final int end) {
	final int nextTag = input.indexOf("{{", start);
	if (nextTag == -1 || nextTag >= end) {
		// End of template
		return null;
	}
	final int nextEndTag = input.indexOf("}}", nextTag);
	if (nextEndTag == -1 || nextEndTag >= end) {
		// Opening tag syntax
		throw new IllegalStateException("Invalid opening tag syntax '{{' without '}}' at position " + nextTag);
	}
	if (nextEndTag - nextTag > MAX_TAG_LENGTH) {
		// Too long tag
		throw new IllegalStateException(
				"Too long (max is " + MAX_TAG_LENGTH + " tag " + input.substring(nextTag + 2, nextTag + 30) + "...}} found at position " + start);
	}
	final String tag = input.substring(nextTag + 2, nextEndTag);
	final String tagClean = StringUtils.removeEnd(tag, "/");
	if (StringUtils.trimToEmpty(tagClean).length() == 0) {
		// Empty tag
		throw new IllegalStateException("Empty tag {{}} found at position " + start);
	}
	final Processor<?> processor = tags.get(tagClean);
	if (processor == null) {
		throw new IllegalStateException("Not mapped template tag {{" + tagClean + "}} found at position " + nextTag);
	}
	return new TagContext(nextTag, processor, tag, tagClean.length() == tag.length());
}
 
Example 17
Project: plugin-vm-vcloud   File: VCloudPluginResource.java   View Source Code Vote up 4 votes
@Override
public void execute(final int subscription, final VmOperation operation) throws Exception {
	final Map<String, String> parameters = subscriptionResource.getParametersNoCheck(subscription);
	final String vmUrl = "/vApp/vm-" + parameters.get(PARAMETER_VM);

	// First get VM state
	final VCloudVm vm = getVmDetails(parameters);
	final VmStatus status = vm.getStatus();

	// Get the right operation depending on the current state
	final VmOperation operationF = failSafeOperation(status, operation);
	if (operationF == null) {
		// Final operation is considered as useless
		log.info("Requested operation {} is marked as useless considering the status {} of vm {}", operation, status,
				parameters.get(PARAMETER_VM));
		return;
	}

	final String action = MapUtils.getObject(OPERATION_TO_VCLOUD, operationF, operationF.name().toLowerCase(Locale.ENGLISH));

	// Check if undeployment is requested to shutdown completely the VM
	if (operationF == VmOperation.SHUTDOWN || operationF == VmOperation.OFF) {
		// The requested operation needs the VM to be undeployed
		final String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><UndeployVAppParams xmlns=\"http://www.vmware.com/vcloud/v1.5\"><UndeployPowerAction>"
				+ action + "</UndeployPowerAction></UndeployVAppParams>";
		final String url = StringUtils.removeEnd(parameters.get(PARAMETER_API), "/");
		final CurlRequest request = new CurlRequest(HttpMethod.POST, url + vmUrl + "/action/undeploy", content,
				"Content-Type:application/vnd.vmware.vcloud.undeployVAppParams+xml");
		request.setSaveResponse(true);

		// Use the preempted authentication
		final VCloudCurlProcessor processor = new VCloudCurlProcessor();
		authenticate(parameters, processor);

		// Execute the request
		processor.process(request);
		processor.close();

		checkSchedulerResponse(request.getResponse());
	} else {
		// Operation does not require to undeploy the VM
		checkSchedulerResponse(authenticateAndExecute(parameters, HttpMethod.POST, vmUrl + "/power/action/" + action));
	}
}
 
Example 18
Project: pprxmtr   File: GifGeneratorHandler.java   View Source Code Vote up 4 votes
@Override
public ApiGatewayResponse handleRequest(SNSEvent input, Context context) {
	LOG.info("Loading Gif Generator Java Lambda handler.");

	ObjectMapper mapper = new ObjectMapper();

	if (CollectionUtils.isNotEmpty(input.getRecords())) {
		try {
			JsonNode json = mapper.readTree(input.getRecords().get(0).getSNS().getMessage());
			byte[] gif = ArrayUtils.EMPTY_BYTE_ARRAY;

			if (json.has("emojiUrl")) {
				HttpClient client = HttpClientBuilder.create().build();
				String emojiUrl = json.get("emojiUrl").asText();
				HttpGet getImageRequest = new HttpGet(emojiUrl);
				HttpResponse getImageResponse = client.execute(getImageRequest);
				int getImageStatus = getImageResponse.getStatusLine().getStatusCode();
				LOG.info("Get image status: {}.", getImageStatus);

				if (StringUtils.contains(getImageResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue(), "image")) {
					byte[] imageFile = IOUtils.toByteArray(getImageResponse.getEntity().getContent());
					gif = GifGenerator.generateGif(imageFile);
				} else {
					LOG.error("Given image URL did not return an image according to mime type!");
				}
			}

			if (ArrayUtils.isNotEmpty(gif)) {
				LOG.info("Gif created successfully, storing in S3.");
				String emoji = json.get("text").asText();
				String emojiName = StringUtils.removeEnd(StringUtils.removeStart(StringUtils.strip(emoji), ":"), ":");
				emojiName = emojiName.replaceAll("ä", "a").replaceAll("ö", "o").replaceAll("å", "o");

				InputStream is = new ByteArrayInputStream(gif);
				ObjectMetadata metadata = new ObjectMetadata();
				metadata.setContentLength(gif.length);
				metadata.setContentType("image/gif");

				if (UrlValidator.getInstance().isValid(emojiName)) {
					emojiName = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('0', '9'))
							.retainFrom(StringUtils.substringAfterLast(emojiName, "/"));
				}

				String filenamePrefix = emojiName + "_approximated_";
				if (!S3.fileExistsInBucket(filenamePrefix)) {
					S3.storeFileInBucket(filenamePrefix + System.currentTimeMillis() + ".gif", is, metadata);
				}

				LOG.info("Image stored in S3, publishing to topic s3-file-ready");
				SNS.publish("s3-file-ready", mapper.writeValueAsString(json)).get();
			} else {
				LOG.error("Gif generator returned an empty byte array, sending error response");
				SNS.publish("gif-generator-error", mapper.writeValueAsString(json)).get();
			}
		} catch (IOException | InterruptedException | ExecutionException e) {
			LOG.error("Exception occured when creating GIF.", e);
		}
	}

	Response responseBody = new Response("pprxmtr-gif-generator called.", new HashMap<>());
	return ApiGatewayResponse.builder().setStatusCode(200).setObjectBody(responseBody).build();
}
 
Example 19
Project: vscrawler   File: RemoveEnd.java   View Source Code Vote up 4 votes
@Override
protected String handle(String input, String second) {
    return StringUtils.removeEnd(input, second);
}
 
Example 20
Project: sponge   File: DefaultInteractiveMode.java   View Source Code Vote up 4 votes
protected boolean iteration(InteractiveModeConsole reader, ScriptKnowledgeBaseInterpreter scriptInterpreter) throws IOException {
    StringBuffer commandBuffer = new StringBuffer();
    while (true) {
        if (!engine.isRunning()) {
            return false;
        }

        String command = null;
        try {
            command = reader.readLine();
        } catch (IOException e) {
            handleException("readLine", e);
            return false;
        }

        if (command == null) {
            return false;
        }

        command = StringUtils.stripEnd(command, null);

        if (StringUtils.equalsAny(command.trim(), InteractiveModeConstants.EXIT_COMMAND, InteractiveModeConstants.QUIT_COMMAND)) {
            return false;
        }

        boolean isMultiLineStatement = command.endsWith(InteractiveModeConstants.LINE_BREAK);
        if (isMultiLineStatement) {
            command = StringUtils.removeEnd(command, InteractiveModeConstants.LINE_BREAK);
        }

        commandBuffer.append(command);

        if (isMultiLineStatement) {
            commandBuffer.append(System.lineSeparator());
        } else {
            break;
        }
    }

    if (engine.isRunning()) {
        scriptInterpreter.eval(commandBuffer.toString());
        return true;
    } else {
        return false;
    }
}