Code development platform for open source projects from the European Union institutions :large_blue_circle: EU Login authentication by SMS has been phased out. To see alternatives please check here

Skip to content
Snippets Groups Projects
Commit 8b67fbba authored by Flavio SANTOS's avatar Flavio SANTOS
Browse files

Merge pull request #67 in EDELIVERY/smp from...

Merge pull request #67 in EDELIVERY/smp from feature/EDELIVERY-2301_refactor_ConfigFile to development

* commit '3da8918b0fefec6772827566b533e07773fb8b80':
  EDELIVERY-2301 Refactored ConfigFile class, used @Value annotation instead
  EDELIVERY-2301 Refactored ConfigFile class, used @Value annotation instead
  EDELIVERY-2301 Refactored ConfigFile class, used @Value annotation instead
  EDELIVERY-2301 Refactored ConfigFile class, used @Value annotation instead
  EDELIVERY-2301 Refactored ConfigFile class, used @Value annotation instead
  EDELIVERY-2301 Refactored ConfigFile class, used @Value annotation instead
  EDELIVERY-2301 Refactored ConfigFile class, used @Value annotation instead
parents 55b8ca2a e8a04fcd
No related branches found
No related tags found
No related merge requests found
Showing
with 500 additions and 817 deletions
......@@ -15,15 +15,13 @@
package eu.europa.ec.cipa.smp.server.conversion;
import eu.europa.ec.cipa.smp.server.util.ConfigFile;
import org.oasis_open.docs.bdxr.ns.smp._2016._05.DocumentIdentifier;
import org.oasis_open.docs.bdxr.ns.smp._2016._05.ParticipantIdentifierType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import static eu.europa.ec.smp.api.Identifiers.asParticipantId;
import static eu.europa.ec.smp.api.Identifiers.asString;
......@@ -34,25 +32,19 @@ import static eu.europa.ec.smp.api.Identifiers.asString;
@Component
public class CaseSensitivityNormalizer {
private static final String CASE_SENSITIVE_PARTICIPANT_SCHEMES = "identifiersBehaviour.caseSensitive.ParticipantIdentifierSchemes";
private static final String CASE_SENSITIVE_DOCUMENT_SCHEMES = "identifiersBehaviour.caseSensitive.DocumentIdentifierSchemes";
private List<String> caseSensitiveParticipantSchemes;
private List<String> caseSensitiveDocumentSchemes;
@Autowired
protected ConfigFile config;
@PostConstruct
public void init() {
caseSensitiveParticipantSchemes = new ArrayList<>();
caseSensitiveDocumentSchemes = new ArrayList<>();
for (String scheme : config.getStringList(CASE_SENSITIVE_PARTICIPANT_SCHEMES)) {
caseSensitiveParticipantSchemes.add(scheme.toLowerCase().trim());
}
for (String scheme : config.getStringList(CASE_SENSITIVE_DOCUMENT_SCHEMES)) {
caseSensitiveDocumentSchemes.add(scheme.toLowerCase().trim());
@Value("#{'${identifiersBehaviour.caseSensitive.DocumentIdentifierSchemes}'.split('\\|')}")
public void setCaseSensitiveDocumentSchemes(List<String> caseSensitiveDocumentSchemes) {
this.caseSensitiveDocumentSchemes = caseSensitiveDocumentSchemes;
toLowerCaseStringList(this.caseSensitiveDocumentSchemes);
}
@Value("#{'${identifiersBehaviour.caseSensitive.DocumentIdentifierSchemes}'.split('\\|')}")
public void setCaseSensitiveParticipantSchemes(List<String> caseSensitiveParticipantSchemes) {
this.caseSensitiveParticipantSchemes = caseSensitiveParticipantSchemes;
toLowerCaseStringList(this.caseSensitiveParticipantSchemes);
}
public ParticipantIdentifierType normalize(final ParticipantIdentifierType participantIdentifier) {
......@@ -79,4 +71,10 @@ public class CaseSensitivityNormalizer {
return asString(normalize(asParticipantId(participantId)));
}
private static void toLowerCaseStringList(List<String> strings) {
ListIterator<String> iterator = strings.listIterator();
while (iterator.hasNext()) {
iterator.set(iterator.next().toLowerCase().trim());
}
}
}
......@@ -22,17 +22,18 @@ import eu.europa.ec.bdmsl.ws.soap.UnauthorizedFault;
import eu.europa.ec.cipa.smp.server.security.DoNothingTrustManager;
import eu.europa.ec.cipa.smp.server.security.HostnameVerifierAlwaysTrue;
import eu.europa.ec.cipa.smp.server.security.KeyStoreUtils;
import eu.europa.ec.cipa.smp.server.util.ConfigFile;
import eu.europa.ec.cipa.smp.server.util.to_be_removed.ESuccess;
import eu.europa.ec.cipa.smp.server.util.to_be_removed.VerySecureRandom;
import org.apache.commons.lang3.StringUtils;
import org.busdox.servicemetadata.locator._1.ServiceMetadataPublisherServiceForParticipantType;
import org.oasis_open.docs.bdxr.ns.smp._2016._05.ParticipantIdentifierType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.concurrent.NotThreadSafe;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
......@@ -61,40 +62,39 @@ import java.util.Map;
@Conditional(SMLHookConditionOn.class)
public final class RegistrationServiceRegistrationHook extends AbstractRegistrationHook {
private static final Logger s_aLogger = LoggerFactory.getLogger(RegistrationServiceRegistrationHook.class);
private static final String CLIENT_CERT_HEADER_KEY = "Client-Cert";
private static final String CONFIG_HOOK_REG_LOCATOR_URL = "regServiceRegistrationHook.regLocatorUrl";
private static final String CONFIG_HOOK_ID = "regServiceRegistrationHook.id";
private static final String CONFIG_HOOK_KEYSTORE_CLASSPATH = "regServiceRegistrationHook.keystore.classpath";
private static final String CONFIG_HOOK_KEYSTORE_PASSWORD = "regServiceRegistrationHook.keystore.password";
private static final String CONFIG_HOOK_CLIENT_CERT = "regServiceRegistrationHook.clientCert";
private static final Logger s_aLogger = LoggerFactory.getLogger (RegistrationServiceRegistrationHook.class);
private URL s_aSMLEndpointURL;
private String s_sSMPID;
private String s_sSMPClientCertificate;
private ConfigFile configFile;
@Value("${regServiceRegistrationHook.regLocatorUrl}")
private String hookRegistrationUrl;
@Value("${regServiceRegistrationHook.id}")
private String hookId;
@Value("${regServiceRegistrationHook.keystore.classpath}")
private String hookRegistrationKeystoreClasspath;
@Autowired
public void setConfigFile(ConfigFile configFile){
@Value("${regServiceRegistrationHook.keystore.password}")
private String hookRegistrationKeystorePassword;
this.configFile = configFile;
@Value("${regServiceRegistrationHook.clientCert}")
private String hookClientCert;
@PostConstruct
public void init() {
// SML endpoint (incl. the service name)
final String sURL = configFile.getString (CONFIG_HOOK_REG_LOCATOR_URL);
try {
s_aSMLEndpointURL = new URL (sURL);
}
catch (final MalformedURLException ex) {
throw new IllegalStateException ("Failed to init SML endpoint URL from '" + sURL + "'", ex);
s_aSMLEndpointURL = new URL(hookRegistrationUrl);
} catch (final MalformedURLException ex) {
throw new IllegalStateException("Failed to init SML endpoint URL from '" + hookRegistrationUrl + "'", ex);
}
// SMP ID
s_sSMPID = configFile.getString (CONFIG_HOOK_ID);
s_sSMPClientCertificate = configFile.getString(CONFIG_HOOK_CLIENT_CERT);
s_aLogger.info("Using the following SML address: " + s_aSMLEndpointURL);
s_aLogger.info ("This SMP has the ID: " + s_sSMPID);
s_aLogger.info("This SMP has the ID: " + hookId);
}
private enum EAction {
......@@ -113,7 +113,7 @@ public final class RegistrationServiceRegistrationHook extends AbstractRegistrat
protected IManageParticipantIdentifierWS getSmlCaller() {
Map<String, List<String>> customHeaders = new HashMap<>();
customHeaders.put(CLIENT_CERT_HEADER_KEY, Arrays.asList(s_sSMPClientCertificate));
customHeaders.put(CLIENT_CERT_HEADER_KEY, Arrays.asList(hookClientCert));
final ManageBusinessIdentifierService aService = new ManageBusinessIdentifierService((URL) null);
final IManageParticipantIdentifierWS aPort = aService.getManageBusinessIdentifierServicePort();
......@@ -126,16 +126,12 @@ public final class RegistrationServiceRegistrationHook extends AbstractRegistrat
private void _setupSSLSocketFactory() {
// Keystore for SML access:
try {
final String sKeystorePath = configFile.getString (CONFIG_HOOK_KEYSTORE_CLASSPATH);
final String sKeystorePassword = configFile.getString (CONFIG_HOOK_KEYSTORE_PASSWORD);
final String sRegLocatorUrl = configFile.getString (CONFIG_HOOK_REG_LOCATOR_URL);
// Main key storage
final KeyStore aKeyStore = KeyStoreUtils.loadKeyStore (sKeystorePath, sKeystorePassword);
final KeyStore aKeyStore = KeyStoreUtils.loadKeyStore(hookRegistrationKeystoreClasspath, hookRegistrationKeystorePassword);
// Key manager
final KeyManagerFactory aKeyManagerFactory = KeyManagerFactory.getInstance("SunX509");
aKeyManagerFactory.init (aKeyStore, sKeystorePassword.toCharArray ());
aKeyManagerFactory.init(aKeyStore, hookRegistrationKeystorePassword.toCharArray());
// Trust manager
......@@ -145,11 +141,10 @@ public final class RegistrationServiceRegistrationHook extends AbstractRegistrat
new TrustManager[]{new DoNothingTrustManager()},
VerySecureRandom.getInstance());
HttpsURLConnection.setDefaultSSLSocketFactory(aSSLCtx.getSocketFactory());
if (sRegLocatorUrl.contains ("localhost")) {
if (hookRegistrationUrl.contains("localhost")) {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifierAlwaysTrue());
}
}
catch (final Exception ex) {
} catch (final Exception ex) {
throw new IllegalStateException("Failed to init keyStore for SML access", ex);
}
}
......@@ -166,13 +161,11 @@ public final class RegistrationServiceRegistrationHook extends AbstractRegistrat
aSMLCaller.create(toBusdoxParticipantId(participantId));
s_aLogger.info("Succeeded in creating business " + toString(participantId) + " using Business Identifier Manager Service");
getQueueInstance().set(this);
}
catch (final UnauthorizedFault ex) {
} catch (final UnauthorizedFault ex) {
final String sMsg = "Seems like this SMP is not registered to the SML, or you're providing invalid credentials!";
s_aLogger.warn(sMsg);
throw new HookException(sMsg, ex);
}
catch (final Throwable t) {
} catch (final Throwable t) {
final String sMsg = "Could not create business " + toString(participantId) + " in Business Identifier Manager Service";
s_aLogger.warn(sMsg, t);
throw new HookException(sMsg, t);
......@@ -181,11 +174,19 @@ public final class RegistrationServiceRegistrationHook extends AbstractRegistrat
private ServiceMetadataPublisherServiceForParticipantType toBusdoxParticipantId(ParticipantIdentifierType aPI) {
ServiceMetadataPublisherServiceForParticipantType busdoxIdentifier = new ServiceMetadataPublisherServiceForParticipantType();
busdoxIdentifier.setServiceMetadataPublisherID(s_sSMPID);
if (StringUtils.isEmpty(hookId)) {
throw new HookException("SMP ID is null or empty");
}
busdoxIdentifier.setServiceMetadataPublisherID(hookId);
if (StringUtils.isEmpty(aPI.getScheme()) || StringUtils.isEmpty(aPI.getValue())) {
throw new HookException("Participant Scheme or Id is null or empty");
}
org.busdox.transport.identifiers._1.ParticipantIdentifierType parId = new org.busdox.transport.identifiers._1.ParticipantIdentifierType();
parId.setScheme(aPI.getScheme());
parId.setValue(aPI.getValue());
busdoxIdentifier.setParticipantIdentifier(parId);
return busdoxIdentifier;
}
......@@ -201,11 +202,9 @@ public final class RegistrationServiceRegistrationHook extends AbstractRegistrat
aSMLCaller.delete(toBusdoxParticipantId(participantId));
s_aLogger.info("Succeded in deleting business " + toString(participantId) + " using Business Identifier Manager Service");
getQueueInstance().set(this);
}
catch (final NotFoundFault e) {
} catch (final NotFoundFault e) {
s_aLogger.warn("The business " + toString(participantId) + " was not present in the SML. Just ignore.");
}
catch (final Throwable t) {
} catch (final Throwable t) {
final String sMsg = "Could not delete business " + toString(participantId) + " in Business Identifier Manager Service";
s_aLogger.warn(sMsg, t);
throw new HookException(sMsg, t);
......@@ -231,8 +230,7 @@ public final class RegistrationServiceRegistrationHook extends AbstractRegistrat
aSMLCaller.create(toBusdoxParticipantId(m_aBusinessIdentifier));
break;
}
}
catch (final Throwable t) {
} catch (final Throwable t) {
throw new HookException("Unable to rollback update business " + toString(m_aBusinessIdentifier), t);
}
}
......
......@@ -15,13 +15,10 @@
package eu.europa.ec.cipa.smp.server.hook;
import eu.europa.ec.cipa.smp.server.util.ConfigFile;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import java.io.IOException;
/**
* Created by gutowpa on 13/07/2017.
*/
......@@ -29,12 +26,7 @@ public class SMLHookConditionOff implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String className = null;
try {
className = new ConfigFile("smp.config.properties").getString("registrationHook.class");
String className = context.getEnvironment().getProperty("registrationHook.class");
return "eu.europa.ec.cipa.smp.server.hook.DoNothingRegistrationHook".equals(className);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
......@@ -15,13 +15,10 @@
package eu.europa.ec.cipa.smp.server.hook;
import eu.europa.ec.cipa.smp.server.util.ConfigFile;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import java.io.IOException;
/**
* Created by gutowpa on 13/07/2017.
*/
......@@ -29,12 +26,7 @@ public class SMLHookConditionOn implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String className = null;
try {
className = new ConfigFile("smp.config.properties").getString("registrationHook.class");
String className = context.getEnvironment().getProperty("registrationHook.class");
return "eu.europa.ec.cipa.smp.server.hook.RegistrationServiceRegistrationHook".equals(className);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
......@@ -36,29 +36,12 @@ import java.util.ArrayList;
*/
@Service
public final class BaseServiceGroupInterfaceImpl {
private static final Logger s_aLogger = LoggerFactory.getLogger (BaseServiceGroupInterfaceImpl.class);
private static final Logger s_aLogger = LoggerFactory.getLogger (BaseServiceGroupInterfaceImpl.class);
@Autowired
private DBMSDataManager dataManager;
/*
private static ConfigFile configFile;
static {
/*
* TODO : This is a quick and dirty hack to allow the use of a configuration
* file with an other name if it's in the classpath (like
* smp.config.properties or sml.config.properties). If the configuration
* file defined in applicationContext.xml couldn't be found, then the
* config.properties inside the war is used as a fallback. Needs to be
* properly refactored
*
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext (new String [] { "classpath:applicationContext.xml" });
configFile = (ConfigFile) context.getBean ("configFile");
}
private BaseServiceGroupInterfaceImpl () {}
*/
/**
* @param sServiceGroupID
* Requested service group ID
......
/*
* Copyright 2017 European Commission | CEF eDelivery
*
* Licensed under the EUPL, Version 1.1 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* or file: LICENCE-EUPL-v1.1.pdf
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and limitations under the Licence.
*/
package eu.europa.ec.cipa.smp.server.util;
import eu.europa.ec.cipa.smp.server.util.to_be_removed.ESuccess;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* Used for accessing configuration files based on properties. By default first
* the private (not checked-in) version of the config file called
* <code>private-config.properties</code> is accessed. If no such file is
* present, the default config file (which is also in the SCM) is accessed by
* the name<code>config.properties</code>.<br>
* Additionally you can create a new instance with a custom file path.
*
* @author PEPPOL.AT, BRZ, Philip Helger
*/
@Immutable
@Deprecated
public class ConfigFile {
public static final String LIST_SEPARATOR = "\\|";
public static final String EMPTY_STRING = "";
private static final class SingletonHolder {
static final ConfigFile s_aInstance = new ConfigFile ();
}
/** Default file name for the private config file */
public static final String DEFAULT_PRIVATE_CONFIG_PROPERTIES = "private-config.properties";
/** Default file name for the regular config file */
public static final String DEFAULT_CONFIG_PROPERTIES = "config.properties";
private static final Logger s_aLogger = LoggerFactory.getLogger (ConfigFile.class);
private final boolean m_bRead;
private final Properties m_aProps = new Properties ();
/**
* Default constructor for the default file paths (private-config.properties
* and afterwards config.properties)
*/
private ConfigFile() {
this(DEFAULT_PRIVATE_CONFIG_PROPERTIES, DEFAULT_CONFIG_PROPERTIES);
}
/**
* Constructor for explicitly specifying a file path to read.
*
* @param aConfigPaths
* The array of paths to the config files to be read. Must be
* classpath-relative. The first file that could be read will be taken
*/
public ConfigFile(@Nonnull final String... aConfigPaths) {
boolean bRead = false;
for (final String sConfigPath : aConfigPaths)
try {
if (_readConfigFile (sConfigPath) == ESuccess.SUCCESS) {
bRead = true;
break;
}
} catch (IOException e) {
throw new RuntimeException("Failed to load config file", e);
}
if (!bRead) {
// No config file found at all
s_aLogger.warn ("Failed to resolve config file paths: " + aConfigPaths);
}
m_bRead = bRead;
}
public ConfigFile(final String configFilePath) throws IOException {
this (configFilePath, DEFAULT_PRIVATE_CONFIG_PROPERTIES, DEFAULT_CONFIG_PROPERTIES);
}
@Nonnull
private ESuccess _readConfigFile (@Nonnull final String sPath) throws IOException {
// Try to get the input stream for the passed property file name
InputStream aIS = ConfigFile.class.getResourceAsStream("/"+sPath);
if (aIS == null) {
try {
// Fallback to file system - maybe this helps...
aIS = new FileInputStream(sPath);
}catch(Exception e){
return ESuccess.FAILURE;
}
}
if (aIS != null) {
try {
// Does not close the input stream!
m_aProps.load (aIS);
if (s_aLogger.isDebugEnabled ())
s_aLogger.debug ("Loaded configuration from '" + sPath + "': " + Collections.list (m_aProps.keys ()));
return ESuccess.SUCCESS;
}
catch (final IOException ex) {
s_aLogger.error ("Failed to read config file '" + sPath + "'", ex);
}
finally {
// Manually close the input stream!
//StreamUtils.close (aIS);
if(aIS!=null){
aIS.close();
}
}
}
return ESuccess.FAILURE;
}
/**
* @return The default configuration file denoted by the file names
* {@value #DEFAULT_PRIVATE_CONFIG_PROPERTIES} and
* {@value #DEFAULT_CONFIG_PROPERTIES}.
*/
@Nonnull
public static ConfigFile getInstance () {
return SingletonHolder.s_aInstance;
}
/**
* @return <code>true</code> if reading succeeded, <code>false</code> if
* reading failed (warning was already logged)
*/
public boolean isRead () {
return m_bRead;
}
/**
* Get the string from the configuration files
*
* @param sKey
* The key to search
* @return <code>null</code> if no such value is in the configuration file.
*/
@Nullable
public String getString (@Nonnull final String sKey) {
return getString (sKey, null);
}
/**
* Get the string from the configuration files
*
* @param sKey
* The key to search
* @param sDefault
* The default value to be returned if the value was not found. May be
* <code>null</code>.
* @return the passed default value if no such value is in the configuration
* file.
*/
@Nullable
public final String getString (@Nonnull final String sKey, @Nullable final String sDefault) {
final String sValue = m_aProps.getProperty (sKey);
return sValue != null ? StringUtils.trim(sValue) : sDefault;
}
@Nullable
public final char [] getCharArray (@Nonnull final String sKey) {
return getCharArray (sKey, null);
}
@Nullable
public final char [] getCharArray (@Nonnull final String sKey, final char [] aDefault) {
final String ret = getString (sKey, null);
return ret == null ? aDefault : ret.toCharArray ();
}
public final boolean getBoolean (@Nonnull final String sKey, final boolean bDefault) {
String val = getString (sKey);
if(StringUtils.isNotBlank(val)){
return Boolean.valueOf(getString (sKey));
}else{
return bDefault;
}
}
public final int getInt (@Nonnull final String sKey, final int nDefault) {
String val = getString (sKey);
if(StringUtils.isNotBlank(val)) {
return Integer.valueOf(val);
} else {
return nDefault;
}
}
public List<String> getStringList(@Nonnull final String sKey) {
List<String> stringsList = Arrays.asList(getString(sKey, EMPTY_STRING).split(LIST_SEPARATOR));
if (stringsList.size() == 1 && stringsList.contains(EMPTY_STRING)) {
return Collections.emptyList(); //configured empty value
} else {
return stringsList;
}
}
/**
* @return A {@link Set} with all keys contained in the configuration file
*/
@Nonnull
public final Set <String> getAllKeys () {
// Convert from Set<Object> to Set<String>
final Set <String> ret = new HashSet <String> ();
for (final Object o : m_aProps.keySet ())
ret.add ((String) o);
return ret;
}
/*
@Override
public String toString () {
return new ToStringGenerator (this).append ("read", m_bRead).append ("props", m_aProps).toString ();
}
*/
}
......@@ -18,10 +18,11 @@ import eu.europa.ec.cipa.smp.server.security.KeyStoreUtils;
import eu.europa.ec.cipa.smp.server.security.Signer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import javax.annotation.PostConstruct;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
......@@ -34,52 +35,57 @@ import java.security.cert.X509Certificate;
@Deprecated // TODO: This is no longer a filter, refactor this garbage.
@Component
public final class SignatureFilter {
public static final String CONFIG_XMLDSIG_KEYSTORE_CLASSPATH = "xmldsig.keystore.classpath";
public static final String CONFIG_XMLDSIG_KEYSTORE_PASSWORD = "xmldsig.keystore.password";
public static final String CONFIG_XMLDSIG_KEYSTORE_KEY_ALIAS = "xmldsig.keystore.key.alias";
public static final String CONFIG_XMLDSIG_KEYSTORE_KEY_PASSWORD = "xmldsig.keystore.key.password";
private static final Logger s_aLogger = LoggerFactory.getLogger(SignatureFilter.class);
@Value("${xmldsig.keystore.classpath}")
private String xmldsigKeystoreClasspath;
@Value("${xmldsig.keystore.password}")
private String xmldsigKeystorePassword;
@Value("${xmldsig.keystore.key.alias}")
private String xmldsigKeystoreKeyAlias;
@Value("${xmldsig.keystore.key.password}")
private String xmldsigKeystoreKeyPassword;
private KeyStore.PrivateKeyEntry m_aKeyEntry;
private X509Certificate m_aCert;
private Signer signer;
@Autowired
public SignatureFilter (ConfigFile configFile) {
@PostConstruct
public void init() {
// Load the KeyStore and get the signing key and certificate.
try {
final String sKeyStoreClassPath = configFile.getString (CONFIG_XMLDSIG_KEYSTORE_CLASSPATH);
final String sKeyStorePassword = configFile.getString (CONFIG_XMLDSIG_KEYSTORE_PASSWORD);
final String sKeyStoreKeyAlias = configFile.getString (CONFIG_XMLDSIG_KEYSTORE_KEY_ALIAS);
final char [] aKeyStoreKeyPassword = configFile.getCharArray (CONFIG_XMLDSIG_KEYSTORE_KEY_PASSWORD);
final KeyStore aKeyStore = KeyStoreUtils.loadKeyStore (sKeyStoreClassPath, sKeyStorePassword);
final KeyStore.Entry aEntry = aKeyStore.getEntry (sKeyStoreKeyAlias,
new KeyStore.PasswordProtection (aKeyStoreKeyPassword));
final KeyStore aKeyStore = KeyStoreUtils.loadKeyStore(xmldsigKeystoreClasspath, xmldsigKeystorePassword);
final KeyStore.Entry aEntry = aKeyStore.getEntry(xmldsigKeystoreKeyAlias,
new KeyStore.PasswordProtection(xmldsigKeystoreKeyPassword.toCharArray()));
if (aEntry == null) {
// Alias not found
throw new IllegalStateException("Failed to find key store alias '" +
sKeyStoreKeyAlias +
"' in keystore '" +
sKeyStorePassword +
xmldsigKeystoreKeyAlias +
"' in keystore with password '" +
xmldsigKeystoreKeyPassword +
"'. Does the alias exist? Is the password correct?");
}
if (!(aEntry instanceof KeyStore.PrivateKeyEntry)) {
// Not a private key
throw new IllegalStateException("The keystore alias '" +
sKeyStoreKeyAlias +
"' was found in keystore '" +
sKeyStorePassword +
xmldsigKeystoreKeyAlias +
"' was found in keystore with password '" +
xmldsigKeystorePassword +
"' but it is not a private key! The internal type is " +
aEntry.getClass().getName());
}
m_aKeyEntry = (KeyStore.PrivateKeyEntry) aEntry;
m_aCert = (X509Certificate) m_aKeyEntry.getCertificate();
s_aLogger.info("Signature filter initialized with keystore '" +
sKeyStoreClassPath +
xmldsigKeystoreClasspath +
"' and alias '" +
sKeyStoreKeyAlias +
xmldsigKeystoreKeyAlias +
"'");
signer = new Signer(m_aKeyEntry.getPrivateKey(), m_aCert);
......@@ -99,8 +105,7 @@ public final class SignatureFilter{
.setLevel (java.util.logging.Level.FINER);
}
*/
}
catch (final Throwable t) {
} catch (final Throwable t) {
s_aLogger.error("Error in constructor of SignatureFilter", t);
throw new IllegalStateException("Error in constructor of SignatureFilter", t);
}
......
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2017 European Commission | CEF eDelivery
~
~ Licensed under the EUPL, Version 1.1 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence");
~ You may not use this work except in compliance with the Licence.
~
~ You may obtain a copy of the Licence at:
~ https://joinup.ec.europa.eu/software/page/eupl
~ or file: LICENCE-EUPL-v1.1.pdf
~
~ Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the Licence for the specific language governing permissions and limitations under the Licence.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:component-scan base-package="eu.europa"/>
<bean id="configFile"
class="eu.europa.ec.cipa.smp.server.util.ConfigFile">
<constructor-arg type="java.lang.String" value="smp.config.properties"/>
</bean>
</beans>
......@@ -15,24 +15,17 @@
package eu.europa.ec.cipa.smp.server.conversion;
import eu.europa.ec.cipa.smp.server.util.ConfigFile;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.oasis_open.docs.bdxr.ns.smp._2016._05.DocumentIdentifier;
import org.oasis_open.docs.bdxr.ns.smp._2016._05.ParticipantIdentifierType;
import java.util.List;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.when;
/**
* Created by gutowpa on 06/03/2017.
......@@ -40,24 +33,13 @@ import static org.mockito.Mockito.when;
@RunWith(JUnitParamsRunner.class)
public class CaseSensitivityNormalizerTest {
private static final String KEY_CASE_SENSITIVE_PARTICIPANT_SCHEMES = "identifiersBehaviour.caseSensitive.ParticipantIdentifierSchemes";
private static final String KEY_CASE_SENSITIVE_DOCUMENT_SCHEMES = "identifiersBehaviour.caseSensitive.DocumentIdentifierSchemes";
private static final List<String> CASE_SENSITIVE_PARTICIPANT_SCHEMES = asList(new String[]{"case-sensitive-scheme-1", "Case-SENSITIVE-Scheme-2"});
private static final List<String> CASE_SENSITIVE_DOCUMENT_SCHEMES = asList(new String[]{"case-sensitive-scheme-1", "Case-SENSITIVE-Scheme-2"});
@InjectMocks
private CaseSensitivityNormalizer normalizer;
@Mock
private ConfigFile configFile;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(configFile.getStringList(KEY_CASE_SENSITIVE_PARTICIPANT_SCHEMES)).thenReturn(CASE_SENSITIVE_PARTICIPANT_SCHEMES);
when(configFile.getStringList(KEY_CASE_SENSITIVE_DOCUMENT_SCHEMES)).thenReturn(CASE_SENSITIVE_DOCUMENT_SCHEMES);
normalizer.init();
public void init() {
normalizer = new CaseSensitivityNormalizer();
normalizer.setCaseSensitiveDocumentSchemes(asList(new String[]{"case-SENSITIVE-scheme-1", "Case-SENSITIVE-Scheme-2"}));
normalizer.setCaseSensitiveParticipantSchemes(asList(new String[]{"case-sensitive-scheme-1", "Case-SENSITIVE-Scheme-2"}));
}
@SuppressWarnings("unused")
......
......@@ -14,20 +14,37 @@
*/
package eu.europa.ec.cipa.smp.server.hook;
import eu.europa.ec.edelivery.smp.config.SmpServicesTestConfig;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.oasis_open.docs.bdxr.ns.smp._2016._05.ParticipantIdentifierType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Test class for class {@link RegistrationServiceRegistrationHook}.
*
* @author PEPPOL.AT, BRZ, Philip Helger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SmpServicesTestConfig.class})
@TestPropertySource(properties = {
"regServiceRegistrationHook.regLocatorUrl=http://localhost:7002/edelivery-sml/manageparticipantidentifier",
"regServiceRegistrationHook.keystore.classpath = C://Development//Tools//oracle//middleware//domain//bdsml//_appconfdir//bdmsl//keystore.jks",
"regServiceRegistrationHook.keystore.password = test",
"regServiceRegistrationHook.clientCert=serial=000000000000000000009A195D2DD88C&subject=CN=SMP_1000000000,O=DG-DIGIT,C=BE&validFrom=Oct 21 02:00:00 2014 CEST&validTo=Oct 21 01:59:59 2016 CEST&issuer=CN=Issuer Common Name,OU=Issuer Organization Unit,O=Issuer Organization,C=BE"
})
public final class RegistrationServiceRegistrationHookTest {
@Autowired
private RegistrationServiceRegistrationHook aHook;
@Test
@Ignore("Potentially modifies the DNS!")
public void testCreateAndDelete() {
final RegistrationServiceRegistrationHook aHook = new RegistrationServiceRegistrationHook ();
final ParticipantIdentifierType aPI = new ParticipantIdentifierType("0088:12345test", "iso6523-actorid-upis");
aHook.create(aPI);
aHook.delete(aPI);
......
......@@ -15,21 +15,83 @@
package eu.europa.ec.edelivery.smp.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
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.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
/**
* Created by gutowpa on 21/09/2017.
*/
@Configuration
@ImportResource("classpath:spring-test-context.xml")
@ComponentScan(basePackages = {
"eu.europa.ec.cipa.smp.server.data.dbms",
"eu.europa.ec.cipa.smp.server.services",
"eu.europa.ec.cipa.smp.server.hook",
"eu.europa.ec.cipa.smp.server.conversion",
"eu.europa.ec.cipa.smp.server.util"})
"eu.europa.ec.cipa.smp.server"})
@PropertySource(value = "classpath:config.properties")
public class SmpServicesTestConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.user}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.url}")
private String url;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName(driver);
driverManagerDataSource.setUrl(url);
driverManagerDataSource.setUsername(username);
driverManagerDataSource.setPassword(password);
return driverManagerDataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean smpEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(dataSource());
lef.setJpaVendorAdapter(jpaVendorAdapter());
lef.setPackagesToScan("eu.europa.ec.cipa.smp.server.data.dbms.model");
lef.setPersistenceXmlLocation("classpath:META-INF/smp-persistence.xml");
return lef;
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
return hibernateJpaVendorAdapter;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2017 European Commission | CEF eDelivery
~
~ Licensed under the EUPL, Version 1.1 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence");
~ You may not use this work except in compliance with the Licence.
~
~ You may obtain a copy of the Licence at:
~ https://joinup.ec.europa.eu/software/page/eupl
~ or file: LICENCE-EUPL-v1.1.pdf
~
~ Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the Licence for the specific language governing permissions and limitations under the Licence.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<context:annotation-config/>
<context:component-scan base-package="eu.europa" />
<bean id="configFile"
class="eu.europa.ec.cipa.smp.server.util.ConfigFile">
<constructor-arg type="java.lang.String" value="smp.config.properties"/>
</bean>
</beans>
......@@ -21,11 +21,15 @@ eclipselink.ddl-generation.output-mode=sql-script
#registrationHook.class=eu.europa.ec.cipa.smp.server.hook.RegistrationServiceRegistrationHook
registrationHook.class=eu.europa.ec.cipa.smp.server.hook.DoNothingRegistrationHook
identifiersBehaviour.caseSensitive.ParticipantIdentifierSchemes=case-sensitive-participant-1|case-sensitive-participant-2
identifiersBehaviour.caseSensitive.DocumentIdentifierSchemes=case-sensitive-doc-1|case-sensitive-doc-2
identifiersBehaviour.caseSensitive.ParticipantIdentifierSchemes=case-sensitive-scheme-1|Case-SENSITIVE-Scheme-2
identifiersBehaviour.caseSensitive.DocumentIdentifierSchemes=case-sensitive-scheme-1|Case-SENSITIVE-Scheme-2
# SMP ID
regServiceRegistrationHook.id=TEST-SMP-ID1
# SMP's certificate - needed only when accessing BDMSL directly through HTTP. The configured "Client-Cert" HTTP header will be added to each BDMSL request(bypassing SSL cert verification made normally by SSL terminator)
regServiceRegistrationHook.clientCert=serial=000000000000000000009A195D2DD88C&subject=CN=SMP_1000000000,O=DG-DIGIT,C=BE&validFrom=Oct 21 02:00:00 2014 CEST&validTo=Oct 21 01:59:59 2016 CEST&issuer=CN=Issuer Common Name,OU=Issuer Organization Unit,O=Issuer Organization,C=BE
# SML URL (incl. the service name)
#regServiceRegistrationHook.regLocatorUrl=https://sml.peppolcentral.org/manageparticipantidentifier
# regServiceRegistrationHook.regLocatorUrl=https://smk.peppolcentral.org/manageparticipantidentifier
......
<!--
~ Copyright 2017 European Commission | CEF eDelivery
~
~ Licensed under the EUPL, Version 1.1 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence");
~ You may not use this work except in compliance with the Licence.
~
~ You may obtain a copy of the Licence at:
~ https://joinup.ec.europa.eu/software/page/eupl
~ or file: LICENCE-EUPL-v1.1.pdf
~
~ Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the Licence for the specific language governing permissions and limitations under the Licence.
-->
<!--
~ Copyright 2017 European Commission | CEF eDelivery
~
~ Licensed under the EUPL, Version 1.1 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence");
~ You may not use this work except in compliance with the Licence.
~
~ You may obtain a copy of the Licence at:
~ https://joinup.ec.europa.eu/software/page/eupl
~ or file: LICENCE-EUPL-v1.1.pdf
~
~ Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the Licence for the specific language governing permissions and limitations under the Licence.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<bean id="configFile" class="eu.europa.ec.cipa.smp.server.util.ConfigFile">
<constructor-arg type="java.lang.String" value="smp.config.properties"/>
</bean>
<bean id="blueCoatEnabled" factory-bean="configFile" factory-method="getString">
<constructor-arg value="authentication.blueCoat.enabled"/>
</bean>
<bean id="encodedSlashesAllowedInUrl" factory-bean="configFile" factory-method="getString">
<constructor-arg value="encodedSlashesAllowedInUrl"/>
</bean>
<!-- TODO: Refactor datasource creation once the application is rewritten into Spring -->
<bean id="jdbcDriver" factory-bean="configFile" factory-method="getString">
<constructor-arg value="jdbc.driver"/>
</bean>
<bean id="jdbcUrl" factory-bean="configFile" factory-method="getString">
<constructor-arg value="jdbc.url"/>
</bean>
<bean id="jdbcUser" factory-bean="configFile" factory-method="getString">
<constructor-arg value="jdbc.user"/>
</bean>
<bean id="jdbcPass" factory-bean="configFile" factory-method="getString">
<constructor-arg value="jdbc.password"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" ref="jdbcDriver"/>
<property name="url" ref="jdbcUrl"/>
<property name="username" ref="jdbcUser"/>
<property name="password" ref="jdbcPass"/>
</bean>
<bean id="smpEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/smp-persistence.xml" />
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="eu.europa.ec.cipa.smp.server.data.dbms.model"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties">
<props/>
</property>
</bean>
<!-- TODO remove together with DBMSDataManager -->
<bean id="smpEntityManager" factory-bean="smpEntityManagerFactory" factory-method="createEntityManager"/>
<tx:annotation-driven transaction-manager="smpTransactionManager"/>
<bean id="smpTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="smpEntityManagerFactory"/>
</bean>
</beans>
\ No newline at end of file
/*
* Copyright 2017 European Commission | CEF eDelivery
*
* Licensed under the EUPL, Version 1.1 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* or file: LICENCE-EUPL-v1.1.pdf
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and limitations under the Licence.
*/
package eu.europa.ec.edelivery.smp.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
/**
* Created by Flavio Santos
*/
@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = {
"eu.europa.ec.cipa.smp.server.data.dbms",
"eu.europa.ec.cipa.smp.server.services",
"eu.europa.ec.cipa.smp.server.hook"})
public class DatabaseConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.user}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${jdbc.url}")
private String url;
@Bean
public DataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName(driver);
driverManagerDataSource.setUrl(url);
driverManagerDataSource.setUsername(username);
driverManagerDataSource.setPassword(password);
return driverManagerDataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean smpEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(dataSource());
lef.setJpaVendorAdapter(jpaVendorAdapter());
lef.setPackagesToScan("eu.europa.ec.cipa.smp.server.data.dbms.model");
lef.setPersistenceXmlLocation("classpath:META-INF/smp-persistence.xml");
return lef;
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
return hibernateJpaVendorAdapter;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
}
......@@ -12,55 +12,27 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and limitations under the Licence.
*/
package eu.europa.ec.cipa.smp.server.util;
import org.junit.Assert;
import org.junit.Test;
package eu.europa.ec.edelivery.smp.config;
import java.util.List;
import static org.junit.Assert.*;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Test class for class {@link ConfigFile}.
*
* @author PEPPOL.AT, BRZ, Philip Helger
* Created by Flavio Santos
*/
public final class ConfigFileTest {
@Test
public void testAll () {
final ConfigFile aCF = ConfigFile.getInstance ();
assertTrue (aCF.isRead ());
// Existing elements
assertEquals ("string", aCF.getString ("element1"));
assertEquals (6, aCF.getCharArray ("element1").length);
assertEquals (2, aCF.getInt ("element2", 5));
assertFalse (aCF.getBoolean ("element3", true));
assertEquals ("abc", aCF.getString ("element4"));
List<String> listElements = aCF.getStringList("aList");
Assert.assertArrayEquals(new String [] {"elem1", "elem2", "elem3"}, listElements.toArray());
// Non-existing elements
assertNull (aCF.getString ("element1a"));
assertNull (aCF.getCharArray ("element1a"));
assertEquals (5, aCF.getInt ("element2a", 5));
assertTrue (aCF.getBoolean ("element3a", true));
assertTrue (aCF.getStringList("anEmptyList").isEmpty());
// All keys
assertEquals (26, aCF.getAllKeys ().size ());
assertNotNull (aCF.toString ());
}
@Test
public void testNonExisting () {
final ConfigFile aCF = new ConfigFile (new String[] {"non-existent-file.xml"});
assertFalse (aCF.isRead ());
assertNull (aCF.getString ("any"));
assertEquals (0, aCF.getAllKeys ().size ());
assertNotNull (aCF.toString ());
@Configuration
@ComponentScan(basePackages = {
"eu.europa.ec"})
@PropertySources({
@PropertySource(value = "classpath:config.properties", ignoreResourceNotFound = true),
@PropertySource(value = "classpath:smp.config.properties", ignoreResourceNotFound = true)
})
public class PropertiesConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
......@@ -17,19 +17,21 @@ package eu.europa.ec.edelivery.smp.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Import;
/**
* Created by gutowpa on 12/07/2017.
*/
@Configuration
@ImportResource("classpath:spring-context.xml")
@ComponentScan(basePackages = {
"eu.europa.ec.edelivery.smp.validation",
"eu.europa.ec.cipa.smp.server.data.dbms",
"eu.europa.ec.cipa.smp.server.services",
"eu.europa.ec.cipa.smp.server.hook",
"eu.europa.ec.cipa.smp.server.conversion",
"eu.europa.ec.cipa.smp.server.util"})
@Import({PropertiesConfig.class, DatabaseConfig.class})
public class SmpAppConfig {
}
......@@ -30,10 +30,9 @@
package eu.europa.ec.edelivery.smp.controllers;
import eu.europa.ec.cipa.smp.server.util.ConfigFile;
import org.oasis_open.docs.bdxr.ns.smp._2016._05.DocumentIdentifier;
import org.oasis_open.docs.bdxr.ns.smp._2016._05.ParticipantIdentifierType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
......@@ -43,7 +42,6 @@ import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UrlPathHelper;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import static eu.europa.ec.smp.api.Identifiers.asString;
......@@ -54,8 +52,8 @@ import static eu.europa.ec.smp.api.Identifiers.asString;
@Component
public class ServiceMetadataPathBuilder {
@Autowired
ConfigFile configFile;
@Value("${contextPath.output:true}")
private boolean keepContext;
public URI getCurrentUri() {
return ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();
......@@ -73,7 +71,6 @@ public class ServiceMetadataPathBuilder {
}
private String getUrlContext() {
boolean keepContext = new Boolean(configFile.getString ("contextPath.output", "true"));
if (keepContext) {
return new UrlPathHelper().getContextPath(getCurrentRequest());
} else {
......
/*
* Copyright 2017 European Commission | CEF eDelivery
*
* Licensed under the EUPL, Version 1.1 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* or file: LICENCE-EUPL-v1.1.pdf
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and limitations under the Licence.
*/
/*
* Copyright 2017 European Commission | CEF eDelivery
*
* Licensed under the EUPL, Version 1.1 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* or file: LICENCE-EUPL-v1.1.pdf
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and limitations under the Licence.
*/
/*
* Copyright 2017 European Commission | CEF eDelivery
*
* Licensed under the EUPL, Version 1.1 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* https://joinup.ec.europa.eu/software/page/eupl
* or file: LICENCE-EUPL-v1.1.pdf
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and limitations under the Licence.
*/
package eu.europa.ec.edelivery.smp.controllers;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
* Created by gutowpa on 07/04/2017.
*/
@Controller
public class UsernameReturningTestController {
@RequestMapping("/getLoggedUsername")
@ResponseBody
public String getLoggedUsername(){
return SecurityContextHolder.getContext().getAuthentication().getName();
}
@RequestMapping("/error")
@ResponseBody
public ResponseEntity error(HttpServletRequest request, Throwable throwable){
return new ResponseEntity(HttpStatus.I_AM_A_TEAPOT);
}
}
......@@ -30,16 +30,14 @@
package eu.europa.ec.edelivery.smp.validation;
import eu.europa.ec.edelivery.smp.error.exceptions.BadRequestException;
import eu.europa.ec.cipa.smp.server.util.ConfigFile;
import eu.europa.ec.cipa.smp.server.util.IdentifierUtils;
import eu.europa.ec.edelivery.smp.error.exceptions.BadRequestException;
import eu.europa.ec.smp.api.Identifiers;
import org.oasis_open.docs.bdxr.ns.smp._2016._05.ParticipantIdentifierType;
import org.oasis_open.docs.bdxr.ns.smp._2016._05.ServiceGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
......@@ -52,22 +50,15 @@ import static eu.europa.ec.edelivery.smp.error.ErrorBusinessCode.WRONG_FIELD;
@Component
public class ServiceGroupValidator {
private static final String CONFIG_SERVICE_GROUP_SCHEME_REGEXP = "identifiersBehaviour.ParticipantIdentifierScheme.validationRegex";
private Pattern schemaPattern;
@Autowired
ConfigFile configFile;
@PostConstruct
public void init() {
String regex = configFile.getString(CONFIG_SERVICE_GROUP_SCHEME_REGEXP);
@Value("${identifiersBehaviour.ParticipantIdentifierScheme.validationRegex}")
public void setRegexPattern(String regex) {
try {
schemaPattern = Pattern.compile(regex);
} catch (PatternSyntaxException | NullPointerException e) {
throw new IllegalStateException("Contact Administrator. ServiceGroup schema pattern is wrongly configured: " + regex);
}
}
public void validate(String serviceGroupId, ServiceGroup serviceGroup) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment