Search in sources :

Example 1 with StringUtils.removeEnd

use of org.apache.commons.lang3.StringUtils.removeEnd in project cxf by apache.

the class OpenApiCustomizer method customize.

public OpenAPIConfiguration customize(final OpenAPIConfiguration configuration) {
    if (configuration == null) {
        return configuration;
    }
    if (dynamicBasePath) {
        final MessageContext ctx = createMessageContext();
        // If the JAX-RS application with custom path is defined, it might be present twice, in the
        // request URI as well as in each resource operation URI. To properly represent server URL,
        // the application path should be removed from it.
        final String url = StringUtils.removeEnd(StringUtils.substringBeforeLast(ctx.getUriInfo().getRequestUri().toString(), "/"), applicationPath);
        final Collection<Server> servers = configuration.getOpenAPI().getServers();
        if (servers == null || servers.stream().noneMatch(s -> s.getUrl().equalsIgnoreCase(url))) {
            configuration.getOpenAPI().setServers(Collections.singletonList(new Server().url(url)));
        }
    }
    return configuration;
}
Also used : URL(java.net.URL) Parameter(io.swagger.v3.oas.models.parameters.Parameter) OpenAPIConfiguration(io.swagger.v3.oas.integration.api.OpenAPIConfiguration) HashMap(java.util.HashMap) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) JAXRSUtils(org.apache.cxf.jaxrs.utils.JAXRSUtils) Operation(io.swagger.v3.oas.models.Operation) StringUtils(org.apache.commons.lang3.StringUtils) JavaDocProvider(org.apache.cxf.jaxrs.model.doc.JavaDocProvider) ArrayList(java.util.ArrayList) Pair(org.apache.commons.lang3.tuple.Pair) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) ResourceUtils(org.apache.cxf.jaxrs.utils.ResourceUtils) Tag(io.swagger.v3.oas.models.tags.Tag) DocumentationProvider(org.apache.cxf.jaxrs.model.doc.DocumentationProvider) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Collection(java.util.Collection) ApplicationPath(javax.ws.rs.ApplicationPath) List(java.util.List) HttpMethod(io.swagger.v3.oas.models.PathItem.HttpMethod) Server(io.swagger.v3.oas.models.servers.Server) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Collections(java.util.Collections) ApplicationInfo(org.apache.cxf.jaxrs.model.ApplicationInfo) Server(io.swagger.v3.oas.models.servers.Server) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext)

Example 2 with StringUtils.removeEnd

use of org.apache.commons.lang3.StringUtils.removeEnd in project alf.io by alfio-event.

the class PaypalManager method createCheckoutRequest.

public String createCheckoutRequest(Event event, String reservationId, OrderSummary orderSummary, CustomerName customerName, String email, String billingAddress, Locale locale, boolean postponeAssignment, boolean invoiceRequested) throws Exception {
    APIContext apiContext = getApiContext(event);
    Optional<String> experienceProfileId = getOrCreateWebProfile(event, locale, apiContext);
    List<Transaction> transactions = buildPaymentDetails(event, orderSummary, reservationId, locale);
    String eventName = event.getShortName();
    Payer payer = new Payer();
    payer.setPaymentMethod("paypal");
    Payment payment = new Payment();
    payment.setIntent("sale");
    payment.setPayer(payer);
    payment.setTransactions(transactions);
    RedirectUrls redirectUrls = new RedirectUrls();
    String baseUrl = StringUtils.removeEnd(configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), ConfigurationKeys.BASE_URL)), "/");
    String bookUrl = baseUrl + "/event/" + eventName + "/reservation/" + reservationId + "/book";
    UriComponentsBuilder bookUrlBuilder = UriComponentsBuilder.fromUriString(bookUrl).queryParam("fullName", customerName.getFullName()).queryParam("firstName", customerName.getFirstName()).queryParam("lastName", customerName.getLastName()).queryParam("email", email).queryParam("billingAddress", billingAddress).queryParam("postponeAssignment", postponeAssignment).queryParam("invoiceRequested", invoiceRequested).queryParam("hmac", computeHMAC(customerName, email, billingAddress, event));
    String finalUrl = bookUrlBuilder.toUriString();
    redirectUrls.setCancelUrl(finalUrl + "&paypal-cancel=true");
    redirectUrls.setReturnUrl(finalUrl + "&paypal-success=true");
    payment.setRedirectUrls(redirectUrls);
    experienceProfileId.ifPresent(payment::setExperienceProfileId);
    Payment createdPayment = payment.create(apiContext);
    TicketReservation reservation = ticketReservationRepository.findReservationById(reservationId);
    // add 15 minutes of validity in case the paypal flow is slow
    ticketReservationRepository.updateValidity(reservationId, DateUtils.addMinutes(reservation.getValidity(), 15));
    if (!"created".equals(createdPayment.getState())) {
        throw new Exception(createdPayment.getFailureReason());
    }
    // extract url for approval
    return createdPayment.getLinks().stream().filter(l -> "approval_url".equals(l.getRel())).findFirst().map(Links::getHref).orElseThrow(IllegalStateException::new);
}
Also used : UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) java.util(java.util) MessageDigest(java.security.MessageDigest) TicketReservationRepository(alfio.repository.TicketReservationRepository) ConfigurationManager(alfio.manager.system.ConfigurationManager) Cache(com.github.benmanes.caffeine.cache.Cache) StringUtils(org.apache.commons.lang3.StringUtils) Supplier(java.util.function.Supplier) com.paypal.api.payments(com.paypal.api.payments) BigDecimal(java.math.BigDecimal) MonetaryUtil.formatCents(alfio.util.MonetaryUtil.formatCents) Pair(org.apache.commons.lang3.tuple.Pair) APIContext(com.paypal.base.rest.APIContext) HmacAlgorithms(org.apache.commons.codec.digest.HmacAlgorithms) MessageSource(org.springframework.context.MessageSource) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) TicketRepository(alfio.repository.TicketRepository) HmacUtils(org.apache.commons.codec.digest.HmacUtils) Currency(com.paypal.api.payments.Currency) FeeCalculator(alfio.manager.support.FeeCalculator) PayPalRESTException(com.paypal.base.rest.PayPalRESTException) StandardCharsets(java.nio.charset.StandardCharsets) DateUtils(org.apache.commons.lang3.time.DateUtils) TimeUnit(java.util.concurrent.TimeUnit) Component(org.springframework.stereotype.Component) MonetaryUtil(alfio.util.MonetaryUtil) alfio.model(alfio.model) Configuration(alfio.model.system.Configuration) Log4j2(lombok.extern.log4j.Log4j2) Event(alfio.model.Event) AllArgsConstructor(lombok.AllArgsConstructor) DigestUtils(org.apache.commons.codec.digest.DigestUtils) ConfigurationKeys(alfio.model.system.ConfigurationKeys) PayPalRESTException(com.paypal.base.rest.PayPalRESTException) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) APIContext(com.paypal.base.rest.APIContext)

Example 3 with StringUtils.removeEnd

use of org.apache.commons.lang3.StringUtils.removeEnd in project dropwizard by dropwizard.

the class DefaultLoggingFactoryTest method testConfigure.

@Test
public void testConfigure() throws Exception {
    final File newAppLog = folder.newFile("example-new-app.log");
    final File newAppNotAdditiveLog = folder.newFile("example-new-app-not-additive.log");
    final File defaultLog = folder.newFile("example.log");
    final StrSubstitutor substitutor = new StrSubstitutor(ImmutableMap.of("new_app", StringUtils.removeEnd(newAppLog.getAbsolutePath(), ".log"), "new_app_not_additive", StringUtils.removeEnd(newAppNotAdditiveLog.getAbsolutePath(), ".log"), "default", StringUtils.removeEnd(defaultLog.getAbsolutePath(), ".log")));
    final String configPath = Resources.getResource("yaml/logging_advanced.yml").getFile();
    final DefaultLoggingFactory config = factory.build(new SubstitutingSourceProvider(new FileConfigurationSourceProvider(), substitutor), configPath);
    config.configure(new MetricRegistry(), "test-logger");
    LoggerFactory.getLogger("com.example.app").debug("Application debug log");
    LoggerFactory.getLogger("com.example.app").info("Application log");
    LoggerFactory.getLogger("com.example.newApp").debug("New application debug log");
    LoggerFactory.getLogger("com.example.newApp").info("New application info log");
    LoggerFactory.getLogger("com.example.legacyApp").debug("Legacy application debug log");
    LoggerFactory.getLogger("com.example.legacyApp").info("Legacy application info log");
    LoggerFactory.getLogger("com.example.notAdditive").debug("Not additive application debug log");
    LoggerFactory.getLogger("com.example.notAdditive").info("Not additive application info log");
    config.stop();
    assertThat(Files.readLines(defaultLog, StandardCharsets.UTF_8)).containsOnly("INFO  com.example.app: Application log", "DEBUG com.example.newApp: New application debug log", "INFO  com.example.newApp: New application info log", "DEBUG com.example.legacyApp: Legacy application debug log", "INFO  com.example.legacyApp: Legacy application info log");
    assertThat(Files.readLines(newAppLog, StandardCharsets.UTF_8)).containsOnly("DEBUG com.example.newApp: New application debug log", "INFO  com.example.newApp: New application info log");
    assertThat(Files.readLines(newAppNotAdditiveLog, StandardCharsets.UTF_8)).containsOnly("DEBUG com.example.notAdditive: Not additive application debug log", "INFO  com.example.notAdditive: Not additive application info log");
}
Also used : SubstitutingSourceProvider(io.dropwizard.configuration.SubstitutingSourceProvider) StrSubstitutor(org.apache.commons.lang3.text.StrSubstitutor) MetricRegistry(com.codahale.metrics.MetricRegistry) File(java.io.File) FileConfigurationSourceProvider(io.dropwizard.configuration.FileConfigurationSourceProvider) Test(org.junit.Test)

Example 4 with StringUtils.removeEnd

use of org.apache.commons.lang3.StringUtils.removeEnd in project oap by oaplatform.

the class InfluxDBReporter method aggregate.

private <T extends Metric> SortedMap<String, SortedMap<String, T>> aggregate(SortedMap<String, T> metrics) {
    final SortedMap<String, SortedMap<String, T>> result = new TreeMap<>();
    for (final Map.Entry<String, T> entry : metrics.entrySet()) {
        final Optional<Pair<Pattern, Matcher>> m = aggregates.stream().map(a -> __(a, a.matcher(entry.getKey()))).filter(p -> p._2.find()).findAny();
        if (m.isPresent()) {
            final Matcher matcher = m.get()._2;
            if (matcher.groupCount() != 2) {
                throw new IllegalArgumentException("Wrong reporter pattern '" + m.get()._1.pattern() + "' or input '" + entry.getKey() + "'");
            }
            final String field = matcher.group(1).substring(1);
            final String tags = matcher.group(2);
            final String point = StringUtils.removeEnd(entry.getKey(), matcher.group(1) + tags) + tags;
            final SortedMap<String, T> map = result.computeIfAbsent(point, (p) -> new TreeMap<>());
            map.put(field, entry.getValue());
        } else {
            final SortedMap<String, T> map = new TreeMap<>();
            map.put("value", entry.getValue());
            result.put(entry.getKey(), map);
        }
    }
    return result;
}
Also used : Pair(oap.util.Pair) Histogram(com.codahale.metrics.Histogram) SneakyThrows(lombok.SneakyThrows) DateTimeUtils(org.joda.time.DateTimeUtils) LoggerFactory(org.slf4j.LoggerFactory) Pair.__(oap.util.Pair.__) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) InterruptedIOException(java.io.InterruptedIOException) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Meter(com.codahale.metrics.Meter) SocketException(java.net.SocketException) Matcher(java.util.regex.Matcher) Map(java.util.Map) Counter(com.codahale.metrics.Counter) BiConsumer(java.util.function.BiConsumer) MetricFilter(com.codahale.metrics.MetricFilter) Stream(oap.util.Stream) MetricRegistry(com.codahale.metrics.MetricRegistry) BatchPoints(org.influxdb.dto.BatchPoints) Logger(org.slf4j.Logger) InfluxDBFactory(org.influxdb.InfluxDBFactory) Collection(java.util.Collection) ScheduledReporter(com.codahale.metrics.ScheduledReporter) lombok.val(lombok.val) Metric(com.codahale.metrics.Metric) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Field(java.lang.reflect.Field) TimeUnit(java.util.concurrent.TimeUnit) Collectors.toList(java.util.stream.Collectors.toList) OkHttpClient(okhttp3.OkHttpClient) TreeMap(java.util.TreeMap) Modifier(java.lang.reflect.Modifier) Timer(com.codahale.metrics.Timer) Optional(java.util.Optional) Point(org.influxdb.dto.Point) Gauge(com.codahale.metrics.Gauge) InfluxDB(org.influxdb.InfluxDB) Pattern(java.util.regex.Pattern) Throwables(oap.util.Throwables) SortedMap(java.util.SortedMap) Matcher(java.util.regex.Matcher) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap) Pair(oap.util.Pair)

Example 5 with StringUtils.removeEnd

use of org.apache.commons.lang3.StringUtils.removeEnd in project syndesis by syndesisio.

the class HttpConnectorVerifierExtension method verify.

@SuppressWarnings("PMD.UseStringBufferForStringAppends")
@Override
public Result verify(Scope scope, Map<String, Object> parameters) {
    final Map<String, Object> options = new HashMap<>(parameters);
    String baseUrl = (String) options.remove("baseUrl");
    String uriScheme = StringHelper.before(baseUrl, "://");
    if (ObjectHelper.isNotEmpty(uriScheme) && !ObjectHelper.equal(supportedScheme, uriScheme)) {
        return ResultBuilder.withScope(scope).error(ResultErrorBuilder.withCode("unsupported_scheme").description("Unsupported scheme: " + uriScheme).parameterKey("baseUrl").build()).build();
    }
    if (ObjectHelper.isEmpty(uriScheme)) {
        baseUrl = supportedScheme + "://" + baseUrl;
    }
    String path = (String) options.remove("path");
    if (ObjectHelper.isNotEmpty(path)) {
        if (path.charAt(0) != '/') {
            path = "/" + path;
        }
        options.put("httpUri", StringUtils.removeEnd(baseUrl, "/") + path);
    } else {
        options.put("httpUri", baseUrl);
    }
    Component component = getCamelContext().getComponent(this.componentScheme);
    if (component == null) {
        return ResultBuilder.withScope(scope).error(ResultErrorBuilder.withCode(VerificationError.StandardCode.UNSUPPORTED_COMPONENT).description("Unsupported component " + this.componentScheme).build()).build();
    }
    return component.getExtension(ComponentVerifierExtension.class).map(extension -> extension.verify(scope, options)).orElseGet(() -> ResultBuilder.unsupported().build());
}
Also used : CamelContext(org.apache.camel.CamelContext) Map(java.util.Map) DefaultComponentVerifierExtension(org.apache.camel.component.extension.verifier.DefaultComponentVerifierExtension) ObjectHelper(org.apache.camel.util.ObjectHelper) HashMap(java.util.HashMap) Component(org.apache.camel.Component) ComponentVerifierExtension(org.apache.camel.component.extension.ComponentVerifierExtension) ResultBuilder(org.apache.camel.component.extension.verifier.ResultBuilder) ResultErrorBuilder(org.apache.camel.component.extension.verifier.ResultErrorBuilder) StringHelper(org.apache.camel.util.StringHelper) StringUtils(org.apache.commons.lang3.StringUtils) HashMap(java.util.HashMap) Component(org.apache.camel.Component)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 MetricRegistry (com.codahale.metrics.MetricRegistry)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 TimeUnit (java.util.concurrent.TimeUnit)2 Pair (org.apache.commons.lang3.tuple.Pair)2 FeeCalculator (alfio.manager.support.FeeCalculator)1 ConfigurationManager (alfio.manager.system.ConfigurationManager)1 alfio.model (alfio.model)1 Event (alfio.model.Event)1 Configuration (alfio.model.system.Configuration)1 ConfigurationKeys (alfio.model.system.ConfigurationKeys)1 TicketRepository (alfio.repository.TicketRepository)1 TicketReservationRepository (alfio.repository.TicketReservationRepository)1 MonetaryUtil (alfio.util.MonetaryUtil)1 MonetaryUtil.formatCents (alfio.util.MonetaryUtil.formatCents)1 Counter (com.codahale.metrics.Counter)1 Gauge (com.codahale.metrics.Gauge)1