index
int64
repo_id
string
file_path
string
content
string
0
java-sources/africa/absa/inception-jta/1.2.0/africa/absa/inception/jta
java-sources/africa/absa/inception-jta/1.2.0/africa/absa/inception/jta/util/TransactionUtil.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.jta.util; import javax.transaction.Status; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import org.springframework.transaction.TransactionSystemException; /** * The <b>TransactionUtil</b> class provides a helper class for working with transactions. * * @author Marcus Portmann */ public class TransactionUtil { /** * Check whether there is an existing JTA transaction. * * @param transactionManager the JTA transaction manager * @return true if there is an existing JTA transaction or false otherwise */ public static boolean transactionExists(TransactionManager transactionManager) { try { Transaction transaction = transactionManager.getTransaction(); if (transaction == null) { return false; } int status = transaction.getStatus(); return ((status != Status.STATUS_UNKNOWN) && (status != Status.STATUS_NO_TRANSACTION) && (status != Status.STATUS_COMMITTED) && (status != Status.STATUS_ROLLEDBACK)); // other states are active transaction: ACTIVE, MARKED_ROLLBACK, PREPARING, PREPARED, // COMMITTING, ROLLING_BACK } catch (Exception e) { throw new TransactionSystemException( "Failed to check for an existing active JTA transaction", e); } } }
0
java-sources/africa/absa/inception-jta/1.2.0/africa/absa/inception/jta
java-sources/africa/absa/inception-jta/1.2.0/africa/absa/inception/jta/util/XAExceptionUtil.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.jta.util; import javax.transaction.xa.XAException; /** * The <b>XAExceptionUtil</b> class provides a helper class for handling XAExceptions. * * @author Marcus Portmann */ public class XAExceptionUtil { /** * Constructs a new <b>XAException</b> object. * * @param errorCode the error code * @param message the message * @param cause the cause * @return the XAException object */ public static XAException xaException(int errorCode, String message, Throwable cause) { XAException xaException = xaException(errorCode, message); xaException.initCause(cause); return xaException; } /** * Constructs a new <b>XAException</b> object. * * @param errorCode the error code * @param message the message * @return the XAException object */ public static XAException xaException(int errorCode, String message) { XAException xaException = new XAException(message); xaException.errorCode = errorCode; return xaException; } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/DuplicateMailTemplateException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * The <b>DuplicateMailTemplateException</b> exception is thrown to indicate an error condition as a * result of an attempt to create a duplicate mail template i.e a mail template with the specified * ID already exists. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/mail/duplicate-mail-template", title = "A mail template with the specified ID already exists.", status = 409) public class DuplicateMailTemplateException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>DuplicateMailTemplateException</b>. * * @param mailTemplateId the ID for the mail template */ public DuplicateMailTemplateException(String mailTemplateId) { super("The mail template with ID (" + mailTemplateId + ") already exists"); } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/FreeMarkerTemplateLoader.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import freemarker.cache.TemplateLoader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.time.ZoneOffset; /** * The <b>FreeMarkerTemplateLoader</b> class implements the Apache FreeMarker template loader. * * @author Marcus Portmann */ public class FreeMarkerTemplateLoader implements TemplateLoader { /** The Mail Service. */ private final IMailService mailService; /** * Constructs a new <b>FreeMarkerTemplateLoader</b>. * * @param mailService the Mail Service */ public FreeMarkerTemplateLoader(IMailService mailService) { this.mailService = mailService; } /** * Closes the template source, releasing any resources held that are only required for reading the * template and/or its metadata. This is the last method that is called by the {@link * freemarker.cache.TemplateCache} for a template source, except that {@link * Object#equals(Object)} is might called later too. {@link freemarker.cache.TemplateCache} * ensures that this method will be called on every object that is returned from {@link * #findTemplateSource(String)}. * * @param templateSource the template source that should be closed. */ @Override public void closeTemplateSource(Object templateSource) throws IOException {} /** * Finds the template in the backing storage and returns an object that identifies the storage * location where the template can be loaded from. See the return value for more information. * * @param name The name of the template, already localized and normalized by the {@link * freemarker.cache.TemplateCache cache}. * @return An object representing the template source, which can be supplied in subsequent calls * to {@link #getLastModified(Object)} and {@link #getReader(Object, String)}, when those are * called on the same {@link TemplateLoader}. {@code null} must be returned if the source for * the template doesn't exist */ @Override public Object findTemplateSource(String name) throws IOException { try { MailTemplate mailTemplate = mailService.getMailTemplate(name); return mailTemplate.getId(); } catch (MailTemplateNotFoundException e) { return null; } catch (Throwable e) { throw new IOException("Failed to find the template source (" + name + ")", e); } } /** * Returns the time of last modification of the specified template source. This method is called * after <b>findTemplateSource()</b>. * * @param templateSource an object representing a template source, obtained through a prior call * to {@link #findTemplateSource(String)} * @return the time of last modification of the specified template source, or -1 if the time is * not known. */ @Override public long getLastModified(Object templateSource) { try { if (templateSource instanceof String) { MailTemplate mailTemplate = mailService.getMailTemplate((String) templateSource); return mailTemplate.getUpdated().toInstant(ZoneOffset.UTC).toEpochMilli(); } } catch (Throwable ignored) { } return -1; } /** * Returns the character stream of a template represented by the specified template source. This * method is possibly called for multiple times for the same template source object, and it must * always return a {@link Reader} that reads the template from its beginning. Before this method * is called for the second time (or later), its caller must close the previously returned {@link * Reader}, and it must not use it anymore. That is, this method is not required to support * multiple concurrent readers for the same source {@code templateSource} object. * * <p>Typically, this method is called if the template is missing from the cache, or if after * calling {@link #findTemplateSource(String)} and {@link #getLastModified(Object)} it was * determined that the cached copy of the template is stale. Then, if it turns out that the {@code * encoding} parameter used doesn't match the actual template content (based on the {@code #ftl * encoding=...} header), this method will be called for a second time with the correct {@code * encoding} parameter value. * * @param templateSource an object representing a template source, obtained through a prior call * to {@link #findTemplateSource(String)}. This must be an object on which {@link * TemplateLoader#closeTemplateSource(Object)} wasn't applied yet. * @param encoding the character encoding used to translate source bytes to characters. Some * loaders may not have access to the byte representation of the template stream, and instead * directly obtain a character stream. These loaders should ignore the encoding parameter. * @return A {@link Reader} representing the template character stream. It's the responsibility of * the caller (which is {@link freemarker.cache.TemplateCache} usually) to {@code close()} it. * The {@link Reader} is not required to work after the {@code templateSource} was closed * ({@link #closeTemplateSource(Object)}). */ @Override public Reader getReader(Object templateSource, String encoding) throws IOException { try { if (templateSource instanceof String) { MailTemplate mailTemplate = mailService.getMailTemplate((String) templateSource); return new StringReader(new String(mailTemplate.getTemplate(), StandardCharsets.UTF_8)); } else { throw new RuntimeException("Invalid template source (" + templateSource + ")"); } } catch (Throwable e) { throw new IOException( "Failed to retrieve the character stream for the template (" + templateSource + ")", e); } } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/IMailService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import java.time.LocalDateTime; import java.util.List; import java.util.Map; /** * The <b>IMailService</b> interface defines the functionality provided by a Mail Service * implementation. * * @author Marcus Portmann */ @SuppressWarnings("unused") public interface IMailService { /** * Create the new mail template. * * @param mailTemplate the <b>MailTemplate</b> instance containing the information for the new * mail template * @return the mail template * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateMailTemplateException if the mail template already exists * @throws ServiceUnavailableException if the mail template could not be created */ MailTemplate createMailTemplate(MailTemplate mailTemplate) throws InvalidArgumentException, DuplicateMailTemplateException, ServiceUnavailableException; /** * Delete the existing mail template. * * @param mailTemplateId the ID for the mail template * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the mail template could not be deleted */ void deleteMailTemplate(String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException; /** * Retrieve the mail template. * * @param mailTemplateId the ID for the mail template * @return the mail template * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the mail template could not be retrieved */ MailTemplate getMailTemplate(String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException; /** * Retrieve the name of the mail template. * * @param mailTemplateId the ID for the mail template * @return the name of the mail template * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the name of the mail template could not be retrieved */ String getMailTemplateName(String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException; /** * Returns the summaries for all the mail templates. * * @return the summaries for all the mail templates * @throws ServiceUnavailableException if the mail template summaries could not be retrieved */ List<MailTemplateSummary> getMailTemplateSummaries() throws ServiceUnavailableException; /** * Retrieve the summary for the mail template. * * @param mailTemplateId the ID for the mail template * @return the summary for the mail template * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the mail template summary could not be retrieved */ MailTemplateSummary getMailTemplateSummary(String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException; /** * Returns the date and time the mail template was last updated. * * @param mailTemplateId the ID for the mail template * @return the date and time the mail template was last updated * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the date and time the mail template was last updated * could not be retrieved */ LocalDateTime getMailTemplateUpdated(String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException; /** * Returns all the mail templates. * * @return the mail templates * @throws ServiceUnavailableException if the mail templates could not be retrieved */ List<MailTemplate> getMailTemplates() throws ServiceUnavailableException; /** * Check whether the mail template exists. * * @param mailTemplateId the ID for the mail template * @return <b>true</b> if the mail template exists or <b>false</b> otherwise * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the check for the existing mail template failed */ boolean mailTemplateExists(String mailTemplateId) throws InvalidArgumentException, ServiceUnavailableException; /** * Process the mail template. * * @param mailTemplateId the ID for the mail template * @param templateParameters the template parameters * @return the output of processing the template * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the mail template processing failed */ String processMailTemplate(String mailTemplateId, Map<String, String> templateParameters) throws InvalidArgumentException, ServiceUnavailableException; /** * Send a mail. * * @param to the list of e-mail addresses to send the mail to * @param subject the subject for the mail * @param from the from e-mail address * @param fromName the from e-mail name * @param mailTemplateId the ID for the mail template * @param mailTemplateParameters the parameters to apply to the mail template * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the mail could not be sent */ void sendMail( List<String> to, String subject, String from, String fromName, String mailTemplateId, Map<String, String> mailTemplateParameters) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException; /** * Update the mail template. * * @param mailTemplate the <b>MailTemplate</b> instance containing the updated information for the * mail template * @return the mail template * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the mail template could not be updated */ MailTemplate updateMailTemplate(MailTemplate mailTemplate) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException; }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/MailConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import africa.absa.inception.jpa.JpaUtil; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; /** * The <b>MailConfiguration</b> class provides the Spring configuration for the Mail module. * * @author Marcus Portmann */ @Configuration @EnableJpaRepositories( entityManagerFactoryRef = "mailEntityManagerFactory", basePackages = {"africa.absa.inception.mail"}) public class MailConfiguration { /** The Spring application context. */ private final ApplicationContext applicationContext; /** * Constructs a new <b>MailConfiguration</b>. * * @param applicationContext the Spring application context */ public MailConfiguration(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Returns the mail entity manager factory bean associated with the application data source. * * @param dataSource the application data source * @param platformTransactionManager the platform transaction manager * @return the mail entity manager factory bean associated with the application data source */ @Bean public LocalContainerEntityManagerFactoryBean mailEntityManagerFactory( @Qualifier("applicationDataSource") DataSource dataSource, PlatformTransactionManager platformTransactionManager) { return JpaUtil.createEntityManager( "mail", dataSource, platformTransactionManager, "africa.absa.inception.mail"); } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/MailService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.core.service.ValidationError; import freemarker.cache.TemplateLookupContext; import freemarker.cache.TemplateLookupResult; import freemarker.cache.TemplateLookupStrategy; import freemarker.template.Configuration; import freemarker.template.Template; import java.io.IOException; import java.io.StringWriter; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.context.ApplicationContext; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; /** * The <b>MailService</b> class provides the Mail Service implementation. * * @author Marcus Portmann */ @Service @SuppressWarnings({"unused"}) public class MailService implements IMailService, InitializingBean { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(MailService.class); /** The Spring application context. */ private final ApplicationContext applicationContext; /** The Apache FreeMarker configuration., */ private final Configuration freeMarkerConfiguration; /** The Mail Template Repository. */ private final MailTemplateRepository mailTemplateRepository; /** The Mail Template Summary Repository. */ private final MailTemplateSummaryRepository mailTemplateSummaryRepository; /** The JSR-303 validator. */ private final Validator validator; /** The Java mail sender. */ private JavaMailSender javaMailSender; /** * Constructs a new <b>MailService</b>. * * @param applicationContext the Spring application context * @param validator the JSR-303 validator * @param mailTemplateRepository the Mail Template Repository * @param mailTemplateSummaryRepository the Mail Template Summary Repository */ public MailService( ApplicationContext applicationContext, Validator validator, MailTemplateRepository mailTemplateRepository, MailTemplateSummaryRepository mailTemplateSummaryRepository) { this.applicationContext = applicationContext; this.validator = validator; this.mailTemplateRepository = mailTemplateRepository; this.mailTemplateSummaryRepository = mailTemplateSummaryRepository; this.freeMarkerConfiguration = new Configuration(Configuration.VERSION_2_3_29); this.freeMarkerConfiguration.setTemplateLoader(new FreeMarkerTemplateLoader(this)); this.freeMarkerConfiguration.setTemplateLookupStrategy( new TemplateLookupStrategy() { @Override public TemplateLookupResult lookup(TemplateLookupContext templateLookupContext) throws IOException { return templateLookupContext.lookupWithAcquisitionStrategy( templateLookupContext.getTemplateName()); } @Override public String toString() { return "MailServiceLookupStrategy"; } }); } @Override public void afterPropertiesSet() { try { javaMailSender = applicationContext.getBean(JavaMailSender.class); } catch (NoSuchBeanDefinitionException ignored) { logger.warn("No JavaMailSender implementation found"); } } @Override @Transactional @CachePut(cacheNames = "mailTemplates", key = "#mailTemplate.id") public MailTemplate createMailTemplate(MailTemplate mailTemplate) throws InvalidArgumentException, DuplicateMailTemplateException, ServiceUnavailableException { validateMailTemplate(mailTemplate); try { if (mailTemplateRepository.existsById(mailTemplate.getId())) { throw new DuplicateMailTemplateException(mailTemplate.getId()); } mailTemplateRepository.saveAndFlush(mailTemplate); return mailTemplate; } catch (DuplicateMailTemplateException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the mail template (" + mailTemplate.getId() + ")", e); } } @Override @Transactional @CacheEvict(cacheNames = "mailTemplates", key = "#mailTemplateId") public void deleteMailTemplate(String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(mailTemplateId)) { throw new InvalidArgumentException("mailTemplateId"); } try { if (!mailTemplateRepository.existsById(mailTemplateId)) { throw new MailTemplateNotFoundException(mailTemplateId); } mailTemplateRepository.deleteById(mailTemplateId); /* * Clear the FreeMarker template cache. This could be optimized in future but given that * message templates are not updated on a continuous or even regular basis this is probably * sufficient for now. */ freeMarkerConfiguration.clearTemplateCache(); } catch (MailTemplateNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to delete the mail template (" + mailTemplateId + ")", e); } } @Override @Cacheable(cacheNames = "mailTemplates", key = "#mailTemplateId") public MailTemplate getMailTemplate(String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(mailTemplateId)) { throw new InvalidArgumentException("mailTemplateId"); } try { Optional<MailTemplate> mailTemplateOptional = mailTemplateRepository.findById(mailTemplateId); if (mailTemplateOptional.isPresent()) { return mailTemplateOptional.get(); } else { throw new MailTemplateNotFoundException(mailTemplateId); } } catch (MailTemplateNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the mail template (" + mailTemplateId + ")", e); } } @Override public String getMailTemplateName(String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(mailTemplateId)) { throw new InvalidArgumentException("mailTemplateId"); } try { Optional<String> nameOptional = mailTemplateRepository.getNameById(mailTemplateId); if (nameOptional.isPresent()) { return nameOptional.get(); } throw new MailTemplateNotFoundException(mailTemplateId); } catch (MailTemplateNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the name of the mail template (" + mailTemplateId + ")", e); } } @Override public List<MailTemplateSummary> getMailTemplateSummaries() throws ServiceUnavailableException { try { return mailTemplateSummaryRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the summaries for the mail templates", e); } } @Override public MailTemplateSummary getMailTemplateSummary(String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(mailTemplateId)) { throw new InvalidArgumentException("mailTemplateId"); } try { Optional<MailTemplateSummary> mailTemplateSummaryOptional = mailTemplateSummaryRepository.findById(mailTemplateId); if (mailTemplateSummaryOptional.isPresent()) { return mailTemplateSummaryOptional.get(); } else { throw new MailTemplateNotFoundException(mailTemplateId); } } catch (MailTemplateNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the summary for the mail template (" + mailTemplateId + ")", e); } } @Override public LocalDateTime getMailTemplateUpdated(String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(mailTemplateId)) { throw new InvalidArgumentException("mailTemplateId"); } try { Optional<LocalDateTime> updatedOptional = mailTemplateRepository.getUpdatedById(mailTemplateId); if (updatedOptional.isPresent()) { return updatedOptional.get(); } throw new MailTemplateNotFoundException(mailTemplateId); } catch (MailTemplateNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the date and time the mail template (" + mailTemplateId + ") was last updated", e); } } @Override public List<MailTemplate> getMailTemplates() throws ServiceUnavailableException { try { return mailTemplateRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the mail templates", e); } } @Override public boolean mailTemplateExists(String mailTemplateId) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(mailTemplateId)) { throw new InvalidArgumentException("mailTemplateId"); } try { return mailTemplateRepository.existsById(mailTemplateId); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to check whether the mail template (" + mailTemplateId + ") exists", e); } } @Override public String processMailTemplate(String mailTemplateId, Map<String, String> templateParameters) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(mailTemplateId)) { throw new InvalidArgumentException("mailTemplateId"); } if (templateParameters == null) { throw new InvalidArgumentException("templateParameters"); } try { Template template = freeMarkerConfiguration.getTemplate(mailTemplateId); StringWriter sw = new StringWriter(); template.process(templateParameters, sw); return sw.toString(); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to process the mail template (" + mailTemplateId + ")", e); } } public void sendMail( List<String> to, String subject, String from, String fromName, String mailTemplateId, Map<String, String> mailTemplateParameters) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { if (to == null) { throw new InvalidArgumentException("to"); } if (!StringUtils.hasText(subject)) { throw new InvalidArgumentException("subject"); } if (!StringUtils.hasText(from)) { throw new InvalidArgumentException("from"); } if (!StringUtils.hasText(fromName)) { throw new InvalidArgumentException("fromName"); } if (!StringUtils.hasText(mailTemplateId)) { throw new InvalidArgumentException("mailTemplateId"); } if (mailTemplateParameters == null) { throw new InvalidArgumentException("mailTemplateParameters"); } try { // Retrieve the mail template Optional<MailTemplate> mailTemplateOptional = mailTemplateRepository.findById(mailTemplateId); if (mailTemplateOptional.isEmpty()) { throw new MailTemplateNotFoundException(mailTemplateId); } MailTemplate mailTemplate = mailTemplateOptional.get(); if (javaMailSender != null) { // Send the e-mail message MimeMessage mimeMessage = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(new InternetAddress(from, fromName)); helper.setTo(to.toArray(new String[0])); helper.setSubject(subject); helper.setText( processMailTemplate(mailTemplate.getId(), mailTemplateParameters), mailTemplate.getContentType() == MailTemplateContentType.HTML); javaMailSender.send(helper.getMimeMessage()); } else { throw new ServiceUnavailableException("No JavaMailSender bean has been configured"); } } catch (MailTemplateNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to send the mail", e); } } @Override @Transactional @CachePut(cacheNames = "mailTemplates", key = "#mailTemplate.id") public MailTemplate updateMailTemplate(MailTemplate mailTemplate) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { validateMailTemplate(mailTemplate); try { if (!mailTemplateRepository.existsById(mailTemplate.getId())) { throw new MailTemplateNotFoundException(mailTemplate.getId()); } mailTemplateRepository.saveAndFlush(mailTemplate); /* * Clear the FreeMarker template cache. This could be optimized in future but given that * message templates are not updated on a continuous or even regular basis this is probably * sufficient for now. */ freeMarkerConfiguration.clearTemplateCache(); return mailTemplate; } catch (MailTemplateNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to update the mail template (" + mailTemplate.getId() + ")", e); } } private void validateMailTemplate(MailTemplate mailTemplate) throws InvalidArgumentException { if (mailTemplate == null) { throw new InvalidArgumentException("mailTemplate"); } Set<ConstraintViolation<MailTemplate>> constraintViolations = validator.validate(mailTemplate); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "mailTemplate", ValidationError.toValidationErrors(constraintViolations)); } } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/MailTemplate.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>MailTemplate</b> class holds the information for a mail template. * * @author Marcus Portmann */ @Schema(description = "A template for an e-mail sent by an application") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "name", "contentType", "template"}) @Entity @Table(schema = "mail", name = "mail_templates") @SuppressWarnings({"unused"}) public class MailTemplate implements Serializable { private static final long serialVersionUID = 1000000; /** The content type for the mail template. */ @Schema(description = "The content type for the mail template", required = true) @JsonProperty(required = true) @NotNull @Column(name = "content_type", nullable = false) private MailTemplateContentType contentType; /** The date and time the mail template was created. */ @JsonIgnore @Column(name = "created", nullable = false, updatable = false) private LocalDateTime created; /** The ID for the mail template. */ @Schema(description = "The ID for the mail template", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "id", length = 100, nullable = false) private String id; /** The name of the mail template. */ @Schema(description = "The name of the mail template", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The Apache FreeMarker template for the mail template. */ @Schema(description = "The Apache FreeMarker template for the mail template", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 10485760) @Column(name = "template", nullable = false) private byte[] template; /** The date and time the mail template was last updated. */ @JsonIgnore @Column(name = "updated", insertable = false) private LocalDateTime updated; /** Constructs a new <b>MailTemplate</b>. */ public MailTemplate() {} /** * Constructs a new <b>MailTemplate</b>. * * @param id the ID for the mail template * @param name the name of the mail template * @param contentType the content type for the mail template * @param template the Apache FreeMarker template for the mail template */ public MailTemplate( String id, String name, MailTemplateContentType contentType, byte[] template) { this.id = id; this.name = name; this.contentType = contentType; this.template = template; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } MailTemplate other = (MailTemplate) object; return Objects.equals(id, other.id); } /** * Returns the content type for the mail template. * * @return the content type for the mail template */ public MailTemplateContentType getContentType() { return contentType; } /** * Returns the date and time the mail template was created. * * @return the date and time the mail template was created */ public LocalDateTime getCreated() { return created; } /** * Returns the ID for the mail template. * * @return the ID for the mail template */ public String getId() { return id; } /** * Returns the name of the mail template. * * @return the name of the mail template */ public String getName() { return name; } /** * Returns the Apache FreeMarker template for the mail template. * * @return the Apache FreeMarker template for the mail template */ public byte[] getTemplate() { return template; } /** * Returns the date and time the mail template was last updated. * * @return the date and time the mail template was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } /** * Set the content type for the mail template. * * @param contentType the content type for the mail template */ public void setContentType(MailTemplateContentType contentType) { this.contentType = contentType; } /** * Set the ID for the mail template. * * @param id the ID for the mail template */ public void setId(String id) { this.id = id; } /** * Set the name of the mail template. * * @param name the name of the mail template */ public void setName(String name) { this.name = name; } /** * Set the Apache FreeMarker template for the mail template. * * @param template the Apache FreeMarker template for the mail template */ public void setTemplate(byte[] template) { this.template = template; } /** * Returns a string representation of the object. * * @return a string representation of the object */ @Override public String toString() { return "MailTemplate {id=\"" + getId() + "\", name=\"" + getName() + "\", contentType=\"" + getContentType() + "\"}"; } /** The Java Persistence callback method invoked before the entity is created in the database. */ @PrePersist protected void onCreate() { created = LocalDateTime.now(); } /** The Java Persistence callback method invoked before the entity is updated in the database. */ @PreUpdate protected void onUpdate() { updated = LocalDateTime.now(); } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/MailTemplateContentType.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.v3.oas.annotations.media.Schema; /** * The <b>MailTemplateContentType</b> enumeration defines the possible content types for mail * templates. * * @author Marcus Portmann */ @Schema(description = "The mail template content type") public enum MailTemplateContentType { /** Text. */ TEXT("text", "Text"), /** HTML. */ HTML("html", "HTML"); private final String code; private final String description; MailTemplateContentType(String code, String description) { this.code = code; this.description = description; } /** * Returns the mail template content type given by the specified code value. * * @param code the code for the mail template content type * @return the mail template content type given by the specified code value */ @JsonCreator public static MailTemplateContentType fromCode(String code) { switch (code) { case "text": return MailTemplateContentType.TEXT; case "html": return MailTemplateContentType.HTML; default: throw new RuntimeException( "Failed to determine the mail template content type with the invalid code (" + code + ")"); } } /** * Returns the mail template content type for the specified numeric code. * * @param numericCode the numeric code for the mail template content type * @return the mail template content type given by the specified numeric code value */ public static MailTemplateContentType fromNumericCode(int numericCode) { switch (numericCode) { case 1: return MailTemplateContentType.TEXT; case 2: return MailTemplateContentType.HTML; default: throw new RuntimeException( "Failed to determine the mail template content type for the numeric code (" + numericCode + ")"); } } /** * Returns the numeric code for the mail template content type. * * @param mailTemplateContentType the mail template content type * @return the numeric code for the mail template content type */ public static int toNumericCode(MailTemplateContentType mailTemplateContentType) { switch (mailTemplateContentType) { case TEXT: return 1; case HTML: return 2; default: throw new RuntimeException( "Failed to determine the numeric code for the mail template content type (" + mailTemplateContentType.code() + ")"); } } /** * Returns the code for the mail template content type. * * @return the code for the mail template content type */ @JsonValue public String code() { return code; } /** * Returns the description for the mail template content type. * * @return the description for the mail template content type */ public String description() { return description; } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/MailTemplateContentTypeConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import javax.persistence.AttributeConverter; import javax.persistence.Converter; /** * The <b>MailTemplateContentTypeConverter</b> class implements the custom JPA converter for the * <b>MailTemplateContentType</b> enumeration. * * @author Marcus Portmann */ @Converter(autoApply = true) public class MailTemplateContentTypeConverter implements AttributeConverter<MailTemplateContentType, Integer> { /** * Converts the value stored in the entity attribute into the data representation to be stored in * the database. * * @param attribute the entity attribute value to be converted * @return the converted data to be stored in the database column */ @Override public Integer convertToDatabaseColumn(MailTemplateContentType attribute) { if (attribute == null) return null; return MailTemplateContentType.toNumericCode(attribute); } /** * Converts the data stored in the database column into the value to be stored in the entity * attribute. Note that it is the responsibility of the converter writer to specify the correct * dbData type for the corresponding column for use by the JDBC driver: i.e., persistence * providers are not expected to do such type conversion. * * @param dbData the data from the database column to be converted * @return the converted value to be stored in the entity attribute */ @Override public MailTemplateContentType convertToEntityAttribute(Integer dbData) { if (dbData == null) return null; return MailTemplateContentType.fromNumericCode(dbData); } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/MailTemplateContentTypeToStringConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.WritingConverter; import org.springframework.stereotype.Component; /** * The <b>MailTemplateContentTypeToStringConverter</b> class implements the Spring converter that * converts a <b>MailTemplateContentType</b> type into a <b>String</b> type. * * @author Marcus Portmann */ @Component @WritingConverter public class MailTemplateContentTypeToStringConverter implements Converter<MailTemplateContentType, String> { /** Constructs a new <b>MailTemplateContentTypeToStringConverter</b>. */ public MailTemplateContentTypeToStringConverter() {} @Override public String convert(MailTemplateContentType source) { return source.code(); } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/MailTemplateNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * The <b>MailTemplateNotFoundException</b> exception is thrown to indicate an error condition as a * result of a mail template that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/mail/mail-template-not-found", title = "The mail template could not be found.", status = 404) public class MailTemplateNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * w Constructs a new <b>MailTemplateNotFoundException</b>. * * @param mailTemplateId the ID for the mail template */ public MailTemplateNotFoundException(String mailTemplateId) { super("The mail template with ID (" + mailTemplateId + ") could not be found"); } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/MailTemplateRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import java.time.LocalDateTime; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>MailTemplateRepository</b> interface declares the repository for the <b> MailTemplate</b> * domain type. * * @author Marcus Portmann */ public interface MailTemplateRepository extends JpaRepository<MailTemplate, String> { /** * Delete the mail template. * * @param mailTemplateId the ID for the mail template */ @Modifying @Query("delete from MailTemplate mt where mt.id = :mailTemplateId") void deleteById(@Param("mailTemplateId") String mailTemplateId); /** * Retrieve the name of the mail template. * * @param mailTemplateId the ID for the mail template * @return an Optional containing the name for the mail template or an empty Optional if the mail * template could not be found */ @Query("select mt.name from MailTemplate mt where mt.id = :mailTemplateId") Optional<String> getNameById(@Param("mailTemplateId") String mailTemplateId); /** * Retrieve the date and time the mail template was last updated. * * @param mailTemplateId the ID for the mail template * @return an Optional containing the date and time the mail template was last updated or an empty * Optional if the mail template could not be found */ @Query("select mt.updated from MailTemplate mt where mt.id = :mailTemplateId") Optional<LocalDateTime> getUpdatedById(@Param("mailTemplateId") String mailTemplateId); }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/MailTemplateSummary.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>MailTemplateSummary</b> class holds the information for a mail template. * * @author Marcus Portmann */ @Schema(description = "A mail template summary") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "name", "contentType"}) @Entity @Table(schema = "mail", name = "mail_templates") @SuppressWarnings({"unused"}) public class MailTemplateSummary implements Serializable { private static final long serialVersionUID = 1000000; /** The content type for the mail template. */ @Schema(description = "The content type for the mail template", required = true) @JsonProperty(required = true) @NotNull @Column(name = "content_type", nullable = false) private MailTemplateContentType contentType; /** The ID for the mail template. */ @Schema(description = "The ID for the mail template", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "id", length = 100, nullable = false) private String id; /** The name of the mail template. */ @Schema(description = "The name of the mail template", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** Constructs a new <b>MailTemplateSummary</b>. */ public MailTemplateSummary() {} /** * Constructs a new <b>MailTemplateSummary</b>. * * @param id the ID for the mail template * @param name the name of the mail template * @param contentType the content type for the mail template */ public MailTemplateSummary(String id, String name, MailTemplateContentType contentType) { this.id = id; this.name = name; this.contentType = contentType; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } MailTemplateSummary other = (MailTemplateSummary) object; return Objects.equals(id, other.id); } /** * Returns the content type for the mail template. * * @return the content type for the mail template */ public MailTemplateContentType getContentType() { return contentType; } /** * Returns the ID for the mail template. * * @return the ID for the mail template */ public String getId() { return id; } /** * Returns the name of the mail template. * * @return the name of the mail template */ public String getName() { return name; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } /** * Returns a string representation of the object. * * @return a string representation of the object */ @Override public String toString() { return "MailTemplateSummary {id=\"" + getId() + "\", name=\"" + getName() + "\", contentType=\"" + getContentType() + "\"}"; } }
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/MailTemplateSummaryRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import org.springframework.data.jpa.repository.JpaRepository; /** * The <b>MailTemplateSummaryRepository</b> interface declares the repository for the <b> * MailTemplateSummary</b> domain type. * * @author Marcus Portmann */ public interface MailTemplateSummaryRepository extends JpaRepository<MailTemplateSummary, String> {}
0
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail/1.2.0/africa/absa/inception/mail/StringToMailTemplateContentTypeConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.stereotype.Component; /** * The <b>StringToMailTemplateContentTypeConverter</b> class implements the Spring converter that * converts a <b>String</b> type into a <b>MailTemplateContentType</b> type. * * @author Marcus Portmann */ @Component @ReadingConverter public class StringToMailTemplateContentTypeConverter implements Converter<String, MailTemplateContentType> { /** Constructs a new <b>StringToMailTemplateContentTypeConverter</b>. */ public StringToMailTemplateContentTypeConverter() {} @Override public MailTemplateContentType convert(String source) { return MailTemplateContentType.fromCode(source); } }
0
java-sources/africa/absa/inception-mail-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail-api/1.2.0/africa/absa/inception/mail/MailApi.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import africa.absa.inception.api.ApiUtil; import africa.absa.inception.api.ProblemDetails; import africa.absa.inception.api.SecureApi; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * The <b>MailApi</b> class. * * @author Marcus Portmann */ @Tag(name = "Mail") @RestController @RequestMapping(value = "/api/mail") @CrossOrigin @SuppressWarnings({"unused"}) // @el (isSecurityDisabled: africa.absa.inception.api.ApiSecurityExpressionRoot.isSecurityEnabled) public class MailApi extends SecureApi { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(MailApi.class); /** The Mail Service. */ private final IMailService mailService; /** * Constructs a new <b>MailRestController</b>. * * @param applicationContext the Spring application context * @param mailService the Mail Service */ public MailApi(ApplicationContext applicationContext, IMailService mailService) { super(applicationContext); this.mailService = mailService; } /** * Create the new mail template. * * @param mailTemplate the mail template to create * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateMailTemplateException if the mail template already exists * @throws ServiceUnavailableException if the mail template could not be created */ @Operation(summary = "Create the mail template", description = "Create the mail template") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The mail template was created successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "A mail template with the specified ID already exists", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/mail-templates", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Mail.MailTemplateAdministration')") public void createMailTemplate( @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The mail template to create", required = true) @RequestBody MailTemplate mailTemplate) throws InvalidArgumentException, DuplicateMailTemplateException, ServiceUnavailableException { mailService.createMailTemplate(mailTemplate); } /** * Delete the mail template. * * @param mailTemplateId the ID for the mail template * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the mail template could not be deleted */ @Operation(summary = "Delete the mail template", description = "Delete the mail template") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The mail template was deleted successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The mail template could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/mail-templates/{mailTemplateId}", method = RequestMethod.DELETE, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Mail.MailTemplateAdministration')") public void deleteMailTemplate( @Parameter( name = "mailTemplateId", description = "The ID for the mail template", required = true) @PathVariable String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { mailService.deleteMailTemplate(mailTemplateId); } /** * Retrieve the mail template. * * @param mailTemplateId the ID for the mail template * @return the mail template * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the mail template could not be retrieved */ @Operation(summary = "Retrieve the mail template", description = "Retrieve the mail template") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The mail template could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/mail-templates/{mailTemplateId}", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Mail.MailTemplateAdministration')") public MailTemplate getMailTemplate( @Parameter( name = "mailTemplateId", description = "The ID for the mail template", required = true) @PathVariable String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { return mailService.getMailTemplate(mailTemplateId); } /** * Retrieve the name of the mail template. * * @param mailTemplateId the ID for the mail template * @return the name of the mail template * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the name of the mail template could not be retrieved */ @Operation( summary = "Retrieve the name of the mail template", description = "Retrieve the name of the mail template") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The mail template could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/mail-templates/{mailTemplateId}/name", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Mail.MailTemplateAdministration')") public String getMailTemplateName( @Parameter( name = "mailTemplateId", description = "The ID for the mail template", required = true) @PathVariable String mailTemplateId) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { return ApiUtil.quote(mailService.getMailTemplateName(mailTemplateId)); } /** * Retrieve the mail template summaries. * * @return the mail template summaries * @throws ServiceUnavailableException if the mail template summaries could not be retrieved */ @Operation( summary = "Retrieve the mail template summaries", description = "Retrieve the mail template summaries") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/mail-template-summaries", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Mail.MailTemplateAdministration')") public List<MailTemplateSummary> getMailTemplateSummaries() throws ServiceUnavailableException { return mailService.getMailTemplateSummaries(); } /** * Retrieve the mail templates. * * @return the mail templates * @throws ServiceUnavailableException if the mail templates could not be retrieved */ @Operation(summary = "Retrieve the mail templates", description = "Retrieve the mail templates") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/mail-templates", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Mail.MailTemplateAdministration')") public List<MailTemplate> getMailTemplates() throws ServiceUnavailableException { return mailService.getMailTemplates(); } // /** Send a test mail. */ // @Operation(summary = "Send a test mail", description = "Send a test mail") // @ApiResponses( // value = { // @ApiResponse(responseCode = "204", description = "The mail was sent successfully"), // @ApiResponse( // responseCode = "400", // description = "Invalid argument", // content = // @Content( // mediaType = "application/problem+json", // schema = @Schema(implementation = ProblemDetails.class))), // @ApiResponse( // responseCode = "403", // description = "Access denied", // content = // @Content( // mediaType = "application/problem+json", // schema = @Schema(implementation = ProblemDetails.class))), // @ApiResponse( // responseCode = "404", // description = "The mail template could not be found", // content = // @Content( // mediaType = "application/problem+json", // schema = @Schema(implementation = ProblemDetails.class))), // @ApiResponse( // responseCode = "409", // description = "A mail template with the specified ID already exists", // content = // @Content( // mediaType = "application/problem+json", // schema = @Schema(implementation = ProblemDetails.class))), // @ApiResponse( // responseCode = "500", // description = // "An error has occurred and the request could not be processed at this time", // content = // @Content( // mediaType = "application/problem+json", // schema = @Schema(implementation = ProblemDetails.class))) // }) // @RequestMapping( // value = "/send-test-mail", // method = RequestMethod.POST, // produces = "application/json") // @ResponseStatus(HttpStatus.NO_CONTENT) // @PreAuthorize( // "hasRole('Administrator') or hasAuthority('FUNCTION_Mail.MailTemplateAdministration')") // public void sendMailTest() // throws InvalidArgumentException, DuplicateMailTemplateException, // MailTemplateNotFoundException, ServiceUnavailableException { // MailTemplate mailTemplate = new MailTemplate(); // mailTemplate.setId("TestMailTemplate"); // mailTemplate.setName("Test Mail Template"); // mailTemplate.setContentType(MailTemplateContentType.HTML); // mailTemplate.setTemplate("Hello World!".getBytes()); // // mailService.createMailTemplate(mailTemplate); // // MailTemplate retrievedMailTemplate = mailService.getMailTemplate(mailTemplate.getId()); // // logger.info( // "Retrieved mail template (" // + retrievedMailTemplate.getName() // + ") with ID (" // + retrievedMailTemplate.getId() // + ")"); // } /** * Update the mail template. * * @param mailTemplateId the ID for the mail template * @param mailTemplate the mail template * @throws InvalidArgumentException if an argument is invalid * @throws MailTemplateNotFoundException if the mail template could not be found * @throws ServiceUnavailableException if the mail template could not be updated */ @Operation(summary = "Update the mail template", description = "Update the mail template") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The mail template was updated successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The mail template could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/mail-templates/{mailTemplateId}", method = RequestMethod.PUT, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Mail.MailTemplateAdministration')") public void updateMailTemplate( @Parameter( name = "mailTemplateId", description = "The ID for the mail template", required = true) @PathVariable String mailTemplateId, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The mail template to update", required = true) @RequestBody MailTemplate mailTemplate) throws InvalidArgumentException, MailTemplateNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(mailTemplateId)) { throw new InvalidArgumentException("mailTemplateId"); } if (mailTemplate == null) { throw new InvalidArgumentException("mailTemplate"); } if (!mailTemplateId.equals(mailTemplate.getId())) { throw new InvalidArgumentException("mailTemplate"); } mailService.updateMailTemplate(mailTemplate); } }
0
java-sources/africa/absa/inception-mail-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail-api/1.2.0/africa/absa/inception/mail/MailApiConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; import io.swagger.v3.oas.models.info.Info; import org.springdoc.core.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * The <b>MailApiConfiguration</b> class provides the Spring configuration for the Mail API module. * * @author Marcus Portmann */ @Configuration public class MailApiConfiguration { /** * Returns the grouped Open API for the Mail API. * * @return the grouped Open API for the Mail API */ @Bean public GroupedOpenApi mailOpenApi() { return GroupedOpenApi.builder() .group("mail") .packagesToScan("africa.absa.inception.mail") .addOpenApiCustomiser( openApi -> openApi.info(new Info().title("Mail API").version(Version.PROJECT_VERSION))) .build(); } }
0
java-sources/africa/absa/inception-mail-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-mail-api/1.2.0/africa/absa/inception/mail/Version.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.mail; /** * The <b>Version</b> class. * * @author Marcus Portmann */ public final class Version { public static final String PROJECT_VERSION = "1.2.0"; }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/OAuth2AuthorizationServerConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; /** * The <b>OAuth2AuthorizationServerConfiguration</b> class provides the Spring configuration for the * OAuth2 Authorization Server module. * * @author Marcus Portmann */ @Configuration public class OAuth2AuthorizationServerConfiguration { /* The RSA private key used to sign the JWTs. */ @Value("${inception.oauth2.authorization-server.jwt.rsa-private-key-location}") private RSAPrivateKey rsaPrivateKey; /* The RSA public key used to verify the JWTs. */ @Value("${inception.oauth2.authorization-server.jwt.rsa-public-key-location}") private RSAPublicKey rsaPublicKey; }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/AuthorizationServerController.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import africa.absa.inception.oauth2.server.authorization.token.ITokenService; import africa.absa.inception.oauth2.server.authorization.token.InvalidOAuth2RefreshTokenException; import africa.absa.inception.oauth2.server.authorization.token.OAuth2AccessToken; import africa.absa.inception.oauth2.server.authorization.token.OAuth2RefreshToken; import africa.absa.inception.oauth2.server.authorization.token.RefreshedOAuth2Tokens; import africa.absa.inception.security.AuthenticationFailedException; import africa.absa.inception.security.ExpiredPasswordException; import africa.absa.inception.security.ISecurityService; import africa.absa.inception.security.UserLockedException; import africa.absa.inception.security.UserNotFoundException; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * The <b>AuthorizationServerController</b> class implements a simple OAuth authorization server * that provides support for the Resource Owner Password Grant. */ @Controller @RequestMapping("oauth") @CrossOrigin public class AuthorizationServerController { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(AuthorizationServerController.class); /* Security Service */ private final ISecurityService securityService; /* Token Service */ private final ITokenService tokenService; /** * Constructs a new <b>AuthorizationServerController</b>. * * @param securityService the Security Service * @param tokenService the Token Service */ public AuthorizationServerController( ISecurityService securityService, ITokenService tokenService) { this.securityService = securityService; this.tokenService = tokenService; } /** * The "token" endpoint that supports the Resource Owner Password Grant. * * @param request the HTTP servlet request * @param parameters the request parameter s * @return the token response */ @PostMapping(value = "/token", produces = "application/json") public ResponseEntity<String> token( HttpServletRequest request, @RequestParam Map<String, String> parameters) { // TODO: Implement OAuth2 client authentication -- MARCUS Response response = processAccessTokenRequest(request, parameters); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); httpHeaders.set("Pragma", "no-cache"); return new ResponseEntity<>(response.getBody(), httpHeaders, response.getStatus()); } private boolean authenticateClient(HttpServletRequest request) { /* TODO: Authenticate the client using the HTTP basic authentication scheme or the client ID * and client secret request body parameters for the x-www-form-urlencoded request. * * See: https://tools.ietf.org/html/rfc6749#section-2.3.1 */ return true; } private Response processAccessTokenRequest( HttpServletRequest request, Map<String, String> parameters) { // Retrieve the grant type associated with the request String grantType = parameters.get(GrantRequest.GRANT_TYPE_PARAMETER); // If no grant type is specified return an error if (!StringUtils.hasText(grantType)) { return new InvalidRequestErrorResponse( "Missing '" + GrantRequest.GRANT_TYPE_PARAMETER + "' parameter"); } if (grantType.equals(ResourceOwnerPasswordCredentialsGrantRequest.GRANT_TYPE)) { if (!ResourceOwnerPasswordCredentialsGrantRequest.isValid(parameters)) { return new InvalidRequestErrorResponse( "Invalid 'Resource Owner Password Credentials Grant' request"); } ResourceOwnerPasswordCredentialsGrantRequest grantRequest = new ResourceOwnerPasswordCredentialsGrantRequest(parameters); return processResourceOwnerPasswordCredentialsGrantRequest(grantRequest); } else if (grantType.equals(RefreshAccessTokenGrantRequest.GRANT_TYPE)) { if (!RefreshAccessTokenGrantRequest.isValid(parameters)) { return new InvalidRequestErrorResponse("Invalid 'Refresh Access Token Grant' request"); } RefreshAccessTokenGrantRequest grantRequest = new RefreshAccessTokenGrantRequest(parameters); return processRefreshAccessTokenGrantRequest(grantRequest); } else { return new UnsupportedGrantTypeErrorResponse(grantType); } } private Response processRefreshAccessTokenGrantRequest(RefreshAccessTokenGrantRequest request) { try { RefreshedOAuth2Tokens refreshedOAuth2Tokens = tokenService.refreshOAuth2Tokens(request.getRefreshToken()); if (refreshedOAuth2Tokens.getRefreshToken() == null) { return new ResourceOwnerPasswordCredentialsGrantResponse( refreshedOAuth2Tokens.getAccessToken().getTokenValue(), refreshedOAuth2Tokens.getAccessToken().getExpiresIn()); } else { return new ResourceOwnerPasswordCredentialsGrantResponse( refreshedOAuth2Tokens.getAccessToken().getTokenValue(), refreshedOAuth2Tokens.getAccessToken().getExpiresIn(), refreshedOAuth2Tokens.getRefreshToken().getTokenValue()); } } catch (InvalidOAuth2RefreshTokenException e) { return new InvalidGrantErrorResponse("Invalid refresh token"); } catch (Throwable e) { logger.error("Failed to process the 'Refresh Access Token Grant' request", e); return new SystemUnavailableResponse( "Failed to process the 'Refresh Access Token Grant' request", e); } } private Response processResourceOwnerPasswordCredentialsGrantRequest( ResourceOwnerPasswordCredentialsGrantRequest request) { try { UUID userDirectoryId = securityService.authenticate(request.getUsername(), request.getPassword()); OAuth2AccessToken oAuth2AccessToken = tokenService.issueOAuth2AccessToken( request.getUsername(), (request.getScope() != null) ? Set.of(request.getScope().split(" ")) : null); OAuth2RefreshToken oAuth2RefreshToken = tokenService.issueOAuth2RefreshToken( oAuth2AccessToken.getSubject(), (request.getScope() != null) ? Set.of(request.getScope().split(" ")) : null); return new ResourceOwnerPasswordCredentialsGrantResponse( oAuth2AccessToken.getTokenValue(), oAuth2AccessToken.getExpiresIn(), oAuth2RefreshToken.getTokenValue()); } catch (AuthenticationFailedException | UserNotFoundException e) { return new InvalidGrantErrorResponse("Bad credentials"); } catch (UserLockedException e) { return new InvalidGrantErrorResponse("User locked"); } catch (ExpiredPasswordException e) { return new InvalidGrantErrorResponse("Credentials expired"); } catch (Throwable e) { logger.error( "Failed to process the 'Resource Owner Password Credentials Grant' request for the user (" + request.getUsername() + ")", e); return new SystemUnavailableResponse( "Failed to process the 'Resource Owner Password Credentials Grant' request for the user '" + request.getUsername() + "'", e); } } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/ErrorResponse.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import java.io.StringWriter; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; /** * The <b>ErrorGrantResponse</b> class holds the information for an OAuth2 error response and * provides the base class that all OAuth2 error response classes should be derived from. * * <p>See: <a href="https://tools.ietf.org/html/rfc6749#section-5.2">Error Response</a> * * @author Marcus Portmann */ public abstract class ErrorResponse extends Response { /** The single ASCII error code. */ private final String error; /** The optional human-readable ASCII text description of the error. */ private final String errorDescription; /** * Constructs a new <b>ErrorGrantResponse</b>. * * @param status the HTTP status that should be returned for the OAuth2 error response * @param error the single ASCII error code */ public ErrorResponse(HttpStatus status, String error) { super(status); this.error = error; this.errorDescription = null; } /** * Constructs a new <b>ErrorResponse</b>. * * @param status the HTTP status that should be returned for the OAuth2 error response * @param error the single ASCII error code * @param errorDescription the optional human-readable ASCII text description of the error */ public ErrorResponse(HttpStatus status, String error, String errorDescription) { super(status); this.error = error; this.errorDescription = errorDescription; } /** * Returns the body for the OAuth2 response. * * @return the body for the OAuth2 response */ @Override public String getBody() { try { JsonFactory jsonFactory = new JsonFactory(); StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = jsonFactory.createGenerator(stringWriter); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("error", error); if (StringUtils.hasText(errorDescription)) { jsonGenerator.writeStringField("error_description", errorDescription); } jsonGenerator.writeEndObject(); jsonGenerator.close(); return stringWriter.getBuffer().toString(); } catch (Throwable e) { throw new RuntimeException("Failed to construct the body for the error response", e); } } /** * Returns the single ASCII error code. * * @return the single ASCII error code */ public String getError() { return error; } /** * Returns the optional human-readable ASCII text description of the error. * * @return the optional human-readable ASCII text description of the error */ public String getErrorDescription() { return errorDescription; } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/GrantRequest.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import java.util.Map; /** * The <b>GrantRequest</b> class provides the base class that all OAuth2 grant request classes * should be derived from. * * @author Marcus Portmann */ public abstract class GrantRequest { /** * The name of the client ID parameter. * * <p>This parameter is REQUIRED if client authentication is enabled. */ public static final String CLIENT_ID_PARAMETER = "client_id"; /** * The name of the client secret parameter. * * <p>This parameter is REQUIRED if client authentication is enabled. */ public static final String CLIENT_SECRET_PARAMETER = "client_secret"; /** * The name of the grant type parameter. * * <p>This parameter is REQUIRED. */ public static final String GRANT_TYPE_PARAMETER = "grant_type"; /** * The name of the parameter providing the requested access token scope. * * <p>See <a href="https://tools.ietf.org/html/rfc6749#section-3.3">Access Token Scope</a> * * <p>This parameter is OPTIONAL. */ public static final String SCOPE_PARAMETER = "scope"; /** * The name of the state parameter. * * <p>This parameter is OPTIONAL. */ public static final String STATE_PARAMETER = "state"; /** The client identifier issued to the client. */ private final String clientId; /** The client secret. */ private final String clientSecret; /** The grant type. */ private final String grantType; /** The requested scope(s) for the access request. */ private final String scope; /** The state received from the client. */ private final String state; /** * Constructs a new <b>GrantRequest</b>. * * @param parameters the request parameters */ public GrantRequest(Map<String, String> parameters) { this.grantType = parameters.get(GRANT_TYPE_PARAMETER); this.clientId = parameters.get(CLIENT_ID_PARAMETER); this.clientSecret = parameters.get(CLIENT_SECRET_PARAMETER); this.scope = parameters.get(SCOPE_PARAMETER); this.state = parameters.get(STATE_PARAMETER); } /** * Returns the client identifier issued to the client. * * @return the client identifier issued to the client */ public String getClientId() { return clientId; } /** * Returns the client secret. * * @return the client secret */ public String getClientSecret() { return clientSecret; } /** * Returns the grant type. * * @return the grant type */ public String getGrantType() { return grantType; } /** * Returns the requested scope(s) for the access request. * * @return the requested scope(s) for the access request */ public String getScope() { return scope; } /** * Returns the state received from the client. * * @return the state received from the client */ public String getState() { return state; } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/InvalidClientErrorResponse.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import org.springframework.http.HttpStatus; /** * The <b>InvalidClientErrorResponse</b> class holds the information for an OAuth2 invalid client * error response. * * <p>See: <a href="https://tools.ietf.org/html/rfc6749#section-5.2">Error Response</a> * * @author Marcus Portmann */ public class InvalidClientErrorResponse extends ErrorResponse { /** The error code for the OAuth2 invalid client error response. */ public static final String ERROR_CODE = "invalid_client"; /** * Constructs a new <b>InvalidClientErrorResponse</b>. * * @param status the HTTP status that should be returned for the OAuth2 invalid client error * response */ public InvalidClientErrorResponse(HttpStatus status) { super(status, ERROR_CODE); } /** * Constructs a new <b>InvalidClientErrorResponse</b>. * * @param status the HTTP status that should be returned for the OAuth2 invalid client error * response * @param errorDescription the optional human-readable ASCII text description of the error */ public InvalidClientErrorResponse(HttpStatus status, String errorDescription) { super(status, ERROR_CODE, errorDescription); } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/InvalidGrantErrorResponse.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import org.springframework.http.HttpStatus; /** * The <b>InvalidGrantErrorResponse</b> class holds the information for an OAuth2 invalid grant * error response. * * @author Marcus Portmann */ public class InvalidGrantErrorResponse extends ErrorResponse { /** The error code for the OAuth2 invalid grant error response. */ public static final String ERROR_CODE = "invalid_grant"; /** Constructs a new <b>InvalidGrantErrorResponse</b>. */ public InvalidGrantErrorResponse() { super(HttpStatus.BAD_REQUEST, ERROR_CODE); } /** * Constructs a new <b>InvalidGrantErrorResponse</b>. * * @param errorDescription the optional human-readable ASCII text description of the error */ public InvalidGrantErrorResponse(String errorDescription) { super(HttpStatus.BAD_REQUEST, ERROR_CODE, errorDescription); } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/InvalidRequestErrorResponse.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import org.springframework.http.HttpStatus; /** * The <b>InvalidRequestErrorResponse</b> class holds the information for an OAuth2 invalid request * error response. * * @author Marcus Portmann */ public class InvalidRequestErrorResponse extends ErrorResponse { /** The error code for the OAuth2 invalid request error response. */ public static final String ERROR_CODE = "invalid_request"; /** Constructs a new <b>InvalidRequestErrorResponse</b>. */ public InvalidRequestErrorResponse() { super(HttpStatus.BAD_REQUEST, ERROR_CODE); } /** * Constructs a new <b>InvalidRequestErrorResponse</b>. * * @param errorDescription the optional human-readable ASCII text description of the error */ public InvalidRequestErrorResponse(String errorDescription) { super(HttpStatus.BAD_REQUEST, ERROR_CODE, errorDescription); } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/InvalidScopeErrorResponse.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import org.springframework.http.HttpStatus; /** * The <b>InvalidScopeErrorResponse</b> class holds the information for an OAuth2 invalid scope * error response. * * @author Marcus Portmann */ public class InvalidScopeErrorResponse extends ErrorResponse { /** The error code for the OAuth2 invalid scope error response. */ public static final String ERROR_CODE = "invalid_request"; /** Constructs a new <b>InvalidScopeErrorResponse</b>. */ public InvalidScopeErrorResponse() { super(HttpStatus.BAD_REQUEST, ERROR_CODE); } /** * Constructs a new <b>InvalidScopeErrorResponse</b>. * * @param errorDescription the optional human-readable ASCII text description of the error */ public InvalidScopeErrorResponse(String errorDescription) { super(HttpStatus.BAD_REQUEST, ERROR_CODE, errorDescription); } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/RefreshAccessTokenGrantRequest.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import java.util.Map; import org.springframework.util.StringUtils; /** * The <b>RefreshAccessTokenGrantRequest</b> class holds the information for a Refresh Access Token * Grant request. * * <p>See <a href="https://tools.ietf.org/html/rfc6749#section-6">Refreshing an Access Token</a> * * @author Marcus Portmann */ public class RefreshAccessTokenGrantRequest extends GrantRequest { /** The grant type for the Refresh Access Token Grant. */ public static final String GRANT_TYPE = "refresh_token"; /** * The name of the refresh token parameter. * * <p>This parameter is REQUIRED. */ public static final String REFRESH_TOKEN_PARAMETER = "refresh_token"; /** The refresh token. */ private final String refreshToken; /** * Constructs a new <b>RefreshAccessTokenGrantRequest</b>. * * @param parameters the request parameters */ public RefreshAccessTokenGrantRequest(Map<String, String> parameters) { super(parameters); this.refreshToken = parameters.get(REFRESH_TOKEN_PARAMETER); } /** * Check whether the required information for the Resource Owner Password Credentials Grant is * provided as part of the HTTP servlet request. * * @param parameters the request parameters * @return <b>true</b> if the HTTP servlet request contains the required information for the * Resource Owner Password Credentials Grant or <b>false</b> otherwise */ public static boolean isValid(Map<String, String> parameters) { if (!StringUtils.hasText(parameters.get(GRANT_TYPE_PARAMETER))) { return false; } if (!GRANT_TYPE.equals(parameters.get(GRANT_TYPE_PARAMETER))) { return false; } return StringUtils.hasText(parameters.get(REFRESH_TOKEN_PARAMETER)); } /** * Returns the refresh token. * * @return the refresh token */ public String getRefreshToken() { return refreshToken; } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/ResourceOwnerPasswordCredentialsGrantRequest.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import java.util.Map; import org.springframework.util.StringUtils; /** * The <b>ResourceOwnerPasswordCredentialsGrantRequest</b> class holds the information for a * Resource Owner Password Credentials Grant request. * * <p>See <a href="https://tools.ietf.org/html/rfc6749#section-4.3.2">Access Token Request</a> * * @author Marcus Portmann */ public class ResourceOwnerPasswordCredentialsGrantRequest extends GrantRequest { /** The grant type for the Resource Owner Password Credentials Grant. */ public static final String GRANT_TYPE = "password"; /** * The name of the resource owner password parameter. * * <p>This parameter is REQUIRED. */ public static final String PASSWORD_PARAMETER = "password"; /** * The name of the resource owner username parameter. * * <p>This parameter is REQUIRED. */ public static final String USERNAME_PARAMETER = "username"; /** The resource owner password. */ private final String password; /** The resource owner username. */ private final String username; /** * Constructs a new <b>ResourceOwnerPasswordCredentialsGrantRequest</b>. * * @param parameters the request parameters */ public ResourceOwnerPasswordCredentialsGrantRequest(Map<String, String> parameters) { super(parameters); this.username = parameters.get(USERNAME_PARAMETER); this.password = parameters.get(PASSWORD_PARAMETER); } /** * Check whether the required information for the Resource Owner Password Credentials Grant is * provided as part of the HTTP servlet request. * * @param parameters the request parameters * @return <b>true</b> if the HTTP servlet request contains the required information for the * Resource Owner Password Credentials Grant or <b>false</b> otherwise */ public static boolean isValid(Map<String, String> parameters) { if (!StringUtils.hasText(parameters.get(GRANT_TYPE_PARAMETER))) { return false; } if (!GRANT_TYPE.equals(parameters.get(GRANT_TYPE_PARAMETER))) { return false; } if (!StringUtils.hasText(parameters.get(USERNAME_PARAMETER))) { return false; } return StringUtils.hasText(parameters.get(PASSWORD_PARAMETER)); } /** * Returns the resource owner password. * * @return the resource owner password */ public String getPassword() { return password; } /** * Returns the resource owner username. * * @return the resource owner username */ public String getUsername() { return username; } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/ResourceOwnerPasswordCredentialsGrantResponse.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import java.io.StringWriter; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; /** * The <b>ResourceOwnerPasswordCredentialsGrantResponse</b> class holds the information for a * Resource Owner Password Credentials Grant response. * * @author Marcus Portmann */ public class ResourceOwnerPasswordCredentialsGrantResponse extends Response { /** The access token. */ private final String accessToken; /** The lifetime in seconds of the access token. */ private final long expiresIn; /** The refresh token. */ private final String refreshToken; /** The access token scope. */ private final String scope; /** * Constructs a new <b>ResourceOwnerPasswordCredentialsGrantResponse</b>. * * @param accessToken the access token * @param expiresIn the access token validity in seconds * @param scope the access token scope * @param refreshToken the refresh token */ public ResourceOwnerPasswordCredentialsGrantResponse( String accessToken, int expiresIn, String scope, String refreshToken) { super(HttpStatus.OK); this.accessToken = accessToken; this.expiresIn = expiresIn; this.scope = scope; this.refreshToken = refreshToken; } /** * Constructs a new <b>ResourceOwnerPasswordCredentialsGrantResponse</b>. * * @param accessToken the access token * @param expiresIn the access token validity in seconds * @param refreshToken the refresh token */ public ResourceOwnerPasswordCredentialsGrantResponse( String accessToken, long expiresIn, String refreshToken) { super(HttpStatus.OK); this.accessToken = accessToken; this.expiresIn = expiresIn; this.scope = null; this.refreshToken = refreshToken; } /** * Constructs a new <b>ResourceOwnerPasswordCredentialsGrantResponse</b>. * * @param accessToken the access token * @param expiresIn the lifetime in seconds of the access token */ public ResourceOwnerPasswordCredentialsGrantResponse(String accessToken, long expiresIn) { super(HttpStatus.OK); this.accessToken = accessToken; this.expiresIn = expiresIn; this.scope = null; this.refreshToken = null; } /** * Returns the body for the OAuth2 response. * * @return the body for the OAuth2 response */ @Override public String getBody() { try { JsonFactory jsonFactory = new JsonFactory(); StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = jsonFactory.createGenerator(stringWriter); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("access_token", accessToken); jsonGenerator.writeStringField("token_type", "bearer"); jsonGenerator.writeNumberField("expires_in", expiresIn); if (StringUtils.hasText(refreshToken)) { jsonGenerator.writeStringField("refresh_token", refreshToken); } if (StringUtils.hasText(scope)) { jsonGenerator.writeStringField("scope", scope); } jsonGenerator.writeEndObject(); jsonGenerator.close(); return stringWriter.getBuffer().toString(); } catch (Throwable e) { throw new RuntimeException( "Failed to construct the body for the Resource Owner Password Credentials Grant response", e); } } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/Response.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import org.springframework.http.HttpStatus; /** * The <b>Response</b> class provides the base class that all OAuth2 response classes should be * derived from. * * @author Marcus Portmann */ public abstract class Response { /** The HTTP status that should be returned for the OAuth2 response. */ private final HttpStatus status; /** * Constructs a new <b>Response</b>. * * @param status the HTTP status that should be returned for the OAuth2 response */ public Response(HttpStatus status) { this.status = status; } /** * Returns the body for the OAuth2 response. * * @return the body for the OAuth2 response */ public abstract String getBody(); /** * Returns the HTTP status that should be returned for the OAuth2 response. * * @return the HTTP status that should be returned for the OAuth2 response */ public HttpStatus getStatus() { return status; } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/SystemUnavailableResponse.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import africa.absa.inception.core.util.ISO8601Util; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.time.LocalDateTime; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; /** * The <b>SystemUnavailableResponse</b> class holds the information for a response returned to * indicated that the system encountered an error and is unable to process the OAuth2 request. * * @author Marcus Portmann */ public class SystemUnavailableResponse extends Response { /** The message. */ private final String message; /** The date and time the error occurred. */ private final LocalDateTime timestamp; /** The optional detail. */ private String detail; /** The optional fully qualified name of the exception associated with the error. */ private String exception; /** The optional stack trace associated with the error. */ private String stackTrace; /** The URI for the HTTP request that resulted in the error. */ @JsonProperty private String uri; /** * Constructs a new <b>SystemUnavailableResponse</b>. * * @param message the message */ public SystemUnavailableResponse(String message) { this(message, null); } /** * Constructs a new <b>SystemUnavailableResponse</b>. * * @param message the message * @param cause the cause */ public SystemUnavailableResponse(String message, Throwable cause) { super(HttpStatus.INTERNAL_SERVER_ERROR); this.timestamp = LocalDateTime.now(); this.message = message; if (cause != null) { this.detail = cause.getMessage(); this.exception = cause.getClass().getName(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); pw.println(cause.getMessage()); pw.println(); cause.printStackTrace(pw); pw.flush(); this.stackTrace = baos.toString(); } catch (Throwable ignored) { } } } /** * Returns the body for the OAuth2 response. * * @return the body for the OAuth2 response */ @Override public String getBody() { try { JsonFactory jsonFactory = new JsonFactory(); StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = jsonFactory.createGenerator(stringWriter); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("timestamp", ISO8601Util.fromLocalDateTime(timestamp)); jsonGenerator.writeStringField("message", message); if (StringUtils.hasText(detail)) { jsonGenerator.writeStringField("detail", detail); } if (StringUtils.hasText(exception)) { jsonGenerator.writeStringField("exception", exception); } if (StringUtils.hasText(stackTrace)) { jsonGenerator.writeStringField("exception", stackTrace); } jsonGenerator.writeEndObject(); jsonGenerator.close(); return stringWriter.getBuffer().toString(); } catch (Throwable e) { throw new RuntimeException( "Failed to construct the body for the system unavailable response", e); } } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/UnauthorizedClientErrorResponse.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import org.springframework.http.HttpStatus; /** * The <b>UnauthorizedClientErrorResponse</b> class holds the information for an OAuth2 unauthorized * client error response. * * @author Marcus Portmann */ public class UnauthorizedClientErrorResponse extends ErrorResponse { /** The error code for the OAuth2 unauthorized client error response. */ public static final String ERROR_CODE = "unauthorized_client"; /** Constructs a new <b>UnauthorizedClientErrorResponse</b>. */ public UnauthorizedClientErrorResponse() { super(HttpStatus.BAD_REQUEST, ERROR_CODE); } /** * Constructs a new <b>UnauthorizedClientErrorResponse</b>. * * @param errorDescription the optional human-readable ASCII text description of the error */ public UnauthorizedClientErrorResponse(String errorDescription) { super(HttpStatus.BAD_REQUEST, ERROR_CODE, errorDescription); } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/controller/UnsupportedGrantTypeErrorResponse.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.controller; import org.springframework.http.HttpStatus; /** * The <b>UnsupportedGrantTypeErrorResponse</b> class holds the information for an OAuth2 * unsupported grant type error response. * * @author Marcus Portmann */ public class UnsupportedGrantTypeErrorResponse extends ErrorResponse { /** The error code for the OAuth2 unsupported grant type error response. */ public static final String ERROR_CODE = "unsupported_grant_type"; /** * Constructs a new <b>UnsupportedGrantTypeErrorResponse</b>. * * @param grantType the unsupported grant type */ public UnsupportedGrantTypeErrorResponse(String grantType) { super(HttpStatus.BAD_REQUEST, ERROR_CODE, "Unsupported grant type '" + grantType + "'"); } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/token/ITokenService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.token; import africa.absa.inception.core.service.ServiceUnavailableException; import java.util.Set; /** * The <b>ITokenService</b> interface defines the functionality provided by a Token Service * implementation, which manages the OAuth2 tokens for an application. * * @author Marcus Portmann */ public interface ITokenService { /** * Issue an OAuth2 access token for the specified user. * * @param username the username for the user * @param scopes the optional scope(s) for the access token * @return the OAuth2 access token * @throws ServiceUnavailableException if the OAuth2 access token could not be issued for the user */ OAuth2AccessToken issueOAuth2AccessToken(String username, Set<String> scopes) throws ServiceUnavailableException; /** * Issue an OAuth2 refresh token for the specified user. * * @param username the username for the user * @param scopes the optional scope(s) for the refresh token * @return the OAuth2 refresh token * @throws ServiceUnavailableException if the OAuth2 refresh token could not be issued for the * user */ OAuth2RefreshToken issueOAuth2RefreshToken(String username, Set<String> scopes) throws ServiceUnavailableException; /** * Refresh an OAuth2 access token and if required the OAuth2 refresh token. * * @param encodedOAuth2RefreshToken the encoded OAuth2 refresh token * @return the refreshed tokens * @throws InvalidOAuth2RefreshTokenException if the OAuth2 refresh token is invalid * @throws ServiceUnavailableException if the OAuth2 access token and refresh token could not be * refreshed */ RefreshedOAuth2Tokens refreshOAuth2Tokens(String encodedOAuth2RefreshToken) throws InvalidOAuth2RefreshTokenException, ServiceUnavailableException; }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/token/InvalidOAuth2RefreshTokenException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.token; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * The <b>InvalidOAuth2RefreshTokenException</b> exception is thrown to indicate an error condition * as a result of an invalid OAuth2 refresh token. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/oauth2/invalid-oauth2-refresh-token", title = "The OAuth2 refresh token is invalid.", status = 400) public class InvalidOAuth2RefreshTokenException extends ServiceException { private static final long serialVersionUID = 1000000; /** Constructs a new <b>InvalidOAuth2RefreshTokenException</b> with the specified message. */ public InvalidOAuth2RefreshTokenException() { super("The OAuth2 refresh token is invalid"); } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/token/OAuth2AccessToken.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.token; import africa.absa.inception.security.User; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.JWSSigner; import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTClaimsSet.Builder; import com.nimbusds.jwt.SignedJWT; import java.security.interfaces.RSAPrivateKey; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Set; import java.util.UUID; import org.springframework.util.StringUtils; /** * The <b>OAuth2AccessToken</b> holds the information for an OAuth2 access token. * * @author Marcus Portmann */ public class OAuth2AccessToken extends org.springframework.security.oauth2.core.OAuth2AccessToken { /** The name of the functions claim that provides the functions assigned to the user. */ public static final String FUNCTIONS_CLAIM = "functions"; /** The name of the claim that provides the name of the user. */ public static final String NAME_CLAIM = "name"; /** The name of the roles claim that provides the roles assigned to the user. */ public static final String ROLES_CLAIM = "roles"; /** The name of the scope claim. */ public static final String SCOPE_CLAIM = "scope"; /** * The name of the tenants claim that provides the IDs for the tenants the user is associated * with. */ public static final String TENANTS_CLAIM = "tenants"; /** * The name of the user directory ID claim that provides the ID for the user directory the user is * associated with. */ public static final String USER_DIRECTORY_ID_CLAIM = "user_directory_id"; private static final long serialVersionUID = 1000000; /** The subject for the token. */ private final String subject; /** * Constructs a new <b>OAuth2AccessToken</b>. * * @param tokenType the token type * @param tokenValue the token value * @param subject the subject for the token * @param issuedAt the time at which the token was issued * @param expiresAt the expiration time on or after which the token MUST NOT be accepted * @param scopes the scope(s) associated to the token */ public OAuth2AccessToken( TokenType tokenType, String tokenValue, String subject, Instant issuedAt, Instant expiresAt, Set<String> scopes) { super(tokenType, tokenValue, issuedAt, expiresAt, scopes); this.subject = subject; } /** * Build a new <b>OAuth2AccessToken</b>. * * @param user the User the token is being issued for * @param roleCodes the role codes for the user the token is being issued for * @param functionCodes the function codes for the user the token is being issued for * @param tenantIds the IDs for the tenants that the user the token is being issued for is * associated with * @param scopes the optional scope(s) associated to the token * @param issuer the optional issuer of the token, which can be <b>null</b> * @param validFor the number of seconds the token should be valid for * @param rsaPrivateKey the RSA private key used to sign the token * @return the OAuth2 access token */ public static OAuth2AccessToken build( User user, List<String> roleCodes, List<String> functionCodes, List<UUID> tenantIds, Set<String> scopes, String issuer, int validFor, RSAPrivateKey rsaPrivateKey) { try { Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plusSeconds(validFor); JWSSigner signer = new RSASSASigner(rsaPrivateKey); JWTClaimsSet.Builder jwtClaimsSetBuilder = new Builder(); jwtClaimsSetBuilder.subject(user.getUsername()); if (StringUtils.hasText(issuer)) { jwtClaimsSetBuilder.issuer(issuer); } if (StringUtils.hasText(user.getName())) { jwtClaimsSetBuilder.claim(NAME_CLAIM, user.getName()); } else if (StringUtils.hasText(user.getEmail())) { jwtClaimsSetBuilder.claim(NAME_CLAIM, user.getEmail()); } else { jwtClaimsSetBuilder.claim(NAME_CLAIM, user.getUsername()); } jwtClaimsSetBuilder.claim(USER_DIRECTORY_ID_CLAIM, user.getUserDirectoryId().toString()); jwtClaimsSetBuilder.issueTime(Date.from(issuedAt)); jwtClaimsSetBuilder.expirationTime(Date.from(expiresAt)); jwtClaimsSetBuilder.claim( TENANTS_CLAIM, Arrays.stream(tenantIds.toArray(new UUID[0])) .map(Object::toString) .toArray(String[]::new)); jwtClaimsSetBuilder.claim(ROLES_CLAIM, roleCodes); jwtClaimsSetBuilder.claim(FUNCTIONS_CLAIM, functionCodes); if ((scopes != null) && (!scopes.isEmpty())) { jwtClaimsSetBuilder.claim( SCOPE_CLAIM, StringUtils.collectionToDelimitedString(scopes, " ")); } SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).build(), jwtClaimsSetBuilder.build()); signedJWT.sign(signer); return new OAuth2AccessToken( TokenType.BEARER, signedJWT.serialize(), user.getUsername(), issuedAt, expiresAt, scopes); } catch (Throwable e) { throw new OAuth2AccessTokenException("Failed to build the OAuth2 access token", e); } } /** * Returns the lifetime in seconds of the access token. * * @return the lifetime in seconds of the access token */ public long getExpiresIn() { if (getIssuedAt() == null) { return Duration.between(Instant.now(), getExpiresAt()).toSeconds(); } else { return Duration.between(getIssuedAt(), getExpiresAt()).toSeconds(); } } /** * Returns the subject for the token. * * @return the subject for the token */ public String getSubject() { return subject; } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/token/OAuth2AccessTokenException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.token; /** * The <b>OAuth2AccessTokenException</b> exception is thrown to indicate an error condition when * working with an OAuth2 access token. * * @author Marcus Portmann */ public class OAuth2AccessTokenException extends RuntimeException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>OAuth2AccessTokenException</b> with the specified message and cause. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ OAuth2AccessTokenException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/token/OAuth2RefreshToken.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.token; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.JWSSigner; import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTClaimsSet.Builder; import com.nimbusds.jwt.SignedJWT; import java.security.interfaces.RSAPrivateKey; import java.time.Instant; import java.util.Date; import java.util.Set; import org.springframework.util.StringUtils; /** * The <b>OAuth2RefreshToken</b> class holds the information for an OAuth2 refresh token. * * @author Marcus Portmann */ public class OAuth2RefreshToken extends org.springframework.security.oauth2.core.OAuth2RefreshToken { /** The name of the scope claim. */ public static final String SCOPE_CLAIM = "scope"; private static final long serialVersionUID = 1000000; /** * Constructs a new <b>OAuth2RefreshToken</b>. * * @param tokenValue the token value * @param issuedAt the time at which the token was issued */ public OAuth2RefreshToken(String tokenValue, Instant issuedAt) { super(tokenValue, issuedAt); } /** * Build a new <b>OAuth2RefreshToken</b>. * * @param username the username for the user the token is being issued for * @param scopes the optional scope(s) associated to the token * @param validFor the number of seconds the token should be valid for * @param rsaPrivateKey the RSA private key used to sign the token * @return the OAuth2 refresh token */ public static OAuth2RefreshToken build( String username, Set<String> scopes, int validFor, RSAPrivateKey rsaPrivateKey) { try { Instant issuedAt = Instant.now(); Instant expiresAt = issuedAt.plusSeconds(validFor); JWSSigner signer = new RSASSASigner(rsaPrivateKey); JWTClaimsSet.Builder jwtClaimsSetBuilder = new Builder(); jwtClaimsSetBuilder.subject(username); if ((scopes != null) && (!scopes.isEmpty())) { jwtClaimsSetBuilder.claim( SCOPE_CLAIM, StringUtils.collectionToDelimitedString(scopes, " ")); } jwtClaimsSetBuilder.issueTime(Date.from(issuedAt)); jwtClaimsSetBuilder.expirationTime(Date.from(expiresAt)); SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).build(), jwtClaimsSetBuilder.build()); signedJWT.sign(signer); return new OAuth2RefreshToken(signedJWT.serialize(), issuedAt); } catch (Throwable e) { throw new OAuth2AccessTokenException("Failed to build the OAuth2 refresh token", e); } } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/token/RefreshedOAuth2Tokens.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.token; /** * The <b>RefreshedOAuth2Tokens</b> class holds a refreshed OAuth2 access token and optionally a * refreshed OAuth2 refresh token. * * @author Marcus Portmann */ public class RefreshedOAuth2Tokens { /** The OAuth2 access token. */ private final OAuth2AccessToken accessToken; /** The OAuth2 refresh token. */ private final OAuth2RefreshToken refreshToken; /** * Constructs a new <b>RefreshedOAuth2Tokens</b>. * * @param accessToken the OAuth2 access token * @param refreshToken the OAuth2 refresh token */ public RefreshedOAuth2Tokens(OAuth2AccessToken accessToken, OAuth2RefreshToken refreshToken) { this.accessToken = accessToken; this.refreshToken = refreshToken; } /** * Returns the OAuth2 access token. * * @return the OAuth2 access token */ public OAuth2AccessToken getAccessToken() { return accessToken; } /** * Returns the OAuth2 refresh token. * * @return the OAuth2 refresh token */ public OAuth2RefreshToken getRefreshToken() { return refreshToken; } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/token/TokenCreationException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.token; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * The <b>TokenCreationException</b> exception is thrown to indicate an error condition when * creating an OAuth2 token. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/oauth2/token-creation", title = "The OAuth2 token could not be created.") public class TokenCreationException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>TokenCreationException</b> with the specified message. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. */ public TokenCreationException(String message) { super(message); } /** * Constructs a new <b>TokenCreationException</b> with the specified message and cause. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ public TokenCreationException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization
java-sources/africa/absa/inception-oauth2-authorization-server/1.2.0/africa/absa/inception/oauth2/server/authorization/token/TokenService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.authorization.token; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.security.ISecurityService; import africa.absa.inception.security.User; import com.nimbusds.jose.crypto.RSASSAVerifier; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; /** * The <b>TokenService</b> class provides the Token Service implementation. * * @author Marcus Portmann */ @Service @SuppressWarnings({"unused", "WeakerAccess"}) public class TokenService implements ITokenService { /** The access token validity in seconds. */ public static final int ACCESS_TOKEN_VALIDITY = 5 * 60; /** * The period in seconds prior to expiry of the refresh token during which it will be * automatically re-issued. */ public static final int REFRESH_TOKEN_REISSUE_INTERVAL = 90 * 24 * 60 * 60; /** The refresh token validity in seconds. */ public static final int REFRESH_TOKEN_VALIDITY = 365 * 24 * 60 * 60; /* Security Service */ private final ISecurityService securityService; /* The application name. */ @Value("${spring.application.name:#{null}}") private String applicationName; /* The RSA private key used to sign the JWTs. */ @Value("${inception.oauth2.authorization-server.jwt.rsa-private-key-location}") private RSAPrivateKey rsaPrivateKey; /* The RSA public key used to verify the JWTs. */ @Value("${inception.oauth2.authorization-server.jwt.rsa-public-key-location}") private RSAPublicKey rsaPublicKey; /** * Constructs a new <b>TokenService</b>. * * @param securityService the Security Service */ public TokenService(ISecurityService securityService) { this.securityService = securityService; } /** * Issue an OAuth2 access token for the specified user. * * @param username the username for the user * @param scopes the optional scope(s) for the access token * @return the OAuth2 access token */ public OAuth2AccessToken issueOAuth2AccessToken(String username, Set<String> scopes) throws ServiceUnavailableException { try { return createOAuth2AccessToken(username, scopes); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to issue the OAuth2 access token for the user (" + username + ")", e); } } /** * Issue an OAuth2 refresh token for the specified user. * * @param username the username for the user * @param scopes the optional scope(s) for the refresh token * @return the OAuth2 refresh token */ public OAuth2RefreshToken issueOAuth2RefreshToken(String username, Set<String> scopes) throws ServiceUnavailableException { try { return createOAuth2RefreshToken(username, scopes); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to issue the OAuth2 refresh token for the user (" + username + ")", e); } } /** * Refresh an OAuth2 access token and if required the OAuth2 refresh token. * * @param encodedOAuth2RefreshToken the encoded OAuth2 refresh token * @return the refreshed tokens */ public RefreshedOAuth2Tokens refreshOAuth2Tokens(String encodedOAuth2RefreshToken) throws InvalidOAuth2RefreshTokenException, ServiceUnavailableException { try { SignedJWT signedJWT = SignedJWT.parse(encodedOAuth2RefreshToken); RSASSAVerifier verifier = new RSASSAVerifier(rsaPublicKey); if (!signedJWT.verify(verifier)) { throw new InvalidOAuth2RefreshTokenException(); } JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet(); String username = claimsSet.getSubject(); String scopeClaim = claimsSet.getStringClaim(OAuth2AccessToken.SCOPE_CLAIM); Instant issuedAt = claimsSet.getIssueTime().toInstant(); Instant expiresAt = claimsSet.getExpirationTime().toInstant(); if (Instant.now().isAfter(expiresAt)) { throw new InvalidOAuth2RefreshTokenException(); } OAuth2AccessToken accessToken = createOAuth2AccessToken( username, (scopeClaim != null) ? Set.of(scopeClaim.split(" ")) : null); if (Instant.now().isBefore(expiresAt.minusSeconds(REFRESH_TOKEN_REISSUE_INTERVAL))) { return new RefreshedOAuth2Tokens(accessToken, null); } else { OAuth2RefreshToken refreshToken = createOAuth2RefreshToken( username, (scopeClaim != null) ? Set.of(scopeClaim.split(" ")) : null); return new RefreshedOAuth2Tokens(accessToken, refreshToken); } } catch (InvalidOAuth2RefreshTokenException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to refresh the OAuth tokens", e); } } private OAuth2AccessToken createOAuth2AccessToken(String username, Set<String> scopes) throws TokenCreationException { try { Optional<UUID> userDirectoryIdOptional = securityService.getUserDirectoryIdForUser(username); if (userDirectoryIdOptional.isEmpty()) { throw new TokenCreationException( "Failed to retrieve the user directory ID for the user (" + username + ")"); } else { UUID userDirectoryId = userDirectoryIdOptional.get(); // Retrieve the details for the user User user = securityService.getUser(userDirectoryId, username); // Retrieve the function codes for the user List<String> functionCodes = securityService.getFunctionCodesForUser(userDirectoryId, username); // Retrieve the list of IDs for the tenants the user is associated with List<UUID> tenantIds = securityService.getTenantIdsForUserDirectory(userDirectoryId); // Retrieve the list of roles for the user List<String> roleCodes = securityService.getRoleCodesForUser(userDirectoryId, username); // Build the OAuth2 access token return OAuth2AccessToken.build( user, roleCodes, functionCodes, tenantIds, scopes, applicationName, ACCESS_TOKEN_VALIDITY, rsaPrivateKey); } } catch (Throwable e) { throw new TokenCreationException("Failed to create the OAuth2 access token", e); } } private OAuth2RefreshToken createOAuth2RefreshToken(String username, Set<String> scopes) throws TokenCreationException { try { return OAuth2RefreshToken.build(username, scopes, REFRESH_TOKEN_VALIDITY, rsaPrivateKey); } catch (Throwable e) { throw new TokenCreationException("Failed to create the OAuth2 refresh token", e); } } }
0
java-sources/africa/absa/inception-oauth2-resource-server/1.2.0/africa/absa/inception/oauth2/server
java-sources/africa/absa/inception-oauth2-resource-server/1.2.0/africa/absa/inception/oauth2/server/resource/JwtGrantedAuthoritiesConverter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.resource; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; /** * The <b>JwtGrantedAuthoritiesConverter</b> class extracts the granted authorities from a JWT. * * @author Marcus Portmann */ public class JwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { /** The name of the functions claim that provides the functions assigned to the user. */ public static final String FUNCTIONS_CLAIM = "functions"; /** * The name of the tenants claim that provides the IDs for the tenants the user is associated * with. */ public static final String TENANTS_CLAIM = "tenants"; /** The name of the roles claim that provides the roles assigned to the user. */ private static final String ROLES_CLAIM = "roles"; /** * Extract {@link GrantedAuthority}s from the given {@link Jwt}. * * @param jwt the {@link Jwt} token * @return the {@link GrantedAuthority authorities} read from the token scopes */ @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); // Function claims List<String> functionsClaim = jwt.getClaimAsStringList(FUNCTIONS_CLAIM); if (functionsClaim != null) { for (String functionClaim : functionsClaim) { grantedAuthorities.add(new SimpleGrantedAuthority("FUNCTION_" + functionClaim)); } } // Tenant claims List<String> tenantsClaim = jwt.getClaimAsStringList(TENANTS_CLAIM); if (tenantsClaim != null) { for (String tenantClaim : tenantsClaim) { grantedAuthorities.add(new SimpleGrantedAuthority("TENANT_" + tenantClaim)); } } // Role claims List<String> rolesClaim = jwt.getClaimAsStringList(ROLES_CLAIM); if (rolesClaim != null) { for (String roleClaim : rolesClaim) { grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + roleClaim)); } } return grantedAuthorities; } }
0
java-sources/africa/absa/inception-oauth2-resource-server/1.2.0/africa/absa/inception/oauth2/server
java-sources/africa/absa/inception-oauth2-resource-server/1.2.0/africa/absa/inception/oauth2/server/resource/OAuth2ResourceServerConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.resource; import java.security.interfaces.RSAPublicKey; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; /** * The <b>OAuth2ResourceServerConfiguration</b> class provides the Spring configuration for the * OAuth2 Resource Server module. * * @author Marcus Portmann */ @Configuration public class OAuth2ResourceServerConfiguration { /* The RSA public key used to verify the JWTs. */ @Value("${inception.oauth2.resource-server.jwt.rsa-public-key-location}") private RSAPublicKey rsaPublicKey; @Bean JwtDecoder jwtDecoderByRSAPublicKeyValue() throws Exception { if (rsaPublicKey == null) { throw new BeanInitializationException( "Failed to retrieve the RSA public key using the " + "inception.oauth2.resource-server.jwt.rsa-public-key-location property " + "to initialize the JwtDecoder bean"); } try { return NimbusJwtDecoder.withPublicKey(rsaPublicKey) .signatureAlgorithm(SignatureAlgorithm.from("RS256")) .build(); } catch (Throwable e) { throw new BeanInitializationException( "Failed to initialize the JwtDecoder bean using the RSA public key (" + rsaPublicKey + ")", e); } } }
0
java-sources/africa/absa/inception-oauth2-resource-server/1.2.0/africa/absa/inception/oauth2/server
java-sources/africa/absa/inception-oauth2-resource-server/1.2.0/africa/absa/inception/oauth2/server/resource/ResourceServerSecurityConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.oauth2.server.resource; import java.util.Collection; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; 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.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; /** * The <b>ResourceServerSecurityConfiguration</b> class provides the OAuth2 resource server security * configuration. * * @author Marcus Portmann */ @Configuration @EnableWebSecurity public class ResourceServerSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic() .disable() .csrf(AbstractHttpConfigurer::disable) .authorizeRequests( authorizeRequests -> authorizeRequests .antMatchers("/**") .permitAll() .antMatchers("/api/**") .authenticated()) .oauth2ResourceServer( oauth2ResourceServer -> oauth2ResourceServer.jwt( jwt -> jwt.jwtAuthenticationConverter(getJwtAuthenticationConverter()))) .sessionManagement( sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); } private Converter<Jwt, AbstractAuthenticationToken> getJwtAuthenticationConverter() { JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter( getJwtGrantedAuthoritiesConverter()); return jwtAuthenticationConverter; } private Converter<Jwt, Collection<GrantedAuthority>> getJwtGrantedAuthoritiesConverter() { return new JwtGrantedAuthoritiesConverter(); } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/Country.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>Country</b> class holds the information for a country. * * @author Marcus Portmann */ @Schema(description = "A geopolitical entity representing a country or dependent territory") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "code", "iso3Code", "locale", "sortIndex", "name", "shortName", "description", "sovereignState", "nationality" }) @Entity @Table(schema = "reference", name = "countries") @IdClass(CountryId.class) public class Country implements Serializable { private static final long serialVersionUID = 1000000; /** The ISO 3166-1 alpha-2 code for the country. */ @Schema(description = "The ISO 3166-1 alpha-2 code for the country", required = true) @JsonProperty(required = true) @NotNull @Size(min = 2, max = 2) @Id @Column(name = "code", length = 2, nullable = false) private String code; /** The description for the country. */ @Schema(description = "The description for the country", required = true) @JsonProperty(required = true) @NotNull @Size(max = 200) @Column(name = "description", length = 200, nullable = false) private String description; /** The ISO 3166-1 alpha-3 code for the country. */ @Schema(description = "The ISO 3166-1 alpha-3 code for the country", required = true) @JsonProperty(required = true) @NotNull @Size(min = 3, max = 3) @Id @Column(name = "iso3_code", length = 3, nullable = false) private String iso3Code; /** The Unicode locale identifier for the country. */ @Schema(description = "The Unicode locale identifier for the country", required = true) @JsonProperty(required = true) @NotNull @Size(min = 2, max = 10) @Id @Column(name = "locale_id", length = 10, nullable = false) private String localeId; /** The name of the country. */ @Schema(description = "The name of the country", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 50, nullable = false) private String name; /** The nationality for the country. */ @Schema(description = "The nationality for the country", required = true) @JsonProperty(required = true) @NotNull @Size(max = 50) @Column(name = "nationality", length = 50, nullable = false) private String nationality; /** The short name for the country. */ @Schema(description = "The short name for the country", required = true) @JsonProperty(required = true) @NotNull @Size(max = 50) @Column(name = "short_name", length = 50, nullable = false) private String shortName; /** The sort index for the country. */ @Schema(description = "The sort index for the country") @JsonProperty @Column(name = "sort_index") private Integer sortIndex; /** The ISO 3166-1 alpha-2 code for the sovereign state the country is associated with. */ @Schema( description = "The ISO 3166-1 alpha-2 code for the sovereign state the country is associated with", required = true) @JsonProperty(required = true) @NotNull @Size(min = 2, max = 2) @Column(name = "sovereign_state", length = 2, nullable = false) private String sovereignState; /** Constructs a new <b>Country</b>. */ public Country() {} /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Country other = (Country) object; return Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns the ISO 3166-1 alpha-2 code for the country. * * @return the ISO 3166-1 alpha-2 code for the country */ public String getCode() { return code; } /** * Returns the description for the country. * * @return the description for the country */ public String getDescription() { return description; } /** * Returns the ISO 3166-1 alpha-3 code for the country. * * @return the ISO 3166-1 alpha-3 code for the country */ public String getIso3Code() { return iso3Code; } /** * Returns the Unicode locale identifier for the country. * * @return the Unicode locale identifier for the country */ public String getLocaleId() { return localeId; } /** * Returns the name of the country. * * @return the name of the country */ public String getName() { return name; } /** * Returns the nationality for the country. * * @return the nationality for the country */ public String getNationality() { return nationality; } /** * Returns the short name for the country. * * @return the short name for the country */ public String getShortName() { return shortName; } /** * Returns the sort index for the country. * * @return the sort index for the country */ public Integer getSortIndex() { return sortIndex; } /** * Returns the ISO 3166-1 alpha-2 code for the sovereign state the country is associated with. * * @return the ISO 3166-1 alpha-2 code for the sovereign state the country is associated with */ public String getSovereignState() { return sovereignState; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } /** * Set the ISO 3166-1 alpha-2 code for the country. * * @param code the ISO 3166-1 alpha-2 code for the country */ public void setCode(String code) { this.code = code; } /** * Set the description for the country. * * @param description the description for the country */ public void setDescription(String description) { this.description = description; } /** * Set the ISO 3166-1 alpha-3 code for the country. * * @param iso3Code the ISO 3166-1 alpha-3 code for the country */ public void setIso3Code(String iso3Code) { this.iso3Code = iso3Code; } /** * Set the Unicode locale identifier for the country. * * @param localeId the Unicode locale identifier for the country */ public void setLocaleId(String localeId) { this.localeId = localeId; } /** * Set the name of the country. * * @param name the name of the country */ public void setName(String name) { this.name = name; } /** * Set the nationality for the country. * * @param nationality the nationality for the country */ public void setNationality(String nationality) { this.nationality = nationality; } /** * Set the short name for the country. * * @param shortDescription the short name for the country */ public void setShortName(String shortDescription) { this.shortName = shortDescription; } /** * Set the sort index for the country. * * @param sortIndex the sort index for the country */ public void setSortIndex(Integer sortIndex) { this.sortIndex = sortIndex; } /** * Set the ISO 3166-1 alpha-2 code for the sovereign state the country is associated with. * * @param sovereignState the ISO 3166-1 alpha-2 code for the sovereign state the country is * associated with */ public void setSovereignState(String sovereignState) { this.sovereignState = sovereignState; } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/CountryId.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.io.Serializable; import java.util.Objects; /** * The <b>CountryId</b> class implements the ID class for the <b>Country</b> class. * * @author Marcus Portmann */ @SuppressWarnings({"UnusedDeclaration"}) public class CountryId implements Serializable { private static final long serialVersionUID = 1000000; /** The ISO 3166-1 alpha-2 code for the country. */ private String code; /** The Unicode locale identifier for the country. */ private String localeId; /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } CountryId other = (CountryId) object; return Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/CountryRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; /** * The <b>CountryRepository</b> interface declares the repository for the <b>Country</b> domain * type. * * @author Marcus Portmann */ public interface CountryRepository extends JpaRepository<Country, CountryId> { /** * Retrieve all the countries sorted by locale ID, sort index, and name. * * @return all the countries sorted by locale ID, sort index, and name. */ @Query("select c from Country c order by c.localeId, -c.sortIndex DESC, c.shortName") List<Country> findAll(); /** * Retrieve the countries for the specified locale sorted by locale ID, sort index, and name. * * @param localeId the Unicode locale identifier for the locale to retrieve the countries for * @return the countries for the specified locale sorted by locale ID, sort index, and name */ @Query( "select c from Country c where upper(c.localeId) = upper(:localeId) order by c.localeId, -c.sortIndex DESC, c.shortName") List<Country> findByLocaleIdIgnoreCase(String localeId); }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/IReferenceService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import java.util.List; /** * The <b>IReferenceService</b> interface defines the functionality provided by a Reference Service * implementation. * * @author Marcus Portmann */ public interface IReferenceService { /** The default locale ID. */ String DEFAULT_LOCALE_ID = "en-US"; /** * Retrieve the country reference data for all locales. * * @return the country reference data * @throws ServiceUnavailableException if the country reference data could not be retrieved */ List<Country> getCountries() throws ServiceUnavailableException; /** * Retrieve the country reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the country reference * data for * @return the country reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the country reference data could not be retrieved */ List<Country> getCountries(String localeId) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the language reference data for all locales. * * @return the language reference data * @throws ServiceUnavailableException if the language reference data could not be retrieved */ List<Language> getLanguages() throws ServiceUnavailableException; /** * Retrieve the language reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the language reference * data for * @return the language reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the language reference data could not be retrieved */ List<Language> getLanguages(String localeId) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the measurement system reference data for all locales. * * @return the measurement system reference data * @throws ServiceUnavailableException if the measurement system reference data could not be * retrieved */ List<MeasurementSystem> getMeasurementSystems() throws ServiceUnavailableException; /** * Retrieve the measurement system reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the measurement system * reference data for * @return the measurement system reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the measurement system reference data could not be * retrieved */ List<MeasurementSystem> getMeasurementSystems(String localeId) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the measurement unit type reference data for all locales. * * @return the measurement unit type reference data * @throws ServiceUnavailableException if the measurement unit type reference data could not be * retrieved */ List<MeasurementUnitType> getMeasurementUnitTypes() throws ServiceUnavailableException; /** * Retrieve the measurement unit type reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the measurement unit * type reference data for * @return the measurement unit type reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the measurement unit type reference data could not be * retrieved */ List<MeasurementUnitType> getMeasurementUnitTypes(String localeId) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the measurement unit reference data for all locales. * * @return the measurement unit reference data * @throws ServiceUnavailableException if the measurement unit reference data could not be * retrieved */ List<MeasurementUnit> getMeasurementUnits() throws ServiceUnavailableException; /** * Retrieve the measurement unit reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the measurement unit * reference data for * @return the measurement unit reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the measurement unit reference data could not be * retrieved */ List<MeasurementUnit> getMeasurementUnits(String localeId) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the region reference data for all locales. * * @return the region reference data * @throws ServiceUnavailableException if the region reference data could not be retrieved */ List<Region> getRegions() throws ServiceUnavailableException; /** * Retrieve the region reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the region reference * data for * @return the region reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the region reference data could not be retrieved */ List<Region> getRegions(String localeId) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the time zone reference data for all locales. * * @return the time zones reference data * @throws ServiceUnavailableException if the time zones reference data could not be retrieved */ List<TimeZone> getTimeZones() throws ServiceUnavailableException; /** * Retrieve the time zone reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the time zone * reference data for * @return the time zone reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the time zones reference data could not be retrieved */ List<TimeZone> getTimeZones(String localeId) throws InvalidArgumentException, ServiceUnavailableException; /** * Check whether the code is a valid code for a country. * * @param countryCode the code for the country * @return <b>true</b> if the code is a valid code for a country or <b>false</b> otherwise * @throws ServiceUnavailableException if the country code check failed */ boolean isValidCountry(String countryCode) throws ServiceUnavailableException; /** * Check whether the code is a valid ISO 639-1 alpha-2 code for a language. * * @param languageCode the code for the language * @return <b>true</b> if the code is a valid ISO 639-1 alpha-2 code for a language or * <b>false</b> otherwise * @throws ServiceUnavailableException if the language code check failed */ boolean isValidLanguage(String languageCode) throws ServiceUnavailableException; /** * Check whether the code is a valid code for a measurement system. * * @param measurementSystemCode the code for the measurement system * @return <b>true</b> if the code is a valid code for a measurement system or <b>false</b> * otherwise * @throws ServiceUnavailableException if the measurement system code check failed */ boolean isValidMeasurementSystem(String measurementSystemCode) throws ServiceUnavailableException; /** * Check whether the code is a valid code for a measurement unit. * * @param measurementUnitCode the code for the measurement unit * @return <b>true</b> if the code is a valid code for a measurement unit or <b>false</b> * otherwise * @throws ServiceUnavailableException if the measurement unit code check failed */ boolean isValidMeasurementUnit(String measurementUnitCode) throws ServiceUnavailableException; /** * Check whether the code is a valid code for a measurement unit type. * * @param measurementUnitTypeCode the code for the measurement unit type * @return <b>true</b> if the code is a valid code for a measurement unit type or <b>false</b> * otherwise * @throws ServiceUnavailableException if the measurement unit type code check failed */ boolean isValidMeasurementUnitType(String measurementUnitTypeCode) throws ServiceUnavailableException; /** * Check whether the code is a valid code for a region. * * @param regionCode the code for the region * @return <b>true</b> if the code is a valid code for a region or <b>false</b> otherwise * @throws ServiceUnavailableException if the region code check failed */ boolean isValidRegion(String regionCode) throws ServiceUnavailableException; /** * Check whether the code is a valid code for a time zone. * * @param timeZoneCode the code for the time zone * @return <b>true</b> if the code is a valid code for a time zone or <b>false</b> otherwise * @throws ServiceUnavailableException if the time zone code check failed */ boolean isValidTimeZone(String timeZoneCode) throws ServiceUnavailableException; }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/Language.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>Language</b> class holds the information for a language. * * <p>See: https://en.wikipedia.org/wiki/List_of_official_languages_by_country_and_territory * * @author Marcus Portmann */ @Schema( description = "A systematic use of sounds, characters, symbols or signs to communicate meaning") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "code", "iso3Code", "localeId", "sortIndex", "name", "shortName", "description" }) @Entity @Table(schema = "reference", name = "languages") @IdClass(LanguageId.class) public class Language implements Serializable { private static final long serialVersionUID = 1000000; /** The ISO 639-1 alpha-2 code for the language. */ @Schema(description = "The ISO 639-1 alpha-2 code for the language", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 30) @Id @Column(name = "code", length = 30, nullable = false) private String code; /** The description for the language. */ @Schema(description = "The description for the language", required = true) @JsonProperty(required = true) @NotNull @Size(max = 200) @Column(name = "description", length = 200, nullable = false) private String description; /** The ISO 639-2 alpha-3 code for the language. */ @Schema(description = "The ISO 639-2 alpha-3 code for the language", required = true) @JsonProperty(required = true) @NotNull @Size(min = 3, max = 3) @Id @Column(name = "iso3_code", length = 3, nullable = false) private String iso3Code; /** The Unicode locale identifier for the language. */ @Schema(description = "The Unicode locale identifier for the language", required = true) @JsonProperty(required = true) @NotNull @Size(min = 2, max = 10) @Id @Column(name = "locale_id", length = 10, nullable = false) private String localeId; /** The name of the language. */ @Schema(description = "The name of the language", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 50, nullable = false) private String name; /** The short name for the language. */ @Schema(description = "The short name for the language", required = true) @JsonProperty(required = true) @NotNull @Size(max = 50) @Column(name = "short_name", length = 50, nullable = false) private String shortName; /** The sort index for the language. */ @Schema(description = "The sort index for the language") @JsonProperty @Column(name = "sort_index") private Integer sortIndex; /** Constructs a new <b>Language</b>. */ public Language() {} /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Language other = (Language) object; return Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns the ISO 639-1 alpha-2 code for the language. * * @return the ISO 639-1 alpha-2 code for the language */ public String getCode() { return code; } /** * Returns the description for the language. * * @return the description for the language */ public String getDescription() { return description; } /** * Returns the ISO 639-2 alpha-3 code for the language. * * @return the ISO 639-2 alpha-3 code for the language */ public String getIso3Code() { return iso3Code; } /** * Returns the Unicode locale identifier for the language. * * @return the Unicode locale identifier for the language */ public String getLocaleId() { return localeId; } /** * Returns the name of the language. * * @return the name of the language */ public String getName() { return name; } /** * Returns the short name for the language. * * @return the short name for the language */ public String getShortName() { return shortName; } /** * Returns the sort index for the language. * * @return the sort index for the language */ public Integer getSortIndex() { return sortIndex; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } /** * Set the ISO 639-1 alpha-2 code for the language. * * @param code the ISO 639-1 alpha-2 code for the language */ public void setCode(String code) { this.code = code; } /** * Set the description for the language. * * @param description the description for the language */ public void setDescription(String description) { this.description = description; } /** * Set the ISO 639-2 alpha-3 code for the language. * * @param iso3Code the ISO 639-2 alpha-3 code for the language */ public void setIso3Code(String iso3Code) { this.iso3Code = iso3Code; } /** * Set the Unicode locale identifier for the language. * * @param localeId the Unicode locale identifier for the language */ public void setLocaleId(String localeId) { this.localeId = localeId; } /** * Set the name of the language. * * @param name the name of the language */ public void setName(String name) { this.name = name; } /** * Set the short name for the language. * * @param shortDescription the short name for the language */ public void setShortName(String shortDescription) { this.shortName = shortDescription; } /** * Set the sort index for the language. * * @param sortIndex the sort index for the language */ public void setSortIndex(Integer sortIndex) { this.sortIndex = sortIndex; } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/LanguageId.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.io.Serializable; import java.util.Objects; /** * The <b>LanguageId</b> class implements the ID class for the <b>Language</b> class. * * @author Marcus Portmann */ @SuppressWarnings({"UnusedDeclaration"}) public class LanguageId implements Serializable { private static final long serialVersionUID = 1000000; /** The ISO 639-1 alpha-2 code for the language. */ private String code; /** The Unicode locale identifier for the language. */ private String localeId; /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } LanguageId other = (LanguageId) object; return Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/LanguageRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; /** * The <b>LanguageRepository</b> interface declares the repository for the <b>Language</b> domain * type. * * @author Marcus Portmann */ public interface LanguageRepository extends JpaRepository<Language, LanguageId> { /** * Retrieve all the languages sorted by locale ID, sort index, and name. * * @return all the languages sorted by locale ID, sort index, and name. */ @Query("select l from Language l order by l.localeId, -l.sortIndex DESC, l.shortName") List<Language> findAll(); /** * Retrieve the languages for the specified locale sorted by locale ID, sort index, and name. * * @param localeId the Unicode locale identifier for the locale to retrieve the languages for * @return the languages for the specified locale sorted by locale ID, sort index, and name */ @Query( "select l from Language l where upper(l.localeId) = upper(:localeId) order by l.localeId, -l.sortIndex DESC, l.shortName") List<Language> findByLocaleIdIgnoreCase(String localeId); }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/MeasurementSystem.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>MeasurementSystem</b> class holds the information for a system of measurement. * * <p>A system of measurement is a collection of units of measurement and rules relating them to * each other. Systems of measurement have historically been important, regulated and defined for * the purposes of science and commerce. Systems of measurement in use include the International * System of Units (SI), the modern form of the metric system, the British imperial system, and the * United States customary system. * * @author Marcus Portmann */ @Schema(description = "A system of measurement") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"code", "localeId", "sortIndex", "name", "description"}) @Entity @Table(schema = "reference", name = "measurement_systems") @IdClass(MeasurementSystemId.class) public class MeasurementSystem implements Serializable { private static final long serialVersionUID = 1000000; /** The code for the measurement system. */ @Schema(description = "The code for the measurement system", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 30) @Id @Column(name = "code", length = 30, nullable = false) private String code; /** The description for the measurement system. */ @Schema(description = "The description for the measurement system", required = true) @JsonProperty(required = true) @NotNull @Size(max = 200) @Column(name = "description", length = 200, nullable = false) private String description; /** The Unicode locale identifier for the measurement system. */ @Schema(description = "The Unicode locale identifier for the measurement system", required = true) @JsonProperty(required = true) @NotNull @Size(min = 2, max = 10) @Id @Column(name = "locale_id", length = 10, nullable = false) private String localeId; /** The name of the measurement system. */ @Schema(description = "The name of the measurement system", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 50, nullable = false) private String name; /** The sort index for the measurement system. */ @Schema(description = "The sort index for the measurement system") @JsonProperty @Column(name = "sort_index") private Integer sortIndex; /** Constructs a new <b>MeasurementSystem</b>. */ public MeasurementSystem() {} /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } MeasurementSystem other = (MeasurementSystem) object; return Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns the code for the measurement system. * * @return the code for the measurement system */ public String getCode() { return code; } /** * Returns the description for the measurement system. * * @return the description for the measurement system */ public String getDescription() { return description; } /** * Returns the Unicode locale identifier for the measurement system. * * @return the Unicode locale identifier for the measurement system */ public String getLocaleId() { return localeId; } /** * Returns the name of the measurement system. * * @return the name of the measurement system */ public String getName() { return name; } /** * Returns the sort index for the measurement system. * * @return the sort index for the measurement system */ public Integer getSortIndex() { return sortIndex; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } /** * Set the code for the measurement system. * * @param code the code for the measurement system */ public void setCode(String code) { this.code = code; } /** * Set the description for the measurement system. * * @param description the description for the measurement system */ public void setDescription(String description) { this.description = description; } /** * Set the Unicode locale identifier for the measurement system. * * @param localeId the Unicode locale identifier for the measurement system */ public void setLocaleId(String localeId) { this.localeId = localeId; } /** * Set the name of the measurement system. * * @param name the name of the measurement system */ public void setName(String name) { this.name = name; } /** * Set the sort index for the measurement system. * * @param sortIndex the sort index for the measurement system */ public void setSortIndex(Integer sortIndex) { this.sortIndex = sortIndex; } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/MeasurementSystemId.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.io.Serializable; import java.util.Objects; /** * The <b>MeasurementSystemId</b> class implements the ID class for the <b>MeasurementSystem</b> * class. * * @author Marcus Portmann */ @SuppressWarnings({"UnusedDeclaration"}) public class MeasurementSystemId implements Serializable { private static final long serialVersionUID = 1000000; /** The ISO code for the measurement system. */ private String code; /** The Unicode locale identifier for the measurement system. */ private String localeId; /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } MeasurementSystemId other = (MeasurementSystemId) object; return Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/MeasurementSystemRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; /** * The <b>MeasurementSystemRepository</b> interface declares the repository for the * <b>MeasurementSystem</b> domain type. * * @author Marcus Portmann */ public interface MeasurementSystemRepository extends JpaRepository<MeasurementSystem, MeasurementSystemId> { /** * Retrieve all the measurement systems sorted by locale ID, sort index, and name. * * @return all the measurement systems sorted by locale ID, sort index, and name. */ @Query("select ms from MeasurementSystem ms order by ms.localeId, -ms.sortIndex DESC, ms.name") List<MeasurementSystem> findAll(); /** * Retrieve the measurement systems for the specified locale sorted by locale ID, sort index, and * name. * * @param localeId the Unicode locale identifier for the locale to retrieve the measurement * systems for * @return the measurement systems for the specified locale sorted by locale ID, sort index, and * name */ @Query( "select ms from MeasurementSystem ms where upper(ms.localeId) = upper(:localeId) order by ms.localeId, -ms.sortIndex DESC, ms.name") List<MeasurementSystem> findByLocaleIdIgnoreCase(String localeId); }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/MeasurementUnit.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>MeasurementUnit</b> class holds the information for a measurement unit. * * @author Marcus Portmann */ @Schema(description = "A type of unit of measurement") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"code", "localeId", "sortIndex", "name", "description", "system", "type"}) @Entity @Table(schema = "reference", name = "measurement_units") @IdClass(MeasurementUnitId.class) public class MeasurementUnit implements Serializable { private static final long serialVersionUID = 1000000; /** The code for the measurement unit. */ @Schema(description = "The code for the measurement unit", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 30) @Id @Column(name = "code", length = 30, nullable = false) private String code; /** The description for the measurement unit. */ @Schema(description = "The description for the measurement unit", required = true) @JsonProperty(required = true) @NotNull @Size(max = 200) @Column(name = "description", length = 200, nullable = false) private String description; /** The Unicode locale identifier for the measurement unit. */ @Schema(description = "The Unicode locale identifier for the measurement unit", required = true) @JsonProperty(required = true) @NotNull @Size(min = 2, max = 10) @Id @Column(name = "locale_id", length = 10, nullable = false) private String localeId; /** The name of the measurement unit. */ @Schema(description = "The name of the measurement unit", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 50, nullable = false) private String name; /** The sort index for the measurement unit. */ @Schema(description = "The sort index for the measurement unit") @JsonProperty @Column(name = "sort_index") private Integer sortIndex; /** The code for the measurement system. */ @Schema(description = "The code for the measurement system", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 30) @Column(name = "system", length = 30, nullable = false) private String system; /** The code for the measurement unit type. */ @Schema(description = "The code for the measurement unit type", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 30) @Column(name = "type", length = 30, nullable = false) private String type; /** Constructs a new <b>MeasurementUnit</b>. */ public MeasurementUnit() {} /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } MeasurementUnit other = (MeasurementUnit) object; return Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns the code for the measurement unit. * * @return the code for the measurement unit */ public String getCode() { return code; } /** * Returns the description for the measurement unit. * * @return the description for the measurement unit */ public String getDescription() { return description; } /** * Returns the Unicode locale identifier for the measurement unit. * * @return the Unicode locale identifier for the measurement unit */ public String getLocaleId() { return localeId; } /** * Returns the name of the measurement unit. * * @return the name of the measurement unit */ public String getName() { return name; } /** * Returns the sort index for the measurement unit. * * @return the sort index for the measurement unit */ public Integer getSortIndex() { return sortIndex; } /** * Returns the code for the measurement system. * * @return the code for the measurement system */ public String getSystem() { return system; } /** * Returns the code for the measurement unit type. * * @return the code for the measurement unit type */ public String getType() { return type; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } /** * Set the code for the measurement unit. * * @param code the code for the measurement unit */ public void setCode(String code) { this.code = code; } /** * Set the description for the measurement unit. * * @param description the description for the measurement unit */ public void setDescription(String description) { this.description = description; } /** * Set the Unicode locale identifier for the measurement unit. * * @param localeId the Unicode locale identifier for the measurement unit */ public void setLocaleId(String localeId) { this.localeId = localeId; } /** * Set the name of the measurement unit. * * @param name the name of the measurement unit */ public void setName(String name) { this.name = name; } /** * Set the sort index for the measurement unit. * * @param sortIndex the sort index for the measurement unit */ public void setSortIndex(Integer sortIndex) { this.sortIndex = sortIndex; } /** * Set the code for the measurement system. * * @param system the code for the measurement system */ public void setSystem(String system) { this.system = system; } /** * Set the code for the measurement unit type. * * @param type the code for the measurement unit type */ public void setType(String type) { this.type = type; } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/MeasurementUnitId.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.io.Serializable; import java.util.Objects; /** * The <b>MeasurementUnitId</b> class implements the ID class for the <b>MeasurementUnit</b> class. * * @author Marcus Portmann */ @SuppressWarnings({"UnusedDeclaration"}) public class MeasurementUnitId implements Serializable { private static final long serialVersionUID = 1000000; /** The ISO code for the measurement unit. */ private String code; /** The Unicode locale identifier for the measurement unit. */ private String localeId; /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } MeasurementUnitId other = (MeasurementUnitId) object; return Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/MeasurementUnitRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; /** * The <b>MeasurementUnitRepository</b> interface declares the repository for the * <b>MeasurementUnit</b> domain type. * * @author Marcus Portmann */ public interface MeasurementUnitRepository extends JpaRepository<MeasurementUnit, MeasurementUnitId> { /** * Retrieve all the measurement units sorted by locale ID, sort index, and name. * * @return all the measurement units sorted by locale ID, sort index, and name. */ @Query( "select mu from MeasurementUnit mu order by mu.localeId, -mu.sortIndex DESC, mu.system, mu.type, mu.name") List<MeasurementUnit> findAll(); /** * Retrieve the measurement units for the specified locale sorted by locale ID, sort index, and * name. * * @param localeId the Unicode locale identifier for the locale to retrieve the measurement units * for * @return the measurement units for the specified locale sorted by locale ID, sort index, and * name */ @Query( "select mu from MeasurementUnit mu where upper(mu.localeId) = upper(:localeId) order by mu.localeId, -mu.sortIndex DESC, mu.system, mu.type, mu.name") List<MeasurementUnit> findByLocaleIdIgnoreCase(String localeId); }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/MeasurementUnitType.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>MeasurementUnitType</b> class holds the information for a measurement unit type. * * @author Marcus Portmann */ @Schema(description = "A type of unit of measurement") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"code", "localeId", "sortIndex", "name", "description"}) @Entity @Table(schema = "reference", name = "measurement_unit_types") @IdClass(MeasurementUnitTypeId.class) public class MeasurementUnitType implements Serializable { private static final long serialVersionUID = 1000000; /** The code for the measurement unit type. */ @Schema(description = "The code for the measurement unit type", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 30) @Id @Column(name = "code", length = 30, nullable = false) private String code; /** The description for the measurement unit type. */ @Schema(description = "The description for the measurement unit type", required = true) @JsonProperty(required = true) @NotNull @Size(max = 200) @Column(name = "description", length = 200, nullable = false) private String description; /** The Unicode locale identifier for the measurement unit type. */ @Schema( description = "The Unicode locale identifier for the measurement unit type", required = true) @JsonProperty(required = true) @NotNull @Size(min = 2, max = 10) @Id @Column(name = "locale_id", length = 10, nullable = false) private String localeId; /** The name of the measurement unit type. */ @Schema(description = "The name of the measurement unit type", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 50, nullable = false) private String name; /** The sort index for the measurement unit type. */ @Schema(description = "The sort index for the measurement unit type") @JsonProperty @Column(name = "sort_index") private Integer sortIndex; /** Constructs a new <b>MeasurementUnitType</b>. */ public MeasurementUnitType() {} /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } MeasurementUnitType other = (MeasurementUnitType) object; return Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns the code for the measurement unit type. * * @return the code for the measurement unit type */ public String getCode() { return code; } /** * Returns the description for the measurement unit type. * * @return the description for the measurement unit type */ public String getDescription() { return description; } /** * Returns the Unicode locale identifier for the measurement unit type. * * @return the Unicode locale identifier for the measurement unit type */ public String getLocaleId() { return localeId; } /** * Returns the name of the measurement unit type. * * @return the name of the measurement unit type */ public String getName() { return name; } /** * Returns the sort index for the measurement unit type. * * @return the sort index for the measurement unit type */ public Integer getSortIndex() { return sortIndex; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } /** * Set the code for the measurement unit type. * * @param code the code for the measurement unit type */ public void setCode(String code) { this.code = code; } /** * Set the description for the measurement unit type. * * @param description the description for the measurement unit type */ public void setDescription(String description) { this.description = description; } /** * Set the Unicode locale identifier for the measurement unit type. * * @param localeId the Unicode locale identifier for the measurement unit type */ public void setLocaleId(String localeId) { this.localeId = localeId; } /** * Set the name of the measurement unit type. * * @param name the name of the measurement unit type */ public void setName(String name) { this.name = name; } /** * Set the sort index for the measurement unit type. * * @param sortIndex the sort index for the measurement unit type */ public void setSortIndex(Integer sortIndex) { this.sortIndex = sortIndex; } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/MeasurementUnitTypeId.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.io.Serializable; import java.util.Objects; /** * The <b>MeasurementUnitTypeId</b> class implements the ID class for the <b>MeasurementUnitType</b> * class. * * @author Marcus Portmann */ @SuppressWarnings({"UnusedDeclaration"}) public class MeasurementUnitTypeId implements Serializable { private static final long serialVersionUID = 1000000; /** The ISO code for the measurement unit type. */ private String code; /** The Unicode locale identifier for the measurement unit type. */ private String localeId; /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } MeasurementUnitTypeId other = (MeasurementUnitTypeId) object; return Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/MeasurementUnitTypeRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; /** * The <b>MeasurementUnitTypeRepository</b> interface declares the repository for the * <b>MeasurementUnitType</b> domain type. * * @author Marcus Portmann */ public interface MeasurementUnitTypeRepository extends JpaRepository<MeasurementUnitType, MeasurementUnitTypeId> { /** * Retrieve all the measurement unit types sorted by locale ID, sort index, and name. * * @return all the measurement unit types sorted by locale ID, sort index, and name. */ @Query( "select mut from MeasurementUnitType mut order by mut.localeId, -mut.sortIndex DESC, mut.name") List<MeasurementUnitType> findAll(); /** * Retrieve the measurement unit types for the specified locale sorted by locale ID, sort index, * and name. * * @param localeId the Unicode locale identifier for the locale to retrieve the measurement unit * types for * @return the measurement unit types for the specified locale sorted by locale ID, sort index, * and name */ @Query( "select mut from MeasurementUnitType mut where upper(mut.localeId) = upper(:localeId) order by mut.localeId, -mut.sortIndex DESC, mut.name") List<MeasurementUnitType> findByLocaleIdIgnoreCase(String localeId); }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/ReferenceConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import africa.absa.inception.jpa.JpaUtil; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; /** * The <b>ReferenceConfiguration</b> class provides the Spring configuration for the Reference * module. * * @author Marcus Portmann */ @Configuration @EnableJpaRepositories( entityManagerFactoryRef = "referenceEntityManagerFactory", basePackages = {"africa.absa.inception.reference"}) public class ReferenceConfiguration { /** The Spring application context. */ private final ApplicationContext applicationContext; /** * Constructs a new <b>ReferenceConfiguration</b>. * * @param applicationContext the Spring application context */ public ReferenceConfiguration(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Returns the reference entity manager factory bean associated with the application data source. * * @param dataSource the application data source * @param platformTransactionManager the platform transaction manager * @return the reference entity manager factory bean associated with the application data source */ @Bean public LocalContainerEntityManagerFactoryBean referenceEntityManagerFactory( @Qualifier("applicationDataSource") DataSource dataSource, PlatformTransactionManager platformTransactionManager) { return JpaUtil.createEntityManager( "reference", dataSource, platformTransactionManager, "africa.absa.inception.reference"); } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/ReferenceService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import com.ibm.icu.util.TimeZone.SystemTimeZoneType; import java.time.ZoneId; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; /** * The <b>ReferenceService</b> class provides the Reference Service implementation. * * @author Marcus Portmann */ @Service public class ReferenceService implements IReferenceService { /** The Country repository. */ private final CountryRepository countryRepository; /** The Language Repository. */ private final LanguageRepository languageRepository; /** The Measurement System Repository. */ private final MeasurementSystemRepository measurementSystemRepository; /** The Measurement Unit Repository. */ private final MeasurementUnitRepository measurementUnitRepository; /** The Measurement Unit Type Repository. */ private final MeasurementUnitTypeRepository measurementUnitTypeRepository; /** The Region Repository. */ private final RegionRepository regionRepository; /** The internal reference to the Reference Service to enable caching. */ @Autowired private IReferenceService self; /** * Constructs a new <b>ReferenceService</b>. * * @param countryRepository the Country Repository * @param languageRepository the Language Repository * @param measurementSystemRepository the Measurement System Repository * @param measurementUnitRepository the Measurement Unit Type Repository * @param measurementUnitTypeRepository the Measurement Unit Type Repository * @param regionRepository the Region Repository */ public ReferenceService( CountryRepository countryRepository, LanguageRepository languageRepository, MeasurementSystemRepository measurementSystemRepository, MeasurementUnitRepository measurementUnitRepository, MeasurementUnitTypeRepository measurementUnitTypeRepository, RegionRepository regionRepository) { this.countryRepository = countryRepository; this.languageRepository = languageRepository; this.measurementSystemRepository = measurementSystemRepository; this.measurementUnitRepository = measurementUnitRepository; this.measurementUnitTypeRepository = measurementUnitTypeRepository; this.regionRepository = regionRepository; } @Override @Cacheable(cacheNames = "reference", key = "'countries.ALL'") public List<Country> getCountries() throws ServiceUnavailableException { try { return countryRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the country reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'countries.' + #localeId") public List<Country> getCountries(String localeId) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(localeId)) { throw new InvalidArgumentException("localeId"); } try { return countryRepository.findByLocaleIdIgnoreCase(localeId); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the country reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'languages.ALL'") public List<Language> getLanguages() throws ServiceUnavailableException { try { return languageRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the language reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'languages.' + #localeId") public List<Language> getLanguages(String localeId) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(localeId)) { throw new InvalidArgumentException("localeId"); } try { return languageRepository.findByLocaleIdIgnoreCase(localeId); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the language reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'measurementSystems.ALL'") public List<MeasurementSystem> getMeasurementSystems() throws ServiceUnavailableException { try { return measurementSystemRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the measurement system reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'measurementSystems.' + #localeId") public List<MeasurementSystem> getMeasurementSystems(String localeId) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(localeId)) { throw new InvalidArgumentException("localeId"); } try { return measurementSystemRepository.findByLocaleIdIgnoreCase(localeId); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the measurement system reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'measurementUnitTypes.ALL'") public List<MeasurementUnitType> getMeasurementUnitTypes() throws ServiceUnavailableException { try { return measurementUnitTypeRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the measurement unit type reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'measurementUnitTypes.' + #localeId") public List<MeasurementUnitType> getMeasurementUnitTypes(String localeId) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(localeId)) { throw new InvalidArgumentException("localeId"); } try { return measurementUnitTypeRepository.findByLocaleIdIgnoreCase(localeId); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the measurement unit type reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'measurementUnits.ALL'") public List<MeasurementUnit> getMeasurementUnits() throws ServiceUnavailableException { try { return measurementUnitRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the measurement unit reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'measurementUnits.' + #localeId") public List<MeasurementUnit> getMeasurementUnits(String localeId) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(localeId)) { throw new InvalidArgumentException("localeId"); } try { return measurementUnitRepository.findByLocaleIdIgnoreCase(localeId); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the measurement unit reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'regions.ALL'") public List<Region> getRegions() throws ServiceUnavailableException { try { return regionRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the region reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'regions.' + #localeId") public List<Region> getRegions(String localeId) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(localeId)) { throw new InvalidArgumentException("localeId"); } try { return regionRepository.findByLocaleIdIgnoreCase(localeId); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the region reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'timeZones.ALL'") public List<TimeZone> getTimeZones() throws ServiceUnavailableException { try { List<TimeZone> timeZones = new ArrayList<>(); int sortIndex = 1; Locale locale = Locale.forLanguageTag("en-US"); int maxLength = 0; for (String timeZoneId : com.ibm.icu.util.TimeZone.getAvailableIDs(SystemTimeZoneType.CANONICAL, null, null) .stream() .filter(timeZoneId -> (!timeZoneId.startsWith("SystemV"))) .filter(timeZoneId -> (timeZoneId.contains("/"))) .collect(Collectors.toList())) { maxLength = Math.max(maxLength, timeZoneId.length()); String zoneName = com.ibm.icu.util.TimeZone.getTimeZone(timeZoneId).getDisplayName(locale); timeZones.add(new TimeZone(timeZoneId, "en-US", zoneName, zoneName, sortIndex)); sortIndex++; } return timeZones; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the time zone reference data", e); } } @Override @Cacheable(cacheNames = "reference", key = "'timeZones.' + #localeId") public List<TimeZone> getTimeZones(String localeId) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(localeId)) { throw new InvalidArgumentException("localeId"); } try { List<TimeZone> timeZones = new ArrayList<>(); int sortIndex = 1; Locale locale = Locale.forLanguageTag(localeId); int maxLength = 0; for (String timeZoneId : com.ibm.icu.util.TimeZone.getAvailableIDs(SystemTimeZoneType.CANONICAL, null, null) .stream() .filter(timeZoneId -> (!timeZoneId.startsWith("SystemV"))) .filter(timeZoneId -> (timeZoneId.contains("/"))) .collect(Collectors.toList())) { maxLength = Math.max(maxLength, timeZoneId.length()); String zoneName = com.ibm.icu.util.TimeZone.getTimeZone(timeZoneId).getDisplayName(locale); timeZones.add(new TimeZone(timeZoneId, localeId, zoneName, zoneName, sortIndex)); sortIndex++; } return timeZones; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the time zones", e); } } @Override public boolean isValidCountry(String countryCode) throws ServiceUnavailableException { if (!StringUtils.hasText(countryCode)) { return false; } return self.getCountries().stream().anyMatch(country -> country.getCode().equals(countryCode)); } @Override public boolean isValidLanguage(String languageCode) throws ServiceUnavailableException { if (!StringUtils.hasText(languageCode)) { return false; } return self.getLanguages().stream() .anyMatch(language -> language.getCode().equals(languageCode)); } @Override public boolean isValidMeasurementSystem(String measurementSystemCode) throws ServiceUnavailableException { if (!StringUtils.hasText(measurementSystemCode)) { return false; } return self.getMeasurementSystems().stream() .anyMatch(measurementSystem -> measurementSystem.getCode().equals(measurementSystemCode)); } @Override public boolean isValidMeasurementUnit(String measurementUnitCode) throws ServiceUnavailableException { if (!StringUtils.hasText(measurementUnitCode)) { return false; } return self.getMeasurementUnits().stream() .anyMatch(measurementUnit -> measurementUnit.getCode().equals(measurementUnitCode)); } @Override public boolean isValidMeasurementUnitType(String measurementUnitTypeCode) throws ServiceUnavailableException { if (!StringUtils.hasText(measurementUnitTypeCode)) { return false; } return self.getMeasurementUnitTypes().stream() .anyMatch( measurementUnitType -> measurementUnitType.getCode().equals(measurementUnitTypeCode)); } @Override public boolean isValidRegion(String regionCode) throws ServiceUnavailableException { if (!StringUtils.hasText(regionCode)) { return false; } return self.getRegions().stream().anyMatch(region -> region.getCode().equals(regionCode)); } @Override public boolean isValidTimeZone(String timeZoneCode) { if (!StringUtils.hasText(timeZoneCode)) { return false; } try { //noinspection ResultOfMethodCallIgnored ZoneId.of(timeZoneCode); return true; } catch (Throwable ignored) { return false; } } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/Region.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>Region</b> class holds the information for a region. * * @author Marcus Portmann */ @Schema( description = "An area, especially part of a country or the world having definable characteristics but not always fixed boundaries") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"country", "code", "localeId", "sortIndex", "name", "description"}) @Entity @Table(schema = "reference", name = "regions") @IdClass(RegionId.class) public class Region implements Serializable { private static final long serialVersionUID = 1000000; /** The ISO 3166-2 subdivision code for the region. */ @Schema(description = "The ISO 3166-2 subdivision code for the region", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 30) @Id @Column(name = "code", length = 30, nullable = false) private String code; /** The ISO 3166-1 alpha-2 code for the country the region is associated with. */ @Schema( description = "The ISO 3166-1 alpha-2 code for the country the region is associated with", required = true) @JsonProperty(required = true) @NotNull @Size(min = 2, max = 2) @Id @Column(name = "country", length = 2, nullable = false) private String country; /** The description for the region. */ @Schema(description = "The description for the region", required = true) @JsonProperty(required = true) @NotNull @Size(max = 200) @Column(name = "description", length = 200, nullable = false) private String description; /** The Unicode locale identifier for the region. */ @Schema(description = "The Unicode locale identifier for the region", required = true) @JsonProperty(required = true) @NotNull @Size(min = 2, max = 10) @Id @Column(name = "locale_id", length = 10, nullable = false) private String localeId; /** The name of the region. */ @Schema(description = "The name of the region", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 50) @Column(name = "name", length = 50, nullable = false) private String name; /** The sort index for the region. */ @Schema(description = "The sort index for the region") @JsonProperty @Column(name = "sort_index") private Integer sortIndex; /** Constructs a new <b>Region</b>. */ public Region() {} /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Region other = (Region) object; return Objects.equals(country, other.country) && Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns the ISO 3166-2 subdivision code for the region. * * @return the ISO 3166-2 subdivision code for the region */ public String getCode() { return code; } /** * Returns the ISO 3166-1 alpha-2 code for the country the region is associated with. * * @return the ISO 3166-1 alpha-2 code for the country the region is associated with */ public String getCountry() { return country; } /** * Returns the description for the region. * * @return the description for the region */ public String getDescription() { return description; } /** * Returns the Unicode locale identifier for the region. * * @return the Unicode locale identifier for the region */ public String getLocaleId() { return localeId; } /** * Returns the name of the region. * * @return the name of the region */ public String getName() { return name; } /** * Returns the sort index for the region. * * @return the sort index for the region */ public Integer getSortIndex() { return sortIndex; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((country == null) ? 0 : country.hashCode()) + ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } /** * Set the ISO 3166-2 subdivision code for the region. * * @param code the ISO 3166-2 subdivision code for the region */ public void setCode(String code) { this.code = code; } /** * Set the ISO 3166-1 alpha-2 code for the country the region is associated with. * * @param country the ISO 3166-1 alpha-2 code for the country the region is associated with */ public void setCountry(String country) { this.country = country; } /** * Set the description for the region. * * @param description the description for the region */ public void setDescription(String description) { this.description = description; } /** * Set the Unicode locale identifier for the region. * * @param localeId the Unicode locale identifier for the region */ public void setLocaleId(String localeId) { this.localeId = localeId; } /** * Set the name of the region. * * @param name the name of the region */ public void setName(String name) { this.name = name; } /** * Set the sort index for the region. * * @param sortIndex the sort index for the region */ public void setSortIndex(Integer sortIndex) { this.sortIndex = sortIndex; } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/RegionId.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.io.Serializable; import java.util.Objects; /** * The <b>RegionId</b> class implements the ID class for the <b>Region</b> class. * * @author Marcus Portmann */ @SuppressWarnings({"UnusedDeclaration"}) public class RegionId implements Serializable { private static final long serialVersionUID = 1000000; /** The ISO 3166-2 subdivision code for the region. */ private String code; /** The ISO 3166-1 alpha-2 code for the country the region is associated with. */ private String country; /** The Unicode locale identifier for the region. */ private String localeId; /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } RegionId other = (RegionId) object; return Objects.equals(country, other.country) && Objects.equals(code, other.code) && Objects.equals(localeId, other.localeId); } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((country == null) ? 0 : country.hashCode()) + ((code == null) ? 0 : code.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/RegionRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; /** * The <b>RegionRepository</b> interface declares the repository for the <b>Region</b> domain type. * * @author Marcus Portmann */ public interface RegionRepository extends JpaRepository<Region, RegionId> { /** * Retrieve all the regions sorted by locale ID, sort index, and name. * * @return all the regions sorted by locale ID, sort index, and name. */ @Query("select r from Region r order by r.localeId, -r.sortIndex DESC, r.name") List<Region> findAll(); /** * Retrieve the regions for the specified locale sorted by locale ID, sort index, and name. * * @param localeId the Unicode locale identifier for the locale to retrieve the regions for * @return the regions for the specified locale sorted by locale ID, sort index, and name */ @Query( "select r from Region r where upper(r.localeId) = upper(:localeId) order by r.localeId, -r.sortIndex DESC, r.name") List<Region> findByLocaleIdIgnoreCase(String localeId); }
0
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference/1.2.0/africa/absa/inception/reference/TimeZone.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.Objects; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>TimeZone</b> class holds the information for a time zone. * * <p>A time zone is a region of the globe that observes a uniform standard time for legal, * commercial, and social purposes. Time zones tend to follow the boundaries of countries and their * subdivisions instead of strictly following longitude, because it is convenient for areas in close * commercial or other communication to keep the same time. * * @author Marcus Portmann */ @Schema(description = "A time zone") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "localeId", "sortIndex", "name", "description"}) public class TimeZone implements Serializable { private static final long serialVersionUID = 1000000; /** The description for the time zone. */ @Schema(description = "The description for the time zone", required = true) @JsonProperty(required = true) @NotNull @Size(max = 200) private String description; /** The ID for the time zone. */ @Schema(description = "The ID for the time zone", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 50) private String id; /** The Unicode locale identifier for the time zone. */ @Schema(description = "The Unicode locale identifier for the time zone", required = true) @JsonProperty(required = true) @NotNull @Size(min = 2, max = 10) private String localeId; /** The name of the time zone. */ @Schema(description = "The name of the time zone", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) private String name; /** The sort index for the time zone. */ @Schema(description = "The sort index for the time zone", required = true) @JsonProperty(required = true) @NotNull private Integer sortIndex; /** Constructs a new <b>TimeZone</b>. */ public TimeZone() {} /** * Constructs a new <b>TimeZone</b>. * * @param id the ID for the time zone * @param localeId the Unicode locale identifier for the time zone * @param name the name of the time zone * @param description the description for the time zone * @param sortIndex the sort index for the time zone */ public TimeZone(String id, String localeId, String name, String description, Integer sortIndex) { this.id = id; this.localeId = localeId; this.name = name; this.description = description; this.sortIndex = sortIndex; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b>false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } TimeZone other = (TimeZone) object; return Objects.equals(id, other.id) && Objects.equals(localeId, other.localeId); } /** * Returns the description for the time zone. * * @return the description for the time zone */ public String getDescription() { return description; } /** * Returns the ID for the time zone. * * @return the ID for the time zone */ public String getId() { return id; } /** * Returns the Unicode locale identifier for the time zone. * * @return the Unicode locale identifier for the time zone */ public String getLocaleId() { return localeId; } /** * Returns the name of the time zone. * * @return the name of the time zone */ public String getName() { return name; } /** * Returns the sort index for the time zone. * * @return the sort index for the time zone */ public Integer getSortIndex() { return sortIndex; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return ((id == null) ? 0 : id.hashCode()) + ((localeId == null) ? 0 : localeId.hashCode()); } /** * Set the description for the time zone. * * @param description the description for the time zone */ public void setDescription(String description) { this.description = description; } /** * Set the ID for the time zone. * * @param id the ID for the time zone */ public void setId(String id) { this.id = id; } /** * Set the Unicode locale identifier for the time zone. * * @param localeId the Unicode locale identifier for the time zone */ public void setLocaleId(String localeId) { this.localeId = localeId; } /** * Set the name of the time zone. * * @param name the name of the time zone */ public void setName(String name) { this.name = name; } /** * Set the sort index for the time zone. * * @param sortIndex the sort index for the time zone */ public void setSortIndex(Integer sortIndex) { this.sortIndex = sortIndex; } }
0
java-sources/africa/absa/inception-reference-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference-api/1.2.0/africa/absa/inception/reference/ReferenceApi.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import africa.absa.inception.api.ProblemDetails; import africa.absa.inception.api.SecureApi; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * The <b>ReferenceApi</b> class. * * @author Marcus Portmann */ @Tag(name = "Reference") @RestController @RequestMapping(value = "/api/reference") @CrossOrigin @SuppressWarnings({"unused", "WeakerAccess"}) // @el (isSecurityDisabled: africa.absa.inception.api.ApiSecurityExpressionRoot.isSecurityEnabled) public class ReferenceApi extends SecureApi { /** The Reference Service. */ private final IReferenceService referenceService; /** * Constructs a new <b>ReferenceRestController</b>. * * @param applicationContext the Spring application context * @param referenceService the Reference Service */ public ReferenceApi(ApplicationContext applicationContext, IReferenceService referenceService) { super(applicationContext); this.referenceService = referenceService; } /** * Retrieve the country reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the country reference * data for * @return the country reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the country reference data could not be retrieved */ @Operation( summary = "Retrieve the country reference data for a specific locale", description = "Retrieve the country reference data for a specific locale") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping(value = "/countries", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize("isSecurityDisabled() or isAuthenticated()") public List<Country> getCountries( @Parameter( name = "localeId", description = "The Unicode locale identifier for the locale to retrieve the country reference data for", example = "en-US") @RequestParam( value = "localeId", required = false, defaultValue = IReferenceService.DEFAULT_LOCALE_ID) String localeId) throws InvalidArgumentException, ServiceUnavailableException { return referenceService.getCountries(localeId); } /** * Retrieve the language reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the language reference * data for * @return the language reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the language reference data could not be retrieved */ @Operation( summary = "Retrieve the language reference data for a specific locale", description = "Retrieve the language reference data for a specific locale") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping(value = "/languages", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize("isSecurityDisabled() or isAuthenticated()") public List<Language> getLanguages( @Parameter( name = "localeId", description = "The Unicode locale identifier for the locale to retrieve the language reference data for", example = "en-US") @RequestParam( value = "localeId", required = false, defaultValue = IReferenceService.DEFAULT_LOCALE_ID) String localeId) throws InvalidArgumentException, ServiceUnavailableException { return referenceService.getLanguages(localeId); } /** * Retrieve the measurement system reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the measurement system * reference data for * @return the measurement system reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the measurement system reference data could not be * retrieved */ @Operation( summary = "Retrieve the measurement system reference data for a specific locale", description = "Retrieve the measurement system reference data for a specific locale") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/measurement-systems", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize("isSecurityDisabled() or isAuthenticated()") public List<MeasurementSystem> getMeasurementSystems( @Parameter( name = "localeId", description = "The Unicode locale identifier for the locale to retrieve the measurement system reference data for", example = "en-US") @RequestParam( value = "localeId", required = false, defaultValue = IReferenceService.DEFAULT_LOCALE_ID) String localeId) throws InvalidArgumentException, ServiceUnavailableException { return referenceService.getMeasurementSystems(localeId); } /** * Retrieve the measurement unit type reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the measurement unit * type reference data for * @return the measurement unit type reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the measurement unit type reference data could not be * retrieved */ @Operation( summary = "Retrieve the measurement unit type reference data for a specific locale", description = "Retrieve the measurement unit type reference data for a specific locale") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/measurement-unit-types", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize("isSecurityDisabled() or isAuthenticated()") public List<MeasurementUnitType> getMeasurementUnitTypes( @Parameter( name = "localeId", description = "The Unicode locale identifier for the locale to retrieve the measurement unit type reference data for", example = "en-US") @RequestParam( value = "localeId", required = false, defaultValue = IReferenceService.DEFAULT_LOCALE_ID) String localeId) throws InvalidArgumentException, ServiceUnavailableException { return referenceService.getMeasurementUnitTypes(localeId); } /** * Retrieve the measurement unit reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the measurement unit * reference data * @return the measurement unit reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the measurement unit reference data could not be * retrieved */ @Operation( summary = "Retrieve the measurement unit reference data for a specific locale", description = "Retrieve the measurement unit reference data for a specific locale") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/measurement-units", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize("isSecurityDisabled() or isAuthenticated()") public List<MeasurementUnit> getMeasurementUnits( @Parameter( name = "localeId", description = "The Unicode locale identifier for the locale to retrieve the measurement unit reference data for", example = "en-US") @RequestParam( value = "localeId", required = false, defaultValue = IReferenceService.DEFAULT_LOCALE_ID) String localeId) throws InvalidArgumentException, ServiceUnavailableException { return referenceService.getMeasurementUnits(localeId); } /** * Retrieve the region reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the region reference * data for * @return the region reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the region reference data could not be retrieved */ @Operation( summary = "Retrieve the region reference data for a specific locale", description = "Retrieve the region reference data for a specific locale") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping(value = "/regions", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize("isSecurityDisabled() or isAuthenticated()") public List<Region> getRegions( @Parameter( name = "localeId", description = "The Unicode locale identifier for the locale to retrieve the region reference data for", example = "en-US") @RequestParam( value = "localeId", required = false, defaultValue = IReferenceService.DEFAULT_LOCALE_ID) String localeId) throws InvalidArgumentException, ServiceUnavailableException { return referenceService.getRegions(localeId); } /** * Retrieve the time zone reference data for a specific locale. * * @param localeId the Unicode locale identifier for the locale to retrieve the time zone * reference data for * @return the time zone reference data * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the time zones reference data could not be retrieved */ @Operation( summary = "Retrieve the time zone reference data for a specific locale", description = "Retrieve the time zone reference data for a specific locale") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping(value = "/time-zones", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize("isSecurityDisabled() or isAuthenticated()") public List<TimeZone> getTimeZones( @Parameter( name = "localeId", description = "The Unicode locale identifier for the locale to retrieve the time zone reference data for", example = "en-US") @RequestParam( value = "localeId", required = false, defaultValue = IReferenceService.DEFAULT_LOCALE_ID) String localeId) throws InvalidArgumentException, ServiceUnavailableException { return referenceService.getTimeZones(localeId); } }
0
java-sources/africa/absa/inception-reference-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference-api/1.2.0/africa/absa/inception/reference/ReferenceApiConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; import io.swagger.v3.oas.models.info.Info; import org.springdoc.core.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * The <b>ReferenceApiConfiguration</b> class provides the Spring configuration for the Reference * API module. * * @author Marcus Portmann */ @Configuration public class ReferenceApiConfiguration { /** * Returns the grouped Open API for the Reference API. * * @return the grouped Open API for the Reference API */ @Bean public GroupedOpenApi referenceOpenApi() { return GroupedOpenApi.builder() .group("reference") .packagesToScan("africa.absa.inception.reference") .addOpenApiCustomiser( openApi -> openApi.info(new Info().title("Reference API").version(Version.PROJECT_VERSION))) .build(); } }
0
java-sources/africa/absa/inception-reference-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reference-api/1.2.0/africa/absa/inception/reference/Version.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reference; /** * The <b>Version</b> class. * * @author Marcus Portmann */ public final class Version { public static final String PROJECT_VERSION = "1.2.0"; }
0
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception/reporting/DuplicateReportDefinitionException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * The <b>DuplicateReportDefinitionException</b> exception is thrown to indicate an error condition * as a result of an attempt to create a duplicate report definition i.e a report definition with * the specified ID already exists. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/reporting/duplicate-report-definition", title = "A report definition with the specified ID already exists.", status = 409) public class DuplicateReportDefinitionException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>DuplicateReportDefinitionException</b>. * * @param reportDefinitionId the ID for the report definition */ public DuplicateReportDefinitionException(String reportDefinitionId) { super("The report definition with ID (" + reportDefinitionId + ") already exists"); } }
0
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception/reporting/IReportingService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import java.sql.Connection; import java.util.List; import java.util.Map; import org.w3c.dom.Document; /** * The <b>IReportingService</b> interface defines the functionality provided by a Reporting Service * implementation. * * @author Marcus Portmann */ @SuppressWarnings("unused") public interface IReportingService { /** The username used to identify operations performed by the system. */ String SYSTEM_USERNAME = "SYSTEM"; /** * Create the new report definition. * * @param reportDefinition the <b>ReportDefinition</b> instance containing the information for the * new report definition * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateReportDefinitionException if the report definition already exists * @throws ServiceUnavailableException if the report definition could not be created */ void createReportDefinition(ReportDefinition reportDefinition) throws InvalidArgumentException, DuplicateReportDefinitionException, ServiceUnavailableException; /** * Create the PDF for the report using a connection retrieved from the application data source. * * @param reportDefinitionId the ID for the report definition * @param parameters the parameters for the report * @return the PDF data for the report * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the report definition could not be created */ byte[] createReportPDF(String reportDefinitionId, Map<String, Object> parameters) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException; /** * Create the PDF for the report. * * @param reportDefinitionId the ID for the report definition * @param parameters the parameters for the report * @param connection the database connection used to retrieve the report data * @return the PDF data for the report * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the PDF for the report could not be created */ byte[] createReportPDF( String reportDefinitionId, Map<String, Object> parameters, Connection connection) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException; /** * Create the PDF for the report. * * @param reportDefinitionId the ID for the report definition * @param parameters the parameters for the report * @param document the XML document containing the report data * @return the PDF data for the report * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the PDF for the report could not be created */ byte[] createReportPDF( String reportDefinitionId, Map<String, Object> parameters, Document document) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException; /** * Delete the existing report definition. * * @param reportDefinitionId the ID for the report definition * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the report definition could not be deleted */ void deleteReportDefinition(String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException; /** * Returns the real path to the folder where the local Jasper reports are stored. * * @return the real path to the folder where the local Jasper reports are stored */ String getLocalReportFolderPath(); /** * Retrieve the report definition. * * @param reportDefinitionId the ID for the report definition * @return the report definition * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the report definition could not be retrieved */ ReportDefinition getReportDefinition(String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException; /** * Retrieve the name of the report definition. * * @param reportDefinitionId the ID for the report definition * @return the name of the report definition * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the name of the report definition could not be retrieved */ String getReportDefinitionName(String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException; /** * Returns the summaries for all the report definitions. * * @return the summaries for all the report definitions * @throws ServiceUnavailableException if the report definition summaries could not be retrieved */ List<ReportDefinitionSummary> getReportDefinitionSummaries() throws ServiceUnavailableException; /** * Retrieve the summary for the report definition. * * @param reportDefinitionId the ID for the report definition * @return the summary for the report definition * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the report definition summary could not be retrieved */ ReportDefinitionSummary getReportDefinitionSummary(String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException; /** * Returns all the report definitions. * * @return the report definitions * @throws ServiceUnavailableException if the report definitions could not be retrieved */ List<ReportDefinition> getReportDefinitions() throws ServiceUnavailableException; /** * Check whether the report definition exists. * * @param reportDefinitionId the ID for the report definition * @return <b>true</b> if the report definition exists or <b>false</b> otherwise * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the check for the existing report definition failed */ boolean reportDefinitionExists(String reportDefinitionId) throws InvalidArgumentException, ServiceUnavailableException; /** * Set the real path to the folder where the local Jasper reports are stored. * * @param localReportFolderPath the real path to the folder where the local Jasper reports are * stored */ void setLocalReportFolderPath(String localReportFolderPath); /** * Update the report definition. * * @param reportDefinition the <b>ReportDefinition</b> instance containing the updated information * for the report definition * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the report definition could not be updated */ void updateReportDefinition(ReportDefinition reportDefinition) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException; }
0
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception/reporting/ReportDefinition.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>ReportDefinition</b> class holds the information for a report definition. * * @author Marcus Portmann */ @Schema(description = "A report definition") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "name", "template"}) @Entity @Table(schema = "reporting", name = "report_definitions") @SuppressWarnings({"unused", "WeakerAccess"}) public class ReportDefinition implements Serializable { private static final long serialVersionUID = 1000000; /** The date and time the report definition was created. */ @JsonIgnore @Column(name = "created", nullable = false, updatable = false) private LocalDateTime created; /** The ID for the report definition. */ @Schema(description = "The ID for the report definition", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "id", length = 100, nullable = false) private String id; /** The name of the report definition. */ @Schema(description = "The name of the report definition", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The JasperReports template for the report definition. */ @Schema(description = "The JasperReports template for the report definition", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 10485760) @Column(name = "template", nullable = false) private byte[] template; /** The date and time the report definition was last updated. */ @JsonIgnore @Column(name = "updated", insertable = false) private LocalDateTime updated; /** Constructs a new <b>ReportDefinition</b>. */ public ReportDefinition() {} /** * Constructs a new <b>ReportDefinition</b>. * * @param id the ID for the report definition * @param name the name of the report definition * @param template the JasperReports template for the report definition */ public ReportDefinition(String id, String name, byte[] template) { this.id = id; this.name = name; this.template = template; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } ReportDefinition other = (ReportDefinition) object; return Objects.equals(id, other.id); } /** * Returns the date and time the report definition was created. * * @return the date and time the report definition was created */ public LocalDateTime getCreated() { return created; } /** * Returns the ID for the report definition. * * @return the ID for the report definition */ public String getId() { return id; } /** * Returns the name of the report definition. * * @return the name of the report definition */ public String getName() { return name; } /** * Returns the JasperReports template for the report definition. * * @return the JasperReports template for the report definition */ public byte[] getTemplate() { return template; } /** * Returns the date and time the report definition was last updated. * * @return the date and time the report definition was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } /** * Set the ID for the report definition. * * @param id the ID for the report definition */ public void setId(String id) { this.id = id; } /** * Set the name of the report definition. * * @param name the name of the report definition */ public void setName(String name) { this.name = name; } /** * Set the JasperReports template for the report definition. * * @param template the JasperReports template for the report definition */ public void setTemplate(byte[] template) { this.template = template; } /** * Returns a string representation of the object. * * @return a string representation of the object */ @Override public String toString() { return "ReportDefinition {id=\"" + getId() + "\", name=\"" + getName() + "\"}"; } /** The Java Persistence callback method invoked before the entity is created in the database. */ @PrePersist protected void onCreate() { created = LocalDateTime.now(); } /** The Java Persistence callback method invoked before the entity is updated in the database. */ @PreUpdate protected void onUpdate() { updated = LocalDateTime.now(); } }
0
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception/reporting/ReportDefinitionNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * The <b>ReportDefinitionNotFoundException</b> exception is thrown to indicate an error condition * as a result of a report definition that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/reporting/report-definition-not-found", title = "The report definition could not be found.", status = 404) public class ReportDefinitionNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * w Constructs a new <b>ReportDefinitionNotFoundException</b>. * * @param reportDefinitionId the ID for the report definition */ public ReportDefinitionNotFoundException(String reportDefinitionId) { super("The report definition with ID (" + reportDefinitionId + ") could not be found"); } }
0
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception/reporting/ReportDefinitionRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>ReportDefinitionRepository</b> interface declares the repository for the <b> * ReportDefinition</b> domain type. * * @author Marcus Portmann */ public interface ReportDefinitionRepository extends JpaRepository<ReportDefinition, String> { /** * Delete the report definition. * * @param reportDefinitionId the ID for the report definition */ @Modifying @Query("delete from ReportDefinition rd where rd.id = :reportDefinitionId") void deleteById(@Param("reportDefinitionId") String reportDefinitionId); /** * Retrieve the name for the report definition. * * @param reportDefinitionId the ID for the report definition * @return an Optional containing the name for the report definition or an empty Optional if the * report definition could not be found */ @Query("select rd.name from ReportDefinition rd where rd.id = :reportDefinitionId") Optional<String> getNameById(@Param("reportDefinitionId") String reportDefinitionId); }
0
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception/reporting/ReportDefinitionSummary.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>ReportDefinitionSummary</b> class holds the summary information for a report definition. * * @author Marcus Portmann */ @Schema(description = "A report definition summary") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"id", "name"}) @Entity @Table(schema = "reporting", name = "report_definitions") @SuppressWarnings({"unused"}) public class ReportDefinitionSummary implements Serializable { private static final long serialVersionUID = 1000000; /** The ID for the report definition. */ @Schema(description = "The ID for the report definition", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "id", length = 100, nullable = false) private String id; /** The name of the report definition. */ @Schema(description = "The name of the report definition", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** Constructs a new <b>ReportDefinitionSummary</b>. */ @SuppressWarnings("unused") public ReportDefinitionSummary() {} /** * Constructs a new <b>ReportDefinitionSummary</b>. * * @param id the ID for the report definition * @param name the name of the report definition */ ReportDefinitionSummary(String id, String name) { this.id = id; this.name = name; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } ReportDefinitionSummary other = (ReportDefinitionSummary) object; return Objects.equals(id, other.id); } /** * Returns the ID for the report definition. * * @return the ID for the report definition */ public String getId() { return id; } /** * Returns the name of the report definition. * * @return the name of the report definition */ public String getName() { return name; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } /** * Returns a string representation of the object. * * @return a string representation of the object */ @Override public String toString() { return "ReportDefinitionSummary {id=\"" + getId() + "\", name=\"" + getName() + "\"}"; } }
0
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception/reporting/ReportDefinitionSummaryRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import org.springframework.data.jpa.repository.JpaRepository; /** * The <b>ReportDefinitionSummaryRepository</b> interface declares the repository for the * <b>ReportDefinitionSummary</b> domain type. * * @author Marcus Portmann */ public interface ReportDefinitionSummaryRepository extends JpaRepository<ReportDefinitionSummary, String> {}
0
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception/reporting/ReportParameter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>ReportParameter</b> class holds the information for a report parameter. * * @author Marcus Portmann */ @Schema(description = "A parameter associated with a report") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"name", "value"}) @SuppressWarnings({"unused", "WeakerAccess"}) public class ReportParameter implements Serializable { private static final long serialVersionUID = 1000000; /** The name of the report parameter. */ @Schema(description = "The name of the report parameter", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) private String name; /** The value for the report parameter. */ @Schema(description = "The value for the report parameter", required = true) @JsonProperty(required = true) @NotNull private String value; /** Constructs a new <b>ReportParameter</b>. */ public ReportParameter() {} /** * Constructs a new <b>ReportParameter</b>. * * @param name the name of the report parameter * @param value the value for the report parameter */ public ReportParameter(String name, String value) { this.name = name; this.value = value; } /** * Returns the name of the report parameter. * * @return the name of the report parameter */ public String getName() { return name; } /** * Returns the value for the report parameter. * * @return the value for the report parameter */ public String getValue() { return value; } /** * Set the name of the report parameter. * * @param name the name of the report parameter */ public void setName(String name) { this.name = name; } /** * Set the value for the report parameter. * * @param value the value for the report parameter */ public void setValue(String value) { this.value = value; } }
0
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception/reporting/ReportingConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import africa.absa.inception.jpa.JpaUtil; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; /** * The <b>ReportingConfiguration</b> class provides the Spring configuration for the Reporting * module. * * @author Marcus Portmann */ @Configuration @EnableJpaRepositories( entityManagerFactoryRef = "reportingEntityManagerFactory", basePackages = {"africa.absa.inception.reporting"}) public class ReportingConfiguration { /** The Spring application context. */ private final ApplicationContext applicationContext; /** * Constructs a new <b>ReportingConfiguration</b>. * * @param applicationContext the Spring application context */ public ReportingConfiguration(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Returns the reporting entity manager factory bean associated with the application data source. * * @param dataSource the application data source * @param platformTransactionManager the platform transaction manager * @return the reporting entity manager factory bean associated with the application data source */ @Bean public LocalContainerEntityManagerFactoryBean reportingEntityManagerFactory( @Qualifier("applicationDataSource") DataSource dataSource, PlatformTransactionManager platformTransactionManager) { return JpaUtil.createEntityManager( "reporting", dataSource, platformTransactionManager, "africa.absa.inception.reporting"); } }
0
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting/1.2.0/africa/absa/inception/reporting/ReportingService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.core.service.ValidationError; import java.io.ByteArrayInputStream; import java.sql.Connection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.sql.DataSource; import javax.validation.ConstraintViolation; import javax.validation.Validator; import net.sf.jasperreports.engine.JRParameter; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import org.w3c.dom.Document; /** * The <b>ReportingService</b> class provides the Reporting Service implementation. * * @author Marcus Portmann */ @Service @SuppressWarnings("unused") public class ReportingService implements IReportingService { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(ReportingService.class); /** The data source used to provide connections to the application database. */ private final DataSource dataSource; /** The Report Definition Repository. */ private final ReportDefinitionRepository reportDefinitionRepository; /** The Report Definition Summary Repository. */ private final ReportDefinitionSummaryRepository reportDefinitionSummaryRepository; /** The JSR-303 validator. */ private final Validator validator; /* The real path to the folder where the local Jasper reports are stored. */ private String localReportFolderPath; /** * Constructs a new <b>ReportingService</b>. * * @param validator the JSR-303 validator * @param dataSource the data source used to provide connections to the application database * @param reportDefinitionRepository the Report Definition Repository * @param reportDefinitionSummaryRepository the Report Definition Summary Repository */ public ReportingService( Validator validator, @Qualifier("applicationDataSource") DataSource dataSource, ReportDefinitionRepository reportDefinitionRepository, ReportDefinitionSummaryRepository reportDefinitionSummaryRepository) { this.validator = validator; this.dataSource = dataSource; this.reportDefinitionRepository = reportDefinitionRepository; this.reportDefinitionSummaryRepository = reportDefinitionSummaryRepository; } @Override @Transactional public void createReportDefinition(ReportDefinition reportDefinition) throws InvalidArgumentException, DuplicateReportDefinitionException, ServiceUnavailableException { validateReportDefinition(reportDefinition); try { if (reportDefinitionRepository.existsById(reportDefinition.getId())) { throw new DuplicateReportDefinitionException(reportDefinition.getId()); } reportDefinitionRepository.saveAndFlush(reportDefinition); } catch (DuplicateReportDefinitionException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the report definition (" + reportDefinition.getId() + ")", e); } } @Override public byte[] createReportPDF(String reportDefinitionId, Map<String, Object> parameters) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(reportDefinitionId)) { throw new InvalidArgumentException("reportDefinitionId"); } if (parameters == null) { throw new InvalidArgumentException("parameters"); } try (Connection connection = dataSource.getConnection()) { return createReportPDF(reportDefinitionId, parameters, connection); } catch (ReportDefinitionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the PDF for the report using the report definition (" + reportDefinitionId + ")", e); } } @Override public byte[] createReportPDF( String reportDefinitionId, Map<String, Object> parameters, Connection connection) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(reportDefinitionId)) { throw new InvalidArgumentException("reportDefinitionId"); } if (parameters == null) { throw new InvalidArgumentException("parameters"); } if (connection == null) { throw new InvalidArgumentException("connection"); } try { Optional<ReportDefinition> reportDefinitionOptional = reportDefinitionRepository.findById(reportDefinitionId); if (reportDefinitionOptional.isEmpty()) { throw new ReportDefinitionNotFoundException(reportDefinitionId); } Map<String, Object> localParameters = new HashMap<>(); if (!StringUtils.hasText(getLocalReportFolderPath())) { localParameters.put("SUBREPORT_DIR", getLocalReportFolderPath()); } for (String name : parameters.keySet()) { localParameters.put(name, parameters.get(name)); } JasperPrint jasperPrint = JasperFillManager.fillReport( new ByteArrayInputStream(reportDefinitionOptional.get().getTemplate()), localParameters, connection); return JasperExportManager.exportReportToPdf(jasperPrint); } catch (ReportDefinitionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the PDF for the report using the report definition (" + reportDefinitionId + ")", e); } } @Override public byte[] createReportPDF( String reportDefinitionId, Map<String, Object> parameters, Document document) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(reportDefinitionId)) { throw new InvalidArgumentException("reportDefinitionId"); } if (parameters == null) { throw new InvalidArgumentException("parameters"); } if (document == null) { throw new InvalidArgumentException("document"); } try { ReportDefinition reportDefinition = getReportDefinition(reportDefinitionId); Map<String, Object> localParameters = new HashMap<>(); localParameters.put(JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, document); localParameters.put(JRXPathQueryExecuterFactory.XML_DATE_PATTERN, "yyyy-MM-dd"); localParameters.put(JRXPathQueryExecuterFactory.XML_NUMBER_PATTERN, "#,##0.##"); localParameters.put(JRXPathQueryExecuterFactory.XML_LOCALE, Locale.ENGLISH); localParameters.put(JRParameter.REPORT_LOCALE, Locale.US); if (!StringUtils.hasText(getLocalReportFolderPath())) { localParameters.put("SUBREPORT_DIR", getLocalReportFolderPath()); } for (String name : parameters.keySet()) { localParameters.put(name, parameters.get(name)); } JasperPrint jasperPrint = JasperFillManager.fillReport( new ByteArrayInputStream(reportDefinition.getTemplate()), localParameters); return JasperExportManager.exportReportToPdf(jasperPrint); } catch (ReportDefinitionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to create the PDF for the report using the report definintion (" + reportDefinitionId + ")", e); } } @Override @Transactional public void deleteReportDefinition(String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(reportDefinitionId)) { throw new InvalidArgumentException("reportDefinitionId"); } try { if (!reportDefinitionRepository.existsById(reportDefinitionId)) { throw new ReportDefinitionNotFoundException(reportDefinitionId); } reportDefinitionRepository.deleteById(reportDefinitionId); } catch (ReportDefinitionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to delete the report definition (" + reportDefinitionId + ")", e); } } @Override public String getLocalReportFolderPath() { return localReportFolderPath; } @Override public ReportDefinition getReportDefinition(String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(reportDefinitionId)) { throw new InvalidArgumentException("reportDefinitionId"); } try { Optional<ReportDefinition> reportDefinitionOptional = reportDefinitionRepository.findById(reportDefinitionId); if (reportDefinitionOptional.isPresent()) { return reportDefinitionOptional.get(); } else { throw new ReportDefinitionNotFoundException(reportDefinitionId); } } catch (ReportDefinitionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the report definition (" + reportDefinitionId + ")", e); } } @Override public String getReportDefinitionName(String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(reportDefinitionId)) { throw new InvalidArgumentException("reportDefinitionId"); } try { Optional<String> nameOptional = reportDefinitionRepository.getNameById(reportDefinitionId); if (nameOptional.isPresent()) { return nameOptional.get(); } throw new ReportDefinitionNotFoundException(reportDefinitionId); } catch (ReportDefinitionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the name of the report definition (" + reportDefinitionId + ")", e); } } @Override public List<ReportDefinitionSummary> getReportDefinitionSummaries() throws ServiceUnavailableException { try { return reportDefinitionSummaryRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the summaries for the report definitions", e); } } @Override public ReportDefinitionSummary getReportDefinitionSummary(String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(reportDefinitionId)) { throw new InvalidArgumentException("reportDefinitionId"); } try { Optional<ReportDefinitionSummary> reportDefinitionSummaryOptional = reportDefinitionSummaryRepository.findById(reportDefinitionId); if (reportDefinitionSummaryOptional.isPresent()) { return reportDefinitionSummaryOptional.get(); } else { throw new ReportDefinitionNotFoundException(reportDefinitionId); } } catch (ReportDefinitionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to retrieve the summary for the report definition (" + reportDefinitionId + ")", e); } } @Override public List<ReportDefinition> getReportDefinitions() throws ServiceUnavailableException { try { return reportDefinitionRepository.findAll(); } catch (Throwable e) { throw new ServiceUnavailableException("Failed to retrieve the report definitions", e); } } @Override public boolean reportDefinitionExists(String reportDefinitionId) throws InvalidArgumentException, ServiceUnavailableException { if (!StringUtils.hasText(reportDefinitionId)) { throw new InvalidArgumentException("reportDefinitionId"); } try { return reportDefinitionRepository.existsById(reportDefinitionId); } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to check whether the report definition (" + reportDefinitionId + ") exists", e); } } @Override public void setLocalReportFolderPath(String localReportFolderPath) { this.localReportFolderPath = localReportFolderPath; } @Override @Transactional public void updateReportDefinition(ReportDefinition reportDefinition) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { validateReportDefinition(reportDefinition); try { if (!reportDefinitionRepository.existsById(reportDefinition.getId())) { throw new ReportDefinitionNotFoundException(reportDefinition.getId()); } reportDefinitionRepository.saveAndFlush(reportDefinition); } catch (ReportDefinitionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException( "Failed to update the report definition (" + reportDefinition.getId() + ")", e); } } private void validateReportDefinition(ReportDefinition reportDefinition) throws InvalidArgumentException { if (reportDefinition == null) { throw new InvalidArgumentException("reportDefinition"); } Set<ConstraintViolation<ReportDefinition>> constraintViolations = validator.validate(reportDefinition); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "reportDefinition", ValidationError.toValidationErrors(constraintViolations)); } } }
0
java-sources/africa/absa/inception-reporting-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting-api/1.2.0/africa/absa/inception/reporting/GenerateReportRequest.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.util.List; /** * The <b>GenerateReportRequest</b> class holds the information for a request to generate a report. * * @author Marcus Portmann */ @Schema(description = "A request to generate a report") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"reportDefinitionId", "reportParameters"}) @SuppressWarnings({"unused", "WeakerAccess"}) public class GenerateReportRequest implements Serializable { private static final long serialVersionUID = 1000000; /** The ID for the report definition. */ @Schema(description = "The ID for the report definition", required = true) @JsonProperty(required = true) private String reportDefinitionId; /** The report parameters. */ @Schema(description = "The report parameters", required = true) @JsonProperty(required = true) private List<ReportParameter> reportParameters; /** Constructs a new <b>GenerateReportRequest</b>. */ public GenerateReportRequest() {} /** * Constructs a new <b>GenerateReportRequest</b>. * * @param reportDefinitionId the ID for the report definition * @param reportParameters the report parameters */ public GenerateReportRequest(String reportDefinitionId, List<ReportParameter> reportParameters) { this.reportDefinitionId = reportDefinitionId; this.reportParameters = reportParameters; } /** * Returns the ID for the report definition. * * @return the ID for the report definition */ public String getReportDefinitionId() { return reportDefinitionId; } /** * Returns the report parameters. * * @return the report parameters */ public List<ReportParameter> getReportParameters() { return reportParameters; } /** * Set the ID for the report definition. * * @param reportDefinitionId the ID for the report definition */ public void setReportDefinitionId(String reportDefinitionId) { this.reportDefinitionId = reportDefinitionId; } /** * Set the report parameters. * * @param reportParameters the report parameters */ public void setReportParameters(List<ReportParameter> reportParameters) { this.reportParameters = reportParameters; } }
0
java-sources/africa/absa/inception-reporting-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting-api/1.2.0/africa/absa/inception/reporting/ReportingApi.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import africa.absa.inception.api.ApiUtil; import africa.absa.inception.api.ProblemDetails; import africa.absa.inception.api.SecureApi; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import africa.absa.inception.core.service.ValidationError; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.tags.Tag; import java.sql.Connection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.sql.DataSource; import javax.validation.ConstraintViolation; import javax.validation.Validator; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * The <b>ReportingApi</b> class. * * @author Marcus Portmann */ @Tag(name = "Reporting") @RestController @RequestMapping(value = "/api/reporting") @CrossOrigin @SuppressWarnings({"unused"}) // @el (isSecurityDisabled: africa.absa.inception.api.ApiSecurityExpressionRoot.isSecurityEnabled) public class ReportingApi extends SecureApi { /** The data source used to provide connections to the application database. */ private final DataSource dataSource; /** The Reporting Service. */ private final IReportingService reportingService; /** The JSR-303 validator. */ private final Validator validator; /** * Constructs a new <b>ReportingRestController</b>. * * @param applicationContext the Spring application context * @param dataSource the data source used to provide connections to the application database * @param reportingService the Reporting Service * @param validator the JSR-303 validator */ public ReportingApi( ApplicationContext applicationContext, @Qualifier("applicationDataSource") DataSource dataSource, IReportingService reportingService, Validator validator) { super(applicationContext); this.dataSource = dataSource; this.reportingService = reportingService; this.validator = validator; } /** * Create the new report definition. * * @param reportDefinition the report definition to create * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateReportDefinitionException if the report definition already exists * @throws ServiceUnavailableException if the report definition could not be created */ @Operation(summary = "Create the report definition", description = "Create the report definition") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The report definition was created successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "409", description = "A report definition with the specified ID already exists", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/report-definitions", method = RequestMethod.POST, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Reporting.ReportingAdministration') or hasAuthority('FUNCTION_Reporting.ReportDefinitionAdministration')") public void createReportDefinition( @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The report definition to create", required = true) @RequestBody ReportDefinition reportDefinition) throws InvalidArgumentException, DuplicateReportDefinitionException, ServiceUnavailableException { reportingService.createReportDefinition(reportDefinition); } /** * Delete the report definition. * * @param reportDefinitionId the ID for the report definition * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the report definition could not be deleted */ @Operation(summary = "Delete the report definition", description = "Delete the report definition") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The report definition was deleted successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The report definition could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/report-definitions/{reportDefinitionId}", method = RequestMethod.DELETE, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Reporting.ReportingAdministration') or hasAuthority('FUNCTION_Reporting.ReportDefinitionAdministration')") public void deleteReportDefinition( @Parameter( name = "reportDefinitionId", description = "The ID for the report definition", required = true) @PathVariable String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { reportingService.deleteReportDefinition(reportDefinitionId); } /** * Generate the PDF report. * * @param generateReportRequest the request to generate the PDF report * @return the PDF report * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the PDF report could not be generated */ @Operation(summary = "Generate the PDF report", description = "Generate the PDF report") @ApiResponses( value = { @ApiResponse( responseCode = "200", description = "The PDF report was generated successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The report definition could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/generate-report", method = RequestMethod.POST, produces = "application/pdf") public ResponseEntity<byte[]> generateReport( @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The request to generate a report", required = true) @RequestBody GenerateReportRequest generateReportRequest) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { if (generateReportRequest == null) { throw new InvalidArgumentException("generateReportRequest"); } Set<ConstraintViolation<GenerateReportRequest>> constraintViolations = validator.validate(generateReportRequest); if (!constraintViolations.isEmpty()) { throw new InvalidArgumentException( "generateReportRequest", ValidationError.toValidationErrors(constraintViolations)); } Map<String, Object> parameters = new HashMap<>(); for (ReportParameter reportParameter : generateReportRequest.getReportParameters()) { parameters.put(reportParameter.getName(), reportParameter.getValue()); } ReportDefinitionSummary reportDefinitionSummary = reportingService.getReportDefinitionSummary(generateReportRequest.getReportDefinitionId()); try (Connection connection = dataSource.getConnection()) { byte[] reportPDF = reportingService.createReportPDF( generateReportRequest.getReportDefinitionId(), parameters, connection); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/pdf")); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); String filename = reportDefinitionSummary.getName().replaceAll(" ", "") + ".pdf"; headers.setContentDispositionFormData(filename, filename); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); return new ResponseEntity<>(reportPDF, headers, HttpStatus.OK); } catch (ReportDefinitionNotFoundException e) { throw e; } catch (Throwable e) { throw new ServiceUnavailableException("Failed to generate the PDF report", e); } } /** * Retrieve the report definition. * * @param reportDefinitionId the ID for the report definition * @return the report definition * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the report definition could not be retrieved */ @Operation( summary = "Retrieve the report definition", description = "Retrieve the report definition") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The report definition could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/report-definitions/{reportDefinitionId}", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Reporting.ReportingAdministration') or hasAuthority('FUNCTION_Reporting.ReportDefinitionAdministration')") public ReportDefinition getReportDefinition( @Parameter( name = "reportDefinition", description = "The ID for the report definition", required = true) @PathVariable String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { return reportingService.getReportDefinition(reportDefinitionId); } /** * Retrieve the name of the report definition. * * @param reportDefinitionId the ID for the report definition * @return the name of the report definition * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the name of the report definition could not be retrieved */ @Operation( summary = "Retrieve the name of the report definition", description = "Retrieve the name of the report definition") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The report definition could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/report-definitions/{reportDefinitionId}/name", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) public String getReportDefinitionName( @Parameter( name = "reportDefinitionId", description = "The ID for the report definition", required = true) @PathVariable String reportDefinitionId) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { return ApiUtil.quote(reportingService.getReportDefinitionName(reportDefinitionId)); } /** * Retrieve the report definition summaries. * * @return the report definition summaries * @throws ServiceUnavailableException if the report definition summaries could not be retrieved */ @Operation( summary = "Retrieve the report definition summaries", description = "Retrieve the report definition summaries") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/report-definition-summaries", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Reporting.ReportingAdministration') or hasAuthority('FUNCTION_Reporting.ReportDefinitionAdministration')") public List<ReportDefinitionSummary> getReportDefinitionSummaries() throws ServiceUnavailableException { return reportingService.getReportDefinitionSummaries(); } /** * Retrieve the report definitions. * * @return the report definitions * @throws ServiceUnavailableException if the report definitions could not be retrieved */ @Operation( summary = "Retrieve the report definitions", description = "Retrieve the report definitions") @ApiResponses( value = { @ApiResponse(responseCode = "200", description = "OK"), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/report-definitions", method = RequestMethod.GET, produces = "application/json") @ResponseStatus(HttpStatus.OK) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Reporting.ReportingAdministration') or hasAuthority('FUNCTION_Reporting.ReportDefinitionAdministration')") public List<ReportDefinition> getReportDefinitions() throws ServiceUnavailableException { return reportingService.getReportDefinitions(); } /** * Update the report definition. * * @param reportDefinitionId the ID for the report definition * @param reportDefinition the report definition * @throws InvalidArgumentException if an argument is invalid * @throws ReportDefinitionNotFoundException if the report definition could not be found * @throws ServiceUnavailableException if the report definition could not be updated */ @Operation(summary = "Update the report definition", description = "Update the report definition") @ApiResponses( value = { @ApiResponse( responseCode = "204", description = "The report definition was updated successfully"), @ApiResponse( responseCode = "400", description = "Invalid argument", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "403", description = "Access denied", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "404", description = "The report definition could not be found", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))), @ApiResponse( responseCode = "500", description = "An error has occurred and the request could not be processed at this time", content = @Content( mediaType = "application/problem+json", schema = @Schema(implementation = ProblemDetails.class))) }) @RequestMapping( value = "/report-definitions/{reportDefinitionId}", method = RequestMethod.PUT, produces = "application/json") @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize( "isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Reporting.ReportingAdministration') or hasAuthority('FUNCTION_Reporting.ReportDefinitionAdministration')") public void updateReportDefinition( @Parameter( name = "reportDefinitionId", description = "The ID for the report definition", required = true) @PathVariable String reportDefinitionId, @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "The report definition to update", required = true) @RequestBody ReportDefinition reportDefinition) throws InvalidArgumentException, ReportDefinitionNotFoundException, ServiceUnavailableException { if (!StringUtils.hasText(reportDefinitionId)) { throw new InvalidArgumentException("reportDefinitionId"); } if (reportDefinition == null) { throw new InvalidArgumentException("reportDefinition"); } if (!reportDefinitionId.equals(reportDefinition.getId())) { throw new InvalidArgumentException("reportDefinition"); } reportingService.updateReportDefinition(reportDefinition); } }
0
java-sources/africa/absa/inception-reporting-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting-api/1.2.0/africa/absa/inception/reporting/ReportingApiConfiguration.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; import io.swagger.v3.oas.models.info.Info; import org.springdoc.core.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * The <b>ReportingApiConfiguration</b> class provides the Spring configuration for the Reporting * API module. * * @author Marcus Portmann */ @Configuration public class ReportingApiConfiguration { /** * Returns the grouped Open API for the Reporting API. * * @return the grouped Open API for the Reporting API */ @Bean public GroupedOpenApi reportingOpenApi() { return GroupedOpenApi.builder() .group("reporting") .packagesToScan("africa.absa.inception.reporting") .addOpenApiCustomiser( openApi -> openApi.info(new Info().title("Reporting API").version(Version.PROJECT_VERSION))) .build(); } }
0
java-sources/africa/absa/inception-reporting-api/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-reporting-api/1.2.0/africa/absa/inception/reporting/Version.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.reporting; /** * The <b>Version</b> class. * * @author Marcus Portmann */ public final class Version { public static final String PROJECT_VERSION = "1.2.0"; }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/AlwaysTrueValueMatcher.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; /** * The <b>AlwaysTrueValueMatcher</b> class implements a <b>ValueMatcher</b> that always returns * <b>true</b>. * * @author Carlo Pelliccia * @author Marcus Portmann */ public class AlwaysTrueValueMatcher implements ValueMatcher { /** * Validate the given integer value against a set of rules. * * @param value the value * @return <b>true</b> if the given value matches the rules of the <b>ValueMatcher</b> , * <b>false</b> otherwise */ public boolean match(int value) { return true; } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/BackgroundJobExecutor.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import java.util.Optional; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; /** * The <b>BackgroundJobExecutor</b> class implements the Background Job Executor. * * @author Marcus Portmann */ @Service @SuppressWarnings("unused") public class BackgroundJobExecutor implements InitializingBean { /** The default number of minutes an idle processing thread should be kept alive. */ private static final int DEFAULT_IDLE_PROCESSING_THREADS_KEEP_ALIVE_TIME = 5; /** The default number of threads to start initially to process jobs. */ private static final int DEFAULT_INITIAL_PROCESSING_THREADS = 1; /** * The default maximum number of jobs to queue for processing if no processing threads are * available. */ private static final int DEFAULT_MAXIMUM_PROCESSING_QUEUE_LENGTH = 100; /** The default maximum number of threads to create to process jobs. */ private static final int DEFAULT_MAXIMUM_PROCESSING_THREADS = 10; /* Logger */ private static final Logger logger = LoggerFactory.getLogger(BackgroundJobExecutor.class); /** The Scheduler Service. */ private final ISchedulerService schedulerService; /** The executor responsible for processing jobs. */ private Executor jobProcessor; /** * Constructs a new <b>BackgroundJobExecutor</b>. * * @param schedulerService the Scheduler Service */ public BackgroundJobExecutor(ISchedulerService schedulerService) { this.schedulerService = schedulerService; } /** Initialize the Background Job Executor. */ @Override public void afterPropertiesSet() { logger.info("Initializing the Background Job Executor"); if (schedulerService != null) { // Initialize the job processor this.jobProcessor = new ThreadPoolExecutor( DEFAULT_INITIAL_PROCESSING_THREADS, DEFAULT_MAXIMUM_PROCESSING_THREADS, DEFAULT_IDLE_PROCESSING_THREADS_KEEP_ALIVE_TIME, TimeUnit.MINUTES, new LinkedBlockingQueue<>(DEFAULT_MAXIMUM_PROCESSING_QUEUE_LENGTH)); // Reset any locks for jobs that were previously being executed try { logger.info("Resetting the locks for the jobs being executed"); schedulerService.resetJobLocks(JobStatus.EXECUTING, JobStatus.SCHEDULED); } catch (Throwable e) { logger.error("Failed to reset the locks for the jobs being executed", e); } // Schedule any unscheduled jobs try { while (schedulerService.scheduleNextUnscheduledJobForExecution()) {} } catch (Throwable e) { logger.error("Failed to schedule the unscheduled jobs for execution"); } } else { logger.error( "Failed to initialize the Background Job Executor: " + "The Scheduler Service was NOT injected"); } } /** Execute the jobs. */ @SuppressWarnings("StatementWithEmptyBody") @Scheduled(cron = "0 * * * * *") public void executeJobs() { Optional<Job> jobOptional; if (schedulerService == null) { return; } while (true) { // Retrieve the next job scheduled for execution try { jobOptional = schedulerService.getNextJobScheduledForExecution(); if (jobOptional.isEmpty()) { if (logger.isDebugEnabled()) { logger.debug("No jobs scheduled for execution"); } // Schedule any unscheduled jobs while (schedulerService.scheduleNextUnscheduledJobForExecution()) {} return; } } catch (Throwable e) { logger.error("Failed to retrieve the next job scheduled for execution", e); return; } jobProcessor.execute(new JobExecutor(schedulerService, jobOptional.get())); } } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/DayOfMonthValueMatcher.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import java.util.List; /** * The <b>DayOfMonthValueMatcher</b> class implements a <b>ValueMatcher</b> whose rules are in a * plain array of integer values. * * <p>When asked to validate a value, this ValueMatcher checks if it is in the array and, if not, * checks whether the last-day-of-month setting applies. * * @author Paul Fernley * @author Marcus Portmann */ @SuppressWarnings({"unused", "WeakerAccess"}) public class DayOfMonthValueMatcher extends IntArrayValueMatcher { private static final int[] lastDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /** * Constructs a new <b>DayOfMonthValueMatcher</b>. * * @param integers The Integer elements, one for every value accepted by the matcher. The match() * method will return <b>true</b> only if its parameter will be one of this list or the * last-day-of-month setting applies. */ public DayOfMonthValueMatcher(List<Integer> integers) { super(integers); } /** * Returns <b>true</b> if the given value is included in the matcher list or the last-day-of-month * setting applies otherwise <b>false</b>. * * @param value the value * @param month the month * @param isLeapYear <b>true</b> if this is a leap year <b>false</b> otherwise * @return <b>true</b> if the given value matches the rules of the <b>ValueMatcher</b> , * <b>false</b> otherwise */ public boolean match(int value, int month, boolean isLeapYear) { return (super.match(value) || ((value > 27) && match(32) && isLastDayOfMonth(value, month, isLeapYear))); } private boolean isLastDayOfMonth(int value, int month, boolean isLeapYear) { if (isLeapYear && (month == 2)) { return value == 29; } else { return value == lastDays[month - 1]; } } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/DuplicateJobException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * A <b>DuplicateJobException</b> is thrown to indicate that a scheduler operation failed as a * result of a duplicate job. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/scheduler/duplicate-job", title = "A job with the specified ID already exists.", status = 409) public class DuplicateJobException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>DuplicateJobException</b>. * * @param jobId the ID for the job */ public DuplicateJobException(String jobId) { super("A job with the ID (" + jobId + ") already exists"); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/IJob.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; /** * The <b>IJob</b> interface defines the functionality that must be provided by all jobs. * * @author Marcus Portmann */ public interface IJob { /** * Execute the job. * * @param context the job execution context * @throws JobExecutionFailedException if the job execution failed */ void execute(JobExecutionContext context) throws JobExecutionFailedException; }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/ISchedulerService.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import africa.absa.inception.core.service.InvalidArgumentException; import africa.absa.inception.core.service.ServiceUnavailableException; import java.util.List; import java.util.Optional; /** * The <b>ISchedulerService</b> interface defines the functionality provided by a Scheduler Service * implementation. * * @author Marcus Portmann */ @SuppressWarnings("unused") public interface ISchedulerService { /** * Create the new job. * * @param job the <b>Job</b> instance containing the information for the job * @throws InvalidArgumentException if an argument is invalid * @throws DuplicateJobException if the job already exists * @throws ServiceUnavailableException if the job could not be created */ void createJob(Job job) throws InvalidArgumentException, DuplicateJobException, ServiceUnavailableException; /** * Delete the job * * @param jobId the ID for the job * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the job could not be deleted */ void deleteJob(String jobId) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException; /** * Execute the job. * * @param job the job * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the job could not be executed */ void executeJob(Job job) throws InvalidArgumentException, ServiceUnavailableException; /** * Retrieve the filtered jobs. * * @param filter the filter to apply to the jobs * @return the jobs * @throws ServiceUnavailableException if the filtered jobs could not be retrieved */ List<Job> getFilteredJobs(String filter) throws ServiceUnavailableException; /** * Retrieve the job. * * @param jobId the ID for the job * @return the job * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the job could not be retrieved */ Job getJob(String jobId) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException; /** * Retrieve the name of the job. * * @param jobId the ID for the job * @return the name of the job * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the name of the job could not be retrieved */ String getJobName(String jobId) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException; /** * Retrieve the jobs. * * @return the jobs * @throws ServiceUnavailableException if the jobs could not be retrieved */ List<Job> getJobs() throws ServiceUnavailableException; /** * Returns the maximum number of times execution will be attempted for a job. * * @return the maximum number of times execution will be attempted for a job */ int getMaximumJobExecutionAttempts(); /** * Retrieve the next job that is scheduled for execution. * * <p>The job will be locked to prevent duplicate processing. * * @return an Optional containing the next job that is scheduled for execution or an empty * Optional if no jobs are currently scheduled for execution * @throws ServiceUnavailableException if the next job scheduled for execution could not be * retrieved */ Optional<Job> getNextJobScheduledForExecution() throws ServiceUnavailableException; /** * Retrieve the unscheduled jobs. * * @return the unscheduled jobs * @throws ServiceUnavailableException if the unscheduled jobs could not be retrieved */ List<Job> getUnscheduledJobs() throws ServiceUnavailableException; /** * Reschedule the job for execution. * * @param jobId the ID for the job * @param schedulingPattern the cron-style scheduling pattern for the job used to determine the * next execution time * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the job could not be rescheduled for execution */ void rescheduleJob(String jobId, String schedulingPattern) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException; /** * Reset the job locks. * * @param status the current status of the jobs that have been locked * @param newStatus the new status for the jobs that have been unlocked * @throws InvalidArgumentException if an argument is invalid * @throws ServiceUnavailableException if the job locks could not be reset */ void resetJobLocks(JobStatus status, JobStatus newStatus) throws InvalidArgumentException, ServiceUnavailableException; /** * Schedule the next unscheduled job for execution. * * @return <b>true</b> if a job was successfully scheduled for execution or <b>false</b> otherwise * @throws ServiceUnavailableException if the next unscheduled job could not be scheduled for * execution */ boolean scheduleNextUnscheduledJobForExecution() throws ServiceUnavailableException; /** * Set the status for the job. * * @param jobId the ID for the job * @param status the new status for the job * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the status could not be set for the job */ void setJobStatus(String jobId, JobStatus status) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException; /** * Unlock a locked job. * * @param jobId the ID for the job * @param status the new status for the unlocked job * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the job could not be unlocked */ void unlockJob(String jobId, JobStatus status) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException; /** * Update the job. * * @param job the <b>Job</b> instance containing the updated information for the job * @throws InvalidArgumentException if an argument is invalid * @throws JobNotFoundException if the job could not be found * @throws ServiceUnavailableException if the job could not be updated */ void updateJob(Job job) throws InvalidArgumentException, JobNotFoundException, ServiceUnavailableException; }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/IntArrayValueMatcher.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import java.util.List; /** * The <b>IntArrayValueMatcher</b> class implements a <b>ValueMatcher</b> whose rules are in a plain * array of integer values. * * <p>When asked to validate a value, this ValueMatcher checks if it is in the array. * * @author Carlo Pelliccia * @author Marcus Portmann */ public class IntArrayValueMatcher implements ValueMatcher { /** The accepted values. */ private final int[] values; /** * Builds the ValueMatcher. * * @param integers The Integer elements, one for every value accepted by the matcher. The match() * method will return true only if its parameter will be one of this list. */ IntArrayValueMatcher(List<Integer> integers) { int size = integers.size(); values = new int[size]; for (int i = 0; i < size; i++) { try { values[i] = integers.get(i); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage()); } } } /** * Validate the given integer value against a set of rules. * * <p>Returns <b>true</b> if the given value is included in the matcher list. * * @param value the value * @return <b>true</b> if the given value matches the rules of the <b>ValueMatcher</b> , * <b>false</b> otherwise */ public boolean match(int value) { for (int value1 : values) { if (value1 == value) { return true; } } return false; } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/InvalidSchedulingPatternException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; /** * The <b>InvalidSchedulingPatternException</b> exception is thrown to indicate an error condition * when executing a job. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @SuppressWarnings({"unused", "WeakerAccess"}) public class InvalidSchedulingPatternException extends Exception { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>InvalidSchedulingPatternException</b> with the specified message. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. */ InvalidSchedulingPatternException(String message) { super(message); } /** * Constructs a new <b>InvalidSchedulingPatternException</b> with the specified message and cause. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ public InvalidSchedulingPatternException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/Job.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>Job</b> class holds the information for a job. * * @author Marcus Portmann */ @Schema(description = "A scheduled job") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "id", "name", "schedulingPattern", "jobClass", "enabled", "status", "executionAttempts", "lockName", "lastExecuted", "nextExecution", "parameters" }) @Entity @Table(schema = "scheduler", name = "jobs") @SuppressWarnings({"unused", "WeakerAccess"}) public class Job implements Serializable { private static final long serialVersionUID = 1000000; /** The parameters for the job. */ @Schema(description = "The parameters for the job") @JsonProperty @JsonManagedReference @Valid @OneToMany( mappedBy = "job", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true) private final Set<JobParameter> parameters = new HashSet<>(); /** The date and time the job was created. */ @JsonIgnore @Column(name = "created", nullable = false, updatable = false) private LocalDateTime created; /** Is the job enabled for execution? */ @Schema(description = "Is the job enabled for execution", required = true) @JsonProperty(required = true) @NotNull @Column(name = "enabled", nullable = false) private boolean enabled; /** The number of times the current execution of the job has been attempted. */ @Schema(description = "The number of times the current execution of the job has been attempted") @JsonProperty @Column(name = "execution_attempts") private Integer executionAttempts = 0; /** The ID for the job. */ @Schema(description = "The ID for the job", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "id", length = 100, nullable = false) private String id; /** The fully qualified name of the Java class that implements the job. */ @Schema( description = "The fully qualified name of the Java class that implements the job", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 1000) @Column(name = "job_class", length = 1000, nullable = false) private String jobClass; /** The date and time the job was last executed. */ @Schema(description = "The date and time the job was last executed") @JsonProperty @Column(name = "last_executed") private LocalDateTime lastExecuted; /** The name of the entity that has locked the job for execution. */ @Schema(description = "The name of the entity that has locked the job for execution") @Size(min = 1, max = 100) @Column(name = "lock_name", length = 100) private String lockName; /** The name of the job. */ @Schema(description = "The name of the job", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "name", length = 100, nullable = false) private String name; /** The date and time when the job will next be executed. */ @Schema(description = "The date and time when the job will next be executed") @JsonProperty @Column(name = "next_execution") private LocalDateTime nextExecution; /** The cron-style scheduling pattern for the job. */ @Schema(description = "The cron-style scheduling pattern for the job", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Column(name = "scheduling_pattern", length = 100, nullable = false) private String schedulingPattern; /** The status of the job. */ @Schema(description = "The status of the job", required = true) @JsonProperty(required = true) @NotNull @Column(name = "status", nullable = false) private JobStatus status; /** The date and time the job was last updated. */ @JsonIgnore @Column(name = "updated", insertable = false) private LocalDateTime updated; /** Constructs a new <b>Job</b>. */ public Job() {} /** * Constructs a new <b>Job</b>. * * @param id the ID for the job * @param name the name of the job * @param schedulingPattern the cron-style scheduling pattern for the job * @param jobClass the fully qualified name of the Java class that implements the job * @param enabled is the job enabled for execution * @param status the status of the job * @param executionAttempts the number of times the current execution of the job has been * attempted * @param lockName the name of the entity that has locked the job for execution * @param lastExecuted the date and time the job was last executed * @param nextExecution the date and time when the job will next be executed */ public Job( String id, String name, String schedulingPattern, String jobClass, boolean enabled, JobStatus status, int executionAttempts, String lockName, LocalDateTime lastExecuted, LocalDateTime nextExecution) { this.id = id; this.name = name; this.schedulingPattern = schedulingPattern; this.jobClass = jobClass; this.enabled = enabled; this.status = status; this.executionAttempts = executionAttempts; this.lockName = lockName; this.lastExecuted = lastExecuted; this.nextExecution = nextExecution; } /** * Add the parameter for the job. * * @param parameter the parameter */ public void addParameter(JobParameter parameter) { parameters.removeIf( existingParameter -> Objects.equals(existingParameter.getName(), parameter.getName())); parameter.setJob(this); this.parameters.add(parameter); } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } Job other = (Job) object; return Objects.equals(id, other.id); } /** * Returns the date and time the job was created. * * @return the date and time the job was created */ public LocalDateTime getCreated() { return created; } /** * Returns the number of times the current execution of the job has been attempted. * * @return the number of times the current execution of the job has been attempted */ public Integer getExecutionAttempts() { return executionAttempts; } /** * Returns the ID for the job. * * @return the ID for the job */ public String getId() { return id; } /** * Returns the fully qualified name of the Java class that implements the job. * * @return the fully qualified name of the Java class that implements the job */ public String getJobClass() { return jobClass; } /** * Returns date and time the job was last executed. * * @return the date and time the job was last executed */ public LocalDateTime getLastExecuted() { return lastExecuted; } /** * Returns the name of the entity that has locked the job for execution. * * @return the name of the entity that has locked the job for execution */ public String getLockName() { return lockName; } /** * Returns the name of the job. * * @return the name of the job */ public String getName() { return name; } /** * Returns the date and time when the job will next be executed. * * @return the date and time when the job will next be executed */ public LocalDateTime getNextExecution() { return nextExecution; } /** * Returns the parameters for the job. * * @return the parameters for the job */ public Set<JobParameter> getParameters() { return parameters; } /** * Returns the cron-style scheduling pattern for the job. * * @return the cron-style scheduling pattern for the job */ public String getSchedulingPattern() { return schedulingPattern; } /** * Returns the status of the job. * * @return the status of the job */ public JobStatus getStatus() { return status; } /** * Returns the date and time the job was last updated. * * @return the date and time the job was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } /** Increment the number of execution attempts for the job. */ public void incrementExecutionAttempts() { if (executionAttempts == null) { executionAttempts = 1; } else { executionAttempts++; } } /** * Returns whether the job is enabled for execution. * * @return <b>true</b> if the job is enabled for execution or <b>false</b> otherwise */ public boolean isEnabled() { return enabled; } /** * Remove the parameter for the job. * * @param parameterName the name of the parameter */ public void removeParameter(String parameterName) { for (JobParameter parameter : parameters) { if (parameterName.equalsIgnoreCase(parameter.getName())) { this.parameters.remove(parameter); return; } } } /** * Set whether the job is enabled for execution. * * @param enabled <b>true</b> if the job is enabled for execution or <b>false</b> otherwise */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Set the number of times the current execution of the job has been attempted. * * @param executionAttempts the number of times the current execution of the job has been * attempted */ public void setExecutionAttempts(Integer executionAttempts) { this.executionAttempts = executionAttempts; } /** * Set the ID for the job. * * @param id the ID for the scheduled job */ public void setId(String id) { this.id = id; } /** * Set the fully qualified name of the Java class that implements the job. * * @param jobClass the fully qualified name of the Java class that implements the job */ public void setJobClass(String jobClass) { this.jobClass = jobClass; } /** * Set the date and time the job was last executed. * * @param lastExecuted the date and time the job was last executed */ public void setLastExecuted(LocalDateTime lastExecuted) { this.lastExecuted = lastExecuted; } /** * Set the name of the entity that has locked the job for execution. * * @param lockName the name of the entity that has locked the job for execution */ public void setLockName(String lockName) { this.lockName = lockName; } /** * Set the name of the job. * * @param name the name of the job */ public void setName(String name) { this.name = name; } /** * Set the date and time when the job will next be executed. * * @param nextExecution the date and time when the job will next be executed */ public void setNextExecution(LocalDateTime nextExecution) { this.nextExecution = nextExecution; } /** * Set the parameters for the job. * * @param parameters the parameters for the job */ public void setParameters(Set<JobParameter> parameters) { this.parameters.clear(); this.parameters.addAll(parameters); } /** * Set the cron-style scheduling pattern for the job. * * @param schedulingPattern the cron-style scheduling pattern for the job */ public void setSchedulingPattern(String schedulingPattern) { this.schedulingPattern = schedulingPattern; } /** * Set the status of the job. * * @param status the status of the job */ public void setStatus(JobStatus status) { this.status = status; } /** The Java Persistence callback method invoked before the entity is created in the database. */ @PrePersist protected void onCreate() { created = LocalDateTime.now(); } /** The Java Persistence callback method invoked before the entity is updated in the database. */ @PreUpdate protected void onUpdate() { updated = LocalDateTime.now(); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/JobExecutionContext.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import java.time.LocalDateTime; import java.util.Map; import java.util.Optional; /** * The <b>JobExecutionContext</b> class provides access to context information associated with the * execution of a job. * * @author Marcus Portmann */ @SuppressWarnings({"unused", "WeakerAccess"}) public class JobExecutionContext { /** The date and time that the job was scheduled to be executed. */ private final LocalDateTime executionDate; /** The parameters for the job. */ private final Map<String, String> parameters; /** * Constructs a new <b>JobExecutionContext</b>. * * @param executionDate the date and time that the job was scheduled to be executed * @param parameters the parameters for the job */ public JobExecutionContext(LocalDateTime executionDate, Map<String, String> parameters) { this.executionDate = executionDate; this.parameters = parameters; } /** * Returns the date and time that the job was scheduled to be executed. * * @return the date and time that the job was scheduled to be executed */ public LocalDateTime getExecutionDate() { return executionDate; } /** * Returns the parameter with the specified name for the job. * * @param name the name of the parameter * @return an Optional containing the value of the parameter with the specified name or an empty * Optional if the parameter cannot be found */ public Optional<String> getParameter(String name) { return Optional.ofNullable(parameters.get(name)); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/JobExecutionFailedException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; /** * The <b>JobExecutionFailedException</b> exception is thrown to indicate an error condition when * executing a job. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @SuppressWarnings({"unused", "WeakerAccess"}) public class JobExecutionFailedException extends Exception { private static final long serialVersionUID = 1000000; /** Constructs a new <b>JobException</b> with <b>null</b> as its message. */ public JobExecutionFailedException() { super(); } /** * Constructs a new <b>JobException</b> with the specified message. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. */ public JobExecutionFailedException(String message) { super(message); } /** * Constructs a new <b>JobException</b> with the specified cause and a message of <b> (cause==null * ? null : cause.toString())</b> (which typically contains the class and message of cause). * * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ public JobExecutionFailedException(Throwable cause) { super(cause); } /** * Constructs a new <b>JobException</b> with the specified message and cause. * * @param message The message saved for later retrieval by the <b>getMessage()</b> method. * @param cause The cause saved for later retrieval by the <b>getCause()</b> method. (A * <b>null</b> value is permitted if the cause is nonexistent or unknown) */ public JobExecutionFailedException(String message, Throwable cause) { super(message, cause); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/JobExecutor.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <b>JobExecutorThread</b> class. * * @author Marcus Portmann */ public class JobExecutor implements Runnable { /* Logger */ private static final Logger logger = LoggerFactory.getLogger(JobExecutor.class); private final Job job; private final ISchedulerService schedulerService; /** * Constructs a new <b>JobExecutorThread</b>. * * @param schedulerService the Scheduler Service * @param job the job */ public JobExecutor(ISchedulerService schedulerService, Job job) { this.schedulerService = schedulerService; this.job = job; } @Override public void run() { try { if (logger.isDebugEnabled()) { logger.debug(String.format("Executing the job (%s)", job.getId())); } schedulerService.executeJob(job); // Reschedule the job try { schedulerService.rescheduleJob(job.getId(), job.getSchedulingPattern()); try { schedulerService.unlockJob(job.getId(), JobStatus.SCHEDULED); } catch (Throwable f) { logger.error( String.format( "Failed to unlock and set the status for the job (%s) to \"Scheduled\"", job.getId()), f); } } catch (Throwable e) { logger.warn( String.format( "The job (%s) could not be rescheduled and will be marked as \"Failed\"", job.getId())); try { schedulerService.unlockJob(job.getId(), JobStatus.FAILED); } catch (Throwable f) { logger.error( String.format( "Failed to unlock and set the status for the job (%s) to \"Failed\"", job.getId()), f); } } } catch (Throwable e) { logger.error(String.format("Failed to execute the job (%s)", job.getId()), e); try { /* * If the job has exceeded the maximum number of execution attempts then * unlock it and set its status to "Failed" otherwise unlock it and set its status to * "Scheduled". */ if (job.getExecutionAttempts() >= schedulerService.getMaximumJobExecutionAttempts()) { logger.warn( String.format( "The job (%s) has exceeded the maximum number of execution attempts and will be " + "marked as \"Failed\"", job.getId())); schedulerService.unlockJob(job.getId(), JobStatus.FAILED); } else { schedulerService.unlockJob(job.getId(), JobStatus.SCHEDULED); } } catch (Throwable f) { logger.error( String.format("Failed to unlock and set the status for the job (%s)", job.getId()), f); } } } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/JobNotFoundException.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import africa.absa.inception.core.service.Problem; import africa.absa.inception.core.service.ServiceException; /** * The <b>JobNotFoundException</b> exception is thrown to indicate an error condition as a result of * a job that could not be found. * * <p>This is a checked exception to prevent the automatic rollback of the current transaction. * * @author Marcus Portmann */ @Problem( type = "http://inception.absa.africa/problems/scheduler/job-not-found", title = "The job could not be found.", status = 404) public class JobNotFoundException extends ServiceException { private static final long serialVersionUID = 1000000; /** * Constructs a new <b>JobNotFoundException</b>. * * @param jobId the ID for the job */ public JobNotFoundException(String jobId) { super("The job with ID (" + jobId + ") could not be found"); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/JobParameter.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.swagger.v3.oas.annotations.media.Schema; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * The <b>JobParameter</b> class holds the information for a job parameter. * * @author Marcus Portmann */ @Schema(description = "A parameter for a scheduled job") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"name", "value"}) @Entity @Table(schema = "scheduler", name = "job_parameters") @IdClass(JobParameterId.class) @SuppressWarnings({"unused"}) public class JobParameter implements Serializable { private static final long serialVersionUID = 1000000; /** The date and time the job parameter was created. */ @JsonIgnore @Column(name = "created", nullable = false, updatable = false) private LocalDateTime created; /** The job the job parameter is associated with. */ @JsonBackReference @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "job_id") private Job job; /** The name of the job parameter. */ @Schema(description = "The name of the job parameter", required = true) @JsonProperty(required = true) @NotNull @Size(min = 1, max = 100) @Id @Column(name = "name", length = 100, nullable = false) private String name; /** The date and time the job parameter was last updated. */ @JsonIgnore @Column(name = "updated", insertable = false) private LocalDateTime updated; /** The value of the job parameter. */ @Schema(description = "The value of the job parameter", required = true) @JsonProperty(required = true) @NotNull @Size(max = 4000) @Column(name = "value", length = 4000, nullable = false) private String value; /** Constructs a new <b>JobParameter</b>. */ public JobParameter() {} /** * Constructs a new <b>JobParameter</b>. * * @param name the name of the job parameter * @param value the value of the job parameter */ public JobParameter(String name, String value) { this.name = name; this.value = value; } /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } JobParameter other = (JobParameter) object; return Objects.equals(job, other.job) && Objects.equals(name, other.name); } /** * Returns the date and time the job parameter was created. * * @return the date and time the job parameter was created */ public LocalDateTime getCreated() { return created; } /** * Returns the job the job parameter is associated with. * * @return the job the job parameter is associated with */ public Job getJob() { return job; } /** * Returns the name of the job parameter. * * @return the name of the job parameter */ public String getName() { return name; } /** * Returns the date and time the job parameter was last updated. * * @return the date and time the job parameter was last updated */ public LocalDateTime getUpdated() { return updated; } /** * Returns the value of the job parameter. * * @return the value of the job parameter */ public String getValue() { return value; } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (((job == null) || (job.getId() == null)) ? 0 : job.getId().hashCode()) + ((name == null) ? 0 : name.hashCode()); } /** * Set the job the job parameter is associated with. * * @param job the job the job parameter is associated with */ public void setJob(Job job) { this.job = job; } /** * Set the name of the job parameter. * * @param name the name of the job parameter */ public void setName(String name) { this.name = name; } /** * Set the value of the job parameter. * * @param value the value of the job parameter */ public void setValue(String value) { this.value = value; } /** The Java Persistence callback method invoked before the entity is created in the database. */ @PrePersist protected void onCreate() { created = LocalDateTime.now(); } /** The Java Persistence callback method invoked before the entity is updated in the database. */ @PreUpdate protected void onUpdate() { updated = LocalDateTime.now(); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/JobParameterId.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import java.io.Serializable; import java.util.Objects; /** * The <b>JobParameterId</b> class implements the ID class for the <b>JobParameter</b> class. * * @author Marcus Portmann */ @SuppressWarnings({"UnusedDeclaration"}) public class JobParameterId implements Serializable { /** The job the job parameter is associated with. */ private Job job; /** The name of the job parameter. */ private String name; /** * Indicates whether some other object is "equal to" this one. * * @param object the reference object with which to compare * @return <b>true</b> if this object is the same as the object argument otherwise <b> false</b> */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } JobParameterId other = (JobParameterId) object; return Objects.equals(job, other.job) && Objects.equals(name, other.name); } /** * Returns a hash code value for the object. * * @return a hash code value for the object */ @Override public int hashCode() { return (((job == null) || (job.getId() == null)) ? 0 : job.getId().hashCode()) + ((name == null) ? 0 : name.hashCode()); } }
0
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception
java-sources/africa/absa/inception-scheduler/1.2.0/africa/absa/inception/scheduler/JobRepository.java
/* * Copyright 2021 original authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package africa.absa.inception.scheduler; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import javax.persistence.LockModeType; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Lock; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; /** * The <b>JobRepository</b> interface declares the repository for the <b>Job</b> domain type. * * @author Marcus Portmann */ public interface JobRepository extends JpaRepository<Job, String> { /** * Delete the job. * * @param jobId the ID for the job */ @Modifying @Query("delete from Job j where j.id = :jobId") void deleteById(@Param("jobId") String jobId); /** * Retrieve the filtered jobs. * * @param filter the filter to apply to the jobs * @return the filtered jobs */ @Query( "select j from Job j where lower(j.name) like lower(:filter) or lower(j.jobClass) " + "like lower(:filter)") List<Job> findFiltered(String filter); /** * Retrieve the jobs scheduled for execution. * * @param lastExecutedBefore the date and time used to select failed jobs for reprocessing * @param currentTimestamp the current date and time * @param pageable the pagination information * @return the jobs scheduled for execution */ @Lock(LockModeType.PESSIMISTIC_WRITE) @Query( "select j from Job j where j.enabled = true and j.status = 2 and " + "(j.lastExecuted < :lastExecutedBefore or j.executionAttempts = 0) " + "and j.nextExecution <= :currentTimestamp") List<Job> findJobsScheduledForExecutionForWrite( @Param("lastExecutedBefore") LocalDateTime lastExecutedBefore, @Param("currentTimestamp") LocalDateTime currentTimestamp, Pageable pageable); /** * Retrieve the unscheduled jobs. * * @return the unscheduled jobs */ @Query("select j from Job j where j.enabled = true and j.status = 1") List<Job> findUnscheduledJobs(); /** * Retrieve and lock the unscheduled jobs. * * @param pageable the pagination information * @return the unscheduled jobs */ @Lock(LockModeType.PESSIMISTIC_WRITE) @Query("select j from Job j where j.enabled = true and j.status = 1") List<Job> findUnscheduledJobsForWrite(Pageable pageable); /** * Retrieve the name for the job. * * @param jobId the ID for the job * @return an Optional containing the name for the job or an empty Optional if the job could not * be found */ @Query("select j.name from Job j where j.id = :jobId") Optional<String> getNameById(@Param("jobId") String jobId); /** * Lock the job for execution. * * @param jobId the ID for the job * @param lockName the name of the lock * @param when the date and time the job is locked for execution */ @Modifying @Query( "update Job j set j.lockName = :lockName, j.status = 3, " + "j.executionAttempts = j.executionAttempts + 1, j.lastExecuted = :when " + "where j.id = :jobId") void lockJobForExecution( @Param("jobId") String jobId, @Param("lockName") String lockName, @Param("when") LocalDateTime when); /** * Reset the job locks with the specified status. * * @param status the status * @param newStatus the new status for the jobs * @param lockName the lock name */ @Modifying @Query( "update Job j set j.status = :newStatus, j.lockName = null " + "where j.lockName = :lockName and j.status = :status") void resetJobLocks( @Param("status") JobStatus status, @Param("newStatus") JobStatus newStatus, @Param("lockName") String lockName); /** * Schedule the job. * * @param jobId the ID for the job * @param nextExecution the date and time the job is scheduled for execution */ @Modifying @Query( "update Job j set j.status = 2, j.executionAttempts = 0, " + "j.nextExecution = :nextExecution where j.id = :jobId") void scheduleJob( @Param("jobId") String jobId, @Param("nextExecution") LocalDateTime nextExecution); /** * Set the job status. * * @param jobId the ID for the job * @param status the status for the job */ @Modifying @Query("update Job j set j.status = :status where j.id = :jobId") void setJobStatus(@Param("jobId") String jobId, @Param("status") JobStatus status); /** * Unlock the job. * * @param jobId the ID for the job * @param status the status for the job */ @Modifying @Query("update Job j set j.status = :status, j.lockName = null where j.id = :jobId") void unlockJob(@Param("jobId") String jobId, @Param("status") JobStatus status); }