Skip to content

Commit

Permalink
Ny scheduler app
Browse files Browse the repository at this point in the history
  • Loading branch information
ulrikHesmyr committed Jul 26, 2024
1 parent 2306943 commit 74f318d
Show file tree
Hide file tree
Showing 14 changed files with 492 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import no.nav.registre.testnorge.levendearbeidsforholdansettelse.entity.JobbParameter;
import no.nav.registre.testnorge.levendearbeidsforholdansettelse.entity.JobbParameterVerdier;
import no.nav.registre.testnorge.levendearbeidsforholdansettelse.entity.Verdier;
Expand All @@ -15,6 +16,7 @@
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
Expand All @@ -38,6 +40,12 @@ public ResponseEntity<List<JobbParameterVerdier>> hentAlleJobber2(){
*/


@GetMapping("/ansettelse-jobb")
public ResponseEntity<String> ansettelseJobb(){
//TODO: Kall ansettelseSerivce.ruNnAnsettelseService her
log.info("FIkk spørring for å kjøre ansettelse-service fra scheduler");
return ResponseEntity.ok("Kjørte ansettelse-service");
}

@GetMapping("/verdi/{parameterNavn}")
public ResponseEntity<List<String>> hentVerdier(@PathVariable("parameterNavn") String parameternavn) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package no.nav.levendearbeidsforholdscheduler.config;

import no.nav.testnav.libs.servletcore.config.ApplicationCoreConfig;
import no.nav.testnav.libs.servletsecurity.config.SecureOAuth2ServerToServerConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({
ApplicationCoreConfig.class,
//InsecureJwtServerToServerConfiguration.class
SecureOAuth2ServerToServerConfiguration.class
})
public class ApplicationConfig {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package no.nav.levendearbeidsforholdscheduler.config;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import no.nav.testnav.libs.securitycore.domain.ServerProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import static lombok.AccessLevel.PACKAGE;

/**
* Samler alle placeholders for ulike {@code consumers.*}-konfigurasjon her, dvs. subklasser av {@code ServerProperties}.
* <br/><br/>
* Husk at Spring Boot bruker <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties.relaxed-binding">relaxed binding</a>
* mellom configuration properties og field names.
*
* @see ServerProperties
*/
@Configuration
@ConfigurationProperties(prefix = "consumers")
@NoArgsConstructor(access = PACKAGE)
@Getter
@Setter(PACKAGE)
public class Consumers {

private ServerProperties testnavLevendeArbeidsforholdAnsettelsev2;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package no.nav.levendearbeidsforholdscheduler.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.vault.annotation.VaultPropertySource;
import org.springframework.vault.authentication.ClientAuthentication;
import org.springframework.vault.authentication.TokenAuthentication;
import org.springframework.vault.client.VaultEndpoint;
import org.springframework.vault.config.AbstractVaultConfiguration;

import static io.micrometer.common.util.StringUtils.isBlank;

@Configuration
@Profile("dev")
@VaultPropertySource(value = "secret/dolly/lokal", ignoreSecretNotFound = false)
public class DevConfig extends AbstractVaultConfiguration {

private static final String VAULT_TOKEN = "spring.cloud.vault.token";

@Override
public VaultEndpoint vaultEndpoint() {
return VaultEndpoint.create("vault.adeo.no", 443);
}

@Override
public ClientAuthentication clientAuthentication() {
if (System.getenv().containsKey("VAULT_TOKEN")) {
System.setProperty(VAULT_TOKEN, System.getenv("VAULT_TOKEN"));
}
var token = System.getProperty(VAULT_TOKEN);
if (isBlank(token)) {
throw new IllegalArgumentException("Påkrevet property 'spring.cloud.vault.token' er ikke satt.");
}
return new TokenAuthentication(System.getProperty(VAULT_TOKEN));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package no.nav.levendearbeidsforholdscheduler.config;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import no.nav.testnav.libs.servletcore.config.ApplicationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

@Configuration
public class OpenApiConfig implements WebMvcConfigurer {

@Bean
public OpenAPI openApi(ApplicationProperties applicationProperties) {
return new OpenAPI()
.components(new Components().addSecuritySchemes("bearer-jwt", new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
.in(SecurityScheme.In.HEADER)
.name("Authorization")
))
.addSecurityItem(
new SecurityRequirement().addList("bearer-jwt", Arrays.asList("read", "write")))
.info(new Info()
.title(applicationProperties.getName())
.version(applicationProperties.getVersion())
.description(applicationProperties.getDescription())
.termsOfService("https://nav.no")
.contact(new Contact()
.url("https://nav-it.slack.com/archives/CA3P9NGA2")
.email("[email protected]")
.name("Team Dolly")
)
.license(new License()
.name("MIT License")
.url("https://opensource.org/licenses/MIT")
)
);
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/swagger").setViewName("redirect:/swagger-ui.html");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package no.nav.levendearbeidsforholdscheduler.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
public class SchedulerConfig {

@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(10);
taskScheduler.setThreadNamePrefix("taskScheduler-");
return taskScheduler;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package no.nav.levendearbeidsforholdscheduler.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@Configuration
@Profile({ "prod", "dev" })
public class SecurityConfig {

@Bean
@SuppressWarnings("java:S4502")
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {

httpSecurity.sessionManagement(sessionConfig -> sessionConfig.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorizeConfig -> authorizeConfig.requestMatchers(
"/internal/**",
"/webjars/**",
"/swagger-resources/**",
"/v3/api-docs/**",
"/swagger-ui/**",
"/swagger",
"/error",
"/swagger-ui.html"
).permitAll().requestMatchers("/scheduler/**").fullyAuthenticated())
.oauth2ResourceServer(oauth2RSConfig -> oauth2RSConfig.jwt(Customizer.withDefaults()));

return httpSecurity.build();
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package no.nav.levendearbeidsforholdscheduler.consumer;

public class AnsettelseConsumer {
//private final ServerProperties serverProperties;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package no.nav.levendearbeidsforholdscheduler.consumer.command;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import no.nav.levendearbeidsforholdscheduler.config.Consumers;
import no.nav.testnav.libs.servletsecurity.exchange.TokenExchange;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

@Slf4j
@RequiredArgsConstructor
@Service
public class AnsettelseCommand {

private final Consumers consumers;
private final TokenExchange tokenExchange;

@EventListener(ApplicationReadyEvent.class)
public void aktiverAnsettelseService(){

log.info("Kjørrrr");

var accessToken = hentToken();

WebClient webClient = WebClient.builder().baseUrl("https://testnav-levende-arbeidsforhold-ansettelse-v2.intern.dev.nav.no/api/ansettelse-jobb").build();
String response = webClient.get()
.header("Authorization", "Bearer " + accessToken)
.retrieve().bodyToMono(String.class).block();
if(response != null){
log.info("Response: {}", response);
}
// try {
//
// } catch (Exception e){
// log.info("Feilet å sende spørring til levende-arbeidsforhold-ansettelse");
// }
}

public String hentToken(){

var serverProperties = consumers.getTestnavLevendeArbeidsforholdAnsettelsev2();
var accessToken = tokenExchange.exchange(serverProperties).block();
if(accessToken != null){
return accessToken.getTokenValue();
} else {
log.warn("Kunne ikke hente access token");
return "";
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package no.nav.levendearbeidsforholdscheduler.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import no.nav.levendearbeidsforholdscheduler.scheduler.JobbScheduler;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static no.nav.levendearbeidsforholdscheduler.utils.Utils.intervallErHeltall;
import static no.nav.levendearbeidsforholdscheduler.utils.Utils.lagCronExpression;

@RestController
@RequestMapping("/scheduler")
@RequiredArgsConstructor
public class JobbController {

private final JobbScheduler jobbScheduler;

/**
* Request handler funksjon for å restarte scheduler
* @param request Spørrings-objekt fra klient
* @return respons til klienten for den tilsvarende spørringen
*/
@GetMapping
public ResponseEntity<String> reschedule(HttpServletRequest request) {
String intervall = request.getHeader("intervall");

if (intervall == null) {
return ResponseEntity.badRequest().body("intervall er ikke spesifisert");
}

String cronExpression;
boolean erGyldigHeltall = intervallErHeltall(intervall);

if (erGyldigHeltall){
cronExpression = lagCronExpression(intervall);
} else {
return ResponseEntity.badRequest().body("intervall er ikke gyldig heltall");
}

jobbScheduler.startScheduler(cronExpression);
return ResponseEntity.ok("Scheduler har begynt med intervall " + intervall);
}

//TODO: Lage et endepunkt som svarer på om scheduler kjører for øyeblikket
}
Loading

0 comments on commit 74f318d

Please sign in to comment.