Skip to content
Snippets Groups Projects
Commit f0b3d0cd authored by Jan Zickermann's avatar Jan Zickermann
Browse files

KOP-2139 KOP-2445 setup: Reduce and refactor code from xta-client-example-lib

parent 237a6f18
No related branches found
No related tags found
No related merge requests found
Showing
with 138 additions and 1368 deletions
......@@ -18,6 +18,7 @@
<!-- build versions -->
<cxf.version>4.0.3</cxf.version>
<cxf-xjc.version>4.0.0</cxf-xjc.version>
<jsr305.version>3.0.2</jsr305.version>
<!-- Build settings -->
<timestamp>${maven.build.timestamp}</timestamp>
......@@ -79,6 +80,12 @@
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>${jsr305.version}</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.projectlombok</groupId>
......@@ -90,6 +97,16 @@
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
......
......@@ -3,28 +3,22 @@ package de.ozgcloud.xta.client;
import org.apache.commons.lang3.NotImplementedException;
import de.ozgcloud.xta.client.config.XtaClientConfig;
import de.ozgcloud.xta.client.core.MsgBoxServiceClient;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import de.ozgcloud.xta.client.model.XtaMessage;
import de.ozgcloud.xta.client.model.XtaMessageId;
import de.ozgcloud.xta.client.model.XtaMessageMetaDatasAndHeader;
import genv3.de.xoev.transport.xta.x211.XTAService;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
@Builder(access = AccessLevel.PROTECTED)
@Getter(AccessLevel.PROTECTED)
public class XtaClient {
private MsgBoxServiceClient msgBoxServiceClient;
public XtaClient(final XtaClientConfig config) throws ClientInitializationException {
// MsgPort initialisieren
if (config.getMsgBoxServiceUrl() != null) {
msgBoxServiceClient = MsgBoxServiceClient.builder(config.getMsgBoxServiceUrl())
.setClientCertKeystore(config.getClientCertKeystore())
.setTrustCertKeystore(config.getTrustCertKeystore())
.setHttpProxy(config.getHttpProxy()).setSoapRequestLogging(config.isLogSoapRequest())
.setSoapResponseLogging(config.isLogSoapResponse()).setValidation(config.isValidation())
.setHttpClientPolicy(config.getHttpClientPolicy())
.build();
}
}
private final XTAService service;
private final XtaClientConfig config;
public XtaMessageMetaDatasAndHeader getMessagesMetadata(String xtaIdentifier) {
throw new NotImplementedException("");
......
package de.ozgcloud.xta.client;
import de.ozgcloud.xta.client.config.XtaClientConfig;
import de.ozgcloud.xta.client.config.XtaConfigValidator;
import de.ozgcloud.xta.client.core.XTAServiceFactory;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Builder
public class XtaClientFactory {
private final XtaConfigValidator configValidator;
private final XTAServiceFactory xtaServiceFactory;
private final XtaClientConfig config;
public static XtaClientFactory from(final XtaClientConfig config) {
return XtaClientFactory.builder()
.configValidator(XtaConfigValidator.builder().build())
.xtaServiceFactory(XTAServiceFactory.from(config))
.build();
}
public XtaClient create() throws ClientInitializationException {
configValidator.validate(config);
return XtaClient.builder()
.config(config)
.service(xtaServiceFactory.create())
.build();
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.config;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
/**
* Model-Klasse für eine HttpClientPolicy
*/
@Getter
@Builder
@ToString
public class HttpClientPolicy {
private Integer connectionTimeout;
private Boolean allowChunking;
private Integer receiveTimeOut;
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.config;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
/**
* Model-Klasse für einen HttpProxy
*/
@Getter
@Builder
@ToString(exclude = {"username", "password"})
public class HttpProxy {
private String host;
private Integer port;
private String username;
private String password;
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.config;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
/**
* Model-Klasse für einen Keystore
*/
@Builder
@Getter
@ToString(exclude = {"password"})
public class Keystore {
private String path;
private String password;
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
* XTA-Client Java Library Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.config;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.List;
import de.ozgcloud.xta.client.exception.ClientException;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import de.ozgcloud.xta.client.model.Identifier;
import lombok.AccessLevel;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* Config-Holder for the Xta-Client.
*/
@Getter
@RequiredArgsConstructor
@Setter(value = AccessLevel.PROTECTED)
@Getter
@Builder
@ToString
public class XtaClientConfig {
private List<Identifier> clientIdentifiers;
@NotEmpty(message = "at least one client identifier is required")
private final List<String> clientIdentifiers;
private URL managementServiceUrl;
private URL sendServiceUrl;
private URL msgBoxServiceUrl;
private HttpClientPolicy httpClientPolicy;
private HttpProxy httpProxy;
private Keystore clientCertKeystore;
private Keystore trustCertKeystore;
@NotBlank
private final String managementServiceUrl;
@NotBlank
private final String sendServiceUrl;
@NotBlank
private final String msgBoxServiceUrl;
private boolean validation;
private boolean logSoapRequest;
private boolean logSoapResponse;
@Valid
private final KeyStore clientCertKeystore;
private final boolean schemaValidation;
private final boolean logSoapRequests;
private final boolean logSoapResponses;
public static class XtaClientConfigBuilder {
private XtaClientConfig config = new XtaClientConfig();
public XtaClientConfigBuilder withValidation() {
config.setValidation(true);
return this;
}
public XtaClientConfigBuilder withSoapLogging() {
config.setLogSoapRequest(true);
config.setLogSoapResponse(true);
return this;
}
public XtaClientConfigBuilder withHttpClientPolicy(final HttpClientPolicy policy) {
config.setHttpClientPolicy(policy);
return this;
}
public XtaClientConfigBuilder withHttpProxy(final HttpProxy proxy) {
config.setHttpProxy(proxy);
return this;
}
public XtaClientConfig build() {
return this.config;
}
}
public static XtaClientConfigBuilder create(final URL manangementServiceUrl, final URL sendServiceUrl,
final URL msgBoxServiceUrl, final List<Identifier> clientIdentifiers, final String clientCertKeystore,
final String clientCertKeyStorePassword, final String trustCertKeystore, final String trustCertKeyStorePassword) {
final XtaClientConfigBuilder builder = new XtaClientConfigBuilder();
builder.config.setMsgBoxServiceUrl(msgBoxServiceUrl);
builder.config.setManagementServiceUrl(manangementServiceUrl);
builder.config.setSendServiceUrl(sendServiceUrl);
builder.config.setClientIdentifiers(clientIdentifiers);
builder.config
.setClientCertKeystore(Keystore.builder().path(clientCertKeystore).password(clientCertKeyStorePassword).build());
builder.config.setTrustCertKeystore(Keystore.builder().path(trustCertKeystore).password(trustCertKeyStorePassword).build());
return builder;
}
public static XtaClientConfigBuilder create(final XtaClientSettings settings) throws ClientException {
return create(List.of(Identifier.from(settings)), settings);
}
public static XtaClientConfigBuilder create(final List<Identifier> clientIdentifiers, final XtaClientSettings settings) throws ClientException {
try {
// Endpoint-URLs
final URL manangementServiceUrl = URI.create(settings.get(XtaClientSettings.BROKER_MANAGEMENT_SERVICE_ENDPONIT)).toURL();
final URL sendServiceUrl = URI.create(settings.get(XtaClientSettings.BROKER_SEND_SERVICE_ENDPOINT)).toURL();
final URL msgBoxServiceUrl = URI.create(settings.get(XtaClientSettings.BROKER_MSGBOX_SERVICE_ENDPOINT)).toURL();
// Clientcert
final String clientCertKeystore = settings.get(XtaClientSettings.CLIENT_KEYSTORE_CERT_PATH);
final String clientCertKeyStorePassword = settings.get(XtaClientSettings.CLIENT_KEYSTORE_CERT_PASSPHRASE);
// Servercert
final String trustCertKeystore = settings.get(XtaClientSettings.BROKER_KEYSTORE_TRUSTCERT_PATH);
final String trustCertKeyStorePassword = settings.get(XtaClientSettings.BROKER_KEYSTORE_TRUSTCERT_PASSPHRASE);
return create(manangementServiceUrl, sendServiceUrl, msgBoxServiceUrl, clientIdentifiers, clientCertKeystore,
clientCertKeyStorePassword, trustCertKeystore, trustCertKeyStorePassword);
} catch (MalformedURLException e) {
throw new ClientInitializationException("Some URLs could not be parsed: " + e.getMessage(), e);
}
@RequiredArgsConstructor
@Getter
@Builder
@ToString
public static class KeyStore {
@NotNull
private final byte[] content;
@NotBlank
private final String type;
@NotNull
private final char[] password;
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
/**
* Klasse zum Laden der Settings über eine Propertie-Datei.
*/
public final class XtaClientSettings {
public final static String BROKER_MANAGEMENT_SERVICE_ENDPONIT = "broker.manangement-service.endpoint";
public final static String BROKER_SEND_SERVICE_ENDPOINT = "broker.send-service.endpoint";
public final static String BROKER_MSGBOX_SERVICE_ENDPOINT = "broker.msgbox-service.endpoint";
public final static String BROKER_KEYSTORE_TRUSTCERT_PATH = "broker.keystore.trustcert.path";
public final static String BROKER_KEYSTORE_TRUSTCERT_PASSPHRASE = "broker.keystore.trustcert.passphrase";
public final static String CLIENT_KEYSTORE_CERT_PATH = "client.keystore.cert.path";
public final static String CLIENT_KEYSTORE_CERT_PASSPHRASE = "client.keystore.cert.passphrase";
public final static String CLIENT_IDENTIFIER_ID_KEY = "client.identifier.id";
public final static String CLIENT_IDENTIFIER_TYPE_KEY = "client.identifier.type";
public final static String CLIENT_IDENTIFIER_CATEGORY_KEY = "client.identifier.category";
public final static String CLIENT_IDENTIFIER_NAME_KEY = "client.identifier.name";
private Properties props = new Properties();
public XtaClientSettings(final InputStream is) throws ClientInitializationException {
try {
props.load(is);
if (props.size() == 0) {
throw new ClientInitializationException("Properties sind nicht initialisiert.");
}
} catch (final IOException e) {
throw new ClientInitializationException("Properties konnten nicht geladen werden.");
}
}
public String get(String key) {
return (String) props.get(key);
}
}
package de.ozgcloud.xta.client.config;
import static lombok.AccessLevel.*;
import java.util.stream.Collectors;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor(access = PRIVATE)
@Builder
public class XtaConfigValidator {
private final static Validator VALIDATOR;
static {
try (var factory = Validation.buildDefaultValidatorFactory()) {
VALIDATOR = factory.getValidator();
}
}
public void validate(final XtaClientConfig config) throws ClientInitializationException {
var violations = VALIDATOR.validate(config);
if (!violations.isEmpty()) {
throw new ClientInitializationException("Client configuration is invalid:\n" + violations.stream()
.map(v -> "'%s' %s".formatted(v.getPropertyPath().toString(), v.getMessage()))
.collect(Collectors.joining("\n")));
}
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.cxf.binding.soap.interceptor.SoapPreProtocolOutInterceptor;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import lombok.extern.slf4j.Slf4j;
/**
* Klasse um leere Namespace-Angaben zu entfernen.
*/
@Slf4j
class EmptyNamespaceMessageOutInterceptor extends AbstractPhaseInterceptor<Message> {
public EmptyNamespaceMessageOutInterceptor() {
super(Phase.PRE_STREAM);
addBefore(SoapPreProtocolOutInterceptor.class.getName());
}
public void handleMessage(Message message) {
OutputStream os = message.getContent(OutputStream.class);
CachedStream cs = new CachedStream();
message.setContent(OutputStream.class, cs);
message.getInterceptorChain().doIntercept(message);
try {
cs.flush();
closeQuietly(cs);
CachedOutputStream csnew = (CachedOutputStream) message.getContent(OutputStream.class);
String currentEnvelopeMessage = IOUtils
.toString(csnew.getInputStream(), "UTF-8");
csnew.flush();
closeQuietly(csnew);
if (log.isDebugEnabled()) {
log.debug("Outbound message: " + currentEnvelopeMessage);
}
String res = changeOutboundMessage(currentEnvelopeMessage);
if (res != null) {
if (log.isDebugEnabled()) {
log.debug("Outbound message has been changed: " + res);
}
}
res = res != null ? res : currentEnvelopeMessage;
InputStream replaceInStream = IOUtils
.toInputStream(res, "UTF-8");
IOUtils.copy(replaceInStream, os);
replaceInStream.close();
closeQuietly(replaceInStream);
os.flush();
message.setContent(OutputStream.class, os);
closeQuietly(os);
} catch (IOException ioe) {
log.error("Unable to perform change.", ioe);
throw new RuntimeException(ioe);
}
}
protected String changeOutboundMessage(String currentEnvelope) {
currentEnvelope = currentEnvelope.replace("xmlns=\"\"", "");
return currentEnvelope;
}
private static class CachedStream extends CachedOutputStream {
public CachedStream() {
super();
}
}
// WA - closeQuietly aus IOUtils ist veraltet, daher hier eine eigene Iplementierung
private static void closeQuietly(final Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (final IOException ioe) {
// ignore
}
}
}
\ No newline at end of file
/**
* XTA-Client Java Library Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.net.URL;
import org.apache.cxf.ws.addressing.AttributedURIType;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import genv3.de.xoev.transport.xta.x211.CancelDeniedException;
import genv3.de.xoev.transport.xta.x211.InvalidMessageIDException;
import genv3.de.xoev.transport.xta.x211.LookupServiceRequest;
import genv3.de.xoev.transport.xta.x211.LookupServiceResponse;
import genv3.de.xoev.transport.xta.x211.ManagementPortType;
import genv3.de.xoev.transport.xta.x211.ParameterIsNotValidException;
import genv3.de.xoev.transport.xta.x211.PermissionDeniedException;
import genv3.de.xoev.transport.xta.x211.TransportReport;
import genv3.de.xoev.transport.xta.x211.XTAService;
import genv3.de.xoev.transport.xta.x211.XTAWSTechnicalProblemException;
import genv3.eu.osci.ws.x2014.x10.transport.PartyType;
import lombok.extern.slf4j.Slf4j;
/**
* gewrapte Serviceklasse für den ManagementServcice eines Brokers
*/
@Slf4j
public class ManagementServiceClient extends WsClient<ManagementPortType> {
public static ManagementServiceClientBuilder builder(final URL serviceUrl) {
return new ManagementServiceClientBuilder(serviceUrl);
}
public ManagementServiceClient(final WsClientConfig conf) throws ClientInitializationException {
this.clientConfiguration = conf;
ManagementServiceClient.log.info(VersionInfo.getInfo());
ManagementServiceClient.log.info(this.clientConfiguration.toString());
this.initializeService();
}
@Override
void initializePort(final URL url) {
final XTAService service = new XTAService(url);
port = service.getManagementPort();
}
public void checkAccountActive(final PartyType authorIdentifier)
throws PermissionDeniedException, XTAWSTechnicalProblemException {
port.checkAccountActive(authorIdentifier);
}
public TransportReport getTransportReport(final AttributedURIType messageID, final PartyType authorIdentifier)
throws PermissionDeniedException, XTAWSTechnicalProblemException, InvalidMessageIDException {
return port.getTransportReport(messageID, authorIdentifier);
}
public void cancelMessage(final AttributedURIType messageID, final PartyType authorIdentifier)
throws XTAWSTechnicalProblemException, PermissionDeniedException, CancelDeniedException, ParameterIsNotValidException {
port.cancelMessage(messageID, authorIdentifier);
}
public LookupServiceResponse lookupService(final LookupServiceRequest lookupServiceRequest, final PartyType authorIdentifier)
throws ParameterIsNotValidException, PermissionDeniedException, XTAWSTechnicalProblemException {
return port.lookupService(lookupServiceRequest, authorIdentifier);
}
public AttributedURIType createMessageId(final PartyType authorIdentifier)
throws PermissionDeniedException, XTAWSTechnicalProblemException {
return port.createMessageId(authorIdentifier);
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.net.URL;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Konstruiert eine Instanz des {@link WsClient}.
*/
@Getter(AccessLevel.PACKAGE)
@Slf4j
public class ManagementServiceClientBuilder extends ServiceBuilder<ManagementServiceClient> {
/**
* Initialisiert einen {@link ServiceBuilder} mit ServiceUrl-Host und ServiceUrl-Port.
*
* @param serviceUrl URL des Endpoints
*/
ManagementServiceClientBuilder(final URL serviceUrl) {
super(serviceUrl);
}
/**
* Erstellt eine Instanz vom Typ AnlieferungServiceClient
*
* @return ManagementServiceClient
* @throws ClientInitializationException {@link ClientInitializationException}
*/
@Override
public ManagementServiceClient build() throws ClientInitializationException {
this.validateConfiguration();
return new ManagementServiceClient(this.clientConfiguration);
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.net.URL;
import jakarta.xml.ws.Holder;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import genv3.de.xoev.transport.xta.x211.*;
import genv3.eu.osci.ws.x2008.x05.transport.MsgBoxCloseRequestType;
import genv3.eu.osci.ws.x2008.x05.transport.MsgBoxFetchRequest;
import genv3.eu.osci.ws.x2008.x05.transport.MsgBoxGetNextRequestType;
import genv3.eu.osci.ws.x2008.x05.transport.MsgBoxResponseType;
import genv3.eu.osci.ws.x2008.x05.transport.MsgBoxStatusListRequestType;
import genv3.eu.osci.ws.x2008.x05.transport.MsgStatusListType;
import genv3.eu.osci.ws.x2014.x10.transport.MessageMetaData;
import genv3.eu.osci.ws.x2014.x10.transport.PartyType;
import lombok.extern.slf4j.Slf4j;
/**
* gewrapte Serviceklasse für den MsgBoxServcice eines Brokers
*/
@Slf4j
public class MsgBoxServiceClient extends WsClient<MsgBoxPortType> {
public static MsgBoxServiceClientBuilder builder(final URL serviceUrl) {
return new MsgBoxServiceClientBuilder(serviceUrl);
}
public MsgBoxServiceClient(final WsClientConfig conf) throws ClientInitializationException {
this.clientConfiguration = conf;
MsgBoxServiceClient.log.info(VersionInfo.getInfo());
MsgBoxServiceClient.log.info(this.clientConfiguration.toString());
this.initializeService();
}
@Override
void initializePort(final URL url) {
final XTAService service = new XTAService(url);
port = service.getMsgBoxPort();
}
public GenericContentContainer getMessage(final MsgBoxFetchRequest fetchRequest, final PartyType authorIdentifier,
final Holder<MessageMetaData> messageMetaData, final Holder<MsgBoxResponseType> fetchResponseHeader)
throws InvalidMessageIDException, PermissionDeniedException, XTAWSTechnicalProblemException {
return port.getMessage(fetchRequest, authorIdentifier, messageMetaData, fetchResponseHeader);
}
public MsgStatusListType getStatusList(final MsgBoxStatusListRequestType fetchRequest, final PartyType authorIdentifier,
final Holder<MsgBoxResponseType> fetchResponseHeader) throws PermissionDeniedException, XTAWSTechnicalProblemException {
return port.getStatusList(fetchRequest, authorIdentifier, fetchResponseHeader);
}
public GenericContentContainer getNextMessage(final MsgBoxGetNextRequestType fetchRequest, final PartyType authorIdentifier,
final Holder<MessageMetaData> messageMetaData, final Holder<MsgBoxResponseType> fetchResponseHeader)
throws InvalidMessageIDException, PermissionDeniedException, XTAWSTechnicalProblemException {
return port.getNextMessage(fetchRequest, authorIdentifier, messageMetaData, fetchResponseHeader);
}
public MsgStatusListType getNextStatusList(final MsgBoxGetNextRequestType fetchRequest, final PartyType authorIdentifier,
final Holder<MsgBoxResponseType> fetchResponseHeader) throws PermissionDeniedException, XTAWSTechnicalProblemException {
return port.getNextStatusList(fetchRequest, authorIdentifier, fetchResponseHeader);
}
public void close(final MsgBoxCloseRequestType fetchRequest, final PartyType authorIdentifier)
throws InvalidMessageIDException, PermissionDeniedException, XTAWSTechnicalProblemException {
port.close(fetchRequest, authorIdentifier);
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.net.URL;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Konstruiert eine Instanz des {@link WsClient}.
*/
@Getter(AccessLevel.PACKAGE)
@Slf4j
public class MsgBoxServiceClientBuilder extends ServiceBuilder<MsgBoxServiceClient> {
/**
* Initialisiert einen {@link ServiceBuilder} mit ServiceUrl-Host und ServiceUrl-Port.
*
* @param serviceUrl URL des Endpoints
*/
MsgBoxServiceClientBuilder(final URL serviceUrl) {
super(serviceUrl);
}
/**
* Erstellt eine Instanz vom Typ AnlieferungServiceClient
*
* @return ManagementServiceClient
* @throws ClientInitializationException {@link ClientInitializationException}
*/
@Override
public MsgBoxServiceClient build() throws ClientInitializationException {
this.validateConfiguration();
return new MsgBoxServiceClient(this.clientConfiguration);
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.net.URL;
import jakarta.xml.ws.Holder;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import genv3.de.xoev.transport.xta.x211.GenericContentContainer;
import genv3.de.xoev.transport.xta.x211.MessageSchemaViolationException;
import genv3.de.xoev.transport.xta.x211.MessageVirusDetectionException;
import genv3.de.xoev.transport.xta.x211.ParameterIsNotValidException;
import genv3.de.xoev.transport.xta.x211.PermissionDeniedException;
import genv3.de.xoev.transport.xta.x211.SendPortType;
import genv3.de.xoev.transport.xta.x211.SyncAsyncException;
import genv3.de.xoev.transport.xta.x211.XTAService;
import genv3.de.xoev.transport.xta.x211.XTAWSTechnicalProblemException;
import genv3.eu.osci.ws.x2008.x05.transport.X509TokenContainerType;
import genv3.eu.osci.ws.x2014.x10.transport.MessageMetaData;
import lombok.extern.slf4j.Slf4j;
/**
* gewrapte Serviceklasse für den SendServcice eines Brokers
*/
@Slf4j
public class SendServiceClient extends WsClient<SendPortType> {
public static SendServiceClientBuilder builder(final URL serviceUrl) {
return new SendServiceClientBuilder(serviceUrl);
}
public SendServiceClient(final WsClientConfig conf) throws ClientInitializationException {
this.clientConfiguration = conf;
SendServiceClient.log.info(VersionInfo.getInfo());
SendServiceClient.log.info(this.clientConfiguration.toString());
this.initializeService();
}
@Override
void initializePort(final URL url) {
final XTAService service = new XTAService(url);
port = service.getSendXtaPort();
}
public void sendMessage(final GenericContentContainer genericContainer, final MessageMetaData messageMetaData,
final X509TokenContainerType x509TokenContainer)
throws PermissionDeniedException, XTAWSTechnicalProblemException, MessageSchemaViolationException, MessageVirusDetectionException,
ParameterIsNotValidException, SyncAsyncException {
port.sendMessage(genericContainer, messageMetaData, x509TokenContainer);
}
public void sendMessageSync(final Holder<GenericContentContainer> genericContainer,
final Holder<MessageMetaData> messageMetaData, final Holder<X509TokenContainerType> x509TokenContainer)
throws PermissionDeniedException, XTAWSTechnicalProblemException, MessageSchemaViolationException, MessageVirusDetectionException, ParameterIsNotValidException, SyncAsyncException {
port.sendMessageSync(genericContainer, messageMetaData, x509TokenContainer);
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.net.URL;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Konstruiert eine Instanz des {@link WsClient}.
*/
@Getter(AccessLevel.PACKAGE)
@Slf4j
public class SendServiceClientBuilder extends ServiceBuilder<SendServiceClient> {
/**
* Initialisiert einen {@link ServiceBuilder} mit ServiceUrl-Host und ServiceUrl-Port.
*
* @param serviceUrl URL des Endpoints
*/
SendServiceClientBuilder(final URL serviceUrl) {
super(serviceUrl);
}
/**
* Erstellt eine Instanz vom Typ AnlieferungServiceClient
*
* @return ManagementServiceClient
* @throws ClientInitializationException {@link ClientInitializationException}
*/
@Override
public SendServiceClient build() throws ClientInitializationException {
this.validateConfiguration();
return new SendServiceClient(this.clientConfiguration);
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.net.URL;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import de.ozgcloud.xta.client.config.HttpClientPolicy;
import de.ozgcloud.xta.client.config.HttpProxy;
import de.ozgcloud.xta.client.config.Keystore;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Konstruiert eine Instanz des {@link WsClient}.
*/
@Getter(AccessLevel.PACKAGE)
@Slf4j
public abstract class ServiceBuilder<T extends WsClient> {
@Getter(AccessLevel.NONE)
final WsClientConfig clientConfiguration;
/**
* Initialisiert einen {@link ServiceBuilder} mit ServiceUrl-Host und ServiceUrl-Port.
*
* @param serviceUrl URL des Endpoints
*/
ServiceBuilder(final URL serviceUrl) {
this.clientConfiguration = new WsClientConfig();
this.clientConfiguration.setServiceUrl(serviceUrl);
}
/**
* Sezt Trust-Keystore des {@link WsClient}s.
*
* @param keystore Trust-Keystore
* @return {@link ServiceBuilder}
*/
public ServiceBuilder<T> setTrustCertKeystore(final Keystore keystore) {
this.clientConfiguration.setTrustCertKeystore(keystore);
return this;
}
/**
* Setzt den Client-Keystore des {@link WsClient}s.
*
* @param keystore Client-Keystore
* @return {@link ServiceBuilder}
*/
public ServiceBuilder<T> setClientCertKeystore(final Keystore keystore) {
this.clientConfiguration.setClientCertKeystore(keystore);
return this;
}
/**
* Setzt den Proxy Host.
*
* @param proxy Proxy Host
* @return {@link ServiceBuilder}
*/
public ServiceBuilder<T> setHttpProxy(final HttpProxy proxy) {
this.clientConfiguration.setHttpProxy(proxy);
return this;
}
/**
* Setzt XSD Validation
*
* @return {@link ServiceBuilder}
*/
public ServiceBuilder<T> setValidation(final boolean validation) {
this.clientConfiguration.setValidation(validation);
return this;
}
public ServiceBuilder<T> enableValidation() {
setValidation(true);
return this;
}
public ServiceBuilder<T> enableSoapLogging() {
setSoapRequestLogging(true);
setSoapResponseLogging(true);
return this;
}
/**
* Setzt SoapRequest Logging
*
* @return {@link ServiceBuilder}
*/
public ServiceBuilder<T> setSoapRequestLogging(final boolean logging) {
this.clientConfiguration.setLogSoapRequest(logging);
return this;
}
/**
* Setzt SoapResponse Logging
*
* @return {@link ServiceBuilder}
*/
public ServiceBuilder<T> setSoapResponseLogging(final boolean logging) {
this.clientConfiguration.setLogSoapResponse(logging);
return this;
}
/**
* Setzt eine HttpClient-Policy
*
* @param policy HttpClientPolicy
* @return {@link ServiceBuilder}
*/
public ServiceBuilder<T> setHttpClientPolicy(final HttpClientPolicy policy) {
this.clientConfiguration.setHttpClientPolicy(policy);
return this;
}
void validateConfiguration() {
final List<String> errorMsgs = Lists.newArrayList();
ServiceBuilder.checkNotNull("Service-URL", this.clientConfiguration.getServiceUrl(), errorMsgs);
// Entweder beide Angaben leer oder beide gesetzt
if (this.clientConfiguration.getHttpProxy() != null) {
if (this.clientConfiguration.getHttpProxy().getHost() == null ^ this.clientConfiguration.getHttpProxy().getPort() == 0) {
errorMsgs.add("Angaben zum Proxy (Host, Port) müssen vollständig gesetzt sein");
}
}
this.checkKeystoreFile("Client-Keystore", this.clientConfiguration.getClientCertKeystore(), errorMsgs);
this.checkKeystoreFile("Trust-Keystore", this.clientConfiguration.getTrustCertKeystore(), errorMsgs);
if (errorMsgs != null && !errorMsgs.isEmpty()) {
throw new IllegalArgumentException(Joiner.on("\n").join(errorMsgs));
}
}
private static void checkNotNull(final String identifier, final Object value, final List<String> errorMsgs) {
if (value == null) {
errorMsgs.add(identifier + ": Wert muss gesetzt sein");
}
}
private void checkKeystoreFile(final String keyStoreIdentifier, final Keystore keyStore,
final List<String> errorMsgs) {
if (StringUtils.isEmpty(keyStore.getPath())) {
errorMsgs.add(keyStoreIdentifier + ": Pfad muss gesetzt sein");
}
ServiceBuilder.checkNotNull(keyStoreIdentifier + " Passwort", keyStore.getPassword(), errorMsgs);
}
public abstract T build() throws ClientInitializationException;
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Klasse mit VersionInfo
*/
@Slf4j
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public final class VersionInfo {
private static String build;
private static String buildTimestamp;
private static String version;
public static String getInfo() {
return String.format("VersionInfo: version: %s, build: %s, timestamp: %s", VersionInfo.version, VersionInfo.build,
VersionInfo.buildTimestamp);
}
static {
final Properties p = new Properties();
try (final InputStream in = VersionInfo.class.getClassLoader().getResourceAsStream("version.properties")) {
p.load(in);
VersionInfo.build = p.getProperty("bamboo_buildNumber");
VersionInfo.buildTimestamp = p.getProperty("build_creation_timestamp");
VersionInfo.version = p.getProperty("project_version");
} catch (final IOException e) {
log.error(e.getMessage(), e);
throw new IllegalStateException("Can not initialize version information");
}
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import jakarta.xml.ws.BindingProvider;
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.ext.logging.LoggingInInterceptor;
import org.apache.cxf.ext.logging.LoggingOutInterceptor;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import de.ozgcloud.xta.client.config.HttpClientPolicy;
import de.ozgcloud.xta.client.config.HttpProxy;
import de.ozgcloud.xta.client.exception.ClientInitializationException;
import de.ozgcloud.xta.client.util.KeyStoreUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Basisklasse für gewrapte Serviceklassen
*/
@Slf4j
abstract class WsClient<T> {
WsClientConfig clientConfiguration;
T port;
abstract void initializePort(final URL url);
void initializeService() throws ClientInitializationException {
final String logMessage =
"JarInfo: " + this.getClass().getName() + ",\nConfiguration: " + this.clientConfiguration + "," + "\ninitializeService";
try {
final String serviceUrl = this.clientConfiguration.getServiceUrl().toString();
WsClient.log.debug("Initialize Service {}", serviceUrl);
final URL url = this.getClass().getClassLoader().getResource("wsdl/XTA.wsdl");
WsClient.log.debug("url: {}", url);
this.initializeServiceEndpoint(url);
this.initializeTransportSecurity();
this.initializeHttpClientPolicy();
this.initializeProxy();
WsClient.log.info("{} sucessfully.", logMessage);
} catch (final Exception ex) {
WsClient.log.error("{} failed. Reason: {}", logMessage, ex.getMessage());
throw new ClientInitializationException(ex.getMessage(), ex);
}
}
private void initializeServiceEndpoint(final URL url) {
initializePort(url);
final BindingProvider bp = (BindingProvider) this.port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, this.clientConfiguration.getServiceUrl().toString());
WsClient.log.debug("Set EnpointUrl to: {}", this.clientConfiguration.getServiceUrl().toString());
// Empty xmlns="" entfernen -> XSD-Modellierung Annonymous Inner Type
// ClientProxy.getClient(port).getOutInterceptors().add(new EmptyNamespaceMessageOutInterceptor());
initializeValidation();
if (this.clientConfiguration.isLogSoapRequest()) {
LoggingOutInterceptor loi = new LoggingOutInterceptor();
loi.setPrettyLogging(true);
ClientProxy.getClient(port).getOutInterceptors().add(loi);
WsClient.log.debug("Set SoapReqeust-Logging: {}", clientConfiguration.isLogSoapRequest());
}
if (this.clientConfiguration.isLogSoapResponse()) {
LoggingInInterceptor lii = new LoggingInInterceptor();
lii.setPrettyLogging(true);
ClientProxy.getClient(port).getInInterceptors().add(lii);
WsClient.log.debug("Set SoapResponse-Logging: {}", clientConfiguration.isLogSoapResponse());
}
}
private void initializeHttpClientPolicy() {
final HttpClientPolicy policy = this.clientConfiguration.getHttpClientPolicy();
if (policy != null) {
final Client client = ClientProxy.getClient(this.port);
final HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
final HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
if (policy.getConnectionTimeout() != null) {
httpClientPolicy.setConnectionTimeout(policy.getConnectionTimeout());
}
if (policy.getAllowChunking() != null) {
httpClientPolicy.setAllowChunking(policy.getAllowChunking());
}
if (policy.getReceiveTimeOut() != null) {
httpClientPolicy.setReceiveTimeout(policy.getReceiveTimeOut());
}
httpConduit.setClient(httpClientPolicy);
WsClient.log.debug("Intitialize HttpClientPolicy");
}
}
private void initializeTransportSecurity() throws ClientInitializationException {
if (this.clientConfiguration.getClientCertKeystore() != null) {
final Client client = ClientProxy.getClient(this.port);
final HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
final TLSClientParameters parameters = new TLSClientParameters();
parameters.setSSLSocketFactory(this.createSSLContext().getSocketFactory());
httpConduit.setTlsClientParameters(parameters);
WsClient.log.debug("Intitialize TransportSecurity");
}
}
private void initializeProxy() {
final HttpProxy proxy = this.clientConfiguration.getHttpProxy();
if (proxy != null) {
final Client client = ClientProxy.getClient(this.port);
final HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
if (!StringUtils.isEmpty(proxy.getHost())) {
httpConduit.getClient().setProxyServer(proxy.getHost());
}
if (proxy.getPort() != null) {
httpConduit.getClient().setProxyServerPort(proxy.getPort());
}
if (!StringUtils.isEmpty(proxy.getUsername())) {
httpConduit.getProxyAuthorization().setUserName(proxy.getUsername());
}
if (!StringUtils.isEmpty(proxy.getPassword())) {
httpConduit.getProxyAuthorization().setPassword(proxy.getPassword());
}
WsClient.log.debug("Intitialize Proxy");
}
}
private SSLContext createSSLContext() throws ClientInitializationException {
try {
// Server
final KeyStore trustStore = KeyStoreUtil
.load(this.clientConfiguration.getTrustCertKeystore().getPath(),
this.clientConfiguration.getTrustCertKeystore().getPassword());
// client
final KeyStore keyStore = KeyStoreUtil
.load(this.clientConfiguration.getClientCertKeystore().getPath(),
this.clientConfiguration.getClientCertKeystore().getPassword());
//Client-Lib Truststore
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
//Default JDK Truststore
final TrustManagerFactory defaultTmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
defaultTmf.init((KeyStore) null);
//Client-Lib-Keystore
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, this.clientConfiguration.getClientCertKeystore().getPassword().toCharArray());
final SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
CustomTruststoreManager customTruststoreManager = new CustomTruststoreManager(getX509TrustMananger(defaultTmf),
getX509TrustMananger(tmf));
sslContext.init(kmf.getKeyManagers(), new TrustManager[]{customTruststoreManager}, new SecureRandom());
return sslContext;
} catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new ClientInitializationException("Exception in createSSLContext: " + e.getMessage(), e);
}
}
private X509TrustManager getX509TrustMananger(TrustManagerFactory tmf) {
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
return (X509TrustManager) tm;
}
}
return null;
}
public void enableValidation() {
clientConfiguration.setValidation(true);
initializeValidation();
}
public void disableValidation() {
clientConfiguration.setValidation(false);
initializeValidation();
}
private void initializeValidation() {
final BindingProvider bp = (BindingProvider) this.port;
if (this.clientConfiguration.isValidation()) {
bp.getRequestContext().put("schema-validation-enabled", true);
} else {
bp.getRequestContext().put("schema-validation-enabled", false);
}
WsClient.log.debug("Set Enpoint-Validation: {}", clientConfiguration.isValidation());
}
@RequiredArgsConstructor
private class CustomTruststoreManager implements X509TrustManager {
final X509TrustManager defaultTm;
final X509TrustManager myTm;
@Override
public X509Certificate[] getAcceptedIssuers() {
// If you're planning to use client-cert auth,
// merge results from "defaultTm" and "myTm".
return defaultTm.getAcceptedIssuers();
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
myTm.checkServerTrusted(chain, authType);
} catch (CertificateException e) {
defaultTm.checkServerTrusted(chain, authType);
}
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// If you're planning to use client-cert auth,
// do the same as checking the server.
defaultTm.checkClientTrusted(chain, authType);
}
}
}
/**
* XTA-Client Java Library
* Copyright (C) 2021 Koordinierungsstelle für IT-Standards (KoSIT)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.ozgcloud.xta.client.core;
import java.net.URL;
import de.ozgcloud.xta.client.config.HttpClientPolicy;
import de.ozgcloud.xta.client.config.HttpProxy;
import de.ozgcloud.xta.client.config.Keystore;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* Konfigurationsparameter für den {@link WsClient}.
*/
@Setter(AccessLevel.PACKAGE)
@Getter(AccessLevel.PACKAGE)
@ToString
class WsClientConfig {
private URL serviceUrl;
private Keystore clientCertKeystore;
private Keystore trustCertKeystore;
private HttpProxy httpProxy;
private HttpClientPolicy httpClientPolicy;
private boolean validation = false;
private boolean logSoapRequest = false;
private boolean logSoapResponse = false;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment