Search in sources :

Example 1 with StringUtils.substringBeforeLast

use of org.apache.commons.lang3.StringUtils.substringBeforeLast 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 : Reader(io.swagger.v3.jaxrs2.Reader) 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) Objects(java.util.Objects) List(java.util.List) Server(io.swagger.v3.oas.models.servers.Server) Optional(java.util.Optional) 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.substringBeforeLast

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

the class Swagger2Customizer method customize.

public Swagger customize(Swagger data) {
    if (dynamicBasePath) {
        MessageContext ctx = createMessageContext();
        String currentBasePath = StringUtils.substringBeforeLast(ctx.getHttpServletRequest().getRequestURI(), "/");
        data.setBasePath(currentBasePath);
        if (data.getHost() == null) {
            data.setHost(beanConfig.getHost());
        }
        if (data.getInfo() == null) {
            data.setInfo(beanConfig.getInfo());
        }
        if (beanConfig.getSwagger() != null && beanConfig.getSwagger().getSecurityDefinitions() != null && data.getSecurityDefinitions() == null) {
            data.setSecurityDefinitions(beanConfig.getSwagger().getSecurityDefinitions());
        }
    }
    if (replaceTags || javadocProvider != null) {
        Map<String, ClassResourceInfo> operations = new HashMap<>();
        Map<Pair<String, String>, OperationResourceInfo> methods = new HashMap<>();
        for (ClassResourceInfo cri : cris) {
            for (OperationResourceInfo ori : cri.getMethodDispatcher().getOperationResourceInfos()) {
                String normalizedPath = getNormalizedPath(cri.getURITemplate().getValue(), ori.getURITemplate().getValue());
                operations.put(normalizedPath, cri);
                methods.put(ImmutablePair.of(ori.getHttpMethod(), normalizedPath), ori);
            }
        }
        if (replaceTags && data.getTags() != null) {
            data.getTags().clear();
        }
        for (final Map.Entry<String, Path> entry : data.getPaths().entrySet()) {
            Tag tag = null;
            if (replaceTags && operations.containsKey(entry.getKey())) {
                ClassResourceInfo cri = operations.get(entry.getKey());
                tag = new Tag();
                tag.setName(cri.getURITemplate().getValue().replaceAll("/", "_"));
                if (javadocProvider != null) {
                    tag.setDescription(javadocProvider.getClassDoc(cri));
                }
                data.addTag(tag);
            }
            for (Map.Entry<HttpMethod, Operation> subentry : entry.getValue().getOperationMap().entrySet()) {
                if (replaceTags && tag != null) {
                    subentry.getValue().setTags(Collections.singletonList(tag.getName()));
                }
                Pair<String, String> key = ImmutablePair.of(subentry.getKey().name(), entry.getKey());
                if (methods.containsKey(key) && javadocProvider != null) {
                    OperationResourceInfo ori = methods.get(key);
                    subentry.getValue().setSummary(javadocProvider.getMethodDoc(ori));
                    for (int i = 0; i < subentry.getValue().getParameters().size(); i++) {
                        subentry.getValue().getParameters().get(i).setDescription(javadocProvider.getMethodParameterDoc(ori, i));
                    }
                    addParameters(subentry.getValue().getParameters());
                    if (subentry.getValue().getResponses() != null && !subentry.getValue().getResponses().isEmpty()) {
                        subentry.getValue().getResponses().entrySet().iterator().next().getValue().setDescription(javadocProvider.getMethodResponseDoc(ori));
                    }
                }
            }
        }
    }
    if (replaceTags && data.getTags() != null) {
        Collections.sort(data.getTags(), new Comparator<Tag>() {

            @Override
            public int compare(final Tag tag1, final Tag tag2) {
                return tag1.getName().compareTo(tag2.getName());
            }
        });
    }
    applyDefaultVersion(data);
    return data;
}
Also used : Path(io.swagger.models.Path) HashMap(java.util.HashMap) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Operation(io.swagger.models.Operation) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) Tag(io.swagger.models.Tag) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(io.swagger.models.HttpMethod) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Pair(org.apache.commons.lang3.tuple.Pair)

Example 3 with StringUtils.substringBeforeLast

use of org.apache.commons.lang3.StringUtils.substringBeforeLast in project cas by apereo.

the class ConfigurationMetadataGenerator method processHints.

private static Set<ConfigurationMetadataHint> processHints(final Collection<ConfigurationMetadataProperty> props, final Collection<ConfigurationMetadataProperty> groups) {
    var hints = new LinkedHashSet<ConfigurationMetadataHint>(0);
    val allValidProps = props.stream().filter(p -> p.getDeprecation() == null || !Deprecation.Level.ERROR.equals(p.getDeprecation().getLevel())).collect(Collectors.toList());
    for (val entry : allValidProps) {
        try {
            val propName = StringUtils.substringAfterLast(entry.getName(), ".");
            val groupName = StringUtils.substringBeforeLast(entry.getName(), ".");
            val grp = groups.stream().filter(g -> g.getName().equalsIgnoreCase(groupName)).findFirst().orElseThrow(() -> new IllegalArgumentException("Cant locate group " + groupName));
            val matcher = PATTERN_GENERICS.matcher(grp.getType());
            val className = matcher.find() ? matcher.group(1) : grp.getType();
            val clazz = ClassUtils.getClass(className);
            val hint = new ConfigurationMetadataHint();
            hint.setName(entry.getName());
            val annotation = Arrays.stream(clazz.getAnnotations()).filter(a -> a.annotationType().equals(RequiresModule.class)).findFirst().map(RequiresModule.class::cast).orElseThrow(() -> new RuntimeException(clazz.getCanonicalName() + " is missing @RequiresModule"));
            val valueHint = new ValueHint();
            valueHint.setValue(toJson(Map.of("module", annotation.name(), "automated", annotation.automated())));
            valueHint.setDescription(RequiresModule.class.getName());
            hint.getValues().add(valueHint);
            val grpHint = new ValueHint();
            grpHint.setValue(toJson(Map.of("owner", clazz.getCanonicalName())));
            grpHint.setDescription(PropertyOwner.class.getName());
            hint.getValues().add(grpHint);
            val names = RelaxedPropertyNames.forCamelCase(propName);
            names.getValues().forEach(Unchecked.consumer(name -> {
                val f = ReflectionUtils.findField(clazz, name);
                if (f != null && f.isAnnotationPresent(RequiredProperty.class)) {
                    val propertyHint = new ValueHint();
                    propertyHint.setValue(toJson(Map.of("owner", clazz.getName())));
                    propertyHint.setDescription(RequiredProperty.class.getName());
                    hint.getValues().add(propertyHint);
                }
                if (f != null && f.isAnnotationPresent(DurationCapable.class)) {
                    val propertyHint = new ValueHint();
                    propertyHint.setDescription(DurationCapable.class.getName());
                    propertyHint.setValue(toJson(List.of(DurationCapable.class.getName())));
                    hint.getValues().add(propertyHint);
                }
                if (f != null && f.isAnnotationPresent(ExpressionLanguageCapable.class)) {
                    val propertyHint = new ValueHint();
                    propertyHint.setDescription(ExpressionLanguageCapable.class.getName());
                    propertyHint.setValue(toJson(List.of(ExpressionLanguageCapable.class.getName())));
                    hint.getValues().add(propertyHint);
                }
            }));
            if (!hint.getValues().isEmpty()) {
                hints.add(hint);
            }
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    return hints;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) lombok.val(lombok.val) RequiresModule(org.apereo.cas.configuration.support.RequiresModule) NestedConfigurationProperty(org.springframework.boot.context.properties.NestedConfigurationProperty) Arrays(java.util.Arrays) MinimalPrettyPrinter(com.fasterxml.jackson.core.util.MinimalPrettyPrinter) RequiredArgsConstructor(lombok.RequiredArgsConstructor) DurationCapable(org.apereo.cas.configuration.support.DurationCapable) StringUtils(org.apache.commons.lang3.StringUtils) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) LiteralStringValueExpr(com.github.javaparser.ast.expr.LiteralStringValueExpr) HashSet(java.util.HashSet) MapperFeature(com.fasterxml.jackson.databind.MapperFeature) ClassUtils(org.apache.commons.lang3.ClassUtils) Map(java.util.Map) TypeReference(com.fasterxml.jackson.core.type.TypeReference) LinkedHashSet(java.util.LinkedHashSet) ValueHint(org.springframework.boot.configurationmetadata.ValueHint) Unchecked(org.jooq.lambda.Unchecked) BooleanLiteralExpr(com.github.javaparser.ast.expr.BooleanLiteralExpr) TypeDeclaration(com.github.javaparser.ast.body.TypeDeclaration) Deprecation(org.springframework.boot.configurationmetadata.Deprecation) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) lombok.val(lombok.val) Set(java.util.Set) RequiredProperty(org.apereo.cas.configuration.support.RequiredProperty) ConfigurationMetadataProperty(org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty) Collectors(java.util.stream.Collectors) File(java.io.File) Objects(java.util.Objects) ExpressionLanguageCapable(org.apereo.cas.configuration.support.ExpressionLanguageCapable) StaticJavaParser(com.github.javaparser.StaticJavaParser) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) ReflectionUtils(org.springframework.util.ReflectionUtils) PropertyOwner(org.apereo.cas.configuration.support.PropertyOwner) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) Pattern(java.util.regex.Pattern) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) RelaxedPropertyNames(org.apereo.cas.configuration.support.RelaxedPropertyNames) ValueHint(org.springframework.boot.configurationmetadata.ValueHint) RequiresModule(org.apereo.cas.configuration.support.RequiresModule) PropertyOwner(org.apereo.cas.configuration.support.PropertyOwner)

Example 4 with StringUtils.substringBeforeLast

use of org.apache.commons.lang3.StringUtils.substringBeforeLast in project simplelocalize-cli by simplelocalize.

the class FileListReader method findFilesToUpload.

public List<FileToUpload> findFilesToUpload(String uploadPath) throws IOException {
    List<FileToUpload> output = new ArrayList<>();
    String beforeTemplatePart = getParentDirectory(uploadPath);
    Path parentDir = Path.of(beforeTemplatePart);
    boolean exists = Files.exists(parentDir);
    if (!exists) {
        String parentDirectory = StringUtils.substringBeforeLast(beforeTemplatePart, File.separator);
        parentDir = Path.of(parentDirectory);
    }
    try (Stream<Path> foundFilesStream = Files.walk(parentDir, 6)) {
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        String uploadPathPattern = uploadPath.replace(LANGUAGE_TEMPLATE_KEY, "**").replace(NAMESPACE_TEMPLATE_KEY, "**");
        var foundFiles = foundFilesStream.filter(Files::isRegularFile).filter(path -> antPathMatcher.matches(uploadPathPattern, path.toString())).collect(Collectors.toList());
        for (Path foundFile : foundFiles) {
            String languageKey = extractTemplateValue(uploadPath, foundFile, LANGUAGE_TEMPLATE_KEY);
            String pathWithLanguage = uploadPath.replace(LANGUAGE_TEMPLATE_KEY, languageKey);
            String namespace = extractTemplateValue(pathWithLanguage, foundFile, NAMESPACE_TEMPLATE_KEY);
            if (StringUtils.isNotBlank(namespace)) {
                String pathWithNamespace = uploadPath.replace(NAMESPACE_TEMPLATE_KEY, namespace);
                languageKey = extractTemplateValue(pathWithNamespace, foundFile, LANGUAGE_TEMPLATE_KEY);
            }
            FileToUpload fileToUpload = FileToUpload.FileToUploadBuilder.aFileToUpload().withLanguage(StringUtils.trimToNull(languageKey)).withNamespace(StringUtils.trimToNull(namespace)).withPath(foundFile).build();
            output.add(fileToUpload);
        }
        return output;
    }
}
Also used : Path(java.nio.file.Path) LANGUAGE_TEMPLATE_KEY(io.simplelocalize.cli.TemplateKeys.LANGUAGE_TEMPLATE_KEY) Files(java.nio.file.Files) FileToUpload(io.simplelocalize.cli.client.dto.FileToUpload) IOException(java.io.IOException) AntPathMatcher(io.micronaut.core.util.AntPathMatcher) StringUtils(org.apache.commons.lang3.StringUtils) Collectors(java.util.stream.Collectors) File(java.io.File) ArrayList(java.util.ArrayList) List(java.util.List) Stream(java.util.stream.Stream) NAMESPACE_TEMPLATE_KEY(io.simplelocalize.cli.TemplateKeys.NAMESPACE_TEMPLATE_KEY) Path(java.nio.file.Path) FileToUpload(io.simplelocalize.cli.client.dto.FileToUpload) ArrayList(java.util.ArrayList) Files(java.nio.file.Files) AntPathMatcher(io.micronaut.core.util.AntPathMatcher)

Example 5 with StringUtils.substringBeforeLast

use of org.apache.commons.lang3.StringUtils.substringBeforeLast in project opencast by opencast.

the class CanvasUserRoleProvider method getCanvasSiteRolesByCurrentUser.

/**
 * Get all sites id taught by current user.
 * Only list available site roles for current user.
 */
private List<String> getCanvasSiteRolesByCurrentUser(String query, boolean exact) {
    User user = securityService.getUser();
    if (exact) {
        Set<String> roles = user.getRoles().stream().map(Role::getName).collect(Collectors.toSet());
        if (roles.contains(query)) {
            return Collections.singletonList(query);
        } else {
            return Collections.emptyList();
        }
    }
    final String finalQuery = StringUtils.chop(query);
    return user.getRoles().stream().map(Role::getName).filter(roleName -> roleName.endsWith("_" + LTI_INSTRUCTOR_ROLE) || roleName.endsWith("_" + LTI_LEARNER_ROLE)).map(roleName -> StringUtils.substringBeforeLast(roleName, "_")).distinct().map(site -> Arrays.asList(site + "_" + LTI_LEARNER_ROLE, site + "_" + LTI_INSTRUCTOR_ROLE)).flatMap(siteRoles -> siteRoles.stream()).filter(roleName -> roleName.startsWith(finalQuery)).collect(Collectors.toList());
}
Also used : User(org.opencastproject.security.api.User) Arrays(java.util.Arrays) LoadingCache(com.google.common.cache.LoadingCache) UserProvider(org.opencastproject.security.api.UserProvider) ComponentContext(org.osgi.service.component.ComponentContext) LoggerFactory(org.slf4j.LoggerFactory) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Component(org.osgi.service.component.annotations.Component) Request(org.apache.http.client.fluent.Request) Organization(org.opencastproject.security.api.Organization) ConfigurationException(org.osgi.service.cm.ConfigurationException) Content(org.apache.http.client.fluent.Content) JaxbRole(org.opencastproject.security.api.JaxbRole) JsonNode(com.fasterxml.jackson.databind.JsonNode) Activate(org.osgi.service.component.annotations.Activate) Group(org.opencastproject.security.api.Group) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) NotFoundException(org.opencastproject.util.NotFoundException) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) OrganizationDirectoryService(org.opencastproject.security.api.OrganizationDirectoryService) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Set(java.util.Set) IOException(java.io.IOException) JaxbUser(org.opencastproject.security.api.JaxbUser) Collectors(java.util.stream.Collectors) SecurityService(org.opencastproject.security.api.SecurityService) CacheLoader(com.google.common.cache.CacheLoader) TimeUnit(java.util.concurrent.TimeUnit) RoleProvider(org.opencastproject.security.api.RoleProvider) URLEncoder(java.net.URLEncoder) List(java.util.List) Role(org.opencastproject.security.api.Role) OsgiUtil(org.opencastproject.util.OsgiUtil) NumberUtils(org.apache.commons.lang3.math.NumberUtils) CacheBuilder(com.google.common.cache.CacheBuilder) Reference(org.osgi.service.component.annotations.Reference) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Collections(java.util.Collections) User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser)

Aggregations

List (java.util.List)7 StringUtils (org.apache.commons.lang3.StringUtils)7 File (java.io.File)5 Map (java.util.Map)5 Collectors (java.util.stream.Collectors)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 Arrays (java.util.Arrays)4 Collection (java.util.Collection)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 HashSet (java.util.HashSet)3 Set (java.util.Set)3 JsonInclude (com.fasterxml.jackson.annotation.JsonInclude)2 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 MinimalPrettyPrinter (com.fasterxml.jackson.core.util.MinimalPrettyPrinter)2 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)2 MapperFeature (com.fasterxml.jackson.databind.MapperFeature)2 StaticJavaParser (com.github.javaparser.StaticJavaParser)2 TypeDeclaration (com.github.javaparser.ast.body.TypeDeclaration)2 BooleanLiteralExpr (com.github.javaparser.ast.expr.BooleanLiteralExpr)2