use of io.micronaut.core.annotation.Nullable in project micronaut-gcp by micronaut-projects.
the class InvokerHttpServer method start.
@Override
public EmbeddedServer start() {
if (running.compareAndSet(false, true)) {
int retryCount = 0;
while (retryCount <= 3) {
try {
this.server = new Server(port);
ServletContextHandler servletContextHandler = new ServletContextHandler();
servletContextHandler.setContextPath("/");
server.setHandler(NotFoundHandler.forServlet(servletContextHandler));
HttpFunction httpFunction = new HttpFunction() {
@Override
protected ApplicationContext buildApplicationContext(@Nullable Object context) {
ApplicationContext ctx = InvokerHttpServer.this.getApplicationContext();
this.applicationContext = ctx;
return ctx;
}
};
HttpServlet servlet = new HttpServlet() {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
try {
httpFunction.service(new HttpRequestImpl(req), new HttpResponseImpl(resp));
} catch (Exception e) {
throw new ServletException(e);
}
}
};
ServletHolder servletHolder = new ServletHolder(servlet);
servletHolder.getRegistration().setMultipartConfig(new MultipartConfigElement(""));
servletContextHandler.addServlet(servletHolder, "/*");
server.start();
logServerInfo();
break;
} catch (BindException e) {
if (randomPort) {
this.port = SocketUtils.findAvailableTcpPort();
retryCount++;
} else {
throw new ServerStartupException(e.getMessage(), e);
}
} catch (Exception e) {
throw new ServerStartupException("Error starting Google Cloud Function server: " + e.getMessage(), e);
}
}
}
return this;
}
use of io.micronaut.core.annotation.Nullable in project micronaut-security by micronaut-projects.
the class InterceptUrlMapRule method check.
/**
* If no configured pattern matches the request, return {@link SecurityRuleResult#UNKNOWN}.
* Reads the rules in order. The first matched rule will be used for determining authorization.
*
* @param request The current request
* @param routeMatch The matched route
* @param authentication The user authentication. Null if not authenticated
* @return The result
*/
@Override
public Publisher<SecurityRuleResult> check(HttpRequest<?> request, @Nullable RouteMatch<?> routeMatch, @Nullable Authentication authentication) {
final String path = request.getUri().getPath();
final HttpMethod httpMethod = request.getMethod();
Predicate<InterceptUrlMapPattern> exactMatch = p -> pathMatcher.matches(p.getPattern(), path) && p.getHttpMethod().isPresent() && httpMethod.equals(p.getHttpMethod().get());
Predicate<InterceptUrlMapPattern> uriPatternMatchOnly = p -> pathMatcher.matches(p.getPattern(), path) && !p.getHttpMethod().isPresent();
Optional<InterceptUrlMapPattern> matchedPattern = getPatternList().stream().filter(exactMatch).findFirst();
// if we don't get an exact match try to find a match by the uri pattern
if (!matchedPattern.isPresent()) {
if (LOG.isDebugEnabled()) {
LOG.debug("No url map pattern exact match found for path [{}] and method [{}]. Searching in patterns with no defined method.", path, httpMethod);
}
matchedPattern = getPatternList().stream().filter(uriPatternMatchOnly).findFirst();
if (LOG.isDebugEnabled()) {
if (matchedPattern.isPresent()) {
LOG.debug("Url map pattern found for path [{}]. Comparing roles.", path);
} else {
LOG.debug("No url map pattern match found for path [{}]. Returning unknown.", path);
}
}
}
return Mono.from(matchedPattern.map(pattern -> compareRoles(pattern.getAccess(), getRoles(authentication))).orElse(Mono.just(SecurityRuleResult.UNKNOWN)));
}
use of io.micronaut.core.annotation.Nullable in project micronaut-test by micronaut-projects.
the class AbstractMicronautExtension method beforeEach.
/**
* To be called by the different implementations before each test method.
*
* @param context The test context
* @param testInstance The test instance
* @param method The test method
* @param propertyAnnotations The {@code @Property} annotations found in the test method, if any
*/
protected void beforeEach(C context, @Nullable Object testInstance, @Nullable AnnotatedElement method, List<Property> propertyAnnotations) {
int testCount = (int) testProperties.compute("micronaut.test.count", (k, oldCount) -> (int) (oldCount != null ? oldCount : 0) + 1);
if (method != null) {
if (propertyAnnotations != null && !propertyAnnotations.isEmpty()) {
for (Property property : propertyAnnotations) {
final String name = property.name();
oldValues.put(name, testProperties.put(name, property.value()));
}
} else {
oldValues.forEach((k, v) -> testProperties.put(k, v));
}
if (testAnnotationValue.rebuildContext() && testCount > 1) {
stopEmbeddedApplication();
if (applicationContext.isRunning()) {
applicationContext.stop();
}
applicationContext = builder.build();
startApplicationContext();
startEmbeddedApplication();
} else if (!oldValues.isEmpty()) {
final Map<String, Object> diff = applicationContext.getEnvironment().refreshAndDiff();
refreshScope.onRefreshEvent(new RefreshEvent(diff));
}
}
if (testInstance != null) {
if (applicationContext != null) {
if (refreshScope != null) {
refreshScope.onRefreshEvent(new RefreshEvent(Collections.singletonMap(TestActiveCondition.ACTIVE_MOCKS, "changed")));
}
applicationContext.inject(testInstance);
alignMocks(context, testInstance);
}
}
}
use of io.micronaut.core.annotation.Nullable in project micronaut-redis by micronaut-projects.
the class AbstractRedisClientFactory method redisClient.
/**
* Creates the {@link RedisClient} from the configuration.
*
* @param config The configuration
* @param optionalClientResources The ClientResources
* @param mutators The list of mutators
* @return The {@link RedisClient}
*/
public RedisClient redisClient(AbstractRedisConfiguration config, @Nullable ClientResources optionalClientResources, @Nullable List<ClientResourcesMutator> mutators) {
ClientResources clientResources = configureClientResources(config, optionalClientResources, mutators);
if (clientResources == null) {
return redisClient(config);
}
Optional<RedisURI> uri = config.getUri();
return uri.map(redisURI -> RedisClient.create(clientResources, redisURI)).orElseGet(() -> RedisClient.create(clientResources, config));
}
use of io.micronaut.core.annotation.Nullable in project micronaut-security by micronaut-projects.
the class DefaultOpenIdTokenResponseValidator method validateClaims.
/**
* @param clientConfiguration The OAuth 2.0 client configuration
* @param openIdProviderMetadata The OpenID provider metadata
* @param jwt JWT with valida signature
* @param nonce The persisted nonce value
* @return the same JWT supplied as a parameter if the claims validation were succesful or empty if not.
*/
@NonNull
protected Optional<JWT> validateClaims(@NonNull OauthClientConfiguration clientConfiguration, @NonNull OpenIdProviderMetadata openIdProviderMetadata, @NonNull JWT jwt, @Nullable String nonce) {
try {
JWTClaimsSet claimsSet = jwt.getJWTClaimsSet();
OpenIdClaims claims = new JWTOpenIdClaims(claimsSet);
if (genericJwtClaimsValidators.stream().allMatch(validator -> validator.validate(claims, null))) {
if (openIdClaimsValidators.stream().allMatch(validator -> validator.validate(claims, clientConfiguration, openIdProviderMetadata))) {
if (nonceClaimValidator == null) {
if (LOG.isTraceEnabled()) {
LOG.trace("Skipping nonce validation because no bean of type {} present. ", NonceClaimValidator.class.getSimpleName());
}
return Optional.of(jwt);
}
if (nonceClaimValidator.validate(claims, clientConfiguration, openIdProviderMetadata, nonce)) {
return Optional.of(jwt);
} else if (LOG.isErrorEnabled()) {
LOG.error("Nonce {} validation failed for claims {}", nonce, claims.getClaims().keySet().stream().map(key -> key + "=" + claims.getClaims().get(key)).collect(Collectors.joining(", ", "{", "}")));
}
} else if (LOG.isErrorEnabled()) {
LOG.error("JWT OpenID specific claims validation failed for provider [{}]", clientConfiguration.getName());
}
} else if (LOG.isErrorEnabled()) {
LOG.error("JWT generic claims validation failed for provider [{}]", clientConfiguration.getName());
}
} catch (ParseException e) {
if (LOG.isErrorEnabled()) {
LOG.error("Failed to parse the JWT returned from provider [{}]", clientConfiguration.getName(), e);
}
}
return Optional.empty();
}
Aggregations