From 1b7401488933f031a68dfe929b25db86279b52d2 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 15 Feb 2016 18:12:06 +0100 Subject: First untested part: Refactor authentication modules and process management to Spring --- .../src/main/java/at/gv/egovernment/moa/id/commons/MOAIDConstants.java | 1 + 1 file changed, 1 insertion(+) (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/MOAIDConstants.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/MOAIDConstants.java index a28fe6a7b..6726aacb5 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/MOAIDConstants.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/MOAIDConstants.java @@ -63,6 +63,7 @@ public class MOAIDConstants { public static final List ALLOWED_STORKATTRIBUTEPROVIDERS; public static final List JDBC_DRIVER_NEEDS_WORKAROUND; + public static final String UNIQUESESSIONIDENTIFIER = "uniqueSessionIdentifier"; static { Hashtable tmp = new Hashtable(); -- cgit v1.2.3 From 48fd33725c53136fe505067b93390b39e19c41b7 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 2 Mar 2016 11:20:36 +0100 Subject: temporarily commit to save state --- .../db/dao/session/AuthenticatedSessionStore.java | 115 ++++++++++++++++++--- .../id/commons/db/dao/session/OASessionStore.java | 18 ++++ 2 files changed, 116 insertions(+), 17 deletions(-) (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java index af5950c98..a8cc1928e 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java @@ -38,7 +38,6 @@ import javax.persistence.Lob; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; -import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.persistence.Temporal; @@ -130,46 +129,115 @@ public class AuthenticatedSessionStore implements Serializable{ this.id = id; } + /** + * Get the internal ID of this MOASession + * + * @return moaSessionID, but never null + */ public String getSessionid() { return sessionid; + } + /** + * Set the internal ID of this MOASession. + * + * @param sessionid The internal ID of this MOASession, but never null + **/ public void setSessionid(String sessionid) { this.sessionid = sessionid; } + /** + * Get the Single Sign-On SessionID of this MOASession + * + * @return SSO SessionID + */ public String getSSOsessionid() { return SSOsessionid; } + /** + * Set the Single Sign-On SessionID for this MOASession + * + * @param sSOsessionid SSO SessionID + */ public void setSSOsessionid(String sSOsessionid) { SSOsessionid = sSOsessionid; } + /** + * Get the serialized (and encrypted) AuthenticatedData DAO, which contains the user + * identification and authentication information. + * + * @return serialized (and encryped) authenticationData, but never null + */ public byte[] getSession() { return authSession; } + /** + * Set the AuthenticationData DAO, as serialized (and encrypted) blob.

+ * + * This method should only be used, since MOASesion is not authenticated + * this.isAuthenticated() == false. If the MOASession is already authenticated, + * the corresponding user authentication data should not be changed any more. + * + * @param session the serialized (and encryped) authenticationData + */ public void setSession(byte[] session) { this.authSession = session; } + /** + * Indicates this MOASession is already authenticated.

+ * + * A authenticated MOASession contains all information, which are + * needed build protocol specific authentication information. + * Therefore, a user has already performed a full identification and + * authentication process. + * + * @return true, if this MOASession is authenticated, otherwise false + */ public boolean isAuthenticated() { return isAuthenticated; } + /** + * Mark a MOASession as authenticated.

+ * + * A MOASession had to be marked as authenticated, if the user + * identification and authentication process is completed. + * + * @param isAuthenticated + */ public void setAuthenticated(boolean isAuthenticated) { this.isAuthenticated = isAuthenticated; } + /** + * Indicates this MOASession as a Single Sign-On session + * + * @return true if it is a SSO session, otherwise false + */ public boolean isSSOSession() { return isSSOSession; } + /** + * Mark this MOASession as a Single Sign-On session + * + * @param isSSOSession true, if this MOASession is a SSO session, otherwise false + */ public void setSSOSession(boolean isSSOSession) { this.isSSOSession = isSSOSession; } + /** + * Get a timestamp when this MOASession was created + * + * @return timestamp + */ public Date getCreated() { return created; } @@ -178,6 +246,11 @@ public class AuthenticatedSessionStore implements Serializable{ this.created = created; } + /** + * Get a timestamp, when this MOASession was updated last time + * + * @return timestamp + */ public Date getUpdated() { return updated; } @@ -186,6 +259,12 @@ public class AuthenticatedSessionStore implements Serializable{ this.updated = updated; } + /** + * Get a List of Service Providers, which has received a authentication information by using + * Single Sign-On + * + * @return + */ public List getActiveOAsessions() { return activeOAsessions; } @@ -198,6 +277,12 @@ public class AuthenticatedSessionStore implements Serializable{ this.activeOAsessions = activeOAsessions; } + /** + * Get a List of old Single Sign-On SessionIDs, which are already used for this MOASession. + * Every SSO SessionID can only be used once. + * + * @return + */ public List getOldssosessionids() { return oldssosessionids; } @@ -207,6 +292,8 @@ public class AuthenticatedSessionStore implements Serializable{ } /** + * Get a List of federated IDPs which are already used in this Session + * * @return the inderfederation */ public List getInderfederation() { @@ -221,20 +308,8 @@ public class AuthenticatedSessionStore implements Serializable{ } /** - * @return the pendingRequestID - */ - public String getPendingRequestID() { - return pendingRequestID; - } - - /** - * @param pendingRequestID the pendingRequestID to set - */ - public void setPendingRequestID(String pendingRequestID) { - this.pendingRequestID = pendingRequestID; - } - - /** + * Get the initial vector for AuthenticationData encryption + * * @return the iv */ public byte[] getIv() { @@ -242,6 +317,8 @@ public class AuthenticatedSessionStore implements Serializable{ } /** + * Set the inital vector for AuthenticationData encryption + * * @param iv the iv to set */ public void setIv(byte[] iv) { @@ -249,14 +326,18 @@ public class AuthenticatedSessionStore implements Serializable{ } /** - * @return the isInterfederatedSSOSession + * Indicates this MOASession as an federated session + * + * @return true if it is a federated session, otherwise false */ public boolean isInterfederatedSSOSession() { return isInterfederatedSSOSession; } /** - * @param isInterfederatedSSOSession the isInterfederatedSSOSession to set + * Mark this MOASession as an federated session + * + * @param isInterfederatedSSOSession true, if this MOASession is a federated session */ public void setInterfederatedSSOSession(boolean isInterfederatedSSOSession) { this.isInterfederatedSSOSession = isInterfederatedSSOSession; diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java index 8b720e901..bead2f593 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java @@ -71,6 +71,9 @@ public class OASessionStore implements Serializable{ @Column(name = "attributequeryused", unique=false, nullable=false) private boolean attributeQueryUsed = false; + @Column(name = "attQueryContainerID", unique=false, nullable=true) + private String attQueryContainerID = null; + @Column(name = "created", updatable=false, nullable=false) // @Temporal(TemporalType.TIMESTAMP) private Date created; @@ -200,6 +203,21 @@ public class OASessionStore implements Serializable{ this.authURL = authURL; } + /** + * @return the attQueryContainerID + */ + public String getAttQueryContainerID() { + return attQueryContainerID; + } + + /** + * @param attQueryContainerID the attQueryContainerID to set + */ + public void setAttQueryContainerID(String attQueryContainerID) { + this.attQueryContainerID = attQueryContainerID; + } + + -- cgit v1.2.3 From b9937af42fdab6b85aa1121148bda474c70f5e75 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 8 Mar 2016 11:10:19 +0100 Subject: finish first beta-version of ELGA mandate-service client-module --- .../id/commons/db/dao/session/OASessionStore.java | 24 +--------------------- 1 file changed, 1 insertion(+), 23 deletions(-) (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java index bead2f593..44ae43115 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java @@ -70,10 +70,7 @@ public class OASessionStore implements Serializable{ @Column(name = "attributequeryused", unique=false, nullable=false) private boolean attributeQueryUsed = false; - - @Column(name = "attQueryContainerID", unique=false, nullable=true) - private String attQueryContainerID = null; - + @Column(name = "created", updatable=false, nullable=false) // @Temporal(TemporalType.TIMESTAMP) private Date created; @@ -203,24 +200,5 @@ public class OASessionStore implements Serializable{ this.authURL = authURL; } - /** - * @return the attQueryContainerID - */ - public String getAttQueryContainerID() { - return attQueryContainerID; - } - - /** - * @param attQueryContainerID the attQueryContainerID to set - */ - public void setAttQueryContainerID(String attQueryContainerID) { - this.attQueryContainerID = attQueryContainerID; - } - - - - - - } -- cgit v1.2.3 From f9020f47b60bc1cff6c671461924ba606ce87853 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 9 Mar 2016 09:15:03 +0100 Subject: fix some problems in ELGA-mandate module --- .../moa/id/commons/utils/KeyValueUtils.java | 23 ++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/utils/KeyValueUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/utils/KeyValueUtils.java index cbdd13d0e..add929e1d 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/utils/KeyValueUtils.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/utils/KeyValueUtils.java @@ -31,8 +31,6 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import org.apache.commons.lang3.StringUtils; - import at.gv.egovernment.moa.util.MiscUtil; /** @@ -283,6 +281,27 @@ public class KeyValueUtils { return false; } + /** + * Convert a CSV list to a List of CSV values + *

+ * This method removes all whitespace at the begin or the + * end of CSV values and remove newLine signs at the end of value. + * The ',' is used as list delimiter + * + * @param csv CSV encoded input data + * @return List of CSV normalized values, but never null + */ + public static List getListOfCSVValues(String csv) { + List list = new ArrayList(); + if (MiscUtil.isNotEmpty(csv)) { + String[] values = csv.split(CSV_DELIMITER); + for (String el: values) + list.add(el.trim()); + + } + + return list; + } /** * This method remove all newline delimiter (\n or \r\n) from input data -- cgit v1.2.3 From 74d8c83f76074d2d0df784cb4a305c586a702d25 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 9 Mar 2016 13:41:09 +0100 Subject: move moa-common to moa-id-common, because MOA-SPSS becomes a seperate project --- .../java/at/gv/egovernment/moa/logging/LogMsg.java | 67 ++ .../java/at/gv/egovernment/moa/logging/Logger.java | 252 +++++ .../gv/egovernment/moa/logging/LoggingContext.java | 70 ++ .../moa/logging/LoggingContextManager.java | 80 ++ .../at/gv/egovernment/moa/util/Base64Utils.java | 153 +++ .../java/at/gv/egovernment/moa/util/BoolUtils.java | 48 + .../gv/egovernment/moa/util/CollectionUtils.java | 60 + .../java/at/gv/egovernment/moa/util/Constants.java | 514 +++++++++ .../java/at/gv/egovernment/moa/util/DOMUtils.java | 1172 ++++++++++++++++++++ .../at/gv/egovernment/moa/util/DateTimeUtils.java | 515 +++++++++ .../java/at/gv/egovernment/moa/util/Empty.java | 31 + .../egovernment/moa/util/EntityResolverChain.java | 76 ++ .../java/at/gv/egovernment/moa/util/FileUtils.java | 179 +++ .../at/gv/egovernment/moa/util/KeyStoreUtils.java | 223 ++++ .../gv/egovernment/moa/util/MOADefaultHandler.java | 106 ++ .../gv/egovernment/moa/util/MOAEntityResolver.java | 129 +++ .../gv/egovernment/moa/util/MOAErrorHandler.java | 115 ++ .../java/at/gv/egovernment/moa/util/MOATimer.java | 134 +++ .../gv/egovernment/moa/util/MessageProvider.java | 87 ++ .../java/at/gv/egovernment/moa/util/Messages.java | 141 +++ .../java/at/gv/egovernment/moa/util/MiscUtil.java | 315 ++++++ .../egovernment/moa/util/NodeIteratorAdapter.java | 111 ++ .../gv/egovernment/moa/util/NodeListAdapter.java | 68 ++ .../at/gv/egovernment/moa/util/OutputXML2File.java | 102 ++ .../egovernment/moa/util/ResourceBundleChain.java | 90 ++ .../java/at/gv/egovernment/moa/util/SSLUtils.java | 244 ++++ .../egovernment/moa/util/StreamEntityResolver.java | 88 ++ .../at/gv/egovernment/moa/util/StreamUtils.java | 197 ++++ .../at/gv/egovernment/moa/util/StringUtils.java | 178 +++ .../at/gv/egovernment/moa/util/URLDecoder.java | 84 ++ .../at/gv/egovernment/moa/util/URLEncoder.java | 89 ++ .../at/gv/egovernment/moa/util/XPathException.java | 86 ++ .../at/gv/egovernment/moa/util/XPathUtils.java | 557 ++++++++++ .../egovernment/moa/util/ex/EgovUtilException.java | 41 + 34 files changed, 6402 insertions(+) create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LogMsg.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/Logger.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LoggingContext.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LoggingContextManager.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Base64Utils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/BoolUtils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/CollectionUtils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Constants.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DateTimeUtils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Empty.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/EntityResolverChain.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/FileUtils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/KeyStoreUtils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOADefaultHandler.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOAEntityResolver.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOAErrorHandler.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOATimer.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MessageProvider.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Messages.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MiscUtil.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeIteratorAdapter.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeListAdapter.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/OutputXML2File.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/ResourceBundleChain.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/SSLUtils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StreamEntityResolver.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StreamUtils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StringUtils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/URLDecoder.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/URLEncoder.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathException.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathUtils.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/ex/EgovUtilException.java (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LogMsg.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LogMsg.java new file mode 100644 index 000000000..51667f010 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LogMsg.java @@ -0,0 +1,67 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.logging; + +/** + * A unified message type to log messages from inside the MOA subsystem. + * + * @author Patrick Peck + * @version $Id$ + */ +public class LogMsg { + /** The message to log. */ + private Object message; + + /** + * Create a LogMsg object. + * + * @param message The actual message to log. May be null. + */ + public LogMsg(Object message) { + this.message = message; + } + + /** + * Convert this log message to a String. + * + * @return The String representation of this log message. + */ + public String toString() { + StringBuffer msg = new StringBuffer(); + LoggingContext ctx = + LoggingContextManager.getInstance().getLoggingContext(); + String tid = ctx != null ? ctx.getTransactionID() : null; + String nodeId = ctx != null ? ctx.getNodeID() : null; + + msg.append("TID="); + msg.append(tid != null ? tid : ""); + msg.append(" NID="); + msg.append(nodeId != null ? nodeId : ""); + msg.append(" MSG="); + msg.append(message != null ? message.toString() : ""); + + return msg.toString(); + } +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/Logger.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/Logger.java new file mode 100644 index 000000000..3730b36ce --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/Logger.java @@ -0,0 +1,252 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.logging; + +import java.util.HashMap; +import java.util.Map; + +/** + * A utility class acting as a facade to the logging subsystem. + * + * Configure the logging defaultHierarchy that the Logger uses by + * calling setHierarchy once before calling any of the logging + * output functions. + * + * @author Patrick Peck + * @version $Id$ + */ +public class Logger { + + /** + * Set the default hierarchy to which the Logger should send its + * logging output. + * @param hierarchy The logging defaultHierarchy. + */ + public static void setHierarchy(String hierarchy) { + // there is no need for that anymore + } + + + /** The Constant instances. */ + private static final Map instances = new HashMap(); + + /** + * Gets the logger. + * + * @return the logger + */ + private static synchronized org.slf4j.Logger getLogger() { + StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); + + int i; + for(i = 2; i < stacktrace.length; i++) + if(!stacktrace[i].getClassName().equals(Logger.class.getName())) + break; + + String className = stacktrace[i].getClassName(); + + org.slf4j.Logger logger = instances.get(className); + if (logger != null) { + return logger; + } + + logger = org.slf4j.LoggerFactory.getLogger(className); + instances.put(className, logger); + + return logger; + } + + /** + * Prepare the message for printing it as string. + *

Mainly introduce because the message might be null. + * + * @param message the message + * @return the string + */ + private static String prepareMessage(Object message) { + if(null == message) + return "no message given"; + return message.toString(); + } + + /** + * Test, if the trace log level is enabled. + * + * @return boolean true, if tracing output is enabled + * false otherwise. + */ + public static boolean isTraceEnabled() { + org.slf4j.Logger logger = getLogger(); + return logger.isTraceEnabled(); + } + + /** + * Test, if the trace log level is enabled for a given hierarchy. + * + * @param hierarchy requested log hierarchy + * @return boolean true, if tracing output is enabled + * false otherwise. + */ + public static boolean isTraceEnabled(String hierarchy) { + org.slf4j.Logger logger = getLogger(); + return logger.isTraceEnabled(); + } + + /** + * Trace a message. + * + * @param message The message to trace. + */ + public static void trace(Object message) { + org.slf4j.Logger logger = getLogger(); + logger.trace(prepareMessage(message)); + } + + /** + * Test, if the debug log level is enabled. + * + * @return boolean true, if debug output is enabled + * false otherwise. + */ + public static boolean isDebugEnabled() { + org.slf4j.Logger logger = getLogger(); + return logger.isDebugEnabled(); + } + + /** + * Test, if the debug log level is enabled for a given hierarchy. + * + * @param hierarchy requested log hierarchy + * @return boolean true, if debug output is enabled + * false otherwise. + */ + public static boolean isDebugEnabled(String hierarchy) { + org.slf4j.Logger logger = getLogger(); + return logger.isDebugEnabled(); + } + + /** + * Log a debug message. + * + * @param message The message to log. + */ + public static void debug(Object message) { + org.slf4j.Logger logger = getLogger(); + logger.debug(prepareMessage(message)); + } + +/** + * Log an info message. + * + * @param message The message to log. + */ + public static void info(Object message) { + org.slf4j.Logger logger = getLogger(); + logger.info(prepareMessage(message)); + } + + /** + * Info. + * + * @param string the string + * @param args the objects + */ + public static void info(String message, Object[] args) { + org.slf4j.Logger logger = getLogger(); + logger.info(prepareMessage(message), args); + } + + /** + * Log a warning message. + * + * @param message The message to log. + */ + public static void warn(Object message) { + org.slf4j.Logger logger = getLogger(); + logger.warn(prepareMessage(message)); + } + + /** + * Log a warning message. + * + * @param message The message to log. + * @param t An exception that may be the cause of the warning. + */ + public static void warn(Object message, Throwable t) { + org.slf4j.Logger logger = getLogger(); + logger.warn(prepareMessage(message), t); + } + + /** + * Log an error message. + * + * @param message The message to log. + */ + public static void error(Object message) { + org.slf4j.Logger logger = getLogger(); + logger.error(prepareMessage(message)); + } + + /** + * Log an error message. + * + * @param message The message to log. + * @param t An exception that may be the cause of the error. + */ + public static void error(Object message, Throwable t) { + org.slf4j.Logger logger = getLogger(); + logger.error(prepareMessage(message), t); + } + + /** + * Log an error message with additional information. + * + * @param message The message to log. + * @param variables The values to substitute {} of the logmessage with. + */ + public static void error(Object message, Object[] variables) { + org.slf4j.Logger logger = getLogger(); + logger.error(prepareMessage(message), variables); + } + + /** + * Log a fatal error message. + * + * @param message The message to log. + */ + public static void fatal(Object message) { + error(message); + } + + /** + * Log a fatal error message. + * + * @param message The message to log. + * @param t An exception that may be the cause of the error. + */ + public static void fatal(Object message, Throwable t) { + error(message, t); + } +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LoggingContext.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LoggingContext.java new file mode 100644 index 000000000..db4b93a0b --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LoggingContext.java @@ -0,0 +1,70 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.logging; + +/** + * Encapsulates contextual information (i.e. per request information) for + * logging purposes. + * + * @author Patrick Peck + * @version $Id$ + */ +public class LoggingContext { + /** The name of the node ID system property. */ + public static final String NODE_ID_PROPERTY = "moa.node-id"; + + /** The current transaction ID. */ + private String transactionID; + /** The node ID. */ + private String nodeID; + + /** + * Create a new LoggingContext. + * + * @param transactionID The transaction ID. May be null. + */ + public LoggingContext(String transactionID) { + this.transactionID = transactionID; + this.nodeID = System.getProperty(NODE_ID_PROPERTY); + } + + /** + * Return the transaction ID. + * + * @return The transaction ID. + */ + public String getTransactionID() { + return transactionID; + } + + /** + * Return the node ID. + * + * @return The node ID. + */ + public String getNodeID() { + return nodeID; + } +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LoggingContextManager.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LoggingContextManager.java new file mode 100644 index 000000000..f0d7b4c07 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/logging/LoggingContextManager.java @@ -0,0 +1,80 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.logging; + +/** + * Provides each thread with a single instance of LoggingContext. + * + * @author Patrick Peck + * @version $Id$ + */ +public class LoggingContextManager { + /** The single instance of this class. */ + private static LoggingContextManager instance = null; + + /** The LoggingContext for each thread. */ + private ThreadLocal context; + + /** + * Get the single instance of the LoggingContextManager class. + * + * @return LoggingContextManager The single instance. + */ + public static synchronized LoggingContextManager getInstance() { + if (instance == null) { + instance = new LoggingContextManager(); + } + return instance; + } + + /** + * Creates a new LoggingContextManager. + * + * Protected to disallow direct instantiation. + */ + protected LoggingContextManager() { + context = new ThreadLocal(); + } + + /** + * Set the LoggingContext context for the current thread. + * + * @param ctx The LoggingContext for the current thread. + */ + public void setLoggingContext(LoggingContext ctx) { + context.set(ctx); + } + + /** + * Return the LoggingContext for the current thread. + * + * @return LoggingContext The LoggingContext for the current + * thread, or null if none has been set. + */ + public LoggingContext getLoggingContext() { + return (LoggingContext) context.get(); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Base64Utils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Base64Utils.java new file mode 100644 index 000000000..66bf50316 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Base64Utils.java @@ -0,0 +1,153 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; + +import iaik.utils.Base64InputStream; +import iaik.utils.Base64OutputStream; + +/** + * Utitility functions for encoding/decoding Base64 strings. + * + * @author Patrick Peck + * @version $Id$ + */ +public class Base64Utils { + + /** + * Read the bytes encoded in a Base64 encoded String. + * + * @param base64String The String containing the Base64 encoded + * bytes. + * @param ignoreInvalidChars Whether to ignore invalid Base64 characters. + * @return byte[] The raw bytes contained in the base64String. + * @throws IOException Failed to read the Base64 data. + */ + public static byte[] decode(String base64String, boolean ignoreInvalidChars, String encoding) + throws IOException { + + Base64InputStream in = + new Base64InputStream( + new ByteArrayInputStream(base64String.getBytes(encoding)), + ignoreInvalidChars); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] bytes = new byte[256]; + int bytesRead; + + while ((bytesRead = in.read(bytes)) > 0) { + out.write(bytes, 0, bytesRead); + } + in.close(); + + return out.toByteArray(); + } + + public static byte[] decode(String base64String, boolean ignoreInvalidChars) throws IOException { + return decode(base64String, ignoreInvalidChars, "UTF-8"); + } + + /** + * Read the bytes encoded in a Base64 encoded String and provide + * them via an InputStream. + * + * @param base64String The String containing the Base64 encoded + * bytes. + * @param ignoreInvalidChars Whether to ignore invalid Base64 characters. + * @return The InputStream from which the binary content of the + * base64String can be read. + */ + public static InputStream decodeToStream( + String base64String, + boolean ignoreInvalidChars, + String encoding) { + + try { + ByteArrayInputStream bin = + new ByteArrayInputStream(base64String.getBytes(encoding)); + Base64InputStream in = new Base64InputStream(bin, ignoreInvalidChars); + + return in; + } catch (UnsupportedEncodingException e) { + // cannot occur, since UTF-8 is required to be supported by every JRE + return null; + } + } + + public static InputStream decodeToStream( + String base64String, + boolean ignoreInvalidChars) { + return decodeToStream(base64String, ignoreInvalidChars, "UTF-8"); + + } + + /** + * Convert a byte array to a Base64 encoded String. + * + * @param bytes The bytes to encode. + * @return String The Base64 encoded representation of the bytes. + * @throws IOException Failed to write the bytes as Base64 data. + */ + public static String encode(byte[] bytes) throws IOException { + return encode(new ByteArrayInputStream(bytes), "UTF-8"); + } + + public static String encode(byte[] bytes, String encoding) throws IOException { + return encode(new ByteArrayInputStream(bytes), encoding); + } + + public static String encode(InputStream inputStream) throws IOException { + return encode(inputStream, "UTF-8"); + } + /** + * Convert the data contained in the given stream to a Base64 encoded + * String. + * + * @param inputStream The stream containing the data to encode. + * @return The Base64 encoded data of inputStream, as a + * String. + * @throws IOException Failed to convert the data in the stream. + */ + public static String encode(InputStream inputStream, String encoding) throws IOException { + ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); + Base64OutputStream base64Stream = new Base64OutputStream(byteStream, "\n".getBytes()); + byte[] bytes = new byte[256]; + int bytesRead; + + while ((bytesRead = inputStream.read(bytes)) > 0) { + base64Stream.write(bytes, 0, bytesRead); + } + base64Stream.flush(); + base64Stream.close(); + inputStream.close(); + + return byteStream.toString(encoding); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/BoolUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/BoolUtils.java new file mode 100644 index 000000000..492aca994 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/BoolUtils.java @@ -0,0 +1,48 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +/** + * Utility class for parsing XML schema boolean values. + * + * @author Patrick Peck + * @version $Id$ + */ +public class BoolUtils { + + /** + * Return the boolean value of an xsd:boolean type of DOM + * element/attribute. + * + * @param boolStr The value of the xsd:boolean element/attribute. + * @return true, if boolStr equals + * "true" or "1;". Otherwise, + * false is returned. + */ + public static boolean valueOf(String boolStr) { + return "true".equals(boolStr) || "1".equals(boolStr); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/CollectionUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/CollectionUtils.java new file mode 100644 index 000000000..8597e1eec --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/CollectionUtils.java @@ -0,0 +1,60 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.util.Iterator; +import java.util.List; + +/** + * Various utility methods for dealing with java.util.Collection + * classes. + * + * @author Patrick Peck + * @version $Id$ + */ +public class CollectionUtils { + + /** + * Convert a List of Number objects to an + * int array. + * + * @param nums The List containing the numbers whose integer + * value to put into the result. + * @return The int values of the Numbers contained + * in nums. + */ + public static int[] toIntArray(List nums) { + int[] result = new int[nums.size()]; + Iterator iter; + int i; + + for (i = 0, iter = nums.iterator(); iter.hasNext(); i++) { + Number num = (Number) iter.next(); + result[i] = num.intValue(); + } + + return result; + } +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Constants.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Constants.java new file mode 100644 index 000000000..5a5f4edac --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Constants.java @@ -0,0 +1,514 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.util.HashMap; + +/** + * Contains various constants used throughout the system. + * + * @author Patrick Peck + * @version $Id$ + */ +public interface Constants { + /** Root location of the schema files. */ + public static final String SCHEMA_ROOT = "/resources/schemas/"; + + /** URI of the Widerrufregister XML namespace. */ + public static final String WRR_NS_URI = + "http://reference.e-government.gv.at/namespace/moavv/20041223"; + + /** Prefix used for the Widerrufregister XML namespace */ + public static final String WRR_PREFIX = "wrr"; + + /** URI of the StandardTextBlock XML namespace. */ + public static final String STB_NS_URI = + "http://reference.e-government.gv.at/namespace/standardtextblock/20041105#"; + + /** Prefix used for the standard text block XML namespace */ + public static final String STB_PREFIX = "stb"; + + /** URI of the MOA XML namespace. */ + public static final String MOA_NS_URI = + "http://reference.e-government.gv.at/namespace/moa/20020822#"; + + /** Name of the mandates infobox */ + public static final String INFOBOXIDENTIFIER_MANDATES = "Mandates"; + + /** Prefix used for the Mandate XML namespace */ + public static final String MD_PREFIX = "md"; + + /** URI of the Mandate XML namespace. */ + public static final String MD_NS_URI = + "http://reference.e-government.gv.at/namespace/mandates/20040701#"; + + /** Prefix used for the Mandate XML namespace */ + public static final String MVV_PREFIX = "mvv"; + + /** URI of the Mandate XML namespace. */ + public static final String MVV_NS_URI = + "http://reference.e-government.gv.at/namespace/moavv/app2mvv/20041125"; + + /** Prefix used for the MandateCheckProfile XML namespace */ + public static final String MDP_PREFIX = "mdp"; + + /** URI of the Mandate XML namespace. */ + public static final String MDP_NS_URI = + "http://reference.e-government.gv.at/namespace/mandateprofile/20041105#"; + + /** Prefix used for the MOA XML namespace */ + public static final String MOA_PREFIX = "moa"; + + /** Local location of the MOA XML schema definition. */ + public static final String MOA_SCHEMA_LOCATION = + SCHEMA_ROOT + "MOA-SPSS-2.0.0.xsd"; + + /** URI of the MOA configuration XML namespace. */ + public static final String MOA_CONFIG_NS_URI = + "http://reference.e-government.gv.at/namespace/moaconfig/20021122#"; + + /** URI of the MOA ID configuration XML namespace. */ + public static final String MOA_ID_CONFIG_NS_URI = + "http://www.buergerkarte.at/namespaces/moaconfig#"; + + /** Prefix used for the MOA configuration XML namespace */ + public static final String MOA_CONFIG_PREFIX = "conf"; + + /** Prefix used for the MOA configuration XML namespace */ + public static final String MOA_ID_CONFIG_PREFIX = "confID"; + + /** Local location of the MOA configuration XML schema definition. */ + public static final String MOA_CONFIG_SCHEMA_LOCATION = + SCHEMA_ROOT + "MOA-SPSS-config-2.0.0.xsd"; + + /** Local location of the MOA ID configuration XML schema definition. */ + public static final String MOA_ID_CONFIG_SCHEMA_LOCATION = + SCHEMA_ROOT + "MOA-ID-Configuration-1.5.2.xsd"; + + /** URI of the Security Layer 1.0 namespace. */ + public static final String SL10_NS_URI = + "http://www.buergerkarte.at/namespaces/securitylayer/20020225#"; + + /** Prefix used for the Security Layer 1.0 XML namespace */ + public static final String SL10_PREFIX = "sl10"; + + /** Local location of the Security Layer 1.0 XML schema definition */ + public static final String SL10_SCHEMA_LOCATION = + SCHEMA_ROOT + "Core.20020225.xsd"; + + /** URI of the Security Layer 1.1 XML namespace */ + public static final String SL11_NS_URI = + "http://www.buergerkarte.at/namespaces/securitylayer/20020831#"; + + /** Prefix used for the Security Layer 1.1 XML namespace */ + public static final String SL11_PREFIX = "sl11"; + + /** Local location of the Security Layer 1.1 XML schema definition */ + public static final String SL11_SCHEMA_LOCATION = + SCHEMA_ROOT + "Core.20020831.xsd"; + + /** URI of the Security Layer 1.2 XML namespace */ + public static final String SL12_NS_URI = + "http://www.buergerkarte.at/namespaces/securitylayer/1.2#"; + + /** Prefix used for the Security Layer 1.2 XML namespace */ + public static final String SL12_PREFIX = "sl"; + + /** Local location of the Security Layer 1.2 XML schema definition */ + public static final String SL12_SCHEMA_LOCATION = + SCHEMA_ROOT + "Core-1.2.xsd"; + + /** URI of the ECDSA XML namespace */ + public static final String ECDSA_NS_URI = + "http://www.w3.org/2001/04/xmldsig-more#"; + + /** Prefix used for ECDSA namespace */ + public static final String ECDSA_PREFIX = "ecdsa"; + + /** Local location of ECDSA XML schema definition */ + public static final String ECDSA_SCHEMA_LOCATION = + SCHEMA_ROOT + "ECDSAKeyValue.xsd"; + + /** URI of the PersonData XML namespace. */ + public static final String PD_NS_URI = + "http://reference.e-government.gv.at/namespace/persondata/20020228#"; + + /** Prefix used for the PersonData XML namespace */ + public static final String PD_PREFIX = "pr"; + +// /** Local location of the PersonData XML schema definition */ +// public static final String PD_SCHEMA_LOCATION = +// SCHEMA_ROOT + "PersonData.xsd"; + + /** Local location of the PersonData XML schema definition */ + public static final String PD_SCHEMA_LOCATION = + SCHEMA_ROOT + "PersonData_20_en_moaWID.xsd"; + + /** URI of the SAML namespace. */ + public static final String SAML_NS_URI = + "urn:oasis:names:tc:SAML:1.0:assertion"; + + /** Prefix used for the SAML XML namespace */ + public static final String SAML_PREFIX = "saml"; + + /** Local location of the SAML XML schema definition. */ + public static final String SAML_SCHEMA_LOCATION = + SCHEMA_ROOT + "cs-sstc-schema-assertion-01.xsd"; + + /** URI of the SAML request-response protocol namespace. */ + public static final String SAMLP_NS_URI = + "urn:oasis:names:tc:SAML:1.0:protocol"; + + /** Prefix used for the SAML request-response protocol namespace */ + public static final String SAMLP_PREFIX = "samlp"; + + /** Local location of the SAML request-response protocol schema definition. */ + public static final String SAMLP_SCHEMA_LOCATION = + SCHEMA_ROOT + "cs-sstc-schema-protocol-01.xsd"; + + /** URI of the XML namespace. */ + public static final String XML_NS_URI = + "http://www.w3.org/XML/1998/namespace"; + + /** Prefix used for the XML namespace */ + public static final String XML_PREFIX = "xml"; + + /** Local location of the XML schema definition. */ + public static final String XML_SCHEMA_LOCATION = SCHEMA_ROOT + "xml.xsd"; + + /** URI of the XMLNS namespace */ + public static final String XMLNS_NS_URI = "http://www.w3.org/2000/xmlns/"; + + /** Prefix used for the XSI namespace */ + public static final String XSI_PREFIX = "xsi"; + + /** Local location of the XSI schema definition. */ + public static final String XSI_SCHEMA_LOCATION = + SCHEMA_ROOT + "XMLSchema-instance.xsd"; + + /** URI of the XSI XMLNS namespace */ + public static final String XSI_NS_URI = + "http://www.w3.org/2001/XMLSchema-instance"; + + /** URI of the XSLT XML namespace */ + public static final String XSLT_NS_URI = + "http://www.w3.org/1999/XSL/Transform"; + + /** Prefix used for the XSLT XML namespace */ + public static final String XSLT_PREFIX = "xsl"; + + /** URI of the XMLDSig XML namespace. */ + public static final String DSIG_NS_URI = "http://www.w3.org/2000/09/xmldsig#"; + + /** Prefix used for the XMLDSig XML namespace */ + public static final String DSIG_PREFIX = "dsig"; + + /** Local location of the XMLDSig XML schema. */ + public static final String DSIG_SCHEMA_LOCATION = + SCHEMA_ROOT + "xmldsig-core-schema.xsd"; + + /** URI of the XMLDSig XPath Filter XML namespace. */ + public static final String DSIG_FILTER2_NS_URI = + "http://www.w3.org/2002/06/xmldsig-filter2"; + + /** Prefix used for the XMLDSig XPath Filter XML namespace */ + public static final String DSIG_FILTER2_PREFIX = "dsig-filter2"; + + /** Local location of the XMLDSig XPath Filter XML schema definition. */ + public static final String DSIG_FILTER2_SCHEMA_LOCATION = + SCHEMA_ROOT + "xmldsig-filter2.xsd"; + + /** URI of the Exclusive Canonicalization XML namespace */ + public static final String DSIG_EC_NS_URI = + "http://www.w3.org/2001/10/xml-exc-c14n#"; + + /** Prefix used for the Exclusive Canonicalization XML namespace */ + public static final String DSIG_EC_PREFIX = "ec"; + + /** Local location of the Exclusive Canonicalizaion XML schema definition */ + public static final String DSIG_EC_SCHEMA_LOCATION = + SCHEMA_ROOT + "exclusive-canonicalization.xsd"; + + /** URI of the XMLLoginParameterResolver Configuration XML namespace */ + public static final String XMLLPR_NS_URI="http://reference.e-government.gv.at/namespace/moa/20020822#/xmllpr20030814"; + + /** Local location of the XMLLoginParameterResolver Configuration XML schema definition */ + public static final String XMLLPR_SCHEMA_LOCATION = + SCHEMA_ROOT + "MOAIdentities.xsd"; + + /** Local location of the XAdES v1.1.1 schema definition */ + public static final String XADES_1_1_1_SCHEMA_LOCATION = + SCHEMA_ROOT + "XAdES-1.1.1.xsd"; + + /** URI of the XAdES v1.1.1 namespace */ + public static final String XADES_1_1_1_NS_URI = "http://uri.etsi.org/01903/v1.1.1#"; + + public static final String XADES_1_1_1_NS_PREFIX = "xades111"; + + /** Local location of the XAdES v1.2.2 schema definition */ + public static final String XADES_1_2_2_SCHEMA_LOCATION = + SCHEMA_ROOT + "XAdES-1.2.2.xsd"; + + /** URI of the XAdES v1.2.2 namespace */ + public static final String XADES_1_2_2_NS_URI = "http://uri.etsi.org/01903/v1.2.2#"; + + public static final String XADES_1_2_2_NS_PREFIX = "xades122"; + + /** Local location of the XAdES v1.1.1 schema definition */ + public static final String XADES_1_3_2_SCHEMA_LOCATION = + SCHEMA_ROOT + "XAdES-1.3.2.xsd"; + + /** URI of the XAdES v1.3.2 namespace */ + public static final String XADES_1_3_2_NS_URI = "http://uri.etsi.org/01903/v1.3.2#"; + + public static final String XADES_1_3_2_NS_PREFIX = "xades132"; + + /** Local location of the XAdES v1.4.1 schema definition */ + public static final String XADES_1_4_1_SCHEMA_LOCATION = + SCHEMA_ROOT + "XAdES-1.4.1.xsd"; + + /** URI of the XAdES v1.4.1 namespace */ + public static final String XADES_1_4_1_NS_URI = "http://uri.etsi.org/01903/v1.4.1#"; + + public static final String XADES_1_4_1_NS_PREFIX = "xades141"; + /** URI of the SAML 2.0 namespace. */ + public static final String SAML2_NS_URI = + "urn:oasis:names:tc:SAML:2.0:assertion"; + + /** Prefix used for the SAML 2.0 XML namespace */ + public static final String SAML2_PREFIX = "saml2"; + + /** Local location of the SAML 2.0 XML schema definition. */ + public static final String SAML2_SCHEMA_LOCATION = + SCHEMA_ROOT + "saml-schema-assertion-2.0.xsd"; + + /** URI of the SAML 2.0 protocol namespace. */ + public static final String SAML2P_NS_URI = + "urn:oasis:names:tc:SAML:2.0:protocol"; + + /** Prefix used for the SAML 2.0 protocol XML namespace */ + public static final String SAML2P_PREFIX = "saml2p"; + + /** Local location of the SAML 2.0 protocol XML schema definition. */ + public static final String SAML2P_SCHEMA_LOCATION = + SCHEMA_ROOT + "saml-schema-protocol-2.0.xsd"; + + /** URI of the STORK namespace. */ + public static final String STORK_NS_URI = + "urn:eu:stork:names:tc:STORK:1.0:assertion"; + + /** Prefix used for the STORK XML namespace */ + public static final String STORK_PREFIX = "stork"; + + /** Local location of the STORK XML schema definition. */ + public static final String STORK_SCHEMA_LOCATION = + SCHEMA_ROOT + "stork-schema-assertion-1.0.xsd"; + + /** URI of the STORK protocol namespace. */ + public static final String STORKP_NS_URI = + "urn:eu:stork:names:tc:STORK:1.0:protocol"; + + /** Prefix used for the STORK protocol XML namespace */ + public static final String STORKP_PREFIX = "storkp"; + + /** Local location of the STORK protocol XML schema definition. */ + public static final String STORKP_SCHEMA_LOCATION = + SCHEMA_ROOT + "stork-schema-protocol-1.0.xsd"; + + /** URI of the TSL namespace. */ + public static final String TSL_NS_URI = + "http://uri.etsi.org/02231/v2#"; + + /** Prefix used for the TSL namespace */ + public static final String TSL_PREFIX = "tsl1"; + + /** Local location of the TSL schema definition. */ + public static final String TSL_SCHEMA_LOCATION = + SCHEMA_ROOT + "ts_119612v010201_xsd.xsd"; + + /** URI of the TSL SIE namespace. */ + public static final String TSL_SIE_NS_URI = + "http://uri.etsi.org/TrstSvc/SvcInfoExt/eSigDir-1999-93-EC-TrustedList/#"; + + /** Prefix used for the TSL SIE namespace */ + public static final String TSL_SIE_PREFIX = "tslsie"; + + /** Local location of the TSL SIE schema definition. */ + public static final String TSL_SIE_SCHEMA_LOCATION = + SCHEMA_ROOT + "ts_119612v010201_sie_xsd.xsd"; + + /** URI of the TSL additional types namespace. */ + public static final String TSL_ADDTYPES_NS_URI = + "http://uri.etsi.org/02231/v2/additionaltypes#"; + + /** Prefix used for the TSL additional types namespace */ + public static final String TSL_ADDTYPES_PREFIX = "tsltype"; + + /** Local location of the TSL additional types schema definition. */ + public static final String TSL_ADDTYPES_SCHEMA_LOCATION = + SCHEMA_ROOT + "ts_ts_119612v010201_additionaltypes_xsd.xsd"; + + /** URI of the XML Encryption namespace. */ + public static final String XENC_NS_URI = + "http://www.w3.org/2001/04/xmlenc#"; + + /** Prefix used for the XML Encryption XML namespace */ + public static final String XENC_PREFIX = "xenc"; + + /** Local location of the XML Encryption XML schema definition. */ + public static final String XENC_SCHEMA_LOCATION = + SCHEMA_ROOT + "xenc-schema.xsd"; + + /** Prefix used for the XML Encryption XML namespace */ + public static final String SAML2_METADATA_PREFIX = "md"; + + /** Prefix used for the XML Encryption XML namespace */ + public static final String SAML2_METADATA_URI = "urn:oasis:names:tc:SAML:2.0:metadata"; + + /** Local location of the XML Encryption XML schema definition. */ + public static final String SAML2_METADATA_SCHEMA_LOCATION = + SCHEMA_ROOT + "saml-schema-metadata-2.0.xsd"; + + /** + * Contains all namespaces and local schema locations for XML schema + * definitions relevant for MOA. For use in validating XML parsers. + */ + public static final String ALL_SCHEMA_LOCATIONS = + (MOA_NS_URI + " " + MOA_SCHEMA_LOCATION + " ") + + (MOA_CONFIG_NS_URI + " " + MOA_CONFIG_SCHEMA_LOCATION + " ") + + (MOA_ID_CONFIG_NS_URI + " " + MOA_ID_CONFIG_SCHEMA_LOCATION + " ") + + (SL10_NS_URI + " " + SL10_SCHEMA_LOCATION + " ") + + (SL11_NS_URI + " " + SL11_SCHEMA_LOCATION + " ") + + (SL12_NS_URI + " " + SL12_SCHEMA_LOCATION + " ") + + (ECDSA_NS_URI + " " + ECDSA_SCHEMA_LOCATION + " ") + + (PD_NS_URI + " " + PD_SCHEMA_LOCATION + " ") + + (SAML_NS_URI + " " + SAML_SCHEMA_LOCATION + " ") + + (SAMLP_NS_URI + " " + SAMLP_SCHEMA_LOCATION + " ") + + (XML_NS_URI + " " + XML_SCHEMA_LOCATION + " ") + + (XSI_NS_URI + " " + XSI_SCHEMA_LOCATION + " ") + + (DSIG_NS_URI + " " + DSIG_SCHEMA_LOCATION + " ") + + (DSIG_FILTER2_NS_URI + " " + DSIG_FILTER2_SCHEMA_LOCATION + " ") + + (DSIG_EC_NS_URI + " " + DSIG_EC_SCHEMA_LOCATION + " ") + + (XMLLPR_NS_URI + " " + XMLLPR_SCHEMA_LOCATION + " ") + + (XADES_1_1_1_NS_URI + " " + XADES_1_1_1_SCHEMA_LOCATION + " ") + + (XADES_1_2_2_NS_URI + " " + XADES_1_2_2_SCHEMA_LOCATION + " ") + + (XADES_1_3_2_NS_URI + " " + XADES_1_3_2_SCHEMA_LOCATION + " ") + + (XADES_1_4_1_NS_URI + " " + XADES_1_4_1_SCHEMA_LOCATION + " ") + + (TSL_NS_URI + " " + TSL_SCHEMA_LOCATION + " ") + + (TSL_SIE_NS_URI + " " + TSL_SIE_SCHEMA_LOCATION + " ") + + (TSL_ADDTYPES_NS_URI + " " + TSL_ADDTYPES_SCHEMA_LOCATION + " ") + + (SAML2_NS_URI + " " + SAML2_SCHEMA_LOCATION + " ") + + (SAML2P_NS_URI + " " + SAML2P_SCHEMA_LOCATION + " ") + + (STORK_NS_URI + " " + STORK_SCHEMA_LOCATION + " ") + + (STORKP_NS_URI + " " + STORKP_SCHEMA_LOCATION + " ") + + (SAML2_METADATA_URI + " " + SAML2_METADATA_SCHEMA_LOCATION + " ") + + (XENC_NS_URI + " " + XENC_SCHEMA_LOCATION); + + /** URN prefix for bPK and wbPK. */ + public static final String URN_PREFIX = "urn:publicid:gv.at"; + + /** URN prefix for context dependent id. */ + public static final String URN_PREFIX_CDID = URN_PREFIX + ":cdid"; + + /** URN prefix for context dependent id (bPK). */ + public static final String URN_PREFIX_BPK = URN_PREFIX_CDID + "+bpk"; + + /** URN prefix for context dependent id (HPI). */ + public static final String URN_PREFIX_HPI = URN_PREFIX_CDID + "+EHSP"; + + /** URN prefix for context dependent id (wbPK). */ + public static final String URN_PREFIX_WBPK = URN_PREFIX + ":wbpk"; + + /** URN prefix for context dependent id (stork). */ + public static final String URN_PREFIX_STORK = URN_PREFIX + ":storkid"; + + //TODO: update to eIDAS prefix + /** URN prefix for context dependent id (eIDAS). */ + public static final String URN_PREFIX_EIDAS = URN_PREFIX + ":storkid"; + + /** URN prefix for context dependent id. */ + public static final String URN_PREFIX_BASEID = URN_PREFIX + ":baseid"; + + /** Security Layer manifest type URI. */ + public static final String SL_MANIFEST_TYPE_URI = + "http://www.buergerkarte.at/specifications/Security-Layer/20020225#SignatureManifest"; + + /** URI of the SHA1 digest algorithm */ + public static final String SHA1_URI = + "http://www.w3.org/2000/09/xmldsig#sha1"; + + /** URI of the SHA1 digest algorithm */ + public static final String SHA256_URI = + "http://www.w3.org/2000/09/xmldsig#sha256"; + + /** URI of the SHA1 digest algorithm */ + public static final String SHA384_URI = + "http://www.w3.org/2000/09/xmldsig#sha384"; + + /** URI of the SHA1 digest algorithm */ + public static final String SHA512_URI = + "http://www.w3.org/2000/09/xmldsig#sha512"; + + /** URI of the Canonical XML algorithm */ + public static final String C14N_URI = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + + /** URI of the Canoncial XML with comments algorithm */ + public static final String C14N_WITH_COMMENTS_URI = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; + + /** URI of the Exclusive Canonical XML algorithm */ + public static final String EXC_C14N_URI = + "http://www.w3.org/2001/10/xml-exc-c14n#"; + + /** URI of the Exclusive Canonical XML with commments algorithm */ + public static final String EXC_C14N_WITH_COMMENTS_URI = + "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; + + // + // Local names for elements of the MOA SPSS schema + // + + /** + * Local name of request for creating an XML signature. + */ + public static final String MOA_SPSS_CREATE_XML_REQUEST = "CreateXMLSignatureRequest"; + + /** + * Local name of request for creating a CMS signature. + */ + public static final String MOA_SPSS_CREATE_CMS_REQUEST = "CreateCMSSignatureRequest"; + + /** + * Local name of request for verifying an XML signature. + */ + public static final String MOA_SPSS_VERIFY_XML_REQUEST = "VerifiyXMLSignatureRequest"; + + /** + * A map used to map namespace prefixes to namespace URIs + */ + public static HashMap nSMap = new HashMap(5); + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java new file mode 100644 index 000000000..0a07fc4a7 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java @@ -0,0 +1,1172 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Vector; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.xerces.parsers.DOMParser; +import org.apache.xerces.parsers.SAXParser; +import org.apache.xerces.parsers.XMLGrammarPreparser; +import org.apache.xerces.util.SymbolTable; +import org.apache.xerces.util.XMLGrammarPoolImpl; +import org.apache.xerces.xni.grammars.XMLGrammarDescription; +import org.apache.xerces.xni.grammars.XMLGrammarPool; +import org.apache.xerces.xni.parser.XMLInputSource; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.logging.Logger; + +/** + * Various utility functions for handling XML DOM trees. + * + * The parsing methods in this class make use of some features internal to the + * Xerces DOM parser, mainly for performance reasons. As soon as JAXP + * (currently at version 1.2) is better at schema handling, it should be used as + * the parser interface. + * + * @author Patrick Peck + * @version $Id$ + */ +public class DOMUtils { + + /** Feature URI for namespace aware parsing. */ + private static final String NAMESPACES_FEATURE = + "http://xml.org/sax/features/namespaces"; + /** Feature URI for validating parsing. */ + private static final String VALIDATION_FEATURE = + "http://xml.org/sax/features/validation"; + /** Feature URI for schema validating parsing. */ + private static final String SCHEMA_VALIDATION_FEATURE = + "http://apache.org/xml/features/validation/schema"; + /** Feature URI for normalization of element/attribute values. */ + private static final String NORMALIZED_VALUE_FEATURE = + "http://apache.org/xml/features/validation/schema/normalized-value"; + /** Feature URI for parsing ignorable whitespace. */ + private static final String INCLUDE_IGNORABLE_WHITESPACE_FEATURE = + "http://apache.org/xml/features/dom/include-ignorable-whitespace"; + /** Feature URI for creating EntityReference nodes in the DOM tree. */ + private static final String CREATE_ENTITY_REF_NODES_FEATURE = + "http://apache.org/xml/features/dom/create-entity-ref-nodes"; + /** Property URI for providing external schema locations. */ + private static final String EXTERNAL_SCHEMA_LOCATION_PROPERTY = + "http://apache.org/xml/properties/schema/external-schemaLocation"; + /** Property URI for providing the external schema location for elements + * without a namespace. */ + private static final String EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY = + "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation"; + + private static final String EXTERNAL_GENERAL_ENTITIES_FEATURE = + "http://xml.org/sax/features/external-general-entities"; + + private static final String EXTERNAL_PARAMETER_ENTITIES_FEATURE = + "http://xml.org/sax/features/external-parameter-entities"; + + private static final String DISALLOW_DOCTYPE_FEATURE = + "http://apache.org/xml/features/disallow-doctype-decl"; + + + + /** Property URI for the Xerces grammar pool. */ + private static final String GRAMMAR_POOL = + org.apache.xerces.impl.Constants.XERCES_PROPERTY_PREFIX + + org.apache.xerces.impl.Constants.XMLGRAMMAR_POOL_PROPERTY; + /** A prime number for initializing the symbol table. */ + private static final int BIG_PRIME = 2039; + /** Symbol table for the grammar pool. */ + private static SymbolTable symbolTable = new SymbolTable(BIG_PRIME); + /** Xerces schema grammar pool. */ + private static XMLGrammarPool grammarPool = new XMLGrammarPoolImpl(); + /** Set holding the NamespaceURIs of the grammarPool, to prevent multiple + * entries of same grammars to the pool */ + private static Set grammarNamespaces; + + static { + grammarPool.lockPool(); + grammarNamespaces = new HashSet(); + } + + /** + * Preparse a schema and add it to the schema pool. + * The method only adds the schema to the pool if a schema having the same + * systemId (namespace URI) is not already present in the pool. + * + * @param inputStream An InputStream providing the contents of + * the schema. + * @param systemId The systemId (namespace URI) to use for the schema. + * @throws IOException An error occurred reading the schema. + */ + public static void addSchemaToPool(InputStream inputStream, String systemId) + throws IOException { + XMLGrammarPreparser preparser; + + if (!grammarNamespaces.contains(systemId)) { + + grammarNamespaces.add(systemId); + + // unlock the pool so that we can add another grammar + grammarPool.unlockPool(); + + // prepare the preparser + preparser = new XMLGrammarPreparser(symbolTable); + preparser.registerPreparser(XMLGrammarDescription.XML_SCHEMA, null); + preparser.setProperty(GRAMMAR_POOL, grammarPool); + preparser.setFeature(NAMESPACES_FEATURE, true); + preparser.setFeature(VALIDATION_FEATURE, true); + + // add the grammar to the pool + preparser.preparseGrammar( + XMLGrammarDescription.XML_SCHEMA, + new XMLInputSource(null, systemId, null, inputStream, null)); + + // lock the pool again so that schemas are not added automatically + grammarPool.lockPool(); + } + } + + /** + * Parse an XML document from an InputStream. + * + * @param inputStream The InputStream containing the XML + * document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace + * URI to schema location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the + * schema for elements without a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @param entityResolver An EntityResolver to resolve external + * entities (schemas and DTDs). If null, it will not be set. + * @param errorHandler An ErrorHandler to decide what to do + * with parsing errors. If null, it will not be set. + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML + * parser. + */ + public static Document parseDocument( + InputStream inputStream, + boolean validating, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation, + EntityResolver entityResolver, + ErrorHandler errorHandler) + throws SAXException, IOException, ParserConfigurationException { + + DOMParser parser; + +// class MyEntityResolver implements EntityResolver { +// +// public InputSource resolveEntity(String publicId, String systemId) +// throws SAXException, IOException { +// return new InputSource(new ByteArrayInputStream(new byte[0])); +// } +// } + + + //if Debug is enabled make a copy of inputStream to enable debug output in case of SAXException + byte buffer [] = null; + ByteArrayInputStream baStream = null; + if(true == Logger.isDebugEnabled()) { + int len = inputStream.available(); + buffer = new byte[len]; + inputStream.read(buffer); + baStream = new ByteArrayInputStream(buffer); + } + + // create the DOM parser + if (symbolTable != null) { + parser = new DOMParser(symbolTable, grammarPool); + } else { + parser = new DOMParser(); + } + + // set parser features and properties + try { + parser.setFeature(NAMESPACES_FEATURE, true); + parser.setFeature(VALIDATION_FEATURE, validating); + parser.setFeature(SCHEMA_VALIDATION_FEATURE, validating); + parser.setFeature(NORMALIZED_VALUE_FEATURE, false); + parser.setFeature(INCLUDE_IGNORABLE_WHITESPACE_FEATURE, true); + parser.setFeature(CREATE_ENTITY_REF_NODES_FEATURE, false); + parser.setFeature(EXTERNAL_GENERAL_ENTITIES_FEATURE, false); + parser.setFeature(EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); + + //fix XXE problem + parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + + + if (validating) { + if (externalSchemaLocations != null) { + parser.setProperty( + EXTERNAL_SCHEMA_LOCATION_PROPERTY, + externalSchemaLocations); + } + if (externalNoNamespaceSchemaLocation != null) { + parser.setProperty( + EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, + externalNoNamespaceSchemaLocation); + } + } + + // set entity resolver and error handler + if (entityResolver != null) { + parser.setEntityResolver(entityResolver); + } + if (errorHandler != null) { + parser.setErrorHandler(errorHandler); + } + + // parse the document and return it + // if debug is enabled: use copy of strem (baStream) else use orig stream + if(null != baStream) + parser.parse(new InputSource(baStream)); + else + parser.parse(new InputSource(inputStream)); + } catch(SAXException e) { + if(true == Logger.isDebugEnabled() && null != buffer) { + String xmlContent = new String(buffer); + Logger.debug("SAXException in:\n" + xmlContent); + } + throw(e); + } + + return parser.getDocument(); + } + + /** + * Parse an XML document from an InputStream. + * + * @param inputStream The InputStream containing the XML + * document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace + * URI to schema location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the + * schema for elements without a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @param entityResolver An EntityResolver to resolve external + * entities (schemas and DTDs). If null, it will not be set. + * @param errorHandler An ErrorHandler to decide what to do + * with parsing errors. If null, it will not be set. + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML + * parser. + */ + public static Document parseDocumentSimple(InputStream inputStream) + throws SAXException, IOException, ParserConfigurationException { + + DOMParser parser; + + parser = new DOMParser(); + // set parser features and properties + parser.setFeature(NAMESPACES_FEATURE, true); + parser.setFeature(VALIDATION_FEATURE, false); + parser.setFeature(SCHEMA_VALIDATION_FEATURE, false); + parser.setFeature(NORMALIZED_VALUE_FEATURE, false); + parser.setFeature(INCLUDE_IGNORABLE_WHITESPACE_FEATURE, true); + parser.setFeature(CREATE_ENTITY_REF_NODES_FEATURE, false); + + parser.parse(new InputSource(inputStream)); + + return parser.getDocument(); + } + + + /** + * Parse an XML document from an InputStream. + * + * It uses a MOAEntityResolver as the EntityResolver + * and a MOAErrorHandler as the ErrorHandler. + * + * @param inputStream The InputStream containing the XML + * document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace + * URI to schema location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the + * schema for elements without a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML + * parser. + */ + public static Document parseDocument( + InputStream inputStream, + boolean validating, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation) + throws SAXException, IOException, ParserConfigurationException { + + + + return parseDocument( + inputStream, + validating, + externalSchemaLocations, + externalNoNamespaceSchemaLocation, + new MOAEntityResolver(), + new MOAErrorHandler()); + } + + /** + * Parse an XML document from a String. + * + * It uses a MOAEntityResolver as the EntityResolver + * and a MOAErrorHandler as the ErrorHandler. + * + * @param xmlString The String containing the XML document. + * @param encoding The encoding of the XML document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace + * URI to schema location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the + * schema for elements without a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML + * parser. + */ + public static Document parseDocument( + String xmlString, + String encoding, + boolean validating, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation) + throws SAXException, IOException, ParserConfigurationException { + + InputStream in = new ByteArrayInputStream(xmlString.getBytes(encoding)); + return parseDocument( + in, + validating, + externalSchemaLocations, + externalNoNamespaceSchemaLocation); + } + + /** + * Parse an UTF-8 encoded XML document from a String. + * + * @param xmlString The String containing the XML document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace + * URI to schema location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the + * schema for elements without a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML + * parser. + */ + public static Document parseDocument( + String xmlString, + boolean validating, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation) + throws SAXException, IOException, ParserConfigurationException { + + return parseDocument( + xmlString, + "UTF-8", + validating, + externalSchemaLocations, + externalNoNamespaceSchemaLocation); + } + + /** + * A convenience method to parse an XML document validating. + * + * @param inputStream The InputStream containing the XML + * document. + * @return The root element of the parsed XML document. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML + * parser. + */ + public static Element parseXmlValidating(InputStream inputStream) + throws ParserConfigurationException, SAXException, IOException { + return DOMUtils + .parseDocument(inputStream, true, Constants.ALL_SCHEMA_LOCATIONS, null) + .getDocumentElement(); + } + + /** + * A convenience method to parse an XML document non validating. + * + * @param inputStream The InputStream containing the XML + * document. + * @return The root element of the parsed XML document. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML + * parser. + */ + public static Element parseXmlNonValidating(InputStream inputStream) + throws ParserConfigurationException, SAXException, IOException { + return DOMUtils + .parseDocument(inputStream, false, Constants.ALL_SCHEMA_LOCATIONS, null) + .getDocumentElement(); + } + + /** + * Schema validate a given DOM element. + * + * @param element The element to validate. + * @param externalSchemaLocations A String containing namespace + * URI to schema location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the + * schema for elements without a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return true, if the element validates against + * the schemas declared in it. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document from its + * serialized representation. + * @throws ParserConfigurationException An error occurred configuring the XML + * @throws TransformerException An error occurred serializing the element. + */ + public static boolean validateElement( + Element element, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation) + throws + ParserConfigurationException, + IOException, + SAXException, + TransformerException { + + byte[] docBytes; + SAXParser parser; + + // create the SAX parser + if (symbolTable != null) { + parser = new SAXParser(symbolTable, grammarPool); + } else { + parser = new SAXParser(); + } + + // serialize the document + docBytes = serializeNode(element, "UTF-8"); + + // set up parser features and attributes + parser.setFeature(NAMESPACES_FEATURE, true); + parser.setFeature(VALIDATION_FEATURE, true); + parser.setFeature(SCHEMA_VALIDATION_FEATURE, true); + parser.setFeature(EXTERNAL_GENERAL_ENTITIES_FEATURE, false); + parser.setFeature(DISALLOW_DOCTYPE_FEATURE, true); + + + if (externalSchemaLocations != null) { + parser.setProperty( + EXTERNAL_SCHEMA_LOCATION_PROPERTY, + externalSchemaLocations); + } + if (externalNoNamespaceSchemaLocation != null) { + parser.setProperty( + EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, + "externalNoNamespaceSchemaLocation"); + } + + // set up entity resolver and error handler + parser.setEntityResolver(new MOAEntityResolver()); + parser.setErrorHandler(new MOAErrorHandler()); + + // parse validating + parser.parse(new InputSource(new ByteArrayInputStream(docBytes))); + return true; + } + + + /** + * Schema validate a given DOM element. + * + * @param element The element to validate. + * @param externalSchemaLocations A String containing namespace + * URI to schema location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the + * schema for elements without a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return true, if the element validates against + * the schemas declared in it. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document from its + * serialized representation. + * @throws ParserConfigurationException An error occurred configuring the XML + * @throws TransformerException An error occurred serializing the element. + */ + public static boolean validateElement( + Element element, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation, + EntityResolver entityResolver) + throws + ParserConfigurationException, + IOException, + SAXException, + TransformerException { + + byte[] docBytes; + SAXParser parser; + + // create the SAX parser + if (symbolTable != null) { + parser = new SAXParser(symbolTable, grammarPool); + } else { + parser = new SAXParser(); + } + + // serialize the document + docBytes = serializeNode(element, "UTF-8"); + + // set up parser features and attributes + parser.setFeature(NAMESPACES_FEATURE, true); + parser.setFeature(VALIDATION_FEATURE, true); + parser.setFeature(SCHEMA_VALIDATION_FEATURE, true); + + if (externalSchemaLocations != null) { + parser.setProperty( + EXTERNAL_SCHEMA_LOCATION_PROPERTY, + externalSchemaLocations); + } + if (externalNoNamespaceSchemaLocation != null) { + parser.setProperty( + EXTERNAL_NO_NAMESPACE_SCHEMA_LOCATION_PROPERTY, + "externalNoNamespaceSchemaLocation"); + } + + // set up entity resolver and error handler + parser.setEntityResolver(entityResolver); + parser.setErrorHandler(new MOAErrorHandler()); + + // parse validating + parser.parse(new InputSource(new ByteArrayInputStream(docBytes))); + return true; + } + + /** + * Serialize the given DOM node. + * + * The node will be serialized using the UTF-8 encoding. + * + * @param node The node to serialize. + * @return String The String representation of the given DOM + * node. + * @throws TransformerException An error occurred transforming the + * node to a String. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static String serializeNode(Node node) + throws TransformerException, IOException { + return new String(serializeNode(node, "UTF-8", false), "UTF-8"); + } + + + /** + * Serialize the given DOM node. + * + * The node will be serialized using the UTF-8 encoding. + * + * @param node The node to serialize. + * @param omitXmlDeclaration The boolean value for omitting the XML Declaration. + * @return String The String representation of the given DOM + * node. + * @throws TransformerException An error occurred transforming the + * node to a String. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static String serializeNode(Node node, boolean omitXmlDeclaration) + throws TransformerException, IOException { + return new String(serializeNode(node, "UTF-8", omitXmlDeclaration), "UTF-8"); + } + + /** + * Serialize the given DOM node. + * + * The node will be serialized using the UTF-8 encoding. + * + * @param node The node to serialize. + * @param omitXmlDeclaration The boolean value for omitting the XML Declaration. + * @param lineSeperator Sets the line seperator String of the parser + * @return String The String representation of the given DOM + * node. + * @throws TransformerException An error occurred transforming the + * node to a String. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static String serializeNode(Node node, boolean omitXmlDeclaration, String lineSeperator) + throws TransformerException, IOException { + return new String(serializeNode(node, "UTF-8", omitXmlDeclaration, lineSeperator), "UTF-8"); + } + + /** + * Serialize the given DOM node to a byte array. + * + * @param node The node to serialize. + * @param xmlEncoding The XML encoding to use. + * @return The serialized node, as a byte array. Using a compatible encoding + * this can easily be converted into a String. + * @throws TransformerException An error occurred transforming the node to a + * byte array. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static byte[] serializeNode(Node node, String xmlEncoding) + throws TransformerException, IOException { + return serializeNode(node, xmlEncoding, false); + } + + /** + * Serialize the given DOM node to a byte array. + * + * @param node The node to serialize. + * @param xmlEncoding The XML encoding to use. + * @param omitDeclaration The boolean value for omitting the XML Declaration. + * @return The serialized node, as a byte array. Using a compatible encoding + * this can easily be converted into a String. + * @throws TransformerException An error occurred transforming the node to a + * byte array. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static byte[] serializeNode(Node node, String xmlEncoding, boolean omitDeclaration) + throws TransformerException, IOException { + return serializeNode(node, xmlEncoding, omitDeclaration, null); + } + + + /** + * Serialize the given DOM node to a byte array. + * + * @param node The node to serialize. + * @param xmlEncoding The XML encoding to use. + * @param omitDeclaration The boolean value for omitting the XML Declaration. + * @param lineSeperator Sets the line seperator String of the parser + * @return The serialized node, as a byte array. Using a compatible encoding + * this can easily be converted into a String. + * @throws TransformerException An error occurred transforming the node to a + * byte array. + * @throws IOException An IO error occurred writing the node to a byte array. + */ + public static byte[] serializeNode(Node node, String xmlEncoding, boolean omitDeclaration, String lineSeperator) + throws TransformerException, IOException { + + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + ByteArrayOutputStream bos = new ByteArrayOutputStream(16384); + + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.ENCODING, xmlEncoding); + String omit = omitDeclaration ? "yes" : "no"; + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omit); + if (null!=lineSeperator) { + transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", lineSeperator);//does not work for xalan <= 2.5.1 + } + transformer.transform(new DOMSource(node), new StreamResult(bos)); + + bos.flush(); + bos.close(); + + return bos.toByteArray(); + } + + /** + * Return the text that a node contains. + * + * This routine: + *

    + *
  • Ignores comments and processing instructions.
  • + *
  • Concatenates TEXT nodes, CDATA nodes, and the results recursively + * processing EntityRef nodes.
  • + *
  • Ignores any element nodes in the sublist. (Other possible options are + * to recurse into element sublists or throw an exception.)
  • + *
+ * + * @param node A DOM node from which to extract text. + * @return A String representing its contents. + */ + public static String getText(Node node) { + if (!node.hasChildNodes()) { + return ""; + } + + StringBuffer result = new StringBuffer(); + NodeList list = node.getChildNodes(); + + for (int i = 0; i < list.getLength(); i++) { + Node subnode = list.item(i); + if (subnode.getNodeType() == Node.TEXT_NODE) { + result.append(subnode.getNodeValue()); + } else if (subnode.getNodeType() == Node.CDATA_SECTION_NODE) { + result.append(subnode.getNodeValue()); + } else if (subnode.getNodeType() == Node.ENTITY_REFERENCE_NODE) { + // Recurse into the subtree for text + // (and ignore comments) + result.append(getText(subnode)); + } + } + return result.toString(); + } + + /** + * Build the namespace prefix to namespace URL mapping in effect for a given + * node. + * + * @param node The context node for which build the map. + * @return The namespace prefix to namespace URL mapping ( + * a String value to String value mapping). + */ + public static Map getNamespaceDeclarations(Node node) { + Map nsDecls = new HashMap(); + int i; + + do { + if (node.hasAttributes()) { + NamedNodeMap attrs = node.getAttributes(); + + for (i = 0; i < attrs.getLength(); i++) { + Attr attr = (Attr) attrs.item(i); + + // add prefix mapping if none exists + if ("xmlns".equals(attr.getPrefix()) + || "xmlns".equals(attr.getName())) { + + String nsPrefix = + attr.getPrefix() != null ? attr.getLocalName() : ""; + + if (nsDecls.get(nsPrefix) == null) { + nsDecls.put(nsPrefix, attr.getValue()); + } + } + } + } + } while ((node = node.getParentNode()) != null); + + return nsDecls; + } + + /** + * Add all namespace declarations declared in the parent(s) of a given + * element and used in the subtree of the given element to the given element. + * + * @param context The element to which to add the namespaces. + */ + public static void localizeNamespaceDeclarations(Element context) { + Node parent = context.getParentNode(); + + if (parent != null) { + Map namespaces = getNamespaceDeclarations(context.getParentNode()); + Set nsUris = collectNamespaceURIs(context); + Iterator iter; + + for (iter = namespaces.entrySet().iterator(); iter.hasNext();) { + Map.Entry e = (Map.Entry) iter.next(); + + if (nsUris.contains(e.getValue())) { + String prefix = (String) e.getKey(); + String nsUri = (String) e.getValue(); + String nsAttrName = "".equals(prefix) ? "xmlns" : "xmlns:" + prefix; + + context.setAttributeNS(Constants.XMLNS_NS_URI, nsAttrName, nsUri); + } + } + } + } + + /** + * Collect all the namespace URIs used in the subtree of a given element. + * + * @param context The element that should be searched for namespace URIs. + * @return All namespace URIs used in the subtree of context, + * including the ones used in context itself. + */ + public static Set collectNamespaceURIs(Element context) { + Set result = new HashSet(); + + collectNamespaceURIsImpl(context, result); + return result; + } + + /** + * A recursive method to do the work of collectNamespaceURIs. + * + * @param context The context element to evaluate. + * @param result The result, passed as a parameter to avoid unnecessary + * instantiations of Set. + */ + private static void collectNamespaceURIsImpl(Element context, Set result) { + NamedNodeMap attrs = context.getAttributes(); + NodeList childNodes = context.getChildNodes(); + String nsUri; + int i; + + // add the namespace of the context element + nsUri = context.getNamespaceURI(); + if (nsUri != null && nsUri != Constants.XMLNS_NS_URI) { + result.add(nsUri); + } + + // add all namespace URIs from attributes + for (i = 0; i < attrs.getLength(); i++) { + nsUri = attrs.item(i).getNamespaceURI(); + if (nsUri != null && nsUri != Constants.XMLNS_NS_URI) { + result.add(nsUri); + } + } + + // add all namespaces from subelements + for (i = 0; i < childNodes.getLength(); i++) { + Node node = childNodes.item(i); + + if (node.getNodeType() == Node.ELEMENT_NODE) { + collectNamespaceURIsImpl((Element) node, result); + } + } + } + + /** + * Check, that each attribute node in the given NodeList has its + * parent in the NodeList as well. + * + * @param nodes The NodeList to check. + * @return true, if each attribute node in nodes + * has its parent in nodes as well. + */ + public static boolean checkAttributeParentsInNodeList(NodeList nodes) { + Set nodeSet = new HashSet(); + int i; + + // put the nodes into the nodeSet + for (i = 0; i < nodes.getLength(); i++) { + nodeSet.add(nodes.item(i)); + } + + // check that each attribute node's parent is in the node list + for (i = 0; i < nodes.getLength(); i++) { + Node n = nodes.item(i); + + if (n.getNodeType() == Node.ATTRIBUTE_NODE) { + Attr attr = (Attr) n; + Element owner = attr.getOwnerElement(); + + if (owner == null) { + if (!isNamespaceDeclaration(attr)) { + return false; + } + } + + if (!nodeSet.contains(owner) && !isNamespaceDeclaration(attr)) { + return false; + } + } + } + + return true; + } + + /** + * Convert an unstructured NodeList into a + * DocumentFragment. + * + * @param nodeList Contains the node list to be converted into a DOM + * DocumentFragment. + * @return the resulting DocumentFragment. The DocumentFragment will be + * backed by a new DOM Document, i.e. all noded of the node list will be + * cloned. + * @throws ParserConfigurationException An error occurred creating the + * DocumentFragment. + * @precondition The nodes in the node list appear in document order + * @precondition for each Attr node in the node list, the owning Element is + * in the node list as well. + * @precondition each Element or Attr node in the node list is namespace + * aware. + */ + public static DocumentFragment nodeList2DocumentFragment(NodeList nodeList) + throws ParserConfigurationException { + + DocumentBuilder builder = + DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document doc = builder.newDocument(); + DocumentFragment result = doc.createDocumentFragment(); + + if (null == nodeList || nodeList.getLength() == 0) { + return result; + } + + int currPos = 0; + currPos = + nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; + + while (currPos < nodeList.getLength()) { + currPos = + nodeList2DocumentFragment(nodeList, currPos, result, null, null) + 1; + } + return result; + } + + /** + * Helper method for the nodeList2DocumentFragment. + * + * @param nodeList The NodeList to convert. + * @param currPos The current position in the nodeList. + * @param result The resulting DocumentFragment. + * @param currOrgElem The current original element. + * @param currClonedElem The current cloned element. + * @return The current position. + */ + private static int nodeList2DocumentFragment( + NodeList nodeList, + int currPos, + DocumentFragment result, + Element currOrgElem, + Element currClonedElem) { + + while (currPos < nodeList.getLength()) { + Node currentNode = nodeList.item(currPos); + switch (currentNode.getNodeType()) { + case Node.COMMENT_NODE : + case Node.PROCESSING_INSTRUCTION_NODE : + case Node.TEXT_NODE : + { + // Append current node either to resulting DocumentFragment or to + // current cloned Element + if (null == currClonedElem) { + result.appendChild( + result.getOwnerDocument().importNode(currentNode, false)); + } else { + // Stop processing if current Node is not a descendant of + // current Element + if (!isAncestor(currOrgElem, currentNode)) { + return --currPos; + } + + currClonedElem.appendChild( + result.getOwnerDocument().importNode(currentNode, false)); + } + break; + } + + case Node.ELEMENT_NODE : + { + Element nextCurrOrgElem = (Element) currentNode; + Element nextCurrClonedElem = + result.getOwnerDocument().createElementNS( + nextCurrOrgElem.getNamespaceURI(), + nextCurrOrgElem.getNodeName()); + + // Append current Node either to resulting DocumentFragment or to + // current cloned Element + if (null == currClonedElem) { + result.appendChild(nextCurrClonedElem); + currOrgElem = nextCurrOrgElem; + currClonedElem = nextCurrClonedElem; + } else { + // Stop processing if current Node is not a descendant of + // current Element + if (!isAncestor(currOrgElem, currentNode)) { + return --currPos; + } + + currClonedElem.appendChild(nextCurrClonedElem); + } + + // Process current Node (of type Element) recursively + currPos = + nodeList2DocumentFragment( + nodeList, + ++currPos, + result, + nextCurrOrgElem, + nextCurrClonedElem); + + break; + } + + case Node.ATTRIBUTE_NODE : + { + Attr currAttr = (Attr) currentNode; + + // GK 20030411: Hack to overcome problems with IAIK IXSIL + if (currAttr.getOwnerElement() == null) + break; + if (currClonedElem == null) + break; + + // currClonedElem must be the owner Element of currAttr if + // preconditions are met + currClonedElem.setAttributeNS( + currAttr.getNamespaceURI(), + currAttr.getNodeName(), + currAttr.getValue()); + break; + } + + default : + { + // All other nodes will be ignored + } + } + + currPos++; + } + + return currPos; + } + + /** + * Check, if the given attribute is a namespace declaration. + * + * @param attr The attribute to check. + * @return true, if the attribute is a namespace declaration, + * false otherwise. + */ + private static boolean isNamespaceDeclaration(Attr attr) { + return Constants.XMLNS_NS_URI.equals(attr.getNamespaceURI()); + } + + /** + * Check, if a given DOM element is an ancestor of a given node. + * + * @param candAnc The DOM element to check for being the ancestor. + * @param cand The node to check for being the child. + * @return true, if candAnc is an (indirect) + * ancestor of cand; false otherwise. + */ + public static boolean isAncestor(Element candAnc, Node cand) { + Node currPar = cand.getParentNode(); + + while (currPar != null) { + if (candAnc == currPar) + return true; + currPar = currPar.getParentNode(); + } + return false; + } + + /** + * Selects the (first) element from a node list and returns it. + * + * @param nl The NodeList to get the element from. + * @return The (first) element included in the node list or null + * if the node list is null or empty or no element is + * included in the list. + */ + public static Element getElementFromNodeList (NodeList nl) { + if ((nl == null) || (nl.getLength() == 0)) { + return null; + } + for (int i=0; idateTime, + * according to ISO 8601. + * + * @author Patrick Peck + * @version $Id$ + * @see http://www.w3.org/2001/XMLSchema-datatypes" + */ +public class DateTimeUtils { + /** Error messages. */ + private static MessageProvider msg = MessageProvider.getInstance(); + +// /** +// * Builds a dateTime value from a Calendar value. +// * @param cal the Calendar value +// * @return the dateTime value +// */ +// public static String buildDateTime(Calendar cal, boolean useUTC) { +// +// if (useUTC) +// return buildDateTimeUTC(cal); +// else { +// StringWriter out = new StringWriter(); +// out.write("" + cal.get(Calendar.YEAR)); +// out.write("-"); +// out.write(to2DigitString(cal.get(Calendar.MONTH) + 1)); +// out.write("-"); +// out.write(to2DigitString(cal.get(Calendar.DAY_OF_MONTH))); +// out.write("T"); +// out.write(to2DigitString(cal.get(Calendar.HOUR_OF_DAY))); +// out.write(":"); +// out.write(to2DigitString(cal.get(Calendar.MINUTE))); +// out.write(":"); +// out.write(to2DigitString(cal.get(Calendar.SECOND))); +// int tzOffsetMilliseconds = +// cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET); +// if (tzOffsetMilliseconds != 0) { +// int tzOffsetMinutes = tzOffsetMilliseconds / (1000 * 60); +// int tzOffsetHours = tzOffsetMinutes / 60; +// tzOffsetMinutes -= tzOffsetHours * 60; +// if (tzOffsetMilliseconds > 0) { +// out.write("+"); +// out.write(to2DigitString(tzOffsetHours)); +// out.write(":"); +// out.write(to2DigitString(tzOffsetMinutes)); +// } else { +// out.write("-"); +// out.write(to2DigitString(-tzOffsetHours)); +// out.write(":"); +// out.write(to2DigitString(-tzOffsetMinutes)); +// } +// } +// return out.toString(); +// } +// } + + /** + * Builds a dateTime value in UTC from a Calendar value. + * @param cal the Calendar value + * @return the dateTime value + */ + public static String buildDateTimeUTC(Calendar cal) { + + SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + f.setTimeZone(TimeZone.getTimeZone("UTC")); + + return f.format(cal.getTime()); + } + + /** + * Builds a dateTime value in UTC from a Calendar value. + * @param cal the Calendar value + * @return the dateTime value + */ + public static String buildDateTimeUTC(Date cal) { + + SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + f.setTimeZone(TimeZone.getTimeZone("UTC")); + + return f.format(cal); + + } + + /** + * Builds a dateTime value from a Calendar value. + * @param cal the Calendar value + * @return the dateTime value + */ + public static String buildDate(Calendar cal) { + StringWriter out = new StringWriter(); + out.write("" + cal.get(Calendar.YEAR)); + out.write("-"); + out.write(to2DigitString(cal.get(Calendar.MONTH) + 1)); + out.write("-"); + out.write(to2DigitString(cal.get(Calendar.DAY_OF_MONTH))); + return out.toString(); + } + + /** + * Builds a dateTime value from a Calendar value. + * @param cal the Calendar value + * @return the dateTime value + */ + public static String buildTime(Calendar cal) { + StringWriter out = new StringWriter(); + out.write(to2DigitString(cal.get(Calendar.HOUR_OF_DAY))); + out.write(":"); + out.write(to2DigitString(cal.get(Calendar.MINUTE))); + out.write(":"); + out.write(to2DigitString(cal.get(Calendar.SECOND))); + + return out.toString(); + } + + /** + * Converts month, day, hour, minute, or second value + * to a 2 digit String. + * @param number the month, day, hour, minute, or second value + * @return 2 digit String + */ + private static String to2DigitString(int number) { + if (number < 10) + return "0" + number; + else + return "" + number; + } + + /** + * Parse a String containing a date and time instant, given in + * ISO 8601 format. + * + * @param dateTime The String to parse. + * @return The Date representation of the contents of + * dateTime. + * @throws ParseException Parsing the dateTime failed. + */ + public static Date parseDateTime(String dateTime) throws ParseException { + GregorianCalendar calendar; + long time; + int yearSign = 1, year, month, day; + int hour, minute, second; + double fraction = 0.0; + int tzSign = 1, tzHour = 0, tzMinute = 0; + int curPos = 0; + String fractStr; + boolean localTime = false; + char c; + + // parse year sign + ensureChars(dateTime, curPos, 1); + c = dateTime.charAt(curPos); + if (c == '+' || c == '-') { + yearSign = c == '+' ? 1 : -1; + curPos++; + } + + // parse year + year = parseInt(dateTime, curPos, 4); + curPos += 4; + + // parse '-' + ensureChar(dateTime, curPos, '-'); + curPos++; + + // parse month + month = parseInt(dateTime, curPos, 2); + ensureValue(month, 1, 12, curPos); + curPos += 2; + + // parse '-' + ensureChar(dateTime, curPos, '-'); + curPos++; + + // parse day + day = parseInt(dateTime, curPos, 2); + ensureValue(day, 1, 31, curPos); + curPos += 2; + + // parse 'T' + ensureChar(dateTime, curPos, 'T'); + curPos++; + + // parse hour + hour = parseInt(dateTime, curPos, 2); + ensureValue(hour, 0, 23, curPos); + curPos += 2; + + // parse ':' + ensureChar(dateTime, curPos, ':'); + curPos++; + + // parse minute + minute = parseInt(dateTime, curPos, 2); + ensureValue(minute, 0, 59, curPos); + curPos += 2; + + // parse ':' + ensureChar(dateTime, curPos, ':'); + curPos++; + + // parse second + second = parseInt(dateTime, curPos, 2); + ensureValue(second, 0, 59, curPos); + curPos += 2; + + // parse a fraction + if (dateTime.length() > curPos && dateTime.charAt(curPos) == '.') { + curPos++; + ensureDigits(dateTime, curPos, 1); + fractStr = "0."; + fractStr + += dateTime.substring(curPos, curPos + countDigits(dateTime, curPos)); + fraction = Double.parseDouble(fractStr); + curPos += countDigits(dateTime, curPos); + } + + // parse a time zone + if (dateTime.length() > curPos) { + c = dateTime.charAt(curPos); + if (c == 'Z') { + curPos++; + } else if (c == '+' || c == '-') { + // parse time zone sign + tzSign = c == '+' ? 1 : -1; + curPos++; + + // parse time zone hour + tzHour = parseInt(dateTime, curPos, 2); + ensureValue(tzHour, 0, 14, curPos); + curPos += 2; + + // parse ':' + ensureChar(dateTime, curPos, ':'); + curPos++; + + // parse time zone minute + tzMinute = parseInt(dateTime, curPos, 2); + ensureValue(tzMinute, 0, 59, curPos); + curPos += 2; + } + } else { + localTime = true; + } + + // if we have characters left, it's an error + if (dateTime.length() != curPos) { + throw new ParseException(msg.getMessage("datetime.00", null), curPos); + } + + // build the Date object + year = year * yearSign; + try { + calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT")); + calendar.set(year, month - 1, day, hour, minute, second); + calendar.set(Calendar.MILLISECOND, 0); + time = calendar.getTime().getTime(); + time += (long) (fraction * 1000.0); + time -= tzSign * ((tzHour * 60) + tzMinute) * 60 * 1000; + if (localTime) { + time -= TimeZone.getDefault().getRawOffset(); + } + return new Date(time); + } catch (IllegalArgumentException e) { + throw new ParseException(msg.getMessage("datetime.00", null), curPos); + } + + } + + /** + * Parse an integer value. + * + * @param str The String containing the digits. + * @param curPos The starting position. + * @param digits The number of digist making up the integer value. + * @return int The integer representation of the digits contained in + * str. + * @throws ParseException Parsing the integer value failed. + */ + private static int parseInt(String str, int curPos, int digits) + throws ParseException { + + ensureDigits(str, curPos, digits); + return Integer.parseInt(str.substring(curPos, curPos + digits)); + } + + /** + * Count the number of digits following curPos. + * + * @param str The String in which to count digits. + * @param curPos The starting position. + * @return int The number of digits. + */ + private static int countDigits(String str, int curPos) { + int i; + + for (i = curPos; i < str.length() && Character.isDigit(str.charAt(i)); i++); + return i - curPos; + } + + /** + * Ensure that a value falls in a given min/max range. + * + * @param value The value to check. + * @param min The minimum allowed value. + * @param max The maximum allowed value. + * @param curPos To indicate the parsing position in the + * ParseException. + * @throws ParseException Thrown, if value < min || value > + * max + */ + private static void ensureValue(int value, int min, int max, int curPos) + throws ParseException { + + if (value < min || value > max) { + throw new ParseException(msg.getMessage("datetime.00", null), curPos); + } + } + + /** + * Ensure that the given String has a number of characters left. + * + * @param str The String to check for its length. + * @param curPos The starting position. + * @param count The minimum number of characters that str must + * contain, starting at from curPos. + * @throws ParseException Thrown, if + * curPos + count > str.length(). + */ + private static void ensureChars(String str, int curPos, int count) + throws ParseException { + if (curPos + count > str.length()) { + throw new ParseException(msg.getMessage("datetime.00", null), curPos); + } + } + + /** + * Ensure that a given String contains a certain character at a + * certain position. + * + * @param str The String in which to look up the character. + * @param curPos The position in str that must contain the + * character. + * @param c The character value that must be contained at position + * curPos. + * @throws ParseException Thrown, if the characters do not match or + * curPos is out of range. + */ + private static void ensureChar(String str, int curPos, char c) + throws ParseException { + + ensureChars(str, curPos, 1); + if (str.charAt(curPos) != c) { + throw new ParseException(msg.getMessage("datetime.00", null), curPos); + } + } + + /** + * Ensure that a given String contains a number of digits, + * starting at a given position. + * + * @param str The String to scan for digits. + * @param curPos The starting postion. + * @param count The number of digits that must be contained in + * str, starting at curPos. + * @throws ParseException Thrown, if str is not long enough, or + * one of the characters following curPos in str is + * not a digit. + */ + private static void ensureDigits(String str, int curPos, int count) + throws ParseException { + + ensureChars(str, curPos, count); + for (int i = curPos; i < curPos + count; i++) { + if (!Character.isDigit(str.charAt(i))) { + throw new ParseException(msg.getMessage("datetime.00", null), curPos); + } + } + } + + /** + * Calculates the age if date of birth is given (for a calendar time stamp) + * @param dateOfBirth Date of Birth + * @param now Calendar time stamp at which the age needs to be calculated for + * @return Age of a person + */ + public static int calcAge(Calendar dateOfBirth, Calendar now) { + int age = now.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR); + + int nowM = now.get(Calendar.MONTH); + int dobM = dateOfBirth.get(Calendar.MONTH); + int nowDOM = now.get(Calendar.DAY_OF_MONTH); + int dobDOM = dateOfBirth.get(Calendar.DAY_OF_MONTH); + + if ((nowM < dobM) || ((nowM == dobM) && (nowDOM < dobDOM))) { + age--; + } + + if (age < 0) { + throw new IllegalArgumentException("Calculated age results in negative value."); + } + return age; + } + + /** + * Calculates the age if date of birth is given as Calendar object + * @param dateOfBirth Date of Birth as Calendar object + * @return Age of a person + */ + public static int calcAge(Calendar dateOfBirth) { + return calcAge(dateOfBirth, Calendar.getInstance()); + } + + /** + * Calculates the age if date of birth is given (for a date time stamp) + * @param dateOfBirth Date of Birth + * @param now Date time stamp at which the age needs to be calculated for + * @return Age of a person + */ + public static int calcAge(Date dateOfBirth, Date now) { + Calendar dob = Calendar.getInstance(); + dob.setTime(dateOfBirth); + Calendar nowCal = Calendar.getInstance(); + nowCal.setTime(now); + return calcAge(dob, nowCal); + } + + /** + * Calculates the age if date of birth is given as Date object + * @param dateOfBirth Date of Birth as Date object + * @return Age of a person + */ + public static int calcAge(Date dateOfBirth) { + return calcAge(dateOfBirth, new Date()); + } + + public static String formatPEPSDateToMOADate(String pepsDate) { + + if (StringUtils.isEmpty(pepsDate)) { + return null; + } + + DateTimeFormatter fmt = null; + + switch (pepsDate.length()) { + case 4: + fmt = DateTimeFormat.forPattern("yyyy"); + break; + case 6: + fmt = DateTimeFormat.forPattern("yyyyMM"); + break; + case 8: + fmt = DateTimeFormat.forPattern("yyyyMMdd"); + break; + default: + fmt = DateTimeFormat.forPattern("yyyy-MM-dd"); + break; + } + + DateTime dt = fmt.parseDateTime(pepsDate); + DateTimeFormatter fmt2 = DateTimeFormat.forPattern("yyyy-MM-dd"); + return fmt2.print(dt); + + } + + /** + * Returns a date as String using a provided format + * @param format Format the date/time should be returned + * @return Date/Time as String formatted according the provided format + */ + public static String getDateTimeWithFormat(String format) { + DateFormat dateFormat = new SimpleDateFormat(format); + Date date = new Date(); + return dateFormat.format(date); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Empty.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Empty.java new file mode 100644 index 000000000..533b39b6b --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Empty.java @@ -0,0 +1,31 @@ +/* + * Copyright 2011 Federal Chancellery Austria and + * Graz University of Technology + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package at.gv.egovernment.moa.util; + +/** + * @author Thomas Knall + */ +public interface Empty { + + /** + * Returns {@code true} if underlying object is empty. + * + * @return {@code true} if empty, {@code false} if not empty. + */ + boolean isEmpty(); + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/EntityResolverChain.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/EntityResolverChain.java new file mode 100644 index 000000000..7213d036b --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/EntityResolverChain.java @@ -0,0 +1,76 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * Implementation of the org.xml.sax.EntityResolver, + * for use by a org.apache.xerces.parsers.DOMParser. + * + * @author Patrick Peck + * @version $Id$ + */ +public class EntityResolverChain implements EntityResolver { + /** The EntityResolvers in the chain. */ + private List resolvers = new ArrayList(); + + /** + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) + */ + public InputSource resolveEntity(String publicId, String systemId) + throws SAXException, IOException { + + Iterator iter; + + for (iter = resolvers.iterator(); iter.hasNext(); ) { + EntityResolver resolver = (EntityResolver) iter.next(); + InputSource is = resolver.resolveEntity(publicId, systemId); + + if (is != null) { + return is; + } + } + + return null; + } + + /** + * Add an EntityResolver to the chain. + * + * @param entityResolver The EntityResolver to add. + */ + public void addEntityResolver(EntityResolver entityResolver) { + resolvers.add(entityResolver); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/FileUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/FileUtils.java new file mode 100644 index 000000000..a70d62e1e --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/FileUtils.java @@ -0,0 +1,179 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; + +/** + * Utility for accessing files on the file system, and for reading from input streams. + * @author Paul Ivancsics + * @version $Id$ + */ +public class FileUtils { + + /** + * Reads a file, given by URL, into a byte array. + * @param urlString file URL + * @return file content + * @throws IOException on any exception thrown + */ + public static byte[] readURL(String urlString) throws IOException { + URL url = new URL(urlString); + InputStream in = new BufferedInputStream(url.openStream()); + byte[] content = StreamUtils.readStream(in); + in.close(); + return content; + } + /** + * Reads a file, given by URL, into a String. + * @param urlString file URL + * @param encoding character encoding + * @return file content + * @throws IOException on any exception thrown + */ + public static String readURL(String urlString, String encoding) throws IOException { + byte[] content = readURL(urlString); + return new String(content, encoding); + } + /** + * Reads a file, given by filename, into a byte array. + * @param filename filename + * @return file content + * @throws IOException on any exception thrown + */ + public static byte[] readFile(String filename) throws IOException { + BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename)); + byte[] content = StreamUtils.readStream(in); + in.close(); + return content; + } + /** + * Reads a file, given by filename, into a String. + * @param filename filename + * @param encoding character encoding + * @return file content + * @throws IOException on any exception thrown + */ + public static String readFile(String filename, String encoding) throws IOException { + byte[] content = readFile(filename); + return new String(content, encoding); + } + /** + * Reads a file from a resource. + * @param name resource name + * @return file content as a byte array + * @throws IOException on any exception thrown + */ + public static byte[] readResource(String name) throws IOException { + ClassLoader cl = FileUtils.class.getClassLoader(); + BufferedInputStream in = new BufferedInputStream(cl.getResourceAsStream(name)); + byte[] content = StreamUtils.readStream(in); + in.close(); + return content; + } + /** + * Reads a file from a resource. + * @param name filename + * @param encoding character encoding + * @return file content + * @throws IOException on any exception thrown + */ + public static String readResource(String name, String encoding) throws IOException { + byte[] content = readResource(name); + return new String(content, encoding); + } + + /** + * Returns the absolute URL of a given url which is relative to the parameter root + * @param url + * @param root + * @return String + */ + public static String makeAbsoluteURL(String url, String root) { + //if url is relative to rootConfigFileDirName make it absolute + + File keyFile; + String newURL = url; + + if(null == url) return null; + + if (url.startsWith("http:/") || url.startsWith("https:/") || url.startsWith("file:/") || url.startsWith("ftp:/")) { + return url; + } else { + // check if absolute - if not make it absolute + keyFile = new File(url); + if (!keyFile.isAbsolute()) { + keyFile = new File(root, url); + + if (keyFile.toString().startsWith("file:")) + newURL = keyFile.toString(); + + else + newURL = keyFile.toURI().toString(); + + } + return newURL; + } + } + + + private static void copy( InputStream fis, OutputStream fos ) + { + try + { + byte[] buffer = new byte[ 0xFFFF ]; + for ( int len; (len = fis.read(buffer)) != -1; ) + fos.write( buffer, 0, len ); + } + catch( IOException e ) { + System.err.println( e ); + } + finally { + if ( fis != null ) + try { fis.close(); } catch ( IOException e ) { e.printStackTrace(); } + if ( fos != null ) + try { fos.close(); } catch ( IOException e ) { e.printStackTrace(); } + } + } + + public static void copyFile(File src, File dest) + { + try + { + copy( new FileInputStream( src ), new FileOutputStream( dest ) ); + } + catch( IOException e ) { + e.printStackTrace(); + } + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/KeyStoreUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/KeyStoreUtils.java new file mode 100644 index 000000000..3d28f4f2b --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/KeyStoreUtils.java @@ -0,0 +1,223 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import iaik.x509.X509Certificate; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.cert.Certificate; + +/** + * Utility for creating and loading key stores. + * + * @author Paul Ivancsics + * @version $Id$ + */ +public class KeyStoreUtils { + + /** + * JAVA KeyStore + */ + private static final String KEYSTORE_TYPE_JKS = "JKS"; + + /** + * PKCS12 KeyStore + */ + private static final String KEYSTORE_TYPE_PKCS12 = "PKCS12"; + + + + /** + * Loads a key store from file. + * + * @param keystoreType key store type + * @param urlString URL of key store + * @param password password protecting the key store + * @return key store loaded + * @throws IOException thrown while reading the key store from file + * @throws GeneralSecurityException thrown while creating the key store + */ + public static KeyStore loadKeyStore( + String keystoreType, + String urlString, + String password) + throws IOException, GeneralSecurityException { + + URL keystoreURL = new URL(urlString); + InputStream in = keystoreURL.openStream(); + return loadKeyStore(keystoreType, in, password); + } + /** + * Loads a key store from an InputStream, and + * closes the InputStream. + * + * @param keystoreType key store type + * @param in input stream + * @param password password protecting the key store + * @return key store loaded + * @throws IOException thrown while reading the key store from the stream + * @throws GeneralSecurityException thrown while creating the key store + */ + public static KeyStore loadKeyStore( + String keystoreType, + InputStream in, + String password) + throws IOException, GeneralSecurityException { + + char[] chPassword = null; + if (password != null) + chPassword = password.toCharArray(); + KeyStore ks = KeyStore.getInstance(keystoreType); + ks.load(in, chPassword); + in.close(); + return ks; + } + /** + * Creates a key store from X509 certificate files, aliasing them with + * the index in the String[], starting with "0". + * + * @param keyStoreType key store type + * @param certFilenames certificate filenames + * @return key store created + * @throws IOException thrown while reading the certificates from file + * @throws GeneralSecurityException thrown while creating the key store + */ + public static KeyStore createKeyStore( + String keyStoreType, + String[] certFilenames) + throws IOException, GeneralSecurityException { + + KeyStore ks = KeyStore.getInstance(keyStoreType); + ks.load(null, null); + for (int i = 0; i < certFilenames.length; i++) { + Certificate cert = loadCertificate(certFilenames[i]); + ks.setCertificateEntry("" + i, cert); + } + return ks; + } + /** + * Creates a key store from a directory containg X509 certificate files, + * aliasing them with the index in the String[], starting with "0". + * All the files in the directory are considered to be certificates. + * + * @param keyStoreType key store type + * @param certDirURLString file URL of directory containing certificate filenames + * @return key store created + * @throws IOException thrown while reading the certificates from file + * @throws GeneralSecurityException thrown while creating the key store + */ + public static KeyStore createKeyStoreFromCertificateDirectory( + String keyStoreType, + String certDirURLString) + throws IOException, GeneralSecurityException { + + URL certDirURL = new URL(certDirURLString); + String certDirname = certDirURL.getFile(); + File certDir = new File(certDirname); + String[] certFilenames = certDir.list(); + String separator = + (certDirname.endsWith(File.separator) ? "" : File.separator); + for (int i = 0; i < certFilenames.length; i++) { + certFilenames[i] = certDirname + separator + certFilenames[i]; + } + return createKeyStore(keyStoreType, certFilenames); + } + + /** + * Loads an X509 certificate from file. + * @param certFilename filename + * @return the certificate loaded + * @throws IOException thrown while reading the certificate from file + * @throws GeneralSecurityException thrown while creating the certificate + */ + private static Certificate loadCertificate(String certFilename) + throws IOException, GeneralSecurityException { + + FileInputStream in = new FileInputStream(certFilename); + Certificate cert = new X509Certificate(in); + in.close(); + return cert; + } + + + /** + * Loads a keyStore without knowing the keyStore type + * @param keyStorePath URL to the keyStore + * @param password Password protecting the keyStore + * @return keyStore loaded + * @throws KeyStoreException thrown if keyStore cannot be loaded + * @throws FileNotFoundException + * @throws IOException + */ + public static KeyStore loadKeyStore(String keyStorePath, String password) throws KeyStoreException, IOException{ + + //InputStream is = new FileInputStream(keyStorePath); + URL keystoreURL = new URL(keyStorePath); + InputStream in = keystoreURL.openStream(); + InputStream isBuffered = new BufferedInputStream(in); + return loadKeyStore(isBuffered, password); + + } + + /** + * Loads a keyStore without knowing the keyStore type + * @param in input stream + * @param password Password protecting the keyStore + * @return keyStore loaded + * @throws KeyStoreException thrown if keyStore cannot be loaded + * @throws FileNotFoundException + * @throws IOException + */ +public static KeyStore loadKeyStore(InputStream is, String password) throws KeyStoreException, IOException{ + is.mark(1024*1024); + KeyStore ks = null; + try { + try { + ks = loadKeyStore(KEYSTORE_TYPE_PKCS12, is, password); + } catch (IOException e2) { + is.reset(); + ks = loadKeyStore(KEYSTORE_TYPE_JKS, is, password); + } + } catch(Exception e) { + e.printStackTrace(); + //throw new KeyStoreException(e); + } + return ks; + + } + + + + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOADefaultHandler.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOADefaultHandler.java new file mode 100644 index 000000000..7a79bd9e5 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOADefaultHandler.java @@ -0,0 +1,106 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.IOException; + +import org.xml.sax.EntityResolver; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * A DefaultHandler that uses a MOAEntityResolver and + * a MOAErrorHandler. + * + * @author Patrick Peck + * @version $Id$ + */ +public class MOADefaultHandler extends DefaultHandler { + /** The EntityResolver to use. */ + private EntityResolver entityResolver; + /** The ErrorHandler to use. */ + private ErrorHandler errorHandler; + + /** + * Create a new MOADefaultHandler. + */ + public MOADefaultHandler() { + entityResolver = new MOAEntityResolver(); + errorHandler = new MOAErrorHandler(); + } + + /** + * Create a new MOADefaultHandler. + * + * @param entityResolver The EntityResolver to use for resolving + * external entities. + * @param errorHandler The ErrorHandler to use for reporting + * parsing errors. + */ + public MOADefaultHandler( + EntityResolver entityResolver, + ErrorHandler errorHandler) { + + this.entityResolver = entityResolver; + this.errorHandler = errorHandler; + } + + /** + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) + */ + public InputSource resolveEntity(String publicId, String systemId) + throws SAXException { + try { + return entityResolver.resolveEntity(publicId, systemId); + } catch (IOException e) { + return null; + } + } + + /** + * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) + */ + public void warning(SAXParseException exception) throws SAXException { + errorHandler.warning(exception); + } + + /** + * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) + */ + public void error(SAXParseException exception) throws SAXException { + errorHandler.error(exception); + } + + /** + * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) + */ + public void fatalError(SAXParseException exception) throws SAXException { + errorHandler.fatalError(exception); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOAEntityResolver.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOAEntityResolver.java new file mode 100644 index 000000000..8f3ffd4c6 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOAEntityResolver.java @@ -0,0 +1,129 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.InputStream; + +import org.apache.xerces.util.URI; +import org.apache.xerces.util.URI.MalformedURIException; +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; + +import at.gv.egovernment.moa.logging.LogMsg; +import at.gv.egovernment.moa.logging.Logger; + +/** + * An EntityResolver that looks up entities stored as + * local resources. + * + *

The following DTDs are mapped to local resources: + *

    + *
  • The XMLSchema.dtd
  • + *
  • The datatypes.dtd
  • + *
+ *

+ *

For all other resources, an attempt is made to resolve them as resources, + * either absolute or relative to Constants.SCHEMA_ROOT. + * + * @author Patrick Peck + * @author Sven Aigner + */ +public class MOAEntityResolver implements EntityResolver { + + /** + * Resolve an entity. + * + * The systemId parameter is used to perform the lookup of the + * entity as a resource, either by interpreting the systemId as + * an absolute resource path, or by appending the last path component of + * systemId to Constants.SCHEMA_ROOT. + * + * @param publicId The public ID of the resource. + * @param systemId The system ID of the resource. + * @return An InputSource from which the entity can be read, or + * null, if the entity could not be found. + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) + */ + public InputSource resolveEntity(String publicId, String systemId) { + InputStream stream; + int slashPos; + + if (Logger.isDebugEnabled()) { + Logger.debug( + new LogMsg("resolveEntity: p=" + publicId + " s=" + systemId)); + } + + if (publicId != null) { + // check if we can resolve some standard dtd's + if (publicId.equalsIgnoreCase("-//W3C//DTD XMLSchema 200102//EN")) { + return new InputSource( + getClass().getResourceAsStream( + Constants.SCHEMA_ROOT + "XMLSchema.dtd")); + } else if (publicId.equalsIgnoreCase("datatypes")) { + return new InputSource( + getClass().getResourceAsStream( + Constants.SCHEMA_ROOT + "datatypes.dtd")); + } + } else if (systemId != null) { + // get the URI path + try { + URI uri = new URI(systemId); + systemId = uri.getPath(); + + if (!"file".equals(uri.getScheme()) || "".equals(systemId.trim())) { + return null; + } + + } catch (MalformedURIException e) { + return null; + } + + // try to get the resource from the full path + stream = getClass().getResourceAsStream(systemId); + if (stream != null) { + InputSource source = new InputSource(stream); + + source.setSystemId(systemId); + return source; + } + + // try to get the resource from the last path component + slashPos = systemId.lastIndexOf('/'); + if (slashPos >= 0 && systemId.length() > slashPos) { + systemId = systemId.substring(slashPos + 1, systemId.length()); + stream = + getClass().getResourceAsStream(Constants.SCHEMA_ROOT + systemId); + if (stream != null) { + InputSource source = new InputSource(stream); + + source.setSystemId(systemId); + return source; + } + } + } + + return null; // nothing found - let the parser handle the entity + } +} \ No newline at end of file diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOAErrorHandler.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOAErrorHandler.java new file mode 100644 index 000000000..3769b264d --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOAErrorHandler.java @@ -0,0 +1,115 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import org.apache.xml.utils.DefaultErrorHandler; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +import at.gv.egovernment.moa.logging.LogMsg; +import at.gv.egovernment.moa.logging.Logger; + +/** + * An ErrorHandler that logs a message and throws a + * SAXException upon error and fatal + * parsing errors. + * + * @author Patrick Peck + * @author Sven Aigner + */ +public class MOAErrorHandler extends DefaultErrorHandler { + + + /** + * Logs a warning message. + * + * @see org.xml.sax.ErrorHandler#warning(SAXParseException) + */ + public void warning(SAXParseException exception) throws SAXException { + warn("parser.00", messageParams(exception), null); + } + + /** + * Logs a warning and rethrows the exception. + * + * @see org.xml.sax.ErrorHandler#error(SAXParseException) + */ + public void error(SAXParseException exception) throws SAXException { + warn("parser.01", messageParams(exception), null); + + // if Target attribute is missing in QualifyingProperties - don't throw exception (bug fix for old MOCCA signatures) + if (exception.getMessage().startsWith("cvc-complex-type.4: Attribute 'Target' must appear on element")) + warn("parser.04", new Object[] {"Attribute 'Target' must appear on element 'QualifyingProperties' - ignored for compatibility reasons."}, null); + else + throw exception; + } + + /** + * Logs a warning and rethrows the exception. + * + * @see org.xml.sax.ErrorHandler#fatalError(SAXParseException) + */ + public void fatalError(SAXParseException exception) throws SAXException { + warn("parser.02", messageParams(exception), null); + throw exception; + } + + /** + * Log a warning message. + * + * @param messageId The message ID to log. + * @param parameters Additional message parameters. + * @param t The Throwable to log; usually the cause of this + * warning. + */ + private static void warn( + String messageId, + Object[] parameters, + Throwable t) { + + MessageProvider msg = MessageProvider.getInstance(); + Logger.warn(new LogMsg(msg.getMessage(messageId, parameters)), t); + } + + /** + * Put the system id, line and column number information from the exception + * into an Object array, to provide it as a + * MessageFormat parameter. + * + * @param e The SAXParseException containing the + * source system id and line/column numbers. + * @return An array containing the system id (a String) as well + * as line/column numbers (2 Integer objects) from the + * SAXParseException. + */ + private static Object[] messageParams(SAXParseException e) { + return new Object[] { + e.getMessage(), + e.getSystemId(), + new Integer(e.getLineNumber()), + new Integer(e.getColumnNumber())}; + } + +} \ No newline at end of file diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOATimer.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOATimer.java new file mode 100644 index 000000000..acc380d1d --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MOATimer.java @@ -0,0 +1,134 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.util.Map; +import java.util.WeakHashMap; + +/** + * A timer utility for named timers. + * + * @author Sven Aigner + */ +public class MOATimer { + + /** The single instance of this class. */ + private static MOATimer instance = null; + /** The starting points of single timings. */ + private static Map timemapstart = new WeakHashMap(); + /** The end points of single timings. */ + private static Map timemapend = new WeakHashMap(); + + /** + * Return the single instance of this class. + * + * @return The single instance of this class. + */ + public static MOATimer getInstance() { + if (instance == null) { + instance = new MOATimer(); + } + return instance; + } + + /** + * Create a new MOATimer. + * + * Protected to disallow multiple instances. + */ + protected MOATimer() { + super(); + } + + /** + * Start timing a certain action. + * + * The timing belonging to the action ID is garbage collected as soon as there + * exists no other reference to the action ID. + * + * @param id The action ID. + */ + public void startTiming(Object id) { + timemapstart.put(id, new Long(System.currentTimeMillis())); + } + + /** + * Stop timing an action. + * + * @param id The action ID. + */ + public void stopTiming(Object id) { + timemapend.put(id, new Long(System.currentTimeMillis())); + } + + /** + * Get the duration of an action. + * + * @param id The action ID for which to compute the duration. + * @return long The duration in milliseconds between calls to + * startTiming() and stopTiming(). If + * only startTiming() has been called for the action, then + * current difference to the system time is returned. If no timing exists for + * the action, - 1 is returned. + */ + public long duration(Object id) { + if (timemapstart.containsKey(id)) { + long start = ((Long) timemapstart.get(id)).longValue(); + if (timemapend.containsKey(id)) { + long end = ((Long) timemapend.get(id)).longValue(); + return end - start; + } else { + return System.currentTimeMillis() - start; + } + } else + return -1; + } + + /** + * Get the duration of an action, as a nicely formatted String. + * + * @param id The action ID. + * @return String The duration() as a String. + */ + public String durationAsString(Object id) { + long dur = duration(id); + long second = dur / 1000; + long mil = (dur) - (second * 1000); + return "Duration: " + second + "." + mil + " seconds"; + } + + /** + * Remove a timing. + * + * @param id The action ID. + */ + public void clearTiming(String id) { + if (timemapstart.containsKey(id)) + timemapstart.remove(id); + if (timemapend.containsKey(id)) + timemapend.remove(id); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MessageProvider.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MessageProvider.java new file mode 100644 index 000000000..1623ff1b3 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MessageProvider.java @@ -0,0 +1,87 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.util.Locale; + +/** + * A singleton wrapper around a Message object. + * + * Provides the messages used in the common project. + * + * @author Patrick Peck + * @version $Id$ + */ +public class MessageProvider { + /** The location of the default message resources. */ + private static final String[] DEFAULT_MESSAGE_RESOURCES = + { "resources/properties/common_messages" }; + /** The locale of the default message resources. */ + private static final Locale[] DEFAULT_MESSAGE_LOCALES = + new Locale[] { new Locale("de", "AT") }; + /** The single instance of this class. */ + private static MessageProvider instance; + + /** The messages provided by this MessageProvider. */ + private Messages messages; + + /** + * Return the single instance of the MessageProvider. + * + * Intialilizes the MessageProvider with the default message + * locations: /resources/properties/common_messages. + * + * @return The single MessageProvider. + */ + public static synchronized MessageProvider getInstance() { + if (instance == null) { + instance = + new MessageProvider(DEFAULT_MESSAGE_RESOURCES, DEFAULT_MESSAGE_LOCALES); + } + return instance; + } + + /** + * Create a MessageProvider. + * + * @param resourceNames The names of the resources containing the messages. + * @param locales The corresponding locales. + */ + protected MessageProvider(String[] resourceNames, Locale[] locales) { + this.messages = new Messages(resourceNames, locales); + } + + /** + * Get the message corresponding to a given message ID. + * + * @param messageId The ID of the message. + * @param parameters The parameters to fill in into the message arguments. + * @return The formatted message. + */ + public String getMessage(String messageId, Object[] parameters) { + return messages.getMessage(messageId, parameters); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Messages.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Messages.java new file mode 100644 index 000000000..20de46b43 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Messages.java @@ -0,0 +1,141 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.text.MessageFormat; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.PropertyResourceBundle; + +import at.gv.egovernment.moa.logging.Logger; + +/** + * Provides access to the system messages resource used for exception handling + * and logging messages. + * + * Messages must be provided as a resource bundle at the path. + * + * @author Patrick Peck + * @version $Id$ + */ +public class Messages { + /** Error message indicating that no messages are avaiable. */ + private static final String ERROR_MESSAGES_UNAVAILABLE = + "Fehler in der Server-Konfiguration. " + + "Die Fehlertexte konnten nicht geladen werden."; + /** Error message indicating that the message is not available. */ + private static final String ERROR_NO_MESSAGE = + "No errormesseage for error with number.={0}"; + + /** The names of the resources containing the messages. */ + private String[] resourceNames; + /** The corresponding Locales of the resources. */ + private Locale[] locales; + /** The ResourceBundles containing the messages. */ + private ResourceBundleChain messages; + + /** + * Create a new Message object containing the messages + * in the given resources. + * + * @param resourceNames The names of the resources containing the messages. + * @param locales The corresponding locales. + */ + public Messages(String[] resourceNames, Locale[] locales) { + this.resourceNames = resourceNames; + this.locales = locales; + this.messages = null; + } + + /** + * Get the message corresponding to a given message ID. + * + * @param messageId The ID of the message. + * @param parameters The parameters to fill in into the message arguments. + * @return The formatted message. + */ + public String getMessage(String messageId, Object[] parameters) { + // initialize messages + if (messages == null) { + initMessages(); + } + + // create the message + if (messages == null) { + return ERROR_MESSAGES_UNAVAILABLE; + } else { + try { + String rawMessage = messages.getString(messageId); + return MessageFormat.format(rawMessage, parameters); + } catch (MissingResourceException e2) { + // couldn't find any message -> set to default error message + return MessageFormat.format( + ERROR_NO_MESSAGE, + new Object[] { messageId }); + } + } + } + + /** + * Return the names of the resources containing the messages. + * + * @return String[] The names of the resource bundles containing the messages. + */ + private String[] getResourceNames() { + return resourceNames; + } + + /** + * Return the Locales of the resources containing the messages. + * + * @return Locale[] The Locales of the resource bundles + * containing the messages. + */ + private Locale[] getLocales() { + return locales; + } + + /** + * Initialize the messages ResourceBundle containing + * the MOA error messages. + */ + private void initMessages() { + messages = new ResourceBundleChain(); + int i; + + // initialize the message resources + for (i = 0; i < resourceNames.length; i++) { + try { + messages.addResourceBundle( + PropertyResourceBundle.getBundle( + getResourceNames()[i], + getLocales()[i])); + } catch (MissingResourceException e) { + Logger.error(ERROR_MESSAGES_UNAVAILABLE, e); + } + } + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MiscUtil.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MiscUtil.java new file mode 100644 index 000000000..246b0eb31 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/MiscUtil.java @@ -0,0 +1,315 @@ +/* + * Copyright 2011 Federal Chancellery Austria and + * Graz University of Technology + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package at.gv.egovernment.moa.util; + +import iaik.logging.Log; +import iaik.logging.LogFactory; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.InvocationTargetException; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Collection; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Iterator; +import java.util.Properties; + +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.ex.EgovUtilException; + + + +/** + * Class providing several utility methods. + * + * @author Arne Tauber + * + */ +public class MiscUtil { + + public static final String DEFAULT_SLASH = "/"; + + private static final int IO_BUFFER_SIZE = 4 * 1024; + + public static void copyStream(InputStream is, OutputStream os) throws IOException { + byte[] b = new byte[IO_BUFFER_SIZE]; + int read; + while ((read = is.read(b)) != -1) { + os.write(b, 0, read); + } + } + + public static void assertNotNull(Object param, String name) { + if (param == null) { + throw new NullPointerException(name + " must not be null."); + } + } + + public static boolean areAllNull(Object... objects) { + for (Object o : objects) { + if (o != null) { + return false; + } + } + return true; + } + + public static String extractContentType(String contentTypeString) { + if (contentTypeString == null) { + return ""; + } + if (contentTypeString.indexOf(";") != -1) { + return contentTypeString.substring(0, contentTypeString.indexOf(";")); + } + return contentTypeString; + } + + public static XMLGregorianCalendar getXMLGregorianCalendar(Date date) + throws DatatypeConfigurationException { + GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); + cal.setTime(date); + return DatatypeFactory.newInstance().newXMLGregorianCalendar(cal); + } + + public static XMLGregorianCalendar getXMLGregorianCalendar(String str) + throws DatatypeConfigurationException { + return DatatypeFactory.newInstance().newXMLGregorianCalendar(str); + } + + public static X509Certificate readCertificate(InputStream certStream) + throws CertificateException { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + return (X509Certificate) cf.generateCertificate(certStream); + } + + public static boolean isEmpty(String str) { + return str == null || "".equals(str); + } + + public static boolean isNotEmpty(String str) { + return str != null && !"".equals(str); + } + + public static byte[] sourceToByteArray(Source result) + throws TransformerException { + TransformerFactory factory = TransformerFactory.newInstance(); + Transformer transformer = factory.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + StreamResult streamResult = new StreamResult(); + streamResult.setOutputStream(out); + transformer.transform(result, streamResult); + return out.toByteArray(); + } + +// public static Document parseDocument(InputStream inputStream) +// throws IOException { +// try { +// DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory +// .newInstance(); +// docBuilderFactory.setNamespaceAware(true); +// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); +// return docBuilder.parse(inputStream); +// } catch (ParserConfigurationException e) { +// throw new IOException(e); +// } catch (SAXException e) { +// throw new IOException(e); +// } +// } + + public static String removePrecedingSlash(String path, String slash) { + assertNotEmpty(slash, "Shash"); + if (!isEmpty(path)) { + while (path.startsWith(slash)) { + path = path.substring(slash.length(), path.length()); + } + } + return path; + } + + public static String removePrecedingSlash(String path) { + return removePrecedingSlash(path, DEFAULT_SLASH); + } + + public static void assertNotEmpty(String param, String name) { + if (param == null) { + throw new NullPointerException(name + " must not be null."); + } + if (param.length() == 0) { + throw new IllegalArgumentException(name + " must not be empty."); + } + } + + @SuppressWarnings("rawtypes") + public static boolean isEmpty(Properties props) { + if (props == null || props.isEmpty()) { + return true; + } + Iterator it = props.values().iterator(); + while (it.hasNext()) { + if (MiscUtil.isNotEmpty((String) it.next())) { + return false; + } + } + return true; + } + + public static boolean isEmpty(Empty empty) { + return empty == null || empty.isEmpty(); + } + + public static boolean isNotEmpty(Empty empty) { + return !isEmpty(empty); + } + + public static boolean isEmpty(byte[] data) { + return data == null || data.length == 0; + } + + public static boolean isNotEmpty(byte[] data) { + return !isEmpty(data); + } + + public static boolean isEmpty(Collection c) { + return c == null || c.isEmpty(); + } + + public static boolean isNotEmpty(Collection c) { + return !isEmpty(c); + } + + public static boolean areAllEmpty(String... strings) { + for (String s : strings) { + if (s != null && s.trim().length() != 0) { + return false; + } + } + return true; + } + + public static boolean areAllEmpty(Empty... empties) { + if (empties != null) { + for (Empty e : empties) { + if (e != null && !e.isEmpty()) { + return false; + } + } + } + return true; + } + + public static void assertNotEmpty(T[] param, String name) { + if (param == null) { + throw new NullPointerException(name + " must not be null."); + } + if (param.length == 0) { + throw new IllegalArgumentException(name + " must not be empty."); + } + } + + public static void assertNotEmpty(Empty empty, String name) { + if (empty == null) { + throw new NullPointerException(name + " must not be null."); + } + if (empty.isEmpty()) { + throw new IllegalArgumentException(name + " must not be empty."); + } + } + + public static void assertNotEmpty(byte[] param, String name) { + if (param == null) { + throw new NullPointerException(name + " must not be null."); + } + if (param.length == 0) { + throw new IllegalArgumentException(name + " must not be empty."); + } + } + + public static Date parseXMLDate(String xmlDate) throws EgovUtilException { + if (xmlDate == null) { + return null; + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + return sdf.parse(xmlDate); + } catch (ParseException e) { + throw new EgovUtilException(e); + } + } + + public static boolean isEmpty(T[] array) { + return array == null || array.length == 0; + } + + public static boolean isNotEmpty(T[] array) { + return !isEmpty(array); + } + + public static String convertDateFromStandardToXML(String dateString) { + MiscUtil.assertNotNull(dateString, "dateString"); + Date date = parseDate(dateString); + return formatDate(date, "yyyy-MM-dd"); + } + + public static Date parseDate(String dateString) { + return parseDate(dateString, "dd.MM.yyyy"); + } + + public static Date parseDate(String dateString, String pattern) { + MiscUtil.assertNotNull(dateString, "dateString"); + MiscUtil.assertNotNull(pattern, "pattern"); + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + try { + return sdf.parse(dateString); + } catch (ParseException e) { + Logger.warn("Error parsing date.", e); + return null; + } + } + + public static String formatDate(Date date, String format) { + SimpleDateFormat sdf = new SimpleDateFormat(format); + return sdf.format(date); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeIteratorAdapter.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeIteratorAdapter.java new file mode 100644 index 000000000..fdc823229 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeIteratorAdapter.java @@ -0,0 +1,111 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.util.ListIterator; + +import org.w3c.dom.DOMException; +import org.w3c.dom.Node; +import org.w3c.dom.traversal.NodeFilter; +import org.w3c.dom.traversal.NodeIterator; + +/** + * A NodeIterator implementation based on a + * ListIterator. + * + * @see java.util.ListIterator + * @see org.w3c.dom.traversal.NodeIterator + * + * @author Patrick Peck + * @version $Id$ + */ +public class NodeIteratorAdapter implements NodeIterator { + + /** The ListIterator to wrap. */ + private ListIterator nodeIterator; + + /** + * Create a new NodeIteratorAdapter. + * @param nodeIterator The ListIterator to iterate over. + */ + public NodeIteratorAdapter(ListIterator nodeIterator) { + this.nodeIterator = nodeIterator; + } + + /** + * @see org.w3c.dom.traversal.NodeIterator#getRoot() + */ + public Node getRoot() { + return null; + } + + /** + * @see org.w3c.dom.traversal.NodeIterator#getWhatToShow() + */ + public int getWhatToShow() { + return NodeFilter.SHOW_ALL; + } + + /** + * @see org.w3c.dom.traversal.NodeIterator#getFilter() + */ + public NodeFilter getFilter() { + return null; + } + + /** + * @see org.w3c.dom.traversal.NodeIterator#getExpandEntityReferences() + */ + public boolean getExpandEntityReferences() { + return false; + } + + /** + * @see org.w3c.dom.traversal.NodeIterator#nextNode() + */ + public Node nextNode() throws DOMException { + if (nodeIterator.hasNext()) { + return (Node) nodeIterator.next(); + } + return null; + } + + /** + * @see org.w3c.dom.traversal.NodeIterator#previousNode() + */ + public Node previousNode() throws DOMException { + if (nodeIterator.hasPrevious()) { + return (Node) nodeIterator.previous(); + } + return null; + } + + /** + * @see org.w3c.dom.traversal.NodeIterator#detach() + */ + public void detach() { + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeListAdapter.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeListAdapter.java new file mode 100644 index 000000000..e39cc0291 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/NodeListAdapter.java @@ -0,0 +1,68 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.util.List; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * A NodeList implementation based on a List. + * + * @see java.util.List + * @see org.w3c.dom.NodeList + * + * @author Patrick Peck + * @version $Id$ + */ +public class NodeListAdapter implements NodeList { + /** The List to wrap. */ + private List nodeList; + + /** + * Create a new NodeListAdapter. + * + * @param nodeList The List containing the nodes. + */ + public NodeListAdapter(List nodeList) { + this.nodeList = nodeList; + } + + /** + * @see org.w3c.dom.NodeList#item(int) + */ + public Node item(int index) { + return (Node) nodeList.get(index); + } + + /** + * @see org.w3c.dom.NodeList#getLength() + */ + public int getLength() { + return nodeList.size(); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/OutputXML2File.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/OutputXML2File.java new file mode 100644 index 000000000..e3f8f75a1 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/OutputXML2File.java @@ -0,0 +1,102 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +/* + * Created on 26.04.2004 + * + * @author rschamberger + * $ID$ + */ +package at.gv.egovernment.moa.util; + +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.logging.Logger; + +/** + * utility functions to write XML data to files + * @author rschamberger + * @version $Id$ + */ +public class OutputXML2File { + + /** + * writes an XML structure to file if debug is enabled in hierarchy (Encoding: UTF-8) + * + * @param filename file name + * @param rootElem root element in DOM tree + * @param hierarchy of the Logger + */ + public static void debugOutputXML2File(String filename, Element rootElem, String hierarchy) { + if (Logger.isDebugEnabled(hierarchy)) { + outputXML2File(filename, rootElem); + } + } + + /** + * writes an XML structure to file if debug is enabled in hierarchy (Encoding: UTF-8) + * + * @param filename file name + * @param xmlString XML string + * @param hierarchy of the Logger + */ + public static void debugOutputXML2File(String filename, String xmlString, String hierarchy) { + if (Logger.isDebugEnabled(hierarchy)) { + outputXML2File(filename, xmlString); + } + } + + /** + * writes an XML structure to file (Encoding: UTF-8) + * + * @param filename file name + * @param rootElem root element in DOM tree + */ + public static void outputXML2File(String filename, Element rootElem) { + try { + String xmlString = new String(DOMUtils.serializeNode(rootElem)); + outputXML2File(filename, xmlString); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + /** + * writes an XML structure to file (Encoding: UTF-8) + * + * @param filename file name + * @param xmlString XML string + */ + public static void outputXML2File(String filename, String xmlString) { + try { + java.io.OutputStream fout = new java.io.FileOutputStream(filename); + byte[] xmlData = xmlString.getBytes("UTF-8"); + fout.write(xmlData); + fout.close(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/ResourceBundleChain.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/ResourceBundleChain.java new file mode 100644 index 000000000..234ed89df --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/ResourceBundleChain.java @@ -0,0 +1,90 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +/** + * A class to chain ResourceBundles. + * + * @author Patrick Peck + * @version $Id$ + */ +public class ResourceBundleChain { + /** Error message indicating the resource is not available. */ + private static final String ERROR_MISSING_RESOURCE = "Missing resource"; + /** The ResourceBundles contained in this chain. */ + private List resourceBundles = new ArrayList(); + + /** + * Add a ResourceBundle to the chain. + * + * @param resourceBundle The ResourceBundle to add. + */ + public void addResourceBundle(ResourceBundle resourceBundle) { + resourceBundles.add(resourceBundle); + } + + /** + * Return the value of the resource. + * + * @param key The key to access the String resource. + * @return The resource value. All the registered ResourceBundles + * are searched in the order in which they have previously been added to this + * ResourceBundleChain. + * @throws MissingResourceException The resource coult not be found in any of + * the bundles. + */ + public String getString(String key) throws MissingResourceException { + MissingResourceException lastException = null; + Iterator iter; + + // handle case where no resource bundles have been added + if (resourceBundles.size() == 0) { + throw new MissingResourceException( + ERROR_MISSING_RESOURCE, + this.getClass().getName(), + key); + } + + // try to find the resource in one of the bundles; if it cannot be found, + // return the exception thrown by the last bundle in the list + for (iter = resourceBundles.iterator(); iter.hasNext();) { + ResourceBundle resourceBundle = (ResourceBundle) iter.next(); + try { + String value = resourceBundle.getString(key); + return value; + } catch (MissingResourceException e) { + lastException = e; + } + } + throw lastException; + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/SSLUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/SSLUtils.java new file mode 100644 index 000000000..c2c67ec58 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/SSLUtils.java @@ -0,0 +1,244 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.IOException; +import java.io.InputStream; +import java.security.GeneralSecurityException; +import java.security.KeyStore; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; + +/** + * Utility for connecting to server applications via SSL. + * + * @author Paul Ivancsics + * @version $Id$ + */ +public class SSLUtils { + + /** + * Creates an SSLSocketFactory which utilizes the given trust store. + * + * @param trustStoreType key store type of trust store + * @param trustStoreInputStream input stream for reading JKS trust store containing + * trusted server certificates; if null, the default + * trust store will be utilized + * @param trustStorePassword if provided, it will be used to check + * the integrity of the trust store; if omitted, it will not be checked + * @return SSLSocketFactory to be used by an HttpsURLConnection + * @throws IOException thrown while reading from the input stream + * @throws GeneralSecurityException thrown while creating the socket factory + */ + public static SSLSocketFactory getSSLSocketFactory( + String trustStoreType, + InputStream trustStoreInputStream, + String trustStorePassword) + throws IOException, GeneralSecurityException { + + TrustManager[] tms = getTrustManagers(trustStoreType, trustStoreInputStream, trustStorePassword); + SSLContext ctx = SSLContext.getInstance("TLS"); + ctx.init(null, tms, null); + + SSLSocketFactory sf = ctx.getSocketFactory(); + return sf; + } + /** + * Creates an SSLSocketFactory which utilizes the + * given trust store and keystore. + * + * @param trustStore trust store containing trusted server certificates; + * if null, the default trust store will be utilized + * @param clientKeyStoreType key store type of clientKeyStore + * @param clientKeyStoreURL URL of key store containing keys to be used for + * client authentication; if null, the default key store will be utilized + * @param clientKeyStorePassword if provided, it will be used to check + * the integrity of the client key store; if omitted, it will not be checked + * @return SSLSocketFactory to be used by an HttpsURLConnection + * @throws IOException thrown while reading key store file + * @throws GeneralSecurityException thrown while creating the socket factory + */ + public static SSLSocketFactory getSSLSocketFactory( + KeyStore trustStore, + String clientKeyStoreType, + String clientKeyStoreURL, + String clientKeyStorePassword) + throws IOException, GeneralSecurityException { + + SSLContext ctx = getSSLContext( + trustStore, clientKeyStoreType, clientKeyStoreURL, clientKeyStorePassword); + SSLSocketFactory sf = ctx.getSocketFactory(); + return sf; + } + /** + * Creates an SSLContext initialized for the + * given trust store and keystore. + * + * @param trustStore trust store containing trusted server certificates; + * if null, the default trust store will be utilized + * @param clientKeyStoreType key store type of clientKeyStore + * @param clientKeyStoreURL URL of key store containing keys to be used for + * client authentication; if null, the default key store will be utilized + * @param clientKeyStorePassword if provided, it will be used to check + * the integrity of the client key store; if omitted, it will not be checked + * @return SSLContext to be used for creating an SSLSocketFactory + * @throws IOException thrown while reading key store file + * @throws GeneralSecurityException thrown while creating the SSL context + */ + public static SSLContext getSSLContext( + KeyStore trustStore, + String clientKeyStoreType, + String clientKeyStoreURL, + String clientKeyStorePassword) + throws IOException, GeneralSecurityException { + + TrustManager[] tms = getTrustManagers(trustStore); + KeyManager[] kms = getKeyManagers(clientKeyStoreType, clientKeyStoreURL, clientKeyStorePassword); + SSLContext ctx = SSLContext.getInstance("TLS"); + ctx.init(kms, tms, null); + return ctx; + } + /** + * Loads the trust store from an input stream and gets the + * TrustManagers from a default TrustManagerFactory, + * initialized from the given trust store. + * @param trustStoreType key store type of trust store + * @param trustStoreInputStream input stream for reading JKS trust store containing + * trusted server certificates; if null, the default + * trust store will be utilized + * @param trustStorePassword if provided, it will be used to check + * the integrity of the trust store; if omitted, it will not be checked + * @return TrustManagers to be used for creating an + * SSLSocketFactory utilizing the given trust store + * @throws IOException thrown while reading from the input stream + * @throws GeneralSecurityException thrown while initializing the + * default TrustManagerFactory + */ + protected static TrustManager[] getTrustManagers( + String trustStoreType, + InputStream trustStoreInputStream, + String trustStorePassword) + throws IOException, GeneralSecurityException { + + if (trustStoreInputStream == null) + return null; + + // Set up the TrustStore to use. We need to load the file into + // a KeyStore instance. + KeyStore trustStore = KeyStoreUtils.loadKeyStore(trustStoreType, trustStoreInputStream, trustStorePassword); + return getTrustManagers(trustStore); + } + /** + * Gets the TrustManagers from a default TrustManagerFactory, + * initialized from the given trust store. + * + * @param trustStore the trust store to use + * @return TrustManagers to be used for creating an + * SSLSocketFactory utilizing the given trust store + * @throws GeneralSecurityException thrown while initializing the + * default TrustManagerFactory + */ + protected static TrustManager[] getTrustManagers(KeyStore trustStore) + throws GeneralSecurityException { + + if (trustStore == null) + return null; + + // Initialize the default TrustManagerFactory with this KeyStore + String alg=TrustManagerFactory.getDefaultAlgorithm(); + TrustManagerFactory tmFact=TrustManagerFactory.getInstance(alg); + tmFact.init(trustStore); + + // And now get the TrustManagers + TrustManager[] tms=tmFact.getTrustManagers(); + return tms; + } + /** + * Loads the client key store from file and gets the + * KeyManagers from a default KeyManagerFactory, + * initialized from the given client key store. + * @param clientKeyStoreType key store type of clientKeyStore + * @param clientKeyStoreURL URL of key store containing keys to be used for + * client authentication; if null, the default key store will be utilized + * @param clientKeyStorePassword password used to check the integrity of the client key store; + * if null, it will not be checked + * @return KeyManagers to be used for creating an + * SSLSocketFactory utilizing the given client key store + * @throws IOException thrown while reading from the key store file + * @throws GeneralSecurityException thrown while initializing the + * default KeyManagerFactory + */ + public static KeyManager[] getKeyManagers ( + String clientKeyStoreType, + String clientKeyStoreURL, + String clientKeyStorePassword) + throws IOException, GeneralSecurityException { + + if (clientKeyStoreURL == null) + return null; + + // Set up the KeyStore to use. We need to load the file into + // a KeyStore instance. + KeyStore clientKeyStore = KeyStoreUtils.loadKeyStore( + clientKeyStoreType, clientKeyStoreURL, clientKeyStorePassword); + return getKeyManagers(clientKeyStore, clientKeyStorePassword); + } + /** + * Gets the KeyManagers from a default KeyManagerFactory, + * initialized from the given client key store. + * @param clientKeyStore client key store + * @param clientKeyStorePassword if provided, it will be used to check + * the integrity of the client key store; if omitted, it will not be checked + * @return KeyManagers to be used for creating an + * SSLSocketFactory utilizing the given client key store + * @throws GeneralSecurityException thrown while initializing the + * default KeyManagerFactory + */ + public static KeyManager[] getKeyManagers ( + KeyStore clientKeyStore, + String clientKeyStorePassword) + throws GeneralSecurityException { + + if (clientKeyStore == null) + return null; + + // Now we initialize the default KeyManagerFactory with this KeyStore + String alg=KeyManagerFactory.getDefaultAlgorithm(); + KeyManagerFactory kmFact=KeyManagerFactory.getInstance(alg); + char[] password = null; + if (clientKeyStorePassword != null) + password = clientKeyStorePassword.toCharArray(); + kmFact.init(clientKeyStore, password); + + // And now get the KeyManagers + KeyManager[] kms=kmFact.getKeyManagers(); + return kms; + } +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StreamEntityResolver.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StreamEntityResolver.java new file mode 100644 index 000000000..b3bc8ae47 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StreamEntityResolver.java @@ -0,0 +1,88 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; + +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * An EntityResolver that maps system IDs to + * InputStreams. + * + * @author Patrick Peck + * @version $Id$ + */ +public class StreamEntityResolver implements EntityResolver { + + /** A mapping from Public ID or System ID to an InputStream + * containing the entity. */ + private Map mappedEntities; + + /** + * Create a StreamEntityResolver. + * + * @param mappedEntities A mapping from public or system IDs + * (String objects) to InputStreams. + */ + public StreamEntityResolver(Map mappedEntities) { + this.mappedEntities = mappedEntities; + } + + /** + * Resolve an entity by looking it up in the mapped entities. + * + * First, the public ID is looked up in the mapping, then the system ID. + * + * @param publicId The public ID of the entity. + * @param systemId The system ID of the entity. + * @return An InputStream containing the entity or + * null if no entity could be found. + * @throws SAXException Signalling a parsing exception. + * @throws IOException Error reading the entity. + */ + public InputSource resolveEntity(String publicId, String systemId) + throws SAXException, IOException { + + InputSource src = null; + + if (publicId != null && mappedEntities.get(publicId) != null) { + src = new InputSource((InputStream) mappedEntities.get(publicId)); + } else if (systemId != null && mappedEntities.get(systemId) != null) { + src = new InputSource((InputStream) mappedEntities.get(systemId)); + } + + if (src != null) { + src.setPublicId(publicId); + src.setSystemId(systemId); + } + + return src; + } +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StreamUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StreamUtils.java new file mode 100644 index 000000000..e4ccd127f --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StreamUtils.java @@ -0,0 +1,197 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; + +/** + * Utility methods for streams. + * + * @author Patrick Peck + * @version $Id$ + */ +public class StreamUtils { + + /** + * Compare the contents of two InputStreams. + * + * @param is1 The 1st InputStream to compare. + * @param is2 The 2nd InputStream to compare. + * @return boolean true, if both streams contain the exactly the + * same content, false otherwise. + * @throws IOException An error occurred reading one of the streams. + */ + public static boolean compareStreams(InputStream is1, InputStream is2) + throws IOException { + + byte[] buf1 = new byte[256]; + byte[] buf2 = new byte[256]; + int length1; + int length2; + + try { + while (true) { + length1 = is1.read(buf1); + length2 = is2.read(buf2); + + if (length1 != length2) { + return false; + } + if (length1 <= 0) { + return true; + } + if (!compareBytes(buf1, buf2, length1)) { + return false; + } + } + } catch (IOException e) { + throw e; + } finally { + // close both streams + try { + is1.close(); + is2.close(); + } catch (IOException e) { + // ignore this + } + } + } + + /** + * Compare two byte arrays, up to a given maximum length. + * + * @param b1 1st byte array to compare. + * @param b2 2nd byte array to compare. + * @param length The maximum number of bytes to compare. + * @return true, if the byte arrays are equal, false + * otherwise. + */ + private static boolean compareBytes(byte[] b1, byte[] b2, int length) { + if (b1.length != b2.length) { + return false; + } + + for (int i = 0; i < b1.length && i < length; i++) { + if (b1[i] != b2[i]) { + return false; + } + } + + return true; + } + + /** + * Reads a byte array from a stream. + * @param in The InputStream to read. + * @return The bytes contained in the given InputStream. + * @throws IOException on any exception thrown + */ + public static byte[] readStream(InputStream in) throws IOException { + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + copyStream(in, out, null); + + /* + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int b; + while ((b = in.read()) >= 0) + out.write(b); + + */ + in.close(); + return out.toByteArray(); + } + + /** + * Reads a String from a stream, using given encoding. + * @param in The InputStream to read. + * @param encoding The character encoding to use for converting the bytes + * of the InputStream into a String. + * @return The content of the given InputStream converted into + * a String. + * @throws IOException on any exception thrown + */ + public static String readStream(InputStream in, String encoding) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + copyStream(in, out, null); + + /* + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int b; + while ((b = in.read()) >= 0) + out.write(b); + */ + in.close(); + return out.toString(encoding); + } + + /** + * Reads all data (until EOF is reached) from the given source to the + * destination stream. If the destination stream is null, all data is dropped. + * It uses the given buffer to read data and forward it. If the buffer is + * null, this method allocates a buffer. + * + * @param source The stream providing the data. + * @param destination The stream that takes the data. If this is null, all + * data from source will be read and discarded. + * @param buffer The buffer to use for forwarding. If it is null, the method + * allocates a buffer. + * @exception IOException If reading from the source or writing to the + * destination fails. + */ + private static void copyStream(InputStream source, OutputStream destination, byte[] buffer) throws IOException { + if (source == null) { + throw new NullPointerException("Argument \"source\" must not be null."); + } + if (buffer == null) { + buffer = new byte[8192]; + } + + if (destination != null) { + int bytesRead; + while ((bytesRead = source.read(buffer)) >= 0) { + destination.write(buffer, 0, bytesRead); + } + } else { + while (source.read(buffer) >= 0); + } + } + + /** + * Gets the stack trace of the Throwable passed in as a string. + * @param t The Throwable. + * @return a String representing the stack trace of the Throwable. + */ + public static String getStackTraceAsString(Throwable t) + { + ByteArrayOutputStream stackTraceBIS = new ByteArrayOutputStream(); + t.printStackTrace(new PrintStream(stackTraceBIS)); + return new String(stackTraceBIS.toByteArray()); + } +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StringUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StringUtils.java new file mode 100644 index 000000000..ad879d2b6 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/StringUtils.java @@ -0,0 +1,178 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.util.StringTokenizer; + +/** + * Utitility functions for string manipulations. + * + * @author Harald Bratko + */ +public class StringUtils { + + /** + * Removes all blanks and tabs from the given string. + * + * @param s The string to remove all blanks and tabs from. + * @return The input string with all blanks and tabs removed from. + */ + public static String removeBlanks(String s) { + StringTokenizer st = new StringTokenizer(s); + StringBuffer sb = new StringBuffer(s.length()); + while (st.hasMoreTokens()) { + sb.append(st.nextToken()); + } + return sb.toString(); + } + + /** + * Removes all occurences of the specified token from the the given string. + * + * @param s The string to remove all occurences of the specified token from. + * @return The input string with all occurences of the specified token removed from. + */ + public static String removeToken(String s, String token) { + StringTokenizer st = new StringTokenizer(s, token); + StringBuffer sb = new StringBuffer(s.length()); + while (st.hasMoreTokens()) { + sb.append(st.nextToken()); + } + return sb.toString(); + } + + /** + * Removes all leading zeros from the input string. + * + * @param s The string remove the leading zeros from. + * @return The input string with the leading zeros removed from. + */ + public static String deleteLeadingZeros(String s) { + StringBuffer sb = new StringBuffer(s); + int l = sb.length(); + int j = 0; + for (int i=0; is that matches the given + * search string by the given replace string. + * + * @param s The string where the replacement should take place. + * @param search The pattern that should be replaced. + * @param replace The string that should replace all each search + * string within s. + * @return A string where all occurrence of search are + * replaced with replace. + */ + public static String replaceAll (String s, String search, String replace) + { + StringBuffer sb = new StringBuffer(); + int i = 0, j = 0; + int len = search.length(); + while (j > -1) + { + j = s.indexOf(search, i); + + if (j > -1) + { + sb.append(s.substring(i,j)); + sb.append(replace); + i = j + len; + } + } + + sb.append(s.substring(i, s.length())); + + return sb.toString(); + } + + /** + * Changes the SecurityLayer version in the given string. + * This method usually takes as input an XML structure represented in a string + * format and changes the SecurityLayer namespaces prefixes and URIs from + * one SecurityLayer version to another. + * e.g.: code>sl10 to sl and + * http://www.buergerkarte.at/namespaces/securitylayer/20020225# + * to + * http://www.buergerkarte.at/namespaces/securitylayer/1.2# + * + * @param s The string (usally an XML structure) where the + * SecurityLayer version should be changed. + * @param slPrefixOld The SecurityLayer namespace prefix that should be + * replaced by the new one. + * @param slPrefixNew The new SecurityLayer namespace prefix that should + * replace the old one. + * @param slNSUriOld The SecurityLayer namespace URI that should be + * replaced by the new one. + * @param slNSUriNew The new SecurityLayer namespace URI that should + * replace the old one. + * @return A string where the SecurityLayer namespace prefixes + * and URIs are replaced by new ones. + */ + public static String changeSLVersion(String s, String slPrefixOld, String slPrefixNew, String slNSUriOld, String slNSUriNew) { + String retString = replaceAll(s, slPrefixOld, slPrefixNew); + retString = replaceAll(retString, slNSUriOld, slNSUriNew); + return retString ; + } + + /** + * Removes the XML declaration from an XML expression. + * + * @param xmlString XML expression as String + * + * @return XML expression, XML declaration removed + */ + public static String removeXMLDeclaration(String xmlString) { + if (xmlString!=null && xmlString.startsWith("application/x-www-form-urlencoded string using a specific encoding scheme. + * @param s the string to decode + * @param encoding name of character encoding + * @return the newly decoded string + * @throws UnsupportedEncodingException if the encoding is not supported + */ + public static String decode(String s, String encoding) throws UnsupportedEncodingException { + StringReader in = new StringReader(s); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + for (int b = read(in); b >= 0; b = read(in)) + bout.write(b); + return bout.toString(encoding); + } + /** + * Decodes the next byte from the string reader. + * @param in string reader + * @return the next byte decoded; + * -1 upon end of string, on erroneous data, and on any exception caught + * @todo syntax check on string + */ + private static int read(StringReader in) { + try { + int b = in.read(); + if (b == '+') + return ' '; + if (b == '%') { + char[] hex = new char[2]; + if (in.read(hex, 0, 2) >= 0) { + String hexString = new String(hex); + return Integer.valueOf(hexString, 16).intValue(); + } + else + return -1; + } + return b; + } + catch (IOException ex) { + return -1; + } + catch (NumberFormatException ex) { + return -1; + } + } +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/URLEncoder.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/URLEncoder.java new file mode 100644 index 000000000..e6df1fd33 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/URLEncoder.java @@ -0,0 +1,89 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.ByteArrayInputStream; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; + +/** + * Translates a string into mime format "x-www-form-urlencoded". + * Provides a function missing in JDK 1.3. + * @author Paul Ivancsics + * @version $Id$ + */ +public class URLEncoder { + + /** + * Translates a string into x-www-form-urlencoded format. + * @param s the string to be translated + * @param encoding the encoding to use + * @return the translated string + * @throws UnsupportedEncodingException when the desired encoding is not supported + */ + public static String encode(String s, String encoding) throws UnsupportedEncodingException { +// if (MiscUtil.isEmpty(s)) +// return null; + byte[] barr = s.getBytes(encoding); + ByteArrayInputStream bin = new ByteArrayInputStream(barr); + StringWriter out = new StringWriter(); + for (int b = bin.read(); b >= 0; b = bin.read()) + encode(b, out); + return out.toString(); + } + + /** + * Encode a character. + * @param ch The character to encode. + * @param out The StringWriter containing the result. + */ + private static void encode(int ch, StringWriter out) { + if ((ch >= 'a' && ch <= 'z') + || (ch >= 'A' && ch <= 'Z') + || (ch >= '0' && ch <= '9') + || ch == '.' || ch == '-' || ch == '*' || ch == '_') + out.write(ch); + else if (ch == ' ') + out.write('+'); + else + encodeHex(ch, out); + } + + /** + * Encode a character as an escaped hex value. + * @param ch The character to encode. + * @param out The StringWriter containing the result. + */ + private static void encodeHex(int ch, StringWriter out) { + out.write('%'); + String hex = Integer.toHexString(ch).toUpperCase(); + if (hex.length() < 2) + out.write('0'); + else + out.write(hex.charAt(hex.length() - 2)); + out.write(hex.charAt(hex.length() - 1)); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathException.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathException.java new file mode 100644 index 000000000..206245a68 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathException.java @@ -0,0 +1,86 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.io.PrintStream; +import java.io.PrintWriter; + +/** + * An exception occurred evaluating an XPath. + * + * @author Patrick Peck + * @version $Id$ + */ +public class XPathException extends RuntimeException { + /** + * + */ + private static final long serialVersionUID = 1736311265333034392L; +/** The wrapped exception. */ + private Throwable wrapped; + + /** + * Create a XPathException. + * + * @param message The exception message. + * @param wrapped The exception being the likely cause of this exception. + */ + public XPathException(String message, Throwable wrapped) { + super(message); + this.wrapped = wrapped; + } + + /** + * Return the wrapped exception. + * + * @return The wrapped exception being the likely cause of this exception. + */ + public Throwable getWrapped() { + return wrapped; + } + + /** + * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) + */ + public void printStackTrace(PrintStream s) { + super.printStackTrace(s); + if (getWrapped() != null) { + s.print("Caused by: "); + getWrapped().printStackTrace(s); + } + } + + /** + * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) + */ + public void printStackTrace(PrintWriter s) { + super.printStackTrace(s); + if (getWrapped() != null) { + s.print("Caused by: "); + getWrapped().printStackTrace(s); + } + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathUtils.java new file mode 100644 index 000000000..89aeaf3d1 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/XPathUtils.java @@ -0,0 +1,557 @@ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.util; + +import java.util.List; +import java.util.Map; + +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.traversal.NodeIterator; + +import org.jaxen.JaxenException; +import org.jaxen.NamespaceContext; +import org.jaxen.Navigator; +import org.jaxen.SimpleNamespaceContext; +import org.jaxen.dom.DOMXPath; +import org.jaxen.dom.DocumentNavigator; + +/** + * Utility methods to evaluate XPath expressions on DOM nodes. + * + * @author Patrick Peck + * @version $Id$ + */ +public class XPathUtils { + + /** + * The XPath expression selecting all nodes under a given root (including the + * root node itself). + */ + public static final String ALL_NODES_XPATH = + "(.//. | .//@* | .//namespace::*)"; + + /** The DocumentNavigator to use for navigating the document. */ + private static Navigator documentNavigator = + DocumentNavigator.getInstance(); + /** The default namespace prefix to namespace URI mappings. */ + private static NamespaceContext NS_CONTEXT; + + static { + SimpleNamespaceContext ctx = new SimpleNamespaceContext(); + ctx.addNamespace(Constants.MOA_PREFIX, Constants.MOA_NS_URI); + ctx.addNamespace(Constants.MOA_CONFIG_PREFIX, Constants.MOA_CONFIG_NS_URI); + ctx.addNamespace(Constants.MOA_ID_CONFIG_PREFIX, Constants.MOA_ID_CONFIG_NS_URI); + ctx.addNamespace(Constants.SL10_PREFIX, Constants.SL10_NS_URI); + ctx.addNamespace(Constants.SL11_PREFIX, Constants.SL11_NS_URI); + ctx.addNamespace(Constants.SL12_PREFIX, Constants.SL12_NS_URI); + ctx.addNamespace(Constants.ECDSA_PREFIX, Constants.ECDSA_NS_URI); + ctx.addNamespace(Constants.PD_PREFIX, Constants.PD_NS_URI); + ctx.addNamespace(Constants.SAML_PREFIX, Constants.SAML_NS_URI); + ctx.addNamespace(Constants.SAMLP_PREFIX, Constants.SAMLP_NS_URI); + ctx.addNamespace(Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); + ctx.addNamespace(Constants.XSLT_PREFIX, Constants.XSLT_NS_URI); + ctx.addNamespace(Constants.XSI_PREFIX, Constants.XSI_NS_URI); + ctx.addNamespace(Constants.DSIG_FILTER2_PREFIX, Constants.DSIG_FILTER2_NS_URI); + ctx.addNamespace(Constants.DSIG_EC_PREFIX, Constants.DSIG_EC_NS_URI); + ctx.addNamespace(Constants.MD_PREFIX, Constants.MD_NS_URI); + ctx.addNamespace(Constants.MDP_PREFIX, Constants.MDP_NS_URI); + ctx.addNamespace(Constants.MVV_PREFIX, Constants.MVV_NS_URI); + ctx.addNamespace(Constants.STB_PREFIX, Constants.STB_NS_URI); + ctx.addNamespace(Constants.WRR_PREFIX, Constants.WRR_NS_URI); + ctx.addNamespace(Constants.STORK_PREFIX, Constants.STORK_NS_URI); + ctx.addNamespace(Constants.STORKP_PREFIX, Constants.STORKP_NS_URI); + ctx.addNamespace(Constants.SAML2_PREFIX, Constants.SAML2_NS_URI); + ctx.addNamespace(Constants.SAML2P_PREFIX, Constants.SAML2P_NS_URI); + ctx.addNamespace(Constants.XENC_PREFIX, Constants.XENC_NS_URI); + ctx.addNamespace(Constants.XADES_1_1_1_NS_PREFIX, Constants.XADES_1_1_1_NS_URI); + NS_CONTEXT = ctx; + } + + /** + * Return a NodeIterator over the nodes matching the XPath + * expression. + * + * All namespace URIs and prefixes declared in the Constants + * interface are used for resolving namespaces. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param exp The XPath expression to evaluate. + * @return An iterator over the resulting nodes. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + public static NodeIterator selectNodeIterator(Node contextNode, String exp) + throws XPathException { + + return selectNodeIterator(contextNode, NS_CONTEXT, exp); + } + + /** + * Return a NodeIterator over the nodes matching the XPath + * expression. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param namespaceElement An element from which to build the + * namespace mapping for evaluating the XPath expression + * @param exp The XPath expression to evaluate. + * @return An iterator over the resulting nodes. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + public static NodeIterator selectNodeIterator( + Node contextNode, + Element namespaceElement, + String exp) + throws XPathException { + + try { + SimpleNamespaceContext ctx = new SimpleNamespaceContext(); + ctx.addElementNamespaces(documentNavigator, namespaceElement); + return selectNodeIterator(contextNode, ctx, exp); + } catch (JaxenException e) { + MessageProvider msg = MessageProvider.getInstance(); + String message = msg.getMessage("xpath.00", new Object[] { exp }); + throw new XPathException(message, e); + } + } + + /** + * Return a NodeIterator over the nodes matching the XPath + * expression. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param namespaceMapping A namespace prefix to namespace URI mapping + * (String to String) for evaluating the XPath + * expression. + * @param exp The XPath expression to evaluate. + * @return An iterator over the resulting nodes. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + public static NodeIterator selectNodeIterator( + Node contextNode, + Map namespaceMapping, + String exp) + throws XPathException { + + SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); + + return selectNodeIterator(contextNode, ctx, exp); + } + + /** + * Return a NodeIterator over the nodes matching the XPath + * expression. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param nsContext The NamespaceContext for resolving namespace + * prefixes to namespace URIs for evaluating the XPath expression. + * @param exp The XPath expression to evaluate. + * @return An iterator over the resulting nodes. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + private static NodeIterator selectNodeIterator( + Node contextNode, + NamespaceContext nsContext, + String exp) + throws XPathException { + + try { + DOMXPath xpath = new DOMXPath(exp); + List nodes; + + xpath.setNamespaceContext(nsContext); + nodes = xpath.selectNodes(contextNode); + return new NodeIteratorAdapter(nodes.listIterator()); + } catch (JaxenException e) { + MessageProvider msg = MessageProvider.getInstance(); + String message = msg.getMessage("xpath.00", new Object[] { exp }); + throw new XPathException(message, e); + } + } + + /** + * Return a NodeList of all the nodes matching the XPath + * expression. + * + * All namespace URIs and prefixes declared in the Constants + * interface are used for resolving namespaces. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param exp The XPath expression to evaluate. + * @return A NodeList containing the matching nodes. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + public static NodeList selectNodeList(Node contextNode, String exp) + throws XPathException { + + return selectNodeList(contextNode, NS_CONTEXT, exp); + } + + /** + * Return a NodeList of all the nodes matching the XPath + * expression. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param namespaceElement An element from which to build the + * namespace mapping for evaluating the XPath expression + * @param exp The XPath expression to evaluate. + * @return A NodeList containing the matching nodes. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + public static NodeList selectNodeList( + Node contextNode, + Element namespaceElement, + String exp) + throws XPathException { + + try { + SimpleNamespaceContext ctx = new SimpleNamespaceContext(); + + ctx.addElementNamespaces(documentNavigator, namespaceElement); + return selectNodeList(contextNode, ctx, exp); + } catch (JaxenException e) { + MessageProvider msg = MessageProvider.getInstance(); + String message = msg.getMessage("xpath.00", new Object[] { exp }); + throw new XPathException(message, e); + } + } + + /** + * Return a NodeList of all the nodes matching the XPath + * expression. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param namespaceMapping A namespace prefix to namespace URI mapping + * (String to String) for evaluating the XPath + * expression. + * @param exp The XPath expression to evaluate. + * @return A NodeList containing the matching nodes. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + public static NodeList selectNodeList( + Node contextNode, + Map namespaceMapping, + String exp) + throws XPathException { + + SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); + + return selectNodeList(contextNode, ctx, exp); + } + + /** + * Return a NodeList of all the nodes matching the XPath + * expression. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param nsContext The NamespaceContext for resolving namespace + * prefixes to namespace URIs for evaluating the XPath expression. + * @param exp The XPath expression to evaluate. + * @return A NodeList containing the matching nodes. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + private static NodeList selectNodeList( + Node contextNode, + NamespaceContext nsContext, + String exp) + throws XPathException { + + try { + DOMXPath xpath = new DOMXPath(exp); + List nodes; + + xpath.setNamespaceContext(nsContext); + nodes = xpath.selectNodes(contextNode); + return new NodeListAdapter(nodes); + } catch (JaxenException e) { + MessageProvider msg = MessageProvider.getInstance(); + String message = msg.getMessage("xpath.00", new Object[] { exp }); + throw new XPathException(message, e); + } + } + + /** + * Select the first node matching an XPath expression. + * + * All namespace URIs and prefixes declared in the Constants + * interface are used for resolving namespaces. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param exp The XPath expression to evaluate. + * @return Node The first node matching the XPath expression, or + * null, if no node matched. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + public static Node selectSingleNode(Node contextNode, String exp) + throws XPathException { + + return selectSingleNode(contextNode, NS_CONTEXT, exp); + } + + /** + * Select the first node matching an XPath expression. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param namespaceElement An element from which to build the + * namespace mapping for evaluating the XPath expression + * @param exp The XPath expression to evaluate. + * @return Node The first node matching the XPath expression, or + * null, if no node matched. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + public static Node selectSingleNode( + Node contextNode, + Element namespaceElement, + String exp) + throws XPathException { + + try { + SimpleNamespaceContext ctx = new SimpleNamespaceContext(); + ctx.addElementNamespaces(documentNavigator, namespaceElement); + + return selectSingleNode(contextNode, ctx, exp); + } catch (JaxenException e) { + MessageProvider msg = MessageProvider.getInstance(); + String message = msg.getMessage("xpath.00", new Object[] { exp }); + throw new XPathException(message, e); + } + } + + /** + * Select the first node matching an XPath expression. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param namespaceMapping A namespace prefix to namespace URI mapping + * (String to String) for evaluating the XPath + * expression. + * @param exp The XPath expression to evaluate. + * @return Node The first node matching the XPath expression, or + * null, if no node matched. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + public static Node selectSingleNode( + Node contextNode, + Map namespaceMapping, + String exp) + throws XPathException { + + SimpleNamespaceContext ctx = new SimpleNamespaceContext(namespaceMapping); + + return selectSingleNode(contextNode, ctx, exp); + } + + /** + * Select the first node matching an XPath expression. + * + * @param contextNode The root node from which to evaluate the XPath + * expression. + * @param nsContext The NamespaceContext for resolving namespace + * prefixes to namespace URIs for evaluating the XPath expression. + * @param exp The XPath expression to evaluate. + * @return Node The first node matching the XPath expression, or + * null, if no node matched. + * @throws XPathException An error occurred evaluating the XPath expression. + */ + public static Node selectSingleNode( + Node contextNode, + NamespaceContext nsContext, + String exp) + throws XPathException { + + try { + DOMXPath xpath = new DOMXPath(exp); + xpath.setNamespaceContext(nsContext); + return (Node) xpath.selectSingleNode(contextNode); + } catch (JaxenException e) { + MessageProvider msg = MessageProvider.getInstance(); + String message = msg.getMessage("xpath.00", new Object[] { exp }); + throw new XPathException(message, e); + } + } + + /** + * Return the value of a DOM element whose location is given by an XPath + * expression. + * + * @param root The root element from which to evaluate the XPath. + * @param xpath The XPath expression pointing to the element whose value + * to return. + * @param def The default value to return, if no element can be found using + * the given xpath. + * @return The element value, if it can be located using the + * xpath. Otherwise, def is returned. + */ + public static String getElementValue( + Element root, + String xpath, + String def) { + + Element elem = (Element) XPathUtils.selectSingleNode(root, xpath); + return elem != null ? DOMUtils.getText(elem) : def; + } + + /** + * Return the value of a DOM attribute whose location is given by an XPath + * expression. + * + * @param root The root element from which to evaluate the XPath. + * @param xpath The XPath expression pointing to the attribute whose value to + * return. + * @param def The default value to return, if no attribute can be found using + * the given xpath. + * @return The element value, if it can be located using the + * xpath. Otherwise, def is returned. + */ + public static String getAttributeValue( + Element root, + String xpath, + String def) { + + Attr attr = (Attr) XPathUtils.selectSingleNode(root, xpath); + return attr != null ? attr.getValue() : def; + } + + /** + * Returns the namespace prefix used within XPathUtils for referring to + * the namespace of the specified (Security Layer command) element. + * + * This namespace prefix can be used in various XPath expression evaluation methods + * within XPathUtils without explicitely binding it to the particular + * namespace. + * + * @param contextElement The (Security Layer command) element. + * + * @return the namespace prefix used within XPathUtils for referring to + * the namespace of the specified (Security Layer command) element. + * + * throws XpathException If the specified element has a namespace other than the ones + * known by this implementation as valid Security Layer namespaces (cf. + * @link Constants#SL10_NS_URI, @link Constants#SL11_NS_URI, @link Constants#SL12_NS_URI). + */ + public static String getSlPrefix (Element contextElement) throws XPathException + { + String sLNamespace = contextElement.getNamespaceURI(); + String sLPrefix = null; + + if (sLNamespace.equals(Constants.SL10_NS_URI)) + { + sLPrefix = Constants.SL10_PREFIX; + } + else if (sLNamespace.equals(Constants.SL12_NS_URI)) + { + sLPrefix = Constants.SL12_PREFIX; + } + else if (sLNamespace.equals(Constants.SL11_NS_URI)) + { + sLPrefix = Constants.SL11_PREFIX; + } + else + { + MessageProvider msg = MessageProvider.getInstance(); + String message = msg.getMessage("xpath.00", new Object[] { "Ung�ltiger Security Layer Namespace: \"" + sLNamespace + "\"."}); + throw new XPathException(message, null); + } + + return sLPrefix; + } + + + /** + * Return the SecurityLayer namespace prefix of the context element. + * If the context element is not the element that lies within the + * SecurityLayer namespace. The Securitylayer namespace is derived from + * the xmlns:sl10, sl11 or sl + * attribute of the context element. + * + * The returned prefix is needed for evaluating XPATH expressions. + * + * @param contextElement The element to get a prefix for the Securitylayer namespace, + * that is used within the corresponding document. + * + * @return The string sl10, sl11 or sl, + * depending on the SecurityLayer namespace of the contextElement. + * + * throws XPathException If no (vlalid) SecurityLayer namespace prefix or namespace + * is defined. + */ + public static String getSlPrefixFromNoRoot (Element contextElement) throws XPathException { + + String slPrefix = checkSLnsDeclaration(contextElement, Constants.SL10_PREFIX, Constants.SL10_NS_URI); + if (slPrefix == null) { + slPrefix = checkSLnsDeclaration(contextElement, Constants.SL11_PREFIX, Constants.SL11_NS_URI); + } + if (slPrefix == null) { + slPrefix = checkSLnsDeclaration(contextElement, Constants.SL12_PREFIX, Constants.SL12_NS_URI); + } + + return slPrefix; + + } + + /** + * Checks if the context element has an attribute xmlns:slPrefix and + * if the prefix of that attribute corresponds with a valid SecurityLayer namespace. + * + * @param contextElement The element to be checked. + * @param slPrefix The prefix which should be checked. Must be a valid SecurityLayer + * namespace prefix. + * @param slNameSpace The SecurityLayer namespace that corresponds to the specified prefix. + * + * @return The valid SecurityLayer prefix or null if this prefix is + * not used. + * @throws XPathException + */ + private static String checkSLnsDeclaration(Element contextElement, String slPrefix, String slNameSpace) + throws XPathException + { + String nsAtt = "xmlns:" + slPrefix; + String nameSpace = contextElement.getAttribute(nsAtt); + if (nameSpace == "") { + return null; + } else { + // check if namespace is correct + if (nameSpace.equals(slNameSpace)) { + return slPrefix; + } else { + MessageProvider msg = MessageProvider.getInstance(); + String message = msg.getMessage("xpath.00", new Object[] { "Ung�ltiger SecurityLayer Namespace: \"" + nameSpace + "\"."}); + throw new XPathException(message, null); + } + } + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/ex/EgovUtilException.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/ex/EgovUtilException.java new file mode 100644 index 000000000..733a2a845 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/ex/EgovUtilException.java @@ -0,0 +1,41 @@ +/* + * Copyright 2011 Federal Chancellery Austria and + * Graz University of Technology + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package at.gv.egovernment.moa.util.ex; + +public class EgovUtilException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public EgovUtilException() { + } + + public EgovUtilException(String message) { + super(message); + } + + public EgovUtilException(Throwable cause) { + super(cause); + } + + public EgovUtilException(String message, Throwable cause) { + super(message, cause); + } + +} -- cgit v1.2.3 From f67427831d1f8c49ce6c474691b880d90a42b584 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 14 Mar 2016 09:17:57 +0100 Subject: refactor the GUI generation for user interaction --- .../moa/id/commons/MOAIDAuthConstants.java | 193 ++++++++++++++ .../moa/id/commons/api/AuthConfiguration.java | 162 ++++++++++++ .../moa/id/commons/api/ConfigurationProvider.java | 66 +++++ .../commons/api/ConnectionParameterInterface.java | 35 +++ .../moa/id/commons/api/IOAAuthParameters.java | 222 +++++++++++++++++ .../egovernment/moa/id/commons/api/IRequest.java | 201 +++++++++++++++ .../moa/id/commons/api/IStorkConfig.java | 51 ++++ .../commons/api/data/BPKDecryptionParameters.java | 135 ++++++++++ .../egovernment/moa/id/commons/api/data/CPEPS.java | 138 +++++++++++ .../moa/id/commons/api/data/ProtocolAllowed.java | 91 +++++++ .../api/data/SAML1ConfigurationParameters.java | 276 +++++++++++++++++++++ .../api/data/SignatureCreationParameter.java | 103 ++++++++ .../api/data/SignatureVerificationParameter.java | 53 ++++ .../moa/id/commons/api/data/StorkAttribute.java | 27 ++ .../api/data/StorkAttributeProviderPlugin.java | 81 ++++++ .../api/exceptions/ConfigurationException.java | 78 ++++++ .../id/commons/api/exceptions/MOAIDException.java | 222 +++++++++++++++++ .../exceptions/SessionDataStorageException.java | 45 ++++ .../moa/id/commons/utils/MOAIDMessageProvider.java | 104 ++++++++ 19 files changed, 2283 insertions(+) create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/MOAIDAuthConstants.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/AuthConfiguration.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/ConfigurationProvider.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/ConnectionParameterInterface.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IOAAuthParameters.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IRequest.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IStorkConfig.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/BPKDecryptionParameters.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/CPEPS.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/ProtocolAllowed.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SAML1ConfigurationParameters.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SignatureCreationParameter.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SignatureVerificationParameter.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/StorkAttribute.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/StorkAttributeProviderPlugin.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/ConfigurationException.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/MOAIDException.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/SessionDataStorageException.java create mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/utils/MOAIDMessageProvider.java (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/MOAIDAuthConstants.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/MOAIDAuthConstants.java new file mode 100644 index 000000000..8d893be9d --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/MOAIDAuthConstants.java @@ -0,0 +1,193 @@ + + + +package at.gv.egovernment.moa.id.commons; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import iaik.asn1.ObjectID; + + +/** + * Constants used throughout moa-id-auth component. + * + * @author Paul Ivancsics + * @version $Id$ + */ +public class MOAIDAuthConstants extends MOAIDConstants{ + + /** servlet parameter "Target" */ + public static final String PARAM_TARGET = "Target"; + /** servlet parameter "useMandate" */ + public static final String PARAM_USEMANDATE = "useMandate"; + public static final String PARAM_USEMISMANDATE = "useMISMandate"; + public static final String PARAM_USEELGAMANDATE = "useELGAMandate"; + /** servlet parameter "OA" */ + public static final String PARAM_OA = "OA"; + /** servlet parameter "bkuURI" */ + public static final String PARAM_BKU = "bkuURI"; + public static final String PARAM_MODUL = "MODUL"; + public static final String PARAM_ACTION = "ACTION"; + public static final String PARAM_SSO = "SSO"; + public static final String INTERFEDERATION_IDP = "interIDP"; + public static final String PARAM_TARGET_PENDINGREQUESTID = "pendingid"; + + public static final String PARAM_SLOSTATUS = "status"; + public static final String PARAM_SLORESTART = "restart"; + public static final String SLOSTATUS_SUCCESS = "success"; + public static final String SLOSTATUS_ERROR = "error"; + + /** servlet parameter "sourceID" */ + public static final String PARAM_SOURCEID = "sourceID"; + /** servlet parameter "BKUSelectionTemplate" */ + public static final String PARAM_BKUTEMPLATE = "BKUSelectionTemplate"; + /** servlet parameter "CCC (Citizen Country Code)" */ + public static final String PARAM_CCC = "CCC"; + /** servlet parameter "BKUSelectionTemplate" */ + public static final String PARAM_INPUT_PROCESSOR_SIGN_TEMPLATE = "InputProcessorSignTemplate"; + /** default BKU URL */ + public static final String DEFAULT_BKU = "http://localhost:3495/http-security-layer-request"; + /** default BKU URL for https connections*/ + public static final String DEFAULT_BKU_HTTPS = "https://127.0.0.1:3496/https-security-layer-request"; + /** servlet parameter "returnURI" */ + public static final String PARAM_RETURN = "returnURI"; + /** servlet parameter "Template" */ + public static final String PARAM_TEMPLATE = "Template"; + /** servlet parameter "MOASessionID" */ + public static final String PARAM_SESSIONID = "MOASessionID"; + /** servlet parameter "XMLResponse" */ + public static final String PARAM_XMLRESPONSE = "XMLResponse"; + /** servlet parameter "SAMLArtifact" */ + public static final String PARAM_SAMLARTIFACT = "SAMLArtifact"; + /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.StartAuthenticationServlet} is mapped to */ + public static final String REQ_START_AUTHENTICATION = "StartAuthentication"; + /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet} is mapped to */ + public static final String REQ_VERIFY_IDENTITY_LINK = "VerifyIdentityLink"; + /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.GetForeignIDServlet} is mapped to */ + public static final String REQ_GET_FOREIGN_ID = "GetForeignID"; + /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet} is mapped to */ + public static final String REQ_VERIFY_CERTIFICATE = "VerifyCertificate"; + /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.GetMISSessionIDServlet} is mapped to */ + public static final String GET_MIS_SESSIONID = "GetMISSessionID"; + /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.ProcessValidatorInputServlet} is mapped to */ + public static final String REQ_PROCESS_VALIDATOR_INPUT = "ProcessInput"; + /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet} is mapped to */ + public static final String REQ_VERIFY_AUTH_BLOCK = "VerifyAuthBlock"; + /** Logging hierarchy used for controlling debug output of XML structures to files */ + public static final String DEBUG_OUTPUT_HIERARCHY = "moa.id.auth"; + /** Header Name for controlling the caching mechanism of the browser */ + public static final String HEADER_EXPIRES = "Expires"; + /** Header Value for controlling the caching mechanism of the browser */ + public static final String HEADER_VALUE_EXPIRES = "Sat, 6 May 1995 12:00:00 GMT"; + /** Header Name for controlling the caching mechanism of the browser */ + public static final String HEADER_PRAGMA = "Pragma"; + /** Header Value for controlling the caching mechanism of the browser */ + public static final String HEADER_VALUE_PRAGMA = "no-cache"; + /** Header Name for controlling the caching mechanism of the browser */ + public static final String HEADER_CACHE_CONTROL = "Cache-control"; + /** Header Value for controlling the caching mechanism of the browser */ + public static final String HEADER_VALUE_CACHE_CONTROL = "no-store, no-cache, must-revalidate"; + /** Header Value for controlling the caching mechanism of the browser */ + public static final String HEADER_VALUE_CACHE_CONTROL_IE = "post-check=0, pre-check=0"; + /** + * the identity link signer X509Subject names of those identity link signer certificates + * not including the identity link signer OID. The authorisation for signing the identity + * link must be checked by using their issuer names. After february 19th 2007 the OID of + * the certificate will be used fo checking the authorisation for signing identity links. + */ + public static final String[] IDENTITY_LINK_SIGNERS_WITHOUT_OID = + new String[] {"T=Dr.,CN=Nikolaus Schwab,O=BM f. Inneres i.A. des gf. Mitgieds der Datenschutzkommission", + "T=Dr.,CN=Nikolaus Schwab,O=BM f. Inneres i.A. des gf. Mitglieds der Datenschutzkommission"}; + + /** the number of the certifcate extension "Eigenschaft zur Ausstellung von Personenbindungen" */ + public static final String IDENTITY_LINK_SIGNER_OID_NUMBER = "1.2.40.0.10.1.7.1"; + /** + * the OID of the identity link signer certificate (Eigenschaft zur Ausstellung von Personenbindungen); + * used for checking the authorisation for signing the identity link for identity links signed after february 19th 2007 + */ + public static final ObjectID IDENTITY_LINK_SIGNER_OID = new ObjectID(IDENTITY_LINK_SIGNER_OID_NUMBER); + + /** the number of the certifcate extension for party representatives */ + public static final String PARTY_REPRESENTATION_OID_NUMBER = "1.2.40.0.10.3"; + +// /** the number of the certifcate extension for party organ representatives */ +// public static final String PARTY_ORGAN_REPRESENTATION_OID_NUMBER = PARTY_REPRESENTATION_OID_NUMBER + ".10"; + + /** OW */ + public static final String OW_ORGANWALTER = PARTY_REPRESENTATION_OID_NUMBER + ".4"; + + /** List of OWs */ + public static final List OW_LIST = Arrays.asList( + new ObjectID(OW_ORGANWALTER)); + + /**BKU type identifiers to use bkuURI from configuration*/ + public static final String REQ_BKU_TYPE_LOCAL = "local"; + public static final String REQ_BKU_TYPE_ONLINE = "online"; + public static final String REQ_BKU_TYPE_HANDY = "handy"; + public static final List REQ_BKU_TYPES = Arrays.asList(REQ_BKU_TYPE_LOCAL, REQ_BKU_TYPE_ONLINE, REQ_BKU_TYPE_HANDY); + + public static final List LEGACYPARAMETERWHITELIST + = Arrays.asList(PARAM_TARGET, PARAM_BKU, PARAM_OA, PARAM_TEMPLATE, PARAM_USEMANDATE, PARAM_CCC, PARAM_SOURCEID); + + public final static String EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION = "OIDTextualDescription"; + public final static String EXT_SAML_MANDATE_OID = "OID"; + public final static String EXT_SAML_MANDATE_RAW = "Mandate"; + public final static String EXT_SAML_MANDATE_NAME = "MandatorName"; + public final static String EXT_SAML_MANDATE_DOB = "MandatorDateOfBirth"; + public final static String EXT_SAML_MANDATE_WBPK = "MandatorWbpk"; + public final static String EXT_SAML_MANDATE_REPRESENTATIONTYPE = "RepresentationType"; + public final static String EXT_SAML_MANDATE_REPRESENTATIONTEXT = "Vollmachtsvertreter"; + public final static String EXT_SAML_MANDATE_CB_BASE_ID = "MandatorDomainIdentifier"; + + public static final String PARAM_APPLET_HEIGTH = "heigth"; + public static final String PARAM_APPLET_WIDTH = "width"; + + public static final Map COUNTRYCODE_XX_TO_NAME = + Collections.unmodifiableMap(new HashMap() { + private static final long serialVersionUID = 1L; + { + put("AT", "Other Countries");//"Workaround for PEPS Simulator" + put("BE", "België/Belgique"); + //put("CH", "Schweiz"); + put("EE", "Eesti"); + put("ES", "España"); + put("FI", "Suomi"); + put("IS", "Ísland"); + put("IT", "Italia"); + put("LI", "Liechtenstein"); + put("LT", "Lithuania"); + put("LU", "Luxemburg"); + put("PT", "Portugal"); + put("SE", "Sverige"); + put("SI", "Slovenija"); + } + }); + + public static final String COUNTRYCODE_AUSTRIA = "AT"; + + public static final String REGEX_PATTERN_TARGET = "^[A-Za-z]{2}(-.*)?$"; + + public static final String MDC_TRANSACTION_ID = "transactionId"; + public static final String MDC_SESSION_ID = "sessionId"; + + //AuthnRequest IssueInstant validation + public static final int TIME_JITTER = 5; //all 5 minutes time jitter + + public static final String PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH = "interfederationAuthentication"; + public static final String PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION = "requireLocalAuthentication"; + public static final String PROCESSCONTEXT_PERFORM_BKUSELECTION = "performBKUSelection"; + public static final String PROCESSCONTEXT_ISLEGACYREQUEST = "isLegacyRequest"; + + //General protocol-request data-store keys + public static final String AUTHPROCESS_DATA_TARGET = "authProces_Target"; + public static final String AUTHPROCESS_DATA_TARGETFRIENDLYNAME = "authProces_TargetFriendlyName"; + public static final String AUTHPROCESS_DATA_SECURITYLAYERTEMPLATE = "authProces_SecurityLayerTemplate"; + + //General MOASession data-store keys + public static final String MOASESSION_DATA_HOLDEROFKEY_CERTIFICATE = "holderofkey_cert"; + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/AuthConfiguration.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/AuthConfiguration.java new file mode 100644 index 000000000..fa08dcab6 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/AuthConfiguration.java @@ -0,0 +1,162 @@ +package at.gv.egovernment.moa.id.commons.api; + +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import at.gv.egovernment.moa.id.commons.api.data.ProtocolAllowed; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; +import at.gv.util.config.EgovUtilPropertiesConfiguration; + +public interface AuthConfiguration extends ConfigurationProvider{ + + public static final String DEFAULT_X509_CHAININGMODE = "pkix"; + + public Properties getGeneralPVP2ProperiesConfig(); + + public Properties getGeneralOAuth20ProperiesConfig(); + + public ProtocolAllowed getAllowedProtocols(); + + public Map getConfigurationWithPrefix(final String Prefix); + + public String getConfigurationWithKey(final String key); + + /** + * Get a configuration value from basic file based MOA-ID configuration + * + * @param key configuration key + * @return configuration value + */ + public String getBasicMOAIDConfiguration(final String key); + + public int getTransactionTimeOut(); + public int getSSOCreatedTimeOut(); + public int getSSOUpdatedTimeOut(); + + public String getAlternativeSourceID() throws ConfigurationException; + + public List getLegacyAllowedProtocols(); + + public IOAAuthParameters getOnlineApplicationParameter(String oaURL); + + public String getMoaSpAuthBlockTrustProfileID(boolean useTestTrustStore) throws ConfigurationException; + + public List getMoaSpAuthBlockVerifyTransformsInfoIDs() throws ConfigurationException; + + public ConnectionParameterInterface getMoaSpConnectionParameter() throws ConfigurationException; + + public ConnectionParameterInterface getForeignIDConnectionParameter() throws ConfigurationException; + + public ConnectionParameterInterface getOnlineMandatesConnectionParameter() throws ConfigurationException; + + public String getMoaSpIdentityLinkTrustProfileID(boolean useTestTrustStore) throws ConfigurationException; + + public List getTransformsInfos() throws ConfigurationException; + + public List getIdentityLinkX509SubjectNames() throws ConfigurationException; + + public List getSLRequestTemplates() throws ConfigurationException; + + public String getSLRequestTemplates(String type) throws ConfigurationException; + + public List getDefaultBKUURLs() throws ConfigurationException; + + public String getDefaultBKUURL(String type) throws ConfigurationException; + + public String getSSOTagetIdentifier() throws ConfigurationException; + + public String getSSOFriendlyName(); + + public String getSSOSpecialText(); + + public String getMOASessionEncryptionKey(); + + public String getMOAConfigurationEncryptionKey(); + + public boolean isIdentityLinkResigning(); + + public String getIdentityLinkResigningKey(); + + public boolean isMonitoringActive(); + + public String getMonitoringTestIdentityLinkURL(); + + public String getMonitoringMessageSuccess(); + + public boolean isAdvancedLoggingActive(); + + /** + * Returns the PublicURLPrefix. + * + * @return the PublicURLPrefix (one or more) of this IDP instance. All publicURLPrefix URLs are ends without / + * @throws ConfigurationException if no PublicURLPrefix is found. + */ + public List getPublicURLPrefix() throws ConfigurationException; + + public boolean isVirtualIDPsEnabled(); + + public boolean isPVP2AssertionEncryptionActive(); + + public boolean isCertifiacteQCActive(); + + public IStorkConfig getStorkConfig() throws ConfigurationException; + + public EgovUtilPropertiesConfiguration geteGovUtilsConfig(); + + public String getDocumentServiceUrl(); + + /** + * Notify, if the STORK fake IdentityLink functionality is active + * + * @return true/false + */ + public boolean isStorkFakeIdLActive(); + + /** + * Get a list of all STORK countries for which a faked IdentityLink should be created + * + * @return {List} of country codes + */ + public List getStorkFakeIdLCountries(); + + /** + * Get a list of all STORK countries for which no signature is required + * + * @return {List} of country codes + */ + public List getStorkNoSignatureCountries(); + + /** + * Get the MOA-SS key-group identifier for fake IdentityLink signing + * + * @return MOA-SS key-group identifier {String} + */ + public String getStorkFakeIdLResigningKey(); + + + /** + * Notify, if the PVP2x metadata schema validation is active + * + * @return true/false + */ + public boolean isPVPSchemaValidationActive(); + + /** + * Get all configuration values with prefix and wildcard + * + * @param key: Search key. * and % can be used as wildcards + * @return Key/Value pairs {Map}, which key maps the search key + */ + Map getConfigurationWithWildCard(String key); + + /** + * Get configured default revisions-log event codes which should be logged + * + * @return {List} if event codes or null + */ + List getDefaultRevisionsLogEventCodes(); + + @Deprecated + public boolean isHTTPAuthAllowed(); +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/ConfigurationProvider.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/ConfigurationProvider.java new file mode 100644 index 000000000..ca0a56049 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/ConfigurationProvider.java @@ -0,0 +1,66 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.commons.api; + +/** + * @author tlenz + * + */ +public interface ConfigurationProvider { + + /** + * The name of the system property which contains the file name of the + * configuration file. + */ + public static final String CONFIG_PROPERTY_NAME = + "moa.id.configuration"; + + /** + * The name of the system property which contains the file name of the + * configuration file. + */ + public static final String PROXY_CONFIG_PROPERTY_NAME = + "moa.id.proxy.configuration"; + + /** + * The name of the generic configuration property giving the certstore directory path. + */ + public static final String DIRECTORY_CERTSTORE_PARAMETER_PROPERTY = + "DirectoryCertStoreParameters.RootDir"; + + /** + * The name of the generic configuration property switching the ssl revocation checking on/off + */ + public static final String TRUST_MANAGER_REVOCATION_CHECKING = + "TrustManager.RevocationChecking"; + + public String getRootConfigFileDir(); + + public String getDefaultChainingMode(); + + public String getTrustedCACertificates(); + + public String getCertstoreDirectory(); + + public boolean isTrustmanagerrevoationchecking(); +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/ConnectionParameterInterface.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/ConnectionParameterInterface.java new file mode 100644 index 000000000..89a21661b --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/ConnectionParameterInterface.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.commons.api; + +public interface ConnectionParameterInterface { + + + public boolean isHTTPSURL(); + public String getUrl(); + public String getAcceptedServerCertificates(); + + public String getClientKeyStore(); + public String getClientKeyStorePassword(); + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IOAAuthParameters.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IOAAuthParameters.java new file mode 100644 index 000000000..be6d34275 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IOAAuthParameters.java @@ -0,0 +1,222 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.commons.api; + +import java.security.PrivateKey; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import at.gv.egovernment.moa.id.commons.api.data.CPEPS; +import at.gv.egovernment.moa.id.commons.api.data.SAML1ConfigurationParameters; +import at.gv.egovernment.moa.id.commons.api.data.StorkAttribute; +import at.gv.egovernment.moa.id.commons.api.data.StorkAttributeProviderPlugin; + +/** + * @author tlenz + * + */ +public interface IOAAuthParameters { + + public static final String ONLINEBKU = "online"; + public static final String HANDYBKU = "handy"; + public static final String LOCALBKU = "local"; + public static final String INDERFEDERATEDIDP = "interfederated"; + + /** + * Get the full key/value configuration for this online application + * + * @return an unmodifiable map of key/value pairs + */ + public Map getFullConfiguration(); + + /** + * Get a configuration value from online application key/value configuration + * + * @param key: The key identifier of a configuration value * + * @return The configuration value {String} or null if the key does not exist + */ + public String getConfigurationValue(String key); + + public String getFriendlyName(); + + public String getPublicURLPrefix(); + + public String getOaType(); + + public boolean getBusinessService(); + + /** + * Get target of a public service-provider + * + * @return target identifier without prefix + */ + public String getTarget(); + + public String getTargetFriendlyName(); + + public boolean isInderfederationIDP(); + + public boolean isSTORKPVPGateway(); + + public boolean isRemovePBKFromAuthBlock(); + + /** + * Return the private-service domain-identifier with PreFix + * + * @return the identityLinkDomainIdentifier + */ + public String getIdentityLinkDomainIdentifier(); + + /** + * @return the keyBoxIdentifier + */ + public String getKeyBoxIdentifier(); + + public SAML1ConfigurationParameters getSAML1Parameter(); + + /** + * Get a list of online application specific trusted security layer templates + * + * @return a {List} with template URLs, maybe empty but never null + */ + public List getTemplateURL(); + + + /** + * Return the additional AuthBlock text for this online application + * + * @return authblock text {String} or null if no text is configured + */ + public String getAditionalAuthBlockText(); + + /** + * Return an online application specific BKU URL for a requested BKU type + * + * @param bkutype: defines the type of BKU + * @return BKU URL {String} or null if no BKU URL is configured + */ + public String getBKUURL(String bkutype); + + /** + * Return a list of all configured BKU URLs for this online application + * + * @return List of BKU URLs or an empty list if no BKU is configured + */ + public List getBKUURL(); + + public boolean useSSO(); + + public boolean useSSOQuestion(); + + /** + * Return all mandate-profile types configured for this online application + * + * @return the mandateProfiles {List} or null if no profile is defined + */ + public List getMandateProfiles(); + + /** + * @return the identityLinkDomainIdentifierType + */ + public String getIdentityLinkDomainIdentifierType(); + + public boolean isShowMandateCheckBox(); + + public boolean isOnlyMandateAllowed(); + + /** + * Shall we show the stork login in the bku selection frontend? + * + * @return true, if is we should show stork login + */ + public boolean isShowStorkLogin(); + + public Integer getQaaLevel(); + + public boolean isRequireConsentForStorkAttributes(); + + /** + * Return a {Collection} of requested STORK attributes + * + * @return {Collection} maybe empty but never null + */ + public Collection getRequestedSTORKAttributes(); + + public byte[] getBKUSelectionTemplate(); + + public byte[] getSendAssertionTemplate(); + + /** + * Return a {Collection} of configured STORK CPEPS + * + * @return {Collection} maybe empty but never null + */ + public Collection getPepsList(); + + public String getIDPAttributQueryServiceURL(); + + /** + * @return + */ + boolean isInboundSSOInterfederationAllowed(); + + /** + * @return + */ + boolean isInterfederationSSOStorageAllowed(); + + /** + * @return + */ + boolean isOutboundSSOInterfederationAllowed(); + + boolean isTestCredentialEnabled(); + + List getTestCredentialOIDs(); + + boolean isUseIDLTestTrustStore(); + boolean isUseAuthBlockTestTestStore(); + + PrivateKey getBPKDecBpkDecryptionKey(); + + /** + * @return + */ + boolean isPassivRequestUsedForInterfederation(); + + /** + * @return + */ + boolean isPerformLocalAuthenticationOnInterfederationError(); + + /** + * Get a {Collection} of configured STORK attribute provider plug-ins + * + * @return {Collection} maybe empty but never null + */ + public Collection getStorkAPs(); + + public List getReversionsLoggingEventCodes(); + +} \ No newline at end of file diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IRequest.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IRequest.java new file mode 100644 index 000000000..b23b4474b --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IRequest.java @@ -0,0 +1,201 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.commons.api; + +import java.util.Collection; + +import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; + +public interface IRequest { + + /** + * Indicates the module, which implements this authentication protocol. + * The class, which is referenced, had to implement the 'IModulInfo' interface. + * + * @return Full-qualified name of the class which implements this protocol + */ + public String requestedModule(); + + /** + * Indicates the protocol specific action, which should executed if the request is processed. + * The class, which is referenced, had to implement the 'IAction' interface. + * + * @return Full-qualified name of the class which implements the action + */ + public String requestedAction(); + + /** + * Unique identifier, which indicates the service provider. + * In case of SAML1 protocol, it is the OA http-GET parameter + * + * @return Unique identifier for the service provider + */ + public String getOAURL(); + + /** + * Indicates the passive flag in authentication requests. + * If the passive flag is set, the identification and authentication process + * failed if no active SSO session is found. + * + * @return true, if the is passive flag is set in authentication request, otherwise false + */ + public boolean isPassiv(); + + /** + * Indicates the force authentication flag in authentication request + * If this flag is set, a new identification and authentication process + * is carried out in any case. + * + * @return true, if the force authentication flag is set, otherwise false + */ + public boolean forceAuth(); + + + /** + * Returns a generic request-data object with is stored with a specific identifier + * + * @param key The specific identifier of the request-data object + * @return The request-data object or null if no data is found with this key + */ + public Object getGenericData(String key); + + /** + * Returns a generic request-data object with is stored with a specific identifier + * + * @param key The specific identifier of the request-data object + * @param clazz The class type which is stored with this key + * @return The request-data object or null if no data is found with this key + */ + public T getGenericData(String key, final Class clazz); + + /** + * Store a generic data-object to request with a specific identifier + * + * @param key Identifier for this data-object + * @param object Generic data-object which should be stored. This data-object had to be implement the 'java.io.Serializable' interface + * @throws SessionDataStorageException Error message if the data-object can not stored to generic request-data storage + */ + public void setGenericDataToSession(String key, Object object) throws SessionDataStorageException; + + /** + * Hold the identifier of this request object. + * This identifier can be used to load the request from request storage + * + * @return Request identifier + */ + public String getRequestID(); + + + /** + * Hold the identifier of the MOASession which is associated with this request + * + * @return MOASession identifier if a associated session exists, otherwise null + */ + public String getMOASessionIdentifier(); + + + /** + * Holds a unique transaction identifier, which could be used for looging + * This transaction identifier is unique for a single identification and authentication process + * + * @return Unique transaction identifier. + */ + public String getUniqueTransactionIdentifier(); + + /** + * Holds a unique session identifier, which could be used for logging + * This session identifier is unique for the full Single Sign-On session time + * + * @return Unique session identifier + */ + public String getUniqueSessionIdentifier(); + + + /** + * Hold the identifier if the process instance, which is associated with this request + * + * @return ProcessInstanceID if this request is associated with a authentication process, otherwise null + */ + public String getProcessInstanceId(); + + + /** + * get the IDP URL PreFix, which was used for authentication request + * + * @return IDP URL PreFix . The URL prefix always ends without / + */ + public String getAuthURL(); + public String getAuthURLWithOutSlash(); + + /** + * Indicates if this pending request needs authentication + * + * @return true if this request needs authentication, otherwise false + */ + public boolean isNeedAuthentication(); + + /** + * Indicates, if this pending request needs Single Sign-On (SSO) functionality + * + * @return true if this request needs SSO, otherwise false + */ + public boolean needSingleSignOnFunctionality(); + public void setNeedSingleSignOnFunctionality(boolean needSSO); + + /** + * Indicates, if this pending request is already authenticated + * + * @return true if this request is already authenticated, otherwise false + */ + public boolean isAuthenticated(); + public void setAuthenticated(boolean isAuthenticated); + + /** + * Get get Service-Provider configuration which is associated with this request. + * + * @return Service-Provider configuration + */ + public IOAAuthParameters getOnlineApplicationConfiguration(); + + /** + * Indicates, if this pending-request is aborted by the user + * + * @return true, if it is aborted, otherwise false + */ + public boolean isAbortedByUser(); + + /** + * Set the 'isAboredByUser' flag of this pending-request + * + * @param b true, if the user has abort the authentication process, otherwise false + */ + public void setAbortedByUser(boolean isAborted); + + /** + * This method get a Set of PVP 2.1 attribute, which are request by this pending-request. + * + * @return A set of PVP attribute names or null if no attributes are requested + * or the Service Provider, which sends this request needs no attributes + */ + public Collection getRequestedAttributes(); +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IStorkConfig.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IStorkConfig.java new file mode 100644 index 000000000..b2d90aed4 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/IStorkConfig.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.commons.api; + +import java.util.List; +import java.util.Map; + +import at.gv.egovernment.moa.id.commons.api.data.CPEPS; +import at.gv.egovernment.moa.id.commons.api.data.SignatureCreationParameter; +import at.gv.egovernment.moa.id.commons.api.data.SignatureVerificationParameter; +import at.gv.egovernment.moa.id.commons.api.data.StorkAttribute; + +/** + * @author tlenz + * + */ +public interface IStorkConfig { + + SignatureCreationParameter getSignatureCreationParameter(); + + SignatureVerificationParameter getSignatureVerificationParameter(); + + Map getCpepsMap(); + + boolean isSTORKAuthentication(String ccc); + + CPEPS getCPEPS(String ccc); + + List getStorkAttributes(); + +} \ No newline at end of file diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/BPKDecryptionParameters.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/BPKDecryptionParameters.java new file mode 100644 index 000000000..cb81fe79e --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/BPKDecryptionParameters.java @@ -0,0 +1,135 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.commons.api.data; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.UnrecoverableKeyException; + +import org.apache.commons.lang3.SerializationUtils; + +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.KeyStoreUtils; + + +/** + * @author tlenz + * + */ +public class BPKDecryptionParameters implements Serializable{ + + private static final long serialVersionUID = 1L; + + private byte[] keyStore = null; + private String keyStorePassword = null; + private String keyAlias = null; + private String keyPassword = null; + + /** + * @return + * @throws IOException + */ + public PrivateKey getPrivateKey() { + InputStream in = null; + try { + in = new ByteArrayInputStream(keyStore); + KeyStore store = KeyStoreUtils.loadKeyStore(in , keyStorePassword); + + char[] chPassword = " ".toCharArray(); + if (keyPassword != null) + chPassword = keyPassword.toCharArray(); + +// Certificate test = store.getCertificate(keyAlias); +// Base64Utils.encode(test.getPublicKey().getEncoded()); + + return (PrivateKey) store.getKey(keyAlias, chPassword); + + + } catch (KeyStoreException e) { + Logger.error("Can not load private key from keystore.", e); + + } catch (IOException e) { + Logger.error("Can not load private key from keystore.", e); + + } catch (UnrecoverableKeyException e) { + Logger.error("Can not load private key from keystore.", e); + + } catch (NoSuchAlgorithmException e) { + Logger.error("Can not load private key from keystore.", e); + + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + Logger.warn("Close InputStream failed." , e); + } + } + } + + return null; + } + + public byte[] serialize() { + return SerializationUtils.serialize(this); + + } + + /** + * @param keyStore the keyStore to set + */ + public void setKeyStore(byte[] keyStore) { + this.keyStore = keyStore; + } + + /** + * @param keyStorePassword the keyStorePassword to set + */ + public void setKeyStorePassword(String keyStorePassword) { + this.keyStorePassword = keyStorePassword; + } + + /** + * @param keyAlias the keyAlias to set + */ + public void setKeyAlias(String keyAlias) { + this.keyAlias = keyAlias; + } + + /** + * @param keyPassword the keyPassword to set + */ + public void setKeyPassword(String keyPassword) { + this.keyPassword = keyPassword; + } + + + + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/CPEPS.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/CPEPS.java new file mode 100644 index 000000000..a88aa2171 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/CPEPS.java @@ -0,0 +1,138 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +/** + * + */ +package at.gv.egovernment.moa.id.commons.api.data; + +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.saml2.metadata.RequestedAttribute; + +/** + * Encpasulates C-PEPS information according MOA configuration + * + * @author bzwattendorfer + * + */ +public class CPEPS { + + /** Country Code of C-PEPS */ + private String countryCode; + + /** URL of C-PEPS */ + private URL pepsURL; + + private Boolean isXMLSignatureSupported; + + /** Specific attributes to be requested for this C-PEPS */ + private List countrySpecificRequestedAttributes = new ArrayList(); + + /** + * Constructs a C-PEPS + * @param countryCode ISO Country Code of C-PEPS + * @param pepsURL URL of C-PEPS + */ + public CPEPS(String countryCode, URL pepsURL, Boolean isXMLSignatureSupported) { + super(); + this.countryCode = countryCode; + this.pepsURL = pepsURL; + this.isXMLSignatureSupported = isXMLSignatureSupported; + } + + /** + * Gets the country code of this C-PEPS + * @return ISO country code + */ + public String getCountryCode() { + return countryCode; + } + + /** + * Sets the country code of this C-PEPS + * @param countryCode ISO country code + */ + public void setCountryCode(String countryCode) { + this.countryCode = countryCode; + } + + /** + * Gets the URL of this C-PEPS + * @return C-PEPS URL + */ + public URL getPepsURL() { + return pepsURL; + } + + /** + * Sets the C-PEPS URL + * @param pepsURL C-PEPS URL + */ + public void setPepsURL(URL pepsURL) { + this.pepsURL = pepsURL; + } + + /** + * Returns weather the C-PEPS supports XMl Signatures or not (important for ERnB) + */ + public Boolean isXMLSignatureSupported() { + return isXMLSignatureSupported; + } + + /** + * Sets weather the C-PEPS supports XMl Signatures or not (important for ERnB) + * @param isXMLSignatureSupported C-PEPS XML Signature support + */ + public void setXMLSignatureSupported(boolean isXMLSignatureSupported) { + this.isXMLSignatureSupported = isXMLSignatureSupported; + } + + /** + * Gets the country specific attributes of this C-PEPS + * @return List of country specific attributes + */ + public List getCountrySpecificRequestedAttributes() { + return countrySpecificRequestedAttributes; + } + + /** + * Sets the country specific attributes + * @param countrySpecificRequestedAttributes List of country specific requested attributes + */ + public void setCountrySpecificRequestedAttributes( + List countrySpecificRequestedAttributes) { + this.countrySpecificRequestedAttributes = countrySpecificRequestedAttributes; + } + + /** + * Adds a Requested attribute to the country specific attribute List + * @param countrySpecificRequestedAttribute Additional country specific requested attribute to add + */ + public void addCountrySpecificRequestedAttribute(RequestedAttribute countrySpecificRequestedAttribute) { + this.countrySpecificRequestedAttributes.add(countrySpecificRequestedAttribute); + } + + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/ProtocolAllowed.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/ProtocolAllowed.java new file mode 100644 index 000000000..4f63dca54 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/ProtocolAllowed.java @@ -0,0 +1,91 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.commons.api.data; + +/** + * @author tlenz + * + */ +public class ProtocolAllowed { + + private boolean isSAML1Active = false; + private boolean isPVP21Active = true; + private boolean isOAUTHActive = true; + + /** + * + */ + public ProtocolAllowed() { + + } + + /** + * + */ + public ProtocolAllowed(boolean saml1, boolean pvp21, boolean oauth) { + this.isOAUTHActive = oauth; + this.isPVP21Active = pvp21; + this.isSAML1Active = saml1; + + } + + /** + * @return the isSAML1Active + */ + public boolean isSAML1Active() { + return isSAML1Active; + } + /** + * @param isSAML1Active the isSAML1Active to set + */ + public void setSAML1Active(boolean isSAML1Active) { + this.isSAML1Active = isSAML1Active; + } + /** + * @return the isPVP21Active + */ + public boolean isPVP21Active() { + return isPVP21Active; + } + /** + * @param isPVP21Active the isPVP21Active to set + */ + public void setPVP21Active(boolean isPVP21Active) { + this.isPVP21Active = isPVP21Active; + } + /** + * @return the isOAUTHActive + */ + public boolean isOAUTHActive() { + return isOAUTHActive; + } + /** + * @param isOAUTHActive the isOAUTHActive to set + */ + public void setOAUTHActive(boolean isOAUTHActive) { + this.isOAUTHActive = isOAUTHActive; + } + + + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SAML1ConfigurationParameters.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SAML1ConfigurationParameters.java new file mode 100644 index 000000000..eb709a6f1 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SAML1ConfigurationParameters.java @@ -0,0 +1,276 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.commons.api.data; + +/** + * @author tlenz + * + */ +public class SAML1ConfigurationParameters { + + private boolean isActive = false; + private boolean provideBaseId = false; + private boolean provideAuthBlock = false; + private boolean provideIdl = false; + private boolean provideCertificate = false; + private boolean provideMandate = false; + private boolean provideAllErrors = true; + private boolean useCondition = false; + private String sourceID = null; + private String condition = new String(); + + + /** + * + */ + public SAML1ConfigurationParameters(boolean isActive, + boolean provideBaseId, boolean provideAuthBlock, + boolean provideIdl, boolean provideCertificate, + boolean provideMandate, boolean provideAllErrors, + boolean useCondition, String condition, + String sourceID) { + this.condition = condition; + this.isActive = isActive; + this.provideAllErrors = provideAllErrors; + this.provideAuthBlock = provideAuthBlock; + this.provideBaseId = provideBaseId; + this.provideCertificate = provideCertificate; + this.provideIdl = provideIdl; + this.provideMandate = provideMandate; + this.useCondition = useCondition; + this.sourceID = sourceID; + + } + + + /** + * + */ + public SAML1ConfigurationParameters() { + + } + + + /** + * Gets the value of the isActive property. + * + * @return + * possible object is + * {@link String } + * + */ + public Boolean isIsActive() { + return this.isActive; + } + + /** + * @param isActive the isActive to set + */ + public void setActive(boolean isActive) { + this.isActive = isActive; + } + + + /** + * @param provideBaseId the provideBaseId to set + */ + public void setProvideBaseId(boolean provideBaseId) { + this.provideBaseId = provideBaseId; + } + + + /** + * @param provideAuthBlock the provideAuthBlock to set + */ + public void setProvideAuthBlock(boolean provideAuthBlock) { + this.provideAuthBlock = provideAuthBlock; + } + + + /** + * @param provideIdl the provideIdl to set + */ + public void setProvideIdl(boolean provideIdl) { + this.provideIdl = provideIdl; + } + + + /** + * @param provideCertificate the provideCertificate to set + */ + public void setProvideCertificate(boolean provideCertificate) { + this.provideCertificate = provideCertificate; + } + + + /** + * @param provideMandate the provideMandate to set + */ + public void setProvideMandate(boolean provideMandate) { + this.provideMandate = provideMandate; + } + + + /** + * @param provideAllErrors the provideAllErrors to set + */ + public void setProvideAllErrors(boolean provideAllErrors) { + this.provideAllErrors = provideAllErrors; + } + + + /** + * @param useCondition the useCondition to set + */ + public void setUseCondition(boolean useCondition) { + this.useCondition = useCondition; + } + + + /** + * @param sourceID the sourceID to set + */ + public void setSourceID(String sourceID) { + this.sourceID = sourceID; + } + + + /** + * @param condition the condition to set + */ + public void setCondition(String condition) { + this.condition = condition; + } + + + /** + * Gets the value of the provideStammzahl property. + * + * @return + * possible object is + * {@link String } + * + */ + public Boolean isProvideStammzahl() { + return this.provideBaseId; + } + + /** + * Gets the value of the provideAUTHBlock property. + * + * @return + * possible object is + * {@link String } + * + */ + public Boolean isProvideAUTHBlock() { + return this.provideAuthBlock; + } + + /** + * Gets the value of the provideIdentityLink property. + * + * @return + * possible object is + * {@link String } + * + */ + public Boolean isProvideIdentityLink() { + return this.provideIdl; + } + + /** + * Gets the value of the provideCertificate property. + * + * @return + * possible object is + * {@link String } + * + */ + public Boolean isProvideCertificate() { + return this.provideCertificate; + } + + /** + * Gets the value of the provideFullMandatorData property. + * + * @return + * possible object is + * {@link String } + * + */ + public Boolean isProvideFullMandatorData() { + return this.provideMandate; + } + + /** + * Gets the value of the useCondition property. + * + * @return + * possible object is + * {@link String } + * + */ + public Boolean isUseCondition() { + return this.useCondition; + } + + /** + * Gets the value of the conditionLength property. + * + * @return + * possible object is + * {@link BigInteger } + * + */ + + public int getConditionLength() { + return condition.length(); + } + + /** + * Gets the value of the sourceID property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSourceID() { + return this.sourceID; + } + + /** + * Gets the value of the provideAllErrors property. + * + * @return + * possible object is + * {@link String } + * + */ + public Boolean isProvideAllErrors() { + return this.provideAllErrors; + } + +} + diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SignatureCreationParameter.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SignatureCreationParameter.java new file mode 100644 index 000000000..9bfd93977 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SignatureCreationParameter.java @@ -0,0 +1,103 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + ******************************************************************************/ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + +package at.gv.egovernment.moa.id.commons.api.data; + +import java.util.Properties; + +/** + * Encapsulates signature creation parameters according MOA configuration + * + * @author bzwattendorfer + * + */ +public class SignatureCreationParameter { + + private static final String PROPS_PREFIX = "stork.samlsigningparameter.signaturecreation."; + private static final String PROPS_KEYSTORE_FILE = "keystore.file"; + private static final String PROPS_KEYSTORE_PASS = "keystore.password"; + private static final String PROPS_KEYNAME_NAME = "keyname.name"; + private static final String PROPS_KEYNAME_PASS = "keyname.password"; + + private Properties props; + private String basedirectory; + + public SignatureCreationParameter(Properties props, String basedirectory) { + this.props = props; + this.basedirectory = basedirectory; + } + + /** + * Gets the KeyStore Path + * @return File Path to KeyStore + */ + public String getKeyStorePath() { + return basedirectory + props.getProperty(PROPS_PREFIX+PROPS_KEYSTORE_FILE); + } + + /** + * Gets the KeyStore Password + * @return Password to KeyStore + */ + public String getKeyStorePassword() { + return props.getProperty(PROPS_PREFIX+PROPS_KEYSTORE_PASS); + } + + /** + * Gets the Signing Key Name + * @return Siging Key Name + */ + public String getKeyName() { + return props.getProperty(PROPS_PREFIX+PROPS_KEYNAME_NAME); + } + + /** + * Gets the Signing Key Password + * @return Signing Key Password + */ + public String getKeyPassword() { + return props.getProperty(PROPS_PREFIX+PROPS_KEYNAME_PASS); + } +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SignatureVerificationParameter.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SignatureVerificationParameter.java new file mode 100644 index 000000000..f408ea7fe --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/SignatureVerificationParameter.java @@ -0,0 +1,53 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +/** + * + */ +package at.gv.egovernment.moa.id.commons.api.data; + +/** + * Encapsulates Signature Verification data for STORK according MOA configuration + * + * @author bzwattendorfer + * + */ +public class SignatureVerificationParameter { + + /** ID of the MOA-SP TrustProfile to be used for STORK SAML signature verification */ + private String trustProfileID; + + public SignatureVerificationParameter(String trustProfileID2) { + this.trustProfileID = trustProfileID2; + } + + /** + * Gets the MOA-SP TrustProfileID + * @return TrustProfileID of MOA-SP for STORK signature verification + */ + public String getTrustProfileID() { + return trustProfileID; + } + + + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/StorkAttribute.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/StorkAttribute.java new file mode 100644 index 000000000..1bbb7d3fe --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/StorkAttribute.java @@ -0,0 +1,27 @@ +package at.gv.egovernment.moa.id.commons.api.data; + +public class StorkAttribute { + + protected Boolean mandatory; + protected String name; + + public StorkAttribute(String name, boolean mandatory) { + this.name = name; + this.mandatory = mandatory; + } + + public Boolean getMandatory() { + return mandatory; + } + public void setMandatory(Boolean mandatory) { + this.mandatory = mandatory; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/StorkAttributeProviderPlugin.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/StorkAttributeProviderPlugin.java new file mode 100644 index 000000000..070d304a6 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/data/StorkAttributeProviderPlugin.java @@ -0,0 +1,81 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.commons.api.data; + +/** + * @author tlenz + * + */ +public class StorkAttributeProviderPlugin { + private String name = null; + private String url = null; + private String attributes = null; + + /** + * + */ + public StorkAttributeProviderPlugin(String name, String url, String attributes) { + this.name = name; + this.url = url; + this.attributes = attributes; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + /** + * @return the url + */ + public String getUrl() { + return url; + } + /** + * @param url the url to set + */ + public void setUrl(String url) { + this.url = url; + } + /** + * @return the attributes + */ + public String getAttributes() { + return attributes; + } + /** + * @param attributes the attributes to set + */ + public void setAttributes(String attributes) { + this.attributes = attributes; + } + + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/ConfigurationException.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/ConfigurationException.java new file mode 100644 index 000000000..e8f6da323 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/ConfigurationException.java @@ -0,0 +1,78 @@ +package at.gv.egovernment.moa.id.commons.api.exceptions; +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + ******************************************************************************/ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + +/** + * Exception signalling an error in the configuration. + * + * @author Patrick Peck + * @version $Id$ + */ +public class ConfigurationException extends MOAIDException { + + /** + * + */ + private static final long serialVersionUID = -7199539463319751278L; + +/** + * Create a MOAConfigurationException. + */ + public ConfigurationException(String messageId, Object[] parameters) { + super(messageId, parameters); + } + + /** + * Create a MOAConfigurationException. + */ + public ConfigurationException( + String messageId, + Object[] parameters, + Throwable wrapped) { + + super(messageId, parameters, wrapped); + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/MOAIDException.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/MOAIDException.java new file mode 100644 index 000000000..955b0f5ea --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/MOAIDException.java @@ -0,0 +1,222 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + ******************************************************************************/ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.id.commons.api.exceptions; + +import java.io.PrintStream; +import java.io.PrintWriter; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; +import at.gv.egovernment.moa.util.Constants; + +/** + * Base class of technical MOA exceptions. + * + * Technical exceptions are exceptions that originate from system failure (e.g., + * a database connection fails, a component is not available, etc.) + * + * @author Patrick Peck, Ivancsics Paul + * @version $Id$ + */ +public class MOAIDException extends Exception { + /** + * + */ + private static final long serialVersionUID = -1507246171708083912L; +/** message ID */ + private String messageId; + /** wrapped exception */ + private Throwable wrapped; + + private Object[] parameters; + + /** + * Create a new MOAIDException. + * + * @param messageId The identifier of the message associated with this + * exception. + * @param parameters Additional message parameters. + */ + public MOAIDException(String messageId, Object[] parameters) { + super(MOAIDMessageProvider.getInstance().getMessage(messageId, parameters)); + this.messageId = messageId; + this.parameters = parameters; + } + + /** + * Create a new MOAIDException. + * + * @param messageId The identifier of the message associated with this + * MOAIDException. + * @param parameters Additional message parameters. + * @param wrapped The exception wrapped by this + * MOAIDException. + */ + public MOAIDException( + String messageId, + Object[] parameters, + Throwable wrapped) { + + super(MOAIDMessageProvider.getInstance().getMessage(messageId, parameters)); + this.messageId = messageId; + this.wrapped = wrapped; + this.parameters = parameters; + } + + /** + * Print a stack trace of this exception to System.err. + * + * @see java.lang.Throwable#printStackTrace() + */ + public void printStackTrace() { + printStackTrace(System.err); + } + + /** + * Print a stack trace of this exception, including the wrapped exception. + * + * @param s The stream to write the stack trace to. + * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) + */ + public void printStackTrace(PrintStream s) { + if (getWrapped() == null) + super.printStackTrace(s); + else { + s.print("Root exception: "); + getWrapped().printStackTrace(s); + } + } + + /** + * Print a stack trace of this exception, including the wrapped exception. + * + * @param s The stream to write the stacktrace to. + * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) + */ + public void printStackTrace(PrintWriter s) { + if (getWrapped() == null) + super.printStackTrace(s); + else { + s.print("Root exception: "); + getWrapped().printStackTrace(s); + } + } + + /** + * @return message ID + */ + public String getMessageId() { + return messageId; + } + + /** + * @return wrapped exception + */ + public Throwable getWrapped() { + return wrapped; + } + + + + /** + * @return the parameters + */ +public Object[] getParameters() { + return parameters; +} + +/** + * Convert this MOAIDException to an ErrorResponse + * element from the MOA namespace. + * + * @return An ErrorResponse element, containing the subelements + * ErrorCode and Info required by the MOA schema. + */ + public Element toErrorResponse() { + DocumentBuilder builder; + DOMImplementation impl; + Document doc; + Element errorResponse; + Element errorCode; + Element info; + + // create a new document + try { + builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + impl = builder.getDOMImplementation(); + } catch (ParserConfigurationException e) { + return null; + } + + // build the ErrorResponse element + doc = impl.createDocument(Constants.MOA_NS_URI, "ErrorResponse", null); + errorResponse = doc.getDocumentElement(); + + // add MOA namespace declaration + errorResponse.setAttributeNS( + Constants.XMLNS_NS_URI, + "xmlns", + Constants.MOA_NS_URI); + + // build the child elements + errorCode = doc.createElementNS(Constants.MOA_NS_URI, "ErrorCode"); + errorCode.appendChild(doc.createTextNode(messageId)); + info = doc.createElementNS(Constants.MOA_NS_URI, "Info"); + info.appendChild(doc.createTextNode(toString())); + errorResponse.appendChild(errorCode); + errorResponse.appendChild(info); + return errorResponse; + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/SessionDataStorageException.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/SessionDataStorageException.java new file mode 100644 index 000000000..9414556a2 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/SessionDataStorageException.java @@ -0,0 +1,45 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.commons.api.exceptions; + +/** + * @author tlenz + * + */ +public class SessionDataStorageException extends MOAIDException { + + /** + * + */ + private static final long serialVersionUID = 5743057708136365929L; + + /** + * @param messageId + * @param parameters + */ + public SessionDataStorageException(String messageId, Object[] parameters) { + super(messageId, parameters); + + } + +} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/utils/MOAIDMessageProvider.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/utils/MOAIDMessageProvider.java new file mode 100644 index 000000000..4d8a07a55 --- /dev/null +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/utils/MOAIDMessageProvider.java @@ -0,0 +1,104 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + ******************************************************************************/ +/* + * Copyright 2003 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * 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: + * http://www.osor.eu/eupl/ + * + * 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. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ + + +package at.gv.egovernment.moa.id.commons.utils; + +import java.util.Locale; + +import at.gv.egovernment.moa.util.Messages; + +/** + * A singleton wrapper around a Message object, providing the messages used in MOA-ID. + * + * @author Paul Ivancsics + * @version $Id$ + */ +public class MOAIDMessageProvider { + + /** DEFAULT_MESSAGE_RESOURCES are resources/properties/id_messages */ + private static final String[] DEFAULT_MESSAGE_RESOURCES = + { "resources/properties/id_messages" }; + /** DEFAULT_MESSAGE_LOCALES are "de", "AT" */ + private static final Locale[] DEFAULT_MESSAGE_LOCALES = + new Locale[] { new Locale("de", "AT") }; + /** The instance for our singleton */ + private static MOAIDMessageProvider instance; + /** The Messages */ + private Messages messages; + + /** + * Returns the single instance of MOAIDMessageProvider. + * + * @return the single instance of MOAIDMessageProvider + */ + public static MOAIDMessageProvider getInstance() { + if (instance == null) + instance = new MOAIDMessageProvider(DEFAULT_MESSAGE_RESOURCES, DEFAULT_MESSAGE_LOCALES); + return instance; + } + + /** + * Create a MOAIDMessageProvider. + * + * @param resourceNames The names of the resources containing the messages. + * @param locales The corresponding locales. + */ + protected MOAIDMessageProvider(String[] resourceNames, Locale[] locales) { + this.messages = new Messages(resourceNames, locales); + } + + /** + * Get the message corresponding to a given message ID. + * + * @param messageId The ID of the message. + * @param parameters The parameters to fill in into the message arguments. + * @return The formatted message. + */ + public String getMessage(String messageId, Object[] parameters) { + return messages.getMessage(messageId, parameters); + } + +} -- cgit v1.2.3 From f1c588836f613209984c15a761d65b20c66ca4e9 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 13:29:52 +0100 Subject: add missing error codes --- .../id/commons/api/exceptions/MOAIDException.java | 52 ---------------------- 1 file changed, 52 deletions(-) (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/MOAIDException.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/MOAIDException.java index 955b0f5ea..6841be92b 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/MOAIDException.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/api/exceptions/MOAIDException.java @@ -49,16 +49,7 @@ package at.gv.egovernment.moa.id.commons.api.exceptions; import java.io.PrintStream; import java.io.PrintWriter; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; -import at.gv.egovernment.moa.util.Constants; /** * Base class of technical MOA exceptions. @@ -176,47 +167,4 @@ public Object[] getParameters() { return parameters; } -/** - * Convert this MOAIDException to an ErrorResponse - * element from the MOA namespace. - * - * @return An ErrorResponse element, containing the subelements - * ErrorCode and Info required by the MOA schema. - */ - public Element toErrorResponse() { - DocumentBuilder builder; - DOMImplementation impl; - Document doc; - Element errorResponse; - Element errorCode; - Element info; - - // create a new document - try { - builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - impl = builder.getDOMImplementation(); - } catch (ParserConfigurationException e) { - return null; - } - - // build the ErrorResponse element - doc = impl.createDocument(Constants.MOA_NS_URI, "ErrorResponse", null); - errorResponse = doc.getDocumentElement(); - - // add MOA namespace declaration - errorResponse.setAttributeNS( - Constants.XMLNS_NS_URI, - "xmlns", - Constants.MOA_NS_URI); - - // build the child elements - errorCode = doc.createElementNS(Constants.MOA_NS_URI, "ErrorCode"); - errorCode.appendChild(doc.createTextNode(messageId)); - info = doc.createElementNS(Constants.MOA_NS_URI, "Info"); - info.appendChild(doc.createTextNode(toString())); - errorResponse.appendChild(errorCode); - errorResponse.appendChild(info); - return errorResponse; - } - } -- cgit v1.2.3 From 54a26c8e353069abacefe5232f8270bec6b3cc60 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 15:49:24 +0100 Subject: update libs --- .../id/commons/db/dao/session/AssertionStore.java | 4 +- .../db/dao/session/AuthenticatedSessionStore.java | 4 +- .../id/commons/db/dao/session/ExceptionStore.java | 125 --------------------- .../dao/session/InterfederationSessionStore.java | 4 +- .../id/commons/db/dao/session/OASessionStore.java | 4 +- .../db/dao/session/OldSSOSessionIDStore.java | 4 +- .../id/commons/db/dao/statistic/StatisticLog.java | 4 +- 7 files changed, 6 insertions(+), 143 deletions(-) delete mode 100644 id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/ExceptionStore.java (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AssertionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AssertionStore.java index a49142d87..c2f5ec962 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AssertionStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AssertionStore.java @@ -27,8 +27,6 @@ import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.NamedQueries; @@ -52,7 +50,7 @@ public class AssertionStore implements Serializable{ private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + //@GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", unique=true, nullable=false) private long id; diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java index a8cc1928e..6333451b9 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java @@ -31,8 +31,6 @@ import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.NamedQueries; @@ -67,7 +65,7 @@ public class AuthenticatedSessionStore implements Serializable{ private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + //@GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", unique=true, nullable=false) private long id; diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/ExceptionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/ExceptionStore.java deleted file mode 100644 index 0d56896ff..000000000 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/ExceptionStore.java +++ /dev/null @@ -1,125 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * 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: - * http://www.osor.eu/eupl/ - * - * 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. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.commons.db.dao.session; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.Table; - -import org.hibernate.annotations.DynamicUpdate; - - - -@Entity -@DynamicUpdate(value=true) -@Table(name = "exceptionstore") -@NamedQueries({ - @NamedQuery(name="getExceptionWithID", query = "select exceptionstore from ExceptionStore exceptionstore where exceptionstore.exid = :id"), - @NamedQuery(name="getExceptionWithTimeOut", query = "select exceptionstore from ExceptionStore exceptionstore where exceptionstore.timestamp < :timeout") -}) - -public class ExceptionStore implements Serializable{ - - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id", unique=true, nullable=false) - private long id; - - @Column(name = "exid", unique=true, nullable=false) - private String exid; - - @Column(name = "exception", nullable=false) - @Lob private byte [] exception; - - @Column(name = "timestamp", nullable=false) - private Date timestamp; - - /** - * @return the id - */ - public long getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(long id) { - this.id = id; - } - - /** - * @return the exid - */ - public String getExid() { - return exid; - } - - /** - * @param exid the exid to set - */ - public void setExid(String exid) { - this.exid = exid; - } - - /** - * @return the exception - */ - public byte[] getException() { - return exception; - } - - /** - * @param exception the exception to set - */ - public void setException(byte[] exception) { - this.exception = exception; - } - - /** - * @return the timestamp - */ - public Date getTimestamp() { - return timestamp; - } - - /** - * @param timestamp the timestamp to set - */ - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } - - -} diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/InterfederationSessionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/InterfederationSessionStore.java index 54216edc4..c62e8be32 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/InterfederationSessionStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/InterfederationSessionStore.java @@ -28,8 +28,6 @@ import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @@ -46,7 +44,7 @@ public class InterfederationSessionStore implements Serializable{ private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + //@GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", unique=true, nullable=false) private long id; diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java index 44ae43115..a11d94af4 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java @@ -28,8 +28,6 @@ import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @@ -46,7 +44,7 @@ public class OASessionStore implements Serializable{ private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + //@GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "idOASession", unique=true, nullable=false) private long idOASession; diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OldSSOSessionIDStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OldSSOSessionIDStore.java index a85bdf2ca..195406a37 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OldSSOSessionIDStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OldSSOSessionIDStore.java @@ -27,8 +27,6 @@ import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @@ -51,7 +49,7 @@ public class OldSSOSessionIDStore implements Serializable{ private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + //@GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "idOldSSOSession", unique=true, nullable=false) private long idOldSSOSession; diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/statistic/StatisticLog.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/statistic/StatisticLog.java index 97f26812f..6040d9870 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/statistic/StatisticLog.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/statistic/StatisticLog.java @@ -27,8 +27,6 @@ import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; @@ -50,7 +48,7 @@ public class StatisticLog implements Serializable{ private static final long serialVersionUID = 1L; @Id - @GeneratedValue(strategy = GenerationType.AUTO) + //@GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", unique=true, nullable=false) private long id; -- cgit v1.2.3 From b819b1f8cd82383fd2b2ed63dc71f6ac23fa9731 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 24 Mar 2016 13:25:04 +0100 Subject: fix problem in moa-id-configuration with duplicate entries and delete operation --- .../moa/id/commons/db/NewConfigurationDBRead.java | 43 ++++++++++++++++------ 1 file changed, 31 insertions(+), 12 deletions(-) (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/NewConfigurationDBRead.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/NewConfigurationDBRead.java index 28c705c71..e2f793edf 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/NewConfigurationDBRead.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/NewConfigurationDBRead.java @@ -248,30 +248,49 @@ public class NewConfigurationDBRead { * @param id * @return */ - public OnlineApplication getOnlineApplication(String id) { + public List getOnlineApplications(String id) { Logger.trace("Getting OnlineApplication with ID " + id + " from database."); // select onlineapplication from OnlineApplication onlineapplication // where onlineapplication.publicURLPrefix = SUBSTRING(:id, 1, LENGTH(onlineapplication.publicURLPrefix)) - OnlineApplication result = null; + List result = new ArrayList(); List allOAs = getAllOnlineApplications(); for (OnlineApplication oa : nullGuard(allOAs)) { - String publicUrlPrefix = oa.getPublicURLPrefix(); - if (publicUrlPrefix != null && publicUrlPrefix.length() <= id.length()) { - if (id.substring(0, publicUrlPrefix.length()).equals(publicUrlPrefix)) { - if (result != null) { - Logger.warn("OAIdentifier match to more then one DB-entry!"); - return null; - } else { - result = oa; - } - } + String publicUrlPrefix = oa.getPublicURLPrefix(); + if (publicUrlPrefix != null && publicUrlPrefix.length() <= id.length()) { + if (id.substring(0, publicUrlPrefix.length()).equals(publicUrlPrefix)) + result.add(oa); + } } return result; } + + /** + * + * @param id + * @return + */ + public OnlineApplication getOnlineApplication(String id) { + Logger.trace("Getting OnlineApplication with ID " + id + " from database."); + + // select onlineapplication from OnlineApplication onlineapplication + // where onlineapplication.publicURLPrefix = SUBSTRING(:id, 1, LENGTH(onlineapplication.publicURLPrefix)) + List result = getOnlineApplications(id); + + if (result != null && result.size() == 1) + return result.get(0); + + else if (result != null && result.size() > 1) + Logger.warn("OAIdentifier match to more then one DB-entry!"); + + else + Logger.warn("no OA with OAIdentifier: "+ id); + + return null; + } /** * -- cgit v1.2.3 From bd53025fa776091cd82d0fca57a28a5404fb4f37 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 30 Mar 2016 08:36:03 +0200 Subject: fix problem with XML parser and additional features options --- .../java/at/gv/egovernment/moa/util/DOMUtils.java | 97 ++++++++++++++++++++-- 1 file changed, 89 insertions(+), 8 deletions(-) (limited to 'id/server/moa-id-commons/src/main/java') diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java index 0a07fc4a7..95cd63643 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/DOMUtils.java @@ -33,6 +33,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.Vector; @@ -115,7 +116,7 @@ public class DOMUtils { private static final String EXTERNAL_PARAMETER_ENTITIES_FEATURE = "http://xml.org/sax/features/external-parameter-entities"; - private static final String DISALLOW_DOCTYPE_FEATURE = + public static final String DISALLOW_DOCTYPE_FEATURE = "http://apache.org/xml/features/disallow-doctype-decl"; @@ -205,7 +206,8 @@ public class DOMUtils { String externalSchemaLocations, String externalNoNamespaceSchemaLocation, EntityResolver entityResolver, - ErrorHandler errorHandler) + ErrorHandler errorHandler, + Map parserFeatures) throws SAXException, IOException, ParserConfigurationException { DOMParser parser; @@ -247,8 +249,25 @@ public class DOMUtils { parser.setFeature(EXTERNAL_GENERAL_ENTITIES_FEATURE, false); parser.setFeature(EXTERNAL_PARAMETER_ENTITIES_FEATURE, false); + //set external added parser features + if (parserFeatures != null) { + for (Entry el : parserFeatures.entrySet()) { + String key = el.getKey(); + if (MiscUtil.isNotEmpty(key)) { + Object value = el.getValue(); + if (value != null && value instanceof Boolean) + parser.setFeature(key, (boolean)value); + + else + Logger.warn("This XML parser only allows features with 'boolean' values"); + + } else + Logger.warn("Can not set 'null' feature to XML parser"); + } + } + //fix XXE problem - parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + //parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); if (validating) { @@ -346,6 +365,7 @@ public class DOMUtils { * @param externalNoNamespaceSchemaLocation The schema location of the * schema for elements without a namespace, the same way it is accepted by the * xsi:noNamespaceSchemaLocation attribute. + * @param parserFeatures * @return The parsed XML document as a DOM tree. * @throws SAXException An error occurred parsing the document. * @throws IOException An error occurred reading the document. @@ -356,7 +376,7 @@ public class DOMUtils { InputStream inputStream, boolean validating, String externalSchemaLocations, - String externalNoNamespaceSchemaLocation) + String externalNoNamespaceSchemaLocation, Map parserFeatures) throws SAXException, IOException, ParserConfigurationException { @@ -367,9 +387,50 @@ public class DOMUtils { externalSchemaLocations, externalNoNamespaceSchemaLocation, new MOAEntityResolver(), - new MOAErrorHandler()); + new MOAErrorHandler(), + parserFeatures); } + /** + * Parse an XML document from a String. + * + * It uses a MOAEntityResolver as the EntityResolver + * and a MOAErrorHandler as the ErrorHandler. + * + * @param xmlString The String containing the XML document. + * @param encoding The encoding of the XML document. + * @param validating If true, parse validating. + * @param externalSchemaLocations A String containing namespace + * URI to schema location pairs, the same way it is accepted by the xsi: + * schemaLocation attribute. + * @param externalNoNamespaceSchemaLocation The schema location of the + * schema for elements without a namespace, the same way it is accepted by the + * xsi:noNamespaceSchemaLocation attribute. + * @return The parsed XML document as a DOM tree. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML + * parser. + */ + public static Document parseDocument( + String xmlString, + String encoding, + boolean validating, + String externalSchemaLocations, + String externalNoNamespaceSchemaLocation, + Map parserFeatures) + throws SAXException, IOException, ParserConfigurationException { + + InputStream in = new ByteArrayInputStream(xmlString.getBytes(encoding)); + return parseDocument( + in, + validating, + externalSchemaLocations, + externalNoNamespaceSchemaLocation, + parserFeatures); + } + + /** * Parse an XML document from a String. * @@ -404,7 +465,8 @@ public class DOMUtils { in, validating, externalSchemaLocations, - externalNoNamespaceSchemaLocation); + externalNoNamespaceSchemaLocation, + null); } /** @@ -453,7 +515,26 @@ public class DOMUtils { public static Element parseXmlValidating(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { return DOMUtils - .parseDocument(inputStream, true, Constants.ALL_SCHEMA_LOCATIONS, null) + .parseDocument(inputStream, true, Constants.ALL_SCHEMA_LOCATIONS, null, null) + .getDocumentElement(); + } + + /** + * A convenience method to parse an XML document validating. + * + * @param inputStream The InputStream containing the XML + * document. + * @param parserFeatures Set additional features to XML parser + * @return The root element of the parsed XML document. + * @throws SAXException An error occurred parsing the document. + * @throws IOException An error occurred reading the document. + * @throws ParserConfigurationException An error occurred configuring the XML + * parser. + */ + public static Element parseXmlValidating(InputStream inputStream, Map parserFeatures) + throws ParserConfigurationException, SAXException, IOException { + return DOMUtils + .parseDocument(inputStream, true, Constants.ALL_SCHEMA_LOCATIONS, null, parserFeatures) .getDocumentElement(); } @@ -471,7 +552,7 @@ public class DOMUtils { public static Element parseXmlNonValidating(InputStream inputStream) throws ParserConfigurationException, SAXException, IOException { return DOMUtils - .parseDocument(inputStream, false, Constants.ALL_SCHEMA_LOCATIONS, null) + .parseDocument(inputStream, false, Constants.ALL_SCHEMA_LOCATIONS, null, null) .getDocumentElement(); } -- cgit v1.2.3