下面列出了org.apache.commons.lang3.StringUtils#removeEnd ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static List<Account> loadNemesisAccountsFromBootstrap(NetworkType networkType) {
String bootstrapFolder = System.getenv("CATAPULT_SERVICE_BOOTSTRAP");
if (StringUtils.isBlank(bootstrapFolder)) {
bootstrapFolder = "../../catapult-service-bootstrap";
}
File generatedAddressesOption = new File(
StringUtils.removeEnd(bootstrapFolder, "/") + "/build/generated-addresses/addresses.yaml");
if (!generatedAddressesOption.exists()) {
throw new IllegalArgumentException("File " + generatedAddressesOption.getAbsolutePath() + " doesn't exist");
}
if (generatedAddressesOption.isDirectory()) {
throw new IllegalArgumentException(
"File " + generatedAddressesOption.getAbsolutePath() + " is a directory!");
}
return loadNemesisAccountsFromBootstrap(networkType, generatedAddressesOption);
}
/**
* Composites partial url to full http url.
*
* @param partUrls partial urls must not be empty
* @return full url
*/
public static String compositeHttpUrl(@NonNull String... partUrls) {
Assert.notEmpty(partUrls, "Partial url must not be blank");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < partUrls.length; i++) {
String partUrl = partUrls[i];
if (StringUtils.isBlank(partUrl)) {
continue;
}
partUrl = StringUtils.removeStart(partUrl, URL_SEPARATOR);
partUrl = StringUtils.removeEnd(partUrl, URL_SEPARATOR);
if (i != 0) {
builder.append(URL_SEPARATOR);
}
builder.append(partUrl);
}
return builder.toString();
}
private String processedPattern() {
if (this.processedPattern == null) {
String[] parts = FilenameUtils.separatorsToUnix(pattern).split("/");
StringBuilder sb = new StringBuilder();
for (String part : parts) {
part = escape(part);
if ("**".equals(part)) {
sb.append(part.replace("**", "([^/]*/)*"));
} else if (part.contains("*")) {
sb.append(part.replace("*", "[^/]*"));
sb.append("/");
} else {
sb.append(part);
sb.append("/");
}
}
this.processedPattern = StringUtils.removeEnd(sb.toString(), "/");
}
return this.processedPattern;
}
private void fetchGroupConfig(final ConfigGroupEnum... groups) throws SoulException {
StringBuilder params = new StringBuilder();
for (ConfigGroupEnum groupKey : groups) {
params.append("groupKeys").append("=").append(groupKey.name()).append("&");
}
SoulException ex = null;
for (String server : serverList) {
String url = server + "/configs/fetch?" + StringUtils.removeEnd(params.toString(), "&");
log.info("request configs: [{}]", url);
String json = this.httpClient.getForObject(url, String.class);
log.info("get latest configs: [{}]", json);
updateCacheWithJson(json);
return;
}
if (ex != null) {
throw ex;
}
}
public String toSrcPath(String packageName, String basePath) {
packageName = packageName.replace(invokerPackage, ""); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (basePath != null && basePath.length() > 0) {
basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separator; // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
}
// Trim prefix file separators from package path
String packagePath = StringUtils.removeStart(
// Replace period, backslash, forward slash with file separator in package name
packageName.replaceAll("[\\.\\\\/]", Matcher.quoteReplacement("/")),
File.separator
);
// Trim trailing file separators from the overall path
return StringUtils.removeEnd(basePath + packagePath, File.separator);
}
public static boolean isURLEqual(String url1, String url2) {
url1 = StringUtils.replace(url1, "https://", "http://");
url2 = StringUtils.replace(url2, "https://", "http://");
url1 = StringUtils.removeEnd(url1, "/");
url2 = StringUtils.removeEnd(url2, "/");
url1 = url1.contains("?") ? url1.substring(0, url1.indexOf("?")) : url1;
url2 = url2.contains("?") ? url2.substring(0, url2.indexOf("?")) : url2;
if (url1.contains(SpecialKeywords.IGNORE) || url2.contains(SpecialKeywords.IGNORE)) {
String[] urlAr1 = url1.split("/");
String[] urlAr2 = url2.split("/");
return compareWithIgnore(urlAr1, urlAr2);
}
return url1.equals(url2);
}
/**
* Format a grade using the locale
*
* @param grade - string representation of a grade
* @param locale
* @return
*/
private static String formatGradeForLocale(final String grade, final Locale locale) {
if (StringUtils.isBlank(grade)) {
return "";
}
String s;
try {
final DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(locale);
final Double d = df.parse(grade).doubleValue();
df.setMinimumFractionDigits(0);
df.setGroupingUsed(false);
s = df.format(d);
} catch (final NumberFormatException | ParseException e) {
log.warn("Bad format, returning original string: {}", grade);
s = grade;
}
return StringUtils.removeEnd(s, ".0");
}
private static String hash(String string) {
byte[] shaArray = DigestUtils.sha(string);
byte[] encodedArray = Base64.getEncoder().encode(shaArray);
String returnValue = new String(encodedArray);
returnValue = StringUtils.removeEnd(returnValue, "\r\n");
return returnValue.replaceAll("=", "").replaceAll("/", "-").replaceAll("\\+", "\\_");
}
private String getPasswordResetLink(String linkPattern, String username, String token) {
try {
String baseUrl = configService.getValue(ConfigValue.SystemUrl);
String link = linkPattern.replace("{token}", URLEncoder.encode(token, "UTF-8"))
.replace("{username}", URLEncoder.encode(username, "UTF-8"));
if (StringUtils.startsWithIgnoreCase(link, "http://") || StringUtils.startsWithIgnoreCase(link, "https://")) {
return link;
} else {
return StringUtils.removeEnd(baseUrl, "/") + "/" + StringUtils.removeStart(link, "/");
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public String getRegionTextFromLines() {
String textAll = "";
for (TextLineType l : getTextLine()) {
TrpTextLineType trp_l = (TrpTextLineType) l;
textAll += trp_l.getUnicodeText()+System.lineSeparator();
}
textAll = StringUtils.removeEnd(textAll, System.lineSeparator());
return textAll;
}
public String getRepoName(final String remoteUrlString) throws MalformedURLException {
final String[] pieces = remoteUrlString.split("[/:]");
if (pieces.length >= 2) {
final String organization = pieces[pieces.length - 2];
final String repo = pieces[pieces.length - 1];
final String name = String.format("%s/%s", organization, repo);
return StringUtils.removeEnd(StringUtils.removeStart(name, "/"), ".git");
} else {
throw new MalformedURLException("Failed to extract repository name from url. Not logging url for security.");
}
}
public List<YarnLockEntryId> parseMultipleEntryLine(String line) {
List<YarnLockEntryId> ids = new ArrayList<>();
String[] entries = line.split(",");
for (String entryRaw : entries) {
String entryNoColon = StringUtils.removeEnd(entryRaw.trim(), ":");
String entryNoColonOrQuotes = removeWrappingQuotes(entryNoColon);
YarnLockEntryId entry = parseSingleEntry(entryNoColonOrQuotes);
ids.add(entry);
}
return ids;
}
/**
* 处理path,连续的/去重,确保以/开始
*
* @param path path
* @return /path
*/
private String formatPath(String path) {
if (StringUtils.isBlank(path)) return path;
path = path.replaceAll("[/]+", "/");
path = StringUtils.removeEnd(path, "/");
return path.startsWith("/") ? path : "/" + path;
}
/**
* Ensures the string contain suffix.
*
* @param string string must not be blank
* @param suffix suffix must not be blank
* @return string contain suffix specified
*/
@NonNull
public static String ensureSuffix(@NonNull String string, @NonNull String suffix) {
Assert.hasText(string, "String must not be blank");
Assert.hasText(suffix, "Suffix must not be blank");
return StringUtils.removeEnd(string, suffix) + suffix;
}
private String inExpression() {
if (this.fromToIn != null && this.parentPartitionTree.partitionType.isList()) {
String tmp = this.fromToIn.substring("FOR VALUES IN (".length());
String fromTo[] = tmp.split(" TO ");
String in = fromTo[0];
in = StringUtils.removeStart(in, "(");
in = StringUtils.removeEnd(in, ")");
return in;
} else {
return null;
}
}
public String argsToString(List<String> args, Object[] params, Map<String, Integer> mapper) {
if (args.size() == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (String arg : args) {
Integer index = mapper.get(arg);
if (index != null) {
sb.append(String.format("%s=%s; ", arg, params[index].toString()));
}
}
return StringUtils.removeEnd(sb.toString(), "; ");
}
public NullLocal(final String parent, final String name) {
super(StringUtils.removeEnd(parent, File.separator), name);
}
private String trimSlashes(String path) {
return StringUtils.removeEnd(StringUtils.removeStart(path, "/"), "/");
}
private String createCheckoutRequest(PaymentSpecification spec) throws Exception {
TicketReservation reservation = ticketReservationRepository.findReservationById(spec.getReservationId());
String eventName = spec.getEvent().getShortName();
String baseUrl = StringUtils.removeEnd(configurationManager.getFor(ConfigurationKeys.BASE_URL, ConfigurationLevel.event(spec.getEvent())).getRequiredValue(), "/");
String bookUrl = baseUrl+"/event/" + eventName + "/reservation/" + spec.getReservationId() + "/payment/paypal/" + URL_PLACEHOLDER;
String hmac = computeHMAC(spec.getCustomerName(), spec.getEmail(), spec.getBillingAddress(), spec.getEvent());
UriComponentsBuilder bookUrlBuilder = UriComponentsBuilder.fromUriString(bookUrl)
.queryParam("hmac", hmac);
String finalUrl = bookUrlBuilder.toUriString();
ApplicationContext applicationContext = new ApplicationContext()
.landingPage("BILLING")
.cancelUrl(finalUrl.replace(URL_PLACEHOLDER, "cancel"))
.returnUrl(finalUrl.replace(URL_PLACEHOLDER, "confirm"))
.userAction("CONTINUE")
.shippingPreference("NO_SHIPPING");
OrderRequest orderRequest = new OrderRequest()
.applicationContext(applicationContext)
.checkoutPaymentIntent("CAPTURE")
.purchaseUnits(List.of(new PurchaseUnitRequest().amountWithBreakdown(new AmountWithBreakdown().currencyCode(spec.getCurrencyCode()).value(spec.getOrderSummary().getTotalPrice()))));
OrdersCreateRequest request = new OrdersCreateRequest().requestBody(orderRequest);
request.header("prefer","return=representation");
request.header("PayPal-Request-Id", reservation.getId());
HttpResponse<Order> response = getClient(spec.getEvent()).execute(request);
if(HttpUtils.statusCodeIsSuccessful(response.statusCode())) {
Order order = response.result();
var status = order.status();
if("APPROVED".equals(status) || "COMPLETED".equals(status)) {
if("APPROVED".equals(status)) {
saveToken(reservation.getId(), spec.getEvent(), new PayPalToken(order.payer().payerId(), order.id(), hmac));
}
return "/event/"+spec.getEvent().getShortName()+"/reservation/"+spec.getReservationId();
} else if("CREATED".equals(status)) {
//add 15 minutes of validity in case the paypal flow is slow
ticketReservationRepository.updateValidity(spec.getReservationId(), DateUtils.addMinutes(reservation.getValidity(), 15));
return order.links().stream().filter(l -> l.rel().equals("approve")).map(LinkDescription::href).findFirst().orElseThrow();
}
}
throw new IllegalStateException();
}
/**
* Experimental method for trying out the loading of complex_annotation doc type
*
* @param opts
* @throws Exception
*/
@CLIMethod("--solr-load-complex-annotations")
public void experimentalLoadComplexAnnotationSolr(Opts opts) throws Exception {
// Check to see if the global url has been set.
String url = sortOutSolrURL(globalSolrURL);
// Only proceed if our environment was well-defined.
if( legoCatalogs == null || legoFiles == null || legoCatalogs.isEmpty() || legoFiles.isEmpty() ){
LOG.warn("Lego environment not well defined--skipping.");
}else{
// Ready the environment for every pass.
ParserWrapper pw = new ParserWrapper();
// Add all of the catalogs.
for( File legoCatalog : legoCatalogs ){
pw.addIRIMapper(new CatalogXmlIRIMapper(legoCatalog));
}
OWLOntologyManager manager = pw.getManager();
OWLReasonerFactory reasonerFactory = new ElkReasonerFactory();
// Actual loading--iterate over our list and load individually.
for( File legoFile : legoFiles ){
String fname = legoFile.getName();
OWLReasoner currentReasoner = null;
OWLOntology ontology = null;
// TODO: Temp cover for missing group labels and IDs.
//String agID = legoFile.getCanonicalPath();
String agLabel = StringUtils.removeEnd(fname, ".owl");
String agID = new String(agLabel);
try {
ontology = pw.parseOWL(IRI.create(legoFile));
currentReasoner = reasonerFactory.createReasoner(ontology);
// Some sanity checks--some of the genereated ones are problematic.
boolean consistent = currentReasoner.isConsistent();
if( consistent == false ){
LOG.info("Skip since inconsistent: " + fname);
continue;
}
Set<OWLClass> unsatisfiable = currentReasoner.getUnsatisfiableClasses().getEntitiesMinusBottom();
// TODO - make configurable to allow fail fast
if (unsatisfiable.isEmpty() == false) {
LOG.info("Skip since unsatisfiable: " + fname);
continue;
}
Set<OWLNamedIndividual> individuals = ontology.getIndividualsInSignature();
Set<OWLAnnotation> modelAnnotations = ontology.getAnnotations();
OWLGraphWrapper currentGraph = new OWLGraphWrapper(ontology);
try {
LOG.info("Trying complex annotation load of: " + fname);
ComplexAnnotationSolrDocumentLoader loader =
new ComplexAnnotationSolrDocumentLoader(url, currentGraph, currentReasoner, individuals, modelAnnotations, agID, agLabel, fname);
loader.load();
} catch (SolrServerException e) {
LOG.info("Complex annotation load of " + fname + " at " + url + " failed!");
e.printStackTrace();
System.exit(1);
}
} finally {
// Cleanup reasoner and ontology.
if (currentReasoner != null) {
currentReasoner.dispose();
}
if (ontology != null) {
manager.removeOntology(ontology);
}
}
}
}
}