Two DML with one session in spring boot - java

Is it possible to call a procedure and then perform an insert in the same spring boot session?
My Adapter
#Override
public Client makeRegister(Client client) {
var clientEntity = clientMapper.toEntity(client);
var cli = Optional.ofNullable(clientRepository.findByid(clientEntity.getId()));
if (!cli.isPresent()) {
clientRepository.callProcedure(1);
clientEntity = clientRepository.saveAndFlush(clientEntity);
}
return clientMapper.toDominio(clientEntity);
}
My Repository
#Procedure("schema.pkg_company.setcompanyid")
void callProcedure(#Param("pId") int pId);
Insert is only possible when the company configuration is correct.
Is there any annotation for this functionality?

Related

Where can I get brace.Tracing with a non-standard server Spring Boot 3.0 application?

I use an injected brave.Tracing that comes with Spring Cloud Sleuth to build the GRPC tracing interceptor like this...
public GrpcServer(
final Set<BindableService> grpcServices,
final Tracing tracing,
#Value("${grpc.port:50000}") int port) {
final var interceptor = GrpcTracing.create(tracing).newServerInterceptor();
var b = ServerBuilder.forPort(port).executor(executor);
grpcServices.forEach(b::addService);
log.info("{} listening on {}", "server", port);
this.healthStatusManager = new HealthStatusManager();
this.server =
b.addService(ProtoReflectionService.newInstance())
.addService(healthStatusManager.getHealthService())
.intercept(interceptor)
.build();
}
But since Spring Boot 3.0 no longer comes with Sleuth, I don't have the brave.Tracing available anymore. How do I get it back?

How to manage Scopes according to the User and not the Client?

I've been following this tutorial in order to create an Authentication Server, but I'm facing some problems regarding the concepts, I guess.
Look, when I register a Client in Repository, I have to define some parameters, like its id, secret, authentication method, grant types, redirection uris and scopes:
#Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient registeredClient = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("articles-client")
.clientSecret("{noop}secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
.redirectUri("http://127.0.0.1:8080/login/oauth2/code/articles-client-oidc")
.redirectUri("http://127.0.0.1:8080/authorized")
.scope(OidcScopes.OPENID)
.scope("articles.read")
.build();
return new InMemoryRegisteredClientRepository(registeredClient);
}
When I'm back to my Resource Server, I find that my client was successfully logged in and it returns with an "articles.read" scope. Everything is fine here, supposing that I want to protect my endpoints with the Client's scope, but this is not my case.
In my situation, I want to protect my endpoints according to my User's role in database.
I'll give you an example, so you don't have to read the whole Baeldung's website:
I try to access: http://localhost:8080/articles.
It redirects to: http://auth-server:9000, where a Spring Security Login Form appears.
When you submit the proper credentials (which are compared from a database using the default Spring Security schema), it basically gets you back to: http://localhost:8080/articles.
Well, in that point, I have an Authorization Token with the Client scope, but not the logged User role.
Is there an standard way to configure my project to achieve this or, do I have to think of a creative way to do so?
Thank you in advance.
For role based authentication you should map authorities in Oauth token.
OAuth2AuthenticationToken.getAuthorities() is used for authorizing requests, such as in hasRole('USER') or hasRole('ADMIN').
For this you need to implement the userAuthoritiesMapper, something like this:
#Configuration
public class AppConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.oauth2Login().userInfoEndpoint().userAuthoritiesMapper(this.userAuthoritiesMapper());
//.oidcUserService(this.oidcUserService());
super.configure(http);
}
private GrantedAuthoritiesMapper userAuthoritiesMapper() {
return (authorities) -> {
Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
authorities.forEach(authority -> {
if (OidcUserAuthority.class.isInstance(authority)) {
OidcUserAuthority oidcUserAuthority = (OidcUserAuthority)authority;
OidcUserInfo userInfo = oidcUserAuthority.getUserInfo();
if (userInfo.containsClaim("role")){
String roleName = "ROLE_" + userInfo.getClaimAsString("role");
mappedAuthorities.add(new SimpleGrantedAuthority(roleName));
}
} else if (OAuth2UserAuthority.class.isInstance(authority)) {
OAuth2UserAuthority oauth2UserAuthority = (OAuth2UserAuthority)authority;
Map<String, Object> userAttributes = oauth2UserAuthority.getAttributes();
if (userAttributes.containsKey("role")){
String roleName = "ROLE_" + (String)userAttributes.get("role");
mappedAuthorities.add(new SimpleGrantedAuthority(roleName));
}
}
});
return mappedAuthorities;
};
}
}

Spring Boot 2.3.1.Release and Cassandra DriverTimeout issue

I am upgrading to Spring boot version 2.3.1.Release. So, there is a major change in Spring Data Cassandra due to Java driver version upgrade to v4. I am stuck on application startup because there is a DriverTimeout exception being thrown:
com.datastax.oss.driver.api.core.DriverTimeoutException: [s0|control|id: 0x8572a9d7, L:/My_IPv4:Random_Port - R:/Cassandra_Server:Port] Protocol initialization request, step 1 (OPTIONS): timed out after 500 ms
My cassandra configuration:
#Bean(name = "mySession")
#Primary
public CqlSession session() {
String containerIpAddress = getContactPoints();
int containerPort = getPort();
InetSocketAddress containerEndPoint = new InetSocketAddress(containerIpAddress, containerPort);
return CqlSession.builder().withLocalDatacenter(getLocalDataCenter())
.addContactPoint(containerEndPoint)
.withAuthCredentials(dbProperties.getCassandraUserName(), dbProperties.getCassandraPassword())
.withKeyspace(getKeyspaceName()).build();
}
I have also tried using DriverConfigLoader option by explicitly setting connection timeout as:
#Bean(name = "mySession")
#Primary
public CqlSession session() {
String containerIpAddress = getContactPoints();
int containerPort = getPort();
InetSocketAddress containerEndPoint = new InetSocketAddress(containerIpAddress, containerPort);
DriverConfigLoader loader =
DriverConfigLoader.programmaticBuilder()
.withDuration(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT, Duration.ofSeconds(5))
.build();
return CqlSession.builder().withLocalDatacenter(getLocalDataCenter())
.withConfigLoader(loader)
.addContactPoint(containerEndPoint)
.withAuthCredentials(dbProperties.getCassandraUserName(), dbProperties.getCassandraPassword())
.withKeyspace(getKeyspaceName()).build();
}
, but to no avail and same exception is being thrown. My current Spring boot version is 2.2.0.Release and I am not even specifying any timeout there and its working fine. How can this issue be fixed?
Assuming that you are using spring-data-cassandra. You can either configure it entirely through your application properties.
Alternatively you can go the route that you're going and build out your own session. If you're doing it that way, you may want to turn off Spring's autoconfiguration.
#EnableAutoConfiguration(exclude = {
CassandraDataAutoConfiguration.class })
and then instead of building the CqlSession, use the CqlSessionFactory like:
#Primary
#Bean("mySessionFactory")
public CqlSessionFactoryBean getCqlSession() {
CqlSessionFactoryBean factory = new CqlSessionFactoryBean();
factory.setUsername(userName);
factory.setPassword(password);
factory.setPort(port);
factory.setKeyspaceName(keyspaceName);
factory.setContactPoints(hostList);
factory.setLocalDatacenter(datacenter);
return factory;
}

Feign Registration - Spring Cloud - Change Target without ribbon over-ride

Introduction
I would like to be able to have two different spring profiles, and depending on the profile to change to a hardcoded address for our feign builders.
Currently was have the following:
return builder.target(cls, "http://" + serviceName);
But I would actually like to do the following and over-ride the address:
return builder.target(cls, "http://our-server:8009/" + serviceName);
Why
Sometimes we don't want to run all the services within our development environment. Additionally, some of the services are only available through a zuul gateway sometimes.
So we run the same code in different situations and conditions.
Technical Details
We have the following code that we use for building our Feign Clients.
We had been using the #FeignClient annotation in the past, but lately we decided to start building our feignClients manually.
Example below:
#FeignClient(name = "ab-document-store", configuration = MultiPartSupportConfiguration.class, fallback = DocumentStoreFallback.class)
We call the feignRegistrar class with the following command:
return registerFeignClient(DocumentStoreClient.class, true);
#RequiredArgsConstructor
//#Component
#Slf4j
public class FeignRegistrar {
#Autowired
private Decoder decoder;
#Autowired
private Encoder encoder;
#Autowired
private Client client;
#Autowired
private Contract feignContract;
#Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
#Autowired
private List<RequestInterceptor> interceptors;
public <T> T register(Class<T> cls, String serviceName, boolean isDocumentStore) {
if(isDocumentStore){
encoder = new MultipartFormEncoder(new SpringEncoder(messageConverters));
}
//Client trustSSLSockets = new Client.Default(getSSLSocketFactory(), new NoopHostnameVerifier());
Feign.Builder builder = Feign.builder()
.client(client)
.encoder(encoder)
.decoder(decoder)
.contract(feignContract)
.logger(new Slf4Logger())
.logLevel(Logger.Level.HEADERS);
builder.requestInterceptor(new RequestInterceptor() {
#Override
public void apply(RequestTemplate template) {
template.header("X-Service-Name", serviceName);
}
});
for(RequestInterceptor interceptor : interceptors) {
builder.requestInterceptor(interceptor);
}
log.debug("Registering {} - as feign proxy ", serviceName);
return builder.target(cls, "http://" + serviceName);
}
public static class Slf4Logger extends Logger {
#Override
protected void log(String configKey, String format, Object... args) {
log.info("{} - {}", configKey, args);
}
}
}
Spring Cloud Property Over-ride
We have also been using property files such as application-ENV.property with entries such as the following:
ab-document-store.ribbon.NIWSServerListClassName:com.netflix.loadbalancer.ConfigurationBasedServerList
ab-document-store.ribbon.listOfServers: localhost:8025
Unfortunately, listOfServers is not enough for us. We would like to be able to assign a directory/path as well. Something like:
ab-document-store.ribbon.listOfServers: localhost:8025/ab-document-store
Otherworkaround
I have thought about sneaking in a header into all requests such as X-SERVICE-NAME using a feign interceptor. Then we could point all services to an address (e.g. localhost:9001) , and forward/proxy those requests to localhost:9001/X-SERVICE-NAME.
However, I would prefer a much easier solution such as:
ab-document-store.ribbon.listOfServers: localhost:8025/ab-document-store
But this doesn't work :(
Introduction
I found a solution for this using a proxy that detects a header.
So, I have a feign interceptor on the java-side that attaches a header x-service-name to every feign-request.
I also have a NodeJS proxy, that analyzes requests, finds x-service-name, and re-writes the requests to become: x-service-name/originalRequestPath.
This allows me to have all the microservices behind a zuul gateway but also access them using a eureka-over-ride.
Java-Feign-Interceptor
Feign.Builder builder = Feign.builder()
.client(client)
.encoder(usedEncoder)
.decoder(decoder)
.contract(feignContract)
.logger(new Slf4Logger())
.logLevel(Logger.Level.HEADERS);
builder.requestInterceptor(new RequestInterceptor() {
#Override
public void apply(RequestTemplate template) {
template.header("X-Service-Name", serviceName);
}
});
NodeJS proxy
In the example, my zuul gateway ( or another proxy ) is on localhost:9001.
I'm listening on localhost:1200 .
let enableProxyForJava = process.env.ENABLE_PROXY_FOR_JAVA;
if (enableProxyForJava != undefined && enableProxyForJava.toLowerCase() === 'true') {
var httpProxyJava = require('http-proxy');
var proxyJava = httpProxyJava.createProxy();
gutil.log( gutil.colors.green('Enabling Proxy for Java. Set your Eureka overrides to localhost:1200.') );
require('http').createServer(function(req, res) {
console.log("req.headers['x-service-name'] = " + req.headers['x-service-name']);
console.log("Before req.url:"+ req.url);
if( req.headers['x-service-name'] != undefined){
let change = req.headers['x-service-name'] +req.url;
console.log("After req.url:"+ change);
req.url = change;
}
proxyJava.web(req, res, {
target: 'http://localhost:9001/'
});
}).listen(1200);
}
Property file inside Java Application that has feign clients
mbak-microservice1.ribbon.NIWSServerListClassName:com.netflix.loadbalancer.ConfigurationBasedServerList
mbak-microservice1.ribbon.listOfServers: localhost:1200
mbak-microservice2.ribbon.NIWSServerListClassName:com.netflix.loadbalancer.ConfigurationBasedServerList
mbak-microservice2.ribbon.listOfServers: localhost:1200
mbak-document-store.ribbon.NIWSServerListClassName:com.netflix.loadbalancer.ConfigurationBasedServerList
mbak-document-store.ribbon.listOfServers: localhost:1200

spring cloud contract - Feign Clients

Using Spring cloud contract to verify contract between my producer and consumer. In my consumer controller, I am using Feign client to call another micro-service method to get some data. But now in spring cloud contract making that stub call for this micro-service is impossible.
Using Spring Cloud with Netflix OSS.
Config-service and eureka is up. Now I installed my producer locally at port 8090. Consumer using Feign clients to call producer to get some data. Now I am getting 500 error. It is showing that URL not found. The closest match is /ping. I believe Feign client is unable to mock, it is somehow trying to connect with eureka not from the locally installed producer. Can you help me on it.
Any example or any idea will be great.
Thanks
It is possible, here is my JUnit test that does it (ParticipantsService uses a Feign Client)
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#AutoConfigureStubRunner(ids = {"com.ryanjbaxter.spring.cloud:ocr-participants:+:stubs"}, workOffline = true)
#DirtiesContext
#ActiveProfiles("test")
public class OcrRacesApplicationTestsBase {
#Autowired
protected ParticipantsService participantsService;
private List<Participant> participants = new ArrayList<>();
//Hack to work around https://github.com/spring-cloud/spring-cloud-commons/issues/156
static {
System.setProperty("eureka.client.enabled", "false");
System.setProperty("spring.cloud.config.failFast", "false");
}
#Before
public void setup() {
this.participants = new ArrayList<>();
this.participants.add(new Participant("Ryan", "Baxter", "MA", "S", Arrays.asList("123", "456")));
this.participants.add(new Participant("Stephanie", "Baxter", "MA", "S", Arrays.asList("456")));
}
#After
public void tearDown() {
this.participants = new ArrayList<>();
}
#Test
public void contextLoads() {
List<Participant> participantList = participantsService.getAllParticipants();
assertEquals(participants, participantList);
}
}

Categories

Resources