index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodesConfiguration.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.codes;
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>CodesConfiguration</b> class provides the Spring configuration for the Codes module.
*
* @author Marcus Portmann
*/
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "codesEntityManagerFactory",
basePackages = {"africa.absa.inception.codes"})
public class CodesConfiguration {
/** The Spring application context. */
private final ApplicationContext applicationContext;
/**
* Constructs a new <b>CodesConfiguration</b>.
*
* @param applicationContext the Spring application context
*/
public CodesConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* Returns the codes entity manager factory bean associated with the application data source.
*
* @param dataSource the application data source
* @param platformTransactionManager the platform transaction manager
* @return the codes entity manager factory bean associated with the application data source
*/
@Bean
public LocalContainerEntityManagerFactoryBean codesEntityManagerFactory(
@Qualifier("applicationDataSource") DataSource dataSource,
PlatformTransactionManager platformTransactionManager) {
return JpaUtil.createEntityManager(
"codes", dataSource, platformTransactionManager, "africa.absa.inception.codes");
}
}
|
0
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/CodesService.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.codes;
import africa.absa.inception.core.service.InvalidArgumentException;
import africa.absa.inception.core.service.ServiceUnavailableException;
import africa.absa.inception.core.service.ValidationError;
import africa.absa.inception.core.xml.DtdJarResolver;
import africa.absa.inception.core.xml.XmlParserErrorHandler;
import africa.absa.inception.core.xml.XmlUtil;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
/**
* The <b>CodesService</b> class provides the Codes Service implementation.
*
* @author Marcus Portmann
*/
@Service
@SuppressWarnings("unused")
public class CodesService implements ICodesService, InitializingBean {
/**
* The path to the code provider configuration files (META-INF/code-providers.xml) on the
* classpath.
*/
private static final String CODE_PROVIDERS_CONFIGURATION_PATH = "META-INF/code-providers.xml";
/* Logger */
private static final Logger logger = LoggerFactory.getLogger(CodesService.class);
/** The Spring application context. */
private final ApplicationContext applicationContext;
/** The Code Category Repository. */
private final CodeCategoryRepository codeCategoryRepository;
/** The Code Category Summary Repository. */
private final CodeCategorySummaryRepository codeCategorySummaryRepository;
/** The Code Repository. */
private final CodeRepository codeRepository;
/** The JSR-303 validator. */
private final Validator validator;
/**
* The configuration information for the code providers read from the code provider configuration
* files (META-INF/code-providers.xml) on the classpath.
*/
private List<CodeProviderConfig> codeProviderConfigs;
/* The code providers. */
private List<ICodeProvider> codeProviders;
/**
* Constructs a new <b>CodesService</b>.
*
* @param applicationContext the Spring application context
* @param validator the JSR-303 validator
* @param codeCategoryRepository the Code Category Repository
* @param codeCategorySummaryRepository the Code Category Summary Repository
* @param codeRepository the Code Repository
*/
public CodesService(
ApplicationContext applicationContext,
Validator validator,
CodeCategoryRepository codeCategoryRepository,
CodeCategorySummaryRepository codeCategorySummaryRepository,
CodeRepository codeRepository) {
this.applicationContext = applicationContext;
this.validator = validator;
this.codeCategoryRepository = codeCategoryRepository;
this.codeCategorySummaryRepository = codeCategorySummaryRepository;
this.codeRepository = codeRepository;
}
@Override
public void afterPropertiesSet() {
logger.info("Initializing the Codes Service");
codeProviders = new ArrayList<>();
try {
// Read the codes configuration
readCodeProviderConfigurations();
// Initialize the code providers
initCodeProviders();
} catch (Throwable e) {
throw new RuntimeException("Failed to initialize the Codes Service", e);
}
}
@Override
public boolean codeCategoryExists(String codeCategoryId)
throws InvalidArgumentException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
try {
return codeCategoryRepository.existsById(codeCategoryId);
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to check whether the code category (" + codeCategoryId + ") exists", e);
}
}
@Override
public boolean codeExists(String codeCategoryId, String codeId)
throws InvalidArgumentException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
if (!StringUtils.hasText(codeId)) {
throw new InvalidArgumentException("codeId");
}
try {
return codeRepository.existsById(new CodeId(codeCategoryId, codeId));
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to check whether the code ("
+ codeId
+ ") exists for the code category ("
+ codeCategoryId
+ ")",
e);
}
}
@Override
@Transactional
public void createCode(Code code)
throws InvalidArgumentException, DuplicateCodeException, CodeCategoryNotFoundException,
ServiceUnavailableException {
validateCode(code);
try {
if (codeRepository.existsById(new CodeId(code.getCodeCategoryId(), code.getId()))) {
throw new DuplicateCodeException(code.getCodeCategoryId(), code.getId());
}
if (!codeCategoryRepository.existsById(code.getCodeCategoryId())) {
throw new CodeCategoryNotFoundException(code.getCodeCategoryId());
}
codeRepository.saveAndFlush(code);
} catch (DuplicateCodeException | CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to create the code ("
+ code.getName()
+ ") for the code category ("
+ code.getCodeCategoryId()
+ ")",
e);
}
}
@Override
@Transactional
public void createCodeCategory(CodeCategory codeCategory)
throws InvalidArgumentException, DuplicateCodeCategoryException, ServiceUnavailableException {
validateCodeCategory(codeCategory);
try {
if (codeCategoryRepository.existsById(codeCategory.getId())) {
throw new DuplicateCodeCategoryException(codeCategory.getId());
}
codeCategoryRepository.saveAndFlush(codeCategory);
} catch (DuplicateCodeCategoryException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to create the code category (" + codeCategory.getId() + ")", e);
}
}
@Override
@Transactional
public void deleteCode(String codeCategoryId, String codeId)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
if (!StringUtils.hasText(codeId)) {
throw new InvalidArgumentException("codeId");
}
try {
CodeId id = new CodeId(codeCategoryId, codeId);
if (!codeRepository.existsById(id)) {
throw new CodeNotFoundException(codeCategoryId, codeId);
}
codeRepository.deleteById(codeCategoryId, codeId);
} catch (CodeNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to delete the code ("
+ codeId
+ ") for the code category ("
+ codeCategoryId
+ ")",
e);
}
}
@Override
@Transactional
public void deleteCodeCategory(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
try {
if (!codeCategoryRepository.existsById(codeCategoryId)) {
throw new CodeCategoryNotFoundException(codeCategoryId);
}
codeCategoryRepository.deleteById(codeCategoryId);
} catch (CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to delete the code category (" + codeCategoryId + ")", e);
}
}
@Override
public Code getCode(String codeCategoryId, String codeId)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
if (!StringUtils.hasText(codeId)) {
throw new InvalidArgumentException("codeId");
}
try {
Optional<Code> codeOptional = codeRepository.findById(new CodeId(codeCategoryId, codeId));
if (codeOptional.isPresent()) {
return codeOptional.get();
} else {
// Check if one of the registered code providers supports the code category
for (ICodeProvider codeProvider : codeProviders) {
if (codeProvider.codeCategoryExists(codeCategoryId)) {
return codeProvider.getCode(codeCategoryId, codeId);
}
}
}
throw new CodeNotFoundException(codeCategoryId, codeId);
} catch (CodeNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the code ("
+ codeId
+ ") for the code category ("
+ codeCategoryId
+ ")",
e);
}
}
@Override
public List<CodeCategory> getCodeCategories() throws ServiceUnavailableException {
try {
return codeCategoryRepository.findAll();
} catch (Throwable e) {
throw new ServiceUnavailableException("Failed to retrieve the code categories", e);
}
}
@Override
public CodeCategory getCodeCategory(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
try {
Optional<CodeCategory> codeCategoryOptional = codeCategoryRepository.findById(codeCategoryId);
if (codeCategoryOptional.isPresent()) {
return codeCategoryOptional.get();
}
// Check if one of the registered code providers supports the code category
for (ICodeProvider codeProvider : codeProviders) {
if (codeProvider.codeCategoryExists(codeCategoryId)) {
return codeProvider.getCodeCategory(codeCategoryId);
}
}
throw new CodeCategoryNotFoundException(codeCategoryId);
} catch (CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the code category (" + codeCategoryId + ")", e);
}
}
@Override
public String getCodeCategoryData(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
try {
Optional<String> dataOptional = codeCategoryRepository.getDataById(codeCategoryId);
if (dataOptional.isPresent()) {
return dataOptional.get();
}
// Check if one of the registered code providers supports the code category
for (ICodeProvider codeProvider : codeProviders) {
if (codeProvider.codeCategoryExists(codeCategoryId)) {
String codeProviderData = codeProvider.getCodeCategoryData(codeCategoryId);
return StringUtils.hasText(codeProviderData) ? codeProviderData : "";
}
}
throw new CodeCategoryNotFoundException(codeCategoryId);
} catch (CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the data for the code category (" + codeCategoryId + ")", e);
}
}
@Override
public String getCodeCategoryDataWithParameters(
String codeCategoryId, Map<String, String> parameters)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
try {
Optional<String> dataOptional = codeCategoryRepository.getDataById(codeCategoryId);
if (dataOptional.isPresent()) {
return dataOptional.get();
}
// Check if one of the registered code providers supports the code category
for (ICodeProvider codeProvider : codeProviders) {
if (codeProvider.codeCategoryExists(codeCategoryId)) {
String codeProviderData =
codeProvider.getCodeCategoryDataWithParameters(codeCategoryId, parameters);
return StringUtils.hasText(codeProviderData) ? codeProviderData : "";
}
}
throw new CodeCategoryNotFoundException(codeCategoryId);
} catch (CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the data for the code category (" + codeCategoryId + ")", e);
}
}
@Override
public String getCodeCategoryName(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
try {
Optional<String> nameOptional = codeCategoryRepository.getNameById(codeCategoryId);
if (nameOptional.isPresent()) {
return nameOptional.get();
}
// Check if one of the registered code providers supports the code category
for (ICodeProvider codeProvider : codeProviders) {
if (codeProvider.codeCategoryExists(codeCategoryId)) {
return codeProvider.getCodeCategoryName(codeCategoryId);
}
}
throw new CodeCategoryNotFoundException(codeCategoryId);
} catch (CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the name of the code category (" + codeCategoryId + ")", e);
}
}
@Override
public List<CodeCategorySummary> getCodeCategorySummaries() throws ServiceUnavailableException {
try {
return codeCategorySummaryRepository.findAll();
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the summaries for the code categories", e);
}
}
@Override
public LocalDateTime getCodeCategoryUpdated(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
try {
Optional<LocalDateTime> updatedOptional =
codeCategoryRepository.getUpdatedById(codeCategoryId);
if (updatedOptional.isPresent()) {
return updatedOptional.get();
}
// Check if one of the registered code providers supports the code category
for (ICodeProvider codeProvider : codeProviders) {
if (codeProvider.codeCategoryExists(codeCategoryId)) {
return codeProvider.getCodeCategoryLastUpdated(codeCategoryId);
}
}
throw new CodeCategoryNotFoundException(codeCategoryId);
} catch (CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the date and time the code category ("
+ codeCategoryId
+ ") was last updated",
e);
}
}
@Override
public String getCodeName(String codeCategoryId, String codeId)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
if (!StringUtils.hasText(codeId)) {
throw new InvalidArgumentException("codeId");
}
try {
Optional<String> nameOptional = codeRepository.getNameById(codeCategoryId, codeId);
if (nameOptional.isPresent()) {
return nameOptional.get();
} else {
// Check if one of the registered code providers supports the code category
for (ICodeProvider codeProvider : codeProviders) {
if (codeProvider.codeCategoryExists(codeCategoryId)) {
return codeProvider.getCodeName(codeCategoryId, codeId);
}
}
}
throw new CodeNotFoundException(codeCategoryId, codeId);
} catch (CodeNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the name of the code ("
+ codeId
+ ") for the code category ("
+ codeCategoryId
+ ")",
e);
}
}
@Override
public List<Code> getCodesForCodeCategory(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
try {
if (codeCategoryRepository.existsById(codeCategoryId)) {
return codeRepository.findByCodeCategoryId(codeCategoryId);
}
// Check if one of the registered code providers supports the code category
for (ICodeProvider codeProvider : codeProviders) {
if (codeProvider.codeCategoryExists(codeCategoryId)) {
return codeProvider.getCodesForCodeCategory(codeCategoryId);
}
}
throw new CodeCategoryNotFoundException(codeCategoryId);
} catch (CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the codes for the code category (" + codeCategoryId + ")", e);
}
}
@Override
public List<Code> getCodesForCodeCategoryWithParameters(
String codeCategoryId, Map<String, String> parameters)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
try {
if (codeCategoryRepository.existsById(codeCategoryId)) {
return codeRepository.findByCodeCategoryId(codeCategoryId);
}
// Check if one of the registered code providers supports the code category
for (ICodeProvider codeProvider : codeProviders) {
if (codeProvider.codeCategoryExists(codeCategoryId)) {
return codeProvider.getCodesForCodeCategoryWithParameters(codeCategoryId, parameters);
}
}
throw new CodeCategoryNotFoundException(codeCategoryId);
} catch (CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the codes for the code category (" + codeCategoryId + ")", e);
}
}
@Override
public void updateCode(Code code)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException {
validateCode(code);
try {
if (!codeRepository.existsById(new CodeId(code.getCodeCategoryId(), code.getId()))) {
throw new CodeNotFoundException(code.getCodeCategoryId(), code.getId());
}
codeRepository.saveAndFlush(code);
} catch (CodeNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException("Failed to update the code (" + code.getId() + ")", e);
}
}
@Override
public void updateCodeCategory(CodeCategory codeCategory)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
validateCodeCategory(codeCategory);
try {
if (!codeCategoryRepository.existsById(codeCategory.getId())) {
throw new CodeCategoryNotFoundException(codeCategory.getId());
}
codeCategoryRepository.saveAndFlush(codeCategory);
} catch (CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to update the code category (" + codeCategory.getId() + ")", e);
}
}
@Override
@Transactional
public void updateCodeCategoryData(String codeCategoryId, String data)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
try {
if (!codeCategoryRepository.existsById(codeCategoryId)) {
throw new CodeCategoryNotFoundException(codeCategoryId);
}
codeCategoryRepository.setDataAndUpdatedById(codeCategoryId, data, LocalDateTime.now());
} catch (CodeCategoryNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to update the data for the code category (" + codeCategoryId + ")", e);
}
}
/** Initialize the code providers. */
private void initCodeProviders() {
// Initialize each code provider
for (CodeProviderConfig codeProviderConfig : codeProviderConfigs) {
try {
logger.info(
"Initializing the code provider ("
+ codeProviderConfig.getName()
+ ") with class ("
+ codeProviderConfig.getClassName()
+ ")");
Class<?> clazz =
Thread.currentThread()
.getContextClassLoader()
.loadClass(codeProviderConfig.getClassName());
Constructor<?> constructor;
try {
constructor = clazz.getConstructor(CodeProviderConfig.class);
} catch (NoSuchMethodException e) {
constructor = null;
}
if (constructor != null) {
// Create an instance of the code provider
ICodeProvider codeProvider = (ICodeProvider) constructor.newInstance(codeProviderConfig);
// Perform dependency injection on the code provider
applicationContext.getAutowireCapableBeanFactory().autowireBean(codeProvider);
codeProviders.add(codeProvider);
} else {
logger.error(
"Failed to register the code provider ("
+ codeProviderConfig.getClassName()
+ "): The code provider class does not provide a constructor with the required "
+ "signature");
}
} catch (Throwable e) {
logger.error(
"Failed to initialize the code provider ("
+ codeProviderConfig.getName()
+ ") with class ("
+ codeProviderConfig.getClassName()
+ ")",
e);
}
}
}
/**
* Read the code provider configurations from all the <i>META-INF/code-providers.xml</i>
* configuration files that can be found on the classpath.
*/
private void readCodeProviderConfigurations() throws ServiceUnavailableException {
try {
codeProviderConfigs = new ArrayList<>();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Load the code provider configuration files from the classpath
Enumeration<URL> codeProviderConfigurationFiles =
classLoader.getResources(CODE_PROVIDERS_CONFIGURATION_PATH);
while (codeProviderConfigurationFiles.hasMoreElements()) {
URL codeProviderConfigurationFile = codeProviderConfigurationFiles.nextElement();
if (logger.isDebugEnabled()) {
logger.debug(
"Reading the code provider configuration file ("
+ codeProviderConfigurationFile.toURI().toString()
+ ")");
}
// Retrieve a document builder instance using the factory
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setValidating(true);
// builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
builder.setEntityResolver(
new DtdJarResolver("code-providers.dtd", "META-INF/code-providers.dtd"));
builder.setErrorHandler(new XmlParserErrorHandler());
// Parse the code providers configuration file using the document builder
InputSource inputSource = new InputSource(codeProviderConfigurationFile.openStream());
Document document = builder.parse(inputSource);
Element rootElement = document.getDocumentElement();
List<Element> codeProviderElements = XmlUtil.getChildElements(rootElement, "codeProvider");
for (Element codeProviderElement : codeProviderElements) {
// Read the handler configuration
Optional<String> nameOptional = XmlUtil.getChildElementText(codeProviderElement, "name");
Optional<String> classNameOptional =
XmlUtil.getChildElementText(codeProviderElement, "class");
if (nameOptional.isPresent() && classNameOptional.isPresent()) {
CodeProviderConfig codeProviderConfig =
new CodeProviderConfig(nameOptional.get(), classNameOptional.get());
codeProviderConfigs.add(codeProviderConfig);
}
}
}
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to read the code provider configuration files", e);
}
}
private void validateCode(Code code) throws InvalidArgumentException {
if (code == null) {
throw new InvalidArgumentException("code");
}
Set<ConstraintViolation<Code>> constraintViolations = validator.validate(code);
if (!constraintViolations.isEmpty()) {
throw new InvalidArgumentException(
"code", ValidationError.toValidationErrors(constraintViolations));
}
}
private void validateCodeCategory(CodeCategory codeCategory) throws InvalidArgumentException {
if (codeCategory == null) {
throw new InvalidArgumentException("codeCategory");
}
Set<ConstraintViolation<CodeCategory>> constraintViolations = validator.validate(codeCategory);
if (!constraintViolations.isEmpty()) {
throw new InvalidArgumentException(
"codeCategory", ValidationError.toValidationErrors(constraintViolations));
}
}
}
|
0
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/DuplicateCodeCategoryException.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.codes;
import africa.absa.inception.core.service.Problem;
import africa.absa.inception.core.service.ServiceException;
/**
* The <b>DuplicateCodeCategoryException</b> exception is thrown to indicate an error condition as a
* result of an attempt to create a duplicate code category i.e a code category 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/codes/duplicate-code-category",
title = "A code category with the specified ID already exists.",
status = 409)
public class DuplicateCodeCategoryException extends ServiceException {
private static final long serialVersionUID = 1000000;
/**
* Constructs a new <b>DuplicateCodeCategoryException</b>.
*
* @param codeCategoryId the ID for the code category
*/
public DuplicateCodeCategoryException(String codeCategoryId) {
super("The code category with ID (" + codeCategoryId + ") already exists");
}
}
|
0
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/DuplicateCodeException.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.codes;
import africa.absa.inception.core.service.Problem;
import africa.absa.inception.core.service.ServiceException;
/**
* The <b>DuplicateCodeException</b> exception is thrown to indicate an error condition as a result
* of an attempt to create a duplicate code i.e a code with the specified ID already exists for the
* code category.
*
* <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/codes/duplicate-code",
title = "A code with the specified ID already exists for the code category.",
status = 409)
public class DuplicateCodeException extends ServiceException {
private static final long serialVersionUID = 1000000;
/**
* Constructs a new <b>DuplicateCodeException</b>.
*
* @param codeCategoryId the ID for the code category the code is associated with
* @param codeId the ID for the code
*/
public DuplicateCodeException(String codeCategoryId, String codeId) {
super(
"The code with ID ("
+ codeId
+ ") already exists for the code category with ID ("
+ codeCategoryId
+ ")");
}
}
|
0
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/ICodeProvider.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.codes;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
/**
* The <b>ICodeProvider</b> interface defines the interface that must be implemented by all custom
* code providers.
*
* @author Marcus Portmann
*/
public interface ICodeProvider {
/**
* Returns whether the code provider supports the code category.
*
* @param codeCategoryId the ID for the code category
* @return <b>true</b> if the code provider supports the code category or <b>false</b> otherwise
* @throws CodeProviderException if the check for the existing code category failed
*/
boolean codeCategoryExists(String codeCategoryId) throws CodeProviderException;
/**
* Check whether the code exists.
*
* @param codeCategoryId the ID for the code category
* @param codeId the ID for the code
* @return <b>true</b> if the code exists or <b>false</b> otherwise
* @throws CodeProviderException if the check for the existing code failed
*/
boolean codeExists(String codeCategoryId, String codeId) throws CodeProviderException;
/**
* Retrieve the code.
*
* @param codeCategoryId the ID for the code category
* @param codeId the ID for the code
* @return the code
* @throws CodeNotFoundException if the code could not be found
* @throws CodeProviderException if the code could not be retrieved
*/
Code getCode(String codeCategoryId, String codeId)
throws CodeNotFoundException, CodeProviderException;
/**
* Returns all the code categories for the code provider.
*
* @return the code categories for the code provider
* @throws CodeProviderException if the code categories could not be retrieved
*/
List<CodeCategory> getCodeCategories() throws CodeProviderException;
/**
* Retrieve the code category.
*
* @param codeCategoryId the ID for the code category
* @return the code category
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws CodeProviderException if the code category could not be retrieved
*/
CodeCategory getCodeCategory(String codeCategoryId)
throws CodeCategoryNotFoundException, CodeProviderException;
/**
* Retrieve the XML or JSON data for the code category.
*
* <p>This will also attempt to retrieve the data from the appropriate code provider that has been
* registered with the Codes Service in the <b>META-INF/code-providers.xml</b> configuration file.
*
* @param codeCategoryId the ID for the code category
* @return the XML or JSON data for the code category
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws CodeProviderException if the code category data could not be retrieved
*/
String getCodeCategoryData(String codeCategoryId)
throws CodeCategoryNotFoundException, CodeProviderException;
/**
* Retrieve the XML or JSON data for the code category using the specified parameters.
*
* <p>This will also attempt to retrieve the data from the appropriate code provider that has been
* registered with the Codes Service in the <b>META-INF/code-providers.xml</b> configuration file.
*
* @param codeCategoryId the ID for the code category
* @param parameters the parameters
* @return the XML or JSON data for the code category
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws CodeProviderException if the code category data could not be retrieved
*/
String getCodeCategoryDataWithParameters(String codeCategoryId, Map<String, String> parameters)
throws CodeCategoryNotFoundException, CodeProviderException;
/**
* Returns the date and time the code category was last updated.
*
* @param codeCategoryId the ID for the code category
* @return the date and time the code category was last updated
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws CodeProviderException if the date and time the code category was last updated could not
* be retrieved
*/
LocalDateTime getCodeCategoryLastUpdated(String codeCategoryId)
throws CodeCategoryNotFoundException, CodeProviderException;
/**
* Retrieve the name of the code category.
*
* @param codeCategoryId the ID for the code category
* @return the name of the code category
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws CodeProviderException if the name of the code category could not be retrieved
*/
String getCodeCategoryName(String codeCategoryId)
throws CodeCategoryNotFoundException, CodeProviderException;
/**
* Retrieve the name of the code.
*
* @param codeCategoryId the ID for the code category
* @param codeId the ID for the code
* @return the name of code
* @throws CodeNotFoundException if the code could not be found
* @throws CodeProviderException if the name of the code could not be retrieved
*/
String getCodeName(String codeCategoryId, String codeId)
throws CodeNotFoundException, CodeProviderException;
/**
* Retrieve the codes for the code category.
*
* <p>This will also attempt to retrieve the codes from the appropriate code provider that has
* been registered with the Codes Service in the <b>META-INF/code-providers.xml</b> configuration
* file.
*
* @param codeCategoryId the ID for the code category
* @return the codes for the code category
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws CodeProviderException if the codes for the code category could not be retrieved
*/
List<Code> getCodesForCodeCategory(String codeCategoryId)
throws CodeCategoryNotFoundException, CodeProviderException;
/**
* Retrieve the codes for the code category using the specified parameters.
*
* <p>This will also attempt to retrieve the codes from the appropriate code provider that has
* been registered with the Codes Service in the <b>META-INF/code-providers.xml</b> configuration
* file.
*
* @param codeCategoryId the ID for the code category
* @param parameters the parameters
* @return the codes for the code category
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws CodeProviderException if the codes for the code category could not be retrieved
*/
List<Code> getCodesForCodeCategoryWithParameters(
String codeCategoryId, Map<String, String> parameters)
throws CodeCategoryNotFoundException, CodeProviderException;
}
|
0
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-codes/1.2.0/africa/absa/inception/codes/ICodesService.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.codes;
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>ICodesService</b> interface defines the functionality provided by a Codes Service
* implementation.
*
* @author Marcus Portmann
*/
public interface ICodesService {
/**
* Check whether the code category exists.
*
* @param codeCategoryId the ID for the code category
* @return <b>true</b> if the code category exists or <b>false</b> otherwise
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the check for the existing code category failed
*/
boolean codeCategoryExists(String codeCategoryId)
throws InvalidArgumentException, ServiceUnavailableException;
/**
* Check whether the code exists.
*
* @param codeCategoryId the ID for the code category the code is associated with
* @param codeId the ID for the code
* @return <b>true</b> if the code exists or <b>false</b> otherwise
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the check for the existing code failed
*/
boolean codeExists(String codeCategoryId, String codeId)
throws InvalidArgumentException, ServiceUnavailableException;
/**
* Create the new code.
*
* @param code the <b>Code</b> instance containing the information for the new code
* @throws InvalidArgumentException if an argument is invalid
* @throws DuplicateCodeException if the code already exists
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code could not be created
*/
void createCode(Code code)
throws InvalidArgumentException, DuplicateCodeException, CodeCategoryNotFoundException,
ServiceUnavailableException;
/**
* Create the new code category.
*
* @param codeCategory the <b>CodeCategory</b> instance containing the information for the new
* code category
* @throws InvalidArgumentException if an argument is invalid
* @throws DuplicateCodeCategoryException if the code category already exists
* @throws ServiceUnavailableException if the code category could not be created
*/
void createCodeCategory(CodeCategory codeCategory)
throws InvalidArgumentException, DuplicateCodeCategoryException, ServiceUnavailableException;
/**
* Delete the code.
*
* @param codeCategoryId the ID for the code category the code is associated with
* @param codeId the ID for the code
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeNotFoundException if the code could not be found
* @throws ServiceUnavailableException if the code could not be deleted
*/
void deleteCode(String codeCategoryId, String codeId)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException;
/**
* Delete the code category.
*
* @param codeCategoryId the ID for the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code category could not be deleted
*/
void deleteCodeCategory(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException;
/**
* Retrieve the code.
*
* @param codeCategoryId the ID for the code category the code is associated with
* @param codeId the ID for the code
* @return the code
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeNotFoundException if the code could not be found
* @throws ServiceUnavailableException if the code could not be retrieved
*/
Code getCode(String codeCategoryId, String codeId)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException;
/**
* Retrieve all the code categories.
*
* @return the code categories
* @throws ServiceUnavailableException if the code categories could not be retrieved
*/
List<CodeCategory> getCodeCategories() throws ServiceUnavailableException;
/**
* Retrieve the code category.
*
* @param codeCategoryId the ID for the code category
* @return the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code category could not be retrieved
*/
CodeCategory getCodeCategory(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException;
/**
* Retrieve the XML or JSON data for the code category.
*
* <p>This will also attempt to retrieve the data from the appropriate code provider that has been
* registered with the Codes Service in the <b>META-INF/code-providers.xml</b> configuration file.
*
* @param codeCategoryId the ID for the code category
* @return the XML or JSON data for the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code category data could not be retrieved
*/
String getCodeCategoryData(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException;
/**
* Retrieve the XML or JSON data for the code category using the specified parameters.
*
* <p>This will also attempt to retrieve the data from the appropriate code provider that has been
* registered with the Codes Service in the <b>META-INF/code-providers.xml</b> configuration file.
*
* @param codeCategoryId the ID for the code category
* @param parameters the parameters
* @return the XML or JSON data for the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code category data could not be retrieved
*/
String getCodeCategoryDataWithParameters(String codeCategoryId, Map<String, String> parameters)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException;
/**
* Retrieve the name of the code category.
*
* @param codeCategoryId the ID for the code category
* @return the name of the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the name of the code category could not be retrieved
*/
String getCodeCategoryName(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException;
/**
* Retrieve the summaries for all the code categories.
*
* @return the summaries for the code categories
* @throws ServiceUnavailableException if the code category summaries could not be retrieved
*/
List<CodeCategorySummary> getCodeCategorySummaries() throws ServiceUnavailableException;
/**
* Returns the date and time the code category was last updated.
*
* @param codeCategoryId the ID for the code category
* @return the date and time the code category was last updated
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the date and time the code category was last updated
* could not be retrieved
*/
LocalDateTime getCodeCategoryUpdated(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException;
/**
* Retrieve the name of the code.
*
* @param codeCategoryId the ID for the code category the code is associated with
* @param codeId the ID for the code
* @return the name of the code
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeNotFoundException if the code could not be found
* @throws ServiceUnavailableException if the name of the code could not be retrieved
*/
String getCodeName(String codeCategoryId, String codeId)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException;
/**
* Retrieve the codes for the code category.
*
* <p>This will also attempt to retrieve the codes from the appropriate code provider that has
* been registered with the Codes Service in the <b>META-INF/code-providers.xml</b> configuration
* file.
*
* @param codeCategoryId the ID for the code category
* @return the codes for the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the codes for the code category could not be retrieved
*/
List<Code> getCodesForCodeCategory(String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException;
/**
* Retrieve the codes for the code category using the specified parameters.
*
* <p>This will also attempt to retrieve the codes from the appropriate code provider that has
* been registered with the Codes Service in the <b>META-INF/code-providers.xml</b> configuration
* file.
*
* @param codeCategoryId the ID for the code category
* @param parameters the parameters
* @return the codes for the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the codes for the code category could not be retrieved
*/
List<Code> getCodesForCodeCategoryWithParameters(
String codeCategoryId, Map<String, String> parameters)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException;
/**
* Update the existing code.
*
* @param code the <b>Code</b> instance containing the updated information for the code
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeNotFoundException if the code could not be found
* @throws ServiceUnavailableException if the code could not be updated
*/
void updateCode(Code code)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException;
/**
* Update the existing code category.
*
* @param codeCategory the <b>CodeCategory</b> instance containing the updated information for the
* code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code category could not be updated
*/
void updateCodeCategory(CodeCategory codeCategory)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException;
/**
* Update the XML or JSON data for the code category.
*
* @param codeCategoryId the ID for the code category
* @param data the updated XML or JSON data
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code category data could not be updated
*/
void updateCodeCategoryData(String codeCategoryId, String data)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException;
}
|
0
|
java-sources/africa/absa/inception-codes-api/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-codes-api/1.2.0/africa/absa/inception/codes/CodesApi.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.codes;
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.util.ISO8601Util;
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.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>CodesApi</b> class.
*
* @author Marcus Portmann
*/
@Tag(name = "Codes")
@RestController
@RequestMapping(value = "/api/codes")
@CrossOrigin
@SuppressWarnings({"unused"})
// @el (isSecurityDisabled: africa.absa.inception.api.ApiSecurityExpressionRoot.isSecurityEnabled)
public class CodesApi extends SecureApi {
/** The Codes Service. */
private final ICodesService codesService;
/**
* Constructs a new <b>CodesRestController</b>.
*
* @param applicationContext the Spring application context
* @param codesService the Codes Service
*/
public CodesApi(ApplicationContext applicationContext, ICodesService codesService) {
super(applicationContext);
this.codesService = codesService;
}
/**
* Create the new code.
*
* @param codeCategoryId the ID for the code category
* @param code the code to create
* @throws InvalidArgumentException if an argument is invalid
* @throws DuplicateCodeException if the code already exists
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code could not be created
*/
@Operation(summary = "Create the code", description = "Create the code")
@ApiResponses(
value = {
@ApiResponse(responseCode = "204", description = "The code 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 code with the specified ID already exists",
content =
@Content(
mediaType = "application/problem+json",
schema = @Schema(implementation = ProblemDetails.class))),
@ApiResponse(
responseCode = "404",
description = "The code category 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 = "/code-categories/{codeCategoryId}/codes",
method = RequestMethod.POST,
produces = "application/json")
@ResponseStatus(HttpStatus.NO_CONTENT)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public void createCode(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category",
required = true)
@PathVariable
String codeCategoryId,
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "The code to create",
required = true)
@RequestBody
Code code)
throws InvalidArgumentException, DuplicateCodeException, CodeCategoryNotFoundException,
ServiceUnavailableException {
if (code == null) {
throw new InvalidArgumentException("code");
}
if (!code.getCodeCategoryId().equals(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
codesService.createCode(code);
}
/**
* Create the code category.
*
* @param codeCategory the code category to create
* @throws InvalidArgumentException if an argument is invalid
* @throws DuplicateCodeCategoryException if the code category already exists
* @throws ServiceUnavailableException if the code category could not be created
*/
@Operation(summary = "Create the code category", description = "Create the code category")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "204",
description = "The code category 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 code category 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 = "/code-categories",
method = RequestMethod.POST,
produces = "application/json")
@ResponseStatus(HttpStatus.NO_CONTENT)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public void createCodeCategory(
@RequestBody
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "The code category to create",
required = true)
CodeCategory codeCategory)
throws InvalidArgumentException, DuplicateCodeCategoryException, ServiceUnavailableException {
codesService.createCodeCategory(codeCategory);
}
/**
* Delete the code.
*
* @param codeCategoryId the ID for the code category
* @param codeId the ID for the code
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeNotFoundException if the code could not be found
* @throws ServiceUnavailableException if the code could not be deleted
*/
@Operation(summary = "Delete the code", description = "Delete the code")
@ApiResponses(
value = {
@ApiResponse(responseCode = "204", description = "The code 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 code 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 = "/code-categories/{codeCategoryId}/codes/{codeId}",
method = RequestMethod.DELETE,
produces = "application/json")
@ResponseStatus(HttpStatus.NO_CONTENT)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public void deleteCode(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category",
required = true)
@PathVariable
String codeCategoryId,
@Parameter(name = "codeId", description = "The ID for the code", required = true)
@PathVariable
String codeId)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException {
codesService.deleteCode(codeCategoryId, codeId);
}
/**
* Delete the code category.
*
* @param codeCategoryId the ID for the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code category could not be deleted
*/
@Operation(summary = "Delete the code category", description = "Delete the code category")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "204",
description = "The code category 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 code category 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 = "/code-categories/{codeCategoryId}",
method = RequestMethod.DELETE,
produces = "application/json")
@ResponseStatus(HttpStatus.NO_CONTENT)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public void deleteCodeCategory(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category",
required = true)
@PathVariable
String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
codesService.deleteCodeCategory(codeCategoryId);
}
/**
* Retrieve the code
*
* @param codeCategoryId the ID for the code category the code is associated with
* @param codeId the ID for the code
* @return the code
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeNotFoundException if the code could not be found
* @throws ServiceUnavailableException if the code could not be retrieved
*/
@Operation(summary = "Retrieve the code", description = "Retrieve the code")
@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 code 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 = "/code-categories/{codeCategoryId}/codes/{codeId}",
method = RequestMethod.GET,
produces = "application/json")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public Code getCode(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category the code is associated with",
required = true)
@PathVariable
String codeCategoryId,
@Parameter(name = "codeId", description = "The ID for the code", required = true)
@PathVariable
String codeId)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException {
return codesService.getCode(codeCategoryId, codeId);
}
/**
* Retrieve all the code categories.
*
* @return the code categories
* @throws ServiceUnavailableException if the code categories could not be retrieved
*/
@Operation(summary = "Retrieve the code categories", description = "Retrieve the code categories")
@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 = "/code-categories",
method = RequestMethod.GET,
produces = "application/json")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public List<CodeCategory> getCodeCategories() throws ServiceUnavailableException {
return codesService.getCodeCategories();
}
/**
* Retrieve the code category
*
* @param codeCategoryId the ID for the code category
* @return the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code category could not be retrieved
*/
@Operation(summary = "Retrieve the code category", description = "Retrieve the code category")
@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 code category 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 = "/code-categories/{codeCategoryId}",
method = RequestMethod.GET,
produces = "application/json")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public CodeCategory getCodeCategory(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category",
required = true)
@PathVariable
String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
return codesService.getCodeCategory(codeCategoryId);
}
/**
* Retrieve the XML or JSON data for a code category
*
* @param codeCategoryId the ID for the code category
* @return the XML or JSON data for the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code category data could not be retrieved
*/
@Operation(
summary = "Retrieve the XML or JSON data for a code category",
description = "Retrieve the XML or JSON data for a code category")
@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 code category 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 = "/code-categories/{codeCategoryId}/data",
method = RequestMethod.GET,
produces = "application/json")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public String getCodeCategoryData(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category",
required = true)
@PathVariable
String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
String data = codesService.getCodeCategoryData(codeCategoryId);
return ApiUtil.quote(StringUtils.hasText(data) ? data : "");
}
/**
* Retrieve the name of the code category.
*
* @param codeCategoryId the ID for the code category
* @return the name of the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the name of the code category could not be retrieved
*/
@Operation(
summary = "Retrieve the name of the code category",
description = "Retrieve the name of the code category")
@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 code category 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 = "/code-categories/{codeCategoryId}/name",
method = RequestMethod.GET,
produces = "application/json")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public String getCodeCategoryName(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category",
required = true)
@PathVariable
String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
return ApiUtil.quote(codesService.getCodeCategoryName(codeCategoryId));
}
/**
* Retrieve the summaries for all the code categories.
*
* @return the summaries for the code categories
* @throws ServiceUnavailableException if the code category summaries could not be retrieved
*/
@Operation(
summary = "Retrieve the code category summaries",
description = "Retrieve the code category 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 = "/code-category-summaries",
method = RequestMethod.GET,
produces = "application/json")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public List<CodeCategorySummary> getCodeCategorySummaries() throws ServiceUnavailableException {
return codesService.getCodeCategorySummaries();
}
/**
* Returns the date and time the code category was last updated.
*
* @param codeCategoryId the ID for the code category
* @return the date and time the code category was last updated
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the date and time the code category was last updated
* could not be retrieved
*/
@Operation(
summary = "Retrieve the date and time the code category was last updated",
description = "Retrieve the date and time the code category was last updated")
@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 code category 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 = "/code-categories/{codeCategoryId}/updated",
method = RequestMethod.GET,
produces = "application/json")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public String getCodeCategoryUpdated(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category",
required = true)
@PathVariable
String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
return ApiUtil.quote(
ISO8601Util.fromLocalDateTime(codesService.getCodeCategoryUpdated(codeCategoryId)));
}
/**
* Retrieve the name of the code.
*
* @param codeCategoryId the ID for the code category the code is associated with
* @param codeId the ID for the code
* @return the name of the code
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeNotFoundException if the code could not be found
* @throws ServiceUnavailableException if the name of the code could not be retrieved
*/
@Operation(
summary = "Retrieve the name of the code",
description = "Retrieve the name of the code")
@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 code 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 = "/code-categories/{codeCategoryId}/codes/{codeId}/name",
method = RequestMethod.GET,
produces = "application/json")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public String getCodeName(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category the code is associated with",
required = true)
@PathVariable
String codeCategoryId,
@Parameter(name = "codeId", description = "The ID for the code", required = true)
@PathVariable
String codeId)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException {
return ApiUtil.quote(codesService.getCodeName(codeCategoryId, codeId));
}
/**
* Retrieve the codes for a code category
*
* @param codeCategoryId the ID for the code category
* @return the codes for the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the codes for the code category could not be retrieved
*/
@Operation(
summary = "Retrieve the codes for a code category",
description = "Retrieve the codes for a code category")
@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 code category 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 = "/code-categories/{codeCategoryId}/codes",
method = RequestMethod.GET,
produces = "application/json")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public List<Code> getCodesForCodeCategory(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category",
required = true)
@PathVariable
String codeCategoryId)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
return codesService.getCodesForCodeCategory(codeCategoryId);
}
/**
* Update the code.
*
* @param codeCategoryId the ID for the code category
* @param codeId the ID for the code
* @param code the code to create
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeNotFoundException if the code could not be found
* @throws ServiceUnavailableException if the code could not be updated
*/
@Operation(summary = "Update the code", description = "Update the code")
@ApiResponses(
value = {
@ApiResponse(responseCode = "204", description = "The code 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 code 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 = "/code-categories/{codeCategoryId}/codes/{codeId}",
method = RequestMethod.PUT,
produces = "application/json")
@ResponseStatus(HttpStatus.NO_CONTENT)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public void updateCode(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category",
required = true)
@PathVariable
String codeCategoryId,
@Parameter(name = "codeId", description = "The ID for the code", required = true)
@PathVariable
String codeId,
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "The code to update",
required = true)
@RequestBody
Code code)
throws InvalidArgumentException, CodeNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
if (!StringUtils.hasText(codeId)) {
throw new InvalidArgumentException("codeId");
}
if (code == null) {
throw new InvalidArgumentException("code");
}
if (!codeCategoryId.equals(code.getCodeCategoryId())) {
throw new InvalidArgumentException("code");
}
if (!codeId.equals(code.getId())) {
throw new InvalidArgumentException("code");
}
codesService.updateCode(code);
}
/**
* Update the code category.
*
* @param codeCategoryId the ID for the code category
* @param codeCategory the code category
* @throws InvalidArgumentException if an argument is invalid
* @throws CodeCategoryNotFoundException if the code category could not be found
* @throws ServiceUnavailableException if the code category could not be updated
*/
@Operation(summary = "Update the code category", description = "Update the code category")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "204",
description = "The code category 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 code category 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 = "/code-categories/{codeCategoryId}",
method = RequestMethod.PUT,
produces = "application/json")
@ResponseStatus(HttpStatus.NO_CONTENT)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Codes.CodeAdministration')")
public void updateCodeCategory(
@Parameter(
name = "codeCategoryId",
description = "The ID for the code category",
required = true)
@PathVariable
String codeCategoryId,
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "The code category to update",
required = true)
@RequestBody
CodeCategory codeCategory)
throws InvalidArgumentException, CodeCategoryNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(codeCategoryId)) {
throw new InvalidArgumentException("codeCategoryId");
}
if (codeCategory == null) {
throw new InvalidArgumentException("codeCategory");
}
if (!codeCategoryId.equals(codeCategory.getId())) {
throw new InvalidArgumentException("codeCategory");
}
codesService.updateCodeCategory(codeCategory);
}
}
|
0
|
java-sources/africa/absa/inception-codes-api/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-codes-api/1.2.0/africa/absa/inception/codes/CodesApiConfiguration.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.codes;
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>CodesApiConfiguration</b> class provides the Spring configuration for the Codes API
* module.
*
* @author Marcus Portmann
*/
@Configuration
public class CodesApiConfiguration {
/**
* Returns the grouped Open API for the Codes API.
*
* @return the grouped Open API for the Codes API
*/
@Bean
public GroupedOpenApi codesOpenApi() {
return GroupedOpenApi.builder()
.group("codes")
.packagesToScan("africa.absa.inception.codes")
.addOpenApiCustomiser(
openApi -> openApi.info(new Info().title("Codes API").version(Version.PROJECT_VERSION)))
.build();
}
}
|
0
|
java-sources/africa/absa/inception-codes-api/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-codes-api/1.2.0/africa/absa/inception/codes/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.codes;
/**
* 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-config/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception/config/Config.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.config;
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>Config</b> class stores the key, value and description for the config.
*
* @author Marcus Portmann
*/
@Schema(description = "A config")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"key", "value", "description"})
@Entity
@Table(schema = "config", name = "config")
public class Config implements Serializable {
private static final long serialVersionUID = 1000000;
/** The date and time the config was created. */
@JsonIgnore
@Column(name = "created", nullable = false, updatable = false)
private LocalDateTime created;
/** The description for the config. */
@Schema(description = "The description for the config", required = true)
@JsonProperty(required = true)
@NotNull
@Size(max = 100)
@Column(name = "description", length = 100, nullable = false)
private String description;
/** The key for the config. */
@Schema(description = "The key for the config", required = true)
@JsonProperty(required = true)
@NotNull
@Size(min = 1, max = 100)
@Id
@Column(name = "key", length = 100, nullable = false)
private String key;
/** The date and time the config was last updated. */
@JsonIgnore
@Column(name = "updated", insertable = false)
private LocalDateTime updated;
/** The value for the config. */
@Schema(description = "The value for the config", required = true)
@JsonProperty(required = true)
@NotNull
@Size(max = 4000)
@Column(name = "value", length = 4000, nullable = false)
private String value;
/** Constructs a new <b>Config</b>. */
public Config() {}
/**
* Constructs a new <b>Config</b>.
*
* @param key the key for the config
* @param value the value for the config
* @param description the description for the config
*/
Config(String key, String value, String description) {
this.key = key;
this.value = value;
this.description = description;
}
/**
* 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;
}
Config other = (Config) object;
return Objects.equals(key, other.key);
}
/**
* Returns the date and time the config was created.
*
* @return the date and time the config was created
*/
public LocalDateTime getCreated() {
return created;
}
/**
* Returns the description for the config.
*
* @return the description for the config
*/
public String getDescription() {
return description;
}
/**
* Returns the key for the config.
*
* @return the key for the config
*/
public String getKey() {
return key;
}
/**
* Returns the date and time the config was last updated.
*
* @return the date and time the config was last updated
*/
public LocalDateTime getUpdated() {
return updated;
}
/**
* Returns the value for the config.
*
* @return the value for the config
*/
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 (key == null) ? 0 : key.hashCode();
}
/**
* Set the description for the config.
*
* @param description the description for the config
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Set the key for the config.
*
* @param key the key for the config
*/
public void setKey(String key) {
this.key = key;
}
/**
* Set the value for the config.
*
* @param value the value for the config
*/
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-config/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception/config/ConfigConfiguration.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.config;
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>ConfigConfig</b> class provides the Spring configuration for the Config module.
*
* @author Marcus Portmann
*/
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "configEntityManagerFactory",
basePackages = {"africa.absa.inception.config"})
public class ConfigConfiguration {
/** The Spring application context. */
private final ApplicationContext applicationContext;
/**
* Constructs a new <b>ConfigConfiguration</b>.
*
* @param applicationContext the Spring application context
*/
public ConfigConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* Returns the config entity manager factory bean associated with the application data source.
*
* @param dataSource the application data source
* @param platformTransactionManager the platform transaction manager
* @return the config entity manager factory bean associated with the application data source
*/
@Bean
public LocalContainerEntityManagerFactoryBean configEntityManagerFactory(
@Qualifier("applicationDataSource") DataSource dataSource,
PlatformTransactionManager platformTransactionManager) {
return JpaUtil.createEntityManager(
"config", dataSource, platformTransactionManager, "africa.absa.inception.config");
}
}
|
0
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception/config/ConfigNotFoundException.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.config;
import africa.absa.inception.core.service.Problem;
import africa.absa.inception.core.service.ServiceException;
/**
* The <b>ConfigNotFoundException</b> exception is thrown to indicate that the required config could
* not be found when working with the Config Service.
*
* <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/config/config-not-found",
title = "The config could not be found.",
status = 404)
public class ConfigNotFoundException extends ServiceException {
private static final long serialVersionUID = 1000000;
/**
* Constructs a new <b>ConfigNotFoundException</b>.
*
* @param key the key for the config
*/
public ConfigNotFoundException(String key) {
super("The config (" + key + ") could not be found");
}
}
|
0
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception/config/ConfigRepository.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.config;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
/**
* The <b>ConfigRepository</b> interface declares the repository for the <b> Config</b> domain type.
*
* @author Marcus Portmann
*/
public interface ConfigRepository extends JpaRepository<Config, String> {
/**
* Delete the config with the specified key.
*
* @param key the key for the config
*/
void deleteByKeyIgnoreCase(String key);
/**
* Check whether the config exists.
*
* @param key the key for the config
* @return <b>true</b> if the config exists or <b>false</b> otherwise
*/
boolean existsByKeyIgnoreCase(String key);
/**
* Retrieve all the configs ordered by key descending.
*
* @return all the configs ordered by key descending
*/
List<Config> findAllByOrderByKeyDesc();
/**
* Retrieve the config.
*
* @param key the key for the config
* @return an Optional containing the config or an empty Optional if the config could not be found
*/
Optional<Config> findByKeyIgnoreCase(String key);
/**
* Retrieve the filtered configs.
*
* @param filter the filter to apply to the keys for the configs
* @return the filtered configs
*/
List<Config> findByKeyIgnoreCaseContaining(String filter);
/**
* Retrieve the value for the config.
*
* @param key the key for the config
* @return an Optional containing the value for the config or an empty Optional if the config
* could not be found
*/
@Query("select c.value from Config c where lower(c.key) = lower(:key)")
Optional<String> getValueByKeyIgnoreCase(@Param("key") String key);
}
|
0
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception/config/ConfigService.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.config;
import africa.absa.inception.core.service.InvalidArgumentException;
import africa.absa.inception.core.service.ServiceUnavailableException;
import africa.absa.inception.core.service.ValidationError;
import africa.absa.inception.core.util.Base64Util;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
/**
* The <b>ConfigService</b> class provides the Config Service implementation.
*
* @author Marcus Portmann
*/
@Service
@SuppressWarnings("unused")
public class ConfigService implements IConfigService {
/** The Config Repository. */
private final ConfigRepository configRepository;
/** The Config Summary Repository. */
private final ConfigSummaryRepository configSummaryRepository;
/** The JSR-303 validator. */
private final Validator validator;
/**
* Constructs a new <b>ConfigService</b>.
*
* @param validator the JSR-303 validator
* @param configRepository the Config Repository
* @param configSummaryRepository the Config Summary Repository
*/
public ConfigService(
Validator validator,
ConfigRepository configRepository,
ConfigSummaryRepository configSummaryRepository) {
this.validator = validator;
this.configRepository = configRepository;
this.configSummaryRepository = configSummaryRepository;
}
@Override
@Transactional
public void deleteConfig(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
if (!configRepository.existsByKeyIgnoreCase(key)) {
throw new ConfigNotFoundException(key);
}
configRepository.deleteByKeyIgnoreCase(key);
} catch (ConfigNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to delete the config with the key (" + key + ")", e);
}
}
@Override
public byte[] getBinary(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
if (valueOptional.isPresent()) {
return Base64Util.decode(valueOptional.get());
} else {
throw new ConfigNotFoundException(key);
}
} catch (ConfigNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the binary config with the key (" + key + ")", e);
}
}
@Override
public byte[] getBinary(String key, byte[] defaultValue)
throws InvalidArgumentException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
return valueOptional.map(Base64Util::decode).orElse(defaultValue);
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the binary config with the key (" + key + ")", e);
}
}
@Override
public boolean getBoolean(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
if (valueOptional.isPresent()) {
return Boolean.parseBoolean(valueOptional.get());
} else {
throw new ConfigNotFoundException(key);
}
} catch (ConfigNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the Boolean config with the key (" + key + ")", e);
}
}
@Override
public boolean getBoolean(String key, boolean defaultValue)
throws InvalidArgumentException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
return valueOptional.map(Boolean::parseBoolean).orElse(defaultValue);
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the Boolean config with the key (" + key + ")", e);
}
}
@Override
public Config getConfig(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<Config> configOptional = configRepository.findByKeyIgnoreCase(key);
if (configOptional.isEmpty()) {
throw new ConfigNotFoundException(key);
} else {
return configOptional.get();
}
} catch (ConfigNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the config with the key (" + key + ")", e);
}
}
@Override
public List<ConfigSummary> getConfigSummaries() throws ServiceUnavailableException {
try {
return configSummaryRepository.findAllByOrderByKeyDesc();
} catch (Throwable e) {
throw new ServiceUnavailableException("Failed to retrieve the config summaries", e);
}
}
@Override
public List<Config> getConfigs() throws ServiceUnavailableException {
try {
return configRepository.findAllByOrderByKeyDesc();
} catch (Throwable e) {
throw new ServiceUnavailableException("Failed to retrieve the configs", e);
}
}
@Override
public Double getDouble(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
if (valueOptional.isPresent()) {
return Double.parseDouble(valueOptional.get());
} else {
throw new ConfigNotFoundException(key);
}
} catch (ConfigNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the Double config with the key (" + key + ")", e);
}
}
@Override
public double getDouble(String key, double defaultValue)
throws InvalidArgumentException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
return valueOptional.map(Double::parseDouble).orElse(defaultValue);
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the Double config with the key (" + key + ")", e);
}
}
@Override
public List<ConfigSummary> getFilteredConfigSummaries(String filter)
throws ServiceUnavailableException {
try {
if (StringUtils.hasText(filter)) {
return configSummaryRepository.findByKeyIgnoreCaseContaining(filter);
} else {
return configSummaryRepository.findAllByOrderByKeyDesc();
}
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the config summaries matching the filter (" + filter + ")", e);
}
}
@Override
public List<Config> getFilteredConfigs(String filter) throws ServiceUnavailableException {
try {
if (StringUtils.hasText(filter)) {
return configRepository.findByKeyIgnoreCaseContaining(filter);
} else {
return configRepository.findAllByOrderByKeyDesc();
}
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the config matching the filter (" + filter + ")", e);
}
}
@Override
public Integer getInteger(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
if (valueOptional.isPresent()) {
return Integer.parseInt(valueOptional.get());
} else {
throw new ConfigNotFoundException(key);
}
} catch (ConfigNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the Integer config with the key (" + key + ")", e);
}
}
@Override
public int getInteger(String key, int defaultValue)
throws InvalidArgumentException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
return valueOptional.map(Integer::parseInt).orElse(defaultValue);
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the Integer config with the key (" + key + ")", e);
}
}
@Override
public Long getLong(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
if (valueOptional.isPresent()) {
return Long.parseLong(valueOptional.get());
} else {
throw new ConfigNotFoundException(key);
}
} catch (ConfigNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the Long config with the key (" + key + ")", e);
}
}
@Override
public long getLong(String key, long defaultValue)
throws InvalidArgumentException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
return valueOptional.map(Long::parseLong).orElse(defaultValue);
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the Long config with the key (" + key + ")", e);
}
}
@Override
public String getString(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
if (valueOptional.isPresent()) {
return valueOptional.get();
} else {
throw new ConfigNotFoundException(key);
}
} catch (ConfigNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the String config with the key (" + key + ")", e);
}
}
@Override
public String getString(String key, String defaultValue)
throws InvalidArgumentException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
Optional<String> valueOptional = configRepository.getValueByKeyIgnoreCase(key);
return valueOptional.orElse(defaultValue);
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the String config with the key (" + key + ")", e);
}
}
@Override
public boolean keyExists(String key)
throws InvalidArgumentException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
try {
return configRepository.existsByKeyIgnoreCase(key);
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to checked whether the config key (" + key + ") exists", e);
}
}
@Override
@Transactional
public void setConfig(Config config)
throws InvalidArgumentException, ServiceUnavailableException {
if (config == null) {
throw new InvalidArgumentException("config");
}
Set<ConstraintViolation<Config>> constraintViolations = validator.validate(config);
if (!constraintViolations.isEmpty()) {
throw new InvalidArgumentException(
"config", ValidationError.toValidationErrors(constraintViolations));
}
try {
configRepository.saveAndFlush(config);
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to set the config with the key (" + config.getKey() + ")", e);
}
}
@Override
@Transactional
public void setConfig(String key, Object value, String description)
throws InvalidArgumentException, ServiceUnavailableException {
if (!StringUtils.hasText(key)) {
throw new InvalidArgumentException("key");
}
if (value == null) {
throw new InvalidArgumentException("value");
}
if (description == null) {
throw new InvalidArgumentException("description");
}
try {
String stringValue;
if (value instanceof String) {
stringValue = (String) value;
} else if (value instanceof byte[]) {
stringValue = Base64Util.encodeBytes((byte[]) value);
} else {
stringValue = value.toString();
}
configRepository.save(new Config(key, stringValue, description));
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to set the config with the key (" + key + ")", e);
}
}
}
|
0
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception/config/ConfigSummary.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.config;
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>Config</b> class stores the summary for a config.
*
* @author Marcus Portmann
*/
@Schema(description = "A config summary")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"key", "description"})
@Entity
@Table(schema = "config", name = "config")
public class ConfigSummary implements Serializable {
private static final long serialVersionUID = 1000000;
/** The description for the config. */
@Schema(description = "The description for the config", required = true)
@JsonProperty(required = true)
@NotNull
@Size(max = 100)
@Column(name = "description", length = 100, nullable = false)
private String description;
/** The key for the config. */
@Schema(description = "The key for the config", required = true)
@JsonProperty(required = true)
@NotNull
@Size(min = 1, max = 100)
@Id
@Column(name = "key", length = 100, nullable = false)
private String key;
/** Constructs a new <b>ConfigSummary</b>. */
public ConfigSummary() {}
/**
* Constructs a new <b>ConfigSummary</b>.
*
* @param key the key for the config
* @param description the description for the config
*/
ConfigSummary(String key, String description) {
this.key = key;
this.description = description;
}
/**
* 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;
}
ConfigSummary other = (ConfigSummary) object;
return Objects.equals(key, other.key);
}
/**
* Returns the description for the config.
*
* @return the description for the config
*/
public String getDescription() {
return description;
}
/**
* Returns the key for the config.
*
* @return the key for the config
*/
public String getKey() {
return key;
}
/**
* Returns a hash code value for the object.
*
* @return a hash code value for the object
*/
@Override
public int hashCode() {
return (key == null) ? 0 : key.hashCode();
}
}
|
0
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception/config/ConfigSummaryRepository.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.config;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* The <b>ConfigSummaryRepository</b> interface declares the repository for the <b>
* ConfigSummary</b> domain type.
*
* @author Marcus Portmann
*/
public interface ConfigSummaryRepository extends JpaRepository<ConfigSummary, String> {
/**
* Retrieve all the config summaries ordered by key descending.
*
* @return all the config summaries ordered by key descending
*/
List<ConfigSummary> findAllByOrderByKeyDesc();
/**
* Retrieve the filtered config summaries.
*
* @param filter the filter to apply to the keys for the configs
* @return the filtered config summaries
*/
List<ConfigSummary> findByKeyIgnoreCaseContaining(String filter);
}
|
0
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config/1.2.0/africa/absa/inception/config/IConfigService.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.config;
import africa.absa.inception.core.service.InvalidArgumentException;
import africa.absa.inception.core.service.ServiceUnavailableException;
import java.util.List;
/**
* The <b>IConfigService</b> interface defines the functionality provided by a Config Service
* implementation, which manages the config information for an application or service.
*
* @author Marcus Portmann
*/
public interface IConfigService {
/**
* Delete the config with the specified key.
*
* @param key the key for the config
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the config could not be deleted
*/
void deleteConfig(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException;
/**
* Retrieve the binary config.
*
* @param key the key for the config
* @return the binary config
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the binary config value could not be retrieved
*/
byte[] getBinary(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException;
/**
* Retrieve the binary config.
*
* @param key the key for the config
* @param defaultValue the default value to return if the config does not exist
* @return the binary config or the default value if the config does not exist
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the binary config value could not be retrieved
*/
byte[] getBinary(String key, byte[] defaultValue)
throws InvalidArgumentException, ServiceUnavailableException;
/**
* Retrieve the <b>Boolean</b> config.
*
* @param key the key for the config
* @return the <b>Boolean</b> config
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the boolean config value could not be retrieved
*/
boolean getBoolean(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException;
/**
* Retrieve the <b>Boolean</b> config.
*
* @param key the key for the config
* @param defaultValue the default value to return if the config does not exist
* @return the <b>Boolean</b> config or the default value if the config value does not exist
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the boolean config value could not be retrieved
*/
boolean getBoolean(String key, boolean defaultValue)
throws InvalidArgumentException, ServiceUnavailableException;
/**
* Retrieve the config.
*
* @param key the key for the config
* @return the config
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the config could not be retrieved
*/
Config getConfig(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException;
/**
* Retrieve all the config summaries.
*
* @return the config summaries
* @throws ServiceUnavailableException if the config summaries could not be retrieved
*/
List<ConfigSummary> getConfigSummaries() throws ServiceUnavailableException;
/**
* Retrieve all the configs.
*
* @return the configs
* @throws ServiceUnavailableException if the configs could not be retrieved
*/
List<Config> getConfigs() throws ServiceUnavailableException;
/**
* Retrieve the <b>Double</b> config.
*
* @param key the key for the config
* @return the <b>Double</b> config
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the double config value could not be retrieved
*/
Double getDouble(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException;
/**
* Retrieve the <b>Double</b> config.
*
* @param key the key for the config
* @param defaultValue the default value to return if the config does not exist
* @return the <b>Double</b> config or the default value if the config entry does not exist
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the double config value could not be retrieved
*/
double getDouble(String key, double defaultValue)
throws InvalidArgumentException, ServiceUnavailableException;
/**
* Retrieve the filtered config summaries.
*
* @param filter the filter to apply to the keys for the config summaries
* @return the config summaries
* @throws ServiceUnavailableException if the filtered config summaries could not be retrieved
*/
List<ConfigSummary> getFilteredConfigSummaries(String filter) throws ServiceUnavailableException;
/**
* Retrieve the filtered configs.
*
* @param filter the filter to apply to the keys for the config
* @return the configs
* @throws ServiceUnavailableException if the filtered configs could not be retrieved
*/
List<Config> getFilteredConfigs(String filter) throws ServiceUnavailableException;
/**
* Retrieve the <b>Integer</b> config.
*
* @param key the key for the config
* @return the <b>Integer</b> config
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the integer config value could not be retrieved
*/
Integer getInteger(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException;
/**
* Retrieve the <b>Integer</b> config.
*
* @param key the key for the config
* @param defaultValue the default value to return if the config does not exist
* @return the <b>Integer</b> config or the default value if the config entry does not exist
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the integer config value could not be retrieved
*/
int getInteger(String key, int defaultValue)
throws InvalidArgumentException, ServiceUnavailableException;
/**
* Retrieve the <b>Long</b> config.
*
* @param key the key for the config
* @return the <b>Long</b> config
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the long config value could not be retrieved
*/
Long getLong(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException;
/**
* Retrieve the <b>Long</b> config.
*
* @param key the key for the config
* @param defaultValue the default value to return if the config does not exist
* @return the <b>Long</b> config or the default value if the config entry does not exist
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the long config value could not be retrieved
*/
long getLong(String key, long defaultValue)
throws InvalidArgumentException, ServiceUnavailableException;
/**
* Retrieve the value for the <b>String</b> config.
*
* @param key the key for the config
* @return the value for the <b>String</b> config
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the string config value could not be retrieved
*/
String getString(String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException;
/**
* Retrieve the value for the <b>String</b> config.
*
* @param key the key for the config
* @param defaultValue the default value to return if the config does not exist
* @return the value for the <b>String</b> config or the default value if the config does not
* exist
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the string config value could not be retrieved
*/
String getString(String key, String defaultValue)
throws InvalidArgumentException, ServiceUnavailableException;
/**
* Check if a config with the specified key exists.
*
* @param key the key for the config
* @return <b>true</b> if the config with the specified key exists or <b>false</b> otherwise
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the check for the existing key failed
*/
boolean keyExists(String key) throws InvalidArgumentException, ServiceUnavailableException;
/**
* Set the config.
*
* @param config the config
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the config could not be set
*/
void setConfig(Config config) throws InvalidArgumentException, ServiceUnavailableException;
/**
* Set the config key to the specified value.
*
* @param key the key for the config
* @param value the value for the config
* @param description the description for the config
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the config could not be set
*/
void setConfig(String key, Object value, String description)
throws InvalidArgumentException, ServiceUnavailableException;
}
|
0
|
java-sources/africa/absa/inception-config-api/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config-api/1.2.0/africa/absa/inception/config/ConfigApi.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.config;
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.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.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>ConfigApi</b> class.
*
* @author Marcus Portmann
*/
@Tag(name = "Config")
@RestController
@RequestMapping(value = "/api/config")
@CrossOrigin
@SuppressWarnings({"unused"})
// @el (isSecurityDisabled: africa.absa.inception.api.ApiSecurityExpressionRoot.isSecurityEnabled)
public class ConfigApi extends SecureApi {
/** The Config Service. */
private final IConfigService configService;
/**
* Constructs a new <b>ConfigApi</b>.
*
* @param applicationContext the Spring application context
* @param configService the Config Service
*/
public ConfigApi(ApplicationContext applicationContext, IConfigService configService) {
super(applicationContext);
this.configService = configService;
}
/**
* Delete the config.
*
* @param key the key for the config
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the config could not be deleted
*/
@Operation(summary = "Delete the config", description = "Delete the config")
@ApiResponses(
value = {
@ApiResponse(responseCode = "204", description = "The config 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 config 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 = "/configs/{key}",
method = RequestMethod.DELETE,
produces = "application/json")
@ResponseStatus(HttpStatus.NO_CONTENT)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Config.ConfigAdministration')")
public void deleteConfig(
@Parameter(name = "key", description = "The key for the config", required = true)
@PathVariable
String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
configService.deleteConfig(key);
}
/**
* Retrieve the config.
*
* @param key the key for the config
* @return the config
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the config could not be retrieved
*/
@Operation(summary = "Retrieve the config", description = "Retrieve the config")
@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 config 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 = "/configs/{key}",
method = RequestMethod.GET,
produces = "application/json")
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Config.ConfigAdministration')")
public Config getConfig(
@Parameter(name = "key", description = "The key for the config", required = true)
@PathVariable
String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
return configService.getConfig(key);
}
/**
* Retrieve the config value.
*
* @param key the key for the config
* @return the config value
* @throws InvalidArgumentException if an argument is invalid
* @throws ConfigNotFoundException if the config could not be found
* @throws ServiceUnavailableException if the string config value could not be retrieved
*/
@Operation(summary = "Retrieve the config value", description = "Retrieve the config value")
@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 config 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 = "/configs/{key}/value",
method = RequestMethod.GET,
produces = "application/json")
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Config.ConfigAdministration')")
public String getConfigValue(
@Parameter(name = "key", description = "The key for the config", required = true)
@PathVariable
String key)
throws InvalidArgumentException, ConfigNotFoundException, ServiceUnavailableException {
return ApiUtil.quote(configService.getString(key));
}
/**
* Retrieve all the configs.
*
* @return the configs
* @throws ServiceUnavailableException if the configs could not be retrieved
*/
@Operation(summary = "Retrieve all the configs", description = "Retrieve all the configs")
@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 = "/configs", method = RequestMethod.GET, produces = "application/json")
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Config.ConfigAdministration')")
public List<Config> getConfigs() throws ServiceUnavailableException {
return configService.getConfigs();
}
/**
* Set the config.
*
* @param config the config
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the config could not be set
*/
@Operation(summary = "Set the config", description = "Set the config")
@ApiResponses(
value = {
@ApiResponse(responseCode = "204", description = "The config was set 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 = "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 = "/configs", method = RequestMethod.POST, produces = "application/json")
@ResponseStatus(HttpStatus.NO_CONTENT)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Config.ConfigAdministration')")
public void setConfig(
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "The config",
required = true)
@RequestBody
Config config)
throws InvalidArgumentException, ServiceUnavailableException {
configService.setConfig(config);
}
}
|
0
|
java-sources/africa/absa/inception-config-api/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config-api/1.2.0/africa/absa/inception/config/ConfigApiConfiguration.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.config;
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>ConfigApiConfiguration</b> class provides the Spring configuration for the Config API
* module.
*
* @author Marcus Portmann
*/
@Configuration
public class ConfigApiConfiguration {
/**
* Returns the grouped Open API for the Config API.
*
* @return the grouped Open API for the Config API
*/
@Bean
public GroupedOpenApi configOpenApi() {
return GroupedOpenApi.builder()
.group("config")
.packagesToScan("africa.absa.inception.config")
.addOpenApiCustomiser(
openApi ->
openApi.info(new Info().title("Config API").version(Version.PROJECT_VERSION)))
.build();
}
}
|
0
|
java-sources/africa/absa/inception-config-api/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-config-api/1.2.0/africa/absa/inception/config/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.config;
/**
* 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-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/configuration/ConfigurationException.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.core.configuration;
/**
* The <b>ConfigurationException</b> exception is thrown to indicate a configuration error.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class ConfigurationException extends RuntimeException {
private static final long serialVersionUID = 1000000;
/** Constructs a new <b>ConfigurationException</b> with <b>null</b> as its message. */
public ConfigurationException() {
super();
}
/**
* Constructs a new <b>ConfigurationException</b> with the specified message.
*
* @param message The message saved for later retrieval by the <b>getMessage()</b> method.
*/
public ConfigurationException(String message) {
super(message);
}
/**
* Constructs a new <b>ConfigurationException</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 ConfigurationException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/converters/DateToLocalDateTimeConverter.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.core.converters;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* The <b>DateToLocalDateTimeConverter</b> class implements the Spring converter that converts a
* <b>Date</b> type into a <b>LocalDateTime</b> type.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
@Component
public final class DateToLocalDateTimeConverter implements Converter<Date, LocalDateTime> {
/** Constructs a new <b>DateToLocalDateTimeConverter</b>. */
public DateToLocalDateTimeConverter() {}
@Override
public LocalDateTime convert(Date source) {
return LocalDateTime.ofInstant(source.toInstant(), ZoneOffset.UTC);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/converters/LocalDateTimeToDateConverter.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.core.converters;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* The <b>LocalDateTimeToDateConverter</b> class implements the Spring converter that converts a
* <b>LocalDateTime</b> type into a <b>Date</b> type.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
@Component
public final class LocalDateTimeToDateConverter implements Converter<LocalDateTime, Date> {
/** Constructs a new <b>LocalDateTimeToDateConverter</b>. */
public LocalDateTimeToDateConverter() {}
@Override
public Date convert(LocalDateTime source) {
return Date.from(source.toInstant(ZoneOffset.UTC));
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/converters/LocalDateTimeToStringConverter.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.core.converters;
import africa.absa.inception.core.util.ISO8601Util;
import java.time.LocalDateTime;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* The <b>LocalDateTimeToStringConverter</b> class implements the Spring converter that converts a
* <b>LocalDateTime</b> type into a <b>String</b> type.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
@Component
public final class LocalDateTimeToStringConverter implements Converter<LocalDateTime, String> {
/** Constructs a new <b>LocalDateTimeToStringConverter</b>. */
public LocalDateTimeToStringConverter() {}
@Override
public String convert(LocalDateTime source) {
return ISO8601Util.fromLocalDateTime(source);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/converters/LocalDateToStringConverter.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.core.converters;
import africa.absa.inception.core.util.ISO8601Util;
import java.time.LocalDate;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* The <b>LocalDateToStringConverter</b> class implements the Spring converter that converts a
* <b>LocalDate</b> type into a <b>String</b> type.
*
* @author Marcus Portmann
*/
@Component
@SuppressWarnings("unused")
public final class LocalDateToStringConverter implements Converter<LocalDate, String> {
/** Constructs a new <b>LocalDateToStringConverter</b>. */
public LocalDateToStringConverter() {}
@Override
public String convert(LocalDate source) {
return ISO8601Util.fromLocalDate(source);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/converters/SortDirectionToStringConverter.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.core.converters;
import africa.absa.inception.core.sorting.SortDirection;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* The <b>SortDirectionToStringConverter</b> class implements the Spring converter that converts a
* <b>SortDirection</b> type into a <b>String</b> type.
*
* @author Marcus Portmann
*/
@Component
public class SortDirectionToStringConverter implements Converter<SortDirection, String> {
/** Constructs a new <b>SortDirectionToStringConverter</b>. */
public SortDirectionToStringConverter() {}
@Override
public String convert(SortDirection source) {
return source.code();
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/converters/StringToLocalDateConverter.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.core.converters;
import africa.absa.inception.core.util.ISO8601Util;
import java.time.LocalDate;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
* The <b>StringToLocalDateConverter</b> class implements the Spring converter that converts a
* <b>String</b> type into a <b>LocalDate</b> type.
*
* @author Marcus Portmann
*/
@Component
@SuppressWarnings("unused")
public final class StringToLocalDateConverter implements Converter<String, LocalDate> {
/** Constructs a new <b>StringToLocalDateConverter</b>. */
public StringToLocalDateConverter() {}
@Override
public LocalDate convert(String source) {
if (!StringUtils.hasText(source)) {
return null;
}
try {
return ISO8601Util.toLocalDate(source);
} catch (Throwable e) {
throw new RuntimeException("Failed to parse the ISO8601 date value (" + source + ")", e);
}
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/converters/StringToLocalDateTimeConverter.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.core.converters;
import africa.absa.inception.core.util.ISO8601Util;
import java.time.LocalDateTime;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
* The <b>StringToLocalDateTimeConverter</b> class implements the Spring converter that converts a
* <b>String</b> type into a <b>LocalDateTime</b> type.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
@Component
public final class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
/** Constructs a new <b>StringToLocalDateTimeConverter</b>. */
public StringToLocalDateTimeConverter() {}
@Override
public LocalDateTime convert(String source) {
if (!StringUtils.hasText(source)) {
return null;
}
try {
return ISO8601Util.toLocalDateTime(source);
} catch (Throwable e) {
throw new RuntimeException("Failed to parse the ISO8601 date time value (" + source + ")", e);
}
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/converters/StringToSortDirectionConverter.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.core.converters;
import africa.absa.inception.core.sorting.SortDirection;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* The <b>StringToSortDirectionConverter</b> class implements the Spring converter that converts a
* <b>String</b> type into a <b>SortDirection</b> type.
*
* @author Marcus Portmann
*/
@Component
public class StringToSortDirectionConverter implements Converter<String, SortDirection> {
/** Constructs a new <b>StringToSortDirectionConverter</b>. */
public StringToSortDirectionConverter() {}
@Override
public SortDirection convert(String source) {
return SortDirection.fromCode(source);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/converters/StringToZonedDateTimeConverter.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.core.converters;
import africa.absa.inception.core.util.ISO8601Util;
import java.time.ZonedDateTime;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
* The <b>StringToZonedDateTimeConverter</b> class implements the Spring converter that converts a
* <b>String</b> type into a <b>ZonedDateTime</b> type.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
@Component
public final class StringToZonedDateTimeConverter implements Converter<String, ZonedDateTime> {
/** Constructs a new <b>StringToZonedDateTimeConverter</b>. */
public StringToZonedDateTimeConverter() {}
@Override
public ZonedDateTime convert(String source) {
if (!StringUtils.hasText(source)) {
return null;
}
try {
return ISO8601Util.toZonedDateTime(source);
} catch (Throwable e) {
throw new RuntimeException("Failed to parse the ISO8601 date time value (" + source + ")", e);
}
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/converters/ZonedDateTimeToStringConverter.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.core.converters;
import africa.absa.inception.core.util.ISO8601Util;
import java.time.ZonedDateTime;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
/**
* The <b>ZonedDateTimeToStringConverter</b> class implements the Spring converter that converts a
* <b>ZonedDateTime</b> type into a <b>String</b> type.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
@Component
public final class ZonedDateTimeToStringConverter implements Converter<ZonedDateTime, String> {
/** Constructs a new <b>ZonedDateTimeToStringConverter</b>. */
public ZonedDateTimeToStringConverter() {}
@Override
public String convert(ZonedDateTime source) {
return ISO8601Util.fromZonedDateTime(source);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/exception/RichException.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.core.exception;
import africa.absa.inception.core.util.ISO8601Util;
import java.time.LocalDateTime;
/**
* The <b>RichException</b> exception is thrown when additional information related to an error
* condition exists including the time the error occurred and an associated error code. condition.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class RichException extends Exception {
private static final String NO_ERROR_CODE = "NONE";
private static final long serialVersionUID = 1000000;
/** The date and time the exception occurred. */
private final LocalDateTime when;
/** The optional error code. */
private String code;
/** Constructs a new <b>RichException</b> with <b>null</b> as its message. */
public RichException() {
super();
this.when = LocalDateTime.now();
}
/**
* Constructs a new <b>RichException</b> with the specified message.
*
* @param message the message saved for later retrieval by the <b>getMessage()</b> method
*/
public RichException(String message) {
super(message);
this.when = LocalDateTime.now();
}
/**
* Constructs a new <b>RichException</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 RichException(Throwable cause) {
super(cause);
this.when = LocalDateTime.now();
}
/**
* Constructs a new <b>RichException</b> with the specified code and message.
*
* @param code the error code
* @param message the message saved for later retrieval by the <b>getMessage()</b> method
*/
public RichException(String code, String message) {
super(message);
this.code = code;
this.when = LocalDateTime.now();
}
/**
* Constructs a new <b>RichException</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 RichException(String message, Throwable cause) {
super(message, cause);
this.when = LocalDateTime.now();
}
/**
* Constructs a new <b>RichException</b> with the specified code, message and cause.
*
* @param code the error code
* @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 RichException(String code, String message, Throwable cause) {
super(message, cause);
this.code = code;
this.when = LocalDateTime.now();
}
/**
* Returns the optional error code or NONE if no error code was specified.
*
* @return the optional error code or NONE if no error code was specified
*/
public String getCode() {
return (code == null) ? NO_ERROR_CODE : code;
}
/**
* Returns the date and time the exception occurred.
*
* @return the date and time the exception occurred
*/
public LocalDateTime getWhen() {
return when;
}
/**
* Returns the date and time the exception occurred as a String.
*
* @return the date and time the exception occurred as a String
*/
@SuppressWarnings("unused")
public String getWhenAsString() {
return ISO8601Util.fromLocalDateTime(when);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/exception/RichRuntimeException.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.core.exception;
import africa.absa.inception.core.util.ISO8601Util;
import java.time.LocalDateTime;
/**
* The <b>RichRuntimeException</b> exception is thrown when additional information related to an
* error condition exists including the time the error occurred and an associated error code.
* condition.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class RichRuntimeException extends RuntimeException {
private static final String NO_ERROR_CODE = "NONE";
private static final long serialVersionUID = 1000000;
/** The date and time the exception occurred. */
private final LocalDateTime when;
/** The optional error code. */
private String code;
/** Constructs a new <b>RichRuntimeException</b> with <b>null</b> as its message. */
public RichRuntimeException() {
super();
this.when = LocalDateTime.now();
}
/**
* Constructs a new <b>RichRuntimeException</b> with the specified message.
*
* @param message the message saved for later retrieval by the <b>getMessage()</b> method
*/
public RichRuntimeException(String message) {
super(message);
this.when = LocalDateTime.now();
}
/**
* Constructs a new <b>RichRuntimeException</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 RichRuntimeException(Throwable cause) {
super(cause);
this.when = LocalDateTime.now();
}
/**
* Constructs a new <b>RichRuntimeException</b> with the specified code and message.
*
* @param code the error code
* @param message the message saved for later retrieval by the <b>getMessage()</b> method
*/
public RichRuntimeException(String code, String message) {
super(message);
this.code = code;
this.when = LocalDateTime.now();
}
/**
* Constructs a new <b>RichRuntimeException</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 RichRuntimeException(String message, Throwable cause) {
super(message, cause);
this.when = LocalDateTime.now();
}
/**
* Constructs a new <b>RichRuntimeException</b> with the specified code, message and cause.
*
* @param code the error code
* @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 RichRuntimeException(String code, String message, Throwable cause) {
super(message, cause);
this.code = code;
this.when = LocalDateTime.now();
}
/**
* Returns the optional error code or NONE if no error code was specified.
*
* @return the optional error code or NONE if no error code was specified
*/
public String getCode() {
return (code == null) ? NO_ERROR_CODE : code;
}
/**
* Returns the date and time the exception occurred.
*
* @return the date and time the exception occurred
*/
public LocalDateTime getWhen() {
return when;
}
/**
* Returns the date and time the exception occurred as a String.
*
* @return the date and time the exception occurred as a String
*/
@SuppressWarnings("unused")
public String getWhenAsString() {
return ISO8601Util.fromLocalDateTime(when);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/service/InvalidArgumentError.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.core.service;
import java.io.Serializable;
import java.util.List;
/**
* The <b>InvalidArgumentError</b> class holds the invalid argument error information.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused"})
public class InvalidArgumentError extends ServiceError implements Serializable {
private static final long serialVersionUID = 1000000;
/** The name of the parameter associated with the invalid argument error. */
private String parameter;
/** The optional validation errors associated with the invalid argument error. */
private List<ValidationError> validationErrors;
/** Constructs a new <b>InvalidArgumentError</b>. */
public InvalidArgumentError() {}
/**
* Constructs a new <b>InvalidArgumentError</b>.
*
* @param message the message for the invalid argument error
* @param parameter the name of the parameter associated with the invalid argument error
* @param validationErrors the validation errors associated with the invalid argument
*/
public InvalidArgumentError(
String message, String parameter, List<ValidationError> validationErrors) {
super(message);
this.parameter = parameter;
this.validationErrors = validationErrors;
}
/**
* Returns the name of the parameter associated with the invalid argument error.
*
* @return the name of the parameter associated with the invalid argument error
*/
public String getParameter() {
return parameter;
}
/**
* Returns the optional validation errors associated with the invalid argument error.
*
* @return the optional validation errors associated with the invalid argument error
*/
public List<ValidationError> getValidationErrors() {
return validationErrors;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/service/InvalidArgumentException.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.core.service;
import java.util.List;
/**
* The <b>InvalidArgumentException</b> exception is thrown to indicate an error condition as a
* result of an invalid argument.
*
* <p>This is a checked exception to prevent the automatic rollback of the current transaction.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
public class InvalidArgumentException extends ServiceException {
private static final long serialVersionUID = 1000000;
/** The invalid argument error information. */
private final InvalidArgumentError invalidArgumentError;
/**
* Constructs a new <b>InvalidArgumentException</b>.
*
* @param parameter the name of the parameter associated with the invalid argument
*/
public InvalidArgumentException(String parameter) {
this(parameter, null);
}
/**
* Constructs a new <b>InvalidArgumentException</b>.
*
* @param parameter the name of the parameter associated with the invalid argument
* @param validationErrors the validation errors associated with the invalid argument
*/
public InvalidArgumentException(String parameter, List<ValidationError> validationErrors) {
super("Invalid argument (" + parameter + ")");
this.invalidArgumentError =
new InvalidArgumentError(
"Invalid argument (" + parameter + ")", parameter, validationErrors);
}
/**
* Returns the fault info.
*
* @return the fault info
*/
public InvalidArgumentError getFaultInfo() {
return invalidArgumentError;
}
/**
* Returns the invalid argument error info.
*
* @return the invalid argument error info
*/
public InvalidArgumentError getInvalidArgumentError() {
return invalidArgumentError;
}
/**
* Returns the name of the parameter associated with the invalid argument.
*
* @return the name of the parameter associated with the invalid argument
*/
public String getParameter() {
return invalidArgumentError.getParameter();
}
/**
* Returns the optional validation errors associated with the invalid argument.
*
* @return the optional validation errors associated with the invalid argument
*/
public List<ValidationError> getValidationErrors() {
return invalidArgumentError.getValidationErrors();
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/service/Problem.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.core.service;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The <b>Problem</b> annotation is applied to an exception thrown by a service to specify how the
* exception should be returned as a RFC 7807 JSON Problem Details Object during an API invocation.
*
* @author Marcus Portmann
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Problem {
/**
* The HTTP status code generated by the origin server for an occurrence of the problem.
*
* @return the HTTP status code generated by the origin server for an occurrence of the problem
*/
int status() default 500;
/**
* The short, human-readable summary of the problem type.
*
* @return the short, human-readable summary of the problem type
*/
String title();
/**
* The URI reference that identifies the problem type.
*
* @return the URI reference that identifies the problem type
*/
String type() default "about:blank";
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/service/ServiceError.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.core.service;
import java.time.LocalDateTime;
/**
* The <b>ServiceError</b> class holds the service error information.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class ServiceError {
/** The message for the service error. */
private String message;
/** The date and time the service error occurred. */
private LocalDateTime timestamp;
/** Constructs a new <b>ServiceError</b>. */
public ServiceError() {}
/**
* Constructs a new <b>ServiceError</b>.
*
* @param message the message for the service error
*/
public ServiceError(String message) {
this.timestamp = LocalDateTime.now();
this.message = message;
}
/**
* Returns the message for the service error.
*
* @return the message for the service error
*/
public String getMessage() {
return message;
}
/**
* Returns the date and time the service error occurred.
*
* @return the date and time the service error occurred
*/
public LocalDateTime getTimestamp() {
return timestamp;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/service/ServiceException.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.core.service;
import java.time.LocalDateTime;
/**
* The <b>ServiceException</b> exception is the base class that all service exceptions should be
* derived from.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
public abstract class ServiceException extends Exception {
private static final long serialVersionUID = 1000000;
/** The service error information. */
private final ServiceError serviceError;
/**
* Constructs a new <b>ServiceException</b> with the specified message.
*
* @param message The message saved for later retrieval by the <b>getMessage()</b> method.
*/
public ServiceException(String message) {
this(message, null);
}
/**
* Constructs a new <b>ServiceException</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 ServiceException(String message, Throwable cause) {
super(message, cause);
this.serviceError = new ServiceError(message);
}
/**
* Returns the fault info.
*
* @return the fault info
*/
public ServiceError getFaultInfo() {
return serviceError;
}
/**
* Returns the date and time the service exception occurred.
*
* @return the date and time the service exception occurred
*/
public LocalDateTime getTimestamp() {
return serviceError.getTimestamp();
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/service/ServiceUnavailableException.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.core.service;
/**
* The <b>ServiceUnavailableException</b> exception is thrown to indicate an error condition when a
* service is unavailable and a request could not be processed.
*
* <p>This is a checked exception to prevent the automatic rollback of the current transaction.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class ServiceUnavailableException extends ServiceException {
private static final long serialVersionUID = 1000000;
/**
* Constructs a new <b>ServiceUnavailableException</b> with the specified message.
*
* @param message The message saved for later retrieval by the <b>getMessage()</b> method.
*/
public ServiceUnavailableException(String message) {
super(message);
}
/**
* Constructs a new <b>ServiceUnavailableException</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 ServiceUnavailableException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/service/ValidationError.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.core.service;
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.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.constraints.NotNull;
import org.springframework.util.StringUtils;
/**
* The <b>ValidationError</b> class represents a validation error.
*
* @author Marcus Portmann
*/
@Schema(description = "A validation error")
@JsonPropertyOrder({"property", "message"})
@SuppressWarnings({"unused", "WeakerAccess"})
public class ValidationError implements Serializable, Cloneable {
private static final long serialVersionUID = 1000000;
/** The error message for the validation error. */
@Schema(description = "The error message for the validation error", required = true)
@JsonProperty(required = true)
@NotNull
private String message;
/** The path for the property that resulted in the validation error. */
@Schema(
description = "The path for the property that resulted in the validation error",
required = true)
@JsonProperty(required = true)
@NotNull
private String property;
/** Constructs a new <b>ValidationError</b>. */
public ValidationError() {}
/**
* Constructs a new <b>ValidationError</b>.
*
* @param constraintViolation the constraint violation
*/
public ValidationError(ConstraintViolation<?> constraintViolation) {
this.property = constraintViolation.getPropertyPath().toString();
this.message = constraintViolation.getMessage();
Map<String, Object> attributes = constraintViolation.getConstraintDescriptor().getAttributes();
}
/**
* Constructs a new <b>ValidationError</b>.
*
* @param property the path for the property that resulted in the validation error
* @param message the error message for the validation error
*/
public ValidationError(String property, String message) {
this.property = property;
this.message = message;
}
/**
* Capitalize each word in the string.
*
* @param str the string
* @return the capitalized string
*/
public static String capitalizePropertyName(String str) {
if (!StringUtils.hasText(str)) {
return str;
}
StringReader reader = new StringReader(str);
try {
StringBuilder buffer = new StringBuilder();
boolean capitilizeNextCharacter = true;
int c;
while ((c = reader.read()) != -1) {
char character = (char) c;
if (capitilizeNextCharacter) {
buffer.append(Character.toUpperCase(character));
} else {
buffer.append(character);
}
capitilizeNextCharacter = (character == '.') || (character == ' ');
}
return buffer.toString();
} catch (Throwable e) {
throw new RuntimeException("Failed to capitalizePropertyName the string (" + str + ")", e);
}
}
/**
* Capitalize the property names for the validation errors.
*
* @param validationErrors the validation errors
*/
public static void capitalizePropertyNames(List<ValidationError> validationErrors) {
if (validationErrors == null) {
return;
}
for (ValidationError validationError : validationErrors) {
validationError.setProperty(capitalizePropertyName(validationError.getProperty()));
}
}
/**
* Helper method to convert a set of JSR 303 constraint violations to a set of validation errors.
*
* @param <T> the type the constraint violations are associated with
* @param constraintViolations the JSR 303 constraint violations to convert
* @return the validation errors
*/
public static <T> List<ValidationError> toValidationErrors(
Set<ConstraintViolation<T>> constraintViolations) {
return toValidationErrors(constraintViolations, false);
}
/**
* Helper method to convert a set of JSR 303 constraint violations to a set of validation errors.
*
* @param <T> the type the constraint violations are associated with
* @param constraintViolations the JSR 303 constraint violations to convert
* @param capitalizePropertyNames should the property names be capitilized
* @return the validation errors
*/
public static <T> List<ValidationError> toValidationErrors(
Set<ConstraintViolation<T>> constraintViolations, boolean capitalizePropertyNames) {
List<ValidationError> validationErrors = new ArrayList<>();
for (ConstraintViolation<T> constraintViolation : constraintViolations) {
ValidationError validationError = new ValidationError(constraintViolation);
if (capitalizePropertyNames) {
validationError.setProperty(capitalizePropertyName(validationError.getProperty()));
}
validationErrors.add(validationError);
}
return validationErrors;
}
/**
* Returns the error message for the validation error.
*
* @return the error message for the validation error
*/
public String getMessage() {
return message;
}
/**
* Returns the path for the property that resulted in the validation error.
*
* @return the path for the property that resulted in the validation error
*/
public String getProperty() {
return property;
}
/**
* Set the error message for the validation error.
*
* @param message the error message for the validation error
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Set the path for the property that resulted in the validation error.
*
* @param property the path for the property that resulted in the validation error
*/
public void setProperty(String property) {
this.property = property;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/sorting/SortDirection.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.core.sorting;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* The <b>SortDirection</b> enumeration defines the possible sort directions when retrieving
* security related entities.
*
* @author Marcus Portmann
*/
@Schema(description = "The sort direction")
public enum SortDirection {
/** Sort ascending. */
ASCENDING("asc", "Ascending"),
/** Sort descending. */
DESCENDING("desc", "Descending");
private final String code;
private final String description;
SortDirection(String code, String description) {
this.code = code;
this.description = description;
}
/**
* Returns the sort direction given by the specified code value.
*
* @param code the code for the sort direction
* @return the sort direction given by the specified code value
*/
@JsonCreator
public static SortDirection fromCode(String code) {
switch (code) {
case "asc":
return SortDirection.ASCENDING;
case "desc":
return SortDirection.DESCENDING;
default:
throw new RuntimeException(
"Failed to determine the sort direction with the invalid code (" + code + ")");
}
}
/**
* Returns the code for the sort direction.
*
* @return the code for the sort direction
*/
@JsonValue
public String code() {
return code;
}
/**
* Returns the description for the sort direction.
*
* @return the description for the sort direction
*/
public String description() {
return description;
}
/**
* Return the string representation of the sort direction enumeration value.
*
* @return the string representation of the sort direction enumeration value
*/
public String toString() {
return description;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/support/MergedMessageSource.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.core.support;
import java.io.IOException;
import java.util.Properties;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
/**
* The <b>MergedMessageSource</b> class implements the merged message source that provides support
* for merging multiple message property files with the .properties suffix.
*
* @author Marcus Portmann
*/
public class MergedMessageSource extends ReloadableResourceBundleMessageSource {
private static final String PROPERTIES_SUFFIX = ".properties";
private final PathMatchingResourcePatternResolver resolver =
new PathMatchingResourcePatternResolver();
@Override
protected PropertiesHolder refreshProperties(String filename, PropertiesHolder propertiesHolder) {
if (filename.startsWith(PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX)) {
return refreshClassPathProperties(filename, propertiesHolder);
} else {
return super.refreshProperties(filename, propertiesHolder);
}
}
private PropertiesHolder refreshClassPathProperties(
String filename, PropertiesHolder propertiesHolder) {
Properties properties = new Properties();
long lastModified = -1;
try {
Resource[] resources = resolver.getResources(filename + PROPERTIES_SUFFIX);
for (Resource resource : resources) {
String resourcePath = resource.getURI().toString().replace(PROPERTIES_SUFFIX, "");
PropertiesHolder resourcePropertiesHolder =
super.refreshProperties(resourcePath, propertiesHolder);
Properties resourceProperties = resourcePropertiesHolder.getProperties();
if (resourceProperties != null) {
properties.putAll(resourceProperties);
}
if (lastModified < resource.lastModified()) {
lastModified = resource.lastModified();
}
}
} catch (IOException ignored) {
}
return new PropertiesHolder(properties, lastModified);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/Base64Exception.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.core.util;
/**
* The <b>Base64Exception</b> exception is thrown to indicate an error condition when performing a
* base64 encode or decode operation.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class Base64Exception extends RuntimeException {
private static final long serialVersionUID = 1000000;
/** Constructs a new <b>Base64Exception</b> with <b>null</b> as its message. */
public Base64Exception() {
super();
}
/**
* Constructs a new <b>Base64Exception</b> with the specified message.
*
* @param message The message saved for later retrieval by the <b>getMessage()</b> method.
*/
public Base64Exception(String message) {
super(message);
}
/**
* Constructs a new <b>Base64Exception</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 Base64Exception(Throwable cause) {
super(cause);
}
/**
* Constructs a new <b>Base64Exception</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 Base64Exception(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/Base64Util.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.core.util;
import java.util.Optional;
/**
* The <b>Base64Util</b> class provides a number of Base-64 related utility functions.
*
* @author Robert Harder
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class Base64Util {
/** Indicates error in encoding. */
public static final byte BAD_ENCODING;
/** Specify that data should be compressed (value is <b>true</b>). */
public static final boolean COMPRESS = true;
/** Specify decoding (value is <b>false</b>). */
public static final boolean DECODE = false;
/** Specify that data should not be compressed (value is <b>false</b>). */
public static final boolean DONT_COMPRESS = false;
/** Specify encoding (value is <b>true</b>). */
public static final boolean ENCODE = true;
/** Indicates equals sign in encoding. */
public static final byte EQUALS_SIGN_ENC;
/** Indicates white space in encoding. */
public static final byte WHITE_SPACE_ENC;
/** The 64 valid Base64Util values. */
private static final byte[] ALPHABET = {
(byte) 'A',
(byte) 'B',
(byte) 'C',
(byte) 'D',
(byte) 'E',
(byte) 'F',
(byte) 'G',
(byte) 'H',
(byte) 'I',
(byte) 'J',
(byte) 'K',
(byte) 'L',
(byte) 'M',
(byte) 'N',
(byte) 'O',
(byte) 'P',
(byte) 'Q',
(byte) 'R',
(byte) 'S',
(byte) 'T',
(byte) 'U',
(byte) 'V',
(byte) 'W',
(byte) 'X',
(byte) 'Y',
(byte) 'Z',
(byte) 'a',
(byte) 'b',
(byte) 'c',
(byte) 'd',
(byte) 'e',
(byte) 'f',
(byte) 'g',
(byte) 'h',
(byte) 'i',
(byte) 'j',
(byte) 'k',
(byte) 'l',
(byte) 'm',
(byte) 'n',
(byte) 'o',
(byte) 'p',
(byte) 'q',
(byte) 'r',
(byte) 's',
(byte) 't',
(byte) 'u',
(byte) 'v',
(byte) 'w',
(byte) 'x',
(byte) 'y',
(byte) 'z',
(byte) '0',
(byte) '1',
(byte) '2',
(byte) '3',
(byte) '4',
(byte) '5',
(byte) '6',
(byte) '7',
(byte) '8',
(byte) '9',
(byte) '+',
(byte) '/'
};
/**
* Translates a Base64Util value to either its 6-bit reconstruction value or a negative number
* indicating some other meaning.
*/
private static final byte[] DECODABET = {
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
// Decimal 0 - 8
-5,
-5, // Whitespace: Tab and Linefeed
-9,
-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 14 - 26
-9,
-9,
-9,
-9,
-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,
-9,
-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,
53,
54,
55,
56,
57,
58,
59,
60,
61, // Numbers zero through nine
-9,
-9,
-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,
-9,
-9, // Decimal 62 - 64
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13, // Letters 'A' through 'N'
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25, // Letters 'O' through 'Z'
-9,
-9,
-9,
-9,
-9,
-9, // Decimal 91 - 96
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38, // Letters 'a' through 'm'
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51, // Letters 'n' through 'z'
-9,
-9,
-9,
-9 // Decimal 123 - 126
/*
* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
*/
};
/** The equals sign (=) as a byte. */
private static final byte EQUALS_SIGN = (byte) '=';
/** Maximum line length (76) of Base64Util output. */
private static final int MAX_LINE_LENGTH = 76;
/** The new line character (\n) as a byte. */
private static final byte NEW_LINE = (byte) '\n';
static {
BAD_ENCODING = -9;
WHITE_SPACE_ENC = -5;
EQUALS_SIGN_ENC = -1;
}
/** Defeats instantiation. */
private Base64Util() {}
/**
* Decodes data from Base64Util notation.
*
* @param s the string to decode
* @return the decoded data
* @since 1.4
*/
public static byte[] decode(String s) {
byte[] bytes = s.getBytes();
return decode(bytes, 0, bytes.length);
}
/**
* Decodes Base64Util content in byte array format and returns the decoded byte array.
*
* @param source the Base64Util encoded data
* @param off the offset of where to begin decoding
* @param len the length of characters to decode
* @return decoded data
* @since 1.3
*/
public static byte[] decode(byte[] source, int off, int len) {
int len34 = len * 3 / 4;
byte[] outBuff = new byte[len34]; // Upper limit on size of output
int outBuffPosn = 0;
byte[] b4 = new byte[4];
int b4Posn = 0;
int i;
byte sbiCrop;
byte sbiDecode;
for (i = off; i < off + len; i++) {
sbiCrop = (byte) (source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[sbiCrop];
if (sbiDecode >= WHITE_SPACE_ENC) // White space, Equals sign or better
{
if (sbiDecode >= EQUALS_SIGN_ENC) {
b4[b4Posn++] = sbiCrop;
if (b4Posn > 3) {
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if (sbiCrop == EQUALS_SIGN) {
break;
}
}
}
} else {
throw new Base64Exception(
"Bad Base64Util input character at " + i + ": " + source[i] + "(decimal)");
}
}
byte[] out = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
return out;
}
/**
* Attempts to decode Base64Util data and deserialize a Java Object within. Returns <b>null</b> if
* there was an error.
*
* @param encodedObject the Base64Util data to decode
* @return an Optional containing the decoded and deserialized object or an empty Optional if
* there was an error
* @since 1.4
*/
public static Optional<Object> decodeToObject(String encodedObject) {
byte[] objBytes = decode(encodedObject);
try (java.io.ObjectInputStream ois =
new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(objBytes))) {
return Optional.of(ois.readObject());
} catch (Throwable e) {
return Optional.empty();
}
}
/**
* Decodes data from Base64Util notation and returns it as a string. Equivlaent to calling <b> new
* String(decode(s))</b>
*
* @param s the string to decode
* @return the data as a string
* @since 1.4
*/
public static String decodeToString(String s) {
return new String(decode(s));
}
/**
* Encodes a byte array into Base64Util notation. Equivalent to calling <b>encodeBytes(source, 0,
* source.length)</b>
*
* @param source the data to convert
* @return the Base64Util encoded string
* @since 1.4
*/
public static String encodeBytes(byte[] source) {
return encodeBytes(source, true);
}
/**
* Encodes a byte array into Base64Util notation. Equivalent to calling <b>encodeBytes(source, 0,
* source.length)</b>
*
* @param source the data to convert
* @param breakLines break lines at 80 characters or less
* @return the Base64Util encoded bytes
* @since 1.4
*/
public static String encodeBytes(byte[] source, boolean breakLines) {
return encodeBytes(source, 0, source.length, breakLines);
}
/**
* Encodes a byte array into Base64Util notation.
*
* @param source the data to convert
* @param off offset in array where conversion should begin
* @param len length of data to convert
* @return the Base64Util encoded bytes
* @since 1.4
*/
public static String encodeBytes(byte[] source, int off, int len) {
return encodeBytes(source, off, len, true);
}
/**
* Encodes a byte array into Base64Util notation.
*
* @param source the data to convert
* @param off offset in array where conversion should begin
* @param len length of data to convert
* @param breakLines break lines at 80 characters or less
* @return the Base64Util encoded bytes
* @since 1.4
*/
public static String encodeBytes(byte[] source, int off, int len, boolean breakLines) {
int len43 = len * 4 / 3;
byte[] outBuff =
new byte
[(len43) // Main 4:3
+ ((len % 3) > 0 ? 4 : 0) // Account for padding
+ (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for (; d < len2; d += 3, e += 4) {
encode3to4(source, d + off, 3, outBuff, e);
lineLength += 4;
if (breakLines && (lineLength == MAX_LINE_LENGTH)) {
outBuff[e + 4] = NEW_LINE;
e++;
lineLength = 0;
}
}
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e);
e += 4;
}
return new String(outBuff, 0, e);
}
/**
* Encodes a string in Base64Util notation with line breaks after every 75 Base64Util characters.
* Of course you probably only need to encode a string if there are non-ASCII characters in it
* such as many non-English languages.
*
* @param s the string to encode
* @return the encoded string
* @since 1.3
*/
public static String encodeString(String s) {
return encodeString(s, true);
}
/**
* Encodes a string in Base64Util notation with line breaks after every 75 Base64Util characters.
* Of course you probably only need to encode a string if there are non-ASCII characters in it
* such as many non-English languages.
*
* @param s the string to encode
* @param breakLines break lines at 80 characters or less
* @return the encoded string
* @since 1.3
*/
public static String encodeString(String s, boolean breakLines) {
return encodeBytes(s.getBytes(), breakLines);
}
/**
* Decodes four bytes from array <var>source</var> and writes the resulting bytes (up to three of
* them) to <var>destination</var>. The source and destination arrays can be manipulated anywhere
* along their length by specifying <var>srcOffset</var> and <var>destOffset</var>. This method
* does not check to make sure your arrays are large enough to accomodate <var>srcOffset</var> + 4
* for the <var>source</var> array or <var>destOffset</var> + 3 for the <var>destination</var>
* array.
*
* <p>This method returns the actual number of bytes that were converted from the Base64Util
* encoding.
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the number of decoded bytes converted
* @since 1.3
*/
private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) {
// Example: Dk==
if (source[srcOffset + 2] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ((DECODABET[ source[ srcOffset ] ] << 24) >>> 6)
// | ((DECODABET[ source[ srcOffset + 1] ] << 24) >>> 12);
int outBuff =
((DECODABET[source[srcOffset]] & 0xFF) << 18)
| ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);
destination[destOffset] = (byte) (outBuff >>> 16);
return 1;
}
// Example: DkL=
else if (source[srcOffset + 3] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ((DECODABET[ source[ srcOffset ] ] << 24) >>> 6)
// | ((DECODABET[ source[ srcOffset + 1 ] ] << 24) >>> 12)
// | ((DECODABET[ source[ srcOffset + 2 ] ] << 24) >>> 18);
int outBuff =
((DECODABET[source[srcOffset]] & 0xFF) << 18)
| ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
| ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);
destination[destOffset] = (byte) (outBuff >>> 16);
destination[destOffset + 1] = (byte) (outBuff >>> 8);
return 2;
}
// Example: DkLE
else {
try {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ((DECODABET[ source[ srcOffset ] ] << 24) >>> 6)
// | ((DECODABET[ source[ srcOffset + 1 ] ] << 24) >>> 12)
// | ((DECODABET[ source[ srcOffset + 2 ] ] << 24) >>> 18)
// | ((DECODABET[ source[ srcOffset + 3 ] ] << 24) >>> 24);
int outBuff =
((DECODABET[source[srcOffset]] & 0xFF) << 18)
| ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
| ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6)
| ((DECODABET[source[srcOffset + 3]] & 0xFF));
destination[destOffset] = (byte) (outBuff >> 16);
destination[destOffset + 1] = (byte) (outBuff >> 8);
destination[destOffset + 2] = (byte) (outBuff);
return 3;
} catch (Exception e) {
System.out.println("" + source[srcOffset] + ": " + (DECODABET[source[srcOffset]]));
System.out.println("" + source[srcOffset + 1] + ": " + (DECODABET[source[srcOffset + 1]]));
System.out.println("" + source[srcOffset + 2] + ": " + (DECODABET[source[srcOffset + 2]]));
System.out.println("" + source[srcOffset + 3] + ": " + (DECODABET[source[srcOffset + 3]]));
return -1;
}
}
}
/**
* Encodes up to three bytes of the array <var>source</var> and writes the resulting four
* Base64Util bytes to <var>destination</var>. The source and destination arrays can be
* manipulated anywhere along their length by specifying <var>srcOffset</var> and
* <var>destOffset</var>. This method does not check to make sure your arrays are large enough to
* accomodate <var>srcOffset</var> + 3 for the <var>source</var> array or <var>destOffset</var> +
* 4 for the <var>destination</var> array. The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset) {
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create _buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff =
((numSigBytes > 0) ? ((source[srcOffset] << 24) >>> 8) : 0)
| ((numSigBytes > 1) ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| ((numSigBytes > 2) ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
}
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/BinaryBuffer.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.core.util;
/**
* The <b>BinaryBuffer</b> class manages binary data. It provides the capabilities similar to the
* <b>StringBuffer</b> class when working with binary data (bytes).
*
* <p>This class is thread-safe.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class BinaryBuffer implements java.io.Serializable {
private static final long serialVersionUID = 1000000;
/** The binary data. */
private byte[] data;
/**
* Constructs a new <b>BinaryBuffer</b> and initializes it using the specified binary data.
*
* @param data <b>BinaryBuffer</b> instance containing the binary data that will be copied and
* managed by the <b>BinaryBuffer</b> instance
*/
public BinaryBuffer(BinaryBuffer data) {
this(data.getData());
}
/**
* Constructs a new <b>BinaryBuffer</b> and initializes it using the specified binary data.
*
* @param data the binary data that will be copied and managed by the <b>BinaryBuffer</b> instance
*/
public BinaryBuffer(byte[] data) {
this.data = new byte[data.length];
System.arraycopy(data, 0, this.data, 0, data.length);
}
/**
* Append the binary data stored in the specified <b>BinaryBuffer</b> instance to this
* <b>BinaryBuffer</b>.
*
* @param buffer the existing <b>BinaryBuffer</b> containing the binary data to append
*/
public void append(BinaryBuffer buffer) {
append(buffer.getData());
}
/**
* Append the specified binary data to the binary data already stored in the <b>BinaryBuffer</b>.
*
* @param data the binary data to append
*/
public synchronized void append(byte[] data) {
byte[] currentData = this.data;
byte[] newData = new byte[currentData.length + data.length];
System.arraycopy(currentData, 0, newData, 0, currentData.length);
System.arraycopy(data, 0, newData, currentData.length, data.length);
this.data = newData;
}
/** Clears the <b>BinaryBuffer</b>. */
public void clear() {
this.data = new byte[0];
}
/**
* Returns the binary data managed by the <b>BinaryBuffer</b>.
*
* @return the binary data managed by the <b>BinaryBuffer</b>
*/
public byte[] getData() {
return data;
}
/**
* Returns the amount of binary data managed by the <b>BinaryBuffer</b>.
*
* @return the amount of binary data managed by the <b>BinaryBuffer</b>
*/
public int length() {
return data.length;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/CryptoException.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.core.util;
/**
* The <b>CryptoException</b> exception is thrown to indicate an error condition when working with
* the cryptography utilities.
*
* @author Marcus Portmann
*/
public class CryptoException extends RuntimeException {
private static final long serialVersionUID = 1000000;
/**
* Constructs a new <b>CryptoException</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)
*/
CryptoException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/CryptoUtil.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.core.util;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.UUID;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.StringUtils;
/**
* The <b>CryptoUtil</b> class provides a number of cryptography related utility functions.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class CryptoUtil {
/** The AES block size. */
public static final int AES_BLOCK_SIZE = 16;
/** The AES key size. */
public static final int AES_KEY_SIZE = 32;
/** The AES key specification. */
public static final String AES_KEY_SPEC = "AES";
/** The AES tranformation name. */
public static final String AES_TRANSFORMATION_NAME = "AES/CFB8/NoPadding";
private static final SecureRandom secureRandom = new SecureRandom();
/**
* Creates a random encryption initialization vector with the specified length.
*
* @param length the length of the random encryption initialization vector
* @return the random encryption initialization vector
*/
public static byte[] createRandomEncryptionIV(int length) {
byte[] encryptionIV = new byte[length];
secureRandom.nextBytes(encryptionIV);
return encryptionIV;
}
/**
* Retrieve the key pair with the specified alias from the key store.
*
* @param keyStore the key store
* @param alias the alias for the key pair
* @param password the password for the key
* @return the key pair
* @throws GeneralSecurityException if the key pair could not be retrieved
*/
public static KeyPair getKeyPair(KeyStore keyStore, String alias, String password)
throws GeneralSecurityException {
try {
RSAPrivateCrtKey key = (RSAPrivateCrtKey) keyStore.getKey(alias, password.toCharArray());
RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
return new KeyPair(publicKey, key);
} catch (Throwable e) {
throw new GeneralSecurityException(
"Failed to load the key pair (" + alias + ") from the key store", e);
}
}
/**
* Returns a randomly generated AES key.
*
* @return a randomly generated AES key
*/
public static byte[] getRandomAESKey() {
String randomPassword = new BigInteger(130, secureRandom).toString(32);
return CryptoUtil.passwordToAESKey(randomPassword, UUID.randomUUID().toString());
}
/**
* Load a key store.
*
* @param type the key store type e.g. JKS, PKCS12, etc
* @param path the path to the key store
* @param password the key store password
* @return the key store that was loaded
* @throws GeneralSecurityException if the key store could not be loaded
*/
public static KeyStore loadKeyStore(String type, String path, String password)
throws GeneralSecurityException {
InputStream input = null;
try {
PathMatchingResourcePatternResolver resourceLoader =
new PathMatchingResourcePatternResolver();
Resource keyStoreResource = resourceLoader.getResource(path);
if (!keyStoreResource.exists()) {
throw new GeneralSecurityException("The key store (" + path + ") could not be found");
}
KeyStore ks = KeyStore.getInstance(type);
input = keyStoreResource.getInputStream();
ks.load(
input,
((password == null) || (password.length() == 0)) ? new char[0] : password.toCharArray());
return ks;
} catch (Throwable e) {
throw new GeneralSecurityException("Failed to load the key store (" + path + ")", e);
} finally {
try {
if (input != null) {
input.close();
}
} catch (Throwable ignored) {
}
}
}
/**
* Load a key store and query it to confirm a key pair with the specified alias is present.
*
* @param type the key store type e.g. JKS, PKCS12, etc
* @param path the path to the key store
* @param password the key store password
* @param alias the alias for the key pair in the key store that should be retrieved
* @return the key store that was loaded
* @throws GeneralSecurityException if the key store could not be loaded
*/
public static KeyStore loadKeyStore(String type, String path, String password, String alias)
throws GeneralSecurityException {
InputStream input = null;
try {
PathMatchingResourcePatternResolver resourceLoader =
new PathMatchingResourcePatternResolver();
Resource keyStoreResource = resourceLoader.getResource(path);
if (!keyStoreResource.exists()) {
throw new GeneralSecurityException("The key store (" + path + ") could not be found");
}
KeyStore ks = KeyStore.getInstance(type);
input = keyStoreResource.getInputStream();
ks.load(
input,
((password == null) || (password.length() == 0)) ? new char[0] : password.toCharArray());
// Attempt to retrieve the private key from the key store
Key privateKey =
ks.getKey(
alias, StringUtils.hasText(password) ? password.toCharArray() : "".toCharArray());
if (privateKey == null) {
throw new GeneralSecurityException(
"A private key with alias ("
+ alias
+ ") could not be found in the key store ("
+ path
+ ")");
}
// Attempt to retrieve the certificate from the key store
java.security.cert.Certificate certificate = ks.getCertificate(alias);
if (certificate == null) {
throw new GeneralSecurityException(
"A certificate with alias ("
+ alias
+ ") could not be found in the key store ("
+ path
+ ")");
}
if (!(certificate instanceof X509Certificate)) {
throw new GeneralSecurityException(
"The certificate with alias (" + alias + ") is not an X509 certificate");
}
return ks;
} catch (Throwable e) {
throw new GeneralSecurityException(
"Failed to load and query the key store (" + path + ")", e);
} finally {
try {
if (input != null) {
input.close();
}
} catch (Throwable ignored) {
}
}
}
/**
* Load the trust store.
*
* @param type the trust store type e.g. JKS, PKCS12, etc
* @param path the path to the trust store
* @param password the trust store password
* @return the trust store that was loaded
* @throws GeneralSecurityException if the trust store could not be loaded
*/
public static KeyStore loadTrustStore(String type, String path, String password)
throws GeneralSecurityException {
KeyStore ks;
InputStream input = null;
try {
PathMatchingResourcePatternResolver resourceLoader =
new PathMatchingResourcePatternResolver();
Resource trustStoreResource = resourceLoader.getResource(path);
if (!trustStoreResource.exists()) {
throw new GeneralSecurityException("The trust store (" + path + ") could not be found");
}
ks = KeyStore.getInstance(type);
input = trustStoreResource.getInputStream();
ks.load(
input,
((password == null) || (password.length() == 0)) ? new char[0] : password.toCharArray());
return ks;
} catch (Throwable e) {
throw new GeneralSecurityException("Failed to load the trust store (" + path + ")", e);
} finally {
try {
if (input != null) {
input.close();
}
} catch (Throwable ignored) {
}
}
}
/**
* Convert the specified password to a 3DES key that can be used with the 3DES cypher encrypt and
* decrypt functions.
*
* @param password the password to convert to a 3DES key
* @return the 3DES key
*/
public static byte[] passwordTo3DESKey(String password) throws CryptoException {
byte[] salt = "0907df13-2ef5-41a8-90e7-f08a3ca16af4".getBytes();
return passwordTo3DESKey(password.getBytes(), salt);
}
/**
* Convert the specified password to an AES key that can be used with the AES cypher encrypt and
* decrypt functions.
*
* @param password the password to convert to an AES key
* @return the AES key
*/
public static byte[] passwordToAESKey(String password) throws CryptoException {
byte[] salt = "9aeabd0f-be94-486e-a693-ed2d553ea202".getBytes();
return passwordToAESKey(password.getBytes(), salt, AES_KEY_SIZE);
}
/**
* Convert the specified password to an AES key that can be used with the AES cypher encrypt and
* decrypt functions.
*
* @param password the password to convert to an AES key
* @param salt the salt to use when generating the AES key
* @return the AES key
*/
public static byte[] passwordToAESKey(String password, byte[] salt) throws CryptoException {
return passwordToAESKey(password.getBytes(), salt, AES_KEY_SIZE);
}
/**
* Convert the specified password to an AES key that can be used with the AES cypher encrypt and
* decrypt functions.
*
* @param password the password to convert to an AES key
* @param salt the salt to use when generating the AES key
* @return the AES key
*/
public static byte[] passwordToAESKey(String password, String salt) throws CryptoException {
return passwordToAESKey(password.getBytes(), salt.getBytes(), AES_KEY_SIZE);
}
private static byte[] hashPasswordAndSalt(byte[] password, byte[] salt) {
try {
// Concatenate password and salt.
byte[] pwAndSalt = new byte[password.length + salt.length];
System.arraycopy(password, 0, pwAndSalt, 0, password.length);
System.arraycopy(salt, 0, pwAndSalt, password.length, salt.length);
// Create the key as sha1(sha1(sha1(sha1(...(pw+salt))...)
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
for (int i = 0; i < 4; i++) {
messageDigest.update(pwAndSalt, 0, pwAndSalt.length);
messageDigest.digest(pwAndSalt, 0, messageDigest.getDigestLength());
}
return pwAndSalt;
} catch (Throwable e) {
throw new CryptoException("Failed to hash the password and key", e);
}
}
private static byte[] passwordTo3DESKey(byte[] password, byte[] salt) throws CryptoException {
try {
byte[] key = new byte[24];
System.arraycopy(hashPasswordAndSalt(password, salt), 0, key, 0, 24);
return key;
} catch (Throwable e) {
throw new CryptoException("Failed to convert the password to a 3DES key", e);
}
}
private static byte[] passwordToAESKey(byte[] password, byte[] salt, int keysize)
throws CryptoException {
try {
byte[] key = new byte[keysize];
System.arraycopy(hashPasswordAndSalt(password, salt), 0, key, 0, keysize);
return key;
} catch (Throwable e) {
throw new CryptoException("Failed to convert the password to an AES key", e);
}
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/ExceptionUtil.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.core.util;
/**
* The <b>ExceptionUtil</b> class is a utility class which provides methods for manipulating
* exceptions.
*
* @author Marcus Portmann
*/
public final class ExceptionUtil {
/**
* Returns the nested messages for an exception.
*
* @param e the exception
* @return the nested messages for the exception
*/
public static String getNestedMessages(Throwable e) {
StringBuilder buffer = new StringBuilder();
Throwable current = e;
do {
if (buffer.length() > 0) {
buffer.append(": ");
}
buffer.append(current.getMessage());
current = current.getCause();
} while (current != null);
return buffer.toString();
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/ISO8601Util.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.core.util;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
/**
* The <b>ISO8601Util</b> class provides a helper class for handling ISO 8601 strings of the
* following format: "2008-03-01T13:00:00+01:00". It also supports parsing the "Z" timezone.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public final class ISO8601Util {
private static final ThreadLocal<SimpleDateFormat> dateFormatter =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
private static final ThreadLocal<DateTimeFormatter> dateInputFormatter =
ThreadLocal.withInitial(
() ->
(new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd")
.parseLenient()
.optionalStart()
.appendPattern("'T'HH:mm:ss")
.optionalEnd()
.optionalStart()
.appendPattern(".SSS")
.optionalEnd()
.optionalStart()
.appendOffset("+HH:MM", "Z")
.optionalEnd()
.toFormatter()));
private static final ThreadLocal<SimpleDateFormat> dateTimeFormatter =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"));
private static final ThreadLocal<DateTimeFormatter> localDateFormatter =
ThreadLocal.withInitial(() -> DateTimeFormatter.ISO_DATE);
private static final ThreadLocal<DateTimeFormatter> localDateTimeFormatter =
ThreadLocal.withInitial(
() ->
(new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd'T'HH:mm:ss")
.parseLenient()
.optionalStart()
.appendPattern(".SSS")
.optionalEnd()
.optionalStart()
.appendOffset("+HH:MM", "Z")
.optionalEnd()
.toFormatter()));
private static final ThreadLocal<DateTimeFormatter> localTimeFormatter =
ThreadLocal.withInitial(() -> DateTimeFormatter.ISO_TIME);
/**
* Transform the <b>Date</b> instance into an ISO 8601 string.
*
* @param date the <b>Date</b> instance to transform into an ISO 8601 string
* @return the ISO 8601 string for the <b>Date</b> instance
*/
public static String fromDate(Date date) {
return dateFormatter.get().format(date);
}
/**
* Transform the <b>Date</b> instance into an ISO 8601 string.
*
* @param date the <b>Date</b> instance to transform into an ISO 8601 string
* @return the ISO 8601 string for the <b>Date</b> instance
*/
public static String fromDateTime(Date date) {
return dateTimeFormatter.get().format(date);
}
/**
* Transform the <b>LocalDate</b> instance into an ISO 8601 string.
*
* @param localDate the <b>LocalDate</b> instance to transform into an ISO 8601 string
* @return the ISO 8601 string for the <b>LocalDate</b> instance
*/
public static String fromLocalDate(LocalDate localDate) {
return localDate.format(localDateFormatter.get());
}
/**
* Transform the <b>LocalDateTime</b> instance into an ISO 8601 string.
*
* @param localDateTime the <b>LocalDateTime</b> instance to transform into an ISO 8601 string
* @return the ISO 8601 string for the <b>LocalDateTime</b> instance
*/
public static String fromLocalDateTimeAsUTC(LocalDateTime localDateTime) {
return localDateTime
.atZone(ZoneId.systemDefault())
.withZoneSameInstant(ZoneOffset.UTC)
.format(localDateTimeFormatter.get());
}
/**
* Transform the <b>LocalDateTime</b> instance into an ISO 8601 string.
*
* @param localDateTime the <b>LocalDateTime</b> instance to transform into an ISO 8601 string
* @return the ISO 8601 string for the <b>LocalDateTime</b> instance
*/
public static String fromLocalDateTime(LocalDateTime localDateTime) {
return localDateTime.format(localDateTimeFormatter.get());
}
/**
* Transform the <b>LocalTime</b> instance into an ISO 8601 string.
*
* @param localTime the <b>LocalTime</b> instance to transform into an ISO 8601 string
* @return the ISO 8601 string for the <b>LocalTime</b> instance
*/
public static String fromLocalTime(LocalTime localTime) {
return localTime.format(localTimeFormatter.get());
}
/**
* Transform the <b>ZonedDateTime</b> instance into an ISO 8601 string.
*
* @param zonedDateTime the <b>ZonedDateTime</b> instance to transform into an ISO 8601 string
* @return the ISO 8601 string for the <b>ZonedDateTime</b> instance
*/
public static String fromZonedDateTime(ZonedDateTime zonedDateTime) {
return zonedDateTime.format(localDateTimeFormatter.get());
}
// /**
// * Main.
// *
// * @param args the command line arguments
// */
// public static void main(String[] args)
// {
// System.out.println("fromDate(new Date()) = " + fromDate(new Date()));
//
// System.out.println("fromDateTime(new Date()) = " + fromDateTime(new Date()));
//
// System.out.println("fromLocalDate(LocalDate.now()) = " + fromLocalDate(LocalDate.now()));
//
// System.out.println("fromLocalDateTime(LocalDateTime.now()) = " + fromLocalDateTime(
// LocalDateTime.now()));
//
// System.out.println("fromZonedDateTime(ZonedDateTime.now(ZoneOffset.UTC)) = "
// + fromZonedDateTime(ZonedDateTime.now(ZoneOffset.UTC)));
//
// System.out.println("fromZonedDateTime(ZonedDateTime.now(ZoneId.systemDefault())) = "
// + fromZonedDateTime(ZonedDateTime.now(ZoneId.systemDefault())));
//
// System.out.println("Date 2017-08-14 = " + toDate("2017-08-14"));
//
// System.out.println("Date 2017-08-14T19:14:53.120Z = " + toDate("2017-08-14T19:14:53.120Z"));
//
// System.out.println("Date 2017-08-14T22:14:53.120+02:00 = " + toDate(
// "2017-08-14T22:14:53.120+02:00"));
//
// System.out.println("Date 2017-08-14T19:14:53.120 = " + toDate("2017-08-14T19:14:53.120"));
//
// System.out.println("Date 2017-08-14T19:14:53 = " + toDate("2017-08-14T19:14:53"));
//
// System.out.println("Local Date Time 2017-08-14T19:14:53.120Z = " + toLocalDateTime(
// "2017-08-14T19:14:53.120Z"));
//
// System.out.println("Local Date Time 2017-08-14T22:14:53.120+02:00 = " + toLocalDateTime(
// "2017-08-14T22:14:53.120+02:00"));
//
// System.out.println("Local Date Time 2017-08-14T19:14:53.120 = " + toLocalDateTime(
// "2017-08-14T19:14:53.120"));
//
// System.out.println("Local Date Time 2017-08-14T19:14:53 = " + toLocalDateTime(
// "2017-08-14T19:14:53"));
//
// System.out.println("Zoned Date Time 2017-08-14T19:14:53.120Z = " + toZonedDateTime(
// "2017-08-14T19:14:53.120Z"));
//
// System.out.println("Zoned Date Time 2017-08-14T22:14:53.120+02:00 = " + toZonedDateTime(
// "2017-08-14T22:14:53.120+02:00"));
//
// System.out.println("Zoned Date Time 2017-08-14T19:14:53.120 = " + toZonedDateTime(
// "2017-08-14T19:14:53.120"));
//
// System.out.println("Zoned Date Time 2017-08-14T19:14:53 = " + toZonedDateTime(
// "2017-08-14T19:14:53"));
// }
/**
* Get current date and time formatted as ISO 8601 string.
*
* @return the current date and time formatted as ISO 8601 string
*/
public static String now() {
return fromLocalDateTime(LocalDateTime.now());
}
/**
* Transform ISO 8601 string into a <b>LocalDate</b> instance.
*
* @param iso8601string the ISO 8601 string to transform
* @return the <b>LocalDate</b> instance for the ISO 8601 string
*/
public static Date toDate(String iso8601string) {
TemporalAccessor temporalAccessor = dateInputFormatter.get().parse(iso8601string);
if (!temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) {
LocalDate localDate = LocalDate.parse(iso8601string, localDateFormatter.get());
return java.sql.Date.valueOf(localDate);
} else if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) {
ZonedDateTime zonedDateTime =
ZonedDateTime.parse(iso8601string, localDateTimeFormatter.get())
.withZoneSameInstant(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
} else {
LocalDateTime localDateTime =
LocalDateTime.parse(iso8601string, localDateTimeFormatter.get());
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
}
/**
* Transform ISO 8601 string into a <b>LocalDate</b> instance.
*
* @param iso8601string the ISO 8601 string to transform
* @return the <b>LocalDate</b> instance for the ISO 8601 string
*/
public static LocalDate toLocalDate(String iso8601string) {
return LocalDate.parse(iso8601string, localDateFormatter.get());
}
/**
* Transform ISO 8601 string into a <b>LocalDateTime</b> instance.
*
* @param iso8601string the ISO 8601 string to transform
* @return the <b>LocalDateTime</b> instance for the ISO 8601 string
*/
public static LocalDateTime toLocalDateTime(String iso8601string) {
TemporalAccessor temporalAccessor = localDateTimeFormatter.get().parse(iso8601string);
if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) {
return ZonedDateTime.parse(iso8601string, localDateTimeFormatter.get())
.withZoneSameInstant(ZoneId.systemDefault())
.toLocalDateTime();
} else {
return LocalDateTime.parse(iso8601string, localDateTimeFormatter.get());
}
}
/**
* Transform ISO 8601 string into a <b>LocalTime</b> instance.
*
* @param iso8601string the ISO 8601 string to transform
* @return the <b>LocalTime</b> instance for the ISO 8601 string
*/
public static LocalTime toLocalTime(String iso8601string) {
return LocalTime.parse(iso8601string, localTimeFormatter.get());
}
/**
* Transform ISO 8601 string into a <b>ZonedDateTime</b> instance.
*
* @param iso8601string the ISO 8601 string to transform
* @return the <b>ZonedDateTime</b> instance for the ISO 8601 string
*/
public static ZonedDateTime toZonedDateTime(String iso8601string) {
TemporalAccessor temporalAccessor = localDateTimeFormatter.get().parse(iso8601string);
if (temporalAccessor.isSupported(ChronoField.OFFSET_SECONDS)) {
return ZonedDateTime.parse(iso8601string, localDateTimeFormatter.get())
.withZoneSameInstant(ZoneId.systemDefault());
} else {
return LocalDateTime.parse(iso8601string, localDateTimeFormatter.get())
.atZone(ZoneId.systemDefault());
}
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/JDBCUtil.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.core.util;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.util.StringUtils;
/**
* The <b>JDBCUtil</b> class provides JDBCUtil utility functions.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class JDBCUtil {
/** Private default constructor to enforce utility pattern. */
private JDBCUtil() {}
/**
* Close the connection.
*
* @param connection the connection to close
*/
public static void close(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// Do nothing
}
}
}
/**
* Close the result set.
*
* @param rs the result set to close
*/
public static void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// Do nothing
}
}
}
/**
* Close the statement.
*
* @param statement the statement to close
*/
public static void close(Statement statement) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// Do nothing
}
}
}
/**
* Execute the SQL statement using the database connection.
*
* @param connection the database connection to use
* @param sql the SQL statement to execute
* @return the row count
* @throws SQLException if the statement execution failed
*/
public static int executeStatement(Connection connection, String sql) throws SQLException {
try (Statement statement = connection.createStatement()) {
return statement.executeUpdate(sql);
} catch (Throwable e) {
throw new SQLException("Failed to execute the SQL statement: " + sql, e);
}
}
/**
* Execute the SQL statements in the file with the specified resource path using the database
* connection.
*
* @param connection the database connection to use
* @param resourcePath the resource path to the file containing the SQL statements
* @return the number of SQL statements successfully executed
* @throws SQLException if the statement execution failed
*/
public static int executeStatements(Connection connection, String resourcePath)
throws SQLException {
int numberOfStatementsExecuted = 0;
try {
List<String> sqlStatements =
loadSQL(Thread.currentThread().getContextClassLoader().getResource(resourcePath));
for (String sqlStatement : sqlStatements) {
System.out.println("EXECUTING: " + sqlStatement);
executeStatement(connection, sqlStatement);
numberOfStatementsExecuted++;
}
return numberOfStatementsExecuted;
} catch (Throwable e) {
throw new SQLException(
"Failed to execute the SQL statements in the resource file (" + resourcePath + ")", e);
}
}
/**
* Retrieve the schema separator for the database associated with the specified data source.
*
* @param dataSource the data source
* @return the schema separator for the database associated with the specified data source
* @throws SQLException if the schema separator could not be retrieved
*/
public static String getSchemaSeparator(DataSource dataSource) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
// Retrieve the schema separator for the database
String schemaSeparator = metaData.getCatalogSeparator();
if ((schemaSeparator == null) || (schemaSeparator.length() == 0)) {
schemaSeparator = ".";
}
return schemaSeparator;
}
}
/**
* Is the database associated with the specified data source an in-memory H2 database.
*
* @param dataSource the data source
* @return <b>true</b> if the database associated with the specified data source is an in-memory
* H2 database or <b>false</b> otherwise
* @throws SQLException if the check for an in-memory H2 database failed
*/
public static boolean isInMemoryH2Database(DataSource dataSource) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
switch (metaData.getDatabaseProductName()) {
case "H2":
return true;
default:
return false;
}
}
}
/**
* Load the SQL statements from the specified URL.
*
* @param url the URL
* @return the SQL statements loaded from the specified URL
* @throws IOException if the SQL statements could not be loaded from the specified URL
*/
public static List<String> loadSQL(URL url) throws IOException {
List<String> sqlStatements = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) {
StringBuilder multiLineBuffer = null;
String line;
while ((line = reader.readLine()) != null) {
/*
* Remove any whitespace at the beginning or end of the line, any newline characters and
* any multiple spaces.
*/
line = cleanSQL(line);
if (line.length() == 0) {
continue;
}
// Only process the line if it is not a SQL comment
if (!line.startsWith("--")) {
// If the line contains a SQL comment then only process the portion before the comment
if (line.contains("--")) {
line = line.substring(0, line.indexOf("--"));
line = line.trim();
}
/*
* NOTE: Removed support for handling multiple SQL statements on a single line that are
* terminated by a ';' delimiter. This is because correctly handling the delimiter
* in single or double quotes is Very Hard (TM).
*/
if (line.endsWith(";")) {
if (multiLineBuffer != null) {
multiLineBuffer.append(" ");
multiLineBuffer.append(line);
sqlStatements.add(multiLineBuffer.toString());
multiLineBuffer = null;
} else {
sqlStatements.add(line);
}
} else {
/*
* The line does not contain the end of a SQL statement which means it is either
* the start of a new multi-line SQL statement or the continuation of an existing
* multi-line SQL statement.
*/
if (multiLineBuffer != null) {
multiLineBuffer.append(" ");
multiLineBuffer.append(line);
} else {
multiLineBuffer = new StringBuilder();
multiLineBuffer.append(line);
}
}
}
}
if ((multiLineBuffer != null) && (StringUtils.hasText(multiLineBuffer.toString()))) {
throw new IOException(
"Failed to process the last SQL statement from the file ("
+ url.getPath()
+ ") since it was not terminated by a ';'");
}
return sqlStatements;
}
}
/**
* Read the blob associated with the column with the specified index from the specified result
* set.
*
* @param rs the result set
* @param index the index of the column containing the blob
* @return the binary data for the BLOB
* @throws SQLException if the blob could not be read
*/
public static byte[] readBlob(ResultSet rs, int index) throws SQLException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedInputStream in = new BufferedInputStream(rs.getBinaryStream(index))) {
int noBytes;
byte[] tmpBuffer = new byte[1024];
while ((noBytes = in.read(tmpBuffer)) != -1) {
baos.write(tmpBuffer, 0, noBytes);
}
return baos.toByteArray();
} catch (IOException e) {
throw new SQLException(
"An IO error occurred while reading the BLOB from the database: " + e.getMessage());
}
}
/**
* Rollback the current transaction on the specified connection.
*
* @param connection the connection to rollback the transaction on
*/
public static void rollback(Connection connection) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException e) {
// Do nothing
}
}
}
/**
* Checks whether the schema with the specified name exists for the database referenced by the
* connection.
*
* @param connection the database connection to use
* @param catalog the catalog name or <b>null</b> if a catalog should not be used
* @param schema the schema name
* @return true if the schema exists or false otherwise
* @throws SQLException if the schema check failed
*/
@SuppressWarnings("resource")
public static boolean schemaExists(Connection connection, String catalog, String schema)
throws SQLException {
if (schema == null) {
throw new SQLException("Failed to check whether the schema (null) exists");
}
DatabaseMetaData metaData = connection.getMetaData();
try (ResultSet rs = metaData.getSchemas()) {
while (rs.next()) {
String tmpCatalog =
StringUtils.hasText(rs.getString("TABLE_CATALOG")) ? rs.getString("TABLE_CATALOG") : "";
String tmpSchema =
StringUtils.hasText(rs.getString("TABLE_SCHEM")) ? rs.getString("TABLE_SCHEM") : "";
if ((catalog == null) || catalog.equalsIgnoreCase(tmpCatalog)) {
if (tmpSchema.equalsIgnoreCase(schema)) {
return true;
}
}
}
}
return false;
}
/**
* Checks whether the schema with the specified name exists for the database referenced by the
* data source.
*
* @param dataSource the data source to use
* @param catalog the catalog name or <b>null</b> if a catalog should not be used
* @param schema the schema name
* @return true if the schema exists or false otherwise
* @throws SQLException if the check for the existing schema failed
*/
@SuppressWarnings("resource")
public static boolean schemaExists(DataSource dataSource, String catalog, String schema)
throws SQLException {
if (schema == null) {
throw new SQLException("Failed to check whether the schema (null) exists");
}
try (Connection connection = dataSource.getConnection()) {
return schemaExists(connection, catalog, schema);
}
}
/**
* Close and release all connections that are currently stored in the connection pool associated
* with the data source.
*
* <p>The HSQLDB database associated with the data source will also be shutdown.
*
* @param connection the HSQLDB database connection
* @throws SQLException if the HSQLDB database could not be shutdown
*/
public static void shutdownHsqlDatabase(Connection connection) throws SQLException {
try (Statement statement = connection.createStatement()) {
// language=H2
statement.executeUpdate("SHUTDOWN");
}
}
/**
* Checks whether the table with the specified name exists under the catalog and schema for the
* database referenced by the data source.
*
* @param connection the database connection to use
* @param catalog the catalog name or <b>null</b> if a catalog should not be used
* @param schema the schema name or <b>null</b> if a schema should not be used
* @param table the name of the table
* @return true if the table exists or false otherwise
* @throws SQLException if the check for the existing table failed
*/
@SuppressWarnings("resource")
public static boolean tableExists(
Connection connection, String catalog, String schema, String table) throws SQLException {
if (table == null) {
throw new SQLException("Failed to check whether the table (null) exists");
}
// First check if the schema exists
if ((schema != null) && (!schemaExists(connection, catalog, schema))) {
return false;
}
DatabaseMetaData metaData = connection.getMetaData();
try (ResultSet rs = metaData.getTables(catalog, schema, table, new String[] {"TABLE"})) {
while (rs.next()) {
String tmpTable =
StringUtils.hasText(rs.getString("TABLE_NAME")) ? rs.getString("TABLE_NAME") : "";
if (table.equals(tmpTable)) {
return true;
}
}
}
return false;
}
/**
* Checks whether the table with the specified name exists under the catalog and schema for the
* database referenced by the data source.
*
* @param dataSource the data source to use
* @param catalog the catalog name or <b>null</b> if a catalog should not be used
* @param schema the schema name or <b>null</b> if a schema should not be used
* @param table the name of the table
* @return true if the table exists or false otherwise
* @throws SQLException if the check for the existing table failed
*/
@SuppressWarnings("resource")
public static boolean tableExists(
DataSource dataSource, String catalog, String schema, String table) throws SQLException {
if (table == null) {
throw new SQLException("Failed to check whether the table (null) exists");
}
try (Connection connection = dataSource.getConnection()) {
return tableExists(connection, catalog, schema, table);
}
}
private static String cleanSQL(String text) {
if (text == null) {
throw new NullPointerException("Failed to clean the null SQL string");
}
// If this is an empty string then stop here
if (text.length() == 0) {
return text;
}
// First remove the new line characters
int index = text.length() - 1;
while ((index >= 0) && ((text.charAt(index) == '\r') || (text.charAt(index) == '\n'))) {
index--;
}
if (index < 0) {
return "";
}
text = text.substring(0, index + 1);
// Replace multiple spaces with a single space
while (text.contains(" ")) {
text = text.replaceAll(" {2}", " ");
}
// Replace tabs with a single space
text = text.replaceAll("\t", " ");
// Strip whitespace from the beginning and end of the text
text = text.trim();
return text;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/JNDIUtil.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.core.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchResult;
/**
* The <b>JNDIUtil</b> class provides JNDI utility functions.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
public final class JNDIUtil {
/**
* Close the JNDIUtil directory context.
*
* @param dirContext the JNDIUtil directory context
*/
public static void close(DirContext dirContext) {
if (dirContext != null) {
try {
dirContext.close();
} catch (Throwable ignored) {
}
}
}
/**
* Close the JNDIUtil search results.
*
* @param searchResults the JNDIUtil search results
*/
public static void close(NamingEnumeration<SearchResult> searchResults) {
if (searchResults != null) {
try {
searchResults.close();
} catch (Throwable ignored) {
}
}
}
/**
* Close the JNDIUtil search result.
*
* @param searchResult the JNDIUtil search result
*/
public static void close(SearchResult searchResult) {
if ((searchResult != null)
&& (searchResult.getObject() != null)
&& (searchResult.getObject() instanceof Context)) {
try {
((Context) searchResult.getObject()).close();
} catch (Throwable ignored) {
}
}
}
/** Dump the contents of the JNDIUtil tree. */
public static void dumpJNDI() {
dumpJNDI(new PrintWriter(System.out));
}
/**
* Dump the contents of the JNDIUtil tree.
*
* @return the contents of the JNDIUtil as a <b>String</b>
*/
public static String dumpJNDIToString() {
StringWriter sw = new StringWriter();
dumpJNDI(new PrintWriter(sw));
return sw.getBuffer().toString();
}
private static void dumpJNDI(PrintWriter pw) {
InitialContext ic = null;
try {
ic = new InitialContext();
TreeDumpStatus treeDumpStatus = new TreeDumpStatus();
pw.println();
pw.println("[]");
pw.println();
dumpNameSpace(pw, treeDumpStatus, ic, "", 1);
pw.println();
pw.println("[java:app]");
pw.println();
dumpNameSpace(pw, treeDumpStatus, ic, "java:app", 1);
pw.println();
pw.println("[java:global]");
pw.println();
dumpNameSpace(pw, treeDumpStatus, ic, "java:global", 1);
pw.println();
pw.println("[java:comp]");
pw.println();
dumpNameSpace(pw, treeDumpStatus, ic, "java:comp", 1);
pw.println();
pw.println("[java:comp/env]");
pw.println();
dumpNameSpace(pw, treeDumpStatus, ic, "java:comp/env", 1);
pw.println();
pw.println("[java:appserver]");
pw.println();
dumpNameSpace(pw, treeDumpStatus, ic, "java:appserver", 1);
pw.println();
} catch (Throwable e) {
pw.println("[ERROR] Failed to dump the JNDIUtil tree: " + e.getMessage());
e.printStackTrace(pw);
} finally {
try {
if (ic != null) {
ic.close();
}
} catch (Throwable ignored) {
}
}
}
private static void dumpNameSpace(
PrintWriter pw, TreeDumpStatus treeDumpStatus, Context context, String path, int depth)
throws NamingException {
StringBuilder indent = new StringBuilder();
for (int i = 0; i < depth; i++) {
indent.append(" ");
}
NamingEnumeration<NameClassPair> nameClassPairs;
try {
nameClassPairs = context.list(path);
} catch (NameNotFoundException e) {
return;
} catch (Throwable e) {
pw.println(
indent
+ "[ERROR] Failed to list the JNDIUtil nodes for the context ("
+ path
+ "): "
+ e.getMessage());
pw.println("");
return;
}
while (nameClassPairs.hasMoreElements()) {
NameClassPair nameClassPair = nameClassPairs.nextElement();
// Process the child node
try {
Object object = InitialContext.doLookup(path + "/" + nameClassPair.getName());
if (!(object instanceof Context)) {
pw.println(
indent
+ nameClassPair.getName()
+ " ["
+ nameClassPair.getClassName()
+ "] = "
+ object);
pw.println();
} else {
boolean processChildren = true;
if (nameClassPair.getName().equals("thisNode") && (depth > 1)) {
processChildren = false;
} else if (nameClassPair.getName().equals("cell")) {
if (treeDumpStatus.foundCell) {
processChildren = false;
} else {
treeDumpStatus.foundCell = true;
}
} else if (nameClassPair.getName().equals("nodes")) {
if (treeDumpStatus.foundNodes) {
processChildren = false;
} else {
treeDumpStatus.foundNodes = true;
}
} else if (nameClassPair.getName().equals("node")) {
if (treeDumpStatus.foundNode) {
processChildren = false;
} else {
treeDumpStatus.foundNode = true;
}
} else if (nameClassPair.getName().equals("servers")) {
if (treeDumpStatus.foundServers) {
processChildren = false;
} else {
treeDumpStatus.foundServers = true;
}
} else if (nameClassPair.getName().equals("clusters")) {
if (treeDumpStatus.foundClusters) {
processChildren = false;
} else {
treeDumpStatus.foundClusters = true;
}
} else if (nameClassPair.getName().equals("persistent")) {
if (treeDumpStatus.foundPersistent) {
processChildren = false;
} else {
treeDumpStatus.foundPersistent = true;
}
} else if (nameClassPair.getName().equals("domain")) {
if (treeDumpStatus.foundDomain) {
processChildren = false;
} else {
treeDumpStatus.foundDomain = true;
}
}
if (processChildren) {
pw.println(
indent
+ nameClassPair.getName()
+ " ["
+ nameClassPair.getClassName()
+ "] = "
+ object);
pw.println();
if (path.length() > 0) {
dumpNameSpace(
pw, treeDumpStatus, context, path + "/" + nameClassPair.getName(), depth + 1);
} else {
dumpNameSpace(pw, treeDumpStatus, context, nameClassPair.getName(), depth + 1);
}
} else {
pw.println(indent + nameClassPair.getName() + " (Duplicate Reference)");
pw.println();
}
}
} catch (Throwable e) {
pw.println(indent + nameClassPair.getName() + " [" + nameClassPair.getClassName() + "]");
pw.println();
}
}
}
static class TreeDumpStatus {
/** foundCell */
boolean foundCell;
/** foundClusters */
boolean foundClusters;
/** foundDomain */
boolean foundDomain;
/** foundNode */
boolean foundNode;
/** foundNodes */
boolean foundNodes;
/** foundPersistent */
boolean foundPersistent;
/** foundServers */
boolean foundServers;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/MobilePhoneNumberUtil.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.core.util;
import java.util.regex.Pattern;
/**
* The <b>MobilePhoneNumberUtil</b> class is a utility class which provides methods for working with
* mobile phone numbers and MSISDNs.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public final class MobilePhoneNumberUtil {
/** The regular expression used to validate an MobilePhoneNumberUtil. */
public static final String MSISDN_VALIDATION_REGEX =
"(9[976]\\d|8[987530]\\d|6[987]\\d|5[90]\\d|42\\d|3[875]\\d|2[98654321]\\d|9[8543210]"
+ "|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\\d{1,14}$";
private static final Pattern msisdnPattern = Pattern.compile(MSISDN_VALIDATION_REGEX);
/**
* Check whether the specified MobilePhoneNumberUtil is valid.
*
* @param msisdn the MobilePhoneNumberUtil
* @return <b>true</b> if the MobilePhoneNumberUtil is valid or <b>false</b> otherwise
*/
public static boolean isValidMSISDN(String msisdn) {
java.util.regex.Matcher matcher = msisdnPattern.matcher(msisdn);
return matcher.matches();
}
// /**
// * Main.
// *
// * @param args the command line arguments
// */
// public static void main(String[] args)
// {
// System.out.println("+27 (0) 83 276 3107 = " + mobilePhoneNumberToMSISDN("+27 (0) 83 276
// 3107",
// "27"));
//
// System.out.println("0832763107 = " + mobilePhoneNumberToMSISDN("0832763107",
// "27"));
//
// System.out.println("083 276 3107 = " + mobilePhoneNumberToMSISDN("083 276 3107",
// "27"));
//
// System.out.println("083-276-3107 = " + mobilePhoneNumberToMSISDN("083-276-3107",
// "27"));
//
// System.out.println("+27832763107 = " + mobilePhoneNumberToMSISDN("+27832763107",
// "27"));
//
// System.out.println("+27 83 276 3107 = " + mobilePhoneNumberToMSISDN("+27 83 276 3107",
// "27"));
//
// System.out.println("27832763107 = " + mobilePhoneNumberToMSISDN("27832763107",
// "27"));
//
// System.out.println("+36 55 002 709 = " + mobilePhoneNumberToMSISDN("+36 55 002 709",
// "27"));
//
// System.out.println("+353 20 910 6402 = " + mobilePhoneNumberToMSISDN("+353 20 910 6402",
// "27"));
//
// System.out.println("+1-202-555-0197 = " + mobilePhoneNumberToMSISDN("+1-202-555-0197",
// "27"));
//
// System.out.println("+1-202-555-0197 = " + mobilePhoneNumberToMSISDN("+1-202-555-0197",
// "27"));
//
// System.out.println("+27 (0) 83 276 3107 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "+27 (0) 83 276 3107", "27")));
//
// System.out.println("0832763107 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "0832763107", "27")));
//
// System.out.println("083 276 3107 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "083 276 3107", "27")));
//
// System.out.println("083-276-3107 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "083-276-3107", "27")));
//
// System.out.println("+27832763107 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "+27832763107", "27")));
//
// System.out.println("+27 83 276 3107 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "+27 83 276 3107", "27")));
//
// System.out.println("27832763107 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "27832763107", "27")));
//
// System.out.println("+36 55 002 709 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "+36 55 002 709", "27")));
//
// System.out.println("+353 20 910 6402 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "+353 20 910 6402", "27")));
//
// System.out.println("+1-202-555-0197 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "+1-202-555-0197", "27")));
//
// System.out.println("+1-202-555-0197 = " + isValidMSISDN(mobilePhoneNumberToMSISDN(
// "+1-202-555-0197", "27")));
// }
/**
* Returns the MobilePhoneNumberUtil for the specified mobile phone number.
*
* @param mobilePhoneNumber the mobile phone number
* @param defaultInternationalPrefix the default international prefix
* @return the MobilePhoneNumberUtil for the mobile phone number
*/
public static String mobilePhoneNumberToMSISDN(
String mobilePhoneNumber, String defaultInternationalPrefix) {
// Remove any plus signs, white space (tabs and spaces) and dashes
mobilePhoneNumber = mobilePhoneNumber.replaceAll("([+\\t -])", "");
// Remove area code prefix e.g. the '(0)' in +27(0)832763107
mobilePhoneNumber = mobilePhoneNumber.replaceFirst("(\\([0-9]*\\))", "");
// Ensure that the default international prefix is applied
mobilePhoneNumber =
mobilePhoneNumber.replaceFirst(
"^(?:" + defaultInternationalPrefix + "|\\+" + defaultInternationalPrefix + "|0)",
defaultInternationalPrefix);
return mobilePhoneNumber;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/MutualSSLSocketFactory.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.core.util;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.KeyStore;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* The <b>MutualSSLSocketFactory</b> class implements the custom SSL socket factory that supports
* Mutual SSL authentication.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class MutualSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory socketFactory;
/**
* Constructs a new <b>MutualSSLSocketFactory</b>
*
* @param keyStore the key store containing the client certificate and private key
* @param keyStorePassword the password required to access the key store
* @param trustStore the trust store
* @param disableServerTrustChecking disable server trust checking
*/
public MutualSSLSocketFactory(
KeyStore keyStore,
String keyStorePassword,
KeyStore trustStore,
boolean disableServerTrustChecking) {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts =
new TrustManager[] {
new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Skip client verification step
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Skip server verification step
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
// Setup the key manager for the mutual SSL socket factory
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
// Setup the trust manager for the mutual SSL socket factory
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
// Setup the SSL contxt
SSLContext sslContext = SSLContext.getInstance("TLS");
if (disableServerTrustChecking) {
sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, new SecureRandom());
} else {
sslContext.init(
keyManagerFactory.getKeyManagers(),
trustManagerFactory.getTrustManagers(),
new SecureRandom());
}
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
/*
* Retrieve the socket factory from the SSL context that will be used to create the MutualSSL
* connections.
*/
socketFactory = sslContext.getSocketFactory();
} catch (Throwable e) {
throw new MutualSSLSocketFactoryException(
"Failed to initialize the Mutual SSL socket factory", e);
}
}
/**
* Returns <b>true</b> if we are running under the IBM JDK or <b>false</b> otherwise.
*
* @return <b>true</b> if we are running under the IBM JDK or <b>false</b> otherwise
*/
public static boolean isIBMJDK() {
for (Provider provider : Security.getProviders()) {
if (provider.getName().startsWith("IBMJSSE")) {
return true;
}
}
return false;
}
/**
* Creates a socket and connects it to the specified port number at the specified address.
*
* <p>This socket is configured using the socket options established for this factory. If there is
* a security manager, its <b>checkConnect</b> method is called with the host address and port as
* its arguments. This could result in a <b>SecurityException</b>.
*
* @param host the address of the server host
* @param port the server port
* @return a socket connected to the specified host and port
*/
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return socketFactory.createSocket(host, port);
}
/**
* Creates a socket and connects it to the specified remote host at the specified remote port.
*
* <p>This socket is configured using the socket options established for this factory. If there is
* a security manager, its <b>checkConnect</b> method is called with the host address and port as
* its arguments. This could result in a <b>SecurityException</b>.
*
* @param host the server host
* @param port the server port
* @return a socket connected to the specified host and port
*/
@Override
public Socket createSocket(String host, int port) throws IOException {
return socketFactory.createSocket(host, port);
}
/**
* Creates a socket and connects it to the specified port number at the specified address. The
* socket will also be bound to the local address and port supplied.
*
* <p>This socket is configured using the socket options established for this factory. If there is
* a security manager, its <b>checkConnect</b> method is called with the host address and port as
* its arguments. This could result in a <b>SecurityException</b>.
*
* @param host the address of the server host
* @param port the server port
* @param localHost the local address
* @param localPort the local port
* @return a socket connected to the specified host and port
*/
@Override
public Socket createSocket(InetAddress host, int port, InetAddress localHost, int localPort)
throws IOException {
return socketFactory.createSocket(host, port, localHost, localPort);
}
/**
* Returns a socket layered over an existing socket connected to the named host, at the given
* port.
*
* <p>This constructor can be used when tunneling SSL through a proxy or when negotiating the use
* of SSL over an existing socket. The host and port refer to the logical peer destination. This
* socket is configured using the socket options established for this factory.
*
* @param s the existing socket
* @param host the server host
* @param port the server port
* @param autoClose close the underlying socket when this socket is closed
* @return a socket connected to the specified host and port
*/
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose)
throws IOException {
return socketFactory.createSocket(s, host, port, autoClose);
}
/**
* Creates a socket and connects it to the specified remote host at the specified remote port. The
* socket will also be bound to the local address and port supplied.
*
* <p>This socket is configured using the socket options established for this factory. If there is
* a security manager, its <b>checkConnect</b> method is called with the host address and port as
* its arguments. This could result in a <b>SecurityException</b>.
*
* @param host the server host
* @param port the server port
* @param localHost the local address
* @param localPort the local port
* @return a socket connected to the specified host and port
*/
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
throws IOException {
return socketFactory.createSocket(host, port, localHost, localPort);
}
/**
* Returns the cipher suites which are enabled by default.
*
* <p>Unless a different list is enabled, handshaking on an SSL connection will use one of these
* cipher suites. The minimum quality of service for these defaults requires confidentiality
* protection and server authentication (that is, no anonymous cipher suites).
*
* @return the cipher suites which are enabled by default
*/
@Override
public String[] getDefaultCipherSuites() {
return socketFactory.getDefaultCipherSuites();
}
/**
* Returns the names of the cipher suites which could be enabled for use on an SSL connection.
*
* <p>Normally, only a subset of these will actually be enabled by default, since this list may
* include cipher suites which do not meet quality of service requirements for those defaults.
* Such cipher suites are useful in specialized applications.
*
* @return the names of the cipher suites which could be enabled for use on an SSL connection
*/
@Override
public String[] getSupportedCipherSuites() {
return socketFactory.getSupportedCipherSuites();
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/MutualSSLSocketFactoryException.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.core.util;
/**
* The <b>MutualSSLSocketFactoryException</b> exception is thrown to indicate an error when working
* with the <b>MutualSSLSocketFactory</b>.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class MutualSSLSocketFactoryException extends RuntimeException {
private static final long serialVersionUID = 1000000;
/** Constructs a new <b>MutualSSLSocketFactoryException</b> with <b>null</b> as its message. */
public MutualSSLSocketFactoryException() {
super();
}
/**
* Constructs a new <b>MutualSSLSocketFactoryException</b> with the specified message.
*
* @param message The message saved for later retrieval by the <b>getMessage()</b> method.
*/
public MutualSSLSocketFactoryException(String message) {
super(message);
}
/**
* Constructs a new <b>MutualSSLSocketFactoryException</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 MutualSSLSocketFactoryException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/NetworkUtil.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.core.util;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
/**
* The <b>NetworkUtil</b> class is a utility class which provides network-related utility methods.
*
* @author Marcus Portmann
*/
public class NetworkUtil {
/**
* Returns an <b>InetAddress</b> object encapsulating what is most likely the machine's LAN IP
* address.
*
* <p>This method is intended for use as a replacement of JDK method <b>
* InetAddress.getLocalHost</b>, because that method is ambiguous on Linux systems. Linux systems
* enumerate the loopback network interface the same way as regular LAN network interfaces, but
* the JDK <b>InetAddress.getLocalHost</b> method does not specify the algorithm used to select
* the address returned under such circumstances, and will often return the loopback address,
* which is not valid for network communication. Details <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037">here</a>.
*
* <p>This method will scan all IP addresses on all network interfaces on the host machine to
* determine the IP address most likely to be the machine's LAN address. If the machine has
* multiple IP addresses, this method will prefer a site-local IP address (e.g. 192.168.x.x or
* 10.10.x.x, usually IPv4) if the machine has one (and will return the first site-local address
* if the machine has more than one), but if the machine does not hold a site-local address, this
* method will return simply the first non-loopback address found (IPv4 or IPv6).
*
* <p>If this method cannot find a non-loopback address using this selection algorithm, it will
* fall back to calling and returning the result of JDK method <b>InetAddress.getLocalHost</b>.
*
* @return the LAN IP address
* @throws UnknownHostException the LAN IP address could not be retrieved
*/
public static InetAddress getLocalHostLANAddress() throws UnknownHostException {
try {
InetAddress candidateAddress = null;
// Iterate all NICs (network interface cards)
for (Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
networkInterfaces.hasMoreElements(); ) {
NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
// Iterate all IP addresses assigned to each card
for (Enumeration inetAddresses = networkInterface.getInetAddresses();
inetAddresses.hasMoreElements(); ) {
InetAddress inetAddress = (InetAddress) inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress()) {
if (inetAddress.isSiteLocalAddress()) {
// Found non-loopback site-local address. Return it immediately
return inetAddress;
} else if (candidateAddress == null) {
// Found non-loopback address, but not necessarily site-local.
// Store it as a candidate to be returned if site-local address is not subsequently
// found...
candidateAddress = inetAddress;
// Note that we don't repeatedly assign non-loopback non-site-local addresses as
// candidates,
// only the first. For subsequent iterations, candidate will be non-null.
}
}
}
}
if (candidateAddress != null) {
// We did not find a site-local address, but we found some other non-loopback address.
// Server might have a non-site-local address assigned to its NIC (or it might be running
// IPv6 which deprecates the "site-local" concept).
// Return this non-loopback candidate address
return candidateAddress;
}
// At this point, we did not find a non-loopback address.
// Fall back to returning whatever InetAddress.getLocalHost() returns...
InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
if (jdkSuppliedAddress == null) {
throw new UnknownHostException(
"The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
}
return jdkSuppliedAddress;
} catch (Throwable e) {
UnknownHostException unknownHostException =
new UnknownHostException("Failed to determine LAN address: " + e);
unknownHostException.initCause(e);
throw unknownHostException;
}
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/NoTrustSSLSocketFactory.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.core.util;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* The <b>NoTrustSSLSocketFactory</b> class implements the no-trust SSL socket factory.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class NoTrustSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory socketFactory;
/** Constructs a new <b>NoTrustSSLSocketFactory</b> */
public NoTrustSSLSocketFactory() {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts =
new TrustManager[] {
new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Skip client verification step
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// Skip server verification step
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
};
// Setup the SSL contxt
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(new KeyManager[0], trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
/*
* Retrieve the socket factory from the SSL context that will be used to create the MutualSSL
* connections.
*/
socketFactory = sslContext.getSocketFactory();
} catch (Throwable e) {
throw new RuntimeException("Failed to initialize the no-trust SSL socket factory", e);
}
}
/**
* Creates a socket and connects it to the specified port number at the specified address.
*
* <p>This socket is configured using the socket options established for this factory. If there is
* a security manager, its <b>checkConnect</b> method is called with the host address and port as
* its arguments. This could result in a <b>SecurityException</b>.
*
* @param host the address of the server host
* @param port the server port
* @return a socket connected to the specified host and port
*/
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return socketFactory.createSocket(host, port);
}
/**
* Creates a socket and connects it to the specified remote host at the specified remote port.
*
* <p>This socket is configured using the socket options established for this factory. If there is
* a security manager, its <b>checkConnect</b> method is called with the host address and port as
* its arguments. This could result in a <b>SecurityException</b>.
*
* @param host the server host
* @param port the server port
* @return a socket connected to the specified host and port
*/
@Override
public Socket createSocket(String host, int port) throws IOException {
return socketFactory.createSocket(host, port);
}
/**
* Creates a socket and connects it to the specified port number at the specified address. The
* socket will also be bound to the local address and port supplied.
*
* <p>This socket is configured using the socket options established for this factory. If there is
* a security manager, its <b>checkConnect</b> method is called with the host address and port as
* its arguments. This could result in a <b>SecurityException</b>.
*
* @param host the address of the server host
* @param port the server port
* @param localHost the local address
* @param localPort the local port
* @return a socket connected to the specified host and port
*/
@Override
public Socket createSocket(InetAddress host, int port, InetAddress localHost, int localPort)
throws IOException {
return socketFactory.createSocket(host, port, localHost, localPort);
}
/**
* Returns a socket layered over an existing socket connected to the named host, at the given
* port.
*
* <p>This constructor can be used when tunneling SSL through a proxy or when negotiating the use
* of SSL over an existing socket. The host and port refer to the logical peer destination. This
* socket is configured using the socket options established for this factory.
*
* @param s the existing socket
* @param host the server host
* @param port the server port
* @param autoClose close the underlying socket when this socket is closed
* @return a socket connected to the specified host and port
*/
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose)
throws IOException {
return socketFactory.createSocket(s, host, port, autoClose);
}
/**
* Creates a socket and connects it to the specified remote host at the specified remote port. The
* socket will also be bound to the local address and port supplied.
*
* <p>This socket is configured using the socket options established for this factory. If there is
* a security manager, its <b>checkConnect</b> method is called with the host address and port as
* its arguments. This could result in a <b>SecurityException</b>.
*
* @param host the server host
* @param port the server port
* @param localHost the local address
* @param localPort the local port
* @return a socket connected to the specified host and port
*/
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
throws IOException {
return socketFactory.createSocket(host, port, localHost, localPort);
}
/**
* Returns the set of cipher suites which are enabled by default.
*
* <p>Unless a different list is enabled, handshaking on an SSL connection will use one of these
* cipher suites. The minimum quality of service for these defaults requires confidentiality
* protection and server authentication (that is, no anonymous cipher suites).
*
* @return the set of cipher suites which are enabled by default
*/
@Override
public String[] getDefaultCipherSuites() {
return socketFactory.getDefaultCipherSuites();
}
/**
* Returns the names of the cipher suites which could be enabled for use on an SSL connection.
*
* <p>Normally, only a subset of these will actually be enabled by default, since this list may
* include cipher suites which do not meet quality of service requirements for those defaults.
* Such cipher suites are useful in specialized applications.
*
* @return the names of the cipher suites which could be enabled for use on an SSL connection
*/
@Override
public String[] getSupportedCipherSuites() {
return socketFactory.getSupportedCipherSuites();
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/PasswordUtil.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.core.util;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* The <b>PasswordUtil</b> class is a utility class which provides password-related utility methods.
*
* @author Marcus Portmann
*/
public class PasswordUtil {
/** Special characters allowed in password. */
private static final String ALLOWED_SPL_CHARACTERS = "!@#$%^&*()_+";
/** The secure random number generator. */
private static final Random random = new SecureRandom();
/**
* Create the SHA-512 hash of the specified password.
*
* @param password the password to hash
* @return the SHA-512 hash of the password
*/
public static final String createPasswordHash(String password) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(password.getBytes(StandardCharsets.ISO_8859_1), 0, password.length());
return Base64Util.encodeBytes(md.digest());
} catch (Throwable e) {
throw new RuntimeException(
String.format("Failed to generate a SHA-512 hash of the password (%s)", password), e);
}
}
/**
* Generate a random password.
*
* @return the random password
*/
public static String generateRandomPassword() {
Stream<Character> pwdStream =
Stream.concat(
getRandomNumbers(2),
Stream.concat(
getRandomSpecialChars(2),
Stream.concat(getRandomAlphabets(2, true), getRandomAlphabets(4, false))));
List<Character> charList = pwdStream.collect(Collectors.toList());
Collections.shuffle(charList);
String password =
charList.stream()
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
return password;
}
private static Stream<Character> getRandomAlphabets(int count, boolean upperCase) {
IntStream characters = null;
if (upperCase) {
characters = random.ints(count, 65, 90);
} else {
characters = random.ints(count, 97, 122);
}
return characters.mapToObj(data -> (char) data);
}
private static Stream<Character> getRandomNumbers(int count) {
IntStream numbers = random.ints(count, 48, 57);
return numbers.mapToObj(data -> (char) data);
}
private static Stream<Character> getRandomSpecialChars(int count) {
IntStream specialChars = random.ints(count, 33, 45);
return specialChars.mapToObj(data -> (char) data);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/RandomStringGenerator.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.core.util;
import java.security.SecureRandom;
import java.util.Objects;
import java.util.Random;
/**
* The <b>RandomStringGenerator</b> class is a utility class that provides the capability to
* generate random alphanumeric strings.
*
* @author Marcus Portmann
*/
public class RandomStringGenerator {
private static final String DIGITS = "0123456789";
private static final String UPPER_CASE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWER_CASE_CHARACTERS = UPPER_CASE_CHARACTERS.toLowerCase();
private static final String ALPHANUMERIC = UPPER_CASE_CHARACTERS + LOWER_CASE_CHARACTERS + DIGITS;
private final char[] buf;
private final Random random;
private final char[] symbols;
/**
* Constructs a new <b>RandomStringGenerator</b> that can be used to generate session identifiers.
*/
public RandomStringGenerator() {
this(21);
}
/**
* Constructs a new <b>RandomStringGenerator</b>.
*
* @param length the length of the random strings that should be generated
*/
public RandomStringGenerator(int length) {
this(length, new SecureRandom());
}
/**
* Constructs a new <b>RandomStringGenerator</b>.
*
* @param length the length of the random strings that should be generated
* @param random the random number generator
*/
public RandomStringGenerator(int length, Random random) {
this(length, random, ALPHANUMERIC);
}
/**
* Constructs a new <b>RandomStringGenerator</b>.
*
* @param length the length of the random strings that should be generated
* @param random the random number generator
* @param symbols the symbols to use when generating the random string
*/
public RandomStringGenerator(int length, Random random, String symbols) {
if (length < 1) {
throw new IllegalArgumentException();
}
if (symbols.length() < 2) {
throw new IllegalArgumentException();
}
this.random = Objects.requireNonNull(random);
this.symbols = symbols.toCharArray();
this.buf = new char[length];
}
/**
* Generate the next random alphanumeric string.
*
* @return the next random alphanumeric string
*/
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx) {
buf[idx] = symbols[random.nextInt(symbols.length)];
}
return new String(buf);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/ResourceException.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.core.util;
/**
* The <b>ResourceException</b> exception is thrown to indicate an error when working with
* resources.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class ResourceException extends RuntimeException {
private static final long serialVersionUID = 1000000;
/** Constructs a new <b>ResourceException</b> with <b>null</b> as its message. */
public ResourceException() {
super();
}
/**
* Constructs a new <b>ResourceException</b> with the specified message.
*
* @param message The message saved for later retrieval by the <b>getMessage()</b> method.
*/
public ResourceException(String message) {
super(message);
}
/**
* Constructs a new <b>ResourceException</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 ResourceException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/ResourceUtil.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.core.util;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
* The <b>ResourceUtil</b> class is a utility class which provides methods for working with
* resources.
*
* @author Marcus Portmann
*/
public final class ResourceUtil {
/**
* Confirms whether the resource with the specified path exists on the classpath using the context
* class loader.
*
* @param path the classpath path for the resource
* @return <b>true</b> if the resource with the specified path exists on the classpath or
* <b>false</b> otherwise.
*/
public static boolean classpathResourceExists(String path) {
try {
return Thread.currentThread().getContextClassLoader().getResource(path) != null;
} catch (Throwable e) {
return false;
}
}
/**
* Retrieves the resource with the specified path on the classpath using the context class loader.
*
* @param path the path to the resource on the classpath
* @return the resource with the specified path on the classpath using the context class loader
*/
public static byte[] getClasspathResource(String path) {
try {
try (InputStream is =
Thread.currentThread().getContextClassLoader().getResourceAsStream(path)) {
if (is == null) {
throw new ResourceException(
"Failed to read the classpath resource ("
+ path
+ "): The resource could not be found");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int numberOfBytesRead;
while ((numberOfBytesRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, numberOfBytesRead);
}
return baos.toByteArray();
}
} catch (ResourceException e) {
throw e;
} catch (Throwable e) {
throw new ResourceException("Failed to read the classpath resource (" + path + ")", e);
}
}
/**
* Retrieves the URL for the resource with the specified path on the classpath using the context
* class loader.
*
* @param path the path to the resource on the classpath
* @return the URL for the resource with the specified path on the classpath using the context
* class loader
*/
public static URL getClasspathResourceURL(String path) {
try {
return Thread.currentThread().getContextClassLoader().getResource(path);
} catch (Throwable e) {
throw new ResourceException(
"Failed to retrieve the URL for the classpath resource (" + path + ")", e);
}
}
/**
* Retrieves the resource with the specified path on the classpath using the context class loader.
*
* @param path the path to the resource on the classpath
* @return the resource with the specified path on the classpath using the context class loader
*/
public static String getStringClasspathResource(String path) {
byte[] data = getClasspathResource(path);
return new String(data, StandardCharsets.UTF_8);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/util/ServiceUtil.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.core.util;
import javax.naming.InitialContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <b>ServiceUtil</b> class provides utility methods that are useful when creating internal
* application services.
*/
public class ServiceUtil {
/* Logger */
private static final Logger logger = LoggerFactory.getLogger(ServiceUtil.class);
/**
* Retrieve the service instance name for the service with the specified name.
*
* @param serviceName the service name
* @return the service instance name for the service with the specified name
*/
public static String getServiceInstanceName(String serviceName) {
String applicationName = null;
try {
applicationName = InitialContext.doLookup("java:app/AppName");
} catch (Throwable ignored) {
}
if (applicationName == null) {
try {
applicationName = InitialContext.doLookup("java:comp/env/ApplicationName");
} catch (Throwable ignored) {
}
}
String instanceName = (applicationName == null) ? "" : applicationName + "::";
try {
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
instanceName += localMachine.getHostName().toLowerCase();
} catch (Throwable e) {
logger.error(
String.format(
"Failed to retrieve the server hostname while constructing the %s instance name",
serviceName),
e);
instanceName = "Unknown";
}
// Check if we are running under JBoss and if so retrieve the server name
if (System.getProperty("jboss.server.name") != null) {
instanceName = instanceName + "::" + System.getProperty("jboss.server.name");
}
// Check if we are running under Glassfish and if so retrieve the server name
else if (System.getProperty("glassfish.version") != null) {
instanceName = instanceName + "::" + System.getProperty("com.sun.aas.instanceName");
}
// Check if we are running under WebSphere Application Server Community Edition (Geronimo)
else if (System.getProperty("org.apache.geronimo.server.dir") != null) {
instanceName = instanceName + "::Geronimo";
}
// Check if we are running under WebSphere Application Server Liberty Profile
else if (System.getProperty("wlp.user.dir") != null) {
instanceName = instanceName + "::WLP";
}
/*
* Check if we are running under WebSphere and if so execute the code below to retrieve the
* server name.
*/
else {
Class<?> clazz = null;
try {
clazz =
Thread.currentThread()
.getContextClassLoader()
.loadClass("com.ibm.websphere.management.configservice.ConfigurationService");
} catch (Throwable ignored) {
}
if (clazz != null) {
try {
instanceName = instanceName + "::" + InitialContext.doLookup("servername").toString();
} catch (Throwable e) {
logger.error(
String.format(
"Failed to retrieve the name of the WebSphere server instance from JNDI while "
+ "constructing the %s instance name",
serviceName),
e);
instanceName = instanceName + "::Unknown";
}
}
}
return instanceName;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/validation/ValidationConfiguration.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.core.validation;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
/**
* The <b>ValidationConfiguration</b> class provides access to the JSR-303 validation configuration
* and initialises the JSR-303 validator.
*
* @author Marcus Portmann
*/
@Configuration
public class ValidationConfiguration {
/**
* Returns the local validator factory bean.
*
* @return the local validator factory bean
*/
@Bean
public static LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
factoryBean.setMessageInterpolator(
BeanUtils.instantiateClass(ParameterMessageInterpolator.class));
return factoryBean;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/xml/DtdJarResolver.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.core.xml;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
/**
* The <b>DdtJarResolver</b> allows the SAX parser to resolve DTD's stored in a JAR file.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class DtdJarResolver implements EntityResolver {
private final String dtdPath;
private final String systemId;
private String publicId;
/**
* Constructs a new <b>DTDJarResolver</b>.
*
* @param systemId the system ID for the DTD
* @param dtdPath the path on the classpath to the DTD
*/
public DtdJarResolver(String systemId, String dtdPath) {
this.systemId = systemId;
this.dtdPath = dtdPath;
}
/**
* Constructs a new <b>DTDJarResolver</b>.
*
* @param publicId the public ID for the DTD
* @param systemId the system ID for the DTD
* @param dtdPath the path on the classpath to the DTD
*/
public DtdJarResolver(String publicId, String systemId, String dtdPath) {
this.publicId = publicId;
this.systemId = systemId;
this.dtdPath = dtdPath;
}
/**
* Returns the public ID for the DTD.
*
* @return the public ID for the DTD
*/
public String getPublicId() {
return publicId;
}
/**
* Returns the system ID for the DTD.
*
* @return the system ID for the DTD
*/
public String getSystemId() {
return systemId;
}
/**
* Resolve the XML entity with the specified public ID and system ID. This method returns an
* InputSource that can be used to read the data for the DTD.
*
* @param publicId the public ID for the DTD
* @param systemId the system ID for the DTD
* @return an InputSource that can be used to read the data for the DTD
*/
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(
Thread.currentThread().getContextClassLoader().getResourceAsStream(dtdPath));
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/xml/XmlParserErrorHandler.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.core.xml;
import org.slf4j.Logger;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXParseException;
/**
* The <b>XmlParserErrorHandler</b> class handles warnings and errors that arise while parsing an
* XML document.
*
* @author Marcus Portmann
*/
public class XmlParserErrorHandler implements ErrorHandler {
private Logger logger = null;
/** Constructs a new <b>XmlParserErrorHandler</b>. */
public XmlParserErrorHandler() {}
/**
* Constructs a new <b>XmlParserErrorHandler</b> using the specified <b>Logger</b>.
*
* @param logger the logger to use to log errors and warnings
*/
@SuppressWarnings("unused")
public XmlParserErrorHandler(Logger logger) {
this.logger = logger;
}
/**
* Process an error that occurred while parsing the XML.
*
* @param e the exception containing the error details
*/
public void error(SAXParseException e) {
if (logger != null) {
logger.error(buildLogMessage(e));
}
throw new XmlParserException(e);
}
/**
* Process a fatal error that occurred while parsing the XML.
*
* @param e the exception containing the fatal error details
*/
public void fatalError(SAXParseException e) {
if (logger != null) {
logger.error(buildLogMessage(e));
}
throw new XmlParserException(e);
}
/**
* Process a warning that occurred while parsing the XML.
*
* @param e the exception containing the warning details
*/
public void warning(SAXParseException e) {
if (logger != null) {
logger.warn(buildLogMessage(e));
}
}
private String buildLogMessage(SAXParseException e) {
StringBuilder buffer = new StringBuilder();
buffer.append(e.getMessage());
buffer.append("\n\tat line (");
buffer.append(e.getLineNumber());
buffer.append(") and column (");
buffer.append(e.getColumnNumber());
buffer.append(")\n");
if ((e.getSystemId() != null) && (e.getPublicId() != null)) {
buffer.append("\twith SystemID (");
buffer.append(e.getSystemId());
buffer.append(") and PublicID (");
buffer.append(e.getPublicId());
buffer.append(")");
} else if (e.getSystemId() != null) {
buffer.append("\twith SystemID (");
buffer.append(e.getSystemId());
buffer.append(")");
} else if (e.getPublicId() != null) {
buffer.append("\twith PublicID (");
buffer.append(e.getPublicId());
buffer.append(")");
}
return buffer.toString();
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/xml/XmlParserException.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.core.xml;
import africa.absa.inception.core.exception.RichRuntimeException;
import org.xml.sax.SAXParseException;
/**
* The <b>XmlParserException</b> exception is thrown to indicate an error condition when parsing an
* XML file.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
public class XmlParserException extends RichRuntimeException {
private static final long serialVersionUID = 1000000;
/** Constructs a new <b>XmlParserException</b> with <b>null</b> as its message. */
public XmlParserException() {
super();
}
/**
* Constructs a new <b>XmlParserException</b> using the information contained in the specified
* <b>SAXParseException</b>.
*
* @param cause the <b>SAXParseException</b> giving the cause of the exception
*/
public XmlParserException(SAXParseException cause) {
super(
cause.getMessage()
+ " at line ("
+ cause.getLineNumber()
+ ") and column ("
+ (cause.getColumnNumber()
+ ") with SystemID ("
+ ((cause.getSystemId() != null) ? cause.getSystemId() : "UNKNOWN")
+ ") and PublicID ("
+ ((cause.getPublicId() != null) ? cause.getPublicId() : "UNKNOWN")
+ ")"));
}
/**
* Constructs a new <b>XmlParserException</b> with the specified message.
*
* @param message The message saved for later retrieval by the <b>getMessage()</b> method.
*/
public XmlParserException(String message) {
super(message);
}
/**
* Constructs a new <b>XmlParserException</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 XmlParserException(Throwable cause) {
super(cause);
}
/**
* Constructs a new <b>XmlParserException</b> with the specified code and message.
*
* @param code the error code
* @param message The message saved for later retrieval by the <b>getMessage()</b> method.
*/
public XmlParserException(String code, String message) {
super(code, message);
}
/**
* Constructs a new <b>XmlParserException</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 XmlParserException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new <b>XmlParserException</b> with the specified code, message and cause.
*
* @param code the error code
* @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 XmlParserException(String code, String message, Throwable cause) {
super(code, message, cause);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/xml/XmlSchemaClasspathInputSource.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.core.xml;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.Reader;
import org.w3c.dom.ls.LSInput;
/**
* The <b>XmlSchemaClasspathInputSource</b> class provides an implementation of the <b>
* org.w3c.dom.ls.LSInput</b> interface that allows resources to be retrieved from the classpath.
*
* @author Marcus Portmann
*/
public class XmlSchemaClasspathInputSource implements LSInput {
/** The namespace for this input source. */
private final String namespaceURI;
/** The base URI to be used for resolving a relative systemId to an absolute URI. */
private String baseURI;
/** Is the input source certified? */
private boolean certifiedText;
/** The data for the input source. */
private byte[] data;
/** The character encoding for the input source. */
private String encoding;
/** The public identifier for this input source. */
private String publicId;
/** The system identifier for this input source. */
private String systemId;
/**
* Constructs a new <b>XmlSchemaClasspathInputSource</b>.
*
* @param namespaceURI the namespace for this input source
* @param publicId the public identifier for this input source.
* @param systemId the system identifier for this input source
* @param baseURI the base URI to be used for resolving a relative systemId to an absolute URI
* @param classpathName the name of the resource on the classpath for this input source
*/
public XmlSchemaClasspathInputSource(
String namespaceURI, String publicId, String systemId, String baseURI, String classpathName) {
this.namespaceURI = namespaceURI;
this.publicId = publicId;
this.systemId = systemId;
this.baseURI = baseURI;
this.certifiedText = false;
try {
try (InputStream is =
Thread.currentThread().getContextClassLoader().getResourceAsStream(classpathName)) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int numberOfBytesRead;
while ((numberOfBytesRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, numberOfBytesRead);
}
this.data = baos.toByteArray();
}
} catch (Throwable e) {
throw new XmlSchemaException(
"Failed to read the classpath resource (" + classpathName + ") for the input source", e);
}
}
/**
* Returns the base URI to be used for resolving a relative systemId to an absolute URI.
*
* @return the base URI to be used for resolving a relative systemId to an absolute URI
*/
@Override
public String getBaseURI() {
return baseURI;
}
/**
* Returns the <b>InputStream</b> for the input source.
*
* @return the <b>InputStream</b> for the input source
*/
@Override
public InputStream getByteStream() {
return new ByteArrayInputStream(data);
}
/**
* Returns <b>true</b> if the input source is certified or <b>false</b> otherwise.
*
* @return <b>true</b> if the input source is certified or <b>false</b> otherwise
*/
@Override
public boolean getCertifiedText() {
return certifiedText;
}
/**
* Returns the character stream for the input source.
*
* @return the character stream for the input source
*/
@Override
public Reader getCharacterStream() {
return null;
}
/**
* Returns the character encoding for the input source.
*
* @return the character encoding for the input source
*/
@Override
public String getEncoding() {
return encoding;
}
/**
* Returns the namespace for this input source.
*
* @return the namespace for this input source
*/
public String getNamespaceURI() {
return namespaceURI;
}
/**
* Returns the public identifier for this input source.
*
* @return the public identifier for this input source
*/
@Override
public String getPublicId() {
return publicId;
}
/**
* Returns the <b>String</b> data for the input source
*
* @return the <b>String</b> data for the input source
*/
@Override
public String getStringData() {
return null;
}
/**
* Returns the system identifier for this input source.
*
* @return the system identifier for this input source
*/
@Override
public String getSystemId() {
return systemId;
}
/**
* Set the base URI to be used for resolving a relative systemId to an absolute URI.
*
* @param baseURI the base URI to be used for resolving a relative systemId to an absolute URI
*/
@Override
public void setBaseURI(String baseURI) {
this.baseURI = baseURI;
}
/**
* Set the byte stream for the input source.
*
* @param byteStream the byte stream for the input source
*/
@Override
public void setByteStream(InputStream byteStream) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int numberOfBytesRead;
while ((numberOfBytesRead = byteStream.read(buffer)) != -1) {
baos.write(buffer, 0, numberOfBytesRead);
}
this.data = baos.toByteArray();
} catch (Throwable e) {
throw new XmlSchemaException(
"Failed to read the data from the byte stream for the input source", e);
}
}
/**
* Set whether the input source is certified.
*
* @param certifiedText <b>true</b> if the input source is certified or <b>false</b> otherwise
*/
@Override
public void setCertifiedText(boolean certifiedText) {
this.certifiedText = certifiedText;
}
/**
* Set the character stream for the input source
*
* @param characterStream the character stream for the input source
*/
@Override
public void setCharacterStream(Reader characterStream) {
throw new XmlSchemaException(
"Reading the data for the input source from a character stream is not supported");
}
/**
* Set the character encoding for the input source.
*
* @param encoding the character encoding for the input source
*/
@Override
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Set the public identifier for this input source.
*
* @param publicId the public identifier for this input source
*/
@Override
public void setPublicId(String publicId) {
this.publicId = publicId;
}
/**
* Set the <b>String</b> data for the input source.
*
* @param stringData the <b>String</b> data for the input source
*/
@Override
public void setStringData(String stringData) {
throw new XmlSchemaException(
"Reading the data for the input source from a string is not supported");
}
/**
* Set the system identifier for this input source.
*
* @param systemId the system identifier for this input source
*/
@Override
public void setSystemId(String systemId) {
this.systemId = systemId;
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/xml/XmlSchemaException.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.core.xml;
/**
* The <b>XmlSchemaException</b> exception is thrown to indicate an error condition when working
* with an XML schema.
*
* @author Marcus Portmann
*/
public class XmlSchemaException extends RuntimeException {
private static final long serialVersionUID = 1000000;
/** Constructs a new <b>XmlSchemaException</b> with <b>null</b> as its message. */
public XmlSchemaException() {
super();
}
/**
* Constructs a new <b>XmlSchemaException</b> with the specified message.
*
* @param message The message saved for later retrieval by the <b>getMessage()</b> method.
*/
public XmlSchemaException(String message) {
super(message);
}
/**
* Constructs a new <b>XmlSchemaException</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 XmlSchemaException(Throwable cause) {
super(cause);
}
/**
* Constructs a new <b>XmlSchemaException</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 XmlSchemaException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core
|
java-sources/africa/absa/inception-core/1.2.0/africa/absa/inception/core/xml/XmlUtil.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.core.xml;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Optional;
import javax.xml.XMLConstants;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import org.springframework.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* The <b>XmlUtil</b> class provides utility methods for working with XML documents.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class XmlUtil {
/**
* The <b>DatatypeFactory</b> instance used to convert java.xml.datatype object that map XML
* to/from Java objects.
*/
private static final DatatypeFactory datatypeFactory;
static {
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
throw new IllegalStateException("Failed to create a new DatatypeFactory instance", e);
}
}
/**
* Converts a <b>javax.xml.datatype.XMLGregorianCalendar</b> instance to a <b>java.util.Date</b>
* instance.
*
* @param calendar the <b>javax.xml.datatype.XMLGregorianCalendar</b> instance to convert
* @return the converted <b>java.util.Date</b> instance
*/
public static java.util.Date asDate(XMLGregorianCalendar calendar) {
if (calendar == null) {
return null;
} else {
return calendar.toGregorianCalendar().getTime();
}
}
/**
* Converts a <b>java.util.Date</b> instance to a <b>javax.xml.datatype.XMLGregorianCalendar</b>
* instance.
*
* @param date the <b>java.util.Date</b> instance to convert
* @return the converted <b>javax.xml.datatype.XMLGregorianCalendar</b> instance
*/
public static XMLGregorianCalendar asXMLGregorianCalendar(java.util.Date date) {
if (date == null) {
return null;
} else {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(date.getTime());
return datatypeFactory.newXMLGregorianCalendar(calendar);
}
}
/**
* Returns the child element with the specified name for the specified element.
*
* @param element the parent element
* @param name the name of the child element to return
* @return an Optional containing the child element or an empty Optional if a child element with
* the specified name could not be found
*/
public static Optional<Element> getChildElement(Element element, String name) {
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Element childElement = (Element) node;
if (childElement.getNodeName().equals(name)) {
return Optional.of(childElement);
}
}
}
return Optional.empty();
}
/**
* Returns the boolean value of the text content for the child element with the specified name for
* the specified element.
*
* @param element the parent element
* @param name the name of the child element to return
* @return an Optional containing the boolean value of the text content for the child element or
* an empty Optional if a child element with the specified name could not be found
*/
public static Optional<Boolean> getChildElementBoolean(Element element, String name) {
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Element childElement = (Element) node;
if (childElement.getNodeName().equals(name)) {
try {
return Optional.of(Boolean.parseBoolean(childElement.getTextContent()));
} catch (Throwable e) {
throw new RuntimeException(
"Failed to parse the invalid boolean value ("
+ childElement.getTextContent()
+ ")");
}
}
}
}
return Optional.empty();
}
/**
* Returns the text content for the child element with the specified name for the specified
* element.
*
* @param element the parent element
* @param name the name of the child element to return
* @return an Optional containing the text content for the child element or an empty Optional if a
* child element with the specified name could not be found
*/
public static Optional<String> getChildElementText(Element element, String name) {
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Element childElement = (Element) node;
if (childElement.getNodeName().equals(name)) {
return Optional.of(childElement.getTextContent());
}
}
}
return Optional.empty();
}
/**
* Returns the child elements with the specified name for the specified element.
*
* @param element the parent element
* @param name the name of the child elements to return
* @return the child elements with the specified name for the specified element
*/
public static List<Element> getChildElements(Element element, String name) {
List<Element> childElements = new ArrayList<>();
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Element childElement = (Element) node;
if (childElement.getNodeName().equals(name)) {
childElements.add(childElement);
}
}
}
return childElements;
}
/**
* Returns the <b>javax.xml.namespace.QName</b> instance for the specified QName.
*
* @param document the <b>org.w3c.dom.Document</b> instance used to determine the namespace URI
* for the QName if the namespace is referenced using a prefix as part of the <b>name</b>
* parameter
* @param qname the QName
* @return the <b>javax.xml.namespace.QName</b> instance for the specified QName
*/
public static QName getQName(Document document, String qname) {
qname = StringUtils.hasText(qname) ? qname.trim() : "";
String[] nameParts = qname.split(":");
if (nameParts.length == 1) {
if (StringUtils.hasText(document.getNamespaceURI())) {
return new QName(document.getNamespaceURI(), nameParts[0]);
} else {
return new QName(XMLConstants.NULL_NS_URI, nameParts[0], XMLConstants.DEFAULT_NS_PREFIX);
}
} else if (nameParts.length == 2) {
String namespaceURI =
nameParts[0].equals(XMLConstants.DEFAULT_NS_PREFIX)
? document.lookupNamespaceURI(null)
: document.lookupNamespaceURI(nameParts[0]);
return new QName(namespaceURI, nameParts[1], nameParts[0]);
} else {
throw new RuntimeException("Failed to parse the QName (" + qname + ")");
}
}
/**
* Returns the <b>javax.xml.namespace.QName</b> instance for the specified QName.
*
* @param element the <b>org.w3c.dom.Element</b> instance used to determine the namespace URI for
* the QName if the namespace is referenced using a prefix as part of the <b>name</b>
* parameter
* @param qname the QName
* @return the <b>javax.xml.namespace.QName</b> instance for the specified QName
*/
public static QName getQName(Element element, String qname) {
return getQName(element.getOwnerDocument(), qname);
}
/**
* Returns <b>true</b> if the specified element has a child with the specified name or
* <b>false</b> otherwise.
*
* @param element the parent element
* @param name the name of the child element
* @return <b>true</b> if the specified element has a child with the specified name or
* <b>false</b> otherwise
*/
public static boolean hasChildElement(Element element, String name) {
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Element childElement = (Element) node;
if (childElement.getNodeName().equals(name)) {
return true;
}
}
}
return false;
}
}
|
0
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception/error/ErrorConfiguration.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.error;
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>ErrorConfiguration</b> class provides the Spring configuration for the Error module.
*
* @author Marcus Portmann
*/
@Configuration
@EnableJpaRepositories(
entityManagerFactoryRef = "errorEntityManagerFactory",
basePackages = {"africa.absa.inception.error"})
public class ErrorConfiguration {
/** The Spring application context. */
private final ApplicationContext applicationContext;
/**
* Constructs a new <b>ErrorConfiguration</b>.
*
* @param applicationContext the Spring application context
*/
public ErrorConfiguration(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* Returns the error entity manager factory bean associated with the application data source.
*
* @param dataSource the application data source
* @param platformTransactionManager the platform transaction manager
* @return the error entity manager factory bean associated with the application data source
*/
@Bean
public LocalContainerEntityManagerFactoryBean errorEntityManagerFactory(
@Qualifier("applicationDataSource") DataSource dataSource,
PlatformTransactionManager platformTransactionManager) {
return JpaUtil.createEntityManager(
"error", dataSource, platformTransactionManager, "africa.absa.inception.error");
}
}
|
0
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception/error/ErrorReport.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.error;
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 java.util.UUID;
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>ErrorReport</b> class holds the information for an error report.
*
* @author Marcus Portmann
*/
@Schema(description = "An error report submitted by a user after experiencing an application error")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"id",
"applicationId",
"applicationVersion",
"description",
"detail",
"created",
"who",
"deviceId",
"feedback",
"data"
})
@Entity
@Table(schema = "error", name = "error_reports")
@SuppressWarnings({"unused", "WeakerAccess"})
public class ErrorReport implements Serializable {
/** The maximum size of the error report detail. */
public static final int MAX_DETAIL_SIZE = 102400;
private static final long serialVersionUID = 1000000;
/** The ID for the application that generated the error report. */
@Schema(description = "ID for the application that generated the error report", required = true)
@JsonProperty(required = true)
@NotNull
@Size(min = 1, max = 200)
@Column(name = "application_id", length = 200, nullable = false)
private String applicationId;
/** The version of the application that generated the error report. */
@Schema(
description = "The version of the application that generated the error report",
required = true)
@JsonProperty(required = true)
@NotNull
@Size(max = 50)
@Column(name = "application_version", length = 50, nullable = false)
private String applicationVersion;
/** The date and time the error report was created. */
@Schema(description = "The date and time the error report was created", required = true)
@JsonProperty(required = true)
@NotNull
@Column(name = "created", nullable = false)
private LocalDateTime created;
/** The base-64 encoded data associated with the error report. */
@Schema(description = "The base-64 encoded data associated with the error report")
@JsonProperty
@Column(name = "data")
private String data;
/** The description of the error. */
@Schema(description = "The description of the error", required = true)
@JsonProperty(required = true)
@NotNull
@Size(max = 4000)
@Column(name = "description", length = 4000, nullable = false)
private String description;
/** The error detail. */
@Schema(description = "The error detail")
@JsonProperty
@Size(max = 102400)
@Column(name = "detail")
private String detail;
/** The optional ID for the device the error report originated from. */
@Schema(description = "The optional ID for the device the error report originated from")
@JsonProperty
@Column(name = "device_id")
private UUID deviceId;
/** The optional feedback provided by the user for the error. */
@Schema(description = "The optional feedback provided by the user for the error")
@JsonProperty
@Size(max = 4000)
@Column(name = "feedback", length = 4000)
private String feedback;
/** The ID for the error report. */
@Schema(description = "The ID for the error report", required = true)
@JsonProperty(required = true)
@NotNull
@Id
@Column(name = "id", nullable = false)
private UUID id;
/** The optional username for the user associated with the error report. */
@Schema(description = "The optional username for the user associated with the error report")
@JsonProperty
@Size(max = 100)
@Column(name = "who", length = 100)
private String who;
/** Constructs a new <b>ErrorReport</b>. */
public ErrorReport() {}
/**
* Constructs a new <b>ErrorReport</b>.
*
* @param id the ID for the error report
* @param applicationId the ID for the application that generated the error report
* @param applicationVersion the version of the application that generated the error report
* @param description the description of the error
* @param detail the error detail
* @param created the date and time the error report was created
*/
public ErrorReport(
UUID id,
String applicationId,
String applicationVersion,
String description,
String detail,
LocalDateTime created) {
this.id = id;
this.applicationId = applicationId;
this.applicationVersion = applicationVersion;
this.description = description;
this.detail = detail;
this.created = created;
}
/**
* Constructs a new <b>ErrorReport</b>.
*
* @param id the ID for the error report
* @param applicationId the ID for the application that generated the error report
* @param applicationVersion the version of the application that generated the error report
* @param description the description of the error
* @param detail the error detail
* @param created the date and time the error report was created
* @param who the optional username for the user associated with the error report
* @param deviceId the optional ID for the device the error report originated from
* @param feedback the optional feedback provided by the user for the error
* @param data the optional base-64 encoded data associated with the error report
*/
public ErrorReport(
UUID id,
String applicationId,
String applicationVersion,
String description,
String detail,
LocalDateTime created,
String who,
UUID deviceId,
String feedback,
String data) {
this.id = id;
this.applicationId = applicationId;
this.applicationVersion = applicationVersion;
this.description = description;
this.detail = detail;
this.created = created;
this.who = who;
this.deviceId = deviceId;
this.feedback = feedback;
this.data = data;
}
/**
* 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;
}
ErrorReport other = (ErrorReport) object;
return Objects.equals(id, other.id);
}
/**
* Returns the ID for the application that generated the error report.
*
* @return the ID for the application that generated the error report
*/
public String getApplicationId() {
return applicationId;
}
/**
* Returns the version of the application that generated the error report.
*
* @return the version of the application that generated the error report
*/
public String getApplicationVersion() {
return applicationVersion;
}
/**
* Returns the date and time the error report was created.
*
* @return the date and time the error report was created
*/
public LocalDateTime getCreated() {
return created;
}
/**
* Returns the optional base-64 encoded data associated with the error report.
*
* @return the optional base-64 encoded data associated with the error report
*/
public String getData() {
return data;
}
/**
* Returns the description of the error.
*
* @return the description of the error
*/
public String getDescription() {
return description;
}
/**
* Returns the error detail.
*
* @return the error detail
*/
public String getDetail() {
return detail;
}
/**
* Returns the optional ID for the device the error report originated from.
*
* @return the optional ID for the device the error report originated from
*/
public UUID getDeviceId() {
return deviceId;
}
/**
* Returns the optional feedback provided by the user for the error.
*
* @return the optional feedback provided by the user for the error
*/
public String getFeedback() {
return feedback;
}
/**
* Returns the ID for the error report.
*
* @return the ID for the error report
*/
public UUID getId() {
return id;
}
/**
* Returns the username for the user associated with the error report.
*
* @return the username for the user associated with the error report
*/
public String getWho() {
return who;
}
/**
* 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 application that generated the error report.
*
* @param applicationId the ID for the application that generated the error report
*/
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
/**
* Set the version of the application that generated the error report.
*
* @param applicationVersion the version of the application that generated the error report
*/
public void setApplicationVersion(String applicationVersion) {
this.applicationVersion = applicationVersion;
}
/**
* Set the date and time the error report was created.
*
* @param created the date and time the error report was created
*/
public void setCreated(LocalDateTime created) {
this.created = created;
}
/**
* Set the base-64 encoded data associated with the error report.
*
* @param data the base-64 encoded data associated with the error report
*/
public void setData(String data) {
this.data = data;
}
/**
* Set the description of the error.
*
* @param description the description of the error
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Set the error detail.
*
* @param detail the error detail
*/
public void setDetail(String detail) {
this.detail = detail;
}
/**
* Set the ID for the device the error report originated from.
*
* @param deviceId the ID for the device the error report originated from
*/
public void setDeviceId(UUID deviceId) {
this.deviceId = deviceId;
}
/**
* Set the feedback provided by the user for the error.
*
* @param feedback the feedback provided by the user for the error
*/
public void setFeedback(String feedback) {
this.feedback = feedback;
}
/**
* Set the ID for the error report.
*
* @param id the ID for the error report
*/
public void setId(UUID id) {
this.id = id;
}
/**
* Set the username for the user associated with the error report.
*
* @param who the username for the user associated with the error report
*/
public void setWho(String who) {
this.who = who;
}
}
|
0
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception/error/ErrorReportNotFoundException.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.error;
import africa.absa.inception.core.service.Problem;
import africa.absa.inception.core.service.ServiceException;
import java.util.UUID;
/**
* The <b>ErrorReportNotFoundException</b> exception is thrown to indicate that the required error
* report could not be found when working with the Error Service.
*
* <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/error/error-report-not-found",
title = "The error report could not be found.",
status = 404)
public class ErrorReportNotFoundException extends ServiceException {
private static final long serialVersionUID = 1000000;
/**
* Constructs a new <b>ErrorReportNotFoundException</b>.
*
* @param errorReportId the ID for the error report
*/
public ErrorReportNotFoundException(UUID errorReportId) {
super("The error report (" + errorReportId + ") could not be found");
}
}
|
0
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception/error/ErrorReportRepository.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.error;
import java.util.UUID;
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>ErrorRepository</b> interface declares the repository for the <b>ErrorReport</b> domain
* type.
*
* @author Marcus Portmann
*/
public interface ErrorReportRepository extends JpaRepository<ErrorReport, UUID> {
/**
* Delete the error report.
*
* @param errorReportId the ID for the error report
*/
@Modifying
@Query("delete from ErrorReport er where er.id = :errorReportId")
void deleteById(@Param("errorReportId") UUID errorReportId);
}
|
0
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception/error/ErrorReportSortBy.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.error;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.v3.oas.annotations.media.Schema;
/**
* The <b>ErrorReportSortBy</b> enumeration defines the possible methods used to sort a list of
* error reports.
*
* @author Marcus Portmann
*/
@Schema(description = "The method used to sort the list of error reports")
public enum ErrorReportSortBy {
/** Sort by created. */
CREATED("created", "Sort By Created"),
/** Sort by who. */
WHO("who", "Sort By Who");
private final String code;
private final String description;
ErrorReportSortBy(String code, String description) {
this.code = code;
this.description = description;
}
/**
* Returns the method used to sort a list of error reports given by the specified code value.
*
* @param code the code for the method used to sort a list of error reports
* @return the method used to sort a list of error reports given by the specified code value
*/
@JsonCreator
public static ErrorReportSortBy fromCode(String code) {
switch (code) {
case "created":
return ErrorReportSortBy.CREATED;
case "who":
return ErrorReportSortBy.WHO;
default:
throw new RuntimeException(
"Failed to determine the error report sort by with the invalid code (" + code + ")");
}
}
/**
* Returns the code for the method used to sort a list of error reports.
*
* @return the code for the method used to sort a list of error reports
*/
@JsonValue
public String code() {
return code;
}
/**
* Returns the description for the method used to sort a list of error reports.
*
* @return the description for the method used to sort a list of error reports
*/
public String description() {
return description;
}
/**
* Return the string representation of the method used to sort a list of error reports enumeration
* value.
*
* @return the string representation of the method used to sort a list of error reports
* enumeration value
*/
public String toString() {
return description;
}
}
|
0
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception/error/ErrorReportSummaries.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.error;
import africa.absa.inception.core.sorting.SortDirection;
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>ErrorReportSummaries</b> class holds the results of a request to retrieve the summaries
* for a list of error reports.
*
* @author Marcus Portmann
*/
@Schema(
description = "The results of a request to retrieve the summaries for a list of error reports")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"errorReportSummaries",
"total",
"filter",
"sortBy",
"sortDirection",
"pageIndex",
"pageSize"
})
@SuppressWarnings({"unused"})
public class ErrorReportSummaries implements Serializable {
private static final long serialVersionUID = 1000000;
/** The error report summaries. */
@Schema(description = "The error report summaries", required = true)
@JsonProperty(required = true)
private List<ErrorReportSummary> errorReportSummaries;
/** The optional filter that was applied to the error reports. */
@Schema(description = "The optional filter that was applied to the error reports")
@JsonProperty
private String filter;
/** The optional page index. */
@Schema(description = "The optional page index")
@JsonProperty
private Integer pageIndex;
/** The optional page size. */
@Schema(description = "The optional page size")
@JsonProperty
private Integer pageSize;
/** The optional method used to sort the error reports e.g. by who submitted them. */
@Schema(
description = "The optional method used to sort the error reports e.g. by who submitted them")
@JsonProperty
private ErrorReportSortBy sortBy;
/** The optional sort direction that was applied to the error reports. */
@Schema(description = "The optional sort direction that was applied to the error reports")
@JsonProperty
private SortDirection sortDirection;
/** The total number of error report summaries. */
@Schema(description = "The total number of error report summaries", required = true)
@JsonProperty(required = true)
private long total;
/** Constructs a new <b>ErrorReportSummaries</b>. */
public ErrorReportSummaries() {}
/**
* Constructs a new <b>ErrorReportSummaries</b>.
*
* @param errorReportSummaries the error report summaries
* @param total the total number of error report summaries
* @param filter the optional filter that was applied to the error reports
* @param sortBy the optional method used to sort the error reports e.g. by who submitted them
* @param sortDirection the optional sort direction that was applied to the error reports
* @param pageIndex the optional page index
* @param pageSize the optional page size
*/
public ErrorReportSummaries(
List<ErrorReportSummary> errorReportSummaries,
long total,
String filter,
ErrorReportSortBy sortBy,
SortDirection sortDirection,
Integer pageIndex,
Integer pageSize) {
this.errorReportSummaries = errorReportSummaries;
this.total = total;
this.filter = filter;
this.sortBy = sortBy;
this.sortDirection = sortDirection;
this.pageIndex = pageIndex;
this.pageSize = pageSize;
}
/**
* Returns the error report summaries.
*
* @return the error report summaries
*/
public List<ErrorReportSummary> getErrorReportSummaries() {
return errorReportSummaries;
}
/**
* Returns the optional filter that was applied to the error reports.
*
* @return the optional filter that was applied to the error reports
*/
public String getFilter() {
return filter;
}
/**
* Returns the optional page index.
*
* @return the optional page index
*/
public Integer getPageIndex() {
return pageIndex;
}
/**
* Returns the optional page size.
*
* @return the optional page size
*/
public Integer getPageSize() {
return pageSize;
}
/**
* Returns the optional method used to sort the error reports e.g. by who submitted them.
*
* @return the optional method used to sort the error reports
*/
public ErrorReportSortBy getSortBy() {
return sortBy;
}
/**
* Returns the optional sort direction that was applied to the error reports.
*
* @return the optional sort direction that was applied to the error reports
*/
public SortDirection getSortDirection() {
return sortDirection;
}
/**
* Returns the total number of error report summaries.
*
* @return the total number of error report summaries
*/
public Long getTotal() {
return total;
}
}
|
0
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception/error/ErrorReportSummary.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.error;
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 java.util.UUID;
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>ErrorReportSummary</b> class holds the summary information for an error report.
*
* @author Marcus Portmann
*/
@Schema(description = "An error report summary")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"id",
"applicationId",
"applicationVersion",
"description",
"created",
"who",
"deviceId"
})
@Entity
@Table(schema = "error", name = "error_reports")
@SuppressWarnings({"unused", "WeakerAccess"})
public class ErrorReportSummary implements Serializable {
private static final long serialVersionUID = 1000000;
/** The ID for the application that generated the error report. */
@Schema(description = "ID for the application that generated the error report", required = true)
@JsonProperty(required = true)
@NotNull
@Size(min = 1, max = 200)
@Column(name = "application_id", length = 200, nullable = false)
private String applicationId;
/** The version of the application that generated the error report. */
@Schema(
description = "The version of the application that generated the error report",
required = true)
@JsonProperty(required = true)
@NotNull
@Size(max = 50)
@Column(name = "application_version", nullable = false)
private String applicationVersion;
/** The date and time the error report was created. */
@Schema(description = "The date and time the error report was created", required = true)
@JsonProperty(required = true)
@NotNull
@Column(name = "created", nullable = false)
private LocalDateTime created;
/** The description of the error. */
@Schema(description = "The description of the error", required = true)
@JsonProperty(required = true)
@NotNull
@Size(max = 4000)
@Column(name = "description", length = 4000, nullable = false)
private String description;
/** The optional ID for the device the error report originated from. */
@Schema(description = "The optional ID for the device the error report originated from")
@JsonProperty
@Size(max = 50)
@Column(name = "device_id")
private UUID deviceId;
/** The ID for the error report. */
@Schema(description = "The ID for the error report", required = true)
@JsonProperty(required = true)
@NotNull
@Id
@Column(name = "id", nullable = false)
private UUID id;
/** The optional username for the user associated with the error report. */
@Schema(description = "The optional username for the user associated with the error report")
@JsonProperty
@Size(max = 100)
@Column(name = "who", length = 100)
private String who;
/** Constructs a new <b>ErrorReportSummary</b>. */
public ErrorReportSummary() {}
/**
* Constructs a new <b>ErrorReportSummary</b>.
*
* @param id the ID for the error report
* @param applicationId the ID for the application that generated the error report
* @param applicationVersion the version of the application that generated the error report
* @param description the description of the error
* @param created the date and time the error report was created
* @param who the optional username for the user associated with the error report
* @param deviceId the optional ID for the device the error report originated from
*/
public ErrorReportSummary(
UUID id,
String applicationId,
String applicationVersion,
String description,
LocalDateTime created,
String who,
UUID deviceId) {
this.id = id;
this.applicationId = applicationId;
this.applicationVersion = applicationVersion;
this.description = description;
this.created = created;
this.who = who;
this.deviceId = deviceId;
}
/**
* 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;
}
ErrorReportSummary other = (ErrorReportSummary) object;
return Objects.equals(id, other.id);
}
/**
* Returns the ID for the application that generated the error report.
*
* @return the ID for the application that generated the error report
*/
public String getApplicationId() {
return applicationId;
}
/**
* Returns the version of the application that generated the error report.
*
* @return the version of the application that generated the error report
*/
public String getApplicationVersion() {
return applicationVersion;
}
/**
* Returns the date and time the error report was created.
*
* @return the date and time the error report was created
*/
public LocalDateTime getCreated() {
return created;
}
/**
* Returns the description of the error.
*
* @return the description of the error
*/
public String getDescription() {
return description;
}
/**
* Returns the optional ID for the device the error report originated from.
*
* @return the optional ID for the device the error report originated from
*/
public UUID getDeviceId() {
return deviceId;
}
/**
* Returns the ID for the error report.
*
* @return the ID for the error report
*/
public UUID getId() {
return id;
}
/**
* Returns the username for the user associated with the error report.
*
* @return the username for the user associated with the error report
*/
public String getWho() {
return who;
}
/**
* 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();
}
}
|
0
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception/error/ErrorReportSummaryRepository.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.error;
import java.util.UUID;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
/**
* The <b>ErrorRepository</b> interface declares the repository for the <b> ErrorReportSummary</b>
* domain type.
*
* @author Marcus Portmann
*/
public interface ErrorReportSummaryRepository extends JpaRepository<ErrorReportSummary, UUID> {
/**
* Retrieve the filtered error report summaries.
*
* @param filter the filter to apply to the error reports
* @param pageable the pagination information
* @return the filtered error report summaries
*/
@Query("select ers from ErrorReportSummary ers where (lower(ers.who) like lower(:filter))")
Page<ErrorReportSummary> findFiltered(@Param("filter") String filter, Pageable pageable);
}
|
0
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception/error/ErrorService.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.error;
import africa.absa.inception.core.service.InvalidArgumentException;
import africa.absa.inception.core.service.ServiceUnavailableException;
import africa.absa.inception.core.service.ValidationError;
import africa.absa.inception.core.sorting.SortDirection;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
/**
* The <b>ErrorService</b> class provides the Error Service implementation.
*
* @author Marcus Portmann
*/
@Service
@SuppressWarnings({"unused"})
public class ErrorService implements IErrorService {
/** The maximum number of filtered error report summaries. */
private static final int MAX_FILTERED_ERROR_REPORT_SUMMARIES = 100;
/* Logger */
private static final Logger logger = LoggerFactory.getLogger(ErrorService.class);
/** The Spring application context. */
private final ApplicationContext applicationContext;
/** The Error Report Repository. */
private final ErrorReportRepository errorReportRepository;
/** The Error Report Summary Repository. */
private final ErrorReportSummaryRepository errorReportSummaryRepository;
/** The JSR-303 validator. */
private final Validator validator;
/** Is debugging enabled for the Inception Framework? */
@Value("${inception.debug.enabled:#{false}}")
private boolean inDebugMode;
/**
* Constructs a new <b>ErrorService</b>.
*
* @param applicationContext the Spring application context
* @param validator the JSR-303 validator
* @param errorReportRepository the Error Report Repository
* @param errorReportSummaryRepository the Error Report Summary Repository
*/
public ErrorService(
ApplicationContext applicationContext,
Validator validator,
ErrorReportRepository errorReportRepository,
ErrorReportSummaryRepository errorReportSummaryRepository) {
this.applicationContext = applicationContext;
this.validator = validator;
this.errorReportRepository = errorReportRepository;
this.errorReportSummaryRepository = errorReportSummaryRepository;
}
@Override
@Transactional
public void createErrorReport(ErrorReport errorReport)
throws InvalidArgumentException, ServiceUnavailableException {
if (errorReport == null) {
throw new InvalidArgumentException("errorReport");
}
// Truncate the detail if required
if ((errorReport.getDetail() != null)
&& (errorReport.getDetail().length() > ErrorReport.MAX_DETAIL_SIZE)) {
errorReport.setDetail(
errorReport.getDetail().substring(0, ErrorReport.MAX_DETAIL_SIZE - 3) + "...");
}
Set<ConstraintViolation<ErrorReport>> constraintViolations = validator.validate(errorReport);
if (!constraintViolations.isEmpty()) {
throw new InvalidArgumentException(
"errorReport", ValidationError.toValidationErrors(constraintViolations));
}
try {
String description = errorReport.getDescription();
if (description.length() > 4000) {
description = description.substring(0, 4000);
}
errorReport.setDescription(description);
String detail = StringUtils.hasText(errorReport.getDetail()) ? errorReport.getDetail() : "";
if (detail.length() > 4000) {
detail = detail.substring(0, 4000);
}
errorReport.setDetail(detail);
String who = errorReport.getWho();
if ((who != null) && (who.length() > 1000)) {
who = who.substring(0, 1000);
}
errorReport.setWho(who);
String feedback = errorReport.getFeedback();
if ((feedback != null) && (feedback.length() > 4000)) {
feedback = feedback.substring(0, 4000);
}
errorReport.setFeedback(feedback);
errorReportRepository.saveAndFlush(errorReport);
if (inDebugMode) {
ObjectMapper objectMapper = applicationContext.getBean(ObjectMapper.class);
if (objectMapper != null) {
logger.info(
"Error Report: "
+ objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorReport));
}
}
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to create the error report (" + errorReport.getId() + ")", e);
}
}
@Override
public ErrorReport getErrorReport(UUID errorReportId)
throws InvalidArgumentException, ErrorReportNotFoundException, ServiceUnavailableException {
if (errorReportId == null) {
throw new InvalidArgumentException("errorReportId");
}
try {
Optional<ErrorReport> errorReportOptional = errorReportRepository.findById(errorReportId);
if (errorReportOptional.isPresent()) {
return errorReportOptional.get();
} else {
throw new ErrorReportNotFoundException(errorReportId);
}
} catch (ErrorReportNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the error report (" + errorReportId + ")", e);
}
}
@Override
public ErrorReportSummaries getErrorReportSummaries(
String filter,
ErrorReportSortBy sortBy,
SortDirection sortDirection,
Integer pageIndex,
Integer pageSize)
throws InvalidArgumentException, ServiceUnavailableException {
if ((pageIndex != null) && (pageIndex < 0)) {
throw new InvalidArgumentException("pageIndex");
}
if ((pageSize != null) && (pageSize <= 0)) {
throw new InvalidArgumentException("pageSize");
}
if (sortBy == null) {
sortBy = ErrorReportSortBy.CREATED;
}
if (sortDirection == null) {
sortDirection = SortDirection.ASCENDING;
}
try {
PageRequest pageRequest;
if (pageIndex == null) {
pageIndex = 0;
}
if (pageSize == null) {
pageSize = MAX_FILTERED_ERROR_REPORT_SUMMARIES;
}
if (sortBy == ErrorReportSortBy.WHO) {
pageRequest =
PageRequest.of(
pageIndex,
Math.min(pageSize, MAX_FILTERED_ERROR_REPORT_SUMMARIES),
(sortDirection == SortDirection.ASCENDING)
? Sort.Direction.ASC
: Sort.Direction.DESC,
"who");
} else {
pageRequest =
PageRequest.of(
pageIndex,
Math.min(pageSize, MAX_FILTERED_ERROR_REPORT_SUMMARIES),
(sortDirection == SortDirection.ASCENDING)
? Sort.Direction.ASC
: Sort.Direction.DESC,
"created");
}
Page<ErrorReportSummary> errorReportSummaryPage;
if (StringUtils.hasText(filter)) {
errorReportSummaryPage =
errorReportSummaryRepository.findFiltered("%" + filter + "%", pageRequest);
} else {
errorReportSummaryPage = errorReportSummaryRepository.findAll(pageRequest);
}
return new ErrorReportSummaries(
errorReportSummaryPage.toList(),
errorReportSummaryPage.getTotalElements(),
filter,
sortBy,
sortDirection,
pageIndex,
pageSize);
} catch (Throwable e) {
logger.error("Failed to retrieve the filtered error report summaries", e);
throw new ServiceUnavailableException(
"Failed to retrieve the filtered error report summaries", e);
}
}
@Override
public ErrorReportSummary getErrorReportSummary(UUID errorReportId)
throws InvalidArgumentException, ErrorReportNotFoundException, ServiceUnavailableException {
if (errorReportId == null) {
throw new InvalidArgumentException("errorReportId");
}
try {
Optional<ErrorReportSummary> errorReportSummaryOptional =
errorReportSummaryRepository.findById(errorReportId);
if (errorReportSummaryOptional.isPresent()) {
return errorReportSummaryOptional.get();
} else {
throw new ErrorReportNotFoundException(errorReportId);
}
} catch (ErrorReportNotFoundException e) {
throw e;
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the summary for the error report (" + errorReportId + ")", e);
}
}
@Override
public List<ErrorReportSummary> getMostRecentErrorReportSummaries(int maximumNumberOfEntries)
throws InvalidArgumentException, ServiceUnavailableException {
if (maximumNumberOfEntries < 0) {
throw new InvalidArgumentException("maximumNumberOfEntries");
}
try {
PageRequest pageRequest =
PageRequest.of(0, maximumNumberOfEntries, Sort.Direction.DESC, "created");
Page<ErrorReportSummary> errorReportSummaryPage =
errorReportSummaryRepository.findAll(pageRequest);
return errorReportSummaryPage.getContent();
} catch (Throwable e) {
throw new ServiceUnavailableException(
"Failed to retrieve the summaries for the most recent error reports", e);
}
}
}
|
0
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error/1.2.0/africa/absa/inception/error/IErrorService.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.error;
import africa.absa.inception.core.service.InvalidArgumentException;
import africa.absa.inception.core.service.ServiceUnavailableException;
import africa.absa.inception.core.sorting.SortDirection;
import java.util.List;
import java.util.UUID;
/**
* The <b>IErrorService</b> interface defines the functionality provided by an Error Service
* implementation.
*
* @author Marcus Portmann
*/
public interface IErrorService {
/**
* Create the new entry for the error report in the database.
*
* @param errorReport the <b>ErrorReport</b> instance containing the information for the error
* report
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the error report could not be created
*/
void createErrorReport(ErrorReport errorReport)
throws InvalidArgumentException, ServiceUnavailableException;
/**
* Retrieve the error report.
*
* @param errorReportId the ID for the error report
* @return the error report
* @throws InvalidArgumentException if an argument is invalid
* @throws ErrorReportNotFoundException if the error report could not be found
* @throws ServiceUnavailableException if the error report could not be retrieved
*/
ErrorReport getErrorReport(UUID errorReportId)
throws InvalidArgumentException, ErrorReportNotFoundException, ServiceUnavailableException;
/**
* Retrieve the error report summaries.
*
* @param filter the optional filter to apply to the error reports
* @param sortBy the optional method used to sort the error reports e.g. by who submitted them
* @param sortDirection the optional sort direction to apply to the error reports
* @param pageIndex the optional page index
* @param pageSize the optional page size
* @return the error report summaries
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the error report summaries could not be retrieved
*/
ErrorReportSummaries getErrorReportSummaries(
String filter,
ErrorReportSortBy sortBy,
SortDirection sortDirection,
Integer pageIndex,
Integer pageSize)
throws InvalidArgumentException, ServiceUnavailableException;
/**
* Retrieve the summary for the error report.
*
* @param errorReportId the ID for the error report
* @return the summary for the error report
* @throws InvalidArgumentException if an argument is invalid
* @throws ErrorReportNotFoundException if the error report could not be found
* @throws ServiceUnavailableException if the error report summary could not be retrieved
*/
ErrorReportSummary getErrorReportSummary(UUID errorReportId)
throws InvalidArgumentException, ErrorReportNotFoundException, ServiceUnavailableException;
/**
* Retrieve the summaries for the most recent error reports.
*
* @param maximumNumberOfEntries the maximum number of summaries for the most recent error reports
* to retrieve
* @return the summaries for the most recent error reports
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the most recent error report summaries could not be
* retrieved
*/
List<ErrorReportSummary> getMostRecentErrorReportSummaries(int maximumNumberOfEntries)
throws InvalidArgumentException, ServiceUnavailableException;
}
|
0
|
java-sources/africa/absa/inception-error-api/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error-api/1.2.0/africa/absa/inception/error/ErrorApi.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.error;
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.sorting.SortDirection;
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 org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
/**
* The <b>ErrorApi</b> class.
*
* @author Marcus Portmann
*/
@Tag(name = "Error")
@RestController
@RequestMapping(value = "/api/error")
@CrossOrigin
@SuppressWarnings({"unused"})
// @el (isSecurityDisabled: africa.absa.inception.api.ApiSecurityExpressionRoot.isSecurityEnabled)
public class ErrorApi extends SecureApi {
/** The Error Service. */
private final IErrorService errorService;
/**
* Constructs a new <b>ErrorRestController</b>.
*
* @param applicationContext the Spring application context
* @param errorService the Error Service
*/
public ErrorApi(ApplicationContext applicationContext, IErrorService errorService) {
super(applicationContext);
this.errorService = errorService;
}
/**
* Create the new error report.
*
* @param errorReport the error report
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the error report could not be created
*/
@Operation(summary = "Create the error report", description = "Create the error report")
@ApiResponses(
value = {
@ApiResponse(
responseCode = "204",
description = "The error report 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 = "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 = "/error-reports",
method = RequestMethod.POST,
produces = "application/json")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void createErrorReport(
@io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "The error report to create",
required = true)
@RequestBody
ErrorReport errorReport)
throws InvalidArgumentException, ServiceUnavailableException {
if (errorReport == null) {
throw new InvalidArgumentException("errorReport");
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
errorReport.setWho(authentication.getName());
}
errorService.createErrorReport(errorReport);
}
/**
* Retrieve the error report summaries.
*
* @param filter the optional filter to apply to the error reports
* @param sortBy the optional method used to sort the error reports e.g. by who submitted them
* @param sortDirection the optional sort direction to apply to the error reports
* @param pageIndex the optional page index
* @param pageSize the optional page size
* @return the error report summaries
* @throws InvalidArgumentException if an argument is invalid
* @throws ServiceUnavailableException if the error report summaries could not be retrieved
*/
@Operation(
summary = "Retrieve the error report summaries",
description = "Retrieve the error report summaries")
@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 = "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 = "/error-report-summaries",
method = RequestMethod.GET,
produces = "application/json")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(
"isSecurityDisabled() or hasRole('Administrator') or hasAuthority('FUNCTION_Error.ErrorAdministration')")
public ErrorReportSummaries getErrorReportSummaries(
@Parameter(name = "filter", description = "The optional filter to apply to the error reports")
@RequestParam(value = "filter", required = false)
String filter,
@Parameter(
name = "sortBy",
description =
"The optional method used to sort the error reports e.g. by who submitted them")
@RequestParam(value = "sortBy", required = false)
ErrorReportSortBy sortBy,
@Parameter(
name = "sortDirection",
description = "The optional sort direction to apply to the error reports")
@RequestParam(value = "sortDirection", required = false)
SortDirection sortDirection,
@Parameter(name = "pageIndex", description = "The optional page index", example = "0")
@RequestParam(value = "pageIndex", required = false, defaultValue = "0")
Integer pageIndex,
@Parameter(name = "pageSize", description = "The optional page size", example = "10")
@RequestParam(value = "pageSize", required = false, defaultValue = "10")
Integer pageSize)
throws InvalidArgumentException, ServiceUnavailableException {
if (pageIndex == null) {
pageIndex = 0;
}
if (pageSize == null) {
pageSize = 10;
}
return errorService.getErrorReportSummaries(filter, sortBy, sortDirection, pageIndex, pageSize);
}
}
|
0
|
java-sources/africa/absa/inception-error-api/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error-api/1.2.0/africa/absa/inception/error/ErrorApiConfiguration.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.error;
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>ErrorApiConfiguration</b> class provides the Spring configuration for the Error API
* module.
*
* @author Marcus Portmann
*/
@Configuration
public class ErrorApiConfiguration {
/**
* Returns the grouped Open API for the Error API.
*
* @return the grouped Open API for the Error API
*/
@Bean
public GroupedOpenApi errorOpenApi() {
return GroupedOpenApi.builder()
.group("error")
.packagesToScan("africa.absa.inception.error")
.addOpenApiCustomiser(
openApi -> openApi.info(new Info().title("Error API").version(Version.PROJECT_VERSION)))
.build();
}
}
|
0
|
java-sources/africa/absa/inception-error-api/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-error-api/1.2.0/africa/absa/inception/error/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.error;
/**
* 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-jpa/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-jpa/1.2.0/africa/absa/inception/jpa/AssignedIdentityGenerator.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.jpa;
import java.io.Serializable;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentityGenerator;
/**
* The <b>AssignedIdentityGenerator</b> implements a Hibernate generator that allows a value to be
* specified in place of an automatically generated value for an identity column in the database.
*
* @author Marcus Portmann
*/
@SuppressWarnings({"unused"})
public class AssignedIdentityGenerator extends IdentityGenerator {
/**
* Generate a new identifier.
*
* @param session the session from which the request originates
* @param object the entity or collection for which the ID is being generated
* @return a new identifier
*/
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) {
if (object instanceof Identifiable) {
Identifiable identifiable = (Identifiable) object;
Serializable id = identifiable.getId();
if (id != null) {
return id;
}
}
return super.generate(session, object);
}
}
|
0
|
java-sources/africa/absa/inception-jpa/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-jpa/1.2.0/africa/absa/inception/jpa/Identifiable.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.jpa;
import java.io.Serializable;
/**
* The <b>Identifiable</b> interface defines the interface that must be implemented by JPA entity
* classes that have an ID that can be explicitly specified in place of an automatically generated
* value for an identity column in the database.
*
* @param <T> the ID type for the entity
* @author Marcus Portmann
*/
public interface Identifiable<T extends Serializable> {
/**
* Returns the ID for the entity.
*
* @return the ID for the entity
*/
T getId();
}
|
0
|
java-sources/africa/absa/inception-jpa/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-jpa/1.2.0/africa/absa/inception/jpa/JpaUtil.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.jpa;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.FatalBeanException;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.jta.JtaTransactionManager;
/**
* The <b>JpaUtil</b> class provides JPA-related utility methods.
*
* @author Marcus Portmann
*/
@SuppressWarnings("unused")
public class JpaUtil {
/**
* Create a new entity manager.
*
* @param persistenceUnitName the name of the persistence unit
* @param dataSource the data source
* @param platformTransactionManager the Spring platform transaction manager
* @param packagesToScan the packages to scan for entities
* @return the entity manager
*/
public static LocalContainerEntityManagerFactoryBean createEntityManager(
String persistenceUnitName,
DataSource dataSource,
PlatformTransactionManager platformTransactionManager,
String... packagesToScan) {
try {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean =
new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setPersistenceUnitName(persistenceUnitName);
entityManagerFactoryBean.setJtaDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan(packagesToScan);
// TODO: Detect the JPA vendor and create the correct adapter -- MARCUS
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(false);
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
switch (metaData.getDatabaseProductName()) {
case "H2":
jpaVendorAdapter.setDatabase(Database.H2);
jpaVendorAdapter.setShowSql(true);
break;
case "Microsoft SQL Server":
jpaVendorAdapter.setDatabase(Database.SQL_SERVER);
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.SQLServer2012Dialect");
jpaVendorAdapter.setShowSql(false);
break;
default:
jpaVendorAdapter.setDatabase(Database.DEFAULT);
jpaVendorAdapter.setShowSql(false);
break;
}
}
entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
Map<String, Object> jpaPropertyMap = entityManagerFactoryBean.getJpaPropertyMap();
if (platformTransactionManager instanceof JtaTransactionManager) {
jpaPropertyMap.put("hibernate.transaction.coordinator_class", "jta");
jpaPropertyMap.put("hibernate.transaction.jta.platform", "JBossTS");
}
return entityManagerFactoryBean;
} catch (Throwable e) {
throw new FatalBeanException(
"Failed to create the entity manager factory bean for the persistence unit ("
+ persistenceUnitName
+ ")",
e);
}
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/DateDeserializer.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.json;
import africa.absa.inception.core.util.ISO8601Util;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.util.Date;
/**
* The <b>DateDeserializer</b> class implements the Jackson deserializer for the <b> LocalDate</b>
* type.
*
* @author Marcus Portmann
*/
public class DateDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
try {
return ISO8601Util.toDate(jsonParser.getValueAsString());
} catch (Throwable e) {
throw new IOException(
"Failed to deserialize the ISO 8601 value (" + jsonParser.getValueAsString() + ")");
}
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/DateSerializer.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.json;
import africa.absa.inception.core.util.ISO8601Util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Date;
/**
* The <b>DateDeserializer</b> class implements the Jackson serializer for the <b>Date</b> type.
*
* @author Marcus Portmann
*/
public class DateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializers)
throws IOException {
jsonGenerator.writeString(ISO8601Util.fromDateTime(date));
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/DateTimeModule.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.json;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.util.Date;
/**
* The <b>DateTimeModule</b> implements the custom Jackson module that registers the serializer and
* deserializer extensions that support the Java 8 Date/Time API.
*
* @author Marcus Portmann
*/
public class DateTimeModule extends SimpleModule {
/** Constructs a new <b>DateTimeModule</b>. */
public DateTimeModule() {
super("DateTimeModule", new Version(1, 0, 0, null, null, null));
addSerializer(Date.class, new DateSerializer());
addDeserializer(Date.class, new DateDeserializer());
addSerializer(LocalDate.class, new LocalDateSerializer());
addDeserializer(LocalDate.class, new LocalDateDeserializer());
addSerializer(LocalTime.class, new LocalTimeSerializer());
addDeserializer(LocalTime.class, new LocalTimeDeserializer());
addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
addSerializer(ZonedDateTime.class, new ZonedDateTimeSerializer());
addDeserializer(ZonedDateTime.class, new ZonedDateTimeDeserializer());
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/LocalDateDeserializer.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.json;
import africa.absa.inception.core.util.ISO8601Util;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalDate;
/**
* The <b>LocalDateDeserializer</b> class implements the Jackson deserializer for the <b>
* LocalDate</b> type.
*
* @author Marcus Portmann
*/
public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
@Override
public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
try {
return ISO8601Util.toLocalDate(jsonParser.getValueAsString());
} catch (Throwable e) {
throw new IOException(
"Failed to deserialize the ISO 8601 value (" + jsonParser.getValueAsString() + ")");
}
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/LocalDateSerializer.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.json;
import africa.absa.inception.core.util.ISO8601Util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.LocalDate;
/**
* The <b>LocalDateDeserializer</b> class implements the Jackson serializer for the <b>
* LocalDate</b> type.
*
* @author Marcus Portmann
*/
public class LocalDateSerializer extends JsonSerializer<LocalDate> {
@Override
public void serialize(
LocalDate localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializers)
throws IOException {
jsonGenerator.writeString(ISO8601Util.fromLocalDate(localDateTime));
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/LocalDateTimeDeserializer.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.json;
import africa.absa.inception.core.util.ISO8601Util;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalDateTime;
/**
* The <b>LocalDateTimeDeserializer</b> class implements the Jackson deserializer for the
* <b>LocalDateTime</b> type.
*
* @author Marcus Portmann
*/
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(
JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
try {
return ISO8601Util.toLocalDateTime(jsonParser.getValueAsString());
} catch (Throwable e) {
throw new IOException(
"Failed to deserialize the ISO 8601 value (" + jsonParser.getValueAsString() + ")");
}
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/LocalDateTimeSerializer.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.json;
import africa.absa.inception.core.util.ISO8601Util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.LocalDateTime;
/**
* The <b>LocalDateTimeDeserializer</b> class implements the Jackson serializer for the <b>
* LocalDateTime</b> type.
*
* @author Marcus Portmann
*/
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(
LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializers)
throws IOException {
jsonGenerator.writeString(ISO8601Util.fromLocalDateTime(localDateTime));
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/LocalTimeDeserializer.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.json;
import africa.absa.inception.core.util.ISO8601Util;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.LocalTime;
/**
* The <b>LocalTimeDeserializer</b> class implements the Jackson deserializer for the <b>
* LocalTime</b> type.
*
* @author Marcus Portmann
*/
public class LocalTimeDeserializer extends JsonDeserializer<LocalTime> {
@Override
public LocalTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
try {
return ISO8601Util.toLocalTime(jsonParser.getValueAsString());
} catch (Throwable e) {
throw new IOException(
"Failed to deserialize the ISO 8601 value (" + jsonParser.getValueAsString() + ")");
}
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/LocalTimeSerializer.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.json;
import africa.absa.inception.core.util.ISO8601Util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.LocalTime;
/**
* The <b>LocalTimeDeserializer</b> class implements the Jackson serializer for the <b>
* LocalTime</b> type.
*
* @author Marcus Portmann
*/
public class LocalTimeSerializer extends JsonSerializer<LocalTime> {
@Override
public void serialize(
LocalTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializers)
throws IOException {
jsonGenerator.writeString(ISO8601Util.fromLocalTime(localDateTime));
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/ZonedDateTimeDeserializer.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.json;
import africa.absa.inception.core.util.ISO8601Util;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.ZonedDateTime;
/**
* The <b>ZonedDateTimeDeserializer</b> class implements the Jackson deserializer for the
* <b>ZonedDateTime</b> type.
*
* @author Marcus Portmann
*/
public class ZonedDateTimeDeserializer extends JsonDeserializer<ZonedDateTime> {
@Override
public ZonedDateTime deserialize(
JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
try {
return ISO8601Util.toZonedDateTime(jsonParser.getValueAsString());
} catch (Throwable e) {
throw new IOException(
"Failed to deserialize the ISO 8601 value (" + jsonParser.getValueAsString() + ")");
}
}
}
|
0
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception
|
java-sources/africa/absa/inception-json/1.2.0/africa/absa/inception/json/ZonedDateTimeSerializer.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.json;
import africa.absa.inception.core.util.ISO8601Util;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.time.ZonedDateTime;
/**
* The <b>ZonedDateTimeDeserializer</b> class implements the Jackson serializer for the <b>
* ZonedDateTime</b> type.
*
* @author Marcus Portmann
*/
public class ZonedDateTimeSerializer extends JsonSerializer<ZonedDateTime> {
@Override
public void serialize(
ZonedDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializers)
throws IOException {
jsonGenerator.writeString(ISO8601Util.fromZonedDateTime(localDateTime));
}
}
|
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/agroal/LocalXAResource.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.agroal;
import africa.absa.inception.jta.util.XAExceptionUtil;
import io.agroal.api.transaction.TransactionAware;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
* The <b>LocalXAResource</b> class provides an XAResource implementation that supports local
* transaction behavior for an Agroal transaction aware connection resource associated with a non-XA
* data source.
*
* @author Marcus Portmann
*/
public class LocalXAResource implements XAResource {
/** The Agroal transaction aware connection resource. */
private final TransactionAware transactionAware;
/** The current transaction ID. */
private Xid currentXid;
/**
* Constructs a new <b>LocalXAResource</b>.
*
* @param transactionAware the Agroal transaction aware connection resource
*/
public LocalXAResource(TransactionAware transactionAware) {
this.transactionAware = transactionAware;
}
@Override
public void commit(Xid xid, boolean onePhase) throws XAException {
if (xid == null || !xid.equals(currentXid)) {
throw XAExceptionUtil.xaException(
XAException.XAER_NOTA,
"Failed to commit the transaction ("
+ currentXid
+ ") for the transaction aware connection resource using the invalid xid ("
+ xid
+ ")");
}
currentXid = null;
try {
transactionAware.transactionBeforeCompletion(true);
transactionAware.transactionCommit();
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
onePhase ? XAException.XA_RBROLLBACK : XAException.XAER_RMERR,
"Failed to commit the transaction ("
+ xid
+ ") for the transaction aware connection resource: "
+ e.getMessage(),
e);
}
}
@Override
public void end(Xid xid, int flags) throws XAException {
if (xid == null || !xid.equals(currentXid)) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_NOTA,
"Failed to end the transaction ("
+ currentXid
+ ") for the transaction aware connection resource using the invalid xid ("
+ xid
+ ")");
}
}
@Override
public void forget(Xid xid) throws XAException {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_NOTA,
"Forget not supported for the transaction aware connection resource");
}
@Override
public int getTransactionTimeout() {
return 0;
}
@Override
public boolean isSameRM(XAResource xaResource) {
return this == xaResource;
}
@Override
public int prepare(Xid xid) {
return XA_OK;
}
@Override
public Xid[] recover(int flag) throws XAException {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Recover not supported for the transaction aware connection resource");
}
@Override
public void rollback(Xid xid) throws XAException {
if (xid == null || !xid.equals(currentXid)) {
throw XAExceptionUtil.xaException(
XAException.XAER_NOTA,
"Failed to rollback the transaction ("
+ currentXid
+ ") for the transaction aware connection resource using the invalid xid ("
+ xid
+ ")");
}
currentXid = null;
try {
transactionAware.transactionBeforeCompletion(false);
transactionAware.transactionRollback();
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to rollback the transaction ("
+ xid
+ ") for the transaction aware connection resource: "
+ e.getMessage(),
e);
}
}
@Override
public boolean setTransactionTimeout(int seconds) {
return false;
}
@Override
public void start(Xid xid, int flags) throws XAException {
if (currentXid == null) {
if (flags != TMNOFLAGS) {
throw XAExceptionUtil.xaException(
XAException.XAER_INVAL,
"Failed to start the transaction ("
+ xid
+ ") for the transaction aware connection resource using the invalid flags ("
+ flags
+ ")");
}
try {
transactionAware.transactionStart();
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to start the transaction ("
+ xid
+ ") for the transaction aware connection resource: "
+ e.getMessage(),
e);
}
currentXid = xid;
} else {
if (flags != TMJOIN && flags != TMRESUME) {
throw XAExceptionUtil.xaException(
XAException.XAER_DUPID,
"Failed to join or resume the transaction ("
+ xid
+ ") for the transaction aware connection resource using the invalid flags ("
+ flags
+ ")");
}
}
}
}
|
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/agroal/NarayanaTransactionIntegration.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.agroal;
import africa.absa.inception.jta.util.TransactionUtil;
import com.arjuna.ats.arjuna.recovery.RecoveryManager;
import com.arjuna.ats.internal.jta.recovery.arjunacore.XARecoveryModule;
import com.arjuna.ats.jta.recovery.XAResourceRecoveryHelper;
import io.agroal.api.transaction.TransactionAware;
import java.sql.SQLException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.transaction.Synchronization;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.xa.XAResource;
/**
* The <b>NarayanaTransactionIntegration</b> class.
*
* @author Marcus Portmann
*/
public class NarayanaTransactionIntegration
implements io.agroal.api.transaction.TransactionIntegration {
private static final ConcurrentMap<ResourceRecoveryFactory, XAResourceRecoveryHelperImpl>
xaResourceRecoveryHelperImplCache = new ConcurrentHashMap<>();
// In order to construct a UID that is globally unique, simply pair a UID with an InetAddress.
private final UUID key = UUID.randomUUID();
private final RecoveryManager recoveryManager;
private final TransactionManager transactionManager;
private final TransactionSynchronizationRegistry transactionSynchronizationRegistry;
/**
* Constructs a new <b>NarayanaTransactionIntegration</b>.
*
* @param transactionManager the transaction manager
* @param transactionSynchronizationRegistry the transaction synchronization registry
*/
public NarayanaTransactionIntegration(
TransactionManager transactionManager,
TransactionSynchronizationRegistry transactionSynchronizationRegistry) {
this(transactionManager, transactionSynchronizationRegistry, null);
}
/**
* Constructs a new <b>NarayanaTransactionIntegration</b>.
*
* @param transactionManager the transaction manager
* @param transactionSynchronizationRegistry the transaction synchronization registry
* @param recoveryManager the recovery manager
*/
public NarayanaTransactionIntegration(
TransactionManager transactionManager,
TransactionSynchronizationRegistry transactionSynchronizationRegistry,
RecoveryManager recoveryManager) {
this.transactionManager = transactionManager;
this.transactionSynchronizationRegistry = transactionSynchronizationRegistry;
this.recoveryManager = recoveryManager;
}
@Override
public void addResourceRecoveryFactory(ResourceRecoveryFactory resourceRecoveryFactory) {
XARecoveryModule xaRecoveryModule =
(XARecoveryModule)
recoveryManager.getModules().stream()
.filter(recoveryModule -> recoveryModule instanceof XARecoveryModule)
.findFirst()
.orElse(null);
if (xaRecoveryModule == null) {
throw new IllegalStateException(
"Failed to retrieve the XARecoveryModule from the Narayana Recovery Manager");
}
xaRecoveryModule.addXAResourceRecoveryHelper(
xaResourceRecoveryHelperImplCache.computeIfAbsent(
resourceRecoveryFactory,
rrf -> new XAResourceRecoveryHelperImpl(new RecoveryXAResource(rrf))));
}
@Override
public void associate(TransactionAware transactionAware, XAResource xaResource)
throws SQLException {
try {
if (transactionRunning()) {
if (transactionSynchronizationRegistry.getResource(key) == null) {
transactionSynchronizationRegistry.registerInterposedSynchronization(
new InterposedSynchronization(transactionAware));
transactionSynchronizationRegistry.putResource(key, transactionAware);
XAResource xaResourceToEnlist;
if (xaResource != null) {
xaResourceToEnlist = new TransactionAwareXAResource(transactionAware, xaResource);
} else {
xaResourceToEnlist = new LocalXAResource(transactionAware);
}
transactionManager.getTransaction().enlistResource(xaResourceToEnlist);
} else {
transactionAware.transactionStart();
}
}
transactionAware.transactionCheckCallback(this::transactionRunning);
} catch (Exception e) {
throw new SQLException("Failed to associate the connection with an existing transaction", e);
}
}
@Override
public boolean disassociate(TransactionAware transactionAware) {
if (transactionRunning()) {
transactionSynchronizationRegistry.putResource(key, null);
}
return true;
}
@Override
public TransactionAware getTransactionAware() {
if (transactionRunning()) {
return (TransactionAware) transactionSynchronizationRegistry.getResource(key);
}
return null;
}
@Override
public void removeResourceRecoveryFactory(ResourceRecoveryFactory resourceRecoveryFactory) {
XARecoveryModule xaRecoveryModule =
(XARecoveryModule)
recoveryManager.getModules().stream()
.filter(recoveryModule -> recoveryModule instanceof XARecoveryModule)
.findFirst()
.orElse(null);
if (xaRecoveryModule == null) {
throw new IllegalStateException(
"Failed to retrieve the XARecoveryModule from the Narayana Recovery Manager");
}
xaRecoveryModule.removeXAResourceRecoveryHelper(
xaResourceRecoveryHelperImplCache.remove(resourceRecoveryFactory));
}
private boolean transactionRunning() {
return TransactionUtil.transactionExists(transactionManager);
}
private static class InterposedSynchronization implements Synchronization {
private final TransactionAware transactionAware;
InterposedSynchronization(TransactionAware transactionAware) {
this.transactionAware = transactionAware;
}
public void afterCompletion(int status) {
try {
transactionAware.transactionEnd();
} catch (Throwable ignored) {
}
}
public void beforeCompletion() {}
}
/**
* The <b>XAResourceRecoveryImpl</b> class provides an implementation of the the
* XAResourceRecoveryHelper interface.
*
* @author Marcus Portmann
*/
private static class XAResourceRecoveryHelperImpl implements XAResourceRecoveryHelper {
private final XAResource[] xaResources;
public XAResourceRecoveryHelperImpl(XAResource xaResource) {
this.xaResources = new XAResource[1];
this.xaResources[0] = xaResource;
}
@Override
public XAResource[] getXAResources() {
return xaResources;
}
@Override
public boolean initialise(String p) {
return true;
}
}
}
|
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/agroal/RecoveryXAResource.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.agroal;
import africa.absa.inception.jta.util.XAExceptionUtil;
import io.agroal.api.transaction.TransactionIntegration.ResourceRecoveryFactory;
import java.sql.SQLException;
import javax.sql.XAConnection;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
* The <b>RecoveryXAResource</b> class provides a closeable wrapper around the XAResource associated
* with an XAConnection that keeps track of the lifecycle of the XAResource and closes the
* connection when required.
*
* @author Marcus Portmann
*/
public class RecoveryXAResource implements AutoCloseable, XAResource {
private final ResourceRecoveryFactory resourceRecoveryFactory;
private XAConnection xaConnection;
private XAResource xaResource;
/**
* Constructs a new <b>RecoveryXAResource</b>.
*
* @param resourceRecoveryFactory the resource recovery factory
*/
public RecoveryXAResource(ResourceRecoveryFactory resourceRecoveryFactory) {
this.resourceRecoveryFactory = resourceRecoveryFactory;
}
@Override
public void close() throws XAException {
try {
if (xaConnection != null) {
xaConnection.close();
}
} catch (SQLException e) {
XAExceptionUtil.xaException(XAException.XAER_RMFAIL, "Failed to close the XAConnection", e);
} finally {
xaConnection = null;
xaResource = null;
}
}
@Override
public void commit(Xid xid, boolean onePhase) throws XAException {
xaResource.commit(xid, onePhase);
}
@Override
public void end(Xid xid, int flags) throws XAException {
xaResource.end(xid, flags);
}
@Override
public void forget(Xid xid) throws XAException {
xaResource.forget(xid);
}
@Override
public int getTransactionTimeout() throws XAException {
return xaResource.getTransactionTimeout();
}
@Override
public boolean isSameRM(XAResource xaResource) throws XAException {
if (xaResource instanceof RecoveryXAResource) {
return this.xaResource.isSameRM(((RecoveryXAResource) xaResource).xaResource);
} else {
return this.xaResource.isSameRM(xaResource);
}
}
@Override
public int prepare(Xid xid) throws XAException {
return xaResource.prepare(xid);
}
@Override
public Xid[] recover(int flag) throws XAException {
if (flag == TMSTARTRSCAN) {
try {
xaConnection = resourceRecoveryFactory.getRecoveryConnection();
xaResource = xaConnection.getXAResource();
} catch (SQLException e) {
XAExceptionUtil.xaException(
XAException.XAER_RMFAIL,
"Failed to retrieve the recovery XAConnection from the ResourceRecoveryFactory",
e);
}
}
if (xaConnection == null) {
throw new XAException(XAException.XAER_RMFAIL);
}
Xid[] value = xaResource.recover(flag);
if (flag == TMENDRSCAN && (value == null || value.length == 0)) {
close();
}
return value;
}
@Override
public void rollback(Xid xid) throws XAException {
xaResource.rollback(xid);
}
@Override
public boolean setTransactionTimeout(int seconds) throws XAException {
return xaResource.setTransactionTimeout(seconds);
}
@Override
public void start(Xid xid, int flags) throws XAException {
xaResource.start(xid, flags);
}
}
|
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/agroal/TransactionAwareXAResource.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.agroal;
import africa.absa.inception.jta.util.XAExceptionUtil;
import io.agroal.api.transaction.TransactionAware;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
* The <b>TransactionAwareXAResource</b> class provides a wrapper for a transactional resource,
* which is represented as both a XAResource object and an Agroal transaction aware connection
* resource. The wrapper ensures that transactional behavior, i.e. start, commit, rollback, etc., is
* propagated to both the underlying XAResource object and the TransactionAware object.
*
* @author Marcus Portmann
* @see <a
* href="https://github.com/agroal/agroal/blob/master/agroal-narayana/src/main/java/io/agroal/narayana/BaseXAResource.java">BaseXAResource.java</a>
*/
public class TransactionAwareXAResource implements XAResource {
/** The Agroal transaction aware connection resource. */
private final TransactionAware transactionAware;
/** The underlying XA resource. */
private final XAResource xaResource;
/**
* Constructs a new <b>TransactionAwareXAResource</b>.
*
* @param transactionAware the Agroal transaction aware connection resource
* @param xaResource the underlying XA resource
*/
public TransactionAwareXAResource(TransactionAware transactionAware, XAResource xaResource) {
this.transactionAware = transactionAware;
this.xaResource = xaResource;
}
@Override
public void commit(Xid xid, boolean onePhase) throws XAException {
try {
transactionAware.transactionBeforeCompletion(true);
xaResource.commit(xid, onePhase);
} catch (XAException e) {
transactionAware.setFlushOnly();
throw e;
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
onePhase ? XAException.XA_RBROLLBACK : XAException.XAER_RMERR,
"Failed to commit the XA transaction ("
+ xid
+ ") for the XA resource: "
+ e.getMessage(),
e);
}
}
@Override
public void end(Xid xid, int flags) throws XAException {
try {
xaResource.end(xid, flags);
} catch (XAException e) {
transactionAware.setFlushOnly();
throw e;
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to end the transaction (" + xid + ") for the XA resource: " + e.getMessage(),
e);
}
}
@Override
public void forget(Xid xid) throws XAException {
try {
xaResource.forget(xid);
} catch (XAException e) {
transactionAware.setFlushOnly();
throw e;
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to forget the transaction (" + xid + ") for the XA resource: " + e.getMessage(),
e);
}
}
@Override
public int getTransactionTimeout() throws XAException {
try {
return xaResource.getTransactionTimeout();
} catch (XAException e) {
transactionAware.setFlushOnly();
throw e;
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to retrieve the transaction timeout for the XA resource: " + e.getMessage(),
e);
}
}
@Override
public boolean isSameRM(XAResource xaResource) throws XAException {
try {
if (xaResource instanceof TransactionAwareXAResource) {
return this.xaResource.isSameRM(((TransactionAwareXAResource) xaResource).xaResource);
} else {
return this.xaResource.isSameRM(xaResource);
}
} catch (XAException e) {
transactionAware.setFlushOnly();
throw e;
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to determine whether the XA resource has the same resource manager: "
+ e.getMessage(),
e);
}
}
@Override
public int prepare(Xid xid) throws XAException {
try {
return xaResource.prepare(xid);
} catch (XAException e) {
transactionAware.setFlushOnly();
throw e;
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to prepare the transaction for the XA resource: " + e.getMessage(),
e);
}
}
@Override
public Xid[] recover(int flag) throws XAException {
try {
return xaResource.recover(flag);
} catch (XAException e) {
transactionAware.setFlushOnly();
throw e;
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to retrieve the list of prepared transaction branches from the resource manager "
+ "for the XA resource: "
+ e.getMessage(),
e);
}
}
@Override
public void rollback(Xid xid) throws XAException {
try {
transactionAware.transactionBeforeCompletion(false);
xaResource.rollback(xid);
} catch (XAException e) {
transactionAware.setFlushOnly();
throw e;
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to rollback the transaction (" + xid + ") for the XA resource: " + e.getMessage(),
e);
}
}
@Override
public boolean setTransactionTimeout(int seconds) throws XAException {
try {
return xaResource.setTransactionTimeout(seconds);
} catch (XAException e) {
transactionAware.setFlushOnly();
throw e;
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to set the transaction timeout for the XA resource: " + e.getMessage(),
e);
}
}
@Override
public void start(Xid xid, int flags) throws XAException {
try {
transactionAware.transactionStart();
xaResource.start(xid, flags);
} catch (XAException e) {
transactionAware.setFlushOnly();
throw e;
} catch (Throwable e) {
transactionAware.setFlushOnly();
throw XAExceptionUtil.xaException(
XAException.XAER_RMERR,
"Failed to start the transaction (" + xid + ") for the XA resource: " + e.getMessage(),
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/narayana/NarayanaFactory.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.narayana;
import africa.absa.inception.jta.agroal.NarayanaTransactionIntegration;
import com.arjuna.ats.arjuna.coordinator.TxControl;
import com.arjuna.ats.arjuna.recovery.RecoveryManager;
import io.agroal.api.transaction.TransactionIntegration;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import javax.transaction.UserTransaction;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.jta.JtaTransactionManager;
/**
* The <b>NarayanaFactory</b> class produces the JTA transaction management beans for the Narayana
* transactions toolkit.
*
* @author Marcus Portmann
* @see <a href="https://narayana.io">Naryana</a>
*/
@Component
@SuppressWarnings("unused")
public class NarayanaFactory {
static {
TxControl.setXANodeName(nodeName());
}
/**
* Retrieve the XA node name.
*
* @return the XA node name
*/
private static String nodeName() {
try {
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
return localMachine.getHostName().toLowerCase();
} catch (Throwable e) {
return "Unknown";
}
}
/**
* Returns the Narayana recovery manager.
*
* @return the Narayana recovery manager
*/
@Bean
public RecoveryManager narayanaRecoveryManager() {
RecoveryManager recoveryManager = RecoveryManager.manager();
recoveryManager.initialize();
return RecoveryManager.manager();
}
/**
* Returns the Narayana transaction integration.
*
* @param transactionManager the transaction manager
* @param transactionSynchronizationRegistry the transaction synchronization registry
* @param recoveryManager the recovery manager
* @return the Narayana transaction integration
*/
@Bean
public TransactionIntegration narayanaTransactionIntegration(
TransactionManager transactionManager,
TransactionSynchronizationRegistry transactionSynchronizationRegistry,
RecoveryManager recoveryManager) {
return new NarayanaTransactionIntegration(
transactionManager, transactionSynchronizationRegistry, recoveryManager);
}
/**
* Returns the Narayana JTA transaction manager.
*
* @return the Narayana JTA transaction manager
*/
@Bean
public TransactionManager narayanaTransactionManager() {
return com.arjuna.ats.jta.TransactionManager.transactionManager();
}
/**
* Returns the Narayana JTA transaction synchronization registry.
*
* @param transactionManager the transaction manager
* @return the Narayana JTA transaction synchronization registry
*/
@Bean
public TransactionSynchronizationRegistry narayanaTransactionSynchronizationRegistry(
TransactionManager transactionManager) {
return new com.arjuna.ats.internal.jta.transaction.arjunacore
.TransactionSynchronizationRegistryImple();
}
/**
* Returns the Narayana JTA user transaction.
*
* @return the Narayana JTA user transaction
*/
@Bean
public UserTransaction narayanaUserTransaction() {
return com.arjuna.ats.jta.UserTransaction.userTransaction();
}
/**
* Returns the Spring JTA platform transaction manager.
*
* @param userTransaction the user transaction
* @param transactionManager the transaction manager
* @return the Spring JTA platform transaction manager
*/
@Bean
public PlatformTransactionManager transactionManager(
UserTransaction userTransaction, TransactionManager transactionManager) {
try {
return new JtaTransactionManager(userTransaction, transactionManager);
} catch (Throwable e) {
throw new RuntimeException("Failed to initialize the JTA transaction manager");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.