Search in sources :

Example 1 with StringUtils.substringBetween

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

the class AbstractOAuth20Tests method internalVerifyClientOK.

protected Pair<String, String> internalVerifyClientOK(final RegisteredService service, final boolean refreshToken, final boolean json) throws Exception {
    final Principal principal = createPrincipal();
    final OAuthCode code = addCode(principal, service);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(HttpMethod.GET.name(), CONTEXT + OAuth20Constants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.name().toLowerCase());
    final String auth = CLIENT_ID + ':' + CLIENT_SECRET;
    final String value = EncodingUtils.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
    mockRequest.addHeader(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX + value);
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuth20Constants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuth20Constants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse);
    assertNull(this.ticketRegistry.getTicket(code.getId()));
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();
    final String accessTokenId;
    String refreshTokenId = null;
    if (json) {
        assertEquals(MediaType.APPLICATION_JSON_VALUE, mockResponse.getContentType());
        assertTrue(body.contains('"' + OAuth20Constants.ACCESS_TOKEN + "\":\"AT-"));
        final Map results = MAPPER.readValue(body, Map.class);
        if (refreshToken) {
            assertTrue(body.contains('"' + OAuth20Constants.REFRESH_TOKEN + "\":\"RT-"));
            refreshTokenId = results.get(OAuth20Constants.REFRESH_TOKEN).toString();
        }
        assertTrue(body.contains('"' + OAuth20Constants.EXPIRES_IN + "\":"));
        accessTokenId = results.get(OAuth20Constants.ACCESS_TOKEN).toString();
    } else {
        assertEquals(MediaType.TEXT_PLAIN_VALUE, mockResponse.getContentType());
        assertTrue(body.contains(OAuth20Constants.ACCESS_TOKEN + "=AT-"));
        if (refreshToken) {
            assertTrue(body.contains(OAuth20Constants.REFRESH_TOKEN + "=RT-"));
            refreshTokenId = Arrays.stream(body.split("&")).filter(f -> f.startsWith(OAuth20Constants.REFRESH_TOKEN)).map(f -> StringUtils.remove(f, OAuth20Constants.REFRESH_TOKEN + "=")).findFirst().get();
        }
        assertTrue(body.contains(OAuth20Constants.EXPIRES_IN + '='));
        accessTokenId = StringUtils.substringBetween(body, OAuth20Constants.ACCESS_TOKEN + '=', "&");
    }
    final AccessToken accessToken = this.ticketRegistry.getTicket(accessTokenId, AccessToken.class);
    assertEquals(principal, accessToken.getAuthentication().getPrincipal());
    final int timeLeft = getTimeLeft(body, refreshToken, json);
    assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
    return Pair.of(accessTokenId, refreshTokenId);
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) Arrays(java.util.Arrays) ReturnAllAttributeReleasePolicy(org.apereo.cas.services.ReturnAllAttributeReleasePolicy) ZonedDateTime(java.time.ZonedDateTime) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) BasicIdentifiableCredential(org.apereo.cas.authentication.BasicIdentifiableCredential) CasCoreConfiguration(org.apereo.cas.config.CasCoreConfiguration) CasWebApplicationServiceFactoryConfiguration(org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration) Pair(org.apache.commons.lang3.tuple.Pair) OAuthCodeFactory(org.apereo.cas.ticket.code.OAuthCodeFactory) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) Map(java.util.Map) CasCoreWebConfiguration(org.apereo.cas.config.CasCoreWebConfiguration) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) SecurityInterceptor(org.pac4j.springframework.web.SecurityInterceptor) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) CasCoreAuthenticationPolicyConfiguration(org.apereo.cas.config.CasCoreAuthenticationPolicyConfiguration) StandardCharsets(java.nio.charset.StandardCharsets) OAuth20AccessTokenEndpointController(org.apereo.cas.support.oauth.web.endpoints.OAuth20AccessTokenEndpointController) CasCookieConfiguration(org.apereo.cas.web.config.CasCookieConfiguration) Slf4j(lombok.extern.slf4j.Slf4j) CasCoreComponentSerializationConfiguration(org.apereo.cas.config.CasCoreComponentSerializationConfiguration) CasCoreTicketCatalogConfiguration(org.apereo.cas.config.CasCoreTicketCatalogConfiguration) Principal(org.apereo.cas.authentication.principal.Principal) EncodingUtils(org.apereo.cas.util.EncodingUtils) MockTicketGrantingTicket(org.apereo.cas.mock.MockTicketGrantingTicket) ComponentSerializationPlan(org.apereo.cas.ComponentSerializationPlan) RefreshTokenFactory(org.apereo.cas.ticket.refreshtoken.RefreshTokenFactory) CasCoreAuthenticationConfiguration(org.apereo.cas.config.CasCoreAuthenticationConfiguration) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) RunWith(org.junit.runner.RunWith) WebApplicationServiceFactory(org.apereo.cas.authentication.principal.WebApplicationServiceFactory) EnableTransactionManagement(org.springframework.transaction.annotation.EnableTransactionManagement) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) CasOAuthAuthenticationServiceSelectionStrategyConfiguration(org.apereo.cas.config.CasOAuthAuthenticationServiceSelectionStrategyConfiguration) ArrayList(java.util.ArrayList) RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) DefaultAuthenticationHandlerExecutionResult(org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult) RefreshAutoConfiguration(org.springframework.cloud.autoconfigure.RefreshAutoConfiguration) Authentication(org.apereo.cas.authentication.Authentication) ServicesManager(org.apereo.cas.services.ServicesManager) CasCoreUtilSerializationConfiguration(org.apereo.cas.config.CasCoreUtilSerializationConfiguration) CasCoreAuthenticationHandlersConfiguration(org.apereo.cas.config.CasCoreAuthenticationHandlersConfiguration) CasCoreServicesConfiguration(org.apereo.cas.config.CasCoreServicesConfiguration) EnvironmentConversionServiceInitializer(org.apereo.cas.config.support.EnvironmentConversionServiceInitializer) CasCoreServicesAuthenticationConfiguration(org.apereo.cas.config.CasCoreServicesAuthenticationConfiguration) CasCoreAuthenticationPrincipalConfiguration(org.apereo.cas.config.CasCoreAuthenticationPrincipalConfiguration) HttpMethod(org.springframework.http.HttpMethod) AuthenticationHandlerExecutionResult(org.apereo.cas.authentication.AuthenticationHandlerExecutionResult) RegisteredService(org.apereo.cas.services.RegisteredService) CasOAuthThrottleConfiguration(org.apereo.cas.config.CasOAuthThrottleConfiguration) ContextConfiguration(org.springframework.test.context.ContextConfiguration) CasCoreUtilConfiguration(org.apereo.cas.config.CasCoreUtilConfiguration) Assert(org.junit.Assert) DirtiesContext(org.springframework.test.annotation.DirtiesContext) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AopAutoConfiguration(org.springframework.boot.autoconfigure.aop.AopAutoConfiguration) HttpStatus(org.apache.http.HttpStatus) TestConfiguration(org.springframework.boot.test.context.TestConfiguration) AbstractRegisteredService(org.apereo.cas.services.AbstractRegisteredService) SchedulingUtils(org.apereo.cas.util.SchedulingUtils) OAuthCode(org.apereo.cas.ticket.code.OAuthCode) RegisteredServiceTestUtils(org.apereo.cas.services.RegisteredServiceTestUtils) CasCoreAuthenticationServiceSelectionStrategyConfiguration(org.apereo.cas.config.CasCoreAuthenticationServiceSelectionStrategyConfiguration) SpringRunner(org.springframework.test.context.junit4.SpringRunner) CredentialMetaData(org.apereo.cas.authentication.CredentialMetaData) CasCoreTicketIdGeneratorsConfiguration(org.apereo.cas.config.CasCoreTicketIdGeneratorsConfiguration) MediaType(org.springframework.http.MediaType) Collection(java.util.Collection) CasCoreLogoutConfiguration(org.apereo.cas.logout.config.CasCoreLogoutConfiguration) CasDefaultServiceTicketIdGeneratorsConfiguration(org.apereo.cas.config.CasDefaultServiceTicketIdGeneratorsConfiguration) List(java.util.List) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) ComponentSerializationPlanConfigurator(org.apereo.cas.ComponentSerializationPlanConfigurator) PostConstruct(javax.annotation.PostConstruct) CasCoreTicketsConfiguration(org.apereo.cas.config.CasCoreTicketsConfiguration) CasOAuthConfiguration(org.apereo.cas.config.CasOAuthConfiguration) CasPersonDirectoryConfiguration(org.apereo.cas.config.CasPersonDirectoryConfiguration) CasCoreAuthenticationSupportConfiguration(org.apereo.cas.config.CasCoreAuthenticationSupportConfiguration) MockServiceTicket(org.apereo.cas.mock.MockServiceTicket) EnableAspectJAutoProxy(org.springframework.context.annotation.EnableAspectJAutoProxy) HttpConstants(org.pac4j.core.context.HttpConstants) HashMap(java.util.HashMap) Qualifier(org.springframework.beans.factory.annotation.Qualifier) CasCoreAuthenticationMetadataConfiguration(org.apereo.cas.config.CasCoreAuthenticationMetadataConfiguration) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) CasOAuthComponentSerializationConfiguration(org.apereo.cas.config.CasOAuthComponentSerializationConfiguration) CasCoreHttpConfiguration(org.apereo.cas.config.CasCoreHttpConfiguration) OAuth20GrantTypes(org.apereo.cas.support.oauth.OAuth20GrantTypes) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ApplicationContext(org.springframework.context.ApplicationContext) Service(org.apereo.cas.authentication.principal.Service) Bean(org.springframework.context.annotation.Bean) CoreAuthenticationTestUtils(org.apereo.cas.authentication.CoreAuthenticationTestUtils) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) OAuthCode(org.apereo.cas.ticket.code.OAuthCode) Map(java.util.Map) HashMap(java.util.HashMap) Principal(org.apereo.cas.authentication.principal.Principal) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 2 with StringUtils.substringBetween

use of org.apache.commons.lang3.StringUtils.substringBetween in project ddf by codice.

the class DocumentationTest method testBrokenAnchorsPresent.

@Test
public void testBrokenAnchorsPresent() throws IOException, URISyntaxException {
    List<Path> docs = Files.list(getPath()).filter(f -> f.toString().endsWith(HTML_DIRECTORY)).collect(Collectors.toList());
    Set<String> links = new HashSet<>();
    Set<String> anchors = new HashSet<>();
    for (Path path : docs) {
        Document doc = Jsoup.parse(path.toFile(), "UTF-8", EMPTY_STRING);
        String thisDoc = StringUtils.substringAfterLast(path.toString(), File.separator);
        Elements elements = doc.body().getAllElements();
        for (Element element : elements) {
            if (!element.toString().contains(":") && StringUtils.substringBetween(element.toString(), HREF_ANCHOR, CLOSE) != null) {
                links.add(thisDoc + "#" + StringUtils.substringBetween(element.toString(), HREF_ANCHOR, CLOSE));
            }
            anchors.add(thisDoc + "#" + StringUtils.substringBetween(element.toString(), ID, CLOSE));
        }
    }
    links.removeAll(anchors);
    assertThat("Anchors missing section reference: " + links.toString(), links.isEmpty());
}
Also used : Path(java.nio.file.Path) Files(java.nio.file.Files) URISyntaxException(java.net.URISyntaxException) Set(java.util.Set) IOException(java.io.IOException) Test(org.junit.Test) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) File(java.io.File) HashSet(java.util.HashSet) List(java.util.List) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) Document(org.jsoup.nodes.Document) Element(org.jsoup.nodes.Element) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Jsoup(org.jsoup.Jsoup) Elements(org.jsoup.select.Elements) Path(java.nio.file.Path) Element(org.jsoup.nodes.Element) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 3 with StringUtils.substringBetween

use of org.apache.commons.lang3.StringUtils.substringBetween in project syncope by apache.

the class CamelRouteLogic method metrics.

@PreAuthorize("isAuthenticated()")
public CamelMetrics metrics() {
    CamelMetrics metrics = new CamelMetrics();
    MetricsRegistryService registryService = context.getCamelContext().hasService(MetricsRegistryService.class);
    if (registryService == null) {
        LOG.warn("Camel metrics not available");
    } else {
        MetricRegistry registry = registryService.getMetricsRegistry();
        registry.getTimers().entrySet().stream().map(entry -> {
            CamelMetrics.MeanRate meanRate = new CamelMetrics.MeanRate();
            meanRate.setRouteId(StringUtils.substringBetween(entry.getKey(), ".", "."));
            meanRate.setValue(entry.getValue().getMeanRate());
            return meanRate;
        }).forEachOrdered(meanRate -> {
            metrics.getResponseMeanRates().add(meanRate);
        });
        Collections.sort(metrics.getResponseMeanRates(), (o1, o2) -> Collections.reverseOrder(Comparator.<Double>naturalOrder()).compare(o1.getValue(), o2.getValue()));
    }
    return metrics;
}
Also used : CamelRouteDataBinder(org.apache.syncope.core.provisioning.api.data.CamelRouteDataBinder) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) Autowired(org.springframework.beans.factory.annotation.Autowired) ArrayUtils(org.apache.commons.lang3.ArrayUtils) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) MetricsRegistryService(org.apache.camel.component.metrics.routepolicy.MetricsRegistryService) CamelRouteTO(org.apache.syncope.common.lib.to.CamelRouteTO) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) CamelException(org.apache.syncope.core.provisioning.camel.CamelException) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) CamelEntitlement(org.apache.syncope.common.lib.types.CamelEntitlement) CamelRouteDAO(org.apache.syncope.core.persistence.api.dao.CamelRouteDAO) Method(java.lang.reflect.Method) MetricRegistry(com.codahale.metrics.MetricRegistry) CamelMetrics(org.apache.syncope.common.lib.to.CamelMetrics) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) CamelRoute(org.apache.syncope.core.persistence.api.entity.CamelRoute) List(java.util.List) Component(org.springframework.stereotype.Component) SyncopeCamelContext(org.apache.syncope.core.provisioning.camel.SyncopeCamelContext) Comparator(java.util.Comparator) Collections(java.util.Collections) Transactional(org.springframework.transaction.annotation.Transactional) CamelMetrics(org.apache.syncope.common.lib.to.CamelMetrics) MetricRegistry(com.codahale.metrics.MetricRegistry) MetricsRegistryService(org.apache.camel.component.metrics.routepolicy.MetricsRegistryService) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 4 with StringUtils.substringBetween

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

the class ConfigurationMetadataGenerator method processNestedEnumProperties.

private void processNestedEnumProperties(final Set<ConfigurationMetadataProperty> properties, final Set<ConfigurationMetadataProperty> groups) {
    val propertiesToProcess = properties.stream().filter(e -> {
        val matcher = NESTED_CLASS_PATTERN.matcher(e.getType());
        return matcher.matches();
    }).collect(Collectors.toSet());
    for (val prop : propertiesToProcess) {
        val matcher = NESTED_CLASS_PATTERN.matcher(prop.getType());
        if (!matcher.matches()) {
            throw new RuntimeException("Unable to find a match for " + prop.getType());
        }
        val parent = matcher.group(1);
        val innerType = matcher.group(2);
        var typePath = ConfigurationMetadataClassSourceLocator.buildTypeSourcePath(this.sourcePath, parent);
        try {
            TypeDeclaration<?> primaryType = null;
            if (typePath.contains("$")) {
                val innerClass = StringUtils.substringBetween(typePath, "$", ".");
                typePath = StringUtils.remove(typePath, '$' + innerClass);
                val cu = StaticJavaParser.parse(new File(typePath));
                for (val type : cu.getTypes()) {
                    for (val member : type.getMembers()) {
                        if (member.isClassOrInterfaceDeclaration()) {
                            val name = member.asClassOrInterfaceDeclaration().getNameAsString();
                            if (name.equals(innerClass)) {
                                primaryType = member.asClassOrInterfaceDeclaration();
                                break;
                            }
                        }
                    }
                }
            } else {
                val cu = StaticJavaParser.parse(new File(typePath));
                primaryType = cu.getPrimaryType().get();
            }
            Objects.requireNonNull(primaryType).getMembers().stream().peek(member -> {
                if (member.isFieldDeclaration()) {
                    var fieldDecl = member.asFieldDeclaration();
                    var variable = fieldDecl.getVariable(0);
                    if (variable.getInitializer().isPresent()) {
                        var beginIndex = prop.getName().lastIndexOf('.');
                        var propShortName = beginIndex != -1 ? prop.getName().substring(beginIndex + 1) : prop.getName();
                        var names = RelaxedPropertyNames.forCamelCase(variable.getNameAsString()).getValues();
                        if (names.contains(propShortName)) {
                            variable.getInitializer().ifPresent(exp -> {
                                var value = (Object) null;
                                if (exp instanceof LiteralStringValueExpr) {
                                    value = ((LiteralStringValueExpr) exp).getValue();
                                } else if (exp instanceof BooleanLiteralExpr) {
                                    value = ((BooleanLiteralExpr) exp).getValue();
                                } else if (exp instanceof FieldAccessExpr) {
                                    value = ((FieldAccessExpr) exp).getNameAsString();
                                }
                                prop.setDefaultValue(value);
                            });
                        }
                    }
                }
            }).filter(member -> {
                if (member.isEnumDeclaration()) {
                    val enumMem = member.asEnumDeclaration();
                    return enumMem.getNameAsString().equals(innerType);
                }
                if (member.isClassOrInterfaceDeclaration()) {
                    val typeName = member.asClassOrInterfaceDeclaration();
                    return typeName.getNameAsString().equals(innerType);
                }
                return false;
            }).forEach(member -> {
                if (member.isEnumDeclaration()) {
                    val enumMem = member.asEnumDeclaration();
                    val builder = ConfigurationMetadataPropertyCreator.collectJavadocsEnumFields(prop, enumMem);
                    prop.setDescription(builder.toString());
                }
                if (member.isClassOrInterfaceDeclaration()) {
                    val typeName = member.asClassOrInterfaceDeclaration();
                    typeName.getFields().stream().filter(field -> !field.isStatic()).forEach(field -> {
                        val resultProps = new HashSet<ConfigurationMetadataProperty>();
                        val resultGroups = new HashSet<ConfigurationMetadataProperty>();
                        val creator = new ConfigurationMetadataPropertyCreator(false, resultProps, resultGroups, parent);
                        creator.createConfigurationProperty(field, prop.getName());
                        groups.addAll(resultGroups);
                        properties.addAll(resultProps);
                    });
                }
            });
        } catch (final Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
Also used : 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) LiteralStringValueExpr(com.github.javaparser.ast.expr.LiteralStringValueExpr) BooleanLiteralExpr(com.github.javaparser.ast.expr.BooleanLiteralExpr) FieldAccessExpr(com.github.javaparser.ast.expr.FieldAccessExpr) File(java.io.File) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 5 with StringUtils.substringBetween

use of org.apache.commons.lang3.StringUtils.substringBetween in project fmv by f-agu.

the class SoftTestCase method test1.

@Test
@Ignore
public void test1() throws Exception {
    SoftFoundFactory ffSoftFoundFactory = ExecSoftFoundFactory.forProvider(new TestSoftProvider("ffprout")).withParameters("-version").parseFactory((file, softPolicy) -> new Parser() {

        private Integer build;

        @Override
        public void readLine(String line) {
            if (line.startsWith("ff")) {
                build = Integer.parseInt(StringUtils.substringBetween(line, "N-", "-"));
            }
        }

        @Override
        public SoftFound closeAndParse(String cmdLineStr, int exitValue) throws IOException {
            if (build == null) {
                return SoftFound.foundBadSoft(file);
            }
            // return SoftFound.found(file, new TestSoftInfo(build));
            return SoftFound.foundBadVersion(new TestSoftInfo(49), "85");
        }
    }).build();
    // SoftFoundFactory identifyFoundFactory = ExecSoftFoundFactory.withParameters("-version").parseFactory(file ->
    // new Parser() {
    // 
    // @Override
    // public void readLine(String line) {}
    // 
    // @Override
    // public SoftFound closeAndParse(String cmdLineStr, int exitValue) throws IOException {
    // return SoftFound.foundBadVersion(new TestSoftInfo(49), "85");
    // }
    // }).build();
    Soft soft = Soft.with(new TestSoftProvider("ffprout")).search(ffSoftFoundFactory);
    // Soft ffprobeSoft = Soft.with("ffprobe").search(ffSoftFoundFactory);
    // Soft identifySoft = Soft.withName("identify").search(identifyFoundFactory);
    SoftLogger softFormatter = new SoftLogger(Arrays.asList(soft));
    // SoftLogger softFormatter = new SoftLogger(Arrays.asList(ffprobeSoft, identifySoft, ffmpegSoft));
    softFormatter.logDetails(System.out::println);
    // System.out.println(soft.getFounds());
    // System.out.println(soft.getFile());
    soft.withParameters("").execute();
}
Also used : SoftFoundFactory(org.fagu.fmv.soft.find.SoftFoundFactory) Arrays(java.util.Arrays) ExecSoftFoundFactory(org.fagu.fmv.soft.find.ExecSoftFoundFactory) Date(java.util.Date) SoftFound(org.fagu.fmv.soft.find.SoftFound) IOException(java.io.IOException) Test(org.junit.Test) StringUtils(org.apache.commons.lang3.StringUtils) Executors(java.util.concurrent.Executors) Future(java.util.concurrent.Future) Executed(org.fagu.fmv.soft.SoftExecutor.Executed) Parser(org.fagu.fmv.soft.find.ExecSoftFoundFactory.Parser) Ignore(org.junit.Ignore) ExecutorService(java.util.concurrent.ExecutorService) SoftFoundFactory(org.fagu.fmv.soft.find.SoftFoundFactory) ExecSoftFoundFactory(org.fagu.fmv.soft.find.ExecSoftFoundFactory) Parser(org.fagu.fmv.soft.find.ExecSoftFoundFactory.Parser) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)5 List (java.util.List)4 Arrays (java.util.Arrays)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 File (java.io.File)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 Set (java.util.Set)2 Collectors (java.util.stream.Collectors)2 Slf4j (lombok.extern.slf4j.Slf4j)2 Autowired (org.springframework.beans.factory.annotation.Autowired)2 MetricRegistry (com.codahale.metrics.MetricRegistry)1 JsonInclude (com.fasterxml.jackson.annotation.JsonInclude)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 MinimalPrettyPrinter (com.fasterxml.jackson.core.util.MinimalPrettyPrinter)1 DeserializationFeature (com.fasterxml.jackson.databind.DeserializationFeature)1 MapperFeature (com.fasterxml.jackson.databind.MapperFeature)1