Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@
public class DocumentTaskItemProcessor implements ItemProcessor<DocumentTask, DocumentTask> {
private final Logger log = LoggerFactory.getLogger(DocumentTaskItemProcessor.class);

private static final String FAILURE_DESCRIPTION_TEMPLATE =
"Document taskId %d, caseId: %s reached max retry count: %d";

private final DmStoreDownloader dmStoreDownloader;
private final DmStoreUploader dmStoreUploader;
private final DocumentConversionService documentConverter;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,9 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext chunkCon
int totalCount = 0;
Date date = DateUtils.addMilliseconds(new Date(), -historicRetentionMiliseconds);
DateFormat df = new SimpleDateFormat();
LOG.info("Remove the Spring Batch history before the {}", df.format(date));

if (LOG.isInfoEnabled()) {
LOG.info("Remove the Spring Batch history before the {}", df.format(date));
}
int rowCount = jdbcTemplate.update(getQuery(SQL_DELETE_BATCH_STEP_EXECUTION_CONTEXT), date);
LOG.info("Deleted rows number from the BATCH_STEP_EXECUTION_CONTEXT table: {}", rowCount);
totalCount += rowCount;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.hibernate.LockOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
Expand Down Expand Up @@ -58,31 +57,23 @@ public class BatchConfiguration {

private static final Logger LOGGER = LoggerFactory.getLogger(BatchConfiguration.class);

@Autowired
PlatformTransactionManager transactionManager;
private final PlatformTransactionManager transactionManager;

@Autowired
JobRepository jobRepository;
@Autowired
EntityManagerFactory entityManagerFactory;
private final JobRepository jobRepository;

@Autowired
JobLauncher jobLauncher;
private final EntityManagerFactory entityManagerFactory;

@Autowired
BuildInfo buildInfo;
private final JobLauncher jobLauncher;

@Autowired
DocumentTaskItemProcessor documentTaskItemProcessor;
private final BuildInfo buildInfo;

@Autowired
DocumentTaskCallbackProcessor documentTaskCallbackProcessor;
private final DocumentTaskItemProcessor documentTaskItemProcessor;

@Autowired
JdbcTemplate jdbcTemplate;
private final DocumentTaskCallbackProcessor documentTaskCallbackProcessor;

@Autowired
DocumentTaskRepository documentTaskRepository;
private final JdbcTemplate jdbcTemplate;

private final DocumentTaskRepository documentTaskRepository;

@Value("${spring.batch.historicExecutionsRetentionMilliseconds}")
int historicExecutionsRetentionMilliseconds;
Expand All @@ -106,6 +97,23 @@ public class BatchConfiguration {

private Random random = new Random();

@Autowired
public BatchConfiguration(PlatformTransactionManager transactionManager, JobRepository jobRepository,
EntityManagerFactory entityManagerFactory, JobLauncher jobLauncher, BuildInfo buildInfo,
DocumentTaskItemProcessor documentTaskItemProcessor,
DocumentTaskCallbackProcessor documentTaskCallbackProcessor, JdbcTemplate jdbcTemplate,
DocumentTaskRepository documentTaskRepository) {
this.transactionManager = transactionManager;
this.jobRepository = jobRepository;
this.entityManagerFactory = entityManagerFactory;
this.jobLauncher = jobLauncher;
this.buildInfo = buildInfo;
this.documentTaskItemProcessor = documentTaskItemProcessor;
this.documentTaskCallbackProcessor = documentTaskCallbackProcessor;
this.jdbcTemplate = jdbcTemplate;
this.documentTaskRepository = documentTaskRepository;
}

@Scheduled(fixedDelayString = "${spring.batch.document-task-milliseconds}")
@SchedulerLock(name = "${task.env}")
public void schedule() throws JobParametersInvalidException,
Expand Down Expand Up @@ -213,8 +221,7 @@ public Query createQuery() {
+ " where t.taskState = 'NEW' and "
+ " t.version <= " + buildInfo.getBuildNumber()
+ " order by t.createdDate")
.setLockMode(LockModeType.PESSIMISTIC_WRITE)
.setHint("jakarta.persistence.lock.timeout", LockOptions.SKIP_LOCKED);
.setLockMode(LockModeType.PESSIMISTIC_WRITE);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,6 @@ public void execute(Runnable task) {
executor.execute(createWrappedRunnable(task));
}

@Override
public void execute(Runnable task, long startTimeout) {
executor.execute(createWrappedRunnable(task), startTimeout);
}

private <T> Callable<T> createCallable(final Callable<T> task) {
return () -> {
try {
Expand Down Expand Up @@ -88,16 +83,14 @@ public <T> Future<T> submit(Callable<T> task) {

@Override
public void destroy() throws Exception {
if (executor instanceof DisposableBean) {
DisposableBean bean = (DisposableBean) executor;
if (executor instanceof DisposableBean bean) {
bean.destroy();
}
}

@Override
public void afterPropertiesSet() throws Exception {
if (executor instanceof InitializingBean) {
InitializingBean bean = (InitializingBean) executor;
if (executor instanceof InitializingBean bean) {
bean.afterPropertiesSet();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,7 @@ public Map<String, String> convertDataToStrings(Map<String, Object> data) {
if (data != null) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
// Extract the data that will be saved.
if (entry.getValue() instanceof WebAuthenticationDetails) {
WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue();
if (entry.getValue() instanceof WebAuthenticationDetails authenticationDetails) {
results.put("remoteAddress", authenticationDetails.getRemoteAddress());
results.put("sessionId", authenticationDetails.getSessionId());
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,45 +18,32 @@ public class EntityAuditEventListener extends AuditingEntityListener {

@PostPersist
public void onPostCreate(AbstractAuditingEntity target) {
try {
AsyncEntityAuditEventWriter asyncEntityAuditEventWriter =
beanFactory.getBean(AsyncEntityAuditEventWriter.class);
asyncEntityAuditEventWriter.writeAuditEvent(target, EntityAuditAction.CREATE);
} catch (NoSuchBeanDefinitionException e) {
log.error("No bean found for AsyncEntityAuditEventWriter");
} catch (Exception e) {
log.error("Exception while persisting create audit entity {}", e.toString());
}
writeAuditEvent(target, EntityAuditAction.CREATE);
}

@PostUpdate
public void onPostUpdate(AbstractAuditingEntity target) {
try {
AsyncEntityAuditEventWriter asyncEntityAuditEventWriter =
beanFactory.getBean(AsyncEntityAuditEventWriter.class);
asyncEntityAuditEventWriter.writeAuditEvent(target, EntityAuditAction.UPDATE);
} catch (NoSuchBeanDefinitionException e) {
log.error("No bean found for AsyncEntityAuditEventWriter");
} catch (Exception e) {
log.error("Exception while persisting update audit entity {}", e.toString());
}
writeAuditEvent(target, EntityAuditAction.UPDATE);
}

@PostRemove
public void onPostRemove(AbstractAuditingEntity target) {
writeAuditEvent(target, EntityAuditAction.DELETE);
}

static void setBeanFactory(BeanFactory beanFactory) {
EntityAuditEventListener.beanFactory = beanFactory;
}

private void writeAuditEvent(AbstractAuditingEntity target, EntityAuditAction action) {
try {
AsyncEntityAuditEventWriter asyncEntityAuditEventWriter =
beanFactory.getBean(AsyncEntityAuditEventWriter.class);
asyncEntityAuditEventWriter.writeAuditEvent(target, EntityAuditAction.DELETE);
beanFactory.getBean(AsyncEntityAuditEventWriter.class);
asyncEntityAuditEventWriter.writeAuditEvent(target, action);
} catch (NoSuchBeanDefinitionException e) {
log.error("No bean found for AsyncEntityAuditEventWriter");
} catch (Exception e) {
log.error("Exception while persisting delete audit entity {}", e.toString());
log.error("Exception while persisting {} audit entity: {}", action.value(), e.toString());
}
}

static void setBeanFactory(BeanFactory beanFactory) {
EntityAuditEventListener.beanFactory = beanFactory;
}

}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package uk.gov.hmcts.reform.em.stitching.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
Expand All @@ -18,24 +17,21 @@
import org.springframework.security.oauth2.jwt.JwtDecoders;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter;
import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter;
import org.springframework.security.web.SecurityFilterChain;
import uk.gov.hmcts.reform.authorisation.filters.ServiceAuthFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
@EnableMethodSecurity()
public class SecurityConfiguration {

@Value("${spring.security.oauth2.client.provider.oidc.issuer-uri}")
private String issuerUri;

@Autowired
private ServiceAuthFilter serviceAuthFilter;

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers("/swagger-ui.html",
return web -> web.ignoring().requestMatchers("/swagger-ui.html",
"/swagger-ui/**",
"/swagger-resources/**",
"/v3/**",
Expand All @@ -48,7 +44,7 @@ public WebSecurityCustomizer webSecurityCustomizer() {
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
public SecurityFilterChain filterChain(HttpSecurity http, ServiceAuthFilter serviceAuthFilter) throws Exception {

http.csrf(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package uk.gov.hmcts.reform.em.stitching.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
Expand All @@ -9,8 +10,8 @@
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Service;
import uk.gov.hmcts.reform.em.stitching.repository.IdamRepository;
import uk.gov.hmcts.reform.idam.client.models.UserInfo;

import java.util.Map;
import java.util.Optional;

import static org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames.ACCESS_TOKEN;
Expand All @@ -37,29 +38,29 @@ public SecurityUtils(final IdamRepository idamRepository) {
*/
public Optional<String> getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();

return Optional.ofNullable(securityContext.getAuthentication())
.map(authentication -> {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
return springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal();
} else if (authentication instanceof JwtAuthenticationToken) {
Jwt jwt = ((JwtAuthenticationToken) authentication).getToken();
if (ACCESS_TOKEN.equals(jwt.getClaim(TOKEN_NAME))) {
uk.gov.hmcts.reform.idam.client.models.UserInfo userInfo =
idamRepository.getUserInfo(jwt.getTokenValue());
return userInfo.getUid();
}
} else if (authentication.getPrincipal() instanceof DefaultOidcUser) {
Map<String, Object> attributes =
((DefaultOidcUser) authentication.getPrincipal()).getAttributes();
if (attributes.containsKey("preferred_username")) {
return (String) attributes.get("preferred_username");
}
.map(authentication -> switch (authentication) {
case Authentication auth when auth.getPrincipal() instanceof UserDetails userDetails ->
userDetails.getUsername();

case Authentication auth when auth.getPrincipal() instanceof String s -> s;

case JwtAuthenticationToken jwtAuth -> {
Jwt jwt = jwtAuth.getToken();
if (jwt.hasClaim(TOKEN_NAME)
&& jwt.getClaim(TOKEN_NAME).equals(ACCESS_TOKEN)) {
UserInfo userInfo = idamRepository.getUserInfo(jwt.getTokenValue());
yield userInfo.getUid();
}
return null;
});
yield null;
}

case Authentication auth when auth.getPrincipal() instanceof DefaultOidcUser oidcUser ->
(String) oidcUser.getAttributes().get("preferred_username");

default -> null;
});
}

}
Loading