perfsonar-dev - [pS-dev] [GEANT/SA2/ps-java-services] r6010 - in trunk/perfsonar_base/src/main/java/org/perfsonar: base/auxiliary base/auxiliary/components/authn base/auxiliary/components/authn/wssec base/auxiliary/components/configuration base/auxiliary/components/configuration/properties base/auxiliary/components/context base/auxiliary/components/context/inMemory base/auxiliary/components/logger base/auxiliary/components/logger/log4j base/auxiliary/components/mapping base/auxiliary/components/scheduler base/auxiliary/components/scheduler/actions base/auxiliary/components/simplescheduler base/exceptions base/nmwg/owamp base/util base/util/iptrie service/base/authn service/base/authn/tokens service/base/container/listeners service/base/engine service/base/measurementExecutor service/base/messages service/base/registration service/base/storage service/base/storage/xmldb service/base/storage/xmldb/exist service/base/storage/xmldb/exist/rest service/base/storage/xmldb/exist/xmlrpc service/base/ storage/xmlfile service/base/transport service/base/util service/base/web service/measurementArchive/eventTypeConfig service/measurementArchive/metadataConfig service/measurementArchive/metadataConfig/keyGenerator service/measurementArchive/metadataConfig/queryGenerator service/measurementArchive/register
Subject: perfsonar development work
List archive
[pS-dev] [GEANT/SA2/ps-java-services] r6010 - in trunk/perfsonar_base/src/main/java/org/perfsonar: base/auxiliary base/auxiliary/components/authn base/auxiliary/components/authn/wssec base/auxiliary/components/configuration base/auxiliary/components/configuration/properties base/auxiliary/components/context base/auxiliary/components/context/inMemory base/auxiliary/components/logger base/auxiliary/components/logger/log4j base/auxiliary/components/mapping base/auxiliary/components/scheduler base/auxiliary/components/scheduler/actions base/auxiliary/components/simplescheduler base/exceptions base/nmwg/owamp base/util base/util/iptrie service/base/authn service/base/authn/tokens service/base/container/listeners service/base/engine service/base/measurementExecutor service/base/messages service/base/registration service/base/storage service/base/storage/xmldb service/base/storage/xmldb/exist service/base/storage/xmldb/exist/rest service/base/storage/xmldb/exist/xmlrpc service/base/ storage/xmlfile service/base/transport service/base/util service/base/web service/measurementArchive/eventTypeConfig service/measurementArchive/metadataConfig service/measurementArchive/metadataConfig/keyGenerator service/measurementArchive/metadataConfig/queryGenerator service/measurementArchive/register
Chronological Thread
- From:
- To:
- Subject: [pS-dev] [GEANT/SA2/ps-java-services] r6010 - in trunk/perfsonar_base/src/main/java/org/perfsonar: base/auxiliary base/auxiliary/components/authn base/auxiliary/components/authn/wssec base/auxiliary/components/configuration base/auxiliary/components/configuration/properties base/auxiliary/components/context base/auxiliary/components/context/inMemory base/auxiliary/components/logger base/auxiliary/components/logger/log4j base/auxiliary/components/mapping base/auxiliary/components/scheduler base/auxiliary/components/scheduler/actions base/auxiliary/components/simplescheduler base/exceptions base/nmwg/owamp base/util base/util/iptrie service/base/authn service/base/authn/tokens service/base/container/listeners service/base/engine service/base/measurementExecutor service/base/messages service/base/registration service/base/storage service/base/storage/xmldb service/base/storage/xmldb/exist service/base/storage/xmldb/exist/rest service/base/storage/xmldb/exist/xmlrpc service/base/ storage/xmlfile service/base/transport service/base/util service/base/web service/measurementArchive/eventTypeConfig service/measurementArchive/metadataConfig service/measurementArchive/metadataConfig/keyGenerator service/measurementArchive/metadataConfig/queryGenerator service/measurementArchive/register
- Date: Fri, 5 Oct 2012 10:22:44 +0100 (BST)
Author: nordunet.behrmann
Date: 2012-10-05 10:22:44 +0100 (Fri, 05 Oct 2012)
New Revision: 6010
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryComponentManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryThreadedComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/ComponentNames.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/ComponentsConfigurationReader.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/AuthNComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/DynamicCrypto.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/SOAPUtil.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/wssec/WSSecAuthNComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/configuration/ConfigurationComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/configuration/properties/PropertiesConfigurationComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/context/PerfsonarContextComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/context/inMemory/InMemoryContext.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/logger/LoggerComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/logger/log4j/Log4jLoggerComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/mapping/ExpressionMapping.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/ScheduleMessageHandler.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/ScheduleMessageParser.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/Scheduler.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/actions/GenericSchedulerAction.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/actions/SchedulerAction.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/Scheduler.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/SchedulerAction.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/SchedulerTask.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/exceptions/PerfSONARException.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/nmwg/owamp/Parameters.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/MathUtil.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/NetUtil.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/StringBufferOutputStream.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/TimeDateUtil.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/XMLUtils.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/Constants.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/HelperClass.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IPAddress.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IPAddressConvertor.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/InvalidIPAddressException.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IpTrie.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IpTrieNode.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/StringBufferUtilities.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/SummarizeIpAddrs.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/Trie.java
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/TrieNode.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchProtocol.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchProtocolFactory.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchSOAPProtocol.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AttrRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AttrResponse.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthNRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthNResponse.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthRRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthRResponse.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenManagerFactory.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenSOAPManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecurityToken.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/container/listeners/StartupInitializer.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ActionType.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ServiceEngine.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ServiceEngineFactory.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/measurementExecutor/MeasurementExecutor.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AttrEERequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AuthNEERequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AuthREERequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/BaseChaining.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/CompleteMetadataStoreRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/DataRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/EchoRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSCleanupRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSDeregisterRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSKeepaliveRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSQueryRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSRegisterRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LinkRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LookupInfoRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementArchiveStoreKeyRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementArchiveStoreRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MessageHandler.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MessageHandlerFactory.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MetadataKeyRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/Request.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SetupDataDBRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SetupDataRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SubscriptionKeepaliveRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SubscriptionRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/TOPSRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/UnSubscriptionRequest.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/GenericServiceLSRegistrator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationContextServiceContent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationExistDbXmlrpcServiceContent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationXMLFileServiceContent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSListAddresses.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSRegistrationComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSSummaryServiceContent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/PropertiesServiceDescription.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceContent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceDescription.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceLSRegistrator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/DataRepository.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/GenericXmlStorageManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/NMWGStorageManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/StorageManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbConstants.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbDataRepository.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbResult.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbStorageManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/ExistDbFactory.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/ExistDbGenericStorageManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbErrorException.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHTTPAccess.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHttpXmlDataRepository.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHttpXmlStorageManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/HTTPAccess.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/HTTPResult.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/xmlrpc/ExistDbXmlrpcXmlDataRepository.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/xmlrpc/ExistDbXmlrpcXmlStorageManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmlfile/XmlFileDataRepository.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmlfile/XmlFileStorageManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/FileTransport.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/FileTransportFactory.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/Location.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/SSHFileTransport.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/util/ResultCodesUtil.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/web/RequestHandler.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventType.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventTypeConfiguration.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventTypeConfigurationComponent.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/MetadataConfigurationStorageManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/SimpleMetadataConfigurationStorageManager.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/Transformations.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/L2PathStatusKeyGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/MetadataKeyGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/MetadataKeyGeneratorFactory.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/BwctlQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/DiscardsQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/ErrorsQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/IperfQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/L2PathStatusQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/L2PathStatusQueryGeneratorTMP.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/MetadataQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/MetadataQueryGeneratorFactory.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/OwampQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/PingQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/RandomFetchTestQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/UtilizationQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/XmlDbAccessTestQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/XmlDbContentTestQueryGenerator.java
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/register/LSRegistrationComponent.java
Log:
perfsonar_base: Reformat code
Among other things, this should get rid of any tab indentation.
Issue: PSSERVICES-588
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -7,13 +7,14 @@
* controlled by AuxiliaryComponentManager.
*
* @author Maciej Glowiak
- *
*/
-public interface AuxiliaryComponent {
+public interface AuxiliaryComponent
+{
/**
* Method used for initialize AuxiliaryComponent
+ *
* @throws SystemException
*/
public void initComponent() throws PerfSONARException;
@@ -21,12 +22,14 @@
/**
* Get component name
+ *
* @return name as String
*/
public String getComponentName();
/**
* Set component name
+ *
* @param name name of component
*/
public void setComponentName(String name);
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryComponentManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryComponentManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryComponentManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -17,7 +17,7 @@
* AuxiliaryComponentManager is a register for components - modules of
* the application. It loads components mapping from its configuration file,
* defined in components.properties system property.
- *
+ * <p/>
* AuxiliaryComponentManager may be either a standalone application or a
* static, persistent part of Axis servlet
*
@@ -25,56 +25,62 @@
* @author Uros Juvan (added componentsIterator)
* @author Michael Bischoff
*/
-public class AuxiliaryComponentManager {
-
- private final static Logger logger =
Logger.getLogger(AuxiliaryComponentManager.class.getName());
-
+public class AuxiliaryComponentManager
+{
+
+ private final static Logger logger =
Logger.getLogger(AuxiliaryComponentManager.class.getName());
+
// -----------------------------------------------------------------
Static
/**
* Static reference to Auxiliary Component Manager
*/
private static AuxiliaryComponentManager componentManager = new
AuxiliaryComponentManager();
- private static final Object initialiseMutex = new Object();
+ private static final Object initialiseMutex = new Object();
- private static volatile boolean initialised;
- private static volatile boolean isInitialising;
+ private static volatile boolean initialised;
+ private static volatile boolean isInitialising;
// ----------------------------------------------------- Instance
variables
/**
* Map of components (component_name, component object reference)
*/
- private ConcurrentMap<String,AuxiliaryComponent> components = new
ConcurrentHashMap<String,AuxiliaryComponent>();
+ private ConcurrentMap<String, AuxiliaryComponent> components = new
ConcurrentHashMap<String, AuxiliaryComponent>();
- private String webInfLocation;
+ private String webInfLocation;
- private File tempDirectory;
+ private File tempDirectory;
// ------------------------------------------------------------
Constructor
+
/**
* Private constructor - object can be created by static getInstance()
* method (singleton pattern) only
*/
- private AuxiliaryComponentManager() {}
+ private AuxiliaryComponentManager()
+ {
+ }
// --------------------------------------------------------- Public
methods
+
/**
* Set up the manager. Load mappings from components.properties file
* and creates all component objects
*/
- public boolean initManager() throws PerfSONARException {
- //read components from Configuration file and init them
+ public boolean initManager() throws PerfSONARException
+ {
+ //read components from Configuration file and init them
//String configFileName =
"/projects/sonar/perfsonar/conf/components.properties";
File componentsProperties =
lookupFile("/perfsonar/conf/components.properties");
- if(componentsProperties==null) {
+ if (componentsProperties == null) {
throw new PerfSONARException(
- "AuxiliaryComponentManager.initManager: " +
+ "AuxiliaryComponentManager.initManager: " +
"Missing or unable to locate components.properties file.
Cannot continue"
);
}
- logger.info("AuxiliaryComponentManager.initManager: Read config file
name as: "+componentsProperties);
+ logger.info("AuxiliaryComponentManager.initManager: Read config file
name as: " + componentsProperties);
try {
//read configfile into properties (name, value)
ArrayList<ComponentsConfigurationReader.Entry> properties = new
ComponentsConfigurationReader().readFile(componentsProperties.getCanonicalPath());
@@ -85,26 +91,26 @@
String componentClassName = e.getValue();
try {
- logger.fine("AUX ComponentManager creating
["+componentName+"] = "+componentClassName);
+ logger.fine("AUX ComponentManager creating [" +
componentName + "] = " + componentClassName);
AuxiliaryComponent component =
loadComponent(componentName, componentClassName);
- logger.finer("AUX ComponentManager: init
["+componentName+"]");
+ logger.finer("AUX ComponentManager: init [" +
componentName + "]");
component.initComponent();
} catch (PerfSONARException ex) {
-
logger.throwing(AuxiliaryComponentManager.class.getName(), "initmanager()",
ex);
+
logger.throwing(AuxiliaryComponentManager.class.getName(), "initmanager()",
ex);
//do nothing - not critical exception, just load other
modules
}
}
} catch (FileNotFoundException e) {
throw new PerfSONARException(
- "error.common.manager.no_configuration",
- "AuxiliaryComponentManager: Cannot load
component.properties file, because the file could not be found",
- e
+ "error.common.manager.no_configuration",
+ "AuxiliaryComponentManager: Cannot load component.properties
file, because the file could not be found",
+ e
);
} catch (IOException e) {
throw new PerfSONARException(
- "error.common.manager.no_configuration",
- "AuxiliaryComponentManager: Cannot load
component.properties file. Encountered IO Exception.",
- e
+ "error.common.manager.no_configuration",
+ "AuxiliaryComponentManager: Cannot load component.properties
file. Encountered IO Exception.",
+ e
);
}
@@ -112,7 +118,7 @@
}
- /**
+ /**
* This method loads a component. It creates Component object, adds
* it to components map and initializes it.
*
@@ -120,18 +126,19 @@
* @param componentClassName
* @throws PerfSONARException
*/
- public AuxiliaryComponent loadComponent(String componentName, String
componentClassName) throws PerfSONARException {
+ public AuxiliaryComponent loadComponent(String componentName, String
componentClassName) throws PerfSONARException
+ {
- if(components.containsKey(componentName)) {
- return components.get(componentName);
- }
-
+ if (components.containsKey(componentName)) {
+ return components.get(componentName);
+ }
+
AuxiliaryComponent component;
try {
//create component from classname
Class<?> componentClass = Class.forName(componentClassName);
- component = (AuxiliaryComponent)componentClass.newInstance();
+ component = (AuxiliaryComponent) componentClass.newInstance();
//set component name
component.setComponentName(componentName);
@@ -140,18 +147,18 @@
setComponent(componentName, component);
} catch (ClassNotFoundException ex) {
String m = "AUXComponentManager: " +
- "can't create component ["+componentName+"]. " +
- "Encountered ClassNotFound Exception. Message: "+ex.getMessage();
+ "can't create component [" + componentName + "]. " +
+ "Encountered ClassNotFound Exception. Message: " +
ex.getMessage();
throw new
PerfSONARException("error.common.manager.cant_create_component", m);
} catch (InstantiationException ex) {
String m = "AUXComponentManager: " +
- "can't create component ["+componentName+"]. " +
- "Encountered Instantiation Exception. Message: "+ex.getMessage();
+ "can't create component [" + componentName + "]. " +
+ "Encountered Instantiation Exception. Message: " +
ex.getMessage();
throw new
PerfSONARException("error.common.manager.cant_create_component", m);
} catch (IllegalAccessException ex) {
String m = "AUXComponentManager: " +
- "can't create component ["+componentName+"]. " +
- "Encountered IllegalAccess Exception. Message: "+ex.getMessage();
+ "can't create component [" + componentName + "]. " +
+ "Encountered IllegalAccess Exception. Message: " +
ex.getMessage();
throw new
PerfSONARException("error.common.manager.cant_create_component", m);
}
@@ -161,27 +168,33 @@
/**
* Put component into component map
- * @param name name of the component
+ *
+ * @param name name of the component
* @param component object
*/
- protected void setComponent(String name, AuxiliaryComponent component) {
+ protected void setComponent(String name, AuxiliaryComponent component)
+ {
components.put(name, component);
}
/**
* Return component for specified mapping
+ *
* @param name name of the component
* @return Auxiliary Component
*/
- public AuxiliaryComponent getComponent(String name) {
+ public AuxiliaryComponent getComponent(String name)
+ {
return components.get(name);
}
/**
* Return key,value pair iterator over components Map.
+ *
* @return iterator over pair Map.Entry<String, AuxiliaryComponent>
*/
- public Iterator<Map.Entry<String, AuxiliaryComponent>>
componentsIterator() {
+ public Iterator<Map.Entry<String, AuxiliaryComponent>>
componentsIterator()
+ {
return components == null ? null : components.entrySet().iterator();
@@ -189,40 +202,45 @@
/**
* Should be set and thus this shouldn't return null
+ *
* @return temp directory that exist can be read and written to or null
- * if this
{@link
AuxiliaryComponentManager} was incorrectly configured
+ * if this
{@link
AuxiliaryComponentManager} was incorrectly configured
*/
- public File getTempDirectory() {
- return tempDirectory;
+ public File getTempDirectory()
+ {
+ return tempDirectory;
}
// --------------------------------------------------------- static
methods
+
/**
* Method creates Auxiliary Component Manager and load all components.
* It's singleton pattern
- *
+ * <p/>
* TODO remove exception from signature.
*/
- public static AuxiliaryComponentManager getInstance() throws
PerfSONARException {
- // initialation must be lazy because of AxisMessageContext.
- if(!initialised) {
- synchronized (initialiseMutex) {
- // avoid other threads from also initialising
- // defend against endless loop. (calling
getInstance() within initManager();)
- if(!initialised && !isInitialising) {
- isInitialising = true;
- initialised = componentManager.initManager();
- isInitialising = false;
- }
- }
- }
+ public static AuxiliaryComponentManager getInstance() throws
PerfSONARException
+ {
+ // initialation must be lazy because of AxisMessageContext.
+ if (!initialised) {
+ synchronized (initialiseMutex) {
+ // avoid other threads from also initialising
+ // defend against endless loop. (calling getInstance()
within initManager();)
+ if (!initialised && !isInitialising) {
+ isInitialising = true;
+ initialised = componentManager.initManager();
+ isInitialising = false;
+ }
+ }
+ }
return componentManager;
}
/**
* For stand-alone applications
*/
- public static void main(String[] args) throws PerfSONARException {
+ public static void main(String[] args) throws PerfSONARException
+ {
//components.properties =
projects/sonar/perfsonar/conf/components.properties
AuxiliaryComponentManager.getInstance();
@@ -231,79 +249,86 @@
/**
* Provides a consistent way to lookup files within perfSONAR.
+ *
* @return File at the specified location or null if not found.
*/
- public static File lookupFile(String location) {
- logger.fine("Looking up file: "+location);
-
- if(location == null) {
- return null;
- }
-
- URL url;
- // try WEB-INF
- logger.finer("WEB-INF:"+componentManager.webInfLocation);
- if(componentManager.webInfLocation != null) {
- if(location.startsWith("/")) {
- url = componentManager.getClass().getResource(
- componentManager.webInfLocation +
location
- );
- } else {
- url = componentManager.getClass().getResource(
-
componentManager.webInfLocation + "/" + location
- );
- }
- if(url != null) {
- return new File(url.getFile());
- }
- }
-
- // try class path
- url = componentManager.getClass().getResource(location);
- if(url!=null) {
- return new File(url.getFile());
- }
-
- // try absolute
- File file = new File(location);
- return (file.exists()) ? file : null;
- }
+ public static File lookupFile(String location)
+ {
+ logger.fine("Looking up file: " + location);
+ if (location == null) {
+ return null;
+ }
+
+ URL url;
+ // try WEB-INF
+ logger.finer("WEB-INF:" + componentManager.webInfLocation);
+ if (componentManager.webInfLocation != null) {
+ if (location.startsWith("/")) {
+ url = componentManager.getClass().getResource(
+ componentManager.webInfLocation + location
+ );
+ } else {
+ url = componentManager.getClass().getResource(
+ componentManager.webInfLocation + "/" + location
+ );
+ }
+ if (url != null) {
+ return new File(url.getFile());
+ }
+ }
+
+ // try class path
+ url = componentManager.getClass().getResource(location);
+ if (url != null) {
+ return new File(url.getFile());
+ }
+
+ // try absolute
+ File file = new File(location);
+ return (file.exists()) ? file : null;
+ }
+
/**
* Set the WebInf Location, a application doesn't necessarily need to do
this.
+ *
* @param location
*/
- public static void setWebInfLocation(String location) {
- logger.fine("WEB-INF location set to: " +location);
- // normalise
- String normalisedLocation = slashify(location);
- logger.finer("location normalised to: "+normalisedLocation);
-
- if(location.endsWith(File.pathSeparator) || location.endsWith("/")) {
- componentManager.webInfLocation =
normalisedLocation.substring(0, location.length()-1);
- } else {
- componentManager.webInfLocation = normalisedLocation;
- }
+ public static void setWebInfLocation(String location)
+ {
+ logger.fine("WEB-INF location set to: " + location);
+ // normalise
+ String normalisedLocation = slashify(location);
+ logger.finer("location normalised to: " + normalisedLocation);
+
+ if (location.endsWith(File.pathSeparator) || location.endsWith("/"))
{
+ componentManager.webInfLocation =
normalisedLocation.substring(0, location.length() - 1);
+ } else {
+ componentManager.webInfLocation = normalisedLocation;
+ }
}
/**
* Sets the temp directory of the application this needs to be set.
+ *
* @param directory
*/
- public static void setTempDirectory(File directory) {
- if(!directory.exists()) throw new IllegalArgumentException("Temp
directory doesn't exist.");
- if(!directory.canRead()) throw new IllegalArgumentException("Temp
directory can't be read");
- if(!directory.canWrite()) throw new IllegalArgumentException("Temp
directory can't be written to.");
- componentManager.tempDirectory = directory;
+ public static void setTempDirectory(File directory)
+ {
+ if (!directory.exists()) throw new IllegalArgumentException("Temp
directory doesn't exist.");
+ if (!directory.canRead()) throw new IllegalArgumentException("Temp
directory can't be read");
+ if (!directory.canWrite()) throw new IllegalArgumentException("Temp
directory can't be written to.");
+ componentManager.tempDirectory = directory;
}
- private static String slashify(String path) {
- String p = path;
- if (File.separatorChar != '/')
- p = p.replace(File.separatorChar, '/');
- if (!p.startsWith("/"))
- p = "/" + p;
- return p;
- }
+ private static String slashify(String path)
+ {
+ String p = path;
+ if (File.separatorChar != '/')
+ p = p.replace(File.separatorChar, '/');
+ if (!p.startsWith("/"))
+ p = "/" + p;
+ return p;
+ }
} //AuxiliaryComponentManager
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryThreadedComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryThreadedComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/AuxiliaryThreadedComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -6,9 +6,9 @@
* stop method, causing threaded components to stop.
*
* @author Uros Juvan
- *
*/
-public interface AuxiliaryThreadedComponent extends AuxiliaryComponent {
+public interface AuxiliaryThreadedComponent extends AuxiliaryComponent
+{
/**
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/ComponentNames.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/ComponentNames.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/ComponentNames.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -4,9 +4,9 @@
* Interface contains common component names
*
* @author Maciej Glowiak
- *
*/
-public interface ComponentNames {
+public interface ComponentNames
+{
public static final String CONFIG = "config";
@@ -18,9 +18,11 @@
public static final String AUTHN = "authn";
- /** The context aux-component is a simple in-application map
- * that allows sharing of data */
- public static final String CONTEXT = "context";
+ /**
+ * The context aux-component is a simple in-application map
+ * that allows sharing of data
+ */
+ public static final String CONTEXT = "context";
} //ComponentNames
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/ComponentsConfigurationReader.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/ComponentsConfigurationReader.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/ComponentsConfigurationReader.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -8,21 +8,24 @@
/**
* ComponentsConfigurationReader is simple reader of a config -
* properties file.
- *
+ * <p/>
* It parses file and stores property name and value as ordered
* ArrayList<ComponentsConfigurationReader.Entry>
+ *
* @author Maciej Glowiak
- *
*/
-public class ComponentsConfigurationReader {
+public class ComponentsConfigurationReader
+{
/**
* Reads properties file and returns an ArrayList of Entry (pair of
* strings: name and value )
+ *
* @return ArrayList of Entry
* @throws IOException
*/
- public ArrayList<Entry> readFile(String filename) throws IOException {
+ public ArrayList<Entry> readFile(String filename) throws IOException
+ {
ArrayList<Entry> listProperties = new ArrayList<Entry>();
BufferedReader input;
@@ -33,9 +36,9 @@
String trimmed = line.trim();
if ((!trimmed.isEmpty()) && // not empty
- (!trimmed.startsWith("#")) && // not a comment
- (trimmed.contains("=")) // contains EQ sign
- ) {
+ (!trimmed.startsWith("#")) && // not a comment
+ (trimmed.contains("=")) // contains EQ sign
+ ) {
// split by [spaces]=[spaces]
String[] tokens = trimmed.split("(\\ |\\t)*\\=(\\ |\\t)*",
2);
if (tokens.length == 2)
@@ -50,21 +53,25 @@
// --------------------------------------------------- Inner class
- public class Entry {
+ public class Entry
+ {
private String name;
private String value;
- public Entry(String name, String value) {
- this.name=name;
- this.value=value;
+ public Entry(String name, String value)
+ {
+ this.name = name;
+ this.value = value;
}
- public String getName() {
+ public String getName()
+ {
return name;
}
- public String getValue() {
+ public String getValue()
+ {
return value;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/AuthNComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/AuthNComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/AuthNComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,16 +2,17 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-public interface AuthNComponent {
- public static final String CHECK_AUTHN_PARAM =
"service.as.authn_active";
- public static final String YES_CHECK_AUTHN = "on";
- public static final String LIST_MSG_AUTHN =
"service.as.authn_for_msg_types";
-
- public static final String CHECK_AUTHR_PARAM =
"service.as.authr_active";
- public static final String YES_CHECK_AUTHR = "on";
- public static final String LIST_MSG_AUTHR =
"service.as.authr_for_msg_types";
+public interface AuthNComponent
+{
+ public static final String CHECK_AUTHN_PARAM = "service.as.authn_active";
+ public static final String YES_CHECK_AUTHN = "on";
+ public static final String LIST_MSG_AUTHN =
"service.as.authn_for_msg_types";
- public void requestAuthN(String messageType) throws
PerfSONARException;
+ public static final String CHECK_AUTHR_PARAM = "service.as.authr_active";
+ public static final String YES_CHECK_AUTHR = "on";
+ public static final String LIST_MSG_AUTHR =
"service.as.authr_for_msg_types";
- public void requestAuthR(String messageType,String eventType) throws
PerfSONARException;
+ public void requestAuthN(String messageType) throws PerfSONARException;
+
+ public void requestAuthR(String messageType, String eventType) throws
PerfSONARException;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/DynamicCrypto.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/DynamicCrypto.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/DynamicCrypto.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -35,32 +35,36 @@
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.X509NameTokenizer;
-public class DynamicCrypto implements Crypto {
+public class DynamicCrypto implements Crypto
+{
private static Log log = LogFactory.getLog(DynamicCrypto.class);
protected static CertificateFactory certFact;
protected Properties properties = null;
protected KeyStore keystore = null;
static String SKI_OID = "2.5.29.14";
- public DynamicCrypto() throws CredentialException {
- properties=new Properties();
- try {
- keystore= KeyStore.getInstance("PKCS12");
- keystore.load(null, "petete".toCharArray());
- } catch (Exception e) {
+ public DynamicCrypto() throws CredentialException
+ {
+ properties = new Properties();
+ try {
+ keystore = KeyStore.getInstance("PKCS12");
+ keystore.load(null, "petete".toCharArray());
+ } catch (Exception e) {
e.printStackTrace();
throw new CredentialException(3, "cryptError00", e);
- }
+ }
}
- public DynamicCrypto(KeyStore ks) {
- properties=new Properties();
- this.keystore=ks;
+ public DynamicCrypto(KeyStore ks)
+ {
+ properties = new Properties();
+ this.keystore = ks;
}
- @Override
+ @Override
public String getAliasForX509Cert(Certificate cert)
- throws WSSecurityException {
+ throws WSSecurityException
+ {
try {
String alias = keystore.getCertificateAlias(cert);
if (alias != null)
@@ -76,22 +80,24 @@
}
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
+ "keystore");
}
return null;
- }
+ }
- @Override
- public String getAliasForX509Cert(String issuer) throws
WSSecurityException {
+ @Override
+ public String getAliasForX509Cert(String issuer) throws
WSSecurityException
+ {
return getAliasForX509Cert(issuer, null, false);
- }
+ }
- @Override
- public String getAliasForX509Cert(byte[] skiBytes) throws
WSSecurityException {
+ @Override
+ public String getAliasForX509Cert(byte[] skiBytes) throws
WSSecurityException
+ {
Certificate cert;
try {
- for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements();) {
+ for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements(); ) {
String alias = e.nextElement();
Certificate[] certs = keystore.getCertificateChain(alias);
if (certs == null || certs.length == 0) {
@@ -116,16 +122,17 @@
}
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
+ "keystore");
}
return null;
- }
+ }
- @Override
+ @Override
public String getAliasForX509Cert(String issuer, BigInteger serialNumber)
- throws WSSecurityException {
+ throws WSSecurityException
+ {
return getAliasForX509Cert(issuer, serialNumber, true);
- }
+ }
/*
* need to check if "getCertificateChain" also finds certificates
that are
@@ -135,49 +142,51 @@
* (this should work as well).
* --- remains to be tested in several ways --
*/
- private String getAliasForX509Cert(String issuer, BigInteger
serialNumber,
- boolean useSerialNumber)
- throws WSSecurityException {
- Vector<String> issuerRDN = splitAndTrim(issuer);
- X509Certificate x509cert;
- Vector<String> certRDN;
- Certificate cert;
+ private String getAliasForX509Cert(String issuer, BigInteger
serialNumber,
+ boolean useSerialNumber)
+ throws WSSecurityException
+ {
+ Vector<String> issuerRDN = splitAndTrim(issuer);
+ X509Certificate x509cert;
+ Vector<String> certRDN;
+ Certificate cert;
- try {
- for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements();) {
- String alias = e.nextElement();
- Certificate[] certs =
keystore.getCertificateChain(alias);
- if (certs == null || certs.length == 0) {
- // no cert chain, so lets check if getCertificate
gives us a result.
- cert = keystore.getCertificate(alias);
- if (cert == null) {
- return null;
- }
- } else {
- cert = certs[0];
- }
- if (!(cert instanceof X509Certificate)) {
- continue;
- }
- x509cert = (X509Certificate) cert;
- if (!useSerialNumber ||
- useSerialNumber &&
x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
- certRDN =
splitAndTrim(x509cert.getIssuerDN().getName());
- if (certRDN.equals(issuerRDN)) {
- return alias;
- }
- }
- }
- } catch (KeyStoreException e) {
- throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
- }
- return null;
- }
+ try {
+ for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements(); ) {
+ String alias = e.nextElement();
+ Certificate[] certs = keystore.getCertificateChain(alias);
+ if (certs == null || certs.length == 0) {
+ // no cert chain, so lets check if getCertificate gives
us a result.
+ cert = keystore.getCertificate(alias);
+ if (cert == null) {
+ return null;
+ }
+ } else {
+ cert = certs[0];
+ }
+ if (!(cert instanceof X509Certificate)) {
+ continue;
+ }
+ x509cert = (X509Certificate) cert;
+ if (!useSerialNumber ||
+ useSerialNumber &&
x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
+ certRDN = splitAndTrim(x509cert.getIssuerDN().getName());
+ if (certRDN.equals(issuerRDN)) {
+ return alias;
+ }
+ }
+ }
+ } catch (KeyStoreException e) {
+ throw new WSSecurityException(WSSecurityException.FAILURE,
+ "keystore");
+ }
+ return null;
+ }
- @Override
+ @Override
public String getAliasForX509CertThumb(byte[] thumb)
- throws WSSecurityException {
+ throws WSSecurityException
+ {
Certificate cert;
MessageDigest sha;
@@ -185,11 +194,11 @@
sha = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e1) {
throw new WSSecurityException(
- 0,
- "noSHA1availabe");
+ 0,
+ "noSHA1availabe");
}
try {
- for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements();) {
+ for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements(); ) {
String alias = e.nextElement();
Certificate[] certs = keystore.getCertificateChain(alias);
if (certs == null || certs.length == 0) {
@@ -209,8 +218,8 @@
sha.update(cert.getEncoded());
} catch (CertificateEncodingException e1) {
throw new WSSecurityException(
- WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "encodeError");
+ WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
+ "encodeError");
}
byte[] data = sha.digest();
@@ -220,12 +229,13 @@
}
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
+ "keystore");
}
return null;
- }
+ }
- private Vector<String> splitAndTrim(String inString) {
+ private Vector<String> splitAndTrim(String inString)
+ {
X509NameTokenizer nmTokens = new X509NameTokenizer(inString);
Vector<String> vr = new Vector<String>();
@@ -236,8 +246,9 @@
return vr;
}
- @Override
- public String[] getAliasesForDN(String subjectDN) throws
WSSecurityException {
+ @Override
+ public String[] getAliasesForDN(String subjectDN) throws
WSSecurityException
+ {
// Store the aliases found
Vector<String> aliases = new Vector<String>();
@@ -249,7 +260,7 @@
// Look at every certificate in the keystore
try {
- for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements();) {
+ for (Enumeration<String> e = keystore.aliases();
e.hasMoreElements(); ) {
String alias = e.nextElement();
Certificate[] certs = keystore.getCertificateChain(alias);
@@ -272,7 +283,7 @@
}
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
+ "keystore");
}
// Convert the vector into an array
@@ -281,11 +292,12 @@
result[i] = aliases.elementAt(i);
return result;
- }
+ }
- @Override
+ @Override
public byte[] getCertificateData(boolean reverse, X509Certificate[]
certs)
- throws WSSecurityException {
+ throws WSSecurityException
+ {
Vector<X509Certificate> list = new Vector<X509Certificate>();
for (X509Certificate cert : certs) {
if (reverse) {
@@ -299,16 +311,17 @@
return path.getEncoded();
} catch (CertificateEncodingException e) {
throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "encodeError");
+ "encodeError");
} catch (CertificateException e) {
throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "parseError");
+ "parseError");
}
- }
+ }
- @Override
+ @Override
public synchronized CertificateFactory getCertificateFactory()
- throws WSSecurityException {
+ throws WSSecurityException
+ {
if (certFact == null) {
try {
String provider =
properties.getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
@@ -319,18 +332,19 @@
}
} catch (CertificateException e) {
throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "unsupportedCertType");
+ "unsupportedCertType");
} catch (NoSuchProviderException e) {
throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "noSecProvider");
+ "noSecProvider");
}
}
return certFact;
- }
+ }
- @Override
+ @Override
public X509Certificate[] getCertificates(String alias)
- throws WSSecurityException {
+ throws WSSecurityException
+ {
Certificate[] certs;
try {
certs = keystore.getCertificateChain(alias);
@@ -344,30 +358,33 @@
}
} catch (KeyStoreException e) {
throw new WSSecurityException(WSSecurityException.FAILURE,
- "keystore");
+ "keystore");
}
X509Certificate[] x509certs = new X509Certificate[certs.length];
for (int i = 0; i < certs.length; i++) {
x509certs[i] = (X509Certificate) certs[i];
}
return x509certs;
- }
+ }
- @Override
- public String getDefaultX509Alias() {
+ @Override
+ public String getDefaultX509Alias()
+ {
if (properties == null) {
return null;
}
return
properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.alias");
- }
+ }
- @Override
- public KeyStore getKeyStore() {
+ @Override
+ public KeyStore getKeyStore()
+ {
return this.keystore;
- }
+ }
- @Override
- public PrivateKey getPrivateKey(String alias, String password) throws
Exception {
+ @Override
+ public PrivateKey getPrivateKey(String alias, String password) throws
Exception
+ {
if (alias == null) {
throw new Exception("alias is null");
}
@@ -381,65 +398,67 @@
throw new Exception("Key is not a private key, alias: " + alias);
}
return (PrivateKey) keyTmp;
- }
+ }
- @Override
+ @Override
public byte[] getSKIBytesFromCert(X509Certificate cert)
- throws WSSecurityException {
+ throws WSSecurityException
+ {
/*
* Gets the DER-encoded OCTET string for the extension value
(extnValue)
* identified by the passed-in oid String. The oid string is
represented
* by a set of positive whole numbers separated by periods.
*/
- byte[] derEncodedValue = cert.getExtensionValue(SKI_OID);
+ byte[] derEncodedValue = cert.getExtensionValue(SKI_OID);
- if (cert.getVersion() < 3 || derEncodedValue == null) {
- PublicKey key = cert.getPublicKey();
- if (!(key instanceof RSAPublicKey)) {
- throw new WSSecurityException(
- 1,
- "noSKIHandling",
- new Object[]{"Support for RSA key only"});
- }
- byte[] encoded = key.getEncoded();
- // remove 22-byte algorithm ID and header
- byte[] value = new byte[encoded.length - 22];
- System.arraycopy(encoded, 22, value, 0, value.length);
- MessageDigest sha;
- try {
- sha = MessageDigest.getInstance("SHA-1");
- } catch (NoSuchAlgorithmException ex) {
- throw new WSSecurityException(
- 1,
- "noSKIHandling",
- new Object[]{"Wrong certificate version (<3) and no
SHA1 message digest availabe"});
- }
- sha.reset();
- sha.update(value);
- return sha.digest();
- }
+ if (cert.getVersion() < 3 || derEncodedValue == null) {
+ PublicKey key = cert.getPublicKey();
+ if (!(key instanceof RSAPublicKey)) {
+ throw new WSSecurityException(
+ 1,
+ "noSKIHandling",
+ new Object[]{"Support for RSA key only"});
+ }
+ byte[] encoded = key.getEncoded();
+ // remove 22-byte algorithm ID and header
+ byte[] value = new byte[encoded.length - 22];
+ System.arraycopy(encoded, 22, value, 0, value.length);
+ MessageDigest sha;
+ try {
+ sha = MessageDigest.getInstance("SHA-1");
+ } catch (NoSuchAlgorithmException ex) {
+ throw new WSSecurityException(
+ 1,
+ "noSKIHandling",
+ new Object[]{"Wrong certificate version (<3) and no SHA1
message digest availabe"});
+ }
+ sha.reset();
+ sha.update(value);
+ return sha.digest();
+ }
- /**
- * Strip away first four bytes from the DerValue (tag and length of
- * ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING)
- */
- byte abyte0[] = new byte[derEncodedValue.length - 4];
+ /**
+ * Strip away first four bytes from the DerValue (tag and length of
+ * ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING)
+ */
+ byte abyte0[] = new byte[derEncodedValue.length - 4];
- System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length);
- return abyte0;
- }
+ System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length);
+ return abyte0;
+ }
- @Override
+ @Override
@SuppressWarnings("unchecked") // the data must only contain
X509Certificates
- public X509Certificate[] getX509Certificates(byte[] data, boolean
reverse)
- throws WSSecurityException {
+ public X509Certificate[] getX509Certificates(byte[] data, boolean
reverse)
+ throws WSSecurityException
+ {
InputStream in = new ByteArrayInputStream(data);
CertPath path;
try {
path = getCertificateFactory().generateCertPath(in);
} catch (CertificateException e) {
throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "parseError");
+ "parseError");
}
List<X509Certificate> l = (List<X509Certificate>)
path.getCertificates();
X509Certificate[] certs = new X509Certificate[l.size()];
@@ -448,56 +467,58 @@
certs[(reverse) ? (l.size() - 1 - i) : i] = iterator.next();
}
return certs;
- }
+ }
- @Override
+ @Override
public X509Certificate loadCertificate(InputStream in)
- throws WSSecurityException {
+ throws WSSecurityException
+ {
X509Certificate cert;
try {
cert =
- (X509Certificate)
getCertificateFactory().generateCertificate(in);
+ (X509Certificate)
getCertificateFactory().generateCertificate(in);
} catch (CertificateException e) {
throw new
WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
- "parseError");
+ "parseError");
}
return cert;
- }
+ }
- @Override
+ @Override
public boolean validateCertPath(X509Certificate[] certs)
- throws WSSecurityException {
- try {
- // Generate cert path
- List<X509Certificate> certList =
java.util.Arrays.asList(certs);
- CertPath path =
this.getCertificateFactory().generateCertPath(certList);
+ throws WSSecurityException
+ {
+ try {
+ // Generate cert path
+ List<X509Certificate> certList = java.util.Arrays.asList(certs);
+ CertPath path =
this.getCertificateFactory().generateCertPath(certList);
- // Use the certificates in the keystore as
TrustAnchors
- PKIXParameters param = new
PKIXParameters(this.keystore);
+ // Use the certificates in the keystore as TrustAnchors
+ PKIXParameters param = new PKIXParameters(this.keystore);
- // Do not check a revocation list
- param.setRevocationEnabled(false);
+ // Do not check a revocation list
+ param.setRevocationEnabled(false);
- // Verify the trust path using the above settings
- String provider = properties
-
.getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
- CertPathValidator certPathValidator;
- if (provider == null || provider.isEmpty()) {
- certPathValidator =
CertPathValidator.getInstance("PKIX");
- } else {
- certPathValidator =
CertPathValidator.getInstance("PKIX",
-
provider);
- }
- certPathValidator.validate(path, param);
- } catch (GeneralSecurityException ex) {
- throw new WSSecurityException(
- WSSecurityException.FAILURE,
- "certpath",
- new Object[] { ex.getMessage() },
- ex
- );
- }
- return true;
- }
+ // Verify the trust path using the above settings
+ String provider = properties
+
.getProperty("org.apache.ws.security.crypto.merlin.cert.provider");
+ CertPathValidator certPathValidator;
+ if (provider == null || provider.isEmpty()) {
+ certPathValidator = CertPathValidator.getInstance("PKIX");
+ } else {
+ certPathValidator = CertPathValidator.getInstance("PKIX",
+ provider);
+ }
+ certPathValidator.validate(path, param);
+ } catch (GeneralSecurityException ex) {
+ throw new WSSecurityException(
+ WSSecurityException.FAILURE,
+ "certpath",
+ new Object[]{ex.getMessage()},
+ ex
+ );
+ }
+ return true;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/SOAPUtil.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/SOAPUtil.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/SOAPUtil.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -9,7 +9,8 @@
import org.apache.xml.security.c14n.Canonicalizer;
import org.w3c.dom.Document;
-public class SOAPUtil {
+public class SOAPUtil
+{
/**
* Convert a DOM Document into a soap message.
@@ -19,9 +20,10 @@
* @return
* @throws Exception
*/
- public static SOAPMessage toSOAPMessage(Document doc) throws Exception {
+ public static SOAPMessage toSOAPMessage(Document doc) throws Exception
+ {
Canonicalizer c14n =
-
Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
+
Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
byte[] canonicalMessage = c14n.canonicalizeSubtree(doc);
ByteArrayInputStream in = new ByteArrayInputStream(canonicalMessage);
MessageFactory factory = MessageFactory.newInstance();
@@ -39,7 +41,8 @@
*/
public static SOAPMessage updateSOAPMessage(Document doc,
SOAPMessage message)
- throws Exception {
+ throws Exception
+ {
DOMSource domSource = new DOMSource(doc);
message.getSOAPPart().setContent(domSource);
return message;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/wssec/WSSecAuthNComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/wssec/WSSecAuthNComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/authn/wssec/WSSecAuthNComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -23,10 +23,11 @@
import org.perfsonar.service.base.authn.tokens.SecTokenSOAPManager;
import org.perfsonar.service.base.authn.tokens.SecurityToken;
-public class WSSecAuthNComponent implements AuthNComponent,
AuxiliaryComponent {
- private final String COMP_ID_SERVICE = "service.as.comp_id";
- private String componentName = null;
- private LoggerComponent logger;
+public class WSSecAuthNComponent implements AuthNComponent,
AuxiliaryComponent
+{
+ private final String COMP_ID_SERVICE = "service.as.comp_id";
+ private String componentName = null;
+ private LoggerComponent logger;
private ConfigurationComponent configuration;
private boolean checkAuthN;
@@ -35,145 +36,154 @@
private boolean checkAuthR;
private Set<String> messageTypesAuthR;
- public WSSecAuthNComponent() {
- checkAuthN = false;
- messageTypesAuthN = new HashSet<String>();
+ public WSSecAuthNComponent()
+ {
+ checkAuthN = false;
+ messageTypesAuthN = new HashSet<String>();
- checkAuthR = false;
- messageTypesAuthR = new HashSet<String>();
+ checkAuthR = false;
+ messageTypesAuthR = new HashSet<String>();
}
- @Override
- public String getComponentName() {
- return componentName;
- }
+ @Override
+ public String getComponentName()
+ {
+ return componentName;
+ }
- @Override
- public void initComponent() throws PerfSONARException {
- try {
- logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance()
- .getComponent(ComponentNames.LOGGER);
- } catch (PerfSONARException e) {
- String m = "WSSecAuthNComponent: Can't obtain Logger
component ";
- throw new PerfSONARException(m);
- }
- try {
- configuration =
(ConfigurationComponent)AuxiliaryComponentManager.
- getInstance().getComponent(ComponentNames.CONFIG);
- } catch (PerfSONARException e) {
- String m = "WSSecAuthNComponent: Can't obtain
Configuration component ";
- throw new PerfSONARException(m);
- }
+ @Override
+ public void initComponent() throws PerfSONARException
+ {
try {
+ logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance()
+ .getComponent(ComponentNames.LOGGER);
+ } catch (PerfSONARException e) {
+ String m = "WSSecAuthNComponent: Can't obtain Logger component ";
+ throw new PerfSONARException(m);
+ }
+ try {
+ configuration = (ConfigurationComponent)
AuxiliaryComponentManager.
+ getInstance().getComponent(ComponentNames.CONFIG);
+ } catch (PerfSONARException e) {
+ String m = "WSSecAuthNComponent: Can't obtain Configuration
component ";
+ throw new PerfSONARException(m);
+ }
+ try {
String checkAuthNParam;
String checkAuthRParam;
try {
-
checkAuthNParam=configuration.getProperty(AuthNComponent.CHECK_AUTHN_PARAM);
+ checkAuthNParam =
configuration.getProperty(AuthNComponent.CHECK_AUTHN_PARAM);
} catch (PerfSONARException e) {
- checkAuthNParam=null;
+ checkAuthNParam = null;
}
try {
-
checkAuthRParam=configuration.getProperty(AuthNComponent.CHECK_AUTHR_PARAM);
+ checkAuthRParam =
configuration.getProperty(AuthNComponent.CHECK_AUTHR_PARAM);
} catch (PerfSONARException e) {
- checkAuthRParam=null;
+ checkAuthRParam = null;
}
- if
(checkAuthNParam!=null&&checkAuthNParam.equals(AuthNComponent.YES_CHECK_AUTHN))
{
- checkAuthN = true;
- String
listMsgsParam=configuration.getProperty(AuthNComponent.LIST_MSG_AUTHN);
- StringTokenizer st=new
StringTokenizer(listMsgsParam,",");
- while (st.hasMoreTokens()) {
- String msg=st.nextToken();
- messageTypesAuthN.add(msg);
- }
- }
- if
(checkAuthRParam!=null&&checkAuthRParam.equals(AuthNComponent.YES_CHECK_AUTHR))
{
- checkAuthR = true;
- String
listMsgsParam=configuration.getProperty(AuthNComponent.LIST_MSG_AUTHR);
- StringTokenizer st=new
StringTokenizer(listMsgsParam,",");
- while (st.hasMoreTokens()) {
- String msg=st.nextToken();
- messageTypesAuthR.add(msg);
- }
- }
+ if (checkAuthNParam != null &&
checkAuthNParam.equals(AuthNComponent.YES_CHECK_AUTHN)) {
+ checkAuthN = true;
+ String listMsgsParam =
configuration.getProperty(AuthNComponent.LIST_MSG_AUTHN);
+ StringTokenizer st = new StringTokenizer(listMsgsParam, ",");
+ while (st.hasMoreTokens()) {
+ String msg = st.nextToken();
+ messageTypesAuthN.add(msg);
+ }
+ }
+ if (checkAuthRParam != null &&
checkAuthRParam.equals(AuthNComponent.YES_CHECK_AUTHR)) {
+ checkAuthR = true;
+ String listMsgsParam =
configuration.getProperty(AuthNComponent.LIST_MSG_AUTHR);
+ StringTokenizer st = new StringTokenizer(listMsgsParam, ",");
+ while (st.hasMoreTokens()) {
+ String msg = st.nextToken();
+ messageTypesAuthR.add(msg);
+ }
+ }
} catch (Exception e) {
- checkAuthN=false;
+ checkAuthN = false;
}
- }
+ }
- @Override
- public void setComponentName(String name) {
- componentName = name;
- }
+ @Override
+ public void setComponentName(String name)
+ {
+ componentName = name;
+ }
- public boolean isRequiredAuthN() {
- return checkAuthN;
- }
+ public boolean isRequiredAuthN()
+ {
+ return checkAuthN;
+ }
- public boolean isRequiredAuthR() {
- return checkAuthR;
- }
+ public boolean isRequiredAuthR()
+ {
+ return checkAuthR;
+ }
- @Override
- public void requestAuthN(String messageType) throws PerfSONARException {
- if (isRequiredAuthN()) {
- if (messageTypesAuthN.contains(messageType)) {
- SecurityToken st=new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
- if (!st.hasSecTokenInRequest()) {
- throw new
PerfSONARException("error.authn.not_sectoken","WSSecAuthNComponent: It has
not sent any Security Token");
- }
- st.setSecTokenFromRequest();
- AuthNRequest authnReq=new AuthNRequest(st);
- AADispatchManager aadm=new
AADispatchManager(AADispatchProtocolFactory.getDefaultAADispatchProtocol());
- AuthNResponse
authnRes=aadm.getAuthentication(authnReq);
- if
(authnRes.getStatus()!=AuthNResponse.AUTHENTICATED) {
- logger.debug("WSSecAuthNComponent:
Authentication failed ("+authnRes.getResultCode()+")");
- throw new
PerfSONARException(authnRes.getResultCode(),"Authentication failed");
- }
- }
- }
- }
+ @Override
+ public void requestAuthN(String messageType) throws PerfSONARException
+ {
+ if (isRequiredAuthN()) {
+ if (messageTypesAuthN.contains(messageType)) {
+ SecurityToken st = new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
+ if (!st.hasSecTokenInRequest()) {
+ throw new PerfSONARException("error.authn.not_sectoken",
"WSSecAuthNComponent: It has not sent any Security Token");
+ }
+ st.setSecTokenFromRequest();
+ AuthNRequest authnReq = new AuthNRequest(st);
+ AADispatchManager aadm = new
AADispatchManager(AADispatchProtocolFactory.getDefaultAADispatchProtocol());
+ AuthNResponse authnRes = aadm.getAuthentication(authnReq);
+ if (authnRes.getStatus() != AuthNResponse.AUTHENTICATED) {
+ logger.debug("WSSecAuthNComponent: Authentication failed
(" + authnRes.getResultCode() + ")");
+ throw new PerfSONARException(authnRes.getResultCode(),
"Authentication failed");
+ }
+ }
+ }
+ }
- private String getResource() throws PerfSONARException {
- String res=configuration.getProperty(COMP_ID_SERVICE);
- if (res==null) {
- throw new
PerfSONARException("error.as.edugain","Component ID not configured");
- }
- return res;
- }
-
- @Override
- public void requestAuthR(String messageType,String eventType) throws
PerfSONARException {
- boolean authr=false;
- if (isRequiredAuthR()) {
- if (messageTypesAuthR.contains(messageType)) {
- authr=true;
- SecurityToken st=new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
- if (!st.hasSecTokenInRequest()) {
- throw new
PerfSONARException("error.authn.not_sectoken","WSSecAuthNComponent: It has
not sent any Security Token");
- }
- st.setSecTokenFromRequest();
- AuthRRequest authrReq=new AuthRRequest(st,
messageType);
- authrReq.setResource(getResource());
- if (!(eventType==null|| eventType.isEmpty()))
{
-
authrReq.setAction(URLEncoder.encode(messageType)+":"+URLEncoder.encode(eventType));
- }
- try {
-
authrReq.setSubject(SecTokenSOAPManager.getSubject(st));
- } catch (Exception e) {
- throw new
PerfSONARException("error.authn.not_sectoken","WSSecAuthNComponent: Cannot
get authR data from the Security Token");
- }
+ private String getResource() throws PerfSONARException
+ {
+ String res = configuration.getProperty(COMP_ID_SERVICE);
+ if (res == null) {
+ throw new PerfSONARException("error.as.edugain", "Component ID
not configured");
+ }
+ return res;
+ }
- AADispatchProtocol
prot=AADispatchProtocolFactory.getDefaultAADispatchProtocol();
- AADispatchManager aadm=new
AADispatchManager(prot);
- AuthRResponse
authrRes=aadm.getAuthorization(authrReq);
- if
(authrRes.getStatus()!=AuthNResponse.AUTHENTICATED) {
- logger.debug("WSSecAuthNComponent:
Authentication failed ("+authrRes.getResultCode()+")");
- throw new
PerfSONARException(authrRes.getResultCode(),"Authentication failed");
- }
- }
- }
- if (!authr) {
- requestAuthN(messageType);
- }
- }
+ @Override
+ public void requestAuthR(String messageType, String eventType) throws
PerfSONARException
+ {
+ boolean authr = false;
+ if (isRequiredAuthR()) {
+ if (messageTypesAuthR.contains(messageType)) {
+ authr = true;
+ SecurityToken st = new
SecurityToken(SecTokenManagerFactory.getDefaultSecTokenManager());
+ if (!st.hasSecTokenInRequest()) {
+ throw new PerfSONARException("error.authn.not_sectoken",
"WSSecAuthNComponent: It has not sent any Security Token");
+ }
+ st.setSecTokenFromRequest();
+ AuthRRequest authrReq = new AuthRRequest(st, messageType);
+ authrReq.setResource(getResource());
+ if (!(eventType == null || eventType.isEmpty())) {
+ authrReq.setAction(URLEncoder.encode(messageType) + ":"
+ URLEncoder.encode(eventType));
+ }
+ try {
+ authrReq.setSubject(SecTokenSOAPManager.getSubject(st));
+ } catch (Exception e) {
+ throw new PerfSONARException("error.authn.not_sectoken",
"WSSecAuthNComponent: Cannot get authR data from the Security Token");
+ }
+
+ AADispatchProtocol prot =
AADispatchProtocolFactory.getDefaultAADispatchProtocol();
+ AADispatchManager aadm = new AADispatchManager(prot);
+ AuthRResponse authrRes = aadm.getAuthorization(authrReq);
+ if (authrRes.getStatus() != AuthNResponse.AUTHENTICATED) {
+ logger.debug("WSSecAuthNComponent: Authentication failed
(" + authrRes.getResultCode() + ")");
+ throw new PerfSONARException(authrRes.getResultCode(),
"Authentication failed");
+ }
+ }
+ }
+ if (!authr) {
+ requestAuthN(messageType);
+ }
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/configuration/ConfigurationComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/configuration/ConfigurationComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/configuration/ConfigurationComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -10,17 +10,17 @@
* of Configuration Components
*
* @author Maciej Glowiak
- *
*/
-public interface ConfigurationComponent {
+public interface ConfigurationComponent
+{
/**
- * Operation which provides access to individual property
+ * Operation which provides access to individual property
*
- * @param name of the parameter
- * @return String containing value/s for the parameter
- * @throws PerfSONARException when property couldn't be read
+ * @param name of the parameter
+ * @return String containing value/s for the parameter
+ * @throws PerfSONARException when property couldn't be read
*/
public String getProperty(String name) throws PerfSONARException;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/configuration/properties/PropertiesConfigurationComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/configuration/properties/PropertiesConfigurationComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/configuration/properties/PropertiesConfigurationComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -11,16 +11,16 @@
import org.perfsonar.base.exceptions.PerfSONARException;
/**
- * Class which reads configurations from a properties file
+ * Class which reads configurations from a properties file
*
- * @author loukik
- * @author Maciej Glowiak
- *
+ * @author loukik
+ * @author Maciej Glowiak
*/
public class PropertiesConfigurationComponent
- implements AuxiliaryComponent, ConfigurationComponent {
+ implements AuxiliaryComponent, ConfigurationComponent
+{
- private Logger logger =
Logger.getLogger(PropertiesConfigurationComponent.class.getName());
+ private Logger logger =
Logger.getLogger(PropertiesConfigurationComponent.class.getName());
// ---------------------------------- class fields
@@ -41,18 +41,19 @@
// ---------------------------------- constructor
@Override
- public void initComponent() throws PerfSONARException {
+ public void initComponent() throws PerfSONARException
+ {
// bootstrapped absolute file location in catalina.properties file
- file =
AuxiliaryComponentManager.lookupFile("/perfsonar/conf/service.properties");
+ file =
AuxiliaryComponentManager.lookupFile("/perfsonar/conf/service.properties");
- if(file==null) {
+ if (file == null) {
logger.severe("PropertiesConfigurationComponent.initComponent:" +
- " Missing or unable to locate service.properties file. Cannot
initialise PropertiesConfigurationComponent.");
+ " Missing or unable to locate service.properties file.
Cannot initialise PropertiesConfigurationComponent.");
throw new
PerfSONARException("PropertiesConfigurationComponent.initComponent:" +
- " Missing or unable to locate service.properties file. Cannot
initialise PropertiesConfigurationComponent.");
+ " Missing or unable to locate service.properties file.
Cannot initialise PropertiesConfigurationComponent.");
}
- logger.info("PropertiesConfigurationComponent.initComponent: Read
the file name as: "+file);
+ logger.info("PropertiesConfigurationComponent.initComponent: Read
the file name as: " + file);
// load configuration
this.loadConfiguration();
}
@@ -62,41 +63,42 @@
/**
- * Operation which provides all the properties read from the file
+ * Operation which provides all the properties read from the file
*
- * @return Properties - static object containing all the properties
- * in the property file
- *
- * @throws PerfSONARException when properties couldn't be read
+ * @return Properties - static object containing all the properties
+ * in the property file
+ * @throws PerfSONARException when properties couldn't be read
*/
@Override
- public Properties getProperties() throws PerfSONARException {
+ public Properties getProperties() throws PerfSONARException
+ {
return properties;
}
/**
- * Operation which provides access to individual properties read
- * from the property file
+ * Operation which provides access to individual properties read
+ * from the property file
*
- * @param name of the parameter
- * @return String containing value/s for the parameter
- * @throws PerfSONARException when property couldn't be read
+ * @param name of the parameter
+ * @return String containing value/s for the parameter
+ * @throws PerfSONARException when property couldn't be read
*/
@Override
- public String getProperty(String name) throws PerfSONARException {
- if(getProperties()==null) {
- throw new PerfSONARException(
- "PropertiesConfigurationComponent.getProperty: "
+ public String getProperty(String name) throws PerfSONARException
+ {
+ if (getProperties() == null) {
+ throw new PerfSONARException(
+ "PropertiesConfigurationComponent.getProperty: "
+ "PropertiesConfigurationComponent wasn't initialised
correctly, can't retrieve."
);
- }
-
+ }
+
String property = properties.getProperty(name);
if (property == null) {
throw new PerfSONARException(
"PropertiesConfigurationComponent.getProperty: "
- + "Requested Param: "+ name + "not found");
+ + "Requested Param: " + name + "not found");
}
return property;
@@ -104,25 +106,27 @@
@Override
- public String getComponentName() {
+ public String getComponentName()
+ {
return componentName;
}
@Override
- public void setComponentName(String componentName) {
+ public void setComponentName(String componentName)
+ {
this.componentName = componentName;
}
// ---------------------------------- private methods
/**
- * Operation which loads configuration
- * from a property file
- *
+ * Operation which loads configuration
+ * from a property file
*/
- void loadConfiguration() throws PerfSONARException {
+ void loadConfiguration() throws PerfSONARException
+ {
try {
properties = new Properties();
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/context/PerfsonarContextComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/context/PerfsonarContextComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/context/PerfsonarContextComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -4,20 +4,20 @@
* Provides a context in which data can be shared among components.
*
* @author michael.bischoff
- *
*/
-public interface PerfsonarContextComponent {
+public interface PerfsonarContextComponent
+{
- /**
- * @param key
- * @return The object stored using this key or null
- */
- Object get(Object key);
-
- /**
- * @param key
- * @param value or null
- */
- void put(Object key, Object value);
+ /**
+ * @param key
+ * @return The object stored using this key or null
+ */
+ Object get(Object key);
+ /**
+ * @param key
+ * @param value or null
+ */
+ void put(Object key, Object value);
+
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/context/inMemory/InMemoryContext.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/context/inMemory/InMemoryContext.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/context/inMemory/InMemoryContext.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -13,32 +13,39 @@
*
* @author michael.bischoff
*/
-public class InMemoryContext implements AuxiliaryComponent,
PerfsonarContextComponent {
+public class InMemoryContext implements AuxiliaryComponent,
PerfsonarContextComponent
+{
- private ConcurrentMap<Object, Object> backingMap = new
ConcurrentHashMap<Object, Object>();
- private String componentName;
-
- @Override
- public Object get(Object key) {
- return backingMap.get(key);
- }
+ private ConcurrentMap<Object, Object> backingMap = new
ConcurrentHashMap<Object, Object>();
+ private String componentName;
- @Override
- public void put(Object key, Object value) {
- backingMap.put(key, value);
- }
+ @Override
+ public Object get(Object key)
+ {
+ return backingMap.get(key);
+ }
- @Override
- public String getComponentName() {
- return componentName;
- }
+ @Override
+ public void put(Object key, Object value)
+ {
+ backingMap.put(key, value);
+ }
- @Override
- public void initComponent() throws PerfSONARException {}
+ @Override
+ public String getComponentName()
+ {
+ return componentName;
+ }
- @Override
- public void setComponentName(String componentName) {
- this.componentName = componentName;
- }
-
+ @Override
+ public void initComponent() throws PerfSONARException
+ {
+ }
+
+ @Override
+ public void setComponentName(String componentName)
+ {
+ this.componentName = componentName;
+ }
+
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/logger/LoggerComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/logger/LoggerComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/logger/LoggerComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -1,50 +1,51 @@
package org.perfsonar.base.auxiliary.components.logger;
+
/**
* Interface contains common methods for all
* Configuration Components
*
* @author Maciej Glowiak
- *
*/
-public interface LoggerComponent {
+public interface LoggerComponent
+{
/**
- * Logs a message with debug log level.
+ * Logs a message with debug log level.
*
- * @param message log this message
+ * @param message log this message
*/
public abstract void debug(String message);
/**
- * Logs a message with info log level.
+ * Logs a message with info log level.
*
- * @param message log this message
+ * @param message log this message
*/
public abstract void info(String message);
/**
- * Logs a message with warn log level.
+ * Logs a message with warn log level.
*
- * @param message log this message
+ * @param message log this message
*/
public abstract void warn(String message);
/**
- * Logs a message with error log level.
+ * Logs a message with error log level.
*
- * @param message log this message
+ * @param message log this message
*/
public abstract void error(String message);
/**
- * Logs a message with fatal log level.
+ * Logs a message with fatal log level.
*
- * @param message log this message
+ * @param message log this message
*/
public abstract void fatal(String message);
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/logger/log4j/Log4jLoggerComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/logger/log4j/Log4jLoggerComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/logger/log4j/Log4jLoggerComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -13,18 +13,19 @@
import org.perfsonar.base.exceptions.PerfSONARException;
/**
- * This class is responsible for logging functionality.
+ * This class is responsible for logging functionality.
*
- * @author Roman Lapacz
- * @author Maciej Glowiak
+ * @author Roman Lapacz
+ * @author Maciej Glowiak
*/
public class Log4jLoggerComponent
- implements AuxiliaryComponent, LoggerComponent {
+ implements AuxiliaryComponent, LoggerComponent
+{
private static final String CALLER_FQCN =
Log4jLoggerComponent.class.getName();
- // ---------------------------------- class fields
+ // ---------------------------------- class fields
/**
* Component Name
@@ -42,13 +43,15 @@
// ---------------------------------- constructors
/* Default no arg constructor */
- public Log4jLoggerComponent() { /* no arg constructor */
+ public Log4jLoggerComponent()
+ { /* no arg constructor */
}
// ---------------------------------- public methods
@Override
- public void initComponent() throws PerfSONARException {
+ public void initComponent() throws PerfSONARException
+ {
try {
debugLog = Logger.getLogger("sonar-debug");
infoLog = Logger.getLogger("sonar-info");
@@ -56,31 +59,31 @@
errorLog = Logger.getLogger("sonar-error");
fatalLog = Logger.getLogger("sonar-fatal");
- configuration =
(ConfigurationComponent)AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONFIG);
+ configuration = (ConfigurationComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONFIG);
String logconf =
configuration.getProperty("service.log.log4j.config");
File logConfiguration =
AuxiliaryComponentManager.lookupFile(logconf);
- if(logConfiguration!=null) {
-
PropertyConfigurator.configure(logConfiguration.getAbsolutePath());
+ if (logConfiguration != null) {
+
PropertyConfigurator.configure(logConfiguration.getAbsolutePath());
} else {
- System.err.println("PerfSONAR:WARNING: perfsonar logging not
configured correctly. (specified logging properties file['"+logconf+"'] not
found.)");
+ System.err.println("PerfSONAR:WARNING: perfsonar logging not
configured correctly. (specified logging properties file['" + logconf + "']
not found.)");
}
- } catch(Exception ex) {
- System.err.println("PerfSONAR:WARNING: perfsonar logging not
configured correctly.");
+ } catch (Exception ex) {
+ System.err.println("PerfSONAR:WARNING: perfsonar logging not
configured correctly.");
ex.printStackTrace();
}
}
-
/**
- * Sets log4j congiguration file
+ * Sets log4j congiguration file
*
- * @param configFile pathname
+ * @param configFile pathname
*/
- public void setConfig(String configFile) {
+ public void setConfig(String configFile)
+ {
PropertyConfigurator.configure(configFile);
@@ -90,7 +93,8 @@
* @see
org.perfsonar.commons.auxiliary.components.logger.log4j.LoggerComponent#debug(java.lang.String)
*/
@Override
- public void debug(String message) {
+ public void debug(String message)
+ {
debugLog.log(CALLER_FQCN, Level.DEBUG, message, null);
}
@@ -98,41 +102,47 @@
* @see
org.perfsonar.commons.auxiliary.components.logger.log4j.LoggerComponent#info(java.lang.String)
*/
@Override
- public void info(String message) {
- infoLog.log(CALLER_FQCN, Level.INFO, message, null);
+ public void info(String message)
+ {
+ infoLog.log(CALLER_FQCN, Level.INFO, message, null);
}
/* (non-Javadoc)
* @see
org.perfsonar.commons.auxiliary.components.logger.log4j.LoggerComponent#warn(java.lang.String)
*/
@Override
- public void warn(String message) {
- warnLog.log(CALLER_FQCN, Level.WARN, message, null);
+ public void warn(String message)
+ {
+ warnLog.log(CALLER_FQCN, Level.WARN, message, null);
}
/* (non-Javadoc)
* @see
org.perfsonar.commons.auxiliary.components.logger.log4j.LoggerComponent#error(java.lang.String)
*/
@Override
- public void error(String message) {
- errorLog.log(CALLER_FQCN, Level.ERROR, message, null);
+ public void error(String message)
+ {
+ errorLog.log(CALLER_FQCN, Level.ERROR, message, null);
}
/* (non-Javadoc)
* @see
org.perfsonar.commons.auxiliary.components.logger.log4j.LoggerComponent#fatal(java.lang.String)
*/
@Override
- public void fatal(String message) {
- fatalLog.log(CALLER_FQCN, Level.FATAL, message, null);
+ public void fatal(String message)
+ {
+ fatalLog.log(CALLER_FQCN, Level.FATAL, message, null);
}
@Override
- public String getComponentName() {
+ public String getComponentName()
+ {
return componentName;
}
@Override
- public void setComponentName(String componentName) {
+ public void setComponentName(String componentName)
+ {
this.componentName = componentName;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/mapping/ExpressionMapping.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/mapping/ExpressionMapping.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/mapping/ExpressionMapping.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -15,9 +15,9 @@
/**
* @author Maciej Glowiak
- *
*/
-public class ExpressionMapping implements AuxiliaryComponent {
+public class ExpressionMapping implements AuxiliaryComponent
+{
// -------------------------------------------- Instance variables
@@ -25,15 +25,16 @@
private String componentName = "expression_mapping";
- private Map<String,String> mappings;
+ private Map<String, String> mappings;
// --------------------------------------------------- Constructor
- public ExpressionMapping() {
+ public ExpressionMapping()
+ {
- mappings = new HashMap<String,String>();
+ mappings = new HashMap<String, String>();
}
@@ -45,22 +46,23 @@
* component.ComponentName.mapping_file property
*/
@Override
- public void initComponent() throws PerfSONARException {
+ public void initComponent() throws PerfSONARException
+ {
LoggerComponent logger = ((LoggerComponent)
- AuxiliaryComponentManager.getInstance().
- getComponent(ComponentNames.LOGGER));
+ AuxiliaryComponentManager.getInstance().
+ getComponent(ComponentNames.LOGGER));
String filename = ((ConfigurationComponent)
- AuxiliaryComponentManager.getInstance().
- getComponent(ComponentNames.CONFIG)).
- getProperty(
- "component."
- +getComponentName()
- +".mapping_file");
+ AuxiliaryComponentManager.getInstance().
+ getComponent(ComponentNames.CONFIG)).
+ getProperty(
+ "component."
+ + getComponentName()
+ + ".mapping_file");
logger.debug(
- "ExpressionMapping: read mapping config file:" + filename);
+ "ExpressionMapping: read mapping config file:" + filename);
ComponentsConfigurationReader confread =
new ComponentsConfigurationReader();
@@ -71,14 +73,15 @@
}
} catch (IOException e1) {
logger.error("ExpressionMapping: read mapping config file:"
- + filename);
+ + filename);
}
}
@Override
- public String getComponentName() {
+ public String getComponentName()
+ {
return componentName;
@@ -86,7 +89,8 @@
@Override
- public void setComponentName(String name) {
+ public void setComponentName(String name)
+ {
componentName = name;
@@ -96,13 +100,14 @@
/**
* Return mapping with applied replacements as Map
*/
- public String getMapping(String mappingName, Map<String,String>
replacements) {
+ public String getMapping(String mappingName, Map<String, String>
replacements)
+ {
String out = mappings.get(mappingName);
- if (replacements!=null && out!=null) {
+ if (replacements != null && out != null) {
for (String e : replacements.keySet()) {
- String regexp="\\%"+e+"\\%";
- out = out.replaceAll(regexp,replacements.get(e));
+ String regexp = "\\%" + e + "\\%";
+ out = out.replaceAll(regexp, replacements.get(e));
}
}
return out;
@@ -112,7 +117,8 @@
/**
* Return mapping without any replacements
*/
- public String getMapping(String mappingName) {
+ public String getMapping(String mappingName)
+ {
return getMapping(mappingName, null);
@@ -123,13 +129,14 @@
* Replace mapping with one replacement
*/
public String getMapping(
- String mappingName,
- String pattern,
- String replacement) {
+ String mappingName,
+ String pattern,
+ String replacement)
+ {
String out = mappings.get(mappingName);
- if (pattern!=null & out!=null && replacement!=null) {
- String regexp="\\%"+pattern+"\\%";
- out.replaceAll(regexp,replacement);
+ if (pattern != null & out != null && replacement != null) {
+ String regexp = "\\%" + pattern + "\\%";
+ out.replaceAll(regexp, replacement);
}
return out;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/ScheduleMessageHandler.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/ScheduleMessageHandler.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/ScheduleMessageHandler.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -15,7 +15,6 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-
/**
* Message Handler for scheduler which extends nmwg handler by adding the
* capability to retrieve element objects and not just complete message
object
@@ -23,53 +22,57 @@
* @author loukik
* @author Roman
*/
-public class ScheduleMessageHandler extends Handler {
+public class ScheduleMessageHandler extends Handler
+{
// ------------------------------------ Member variables
protected LoggerComponent logger;
- // ------------------------------------ constructor
+ // ------------------------------------ constructor
- public ScheduleMessageHandler() throws PerfSONARException {
- super();
+ public ScheduleMessageHandler() throws PerfSONARException
+ {
+ super();
- this.logger =
(LoggerComponent)AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
+ this.logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
- }
+ }
- // ------------------------------------ public methods
+ // ------------------------------------ public methods
- /**
- * Returns an element object for the given name
- * @param elementName object of type String containing the given name
- */
- public Object getElement(String elementName) {
+ /**
+ * Returns an element object for the given name
+ *
+ * @param elementName object of type String containing the given name
+ */
+ public Object getElement(String elementName)
+ {
- Iterator it = ht.values().iterator();
- Element element = null;
- boolean found = false;
+ Iterator it = ht.values().iterator();
+ Element element = null;
+ boolean found = false;
- while(it.hasNext()) {
- element = (Element) it.next();
- String ln = element.getLocalName();
- if (ln.equals(elementName)) {
- found = true;
- break;
- }
- }
+ while (it.hasNext()) {
+ element = (Element) it.next();
+ String ln = element.getLocalName();
+ if (ln.equals(elementName)) {
+ found = true;
+ break;
+ }
+ }
- if (!found) {
- logger.debug("ScheduleMessageHandler: There is no such element in
this XML document");
- return null;
- }
+ if (!found) {
+ logger.debug("ScheduleMessageHandler: There is no such element
in this XML document");
+ return null;
+ }
- logger.debug("ScheduleMessageHandlerElement parsed in this XML
document");
- return element;
+ logger.debug("ScheduleMessageHandlerElement parsed in this XML
document");
+ return element;
- }
+ }
} //SchedulerMessageHandler
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/ScheduleMessageParser.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/ScheduleMessageParser.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/ScheduleMessageParser.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -25,15 +25,14 @@
import org.xml.sax.SAXException;
-
/**
* Message Parser for Scheduler. It provides the capability to parse a
string object
* It uses ScheduleMessageHandler as its default xml event handler
*
* @author loukik
- *
*/
-public class ScheduleMessageParser {
+public class ScheduleMessageParser
+{
protected LoggerComponent logger;
@@ -55,172 +54,174 @@
*
* @throws PerfSONARException
*/
- public ScheduleMessageParser() throws PerfSONARException {
+ public ScheduleMessageParser() throws PerfSONARException
+ {
- logger =
(LoggerComponent)AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
+ logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
- configurationComponent =
(ConfigurationComponent)AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONFIG);
+ configurationComponent = (ConfigurationComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONFIG);
handler = new ScheduleMessageHandler();
}
-
// ------------------------------------ public methods
- /**
- * Parses xml in a document in order to convert it into a message object
- *
- * @param object of type org.w3c.dom.Document containing the given xml
- * @throws PerfSONARException
- * @throws RequestException
- *
- */
- public void parse(Document document) throws PerfSONARException {
+ /**
+ * Parses xml in a document in order to convert it into a message object
+ *
+ * @param object of type org.w3c.dom.Document containing the given xml
+ * @throws PerfSONARException
+ * @throws RequestException
+ */
+ public void parse(Document document) throws PerfSONARException
+ {
- if(document==null) {
+ if (document == null) {
- throw new PerfSONARException(
- "error.common.parse_error",
- "ScheduleMessageHandler.parse: Document object in request
is null. Nothing to parse");
+ throw new PerfSONARException(
+ "error.common.parse_error",
+ "ScheduleMessageHandler.parse: Document object in request is
null. Nothing to parse");
- }
+ }
- XMLSerializer serializer = new XMLSerializer();
- ByteArrayOutputStream boStream = new ByteArrayOutputStream();
+ XMLSerializer serializer = new XMLSerializer();
+ ByteArrayOutputStream boStream = new ByteArrayOutputStream();
- serializer.setOutputByteStream(boStream);
+ serializer.setOutputByteStream(boStream);
- try {
- serializer.serialize(document);
- } catch (IOException e) {
+ try {
+ serializer.serialize(document);
+ } catch (IOException e) {
- logger.fatal("ScheduleMessageHandler - IO exception encountered
while "
- + "serializing request document");
- throw new PerfSONARException("error.common.parse_error",
- "ScheduleMessageHandler- IO exception encountered while "
- + "serializing request document@: "+ e.getMessage());
- }
+ logger.fatal("ScheduleMessageHandler - IO exception encountered
while "
+ + "serializing request document");
+ throw new PerfSONARException("error.common.parse_error",
+ "ScheduleMessageHandler- IO exception encountered while "
+ + "serializing request document@: " + e.getMessage());
+ }
- InputSource ipSrc = new InputSource(
- new ByteArrayInputStream(boStream.toByteArray()));
+ InputSource ipSrc = new InputSource(
+ new ByteArrayInputStream(boStream.toByteArray()));
- this.parse(ipSrc);
- }
+ this.parse(ipSrc);
+ }
- /**
- * Parses xml present in a string object in order to convert it into a
message object
- *
- * @param requestString object of type string containing given xml
- * @throws PerfSONARException
- * @throws RequestException
- */
- public void parse(String requestString) throws PerfSONARException {
+ /**
+ * Parses xml present in a string object in order to convert it into a
message object
+ *
+ * @param requestString object of type string containing given xml
+ * @throws PerfSONARException
+ * @throws RequestException
+ */
+ public void parse(String requestString) throws PerfSONARException
+ {
- if(requestString==null) {
+ if (requestString == null) {
- throw new PerfSONARException(
- "error.common.parse_error",
- "ScheduleMessageHandler.parse: String object in request
is null. Nothing to parse");
+ throw new PerfSONARException(
+ "error.common.parse_error",
+ "ScheduleMessageHandler.parse: String object in request is
null. Nothing to parse");
- }
+ }
- StringReader reader = new StringReader(requestString);
+ StringReader reader = new StringReader(requestString);
- InputSource ipSrc = new InputSource(reader);
+ InputSource ipSrc = new InputSource(reader);
- this.parse(ipSrc);
+ this.parse(ipSrc);
- }
+ }
- /**
- * Parses xml presented as an input source
- *
- * @param inputSource object of type InputSource containing xml
- * @throws PerfSONARException
- * @throws RequestException
- */
- public void parse(InputSource inputSource) throws PerfSONARException {
+ /**
+ * Parses xml presented as an input source
+ *
+ * @param inputSource object of type InputSource containing xml
+ * @throws PerfSONARException
+ * @throws RequestException
+ */
+ public void parse(InputSource inputSource) throws PerfSONARException
+ {
+ String f =
+ configurationComponent.getProperty("service.sax_parser.config");
+ Handler.setConfigFile(f);
- String f =
- configurationComponent.getProperty("service.sax_parser.config");
- Handler.setConfigFile(f);
+ try {
+ final javax.xml.parsers.SAXParserFactory saxParserFactory =
+ javax.xml.parsers.SAXParserFactory.newInstance();
+ //saxParserFactory.setValidating(true);
+ saxParserFactory.setNamespaceAware(true);
- try {
+ final javax.xml.parsers.SAXParser saxParser =
+ saxParserFactory.newSAXParser();
+ final org.xml.sax.XMLReader parser = saxParser.getXMLReader();
- final javax.xml.parsers.SAXParserFactory saxParserFactory =
- javax.xml.parsers.SAXParserFactory.newInstance();
- //saxParserFactory.setValidating(true);
- saxParserFactory.setNamespaceAware(true);
+ boolean namespaces = DEFAULT_NAMESPACES;
+ boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
- final javax.xml.parsers.SAXParser saxParser =
- saxParserFactory.newSAXParser();
- final org.xml.sax.XMLReader parser = saxParser.getXMLReader();
+ parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
+ parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID,
namespacePrefixes);
- boolean namespaces = DEFAULT_NAMESPACES;
- boolean namespacePrefixes = DEFAULT_NAMESPACE_PREFIXES;
+ parser.setContentHandler(handler);
- parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
- parser.setFeature(NAMESPACE_PREFIXES_FEATURE_ID,
namespacePrefixes);
- parser.setContentHandler(handler);
+ try {
+ parser.parse(inputSource);
- try {
+ } catch (SAXException e) {
- parser.parse(inputSource);
+ logger.fatal("ScheduleMessageHandler.parse: SAX Exception
occurred while "
+ + "satisfying request. Error Message: "
+ + e.getMessage());
+ throw new PerfSONARException("error.common.parse_error",
+ "Request could not be parsed because "
+ + "of SAX exception. Error message: "
+ + e.getMessage());
- } catch(SAXException e) {
+ }
+ } catch (IOException e) {
- logger.fatal("ScheduleMessageHandler.parse: SAX Exception
occurred while "
- + "satisfying request. Error Message: "
- + e.getMessage());
- throw new PerfSONARException("error.common.parse_error",
- "Request could not be parsed because "
- + "of SAX exception. Error message: "
- + e.getMessage());
+ logger.fatal("ScheduleMessageHandler.parse: - IO exception
encountered while "
+ + "reading schema file");
+ throw new PerfSONARException("error.common.parse_error",
"MonitoringService - IO exception "
+ + "encountered while reading schema file "
+ + e.getMessage());
- }
- } catch (IOException e) {
+ } catch (SAXException e) {
- logger.fatal("ScheduleMessageHandler.parse: - IO exception
encountered while "
- + "reading schema file");
- throw new PerfSONARException("error.common.parse_error",
"MonitoringService - IO exception "
- + "encountered while reading schema file "
- + e.getMessage());
+ logger.fatal("ScheduleMessageHandler.parse -SAX Exception");
+ throw new PerfSONARException("error.common.parse_error",
+ "MonitoringService - SAX Exception "
+ + e.getMessage());
- } catch (SAXException e) {
+ } catch (ParserConfigurationException e) {
- logger.fatal("ScheduleMessageHandler.parse -SAX Exception");
- throw new PerfSONARException("error.common.parse_error",
- "MonitoringService - SAX Exception "
- + e.getMessage());
+ logger.fatal("ScheduleMessageHandler.parse -Parser Configuration
Exception");
+ throw new PerfSONARException("error.common.parse_error",
+ "MonitoringService - Parser Configuration "
+ + "Exception " + e.getMessage());
- } catch (ParserConfigurationException e) {
+ }
- logger.fatal("ScheduleMessageHandler.parse -Parser Configuration
Exception");
- throw new PerfSONARException("error.common.parse_error",
- "MonitoringService - Parser Configuration "
- + "Exception " + e.getMessage());
+ }
- }
+ /**
+ * Returns element object for the given name
+ *
+ * @param elementName string object containing the name of the element
+ * @return element object for the given name
+ */
+ public Object getElement(String elementName)
+ {
- }
+ return (this.handler.getElement(elementName));
+ }
- /**
- * Returns element object for the given name
- * @param elementName string object containing the name of the element
- * @return element object for the given name
- */
- public Object getElement(String elementName) {
-
- return (this.handler.getElement(elementName));
- }
-
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/Scheduler.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/Scheduler.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/Scheduler.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -24,13 +24,13 @@
import
org.perfsonar.service.base.storage.xmldb.exist.xmlrpc.ExistDbXmlrpcXmlStorageManager;
-
/**
* This class provides the capability to read and write schedules into an
xml database.
- * @author loukik
*
+ * @author loukik
*/
-public class Scheduler extends Thread implements AuxiliaryComponent {
+public class Scheduler extends Thread implements AuxiliaryComponent
+{
// ----------------------------Member Variables
@@ -46,25 +46,26 @@
// ----------------------------Constructor
@Override
- public void initComponent() throws PerfSONARException {
+ public void initComponent() throws PerfSONARException
+ {
try {
- logger =
(LoggerComponent)AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
+ logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
- configurationComponent =
(ConfigurationComponent)AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONFIG);
+ configurationComponent = (ConfigurationComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONFIG);
} catch (PerfSONARException e) {
System.out.println("Scheduler: ERROR! Scheduler could not be
initialized because " +
- "either ServiceConfigurationManager or Log could not be
initialized. " +
- "Scheduler cannot continue without these components");
+ "either ServiceConfigurationManager or Log could not be
initialized. " +
+ "Scheduler cannot continue without these components");
throw new PerfSONARException("error.common.scheduler.init",
- "Scheduler: ERROR! Scheduler could not be initialized
because " +
+ "Scheduler: ERROR! Scheduler could not be initialized
because " +
"either ServiceConfigurationManager or Log could not be
initialized. " +
- "Scheduler cannot continue without these components.
Error message: "+e.getMessage());
+ "Scheduler cannot continue without these components.
Error message: " + e.getMessage());
}
@@ -75,7 +76,8 @@
@Override
- public String getComponentName() {
+ public String getComponentName()
+ {
return componentName;
@@ -83,21 +85,24 @@
@Override
- public void setComponentName(String componentName) {
+ public void setComponentName(String componentName)
+ {
this.componentName = componentName;
}
- public boolean isWorking() {
+ public boolean isWorking()
+ {
return working;
}
- public void setWorking(boolean working) {
+ public void setWorking(boolean working)
+ {
this.working = working;
@@ -105,7 +110,8 @@
@Override
- public void run() {
+ public void run()
+ {
while (working) { //infinite loop
try {
@@ -123,125 +129,126 @@
// ---------------------------- Public Methods
- public void readSchedules(String scheduleSeconds) throws
PerfSONARException {
+ public void readSchedules(String scheduleSeconds) throws
PerfSONARException
+ {
logger.debug("Scheduler.readSchedules: Scheduler has been woken up
to read schedules");
String xmlDbURL;
- String userName;
- String password;
- String community;
+ String userName;
+ String password;
+ String community;
- try{
- xmlDbURL =
this.configurationComponent.getProperty("Scheduler.Database.XML.location");
- userName =
this.configurationComponent.getProperty("Scheduler.Database.XML.login.username");
- password =
this.configurationComponent.getProperty("Scheduler.Database.XML.login.password");
- community =
this.configurationComponent.getProperty("Scheduler.Database.XML.community");
+ try {
+ xmlDbURL =
this.configurationComponent.getProperty("Scheduler.Database.XML.location");
+ userName =
this.configurationComponent.getProperty("Scheduler.Database.XML.login.username");
+ password =
this.configurationComponent.getProperty("Scheduler.Database.XML.login.password");
+ community =
this.configurationComponent.getProperty("Scheduler.Database.XML.community");
- }catch(PerfSONARException e) {
+ } catch (PerfSONARException e) {
- logger.fatal("Scheduler.readSchedules: Scheduler is unable to
" +
- "read configuration information required to
connect to " +
- "an xml database. Scheduler cannot gather
schedules which are " +
- "stored in the xml database. Please configure
service.properties file " +
- "with the following properties: " +
- "Scheduler.Database.XML.location = URL for
accessing xml database, " +
- "Scheduler.Database.XML.login.username =
Username for accessing database, " +
- "Scheduler.Database.XML.login.password =
Password for accessing database, " +
- "Scheduler.Database.XML.community = Community
under which schedule resource " +
- "should be looked up");
+ logger.fatal("Scheduler.readSchedules: Scheduler is unable to " +
+ "read configuration information required to connect to " +
+ "an xml database. Scheduler cannot gather schedules which
are " +
+ "stored in the xml database. Please configure
service.properties file " +
+ "with the following properties: " +
+ "Scheduler.Database.XML.location = URL for accessing xml
database, " +
+ "Scheduler.Database.XML.login.username = Username for
accessing database, " +
+ "Scheduler.Database.XML.login.password = Password for
accessing database, " +
+ "Scheduler.Database.XML.community = Community under which
schedule resource " +
+ "should be looked up");
- return;
+ return;
- }
+ }
- if(xmlDbURL==null || xmlDbURL.isEmpty()) {
+ if (xmlDbURL == null || xmlDbURL.isEmpty()) {
- logger.fatal("Scheduler.readSchedules: Scheduler is unable to
" +
- "read configuration information from
service.properties file " +
- "required to connect to an xml database.
Scheduler cannot " +
- "gather schedules which are stored in the xml
database. " +
- "XML location property is missing. Please
make sure " +
- "service.properties file contains value for
the property: " +
- "Scheduler.Database.XML.location");
- return;
+ logger.fatal("Scheduler.readSchedules: Scheduler is unable to " +
+ "read configuration information from service.properties file
" +
+ "required to connect to an xml database. Scheduler cannot " +
+ "gather schedules which are stored in the xml database. " +
+ "XML location property is missing. Please make sure " +
+ "service.properties file contains value for the property: " +
+ "Scheduler.Database.XML.location");
+ return;
- }
+ }
- if(userName==null || userName.isEmpty()) {
+ if (userName == null || userName.isEmpty()) {
- logger.fatal("Scheduler.readSchedules: Scheduler is unable to
" +
- "read configuration information from
service.properties file " +
- "required to connect to an xml database.
Scheduler cannot " +
- "gather schedules which are stored in the xml
database. " +
- "Username to connect to the database is
missing. " +
- "Please make sure service.properties file
contains value " +
- "for the property:
Scheduler.Database.XML.login.username");
- return;
+ logger.fatal("Scheduler.readSchedules: Scheduler is unable to " +
+ "read configuration information from service.properties file
" +
+ "required to connect to an xml database. Scheduler cannot " +
+ "gather schedules which are stored in the xml database. " +
+ "Username to connect to the database is missing. " +
+ "Please make sure service.properties file contains value " +
+ "for the property: Scheduler.Database.XML.login.username");
+ return;
- }
+ }
- if(password==null || password.isEmpty()) {
+ if (password == null || password.isEmpty()) {
- logger.fatal("Scheduler.readSchedules: Scheduler is unable to
" +
- "read configuration information from
service.properties file " +
- "required to connect to an xml database.
Scheduler cannot " +
- "gather schedules which are stored in the xml
database. " +
- "Password to be used to connect to the
database is missing. " +
- "Please make sure service.properties file
contains value " +
- "for the property:
Scheduler.Database.XML.login.password");
- return;
+ logger.fatal("Scheduler.readSchedules: Scheduler is unable to " +
+ "read configuration information from service.properties file
" +
+ "required to connect to an xml database. Scheduler cannot " +
+ "gather schedules which are stored in the xml database. " +
+ "Password to be used to connect to the database is missing.
" +
+ "Please make sure service.properties file contains value " +
+ "for the property: Scheduler.Database.XML.login.password");
+ return;
- }
+ }
- if(community==null || community.isEmpty()) {
+ if (community == null || community.isEmpty()) {
- logger.fatal("Scheduler.readSchedules: Scheduler is unable to
" +
- "read configuration information from
service.properties file " +
- "required to connect to an xml database.
Scheduler cannot " +
- "gather schedules which are stored in the xml
database. " +
- "Community info in which schedule information
is stored is " +
- "missing. Please make sure service.properties
file contains value " +
- "for the property:
Scheduler.Database.XML.community");
- return;
+ logger.fatal("Scheduler.readSchedules: Scheduler is unable to " +
+ "read configuration information from service.properties file
" +
+ "required to connect to an xml database. Scheduler cannot " +
+ "gather schedules which are stored in the xml database. " +
+ "Community info in which schedule information is stored is "
+
+ "missing. Please make sure service.properties file contains
value " +
+ "for the property: Scheduler.Database.XML.community");
+ return;
- }
+ }
- scheduleSeconds = "60";
+ scheduleSeconds = "60";
- // for now assume that the storage manager is ExistDb. Lets work
on the generalization later
+ // for now assume that the storage manager is ExistDb. Lets work on
the generalization later
- ExistDbXmlrpcXmlDataRepository dbRepository = new
ExistDbXmlrpcXmlDataRepository(xmlDbURL, userName, password);
+ ExistDbXmlrpcXmlDataRepository dbRepository = new
ExistDbXmlrpcXmlDataRepository(xmlDbURL, userName, password);
- ExistDbXmlrpcXmlStorageManager storageManager = new
ExistDbXmlrpcXmlStorageManager();
+ ExistDbXmlrpcXmlStorageManager storageManager = new
ExistDbXmlrpcXmlStorageManager();
- storageManager.initStorage(dbRepository);
+ storageManager.initStorage(dbRepository);
- logger.debug("Scheduler.readSchedules: reading schedules from xml
db repository using XPath");
+ logger.debug("Scheduler.readSchedules: reading schedules from xml db
repository using XPath");
- String queryForSchedules =
"//*:parameters/*:parameter[@name='Repetetion_Seconds'"
+
+ String queryForSchedules =
"//*:parameters/*:parameter[@name='Repetetion_Seconds'"
+
" and text()='" + scheduleSeconds + "']/ancestor::*:metadata";
- logger.debug("Scheduler.readSchedules: reading schedules from " +
- "xml db repository using XPath expression:
"+queryForSchedules);
+ logger.debug("Scheduler.readSchedules: reading schedules from " +
+ "xml db repository using XPath expression: " +
queryForSchedules);
- //TODO: Put these schedules into an array of metadata objects?
+ //TODO: Put these schedules into an array of metadata objects?
- String[] scheduleResults = (String[])
storageManager.fetch(queryForSchedules);
+ String[] scheduleResults = (String[])
storageManager.fetch(queryForSchedules);
- Calendar cal = GregorianCalendar.getInstance();
- cal.setTimeInMillis(System.currentTimeMillis());
+ Calendar cal = GregorianCalendar.getInstance();
+ cal.setTimeInMillis(System.currentTimeMillis());
- logger.debug("Scheduler: Executing schedules at
"+cal.get(Calendar.DAY_OF_MONTH)+"/" +
-
""+cal.get(Calendar.MONTH)+"/"+cal.get(Calendar.YEAR)+"-"+
-
cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+"."
+
- " Identified "+scheduleResults.length+" schedules to
execute " +
- "at this time");
+ logger.debug("Scheduler: Executing schedules at " +
cal.get(Calendar.DAY_OF_MONTH) + "/" +
+ "" + cal.get(Calendar.MONTH) + "/" + cal.get(Calendar.YEAR) +
"-" +
+ cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) +
":" + cal.get(Calendar.SECOND) + "." +
+ " Identified " + scheduleResults.length + " schedules to execute
" +
+ "at this time");
- ScheduleMessageParser parser = new ScheduleMessageParser();
- Vector<String> metadataIdVector = new Vector<String>();
+ ScheduleMessageParser parser = new ScheduleMessageParser();
+ Vector<String> metadataIdVector = new Vector<String>();
for (String scheduleResult : scheduleResults) {
try {
@@ -272,209 +279,201 @@
}
- String[] leafMetadataIds = new String[metadataIdVector.size()];
+ String[] leafMetadataIds = new String[metadataIdVector.size()];
- for(int i = 0;i<metadataIdVector.size();i++) {
+ for (int i = 0; i < metadataIdVector.size(); i++) {
- leafMetadataIds[i] = metadataIdVector.get(i);
- }
+ leafMetadataIds[i] = metadataIdVector.get(i);
+ }
- // there can be many leaves, where each leaf is the end part of a
schedule
+ // there can be many leaves, where each leaf is the end part of a
schedule
- for(int itr=0;itr<leafMetadataIds.length;itr++) {
-
- logger.debug("Scheduler.readSchedules: Schedule metadata
points " +
- "to a metadata with id:
"+leafMetadataIds[itr]);
+ for (int itr = 0; itr < leafMetadataIds.length; itr++) {
- String queryForLeafMetadataContent =
+ logger.debug("Scheduler.readSchedules: Schedule metadata points
" +
+ "to a metadata with id: " + leafMetadataIds[itr]);
+
+ String queryForLeafMetadataContent =
"/*:message/*:metadata[@id='"
+ leafMetadataIds[itr] + "']";
- //StringDataQuery queryForLeafMetadataContent = new
StringDataQuery("//*:metadata[@id='meta2']");
+ //StringDataQuery queryForLeafMetadataContent = new
StringDataQuery("//*:metadata[@id='meta2']");
- String[] metadataLeafResults = (String[])
storageManager.fetch(queryForLeafMetadataContent);
+ String[] metadataLeafResults = (String[])
storageManager.fetch(queryForLeafMetadataContent);
- if(metadataLeafResults.length!=1) {
+ if (metadataLeafResults.length != 1) {
- if(metadataLeafResults.length==0) {
- logger.error("Scheduler.readSchedules: XML
configuration file is corrupt! " +
- "Schedule links to a metadata element with id
"+leafMetadataIds[itr]+
- " But the configuration file contains no
entry for elements with this id");
+ if (metadataLeafResults.length == 0) {
+ logger.error("Scheduler.readSchedules: XML configuration
file is corrupt! " +
+ "Schedule links to a metadata element with id " +
leafMetadataIds[itr] +
+ " But the configuration file contains no entry for
elements with this id");
- }
- else {
+ } else {
logger.error("Scheduler.readSchedules: XML configuration
file is corrupt! " +
- "Schedule links to a metadata element with id
"+leafMetadataIds[itr]+
- " But the configuration file returns
"+metadataLeafResults.length+" entries."+
- " Metadata element ids have to be unique.");
+ "Schedule links to a metadata element with id " +
leafMetadataIds[itr] +
+ " But the configuration file returns " +
metadataLeafResults.length + " entries." +
+ " Metadata element ids have to be unique.");
}
continue;
- }
+ }
- String[] scheduleChain = new String[1];
- scheduleChain[0] = metadataLeafResults[0];
+ String[] scheduleChain = new String[1];
+ scheduleChain[0] = metadataLeafResults[0];
- String nextNodeIdRef;
- boolean moreNodesInChain;
+ String nextNodeIdRef;
+ boolean moreNodesInChain;
- try {
- parser.parse(metadataLeafResults[0]);
+ try {
+ parser.parse(metadataLeafResults[0]);
- Metadata metadataElement = (Metadata)
parser.getElement("metadata");
- Subject subjectElement = metadataElement.getSubject();
- String metadataIdRef = subjectElement.getMetadataIdRef();
+ Metadata metadataElement = (Metadata)
parser.getElement("metadata");
+ Subject subjectElement = metadataElement.getSubject();
+ String metadataIdRef = subjectElement.getMetadataIdRef();
- if(!(metadataIdRef == null ||
metadataIdRef.equalsIgnoreCase(""))) {
- nextNodeIdRef = metadataIdRef;
- moreNodesInChain = true;
+ if (!(metadataIdRef == null ||
metadataIdRef.equalsIgnoreCase(""))) {
+ nextNodeIdRef = metadataIdRef;
+ moreNodesInChain = true;
- }
- else {
- nextNodeIdRef = null;
- moreNodesInChain = false;
+ } else {
+ nextNodeIdRef = null;
+ moreNodesInChain = false;
- }
-
- }
- catch(Exception e) {
- logger.error("Scheduler.readSchedules: Unexpected
exception " +
- "caught while parsing schedule entry.
Message: "+e.getMessage()+
- " Schedule entry is corrupt at metadata with
id:"+leafMetadataIds[itr]);
- continue;
- }
+ }
+ } catch (Exception e) {
+ logger.error("Scheduler.readSchedules: Unexpected exception
" +
+ "caught while parsing schedule entry. Message: " +
e.getMessage() +
+ " Schedule entry is corrupt at metadata with id:" +
leafMetadataIds[itr]);
+ continue;
+ }
- boolean errorInChain = false;
- while(moreNodesInChain) {
+ boolean errorInChain = false;
- if(nextNodeIdRef!=null) {
+ while (moreNodesInChain) {
- String queryForNextMetadataContent =
"/*:message/*:metadata[@id='"
+ nextNodeIdRef + "']";
+ if (nextNodeIdRef != null) {
- String[] nextMetadataResults = (String[])
storageManager.fetch(queryForNextMetadataContent);
+ String queryForNextMetadataContent =
"/*:message/*:metadata[@id='"
+ nextNodeIdRef + "']";
+ String[] nextMetadataResults = (String[])
storageManager.fetch(queryForNextMetadataContent);
- if(nextMetadataResults.length!=1) {
- if(nextMetadataResults.length==0) {
- logger.error("Scheduler.readSchedules: XML
configuration file is corrupt! " +
- "A reference was found to a metadata
element with id: "+nextNodeIdRef+" " +
- "but no metadata elements
were returned when queried");
- }
- else {
- logger.error("Scheduler.readSchedules: XML
configuration file is corrupt! " +
- "A reference was found to a
metadata element with id: "+nextNodeIdRef+" " +
- "but
"+nextMetadataResults.length+" metadata elements were returned when " +
- "queried. Metadata
elements should have unique ids. Ignoring this schedule");
- }
+ if (nextMetadataResults.length != 1) {
- errorInChain=true;
- break;
- }
+ if (nextMetadataResults.length == 0) {
+ logger.error("Scheduler.readSchedules: XML
configuration file is corrupt! " +
+ "A reference was found to a metadata element
with id: " + nextNodeIdRef + " " +
+ "but no metadata elements were returned when
queried");
+ } else {
+ logger.error("Scheduler.readSchedules: XML
configuration file is corrupt! " +
+ "A reference was found to a metadata element
with id: " + nextNodeIdRef + " " +
+ "but " + nextMetadataResults.length + "
metadata elements were returned when " +
+ "queried. Metadata elements should have
unique ids. Ignoring this schedule");
+ }
- try {
- parser.parse(nextMetadataResults[0]);
+ errorInChain = true;
+ break;
+ }
- Metadata metadataElement = (Metadata)
parser.getElement("metadata");
+ try {
+ parser.parse(nextMetadataResults[0]);
- Subject subjectElement =
metadataElement.getSubject();
- String metadataIdRef;
- metadataIdRef = subjectElement.getMetadataIdRef();
+ Metadata metadataElement = (Metadata)
parser.getElement("metadata");
- if(!(metadataIdRef == null ||
metadataIdRef.equalsIgnoreCase(""))) {
+ Subject subjectElement =
metadataElement.getSubject();
+ String metadataIdRef;
+ metadataIdRef = subjectElement.getMetadataIdRef();
- nextNodeIdRef = metadataIdRef;
- moreNodesInChain = true;
- // System.out.println("next in
chain:*"+metadataIdRef+"*");
+ if (!(metadataIdRef == null ||
metadataIdRef.equalsIgnoreCase(""))) {
- }
- else {
- nextNodeIdRef = null;
- moreNodesInChain = false;
- //System.out.println("end of chain");
- }
-
- }
- catch(Exception e) {
- logger.error("Scheduler.readSchedules: Unexpected
Exception " +
- "caught while parsing schedule entry.
" +
- "Schedule entry is corrupt at
metadata with id: "+nextNodeIdRef);
- errorInChain = true; break;
+ nextNodeIdRef = metadataIdRef;
+ moreNodesInChain = true;
+ // System.out.println("next in
chain:*"+metadataIdRef+"*");
- }
+ } else {
+ nextNodeIdRef = null;
+ moreNodesInChain = false;
+ //System.out.println("end of chain");
+ }
- String[] newScheduleChain = new
String[scheduleChain.length+1];
- // insert it above the current content in chain
+ } catch (Exception e) {
+ logger.error("Scheduler.readSchedules: Unexpected
Exception " +
+ "caught while parsing schedule entry. " +
+ "Schedule entry is corrupt at metadata with id:
" + nextNodeIdRef);
+ errorInChain = true;
+ break;
- System.arraycopy(scheduleChain, 0, newScheduleChain, 1,
scheduleChain.length);
+ }
- scheduleChain = newScheduleChain;
+ String[] newScheduleChain = new
String[scheduleChain.length + 1];
+ // insert it above the current content in chain
- scheduleChain[0]=nextMetadataResults[0];
+ System.arraycopy(scheduleChain, 0, newScheduleChain, 1,
scheduleChain.length);
- }
+ scheduleChain = newScheduleChain;
- else moreNodesInChain=false;
+ scheduleChain[0] = nextMetadataResults[0];
- if(errorInChain) break;
+ } else moreNodesInChain = false;
+ if (errorInChain) break;
- }
- if(errorInChain) continue;
- //TODO: Decide which schedule action to call upon - this is
done based on the first event type in the chain
- //call on action thread which should accept array of metadata
(or message?) objects
+ }
+ if (errorInChain) continue;
- Metadata[] scheduleMetadataChain = new
Metadata[scheduleChain.length];
+ //TODO: Decide which schedule action to call upon - this is done
based on the first event type in the chain
+ //call on action thread which should accept array of metadata
(or message?) objects
- for(int i=0;i<scheduleChain.length;i++) {
+ Metadata[] scheduleMetadataChain = new
Metadata[scheduleChain.length];
- parser.parse(scheduleChain[i]);
+ for (int i = 0; i < scheduleChain.length; i++) {
+ parser.parse(scheduleChain[i]);
+
Metadata metadataElement = (Metadata)
parser.getElement("metadata");
scheduleMetadataChain[i] = metadataElement;
- // System.out.println("Location "+i);
- // System.out.println(scheduleChain[i]);
- }
+ // System.out.println("Location "+i);
+ // System.out.println(scheduleChain[i]);
+ }
- // TODO: decide whether we need to call on generic or any
other type of SchedulerAction by using the
- // entry in service.properties file. If no entry is found,
use generic
+ // TODO: decide whether we need to call on generic or any other
type of SchedulerAction by using the
+ // entry in service.properties file. If no entry is found, use
generic
- EventType eventType = scheduleMetadataChain[0].getEventType();
+ EventType eventType = scheduleMetadataChain[0].getEventType();
- String eventTypeString = eventType.getEventType();
+ String eventTypeString = eventType.getEventType();
- if(eventTypeString == null || eventTypeString.equals(" ")) {
+ if (eventTypeString == null || eventTypeString.equals(" ")) {
- logger.error("Scheduler: Error in schedule entry. "+
- "The metadata element with Id: "
- +scheduleMetadataChain[0].getId()+
- "does not have an event type element. " +
- "Scheduler cannot determine what to do with
it");
- continue;
- }
+ logger.error("Scheduler: Error in schedule entry. " +
+ "The metadata element with Id: "
+ + scheduleMetadataChain[0].getId() +
+ "does not have an event type element. " +
+ "Scheduler cannot determine what to do with it");
+ continue;
+ }
- String schedulerActionType = null;
- try{
- schedulerActionType =
this.configurationComponent.getProperty(eventTypeString);
- }
- catch(Exception e) {
- // TODO: do nothing here?
- }
+ String schedulerActionType = null;
+ try {
+ schedulerActionType =
this.configurationComponent.getProperty(eventTypeString);
+ } catch (Exception e) {
+ // TODO: do nothing here?
+ }
- if(schedulerActionType!=null
- && (!schedulerActionType.equalsIgnoreCase("GENERIC"))
- && (!schedulerActionType.equalsIgnoreCase
-
("net.geant2.monitoring.nms.service.commons.auxiliary.GenericSchedulerAction")))
{
+ if (schedulerActionType != null
+ && (!schedulerActionType.equalsIgnoreCase("GENERIC"))
+ && (!schedulerActionType.equalsIgnoreCase
+
("net.geant2.monitoring.nms.service.commons.auxiliary.GenericSchedulerAction")))
{
- // use a custom schedulerAction
+ // use a custom schedulerAction
- logger.debug("Scheduler.readSchedules: Configured to
calling on " +
- "Custom Scheduler Action with classname:
"+schedulerActionType+
- "for the metadata chain containing head with
event type: "+
- eventTypeString);
+ logger.debug("Scheduler.readSchedules: Configured to calling
on " +
+ "Custom Scheduler Action with classname: " +
schedulerActionType +
+ "for the metadata chain containing head with event type:
" +
+ eventTypeString);
Class<?> tempClass;
SchedulerAction schedulerActionClass;
@@ -485,56 +484,54 @@
//TODO handle ClassCastException.
schedulerActionClass =
- (SchedulerAction)tempClass.newInstance();
+ (SchedulerAction) tempClass.newInstance();
schedulerActionClass.init(scheduleMetadataChain, itr);
} catch (ClassNotFoundException e1) {
logger.error("Scheduler: The configured SchedulerAction"
+
- " class cannot be found. The event type " +
- "associated with this class
is:"+eventTypeString+" The" +
- " error message seen
is"+e1.getMessage());
+ " class cannot be found. The event type " +
+ "associated with this class is:" + eventTypeString +
" The" +
+ " error message seen is" + e1.getMessage());
continue;
} catch (InstantiationException e) {
logger.error("Scheduler: The configured SchedulerAction"
+
- " class cannot be instantiated. The event
type " +
- "associated with this class
is:"+eventTypeString+" The" +
- " error message seen
is"+e.getMessage());
+ " class cannot be instantiated. The event type " +
+ "associated with this class is:" + eventTypeString +
" The" +
+ " error message seen is" + e.getMessage());
continue;
} catch (IllegalAccessException e) {
logger.error("Scheduler: The configured SchedulerAction"
+
- " class cannot be instantiated because of
illegal" +
- "Access. The event type associated with this
" +
- "class is:"+eventTypeString+" The error
message seen is"+
- e.getMessage());
+ " class cannot be instantiated because of illegal" +
+ "Access. The event type associated with this " +
+ "class is:" + eventTypeString + " The error message
seen is" +
+ e.getMessage());
continue;
} catch (Exception e) {
logger.error("Scheduler: The configured SchedulerAction"
+
- " class cannot be invoked because of unknown"
+
- "exception. The event type associated with
this " +
- "class is:"+eventTypeString+" The error
message seen is"+
- e.getMessage());
+ " class cannot be invoked because of unknown" +
+ "exception. The event type associated with this " +
+ "class is:" + eventTypeString + " The error message
seen is" +
+ e.getMessage());
continue;
}
- }
+ } else {
+ // use the generic schedulerAction
+ logger.debug("Scheduler.readSchedules: Calling on
GenericSchedulerAction" +
+ "for the metadata chain containing head with event type:
" +
+ eventTypeString);
- else {
- // use the generic schedulerAction
- logger.debug("Scheduler.readSchedules: Calling on
GenericSchedulerAction" +
- "for the metadata chain containing head with
event type: "+
- eventTypeString);
-
- SchedulerAction schedulerAction = new
GenericSchedulerAction();
- schedulerAction.init(scheduleMetadataChain, itr);
- }
+ SchedulerAction schedulerAction = new
GenericSchedulerAction();
+ schedulerAction.init(scheduleMetadataChain, itr);
+ }
}// end of for(each leaf)
@@ -551,7 +548,8 @@
* @throws DataFormatException
* @throws PerfSONARException
*/
- public static void main(String args[]) throws PerfSONARException {
+ public static void main(String args[]) throws PerfSONARException
+ {
Scheduler tester = new Scheduler();
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/actions/GenericSchedulerAction.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/actions/GenericSchedulerAction.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/actions/GenericSchedulerAction.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -6,21 +6,20 @@
package org.perfsonar.base.auxiliary.components.scheduler.actions;
-
-
/**
* Generic scheduler action which exploits the capabilities which are
* already existing in the SchedulerAction abstract class
*
* @author loukik
- *
*/
-public class GenericSchedulerAction extends SchedulerAction {
+public class GenericSchedulerAction extends SchedulerAction
+{
// ----------------------------Constructor
- public GenericSchedulerAction() {
+ public GenericSchedulerAction()
+ {
super();
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/actions/SchedulerAction.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/actions/SchedulerAction.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/scheduler/actions/SchedulerAction.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -24,17 +24,17 @@
import org.perfsonar.service.base.storage.StorageManager;
-
/**
* Abstract SchedulerAction class
*
* @author loukik
*/
-public abstract class SchedulerAction implements Runnable {
+public abstract class SchedulerAction implements Runnable
+{
// TODO: thread.stop is used here but has been deprecated. Need to
replace this.
// FIXME thread.stop is deathlock prone
-
+
// ----------------------------Member Variables
public Metadata[] metadataList = null;
@@ -57,15 +57,16 @@
* @param me
* @throws SystemException
*/
- public void init(Metadata[] metadataList, int me) throws
PerfSONARException {
+ public void init(Metadata[] metadataList, int me) throws
PerfSONARException
+ {
this.me = me;
this.metadataList = metadataList;
- logger =
(LoggerComponent)AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
+ logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
- configurationComponent =
(ConfigurationComponent)AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONFIG);
+ configurationComponent = (ConfigurationComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONFIG);
this.thread = new Thread(this);
@@ -73,16 +74,17 @@
}
-
// ---------------------------- Public Methods
/**
* Implemented interface method which calls on the performAction method
+ *
* @see java.lang.Runnable#run()
*/
@Override
- public void run() {
+ public void run()
+ {
System.out.println("SchedulerAction: SchedulerAction has been
invoked");
this.performAction();
@@ -97,15 +99,16 @@
* This method should be overridden if required
*
* @param messageList An array of Message objects
- * containing well defined actions
+ * containing well defined actions
* @throws PerfSONARException
*/
- public void performAction() {
+ public void performAction()
+ {
logger.debug("SchedulerAction: Generic Scheduler Action invoked");
- Message requestMessage= new Message();
+ Message requestMessage = new Message();
// this is a message object which will be used to populate results
from one stage
// and feed it to the next stage
@@ -471,7 +474,6 @@
} // end of for
-
}// end of performAction
@@ -479,9 +481,11 @@
/**
* Returns the Thread object which should help in controlling the object
+ *
* @return Thread object which helps in controlling the current thread
*/
- public Thread getThread() {
+ public Thread getThread()
+ {
return this.thread;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/Scheduler.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/Scheduler.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/Scheduler.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -23,11 +23,11 @@
*
* @author Maciej Glowiak
* @author Uros Juvan (changed interface being implemented from
- * AuxiliaryComponent to AuxiliaryThreadedComponent,
- * added stopThread method)
- *
+ * AuxiliaryComponent to AuxiliaryThreadedComponent,
+ * added stopThread method)
*/
-public class Scheduler extends Thread implements AuxiliaryThreadedComponent {
+public class Scheduler extends Thread implements AuxiliaryThreadedComponent
+{
// ----------------------------Member Variables
@@ -49,7 +49,8 @@
// -------------------------------------------------- Constructor
- public Scheduler() {
+ public Scheduler()
+ {
setComponentName("SCHEDULER"); //temporary name
@@ -60,11 +61,12 @@
@Override
- public void initComponent() throws PerfSONARException {
+ public void initComponent() throws PerfSONARException
+ {
try {
- logger = (LoggerComponent)AuxiliaryComponentManager.
+ logger = (LoggerComponent) AuxiliaryComponentManager.
getInstance().getComponent(ComponentNames.LOGGER);
config = (ConfigurationComponent)
@@ -74,9 +76,9 @@
} catch (PerfSONARException e) {
String m = "Cannot initialize components: " +
- "logger and configuration "+e.getMessage();
+ "logger and configuration " + e.getMessage();
- throw new PerfSONARException("error.common.no_configuration",m);
+ throw new PerfSONARException("error.common.no_configuration", m);
}
@@ -89,9 +91,11 @@
/**
* Checks if scheduler is active and working
+ *
* @return
*/
- public boolean isWorking() {
+ public boolean isWorking()
+ {
return working;
@@ -100,9 +104,9 @@
/**
* Stops scheduler permanently
- *
*/
- public void stopScheduler() {
+ public void stopScheduler()
+ {
this.working = false;
@@ -110,7 +114,8 @@
@Override
- public void run() {
+ public void run()
+ {
paused = false;
@@ -132,7 +137,8 @@
}
- } catch (ConcurrentModificationException cme) {}
+ } catch (ConcurrentModificationException cme) {
+ }
}
@@ -147,14 +153,16 @@
// ---------------------------- Public Methods
- public int getWakeupInterval() {
+ public int getWakeupInterval()
+ {
return wakeupInterval;
}
- public void setWakeupInterval(int wakeupInterval) {
+ public void setWakeupInterval(int wakeupInterval)
+ {
this.wakeupInterval = wakeupInterval;
@@ -162,7 +170,8 @@
@Override
- public String getComponentName() {
+ public String getComponentName()
+ {
return componentName;
@@ -170,19 +179,22 @@
@Override
- public void setComponentName(String name) {
+ public void setComponentName(String name)
+ {
componentName = name;
}
- public void addSchedulerTask(SchedulerTask t) {
+ public void addSchedulerTask(SchedulerTask t)
+ {
tasks.add(t);
}
- public void addSchedulerTask(int interval, SchedulerAction action) {
+ public void addSchedulerTask(int interval, SchedulerAction action)
+ {
tasks.add(new SchedulerTask(interval, action));
@@ -194,7 +206,8 @@
*
* @param action to remove
*/
- public void remSchedulerTask(SchedulerAction action) {
+ public void remSchedulerTask(SchedulerAction action)
+ {
// Interval is not important in remove
tasks.remove(new SchedulerTask(0, action));
@@ -202,11 +215,11 @@
}
-
// ---------------------------- Private Methods
- public static void main(String[] a) throws PerfSONARException {
+ public static void main(String[] a) throws PerfSONARException
+ {
new Scheduler().initComponent();
@@ -215,9 +228,11 @@
/**
* Checks if scheduler is temporarly paused
+ *
* @return
*/
- public boolean isPaused() {
+ public boolean isPaused()
+ {
return paused;
}
@@ -225,9 +240,11 @@
/**
* Set scheduler paused. It'll be still working but won't be
* scheduling and running tasks
+ *
* @param paused
*/
- public void setPaused(boolean paused) {
+ public void setPaused(boolean paused)
+ {
this.paused = paused;
@@ -237,7 +254,8 @@
* Stop the thread by calling stopScheduler
*/
@Override
- public void stopThread() {
+ public void stopThread()
+ {
stopScheduler();
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/SchedulerAction.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/SchedulerAction.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/SchedulerAction.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -3,10 +3,11 @@
/**
* Interface that represents simple scheduler action
+ *
* @author Maciej Glowiak
- *
*/
-public interface SchedulerAction {
+public interface SchedulerAction
+{
public void runAction();
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/SchedulerTask.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/SchedulerTask.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/auxiliary/components/simplescheduler/SchedulerTask.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -1,7 +1,8 @@
package org.perfsonar.base.auxiliary.components.simplescheduler;
-public class SchedulerTask {
+public class SchedulerTask
+{
private long MIN_INTERVAL = 100; //ms
@@ -17,9 +18,10 @@
// --------------------------------------------------- constructor
- public SchedulerTask(long interval, SchedulerAction action) {
+ public SchedulerTask(long interval, SchedulerAction action)
+ {
- if (interval<MIN_INTERVAL) this.interval = MIN_INTERVAL;
+ if (interval < MIN_INTERVAL) this.interval = MIN_INTERVAL;
else this.interval = interval;
this.action = action;
@@ -31,12 +33,13 @@
/**
* This constructor is used, when some action should be run in the future
*
- * @param interval interval for running action
- * @param action action to run
+ * @param interval interval for running action
+ * @param action action to run
* @param startTimestamp when should we start running action
*/
public SchedulerTask(
- long interval, SchedulerAction action, long startTimestamp) {
+ long interval, SchedulerAction action, long startTimestamp)
+ {
this(interval, action);
@@ -50,7 +53,8 @@
/**
* Runs proper action as new Thread (only if time is out)
*/
- public boolean runAction() {
+ public boolean runAction()
+ {
long currentTimestamp = System.currentTimeMillis();
@@ -60,9 +64,11 @@
timestamp = currentTimestamp;
//run action in thread
- new Thread() {
+ new Thread()
+ {
@Override
- public void run() {
+ public void run()
+ {
super.run();
action.runAction();
}
@@ -77,26 +83,29 @@
}
- public SchedulerAction getAction() {
+ public SchedulerAction getAction()
+ {
return action;
}
- public void setAction(SchedulerAction action) {
+ public void setAction(SchedulerAction action)
+ {
this.action = action;
}
-
/**
* Get interval between two subsequence runs of action
+ *
* @param interval
*/
- public long getInterval() {
+ public long getInterval()
+ {
return interval;
@@ -105,9 +114,11 @@
/**
* Set interval between two subsequence runs of action
+ *
* @param interval
*/
- public void setInterval(long interval) {
+ public void setInterval(long interval)
+ {
this.interval = interval;
@@ -116,9 +127,11 @@
/**
* Returns timestamp of recent run of action
+ *
* @return
*/
- public long getTimestamp() {
+ public long getTimestamp()
+ {
return timestamp;
@@ -129,9 +142,9 @@
* Set timestamp of recent run of action on the beginning of epoch
* (1970), so action should be run immediately (in the next cycle of
* Scheduler)
- *
*/
- public void resetTimestamp() {
+ public void resetTimestamp()
+ {
this.timestamp = 0;
@@ -144,7 +157,8 @@
*
* @return hash code
*/
- public int hashCode() {
+ public int hashCode()
+ {
return action == null ? 0 : action.hashCode();
@@ -158,15 +172,16 @@
* @param o other objects (should be instanceof SchedulerTask
* @return true if both action objects are equal
*/
- public boolean equals(Object o) {
+ public boolean equals(Object o)
+ {
if (o == null) return false;
return o instanceof SchedulerTask ?
- (((SchedulerTask)o).action == null ?
- action == null :
- ((SchedulerTask)o).action.equals(action)) :
- false;
+ (((SchedulerTask) o).action == null ?
+ action == null :
+ ((SchedulerTask) o).action.equals(action)) :
+ false;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/exceptions/PerfSONARException.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/exceptions/PerfSONARException.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/exceptions/PerfSONARException.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,13 +2,13 @@
/**
* Common Exception class for all PerfSONAR Exceptions
- *
+ * <p/>
* All other Exception classes should be derived from this class.
*
* @author Maciej Glowiak
- *
*/
-public class PerfSONARException extends Exception {
+public class PerfSONARException extends Exception
+{
// ----------------------------------------------------- Constants
@@ -37,7 +37,8 @@
// -------------------------------------------------- Constructors
- public PerfSONARException() {
+ public PerfSONARException()
+ {
super();
resetResult();
@@ -45,7 +46,8 @@
}
- public PerfSONARException(String message) {
+ public PerfSONARException(String message)
+ {
super(message);
setResult(message);
@@ -53,7 +55,8 @@
}
- public PerfSONARException(String message, Throwable t) {
+ public PerfSONARException(String message, Throwable t)
+ {
super(message, t);
setResult(message);
@@ -62,10 +65,12 @@
/**
* PerfSONAR Exception - result code support
+ *
* @param resultCode - textual result code
- * @param message - textual result description (message)
+ * @param message - textual result description (message)
*/
- public PerfSONARException(String resultCode, String message) {
+ public PerfSONARException(String resultCode, String message)
+ {
super(message);
setResult(resultCode, message);
@@ -75,12 +80,14 @@
/**
* PerfSONAR Exception - result code support
+ *
* @param resultCode - textual result code
- * @param message - textual result description (message)
+ * @param message - textual result description (message)
*/
- public PerfSONARException(String resultCode, String message, Throwable
t) {
+ public PerfSONARException(String resultCode, String message, Throwable t)
+ {
- super(message,t);
+ super(message, t);
setResult(resultCode, message);
}
@@ -90,9 +97,10 @@
@Override
- public String getMessage() {
+ public String getMessage()
+ {
- return "[" + resultCode + "]: "+super.getMessage();
+ return "[" + resultCode + "]: " + super.getMessage();
}
@@ -100,7 +108,8 @@
/**
* Returns result code (or "unknown")
*/
- public String getResultCode() {
+ public String getResultCode()
+ {
return resultCode;
@@ -110,7 +119,8 @@
/**
* Return result code description (or empty String)
*/
- public String getResultDescription() {
+ public String getResultDescription()
+ {
return resultDescription;
@@ -119,7 +129,8 @@
// ----------------------------------------------- private methods
- private void setResult(String rc, String rd) {
+ private void setResult(String rc, String rd)
+ {
resultCode = rc;
resultDescription = rd;
@@ -127,7 +138,8 @@
}
- private void setResult(String desc) {
+ private void setResult(String desc)
+ {
resultCode = UNKNOWN_RESULT_CODE;
resultDescription = desc;
@@ -135,12 +147,12 @@
}
- private void resetResult() {
+ private void resetResult()
+ {
setResult(UNKNOWN_RESULT_CODE, "");
}
-
} //PerfSONARException
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/nmwg/owamp/Parameters.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/nmwg/owamp/Parameters.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/nmwg/owamp/Parameters.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -1,143 +1,142 @@
/**
* Describes the basic format of the ping parameters.
*
- * @author Martin Swany
- * @author Jason Zurawski
+ * @author Martin Swany
+ * @author Jason Zurawski
* @author Piotr Pikusa
- * @version $Id$
- * @see org.ggf.ns.nmwg.base.v2_0.Element
- * @see org.ggf.ns.nmwg.base.v2_0.Parameter
- * @see org.w3c.dom.Document
- * @see org.w3c.dom.Element
+ * @version $Id$
+ * @see org.ggf.ns.nmwg.base.v2_0.Element
+ * @see org.ggf.ns.nmwg.base.v2_0.Parameter
+ * @see org.w3c.dom.Document
+ * @see org.w3c.dom.Element
*/
package org.perfsonar.base.nmwg.owamp;
import org.ggf.ns.nmwg.base.v2_0.Parameter;
-public class Parameters extends org.ggf.ns.nmwg.base.v2_0.Parameters {
+public class Parameters extends org.ggf.ns.nmwg.base.v2_0.Parameters
+{
- /**
- * Constructor.
- */
- public Parameters() {
- parent = null;
- id = "";
- completed = false;
-
- localName = "parameters";
- uri = "http://ggf.org/ns/nmwg/tools/owamp/2.0/";
- qName = "owamp:parameters";
- prefix = "owamp";
- fileName = "org/ggf/ns/nmwg/tools/owamp/v2_0/Parameters.java";
- }
-
- /**
- * Return parameter by name.
- */
- @Override
- public Parameter getParameterByName(String name) {
- if(!(name.isEmpty())) {
- if(name.equals("count") ||
- name.equals("dscp") ||
- name.equals("phb") ||
- name.equals("wait") ||
- name.equals("timeOut") ||
- name.equals("padding") ||
- name.equals("endDelay") ||
- name.equals("portRange") ||
- name.equals("size") ||
- name.equals("output") ||
- name.equals("direction")) {
- Parameter p =
(Parameter)parameterMap.get(name);
- return(p);
- }
- else {
- System.err.println("Error: " + getFileName() +
- "
'getParameterByName(String)' Unrecognized " +
- " parameter: "+name+".");
- return null;
- }
- }
- else {
- System.err.println("Error: " + getFileName() +
- " 'getParameterByName(String)' name
cannont be nil.");
- return null;
- }
- }
+ /**
+ * Constructor.
+ */
+ public Parameters()
+ {
+ parent = null;
+ id = "";
+ completed = false;
- /**
- * Adds a parameter to the map
- */
- @Override
- public void addParameter(Parameter newParameter) {
- if(newParameter != null) {
- if(newParameter.getParameterName().equals("count") ||
-
newParameter.getParameterName().equals("dscp") ||
-
newParameter.getParameterName().equals("phb") ||
-
newParameter.getParameterName().equals("wait") ||
-
newParameter.getParameterName().equals("timeOut") ||
-
newParameter.getParameterName().equals("padding") ||
-
newParameter.getParameterName().equals("direction") ||
-
newParameter.getParameterName().equals("size") ||
-
newParameter.getParameterName().equals("output") ||
-
newParameter.getParameterName().equals("portRange") ||
-
newParameter.getParameterName().equals("endDelay")) {
-
if(getParameterByName(newParameter.getParameterName())!=null){
- System.err.println("Error: " +
getFileName() +
- "
'setParameter(Parameter)' Duplicate parameter" +
- " name: " +
newParameter.getParameterName() +
- " for id: " +
newParameter.getId());
- return;
- }
-
parameterMap.put(newParameter.getParameterName(),newParameter);
- }
- else {
- System.err.println("Error: " + getFileName() +
- " 'addParameter(Parameter)'
Unrecognized " +
- " parameter:
"+newParameter.getParameterName()+".");
- return;
- }
- }
- else {
- System.err.println("Error: " + getFileName() +
- " 'addParameter(Paramter)' Parameter cannont be
nil.");
- return;
- }
- }
+ localName = "parameters";
+ uri = "http://ggf.org/ns/nmwg/tools/owamp/2.0/";
+ qName = "owamp:parameters";
+ prefix = "owamp";
+ fileName = "org/ggf/ns/nmwg/tools/owamp/v2_0/Parameters.java";
+ }
- @Override
- public void addParameter(String name, String value) {
- if(!(name.isEmpty()) && !(value.isEmpty())) {
- if(name.equals("count") ||
- name.equals("dscp") ||
- name.equals("phb") ||
- name.equals("wait") ||
- name.equals("timeOut") ||
- name.equals("padding") ||
- name.equals("endDelay") ||
- name.equals("portRange") ||
- name.equals("size") ||
- name.equals("output") ||
- name.equals("direction")) {
- Parameter p = new Parameter();
- p.setParameterName(name);
- p.setParameterValue(value);
- this.addParameter(p);
- }
- else {
- System.err.println("Error: " + getFileName() +
- " 'addParameter(String,
String)' Unrecognized " +
- " parameter: "+name+".");
- return;
- }
- }
- else {
- System.err.println("Error: " + getFileName() +
- " 'addParameter(String, String)'
cannot have nil value" +
- " for name or value.");
- return;
- }
- }
-
+ /**
+ * Return parameter by name.
+ */
+ @Override
+ public Parameter getParameterByName(String name)
+ {
+ if (!(name.isEmpty())) {
+ if (name.equals("count") ||
+ name.equals("dscp") ||
+ name.equals("phb") ||
+ name.equals("wait") ||
+ name.equals("timeOut") ||
+ name.equals("padding") ||
+ name.equals("endDelay") ||
+ name.equals("portRange") ||
+ name.equals("size") ||
+ name.equals("output") ||
+ name.equals("direction")) {
+ Parameter p = (Parameter) parameterMap.get(name);
+ return (p);
+ } else {
+ System.err.println("Error: " + getFileName() +
+ " 'getParameterByName(String)' Unrecognized " +
+ " parameter: " + name + ".");
+ return null;
+ }
+ } else {
+ System.err.println("Error: " + getFileName() +
+ " 'getParameterByName(String)' name cannont be nil.");
+ return null;
+ }
+ }
+
+ /**
+ * Adds a parameter to the map
+ */
+ @Override
+ public void addParameter(Parameter newParameter)
+ {
+ if (newParameter != null) {
+ if (newParameter.getParameterName().equals("count") ||
+ newParameter.getParameterName().equals("dscp") ||
+ newParameter.getParameterName().equals("phb") ||
+ newParameter.getParameterName().equals("wait") ||
+ newParameter.getParameterName().equals("timeOut") ||
+ newParameter.getParameterName().equals("padding") ||
+ newParameter.getParameterName().equals("direction") ||
+ newParameter.getParameterName().equals("size") ||
+ newParameter.getParameterName().equals("output") ||
+ newParameter.getParameterName().equals("portRange") ||
+ newParameter.getParameterName().equals("endDelay")) {
+ if (getParameterByName(newParameter.getParameterName()) !=
null) {
+ System.err.println("Error: " + getFileName() +
+ " 'setParameter(Parameter)' Duplicate parameter" +
+ " name: " + newParameter.getParameterName() +
+ " for id: " + newParameter.getId());
+ return;
+ }
+ parameterMap.put(newParameter.getParameterName(),
newParameter);
+ } else {
+ System.err.println("Error: " + getFileName() +
+ " 'addParameter(Parameter)' Unrecognized " +
+ " parameter: " + newParameter.getParameterName() + ".");
+ return;
+ }
+ } else {
+ System.err.println("Error: " + getFileName() +
+ " 'addParameter(Paramter)' Parameter cannont be nil.");
+ return;
+ }
+ }
+
+ @Override
+ public void addParameter(String name, String value)
+ {
+ if (!(name.isEmpty()) && !(value.isEmpty())) {
+ if (name.equals("count") ||
+ name.equals("dscp") ||
+ name.equals("phb") ||
+ name.equals("wait") ||
+ name.equals("timeOut") ||
+ name.equals("padding") ||
+ name.equals("endDelay") ||
+ name.equals("portRange") ||
+ name.equals("size") ||
+ name.equals("output") ||
+ name.equals("direction")) {
+ Parameter p = new Parameter();
+ p.setParameterName(name);
+ p.setParameterValue(value);
+ this.addParameter(p);
+ } else {
+ System.err.println("Error: " + getFileName() +
+ " 'addParameter(String, String)' Unrecognized " +
+ " parameter: " + name + ".");
+ return;
+ }
+ } else {
+ System.err.println("Error: " + getFileName() +
+ " 'addParameter(String, String)' cannot have nil value" +
+ " for name or value.");
+ return;
+ }
+ }
+
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/MathUtil.java
===================================================================
--- trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/MathUtil.java
2012-10-05 09:22:41 UTC (rev 6009)
+++ trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/MathUtil.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -11,11 +11,12 @@
* Class providing Mathematical functions
*
* @author loukik
- *
*/
-public class MathUtil {
+public class MathUtil
+{
- public MathUtil() {
+ public MathUtil()
+ {
}
@@ -25,45 +26,46 @@
*
* @param octetValues array of double values which represent octet values
* @return array of double values which represent bit values converted
from octet values <br>
- * returns null only if input is null
+ * returns null only if input is null
* @throws SystemException
* @throws DataFormatException
*/
- public double[] convertOctetsToBits (double[] octetValues) throws
PerfSONARException {
+ public double[] convertOctetsToBits(double[] octetValues) throws
PerfSONARException
+ {
- if(octetValues==null)
+ if (octetValues == null)
return null;
- if(octetValues.length==0)
+ if (octetValues.length == 0)
return octetValues;
double[] bitValues = new double[octetValues.length];
- for(int itr=0;itr<octetValues.length;itr++) {
+ for (int itr = 0; itr < octetValues.length; itr++) {
try {
bitValues[itr] = octetValues[itr] * 8;
- }catch(Exception e) {
+ } catch (Exception e) {
throw new PerfSONARException("MathUtil: Error converting
response octet values " +
- "to bit values: "+e.getMessage(), e);
+ "to bit values: " + e.getMessage(), e);
}
}
- if (bitValues==null) {
+ if (bitValues == null) {
throw new PerfSONARException("MathUtil: Error converting octet
values to bit values. Result was null");
}
- if (bitValues.length==0) {
+ if (bitValues.length == 0) {
throw new PerfSONARException("Mathutil: Conversion of values in
" +
- "octets to values in bits could not be completed.
Zero values " +
- "were converted");
+ "octets to values in bits could not be completed. Zero
values " +
+ "were converted");
}
@@ -77,45 +79,46 @@
*
* @param octetValues array of long values which represent octet values
* @return array of long values which represent bit values converted
from octet values <br>
- * returns null only if input is null
+ * returns null only if input is null
* @throws PerfSONARException
* @throws DataFormatException
*/
- public long[] convertOctetsToBits (long[] octetValues) throws
PerfSONARException {
+ public long[] convertOctetsToBits(long[] octetValues) throws
PerfSONARException
+ {
- if(octetValues==null)
+ if (octetValues == null)
return null;
- if(octetValues.length==0)
+ if (octetValues.length == 0)
return octetValues;
long[] bitValues = new long[octetValues.length];
- for(int itr=0;itr<octetValues.length;itr++) {
+ for (int itr = 0; itr < octetValues.length; itr++) {
try {
bitValues[itr] = octetValues[itr] * 8;
- }catch(Exception e) {
+ } catch (Exception e) {
throw new PerfSONARException("MathUtil: Error converting
response octet values " +
- "to bit values: "+e.getMessage(), e);
+ "to bit values: " + e.getMessage(), e);
}
}
- if (bitValues==null) {
+ if (bitValues == null) {
throw new PerfSONARException("MathUtil: Error converting octet
values to bit values. Result was null");
}
- if (bitValues.length==0) {
+ if (bitValues.length == 0) {
throw new PerfSONARException("Mathutil: Conversion of values in
" +
- "octets to values in bits could not be completed.
Zero values " +
- "were converted");
+ "octets to values in bits could not be completed. Zero
values " +
+ "were converted");
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/NetUtil.java
===================================================================
--- trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/NetUtil.java
2012-10-05 09:22:41 UTC (rev 6009)
+++ trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/NetUtil.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -5,27 +5,31 @@
*/
package org.perfsonar.base.util;
-/**Class containing Network related utilities
+/**
+ * Class containing Network related utilities
*
* @author loukik
- *
*/
-public class NetUtil {
- public NetUtil(){
+public class NetUtil
+{
+ public NetUtil()
+ {
}
/**
* Operation to check if a given IPv4 string is valid or not
+ *
* @param ipv4AddressString
* @return True if it is valid, False otherwise
*/
- public static boolean validateIPv4Address(String ipv4AddressString){
+ public static boolean validateIPv4Address(String ipv4AddressString)
+ {
String[] splitByDot;
splitByDot = ipv4AddressString.split("[.]+");
- if(splitByDot.length>4)
+ if (splitByDot.length > 4)
return false;
//TODO: complete work on IPv4 validation
@@ -34,10 +38,12 @@
/**
* Operation to check if a given IPv6 string is valid or not
+ *
* @param ipv6AddressString
* @return True if it is valid, False otherwise
*/
- public static boolean validateIPv6Address(String ipv6Address){
+ public static boolean validateIPv6Address(String ipv6Address)
+ {
// TODO: work on IPv6 validation
return true;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/StringBufferOutputStream.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/StringBufferOutputStream.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/StringBufferOutputStream.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -5,9 +5,11 @@
/**
* StringBuffer OutputStream. Writes to given StringBuffer
+ *
* @author Maciej Glowiak
*/
-public class StringBufferOutputStream extends OutputStream {
+public class StringBufferOutputStream extends OutputStream
+{
/**
@@ -18,9 +20,11 @@
/**
* Constructor, needs to specify StringBuffer destination
+ *
* @param sb
*/
- public StringBufferOutputStream (StringBuffer sb) {
+ public StringBufferOutputStream(StringBuffer sb)
+ {
this.sb = sb;
@@ -28,9 +32,10 @@
@Override
- public void write(int b) throws IOException {
+ public void write(int b) throws IOException
+ {
- sb.append((char)b);
+ sb.append((char) b);
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/TimeDateUtil.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/TimeDateUtil.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/TimeDateUtil.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -19,36 +19,36 @@
/**
- * This class contains methods that deal with time and date operations.
+ * This class contains methods that deal with time and date operations.
*
- * @author romradz
- *
+ * @author romradz
*/
-public class TimeDateUtil {
+public class TimeDateUtil
+{
/**
- * Returns unix time value.
+ * Returns unix time value.
+ * <p/>
+ * ISO format:
+ * <p/>
+ * datetime = time | date-opt-time
+ * time = 'T' time-element [offset]
+ * date-opt-time = date-element ['T' [time-element] [offset]]
+ * date-element = std-date-element | ord-date-element |
week-date-element
+ * std-date-element = yyyy ['-' MM ['-' dd]]
+ * ord-date-element = yyyy ['-' DDD]
+ * week-date-element = xxxx '-W' ww ['-' e]
+ * time-element = HH [minute-element] | [fraction]
+ * minute-element = ':' mm [second-element] | [fraction]
+ * second-element = ':' ss [fraction]
+ * fraction = ('.' | ',') digit+
+ * offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' |
',') SSS]]])
*
- * ISO format:
- *
- * datetime = time | date-opt-time
- * time = 'T' time-element [offset]
- * date-opt-time = date-element ['T' [time-element] [offset]]
- * date-element = std-date-element | ord-date-element |
week-date-element
- * std-date-element = yyyy ['-' MM ['-' dd]]
- * ord-date-element = yyyy ['-' DDD]
- * week-date-element = xxxx '-W' ww ['-' e]
- * time-element = HH [minute-element] | [fraction]
- * minute-element = ':' mm [second-element] | [fraction]
- * second-element = ':' ss [fraction]
- * fraction = ('.' | ',') digit+
- * offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' |
',') SSS]]])
- *
- *
- * @author romradz
+ * @author romradz
*/
public static String getUnixTime(Parameter timeParemeter)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
if (timeParemeter == null)
return null;
@@ -62,7 +62,8 @@
}
protected static String _getUnixTime(Parameter timeParemeter)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
Vector pchildren = timeParemeter.getChildrenByType("time");
Element subelement = null;
@@ -77,8 +78,8 @@
if (!subelement.getLocalName().equals("time"))
throw new PerfSONARException(
- "error.parameter",
- "TimeDateUtil._getUnixTime: wrong type of parameter; "
+ "error.parameter",
+ "TimeDateUtil._getUnixTime: wrong type of parameter; "
+ "it should be time type");
Time time = (Time) subelement;
@@ -95,20 +96,20 @@
DateTimeFormatter dtf = ISODateTimeFormat.dateTimeParser();
DateTime dt = dtf.parseDateTime(isoTimeString);
- unixTimeString = Long.toString(dt.getMillis()/1000);
+ unixTimeString = Long.toString(dt.getMillis() / 1000);
} catch (Exception ex) {
throw new PerfSONARException(
- "error.parameter",
- "TimeDateUtil._getUnixTime: ISO time coversion is
wrong; "
+ "error.parameter",
+ "TimeDateUtil._getUnixTime: ISO time coversion is wrong;
"
+ ex.toString());
}
} else {
throw new PerfSONARException(
- "error.parameter",
- "TimeDateUtil._getUnixTime: "
+ "error.parameter",
+ "TimeDateUtil._getUnixTime: "
+ "Time type " + time.getType() + "is not supported");
}
@@ -119,19 +120,20 @@
public static long getUnixTime(String isoTimeString)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
try {
DateTimeFormatter dtf = ISODateTimeFormat.dateTimeParser();
DateTime dt = dtf.parseDateTime(isoTimeString);
- return dt.getMillis()/1000;
+ return dt.getMillis() / 1000;
} catch (Exception ex) {
throw new PerfSONARException(
- "error.parameter",
- "TimeDateUtil.getUnixTime: ISO time coversion is
wrong; "
- + ex.toString());
+ "error.parameter",
+ "TimeDateUtil.getUnixTime: ISO time coversion is wrong; "
+ + ex.toString());
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/XMLUtils.java
===================================================================
--- trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/XMLUtils.java
2012-10-05 09:22:41 UTC (rev 6009)
+++ trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/XMLUtils.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -41,11 +41,11 @@
*
* @author Maciej Glowiak
* @author romradz (contributor)
- *
*/
-public class XMLUtils {
+public class XMLUtils
+{
- // --------------------------------------------------------------
constants
+ // --------------------------------------------------------------
constants
/* feature ids */
public static final String NAMESPACES_FEATURE_ID =
"http://xml.org/sax/features/namespaces";
@@ -60,10 +60,12 @@
/**
* Converts XML entities \<\; and \>\; to characters "<" ">".
+ *
* @param input input string
* @return ouput output string
*/
- public static String convertEntitiesToCharacters(String input) {
+ public static String convertEntitiesToCharacters(String input)
+ {
String output;
@@ -85,15 +87,16 @@
/**
* Serialize org.w3c.document
*/
- public static String serializeDOM(Document doc) throws Exception {
+ public static String serializeDOM(Document doc) throws Exception
+ {
- OutputFormat format = new OutputFormat( doc );
+ OutputFormat format = new OutputFormat(doc);
StringWriter stringOut = new StringWriter();
- XMLSerializer serial = new XMLSerializer( stringOut, format );
+ XMLSerializer serial = new XMLSerializer(stringOut, format);
serial.asDOMSerializer();
- serial.serialize( doc.getDocumentElement() );
+ serial.serialize(doc.getDocumentElement());
return stringOut.toString();
}
@@ -101,11 +104,13 @@
/**
* Serialize schema element. It omits all comments, document type and XML
* declaration, so can be used to generate part of XML document
+ *
* @param element NMWG schema element
* @return XML document as String
*/
public static String serializeXML(Element element)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
OutputFormat outputFormat = new OutputFormat("XML", "UTF-8", true);
outputFormat.setIndent(1);
@@ -116,18 +121,18 @@
StringBuffer outputBuffer = new StringBuffer();
XMLSerializer serializer = new XMLSerializer(
- new StringBufferOutputStream(outputBuffer),
- outputFormat);
+ new StringBufferOutputStream(outputBuffer),
+ outputFormat);
try {
ContentHandler hd = serializer.asContentHandler();
NamespaceSupport nss = new NamespaceSupport();
- element.toXML(hd, nss);
+ element.toXML(hd, nss);
return outputBuffer.toString();
} catch (Exception e) {
- String m = "XMLUtils.serializeXML: error while serializing XML:
"+
+ String m = "XMLUtils.serializeXML: error while serializing XML:
" +
e.getMessage();
throw new PerfSONARException(m);
}
@@ -136,12 +141,14 @@
/**
* Converts Message into DOM Document
+ *
* @param m message object
* @return Document
* @throws PerfSONARException if something goes wrong
*/
public static Document convertMessageToDOM(Message m)
- throws PerfSONARException{
+ throws PerfSONARException
+ {
try {
DocumentBuilder builder =
@@ -149,20 +156,21 @@
Document doc = builder.newDocument();
Document builtDoc = m.getDOM(doc);
- if (builtDoc==null) throw new NullPointerException();
+ if (builtDoc == null) throw new NullPointerException();
else return builtDoc;
} catch (Exception e) {
throw new PerfSONARException(
- "error.common.parse_error",
- "Cannot convert Message to DOM");
+ "error.common.parse_error",
+ "Cannot convert Message to DOM");
}
}
public static Document convertMessageToDOM(String m)
- throws PerfSONARException{
+ throws PerfSONARException
+ {
try {
java.io.InputStream stream = new
ByteArrayInputStream(m.getBytes());
@@ -174,8 +182,8 @@
} catch (Exception e) {
throw new PerfSONARException(
- "error.common.parse_error",
- "Cannot convert Message string to DOM");
+ "error.common.parse_error",
+ "Cannot convert Message string to DOM");
}
}
@@ -183,13 +191,15 @@
/**
* Converts Document containing message into NMWG Message object
+ *
* @param request - message Document
- * @param f - parser's mapping file
+ * @param f - parser's mapping file
* @return Message
* @throws Exception
*/
public static Message convertToMessage(Document request, String f)
- throws PerfSONARException{
+ throws PerfSONARException
+ {
XMLSerializer serializer = new XMLSerializer();
ByteArrayOutputStream boStream = new ByteArrayOutputStream();
@@ -228,45 +238,46 @@
parser.parse(ipSrc);
- } catch(SAXException e) {
+ } catch (SAXException e) {
throw new PerfSONARException("error.common.parse_error",
- "Request couldnot be parsed because "
- + "of SAX exception. Error message: "
- + e.getMessage());
+ "Request couldnot be parsed because "
+ + "of SAX exception. Error message: "
+ + e.getMessage());
}
} catch (IOException e) {
throw new PerfSONARException("error.common.parse_error",
- "IO exception: "
- + "encountered while reading schema file "
- + e.getMessage());
+ "IO exception: "
+ + "encountered while reading schema file "
+ + e.getMessage());
} catch (SAXException e) {
throw new PerfSONARException("error.common.parse_error",
- "SAX Exception: "
- + e.getMessage());
+ "SAX Exception: "
+ + e.getMessage());
} catch (ParserConfigurationException e) {
throw new PerfSONARException("error.common.parse_error", "Parser
Configuration "
- + "Exception " + e.getMessage());
+ + "Exception " + e.getMessage());
}
Message message =
- ((org.ggf.ns.nmwg.base.v2_0.MessageHandler)handler).getMessage();
+ ((org.ggf.ns.nmwg.base.v2_0.MessageHandler)
handler).getMessage();
return message;
}
/**
- * Returns nmwg object with specific tag name parsed from xml string
+ * Returns nmwg object with specific tag name parsed from xml string
*/
public static Map<String, Element> getElementFromXML(
- String xmlPart, String tagName, String parserFile) {
+ String xmlPart, String tagName, String parserFile)
+ {
- ElemHandler handler = parseNmwgXML(xmlPart, parserFile);
+ ElemHandler handler = parseNmwgXML(xmlPart, parserFile);
String[] tagNames = {tagName};
Map<String, Element> elements = handler.getElement(tagNames);
@@ -274,9 +285,10 @@
}
public static Map<String, Element> getElementFromXML(
- String xmlPart, String[] tagNames, String parserFile) {
+ String xmlPart, String[] tagNames, String parserFile)
+ {
- ElemHandler handler = parseNmwgXML(xmlPart, parserFile);
+ ElemHandler handler = parseNmwgXML(xmlPart, parserFile);
Map<String, Element> elements = handler.getElement(tagNames);
return elements;
@@ -286,16 +298,18 @@
/**
* Remove HTML/XML tags from string
*/
- public static String removeXMLTags(String xml) {
+ public static String removeXMLTags(String xml)
+ {
- return xml.replaceAll("\\<[^\\>]+\\>","");
+ return xml.replaceAll("\\<[^\\>]+\\>", "");
}
// --------------------------------------------------------- private
methods
public static ElemHandler parseNmwgXML(
- String xmlPart, String parserFile) {
+ String xmlPart, String parserFile)
+ {
String DEFAULT_PARSER_NAME = "org.apache.xerces.parsers.SAXParser";
@@ -340,7 +354,7 @@
parser.setErrorHandler(handler);
try {
- parser.parse(inputSource);
+ parser.parse(inputSource);
} catch (SAXParseException e) {
// ignore
} catch (Exception e) {
@@ -352,54 +366,59 @@
}
- public static String extractXMLTag(String str, String tag) {
+ public static String extractXMLTag(String str, String tag)
+ {
//trim from blank spaces
str = str.trim();
//find starting tag
- int indexStartTag1 = str.indexOf("<"+tag);
- if (indexStartTag1==-1) return null;
+ int indexStartTag1 = str.indexOf("<" + tag);
+ if (indexStartTag1 == -1) return null;
//find end of starting tag
int indexStartTag2 = str.indexOf(">", indexStartTag1);
- if (indexStartTag2==-1) return null;
+ if (indexStartTag2 == -1) return null;
//find closing tag
- int indexEndTag1 = str.indexOf("</"+tag, indexStartTag2);
- if (indexEndTag1==-1) return null;
+ int indexEndTag1 = str.indexOf("</" + tag, indexStartTag2);
+ if (indexEndTag1 == -1) return null;
- String substr = str.substring(indexStartTag2+1, indexEndTag1);
+ String substr = str.substring(indexStartTag2 + 1, indexEndTag1);
return substr;
}
/**
* Extracts attribute value from string
- * @param a string
+ *
+ * @param a string
* @param attribute attribute name
* @return
*/
public static String extractXMLAttributeValue(
- String str,
- String attribute) {
+ String str,
+ String attribute)
+ {
try { //just in case of a RuntimeException
int ind1 = str.indexOf(attribute);
- if (ind1>-1) { ind1 = str.indexOf('\"', ind1); }
- else return null; //attribute not found
+ if (ind1 > -1) {
+ ind1 = str.indexOf('\"', ind1);
+ } else return null; //attribute not found
- if (ind1>-1) {
- ind1+=1;
- int ind2 = str.indexOf('\"',ind1);
- if (ind2>-1) {
- return str.substring(ind1,ind2); //return value of
attribute
+ if (ind1 > -1) {
+ ind1 += 1;
+ int ind2 = str.indexOf('\"', ind1);
+ if (ind2 > -1) {
+ return str.substring(ind1, ind2); //return value of
attribute
}
}
- } catch (Exception ex) {}
+ } catch (Exception ex) {
+ }
return null; //bad xml?
@@ -409,95 +428,104 @@
/**
* Converts XML File into DOM Document
+ *
* @param file xml file in system
* @return Document
* @throws PerfSONARException if something goes wrong
*/
- public static Document convertXMLFileToDom(String file) throws
PerfSONARException{
+ public static Document convertXMLFileToDom(String file) throws
PerfSONARException
+ {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- Document dom;
- try {
+ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+ Document dom;
+ try {
- DocumentBuilder db = dbf.newDocumentBuilder();
- dom = db.parse(file);
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ dom = db.parse(file);
- }catch (IOException e) {
+ } catch (IOException e) {
throw new PerfSONARException("error.common.parse_error",
- "IO exception: "
- + "encountered while reading xml file "
- + e.getMessage());
- } catch (SAXException e) {
- throw new
PerfSONARException("error.common.parse_error",
- "SAX Exception: "
- + e.getMessage());
- } catch (ParserConfigurationException e) {
- throw new
PerfSONARException("error.common.parse_error", "Parser Configuration "
- + "Exception " + e.getMessage());
- }
+ "IO exception: "
+ + "encountered while reading xml file "
+ + e.getMessage());
+ } catch (SAXException e) {
+ throw new PerfSONARException("error.common.parse_error",
+ "SAX Exception: "
+ + e.getMessage());
+ } catch (ParserConfigurationException e) {
+ throw new PerfSONARException("error.common.parse_error", "Parser
Configuration "
+ + "Exception " + e.getMessage());
+ }
return dom;
}
/**
* Gets the internal elements of nodes with a specific tag
- * @param dom The document to get the elements from
- * @param node The tag for the nodes
+ *
+ * @param dom The document to get the elements from
+ * @param node The tag for the nodes
* @param elements A list of internal elements to get from the node
* @return Document
*/
- public static List<Map<String,String>> getNodeElementsFromDom(
- Document dom, String node, List<String> elements) {
-
- List<Map<String,String>> elementsMapList = new
ArrayList<Map<String,String>>();
- org.w3c.dom.Element root = dom.getDocumentElement();
+ public static List<Map<String, String>> getNodeElementsFromDom(
+ Document dom, String node, List<String> elements)
+ {
- NodeList nl = root.getElementsByTagName(node);
- if(nl != null && nl.getLength() > 0) {
- for(int i = 0 ; i < nl.getLength();i++) {
- org.w3c.dom.Element el =
(org.w3c.dom.Element)nl.item(i);
- HashMap<String,String> elementsMap = new
HashMap<String,String>();
- for(String e : elements)
- elementsMap.put(e,
getElementValue(el,e));
- elementsMapList.add(elementsMap);
- }
- }
-
- return elementsMapList;
+ List<Map<String, String>> elementsMapList = new
ArrayList<Map<String, String>>();
+ org.w3c.dom.Element root = dom.getDocumentElement();
+
+ NodeList nl = root.getElementsByTagName(node);
+ if (nl != null && nl.getLength() > 0) {
+ for (int i = 0; i < nl.getLength(); i++) {
+ org.w3c.dom.Element el = (org.w3c.dom.Element) nl.item(i);
+ HashMap<String, String> elementsMap = new HashMap<String,
String>();
+ for (String e : elements)
+ elementsMap.put(e, getElementValue(el, e));
+ elementsMapList.add(elementsMap);
+ }
+ }
+
+ return elementsMapList;
}
/**
* Auxiliar private method to get a text value from an Element
+ *
* @param element The element to get the value from
- * @param node The tag of the node which value is wanted
+ * @param node The tag of the node which value is wanted
* @return Document
*/
- private static String getElementValue(org.w3c.dom.Element element,
String node) {
- NodeList nl = element.getElementsByTagName(node);
- String value = null;
- if(nl != null && nl.getLength() > 0) {
- org.w3c.dom.Element el =
(org.w3c.dom.Element)nl.item(0);
- value = el.getFirstChild().getNodeValue();
- }
+ private static String getElementValue(org.w3c.dom.Element element,
String node)
+ {
+ NodeList nl = element.getElementsByTagName(node);
+ String value = null;
+ if (nl != null && nl.getLength() > 0) {
+ org.w3c.dom.Element el = (org.w3c.dom.Element) nl.item(0);
+ value = el.getFirstChild().getNodeValue();
+ }
- return value;
- }
+ return value;
+ }
// ---------------------------------------------------------- Inner class
/**
- * Private class based on Handler class from ggf package.
- * This adds a method to get any object representing xml tag
- * inside xml document.
+ * Private class based on Handler class from ggf package.
+ * This adds a method to get any object representing xml tag
+ * inside xml document.
*/
- private static class ElemHandler extends Handler {
+ private static class ElemHandler extends Handler
+ {
- public ElemHandler() {
+ public ElemHandler()
+ {
super();
}
- public Map<String, Element> getElement(String[] names) {
- Map<String, Element> map = new HashMap<String, Element>();
+ public Map<String, Element> getElement(String[] names)
+ {
+ Map<String, Element> map = new HashMap<String, Element>();
Element element;
boolean found = false;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/Constants.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/Constants.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/Constants.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -4,9 +4,9 @@
* Summarization code
*
* @author swany
- *
*/
-public interface Constants {
+public interface Constants
+{
public final static int MAX_KEY_LENGTH = 32;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/HelperClass.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/HelperClass.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/HelperClass.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -1,18 +1,20 @@
package org.perfsonar.base.util.iptrie;
import java.util.ArrayList;
+
/**
* Summarization code
*
* @author swany
- *
*/
-public class HelperClass {
+public class HelperClass
+{
// The purpose of the Helper class is to separate the code that is not
a part of the functionality of Trie.java,
// but makes use of the data found there for display purposes.
- public int displayElementsInKeyList(ArrayList<TrieNode> keyList) {
+ public int displayElementsInKeyList(ArrayList<TrieNode> keyList)
+ {
long keyDifference;
String mostDominantKey;
int noOfNodes = 0;
@@ -26,7 +28,8 @@
return noOfNodes;
}
- public String longToIP(Long ipInLong) {
+ public String longToIP(Long ipInLong)
+ {
String ipAddress = "";
long[] ipArrayInLong = new long[4];
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IPAddress.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IPAddress.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IPAddress.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -6,51 +6,60 @@
* Summarization code
*
* @author swany
- *
*/
-public class IPAddress {
- private String addrAsString;
- private long addrAsLong;
- private long maskAsLong;
-
- public IPAddress (String newIp) throws InvalidIPAddressException {
- addrAsString = newIp;
- addrAsLong = this.ipToLong(newIp);
- }
+public class IPAddress
+{
+ private String addrAsString;
+ private long addrAsLong;
+ private long maskAsLong;
- public String getString() {
- return addrAsString;
- }
- public long getAddrAsLong() {
- return addrAsLong;
- }
- public long getMaskAsLong() {
- return maskAsLong;
- }
+ public IPAddress(String newIp) throws InvalidIPAddressException
+ {
+ addrAsString = newIp;
+ addrAsLong = this.ipToLong(newIp);
+ }
- public long ipToLong(String ip) throws InvalidIPAddressException {
-
- ip = ip.replace(".", ":");
- String[] splitIP = ip.split(":");
- long temp;
- long ipInLong = 0;
-
- for (String aSplitIP : splitIP) {
+ public String getString()
+ {
+ return addrAsString;
+ }
+
+ public long getAddrAsLong()
+ {
+ return addrAsLong;
+ }
+
+ public long getMaskAsLong()
+ {
+ return maskAsLong;
+ }
+
+ public long ipToLong(String ip) throws InvalidIPAddressException
+ {
+
+ ip = ip.replace(".", ":");
+ String[] splitIP = ip.split(":");
+ long temp;
+ long ipInLong = 0;
+
+ for (String aSplitIP : splitIP) {
try {
temp = Long.parseLong(aSplitIP);
} catch (Exception e) {
- throw new InvalidIPAddressException("IP address is not
valid"+ip);
+ throw new InvalidIPAddressException("IP address is not
valid" + ip);
}
if (temp < 0 || temp > 256) {
- throw new InvalidIPAddressException("IP address is not
valid: "+ip);
+ throw new InvalidIPAddressException("IP address is not
valid: " + ip);
}
ipInLong = (ipInLong << 8) + temp;
}
-
- return ipInLong;
-
- }
- public long[] ipArrayToLongArray(String[] ip) throws
InvalidIPAddressException {
+
+ return ipInLong;
+
+ }
+
+ public long[] ipArrayToLongArray(String[] ip) throws
InvalidIPAddressException
+ {
long[] ipArray = new long[ip.length];
for (int i = 0; i < ip.length; i++) {
@@ -63,10 +72,10 @@
try {
temp = Long.parseLong(aSplitIP);
} catch (Exception e) {
- throw new InvalidIPAddressException("IP address is not
valid: "+ Arrays.toString(ip));
+ throw new InvalidIPAddressException("IP address is not
valid: " + Arrays.toString(ip));
}
if (temp < 0 || temp > 256) {
- throw new InvalidIPAddressException("IP address is not
valid "+ Arrays.toString(ip));
+ throw new InvalidIPAddressException("IP address is not
valid " + Arrays.toString(ip));
}
ipInLong = (ipInLong << 8) + temp;
}
@@ -75,7 +84,8 @@
return ipArray;
}
- public String longToIP(Long ipInLong) {
+ public String longToIP(Long ipInLong)
+ {
String ipAddress = "";
long[] ipArrayInLong = new long[4];
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IPAddressConvertor.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IPAddressConvertor.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IPAddressConvertor.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -4,9 +4,9 @@
* Summarization code
*
* @author swany
- *
*/
-public class IPAddressConvertor {
+public class IPAddressConvertor
+{
private String ipAddress;
private int subnetMask;
private String keyMappedToIPAddress;
@@ -23,11 +23,10 @@
public void splitIPAddressOnSubnetMask() throws InvalidIPAddressException
{
String[] splitIP = ipAddress.split("/");
- if(splitIP.length == 2){
+ if (splitIP.length == 2) {
subnetMask = Integer.parseInt(splitIP[1]);
ipAddress = splitIP[0];
- }
- else{
+ } else {
throw new InvalidIPAddressException(message);
}
}
@@ -50,7 +49,8 @@
}
}
- public String getKey() {
+ public String getKey()
+ {
return keyMappedToIPAddress;
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/InvalidIPAddressException.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/InvalidIPAddressException.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/InvalidIPAddressException.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -1,15 +1,17 @@
package org.perfsonar.base.util.iptrie;
+
/**
* Summarization code
*
* @author swany
- *
*/
@SuppressWarnings("serial")
-public class InvalidIPAddressException extends Exception{
+public class InvalidIPAddressException extends Exception
+{
- InvalidIPAddressException(final String message) {
+ InvalidIPAddressException(final String message)
+ {
super(message);
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IpTrie.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IpTrie.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IpTrie.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -6,204 +6,212 @@
/**
* @author swany
- * This class wraps the base Trie with IP-specific semantics
- * such as shifting the current keys into the correct position.
- * For now, this will be created from a basic Trie containing
- * IP information and will provide iterator functionality
+ * This class wraps the base Trie with IP-specific semantics
+ * such as shifting the current keys into the correct position.
+ * For now, this will be created from a basic Trie containing
+ * IP information and will provide iterator functionality
*/
-public class IpTrie {
+public class IpTrie
+{
- private Trie trie;
- private ArrayList<IpTrieNode> nodelist;
- IpTrieNode root;
-
- public IpTrie (Trie t) {
- // need to establish state for an iterator
- trie = t;
- nodelist = new ArrayList<IpTrieNode>();
- this.updateNodelist();
- }
-
- /**
- * this method will walk the Trie and fill in IpTrieNodes
- */
- public void updateNodelist() {
- nodelist.clear();
- long startPosition = Constants.MAX_KEY_LENGTH;
- long startKey = 0;
- root = new IpTrieNode(trie.getRootNode(), startPosition,
startKey);
- nodelist.add(root);
- walkTree(root, startPosition, startKey);
- }
-
- // walk the tree from node down
- private void walkTree(IpTrieNode node, long position, long
currentKey) {
- TrieNode tnode = node.trieNode;
- TrieNode c0 = tnode.getChildZero();
- TrieNode c1 = tnode.getChildOne();
-
- if (c0 != null) {
- long c0Key = c0.getKey() << (position - c0.getKeyLength());
- long c0Position = position - c0.getKeyLength();
- c0Key = c0Key | currentKey;
- IpTrieNode c0ipTrieNode = new IpTrieNode(c0, c0Position,
c0Key);
- nodelist.add(c0ipTrieNode);
- node.setChildZero(c0ipTrieNode);
- c0ipTrieNode.setParent(node);
- walkTree(c0ipTrieNode,c0Position, c0Key);
+ private Trie trie;
+ private ArrayList<IpTrieNode> nodelist;
+ IpTrieNode root;
- }
- if (c1 != null) {
- long c1Key = c1.getKey() << (position - c1.getKeyLength());
- long c1Position = position - c1.getKeyLength();
- c1Key = c1Key | currentKey;
- IpTrieNode c1ipTrieNode = new IpTrieNode(c1, c1Position,
c1Key);
- nodelist.add(c1ipTrieNode);
- node.setChildOne(c1ipTrieNode);
- c1ipTrieNode.setParent(node);
- walkTree(c1ipTrieNode,c1Position, c1Key);
- }
+ public IpTrie(Trie t)
+ {
+ // need to establish state for an iterator
+ trie = t;
+ nodelist = new ArrayList<IpTrieNode>();
+ this.updateNodelist();
+ }
- }
-
- public ArrayList<IpTrieNode> getNodes() {
- return nodelist;
- }
-
- public ArrayList<IpTrieNode> getInternalNodes() {
- ArrayList<IpTrieNode> alitn = new ArrayList<IpTrieNode>();
- Iterator<IpTrieNode> it = nodelist.iterator();
- for ( IpTrieNode node; it.hasNext(); ) {
- node = it.next();
- if (node.childZero != null) {
- alitn.add(node);
- }
- }
- return alitn;
- }
-
- public ArrayList<IpTrieNode> getSummaryNodes() {
- ArrayList<IpTrieNode> alitn = new ArrayList<IpTrieNode>();
- Iterator<IpTrieNode> it = nodelist.iterator();
- for ( IpTrieNode node; it.hasNext(); ) {
- node = it.next();
- // evaluate what to return
- // here we say if the data pointer is null, but it
- // has one child with data, then it is on the summary
front
-
- // hackage for the root node, which might have a null
child
- // no other node does
- if (node.childOne == null || node.childZero == null)
continue;
-
- if (node.trieNode.getData() == null &&
- (node.childZero.trieNode.getData() != null ||
- node.childOne.trieNode.getData() != null) ) {
- alitn.add(node);
- }
- }
- return alitn;
- }
-
- public ArrayList<IpTrieNode> getSummaryNodesHueristic_dumb() {
- ArrayList<IpTrieNode> alitn = new ArrayList<IpTrieNode>();
- Iterator<IpTrieNode> it = nodelist.iterator();
- for ( IpTrieNode node; it.hasNext(); ) {
- node = it.next();
- // evaluate what to return
- // here we say if the data pointer is null, but it
- // has one child with data, then it is on the summary
front
-
- // hackage for the root node, which might have a null
child
- // no other node does
- if (node.childOne == null || node.childZero == null)
continue;
-
- if (node.trieNode.getData() == null &&
- (node.childZero.trieNode.getData() != null ||
- node.childOne.trieNode.getData() != null) ) {
- alitn.add(node);
- }
- }
-
- ArrayList<IpTrieNode> alitn2 = new ArrayList<IpTrieNode>();
- it = alitn.iterator();
- for ( IpTrieNode node; it.hasNext(); ) {
- node = it.next();
- if( (node.mask - node.parent.mask) > 2) {
- alitn2.add(node);
- }
- }
-
- //sanity check
- long sum = 0;
- it = alitn2.iterator();
- for ( IpTrieNode node; it.hasNext(); ) {
- node = it.next();
- System.out.println(node.addrString + " " +
node.childCount);
- sum += node.childCount;
- }
-
- if (sum != trie.getCount()) {
- System.out.println("sum, nodeCount " + sum + " " +
trie.getCount());
- System.out.println("Heuristic failed!");
- alitn2.clear();
- }
- return alitn2;
- }
-
- public ArrayList<IpTrieNode> getSummary() {
- ArrayList<IpTrieNode> alitn = new ArrayList<IpTrieNode>();
- if (root.childZero != null) {
- walkIpTrie(alitn, root.childZero);
- }
- if (root.childOne != null) {
- walkIpTrie(alitn, root.childOne);
- }
-
- //sanity check
- long sum = 0;
- Iterator<IpTrieNode> it = alitn.iterator();
- for ( IpTrieNode node; it.hasNext(); ) {
- node = it.next();
- sum += node.childCount;
- if (node.mask == 32) sum++;
- }
-
- if (sum != trie.getCount()) {
- System.out.println("Summarization failed! (covered "
+ sum + "prefixes out of " + trie.getCount() + ")");
- alitn.clear();
- }
-
- return alitn;
- }
-
- /* this will consider whether to recurse down the tree or
- * add itself to the summary list and prune the subtree.
- */
- private void walkIpTrie (ArrayList<IpTrieNode> alitn, IpTrieNode
node) {
- IpTrieNode c0n = node.childZero;
- IpTrieNode c1n = node.childOne;
-
- if(c0n == null) {
- alitn.add(node);
- }
- else if((c0n.mask - node.mask > 8) || (c1n.mask - node.mask >
8)) {
- walkIpTrie(alitn, c0n);
- walkIpTrie(alitn, c1n);
- }
- else {
- alitn.add(node);
- }
-
- }
- /*
- public void printDot(String fileName) throws FileNotFoundException {
- FileOutputStream file = new FileOutputStream(fileName);
- PrintStream p = new PrintStream(file);
- p.println("digraph g {");
-
- p.println("}");
- p.close();
- }
- */
+ /**
+ * this method will walk the Trie and fill in IpTrieNodes
+ */
+ public void updateNodelist()
+ {
+ nodelist.clear();
+ long startPosition = Constants.MAX_KEY_LENGTH;
+ long startKey = 0;
+ root = new IpTrieNode(trie.getRootNode(), startPosition, startKey);
+ nodelist.add(root);
+ walkTree(root, startPosition, startKey);
+ }
+
+ // walk the tree from node down
+ private void walkTree(IpTrieNode node, long position, long currentKey)
+ {
+ TrieNode tnode = node.trieNode;
+ TrieNode c0 = tnode.getChildZero();
+ TrieNode c1 = tnode.getChildOne();
+
+ if (c0 != null) {
+ long c0Key = c0.getKey() << (position - c0.getKeyLength());
+ long c0Position = position - c0.getKeyLength();
+ c0Key = c0Key | currentKey;
+ IpTrieNode c0ipTrieNode = new IpTrieNode(c0, c0Position, c0Key);
+ nodelist.add(c0ipTrieNode);
+ node.setChildZero(c0ipTrieNode);
+ c0ipTrieNode.setParent(node);
+ walkTree(c0ipTrieNode, c0Position, c0Key);
+
+ }
+ if (c1 != null) {
+ long c1Key = c1.getKey() << (position - c1.getKeyLength());
+ long c1Position = position - c1.getKeyLength();
+ c1Key = c1Key | currentKey;
+ IpTrieNode c1ipTrieNode = new IpTrieNode(c1, c1Position, c1Key);
+ nodelist.add(c1ipTrieNode);
+ node.setChildOne(c1ipTrieNode);
+ c1ipTrieNode.setParent(node);
+ walkTree(c1ipTrieNode, c1Position, c1Key);
+ }
+
+ }
+
+ public ArrayList<IpTrieNode> getNodes()
+ {
+ return nodelist;
+ }
+
+ public ArrayList<IpTrieNode> getInternalNodes()
+ {
+ ArrayList<IpTrieNode> alitn = new ArrayList<IpTrieNode>();
+ Iterator<IpTrieNode> it = nodelist.iterator();
+ for (IpTrieNode node; it.hasNext(); ) {
+ node = it.next();
+ if (node.childZero != null) {
+ alitn.add(node);
+ }
+ }
+ return alitn;
+ }
+
+ public ArrayList<IpTrieNode> getSummaryNodes()
+ {
+ ArrayList<IpTrieNode> alitn = new ArrayList<IpTrieNode>();
+ Iterator<IpTrieNode> it = nodelist.iterator();
+ for (IpTrieNode node; it.hasNext(); ) {
+ node = it.next();
+ // evaluate what to return
+ // here we say if the data pointer is null, but it
+ // has one child with data, then it is on the summary front
+
+ // hackage for the root node, which might have a null child
+ // no other node does
+ if (node.childOne == null || node.childZero == null) continue;
+
+ if (node.trieNode.getData() == null &&
+ (node.childZero.trieNode.getData() != null ||
+ node.childOne.trieNode.getData() != null)) {
+ alitn.add(node);
+ }
+ }
+ return alitn;
+ }
+
+ public ArrayList<IpTrieNode> getSummaryNodesHueristic_dumb()
+ {
+ ArrayList<IpTrieNode> alitn = new ArrayList<IpTrieNode>();
+ Iterator<IpTrieNode> it = nodelist.iterator();
+ for (IpTrieNode node; it.hasNext(); ) {
+ node = it.next();
+ // evaluate what to return
+ // here we say if the data pointer is null, but it
+ // has one child with data, then it is on the summary front
+
+ // hackage for the root node, which might have a null child
+ // no other node does
+ if (node.childOne == null || node.childZero == null) continue;
+
+ if (node.trieNode.getData() == null &&
+ (node.childZero.trieNode.getData() != null ||
+ node.childOne.trieNode.getData() != null)) {
+ alitn.add(node);
+ }
+ }
+
+ ArrayList<IpTrieNode> alitn2 = new ArrayList<IpTrieNode>();
+ it = alitn.iterator();
+ for (IpTrieNode node; it.hasNext(); ) {
+ node = it.next();
+ if ((node.mask - node.parent.mask) > 2) {
+ alitn2.add(node);
+ }
+ }
+
+ //sanity check
+ long sum = 0;
+ it = alitn2.iterator();
+ for (IpTrieNode node; it.hasNext(); ) {
+ node = it.next();
+ System.out.println(node.addrString + " " + node.childCount);
+ sum += node.childCount;
+ }
+
+ if (sum != trie.getCount()) {
+ System.out.println("sum, nodeCount " + sum + " " +
trie.getCount());
+ System.out.println("Heuristic failed!");
+ alitn2.clear();
+ }
+ return alitn2;
+ }
+
+ public ArrayList<IpTrieNode> getSummary()
+ {
+ ArrayList<IpTrieNode> alitn = new ArrayList<IpTrieNode>();
+ if (root.childZero != null) {
+ walkIpTrie(alitn, root.childZero);
+ }
+ if (root.childOne != null) {
+ walkIpTrie(alitn, root.childOne);
+ }
+
+ //sanity check
+ long sum = 0;
+ Iterator<IpTrieNode> it = alitn.iterator();
+ for (IpTrieNode node; it.hasNext(); ) {
+ node = it.next();
+ sum += node.childCount;
+ if (node.mask == 32) sum++;
+ }
+
+ if (sum != trie.getCount()) {
+ System.out.println("Summarization failed! (covered " + sum +
"prefixes out of " + trie.getCount() + ")");
+ alitn.clear();
+ }
+
+ return alitn;
+ }
+
+ /* this will consider whether to recurse down the tree or
+ * add itself to the summary list and prune the subtree.
+ */
+ private void walkIpTrie(ArrayList<IpTrieNode> alitn, IpTrieNode node)
+ {
+ IpTrieNode c0n = node.childZero;
+ IpTrieNode c1n = node.childOne;
+
+ if (c0n == null) {
+ alitn.add(node);
+ } else if ((c0n.mask - node.mask > 8) || (c1n.mask - node.mask > 8))
{
+ walkIpTrie(alitn, c0n);
+ walkIpTrie(alitn, c1n);
+ } else {
+ alitn.add(node);
+ }
+
+ }
+ /*
+ public void printDot(String fileName) throws FileNotFoundException {
+ FileOutputStream file = new FileOutputStream(fileName);
+ PrintStream p = new PrintStream(file);
+ p.println("digraph g {");
+
+ p.println("}");
+ p.close();
+ }
+ */
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IpTrieNode.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IpTrieNode.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/IpTrieNode.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -3,42 +3,47 @@
/**
* @author swany
- * This class contains IP-specific references to a
- * generic Trie
+ * This class contains IP-specific references to a
+ * generic Trie
*/
-public class IpTrieNode {
- long mask;
- long ipAddress;
- long key;
- String keyString;
- String addrString;
- TrieNode trieNode;
- IpTrieNode parent;
- IpTrieNode childZero, childOne;
- long childCount;
-
- public IpTrieNode(TrieNode tnode, long position, long currentKey) {
- HelperClass helper = new HelperClass();
- trieNode = tnode;
- mask = Constants.MAX_KEY_LENGTH - position;
- key = currentKey;
- keyString = helper.longToIP(key);
- addrString = keyString + "/" + mask;
- childCount = tnode.getChildCount();
- }
-
- public IpTrieNode setParent(IpTrieNode newParent) {
- parent = newParent;
- return this;
- }
-
- public IpTrieNode setChildZero(IpTrieNode newChild) {
- childZero = newChild;
- return this;
- }
-
- public IpTrieNode setChildOne(IpTrieNode newChild) {
- childOne = newChild;
- return this;
- }
+public class IpTrieNode
+{
+ long mask;
+ long ipAddress;
+ long key;
+ String keyString;
+ String addrString;
+ TrieNode trieNode;
+ IpTrieNode parent;
+ IpTrieNode childZero, childOne;
+ long childCount;
+
+ public IpTrieNode(TrieNode tnode, long position, long currentKey)
+ {
+ HelperClass helper = new HelperClass();
+ trieNode = tnode;
+ mask = Constants.MAX_KEY_LENGTH - position;
+ key = currentKey;
+ keyString = helper.longToIP(key);
+ addrString = keyString + "/" + mask;
+ childCount = tnode.getChildCount();
+ }
+
+ public IpTrieNode setParent(IpTrieNode newParent)
+ {
+ parent = newParent;
+ return this;
+ }
+
+ public IpTrieNode setChildZero(IpTrieNode newChild)
+ {
+ childZero = newChild;
+ return this;
+ }
+
+ public IpTrieNode setChildOne(IpTrieNode newChild)
+ {
+ childOne = newChild;
+ return this;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/StringBufferUtilities.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/StringBufferUtilities.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/StringBufferUtilities.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -9,11 +9,12 @@
* Summarization code
*
* @author swany
- *
*/
-public class StringBufferUtilities {
+public class StringBufferUtilities
+{
- public static String getContents(String fileName) {
+ public static String getContents(String fileName)
+ {
StringBuilder contents = new StringBuilder();
BufferedReader input = null;
@@ -23,20 +24,16 @@
while (((line = input.readLine()) != null)) {
contents.append(line).append("\n");
}
- }
- catch (FileNotFoundException ex) {
+ } catch (FileNotFoundException ex) {
ex.printStackTrace();
- }
- catch (IOException ex) {
+ } catch (IOException ex) {
ex.printStackTrace();
- }
- finally {
+ } finally {
try {
if (input != null) {
input.close();
}
- }
- catch (IOException ex) {
+ } catch (IOException ex) {
ex.printStackTrace();
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/SummarizeIpAddrs.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/SummarizeIpAddrs.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/SummarizeIpAddrs.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -12,17 +12,19 @@
*
* @author swany
* @author mac
- *
*/
-public class SummarizeIpAddrs {
+public class SummarizeIpAddrs
+{
/**
* Main method, reads input set of IP addresses, returns summarized set
* of IP addresses/masks
+ *
* @param ipAddresses
* @return set of strings containing IP addresses/masks
*/
- public static HashSet<String> getSummary(Collection<String> ipAddresses)
{
+ public static HashSet<String> getSummary(Collection<String> ipAddresses)
+ {
final TrieNode ROOTNODE = new TrieNode(-1, Constants.MAX_KEY_LENGTH);
Trie trie = new Trie(ROOTNODE);
@@ -53,7 +55,8 @@
* @param args
*/
public static void main(String[] args) throws InvalidIPAddressException,
- IOException {
+ IOException
+ {
String inputFile;
if (args.length > 0) {
@@ -63,7 +66,7 @@
}
String[] splitIPAddressInString = StringBufferUtilities.getContents(
- inputFile).split("\n");
+ inputFile).split("\n");
Collection<String> ipAddresses =
Arrays.asList(splitIPAddressInString);
Set<String> result = getSummary(ipAddresses);
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/Trie.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/Trie.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/Trie.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -10,48 +10,51 @@
* Summarization code
*
* @author swany
- *
*/
-public class Trie {
+public class Trie
+{
private int nodeCount;
private ArrayList<TrieNode> keyList = new ArrayList<TrieNode>();
- public ArrayList<TrieNode> getKeyList() {
+ public ArrayList<TrieNode> getKeyList()
+ {
return keyList;
}
private TrieNode rootNode;
- public Trie(TrieNode rootnode) {
+ public Trie(TrieNode rootnode)
+ {
rootNode = rootnode;
}
- public TrieNode getRootNode() {
- return rootNode;
+ public TrieNode getRootNode()
+ {
+ return rootNode;
}
- private long firstDigit(long key, long keyLength) {
+ private long firstDigit(long key, long keyLength)
+ {
return ((key >> (keyLength - 1)) & 1);
}
- public Trie Add(long key, long keyLength, Object data) {
+ public Trie Add(long key, long keyLength, Object data)
+ {
nodeCount++;
rootNode.incrementChildCount();
if (firstDigit(key, keyLength) == 1) {
if (rootNode.getChildOne() != null) {
rootNode.getChildOne().Add(key, keyLength, data);
- }
- else {
+ } else {
rootNode.setChildOne(new TrieNode(key, keyLength));
rootNode.getChildOne().setData(data);
}
} else {
if (rootNode.getChildZero() != null) {
rootNode.getChildZero().Add(key, keyLength, data);
- }
- else {
+ } else {
rootNode.setChildZero(new TrieNode(key, keyLength));
rootNode.getChildZero().setData(data);
}
@@ -59,21 +62,23 @@
return this;
}
- public boolean FindExactMatch(long key, long keyLength) {
+ public boolean FindExactMatch(long key, long keyLength)
+ {
if (firstDigit(key, keyLength) == 1)
return rootNode.getChildOne() != null &&
rootNode.getChildOne().FindExactMatch(key, keyLength);
else
return rootNode.getChildZero() != null &&
rootNode.getChildZero().FindExactMatch(key, keyLength);
}
- // public Trie Merge(Trie trie) {
- // List<Long> keys = trie.GetKeys();
- // for (Long key : keys)
- // this.Add(Long.parseLong(key.toString()),
Constants.MAX_KEY_LENGTH);
- // return this;
- // }
+ // public Trie Merge(Trie trie) {
+ // List<Long> keys = trie.GetKeys();
+ // for (Long key : keys)
+ // this.Add(Long.parseLong(key.toString()),
Constants.MAX_KEY_LENGTH);
+ // return this;
+ // }
- public List<Long> GetKeys() {
+ public List<Long> GetKeys()
+ {
long key = 0;
long position = Constants.MAX_KEY_LENGTH;
List<Long> keys = new ArrayList<Long>();
@@ -87,7 +92,8 @@
return keys;
}
- private List<Long> GetKeys(List<Long> keys, TrieNode node, long key,
long position) {
+ private List<Long> GetKeys(List<Long> keys, TrieNode node, long key,
long position)
+ {
key = key | (node.getKey() << (position - node.getKeyLength()));
if (node.getChildZero() != null)
@@ -102,7 +108,8 @@
}
//returns the best match of keys for the given inputs
- public TrieNode FindBestMatch(long key, long keyLength) {
+ public TrieNode FindBestMatch(long key, long keyLength)
+ {
//implements the best match by digging all the way to the leaf based
on the key difference.
if (firstDigit(key, keyLength) == 1) {
if (rootNode.getChildOne() != null)
@@ -114,7 +121,8 @@
return rootNode.getChildZero().FindBestMatch(key, keyLength);
}
- public boolean Equals(Trie trie) {
+ public boolean Equals(Trie trie)
+ {
if (trie != null) {
if (this.getCount() == trie.getCount()) {
List<Long> list1 = this.GetKeys();
@@ -130,11 +138,13 @@
return false;
}
- public long getCount() {
+ public long getCount()
+ {
return nodeCount;
}
- public boolean Remove(long key, long keyLength) {
+ public boolean Remove(long key, long keyLength)
+ {
TrieNode root;
root = firstDigit(key, keyLength) == 1 ? rootNode.getChildOne() :
rootNode.getChildZero();
@@ -146,7 +156,8 @@
return false;
}
- private boolean Remove(TrieNode node, long key, long keyLength, long
currentKeyLength) {
+ private boolean Remove(TrieNode node, long key, long keyLength, long
currentKeyLength)
+ {
boolean success;
TrieNode child;
@@ -188,7 +199,8 @@
return success;
}
- public void mostDominantKeyList() {
+ public void mostDominantKeyList()
+ {
TrieNode childOne = rootNode.getChildOne();
TrieNode childZero = rootNode.getChildZero();
@@ -201,7 +213,8 @@
}
}
- private void mostDominantKeyList(TrieNode node, long key, long position)
{
+ private void mostDominantKeyList(TrieNode node, long key, long position)
+ {
TrieNode childZero = node.getChildZero();
TrieNode childOne = node.getChildOne();
@@ -218,30 +231,33 @@
keyList.add(new TrieNode(key, position));
}
- public void printDot(String fileName) throws FileNotFoundException {
- FileOutputStream file = new FileOutputStream(fileName);
- PrintStream p = new PrintStream(file);
- long position = Constants.MAX_KEY_LENGTH;
- long currentKey = 0;
- p.println("digraph g {");
- rootNode.printDotNode(p, rootNode, position, currentKey);
- p.println("}");
- p.close();
+ public void printDot(String fileName) throws FileNotFoundException
+ {
+ FileOutputStream file = new FileOutputStream(fileName);
+ PrintStream p = new PrintStream(file);
+ long position = Constants.MAX_KEY_LENGTH;
+ long currentKey = 0;
+ p.println("digraph g {");
+ rootNode.printDotNode(p, rootNode, position, currentKey);
+ p.println("}");
+ p.close();
}
- public ArrayList<String> listInternalNodes() {
- long position = Constants.MAX_KEY_LENGTH;
- long currentKey = 0;
- ArrayList<String> listOfNodes = new ArrayList<String>();
- rootNode.listInternalNodes(listOfNodes, position, currentKey);
- return listOfNodes;
+ public ArrayList<String> listInternalNodes()
+ {
+ long position = Constants.MAX_KEY_LENGTH;
+ long currentKey = 0;
+ ArrayList<String> listOfNodes = new ArrayList<String>();
+ rootNode.listInternalNodes(listOfNodes, position, currentKey);
+ return listOfNodes;
}
- public ArrayList<String> listSummaryNodes() {
- long position = Constants.MAX_KEY_LENGTH;
- long currentKey = 0;
- ArrayList<String> listOfNodes = new ArrayList<String>();
- rootNode.listSummaryNodes(listOfNodes, position, currentKey);
- return listOfNodes;
+ public ArrayList<String> listSummaryNodes()
+ {
+ long position = Constants.MAX_KEY_LENGTH;
+ long currentKey = 0;
+ ArrayList<String> listOfNodes = new ArrayList<String>();
+ rootNode.listSummaryNodes(listOfNodes, position, currentKey);
+ return listOfNodes;
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/TrieNode.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/TrieNode.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/base/util/iptrie/TrieNode.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -7,9 +7,9 @@
* Summarization code
*
* @author swany
- *
*/
-public class TrieNode {
+public class TrieNode
+{
private long key;
@@ -27,57 +27,69 @@
HelperClass helper = new HelperClass();
- public void incrementChildCount() {
- this.childCount++;
+ public void incrementChildCount()
+ {
+ this.childCount++;
}
- public long getChildCount() {
- return this.childCount;
+ public long getChildCount()
+ {
+ return this.childCount;
}
- public TrieNode getChildZero() {
+ public TrieNode getChildZero()
+ {
return childZero;
}
- public void setChildZero(TrieNode childZero) {
+ public void setChildZero(TrieNode childZero)
+ {
this.childZero = childZero;
}
- public TrieNode getChildOne() {
+ public TrieNode getChildOne()
+ {
return childOne;
}
- public void setChildOne(TrieNode childOne) {
+ public void setChildOne(TrieNode childOne)
+ {
this.childOne = childOne;
}
- public long getKey() {
+ public long getKey()
+ {
return key;
}
- public long getKeyLength() {
+ public long getKeyLength()
+ {
return keyLength;
}
- private TrieNode(long key, long keyLength, long valueCount) {
+ private TrieNode(long key, long keyLength, long valueCount)
+ {
this.key = key;
this.keyLength = keyLength;
this.valueCount = valueCount;
}
- public TrieNode(long key, long keyLength) {
+ public TrieNode(long key, long keyLength)
+ {
this.key = key;
this.keyLength = keyLength;
valueCount = 1;
childCount = 0;
}
- private static long firstDigit(long key, long keyLength) {
+ private static long firstDigit(long key, long keyLength)
+ {
return (key >> (keyLength - 1)) & 1;
}
- private static long[] getCommonPart(long keyA, long keyLengthA, long
keyB, long keyLengthB) {
+ private static long[] getCommonPart(long keyA, long keyLengthA, long
keyB, long keyLengthB)
+ {
// truncate the keys so they are the same size (discard low bits)
if (keyLengthA > keyLengthB) {
keyA >>= keyLengthA - keyLengthB;
@@ -99,38 +111,46 @@
return new long[]{keyCommon, keyLengthCommon};
}
- public boolean Equals(TrieNode node) {
+ public boolean Equals(TrieNode node)
+ {
return node != null && (this.key == node.key && this.keyLength ==
node.keyLength);
}
- public boolean isKey() {
+ public boolean isKey()
+ {
return valueCount > 0;
}
//no of times the key is repeated.
- public long getValueCount() {
+ public long getValueCount()
+ {
return valueCount;
}
- public void setValueCount(long valueCount) {
+ public void setValueCount(long valueCount)
+ {
this.valueCount = valueCount;
}
- public void setValueCount(Object value) {
+ public void setValueCount(Object value)
+ {
data = value;
}
- public Object getData() {
+ public Object getData()
+ {
return data;
}
- public void setData(Object data) {
+ public void setData(Object data)
+ {
this.data = data;
}
- public TrieNode Add(long key, long keyLength, Object data) {
- this.childCount++;
-
+ public TrieNode Add(long key, long keyLength, Object data)
+ {
+ this.childCount++;
+
if (key == this.key && keyLength == this.keyLength) {
this.valueCount++;
} else {
@@ -139,7 +159,7 @@
TrieNode newNode;
long[] commonKeyAndKeyLength =
- getCommonPart(key, keyLength, this.key, this.keyLength);
+ getCommonPart(key, keyLength, this.key, this.keyLength);
long keyCommon = commonKeyAndKeyLength[0];
long keyLengthCommon = commonKeyAndKeyLength[1];
@@ -170,12 +190,12 @@
this.childOne = null;
}
- if(newNode.childOne == null && newNode.childZero == null){
- this.childCount++;
- if(newNode.childCount > 1) {
- //System.out.println("--confusion--");
- }
- newNode.childCount = 0;
+ if (newNode.childOne == null && newNode.childZero == null) {
+ this.childCount++;
+ if (newNode.childCount > 1) {
+ //System.out.println("--confusion--");
+ }
+ newNode.childCount = 0;
}
}
@@ -200,8 +220,7 @@
this.childZero.setData(data);
}
}
- }
- else {
+ } else {
this.valueCount = 1;
//this.data = data; //XXX
}
@@ -209,7 +228,8 @@
return this;
}
- public boolean FindExactMatch(long key, long keyLength) {
+ public boolean FindExactMatch(long key, long keyLength)
+ {
boolean matchStatus;
long keyCommon;
@@ -247,7 +267,8 @@
}
}
- public TrieNode FindBestMatch(long key, long keyLength) {
+ public TrieNode FindBestMatch(long key, long keyLength)
+ {
// note : we don't need to worry about a node being a terminator
since at the end, we will either have
// - an exact match of the key, so the node will be a terminator
// - the last possible node on the path matching the key which can't
be anything but a leaf, hence a terminator
@@ -278,7 +299,8 @@
}
}
- public TrieNode Clone() {
+ public TrieNode Clone()
+ {
TrieNode clone = new TrieNode(this.key, this.keyLength,
this.valueCount);
if (this.childZero != null)
clone.childZero = this.childZero.Clone();
@@ -289,101 +311,99 @@
return clone;
}
- public void printDotNode(PrintStream p, TrieNode node, long position,
long currentKey) {
- TrieNode c0 = node.getChildZero();
- TrieNode c1 = node.getChildOne();
- long key = node.getKey();
- long mask = Constants.MAX_KEY_LENGTH - position;
- String addrString;
-
- if (key == -1) {
- addrString = "\"" + "0.0.0.0/0" + "\"";
- currentKey = 0;
- p.println(addrString + "
[shape=record,label=\"<f0>0.0.0.0/0|<f1>"
- + node.getChildCount()
- + "\"];" + " // COUNT: " +
node.getChildCount());
- }
- else {
- key = currentKey;
- String keyString = helper.longToIP(key);
- String unquotedAddrString = keyString + "/" + mask;
- addrString = "\"" + keyString + "/" + mask + "\"";
- if (node.getData() == null) {
- //p.println(addrString + " [style=filled];" + " //
COUNT: " + node.getChildCount());
- p.println(addrString + "
[style=filled,shape=record,label=\"<f0>" + unquotedAddrString
- + "|<f1>" + node.getChildCount() +
"\"]"
- + "; // COUNT: " +
node.getChildCount());
- }
- else {
- //p.println(addrString + "; // COUNT: " +
node.getChildCount());
- p.println(addrString + " [shape=record,label=\"<f0>"
+ unquotedAddrString
- + "|<f1>" + node.getChildCount() +
"\"]"
- + "; // COUNT: " +
node.getChildCount());
- }
- }
-
- if (c0 != null) {
- long c0Key = c0.getKey() << (position - c0.getKeyLength());
- long c0Position = position - c0.getKeyLength();
- long c0Mask = Constants.MAX_KEY_LENGTH - c0Position;
- c0Key = c0Key | currentKey;
- p.println(addrString + " -> \""
- + helper.longToIP(c0Key) + "/" + c0Mask
- + "\"" + "[label=" + (c0Mask - mask)
- + "];" + "// kl: " + c0.getKeyLength() + "
pos: " + position);
- printDotNode(p, c0, c0Position, c0Key);
- }
- if (c1 != null) {
- long c1Key = c1.getKey() << (position - c1.getKeyLength());
- long c1Position = position - c1.getKeyLength();
- long c1Mask = Constants.MAX_KEY_LENGTH - c1Position;
- c1Key = c1Key | currentKey;
- p.println(addrString + " -> \""
- + helper.longToIP(c1Key) + "/" + c1Mask
- + "\"" + "[label=" + (c1Mask - mask)
- + "];" + "// kl: " + c1.getKeyLength() + "
pos: " + position);
- printDotNode(p, c1, c1Position, c1Key);
- }
+ public void printDotNode(PrintStream p, TrieNode node, long position,
long currentKey)
+ {
+ TrieNode c0 = node.getChildZero();
+ TrieNode c1 = node.getChildOne();
+ long key = node.getKey();
+ long mask = Constants.MAX_KEY_LENGTH - position;
+ String addrString;
+
+ if (key == -1) {
+ addrString = "\"" + "0.0.0.0/0" + "\"";
+ currentKey = 0;
+ p.println(addrString + "
[shape=record,label=\"<f0>0.0.0.0/0|<f1>"
+ + node.getChildCount()
+ + "\"];" + " // COUNT: " + node.getChildCount());
+ } else {
+ key = currentKey;
+ String keyString = helper.longToIP(key);
+ String unquotedAddrString = keyString + "/" + mask;
+ addrString = "\"" + keyString + "/" + mask + "\"";
+ if (node.getData() == null) {
+ //p.println(addrString + " [style=filled];" + " // COUNT: "
+ node.getChildCount());
+ p.println(addrString + "
[style=filled,shape=record,label=\"<f0>" + unquotedAddrString
+ + "|<f1>" + node.getChildCount() + "\"]"
+ + "; // COUNT: " + node.getChildCount());
+ } else {
+ //p.println(addrString + "; // COUNT: " +
node.getChildCount());
+ p.println(addrString + " [shape=record,label=\"<f0>" +
unquotedAddrString
+ + "|<f1>" + node.getChildCount() + "\"]"
+ + "; // COUNT: " + node.getChildCount());
+ }
+ }
+
+ if (c0 != null) {
+ long c0Key = c0.getKey() << (position - c0.getKeyLength());
+ long c0Position = position - c0.getKeyLength();
+ long c0Mask = Constants.MAX_KEY_LENGTH - c0Position;
+ c0Key = c0Key | currentKey;
+ p.println(addrString + " -> \""
+ + helper.longToIP(c0Key) + "/" + c0Mask
+ + "\"" + "[label=" + (c0Mask - mask)
+ + "];" + "// kl: " + c0.getKeyLength() + " pos: " +
position);
+ printDotNode(p, c0, c0Position, c0Key);
+ }
+ if (c1 != null) {
+ long c1Key = c1.getKey() << (position - c1.getKeyLength());
+ long c1Position = position - c1.getKeyLength();
+ long c1Mask = Constants.MAX_KEY_LENGTH - c1Position;
+ c1Key = c1Key | currentKey;
+ p.println(addrString + " -> \""
+ + helper.longToIP(c1Key) + "/" + c1Mask
+ + "\"" + "[label=" + (c1Mask - mask)
+ + "];" + "// kl: " + c1.getKeyLength() + " pos: " +
position);
+ printDotNode(p, c1, c1Position, c1Key);
+ }
}
- public ArrayList<String> listInternalNodes(ArrayList<String>
listOfNodes, long position, long currentKey) {
- TrieNode c0 = this.getChildZero();
- TrieNode c1 = this.getChildOne();
- long key = this.getKey();
- long mask = Constants.MAX_KEY_LENGTH - position;
- TrieNode node = this;
-
- if (key == -1) {
- currentKey = 0;
- }
- else {
- key = currentKey;
- String keyString = helper.longToIP(key);
- String addrString = keyString + "/" + mask;
- if (node.getData() == null) {
- listOfNodes.add(addrString);
- }
- }
- if (c0 != null) {
- long c0Key = c0.getKey() << (position - c0.getKeyLength());
- long c0Position = position - c0.getKeyLength();
- long c0Mask = Constants.MAX_KEY_LENGTH - c0Position;
- c0Key = c0Key | currentKey;
- c0.listInternalNodes(listOfNodes, c0Position, c0Key);
- }
- if (c1 != null) {
- long c1Key = c1.getKey() << (position - c1.getKeyLength());
- long c1Position = position - c1.getKeyLength();
- long c1Mask = Constants.MAX_KEY_LENGTH - c1Position;
- c1Key = c1Key | currentKey;
- c1.listInternalNodes(listOfNodes, c1Position, c1Key);
- }
+ public ArrayList<String> listInternalNodes(ArrayList<String>
listOfNodes, long position, long currentKey)
+ {
+ TrieNode c0 = this.getChildZero();
+ TrieNode c1 = this.getChildOne();
+ long key = this.getKey();
+ long mask = Constants.MAX_KEY_LENGTH - position;
+ TrieNode node = this;
- return listOfNodes;
+ if (key == -1) {
+ currentKey = 0;
+ } else {
+ key = currentKey;
+ String keyString = helper.longToIP(key);
+ String addrString = keyString + "/" + mask;
+ if (node.getData() == null) {
+ listOfNodes.add(addrString);
+ }
+ }
+ if (c0 != null) {
+ long c0Key = c0.getKey() << (position - c0.getKeyLength());
+ long c0Position = position - c0.getKeyLength();
+ long c0Mask = Constants.MAX_KEY_LENGTH - c0Position;
+ c0Key = c0Key | currentKey;
+ c0.listInternalNodes(listOfNodes, c0Position, c0Key);
+ }
+ if (c1 != null) {
+ long c1Key = c1.getKey() << (position - c1.getKeyLength());
+ long c1Position = position - c1.getKeyLength();
+ long c1Mask = Constants.MAX_KEY_LENGTH - c1Position;
+ c1Key = c1Key | currentKey;
+ c1.listInternalNodes(listOfNodes, c1Position, c1Key);
+ }
+
+ return listOfNodes;
}
/**
- *
* This method returns all the nodes which are necessary to summarize
all inputs.
*
* @param listOfNodes
@@ -391,41 +411,41 @@
* @param currentKey
* @return
*/
- public ArrayList<String> listSummaryNodes(ArrayList<String> listOfNodes,
long position, long currentKey) {
- TrieNode c0 = this.getChildZero();
- TrieNode c1 = this.getChildOne();
- long key = this.getKey();
- long mask = Constants.MAX_KEY_LENGTH - position;
- TrieNode node = this;
-
- if (key == -1) {
- currentKey = 0;
- }
- else {
- key = currentKey;
+ public ArrayList<String> listSummaryNodes(ArrayList<String> listOfNodes,
long position, long currentKey)
+ {
+ TrieNode c0 = this.getChildZero();
+ TrieNode c1 = this.getChildOne();
+ long key = this.getKey();
+ long mask = Constants.MAX_KEY_LENGTH - position;
+ TrieNode node = this;
+
+ if (key == -1) {
+ currentKey = 0;
+ } else {
+ key = currentKey;
String keyString = helper.longToIP(key);
- String addrString = keyString + "/" + mask;
- if (node.getData() == null &&
- ( c0.getData() != null ||
- c1.getData() != null )) {
- listOfNodes.add(addrString);
- }
- }
- if (c0 != null) {
- long c0Key = c0.getKey() << (position - c0.getKeyLength());
- long c0Position = position - c0.getKeyLength();
- //long c0Mask = Constants.MAX_KEY_LENGTH - c0Position;
- c0Key = c0Key | currentKey;
- c0.listSummaryNodes(listOfNodes, c0Position, c0Key);
- }
- if (c1 != null) {
- long c1Key = c1.getKey() << (position - c1.getKeyLength());
- long c1Position = position - c1.getKeyLength();
- //long c1Mask = Constants.MAX_KEY_LENGTH - c1Position;
- c1Key = c1Key | currentKey;
- c1.listSummaryNodes(listOfNodes, c1Position, c1Key);
- }
+ String addrString = keyString + "/" + mask;
+ if (node.getData() == null &&
+ (c0.getData() != null ||
+ c1.getData() != null)) {
+ listOfNodes.add(addrString);
+ }
+ }
+ if (c0 != null) {
+ long c0Key = c0.getKey() << (position - c0.getKeyLength());
+ long c0Position = position - c0.getKeyLength();
+ //long c0Mask = Constants.MAX_KEY_LENGTH - c0Position;
+ c0Key = c0Key | currentKey;
+ c0.listSummaryNodes(listOfNodes, c0Position, c0Key);
+ }
+ if (c1 != null) {
+ long c1Key = c1.getKey() << (position - c1.getKeyLength());
+ long c1Position = position - c1.getKeyLength();
+ //long c1Mask = Constants.MAX_KEY_LENGTH - c1Position;
+ c1Key = c1Key | currentKey;
+ c1.listSummaryNodes(listOfNodes, c1Position, c1Key);
+ }
- return listOfNodes;
+ return listOfNodes;
}
}
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,18 +2,22 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-public class AADispatchManager {
- AADispatchProtocol protocol;
+public class AADispatchManager
+{
+ AADispatchProtocol protocol;
- public AADispatchManager(AADispatchProtocol prot) {
- this.protocol=prot;
- }
-
- public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException {
- return protocol.getAuthentication(req);
- }
-
- public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException {
- return protocol.getAuthorization(req);
- }
+ public AADispatchManager(AADispatchProtocol prot)
+ {
+ this.protocol = prot;
+ }
+
+ public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException
+ {
+ return protocol.getAuthentication(req);
+ }
+
+ public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException
+ {
+ return protocol.getAuthorization(req);
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchProtocol.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchProtocol.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchProtocol.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,8 +2,11 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-public interface AADispatchProtocol {
- public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException;
- public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException;
- public AttrResponse getAttributes(AttrRequest req) throws
PerfSONARException;
+public interface AADispatchProtocol
+{
+ public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException;
+
+ public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException;
+
+ public AttrResponse getAttributes(AttrRequest req) throws
PerfSONARException;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchProtocolFactory.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchProtocolFactory.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchProtocolFactory.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,8 +2,10 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-public class AADispatchProtocolFactory {
- public static AADispatchProtocol getDefaultAADispatchProtocol()
throws PerfSONARException {
- return new AADispatchSOAPProtocol();
- }
+public class AADispatchProtocolFactory
+{
+ public static AADispatchProtocol getDefaultAADispatchProtocol() throws
PerfSONARException
+ {
+ return new AADispatchSOAPProtocol();
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchSOAPProtocol.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchSOAPProtocol.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AADispatchSOAPProtocol.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -39,74 +39,79 @@
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
-public class AADispatchSOAPProtocol implements AADispatchProtocol {
- public static final String
WSS_X509="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
- public static final String
WSS_SAML="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
-
- private final String AS_POINT_PARAM = "service.as.point";
- private final String SAX_PARSER_CONFIG = "service.sax_parser.config";
- private LoggerComponent logger;
- private ConfigurationComponent config;
- private String asPoint;
- private String saxParser;
+public class AADispatchSOAPProtocol implements AADispatchProtocol
+{
+ public static final String WSS_X509 =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3";
+ public static final String WSS_SAML =
"http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
- public AADispatchSOAPProtocol() throws PerfSONARException {
- try {
- logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance()
- .getComponent(ComponentNames.LOGGER);
- } catch (PerfSONARException e) {
- String m = "AADispatchSOAPProtocol: Can't obtain
Logger component ";
- throw new PerfSONARException(m);
- }
- try {
- config = (ConfigurationComponent)
AuxiliaryComponentManager
- .getInstance().getComponent(ComponentNames.CONFIG);
- } catch (PerfSONARException e) {
+ private final String AS_POINT_PARAM = "service.as.point";
+ private final String SAX_PARSER_CONFIG = "service.sax_parser.config";
+ private LoggerComponent logger;
+ private ConfigurationComponent config;
+ private String asPoint;
+ private String saxParser;
- String m = "AADispatchSOAPProtocol: Can't obtain
Config component ";
- logger.error(m);
- throw new PerfSONARException(m);
- }
- try {
- asPoint=config.getProperty(AS_POINT_PARAM);
- saxParser=config.getProperty(SAX_PARSER_CONFIG);
- } catch (Exception e) {
- String m = "AADispatchSOAPProtocol: Can't obtain
required parameters ";
- logger.error(m);
- throw new PerfSONARException(m);
- }
- }
+ public AADispatchSOAPProtocol() throws PerfSONARException
+ {
+ try {
+ logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance()
+ .getComponent(ComponentNames.LOGGER);
+ } catch (PerfSONARException e) {
+ String m = "AADispatchSOAPProtocol: Can't obtain Logger
component ";
+ throw new PerfSONARException(m);
+ }
+ try {
+ config = (ConfigurationComponent) AuxiliaryComponentManager
+ .getInstance().getComponent(ComponentNames.CONFIG);
+ } catch (PerfSONARException e) {
- public AADispatchSOAPProtocol(String asPoint, String saxParser)
throws PerfSONARException {
- try {
- logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance()
- .getComponent(ComponentNames.LOGGER);
- } catch (PerfSONARException e) {
- String m = "AADispatchSOAPProtocol: Can't obtain
Logger component ";
- throw new PerfSONARException(m);
- }
- this.asPoint=asPoint;
- this.saxParser=saxParser;
- }
-
+ String m = "AADispatchSOAPProtocol: Can't obtain Config
component ";
+ logger.error(m);
+ throw new PerfSONARException(m);
+ }
+ try {
+ asPoint = config.getProperty(AS_POINT_PARAM);
+ saxParser = config.getProperty(SAX_PARSER_CONFIG);
+ } catch (Exception e) {
+ String m = "AADispatchSOAPProtocol: Can't obtain required
parameters ";
+ logger.error(m);
+ throw new PerfSONARException(m);
+ }
+ }
- private String getClient(SecurityToken token) throws Exception {
- Object stValue=token.getSecTokenValue();
- if (SecTokenSOAPManager.isDelegated(token)) {
- SAMLAssertion assertion=(SAMLAssertion)stValue;
- String clientIssuer=assertion.getIssuer();
-
- return clientIssuer;
- }
-
- return "";
- }
-
- private Document updateSecurityTokenParameter(Document request,
Message requestMessage, SecurityToken token) throws TransformerException {
- // get the parameter which specifies the format of the
security token
- Parameters params;
- Parameter parameter=null;
- Metadata[] mds=requestMessage.getMetadataArray();
+ public AADispatchSOAPProtocol(String asPoint, String saxParser) throws
PerfSONARException
+ {
+ try {
+ logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance()
+ .getComponent(ComponentNames.LOGGER);
+ } catch (PerfSONARException e) {
+ String m = "AADispatchSOAPProtocol: Can't obtain Logger
component ";
+ throw new PerfSONARException(m);
+ }
+ this.asPoint = asPoint;
+ this.saxParser = saxParser;
+ }
+
+
+ private String getClient(SecurityToken token) throws Exception
+ {
+ Object stValue = token.getSecTokenValue();
+ if (SecTokenSOAPManager.isDelegated(token)) {
+ SAMLAssertion assertion = (SAMLAssertion) stValue;
+ String clientIssuer = assertion.getIssuer();
+
+ return clientIssuer;
+ }
+
+ return "";
+ }
+
+ private Document updateSecurityTokenParameter(Document request, Message
requestMessage, SecurityToken token) throws TransformerException
+ {
+ // get the parameter which specifies the format of the security token
+ Parameters params;
+ Parameter parameter = null;
+ Metadata[] mds = requestMessage.getMetadataArray();
for (Metadata md : mds) {
params = md.getParameters();
Parameter[] pars = params.getParameterArray();
@@ -117,181 +122,184 @@
}
}
- javax.xml.soap.SOAPHeader
header=(javax.xml.soap.SOAPHeader)token.getSecToken();
- Iterator<?> it=header.examineAllHeaderElements();
- while (it.hasNext()) {
- SOAPHeaderElement he=(SOAPHeaderElement)it.next();
-
- // if there is any assertion, it should be a saml
security token
- NodeList nodelist2 =
org.apache.xpath.XPathAPI.selectNodeList(he, "//wsse:BinarySecurityToken");
- for (int i = 0; i < nodelist2.getLength(); i++) {
- Element e=(Element)nodelist2.item(i);
- if
(e.getAttribute("ValueType").equals("#SAMLBase64Binary")) {
-
parameter.setParameterValue(AADispatchSOAPProtocol.WSS_SAML);
- }
- }
- }
+ javax.xml.soap.SOAPHeader header = (javax.xml.soap.SOAPHeader)
token.getSecToken();
+ Iterator<?> it = header.examineAllHeaderElements();
+ while (it.hasNext()) {
+ SOAPHeaderElement he = (SOAPHeaderElement) it.next();
- return requestMessage.getDOM(request);
- }
-
- private Message sendMessage(String point,Message requestMessage,
SecurityToken token) throws Exception {
- Service service = new Service();
- Call call = (Call)service.createCall();
- call.setTargetEndpointAddress(new URL(point));
- call.setOperationName(new
QName("http://soapinterop.org/","submit"));
+ // if there is any assertion, it should be a saml security token
+ NodeList nodelist2 =
org.apache.xpath.XPathAPI.selectNodeList(he, "//wsse:BinarySecurityToken");
+ for (int i = 0; i < nodelist2.getLength(); i++) {
+ Element e = (Element) nodelist2.item(i);
+ if (e.getAttribute("ValueType").equals("#SAMLBase64Binary"))
{
+
parameter.setParameterValue(AADispatchSOAPProtocol.WSS_SAML);
+ }
+ }
+ }
- // read the request into a org.w3c.DOM.Document
- DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
+ return requestMessage.getDOM(request);
+ }
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document request = builder.newDocument();
+ private Message sendMessage(String point, Message requestMessage,
SecurityToken token) throws Exception
+ {
+ Service service = new Service();
+ Call call = (Call) service.createCall();
+ call.setTargetEndpointAddress(new URL(point));
+ call.setOperationName(new QName("http://soapinterop.org/",
"submit"));
- request = updateSecurityTokenParameter(request,
requestMessage, token);
+ // read the request into a org.w3c.DOM.Document
+ DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
- SOAPBodyElement requestSOAPMessage =
- new SOAPBodyElement(request.getDocumentElement());
- SOAPEnvelope envelope = new SOAPEnvelope();
- envelope.addBodyElement(requestSOAPMessage);
-
- javax.xml.soap.SOAPHeader
header=(javax.xml.soap.SOAPHeader)token.getSecToken();
- Iterator<?> it=header.examineAllHeaderElements();
- while (it.hasNext()) {
- SOAPHeaderElement he=(SOAPHeaderElement)it.next();
- envelope.getHeader().addChildElement(he);
- }
-
- StringWriter sw=new StringWriter();
-
XMLUtils.PrettyElementToWriter(requestSOAPMessage.getAsDOM(),sw);
- logger.debug("------- Sending message >>>>>>>");
- logger.debug(sw.toString());
- logger.debug("<<<<<<< Sending message -------");
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ Document request = builder.newDocument();
- // call on the end point
- Object resultObject = call.invoke(envelope);
+ request = updateSecurityTokenParameter(request, requestMessage,
token);
- SOAPEnvelope envelopeResult;
- SOAPBodyElement resultSBE;
- Document result;
+ SOAPBodyElement requestSOAPMessage =
+ new SOAPBodyElement(request.getDocumentElement());
+ SOAPEnvelope envelope = new SOAPEnvelope();
+ envelope.addBodyElement(requestSOAPMessage);
- envelopeResult= (SOAPEnvelope)resultObject;
- resultSBE= envelopeResult.getFirstBody();
+ javax.xml.soap.SOAPHeader header = (javax.xml.soap.SOAPHeader)
token.getSecToken();
+ Iterator<?> it = header.examineAllHeaderElements();
+ while (it.hasNext()) {
+ SOAPHeaderElement he = (SOAPHeaderElement) it.next();
+ envelope.getHeader().addChildElement(he);
+ }
- // change it to document - here is where validity
- // can be checked..
- result = resultSBE.getAsDocument();
+ StringWriter sw = new StringWriter();
+ XMLUtils.PrettyElementToWriter(requestSOAPMessage.getAsDOM(), sw);
+ logger.debug("------- Sending message >>>>>>>");
+ logger.debug(sw.toString());
+ logger.debug("<<<<<<< Sending message -------");
- logger.debug("------- Receiving message >>>>>>>");
- logger.debug(XMLUtils.PrettyDocumentToString(result));
- logger.debug("<<<<<<< Receiving message -------");
+ // call on the end point
+ Object resultObject = call.invoke(envelope);
- Message responseNmwg =
org.perfsonar.base.util.XMLUtils.convertToMessage(
- result, saxParser);
-
- return responseNmwg;
- }
+ SOAPEnvelope envelopeResult;
+ SOAPBodyElement resultSBE;
+ Document result;
- @Override
- public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException {
- AuthNResponse resp;
- // prepare to call - set service elements
- try {
+ envelopeResult = (SOAPEnvelope) resultObject;
+ resultSBE = envelopeResult.getFirstBody();
- Message authnRequest = new
AuthNEERequestGenerator().generateRequestMessage();
- Message response = sendMessage(asPoint, authnRequest,
req.getSecurityToken());
+ // change it to document - here is where validity
+ // can be checked..
+ result = resultSBE.getAsDocument();
- resp=AuthNResponse.getAuthNResponse(response);
- logger.debug("Authentication response:
("+resp.getResultCode()+","+resp.getStatus()+")");
+ logger.debug("------- Receiving message >>>>>>>");
+ logger.debug(XMLUtils.PrettyDocumentToString(result));
+ logger.debug("<<<<<<< Receiving message -------");
- } catch (ClassCastException e) {
- e.printStackTrace();
- String m = "AADispatchSOAPProtocol.getAuthentication:
We didn't get a Vector of SOAPBodyElements!";
- System.out.println(m);
- throw new PerfSONARException("error.as.body",m);
- } catch (Exception e) {
- e.printStackTrace();
- String m="AADispatchSOAPProtocol.getAuthentication:
General exception while retrieving report";
- System.out.println(m);
- throw new PerfSONARException("error.as.query",m);
- }
+ Message responseNmwg =
org.perfsonar.base.util.XMLUtils.convertToMessage(
+ result, saxParser);
- return resp;
- }
+ return responseNmwg;
+ }
- @Override
- public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException {
- // prepare to call - set service elements
- try {
+ @Override
+ public AuthNResponse getAuthentication(AuthNRequest req) throws
PerfSONARException
+ {
+ AuthNResponse resp;
+ // prepare to call - set service elements
+ try {
- Message authrRequest = new
AuthREERequestGenerator().generateRequestMessage();
-
- SimpleRequest simpleRequest;
- if
(SecTokenSOAPManager.isDelegated(req.getSecurityToken())) {
- simpleRequest =
RequestFactory.getDefaultSimpleDelegatedRequest();
- }
- else {
- simpleRequest =
RequestFactory.getDefaultSimpleRequest();
- }
- simpleRequest.setResource(req.getResource());
- simpleRequest.setAction(req.getAction());
- simpleRequest.setSubject(req.getSubject());
- if
(SecTokenSOAPManager.isDelegated(req.getSecurityToken())) {
- SimpleDelegatedRequest
sdr=(SimpleDelegatedRequest)simpleRequest;
-
sdr.setClient(getClient(req.getSecurityToken()));
- }
- String reqString=simpleRequest.getMessage();
- Subject authrElement=new Subject();
- authrElement.setSubject(reqString);
-
authrRequest.getMetadata("authRmetadata").setSubject(authrElement);
+ Message authnRequest = new
AuthNEERequestGenerator().generateRequestMessage();
+ Message response = sendMessage(asPoint, authnRequest,
req.getSecurityToken());
- Message response = sendMessage(asPoint, authrRequest,
req.getSecurityToken());
+ resp = AuthNResponse.getAuthNResponse(response);
+ logger.debug("Authentication response: (" + resp.getResultCode()
+ "," + resp.getStatus() + ")");
- AuthRResponse
respAuth=AuthRResponse.getAuthRResponse(response);
- logger.debug("Authorization response:
("+respAuth.getResultCode()+","+respAuth.getStatus()+")");
+ } catch (ClassCastException e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAuthentication: We didn't
get a Vector of SOAPBodyElements!";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.body", m);
+ } catch (Exception e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAuthentication: General
exception while retrieving report";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.query", m);
+ }
- return respAuth;
- } catch (ClassCastException e) {
- e.printStackTrace();
- String m = "AADispatchSOAPProtocol.getAuthorization:
We didn't get a Vector of SOAPBodyElements!";
- System.out.println(m);
- throw new PerfSONARException("error.as.body",m);
- } catch (Exception e) {
- e.printStackTrace();
- String m="AADispatchSOAPProtocol.getAuthorization:
General exception while retrieving report";
- System.out.println(m);
- throw new PerfSONARException("error.as.query",m);
- }
+ return resp;
+ }
- }
-
- @Override
- public AttrResponse getAttributes(AttrRequest req) throws
PerfSONARException {
- // prepare to call - set service elements
- try {
+ @Override
+ public AuthRResponse getAuthorization(AuthRRequest req) throws
PerfSONARException
+ {
+ // prepare to call - set service elements
+ try {
- Message attrRequest = new
AttrEERequestGenerator().generateRequestMessage();
-
-
- Message response = sendMessage(asPoint, attrRequest,
req.getSecurityToken());
+ Message authrRequest = new
AuthREERequestGenerator().generateRequestMessage();
- AttrResponse
respAuth=AttrResponse.getAttrResponse(response);
- logger.debug("Attribte response:
("+respAuth.getResultCode()+","+respAuth.getStatus()+")");
+ SimpleRequest simpleRequest;
+ if (SecTokenSOAPManager.isDelegated(req.getSecurityToken())) {
+ simpleRequest =
RequestFactory.getDefaultSimpleDelegatedRequest();
+ } else {
+ simpleRequest = RequestFactory.getDefaultSimpleRequest();
+ }
+ simpleRequest.setResource(req.getResource());
+ simpleRequest.setAction(req.getAction());
+ simpleRequest.setSubject(req.getSubject());
+ if (SecTokenSOAPManager.isDelegated(req.getSecurityToken())) {
+ SimpleDelegatedRequest sdr = (SimpleDelegatedRequest)
simpleRequest;
+ sdr.setClient(getClient(req.getSecurityToken()));
+ }
+ String reqString = simpleRequest.getMessage();
+ Subject authrElement = new Subject();
+ authrElement.setSubject(reqString);
+
authrRequest.getMetadata("authRmetadata").setSubject(authrElement);
- return respAuth;
-
- } catch (ClassCastException e) {
- e.printStackTrace();
- String m = "AADispatchSOAPProtocol.getAttributes: We
didn't get a Vector of SOAPBodyElements!";
- System.out.println(m);
- throw new PerfSONARException("error.as.body",m);
- } catch (Exception e) {
- e.printStackTrace();
- String m="AADispatchSOAPProtocol.getAttributes:
General exception while retrieving report";
- System.out.println(m);
- throw new PerfSONARException("error.as.query",m);
- }
+ Message response = sendMessage(asPoint, authrRequest,
req.getSecurityToken());
-
- }
+ AuthRResponse respAuth =
AuthRResponse.getAuthRResponse(response);
+ logger.debug("Authorization response: (" +
respAuth.getResultCode() + "," + respAuth.getStatus() + ")");
+
+ return respAuth;
+ } catch (ClassCastException e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAuthorization: We didn't
get a Vector of SOAPBodyElements!";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.body", m);
+ } catch (Exception e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAuthorization: General
exception while retrieving report";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.query", m);
+ }
+
+ }
+
+ @Override
+ public AttrResponse getAttributes(AttrRequest req) throws
PerfSONARException
+ {
+ // prepare to call - set service elements
+ try {
+
+ Message attrRequest = new
AttrEERequestGenerator().generateRequestMessage();
+
+
+ Message response = sendMessage(asPoint, attrRequest,
req.getSecurityToken());
+
+ AttrResponse respAuth = AttrResponse.getAttrResponse(response);
+ logger.debug("Attribte response: (" + respAuth.getResultCode() +
"," + respAuth.getStatus() + ")");
+
+ return respAuth;
+
+ } catch (ClassCastException e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAttributes: We didn't get
a Vector of SOAPBodyElements!";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.body", m);
+ } catch (Exception e) {
+ e.printStackTrace();
+ String m = "AADispatchSOAPProtocol.getAttributes: General
exception while retrieving report";
+ System.out.println(m);
+ throw new PerfSONARException("error.as.query", m);
+ }
+
+
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AttrRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AttrRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AttrRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -7,52 +7,63 @@
import org.perfsonar.service.base.authn.tokens.SecurityToken;
-public class AttrRequest extends AuthNRequest {
- String issuer;
- String subject;
- Map<String, Map<String, List<String>>> attrs;
+public class AttrRequest extends AuthNRequest
+{
+ String issuer;
+ String subject;
+ Map<String, Map<String, List<String>>> attrs;
- public AttrRequest() {
- super();
- attrs = new HashMap<String, Map<String,List<String>>>();
- }
+ public AttrRequest()
+ {
+ super();
+ attrs = new HashMap<String, Map<String, List<String>>>();
+ }
- public AttrRequest(SecurityToken st) {
- super(st);
- attrs = new HashMap<String, Map<String,List<String>>>();
- }
+ public AttrRequest(SecurityToken st)
+ {
+ super(st);
+ attrs = new HashMap<String, Map<String, List<String>>>();
+ }
- public String getIssuer() {
- return issuer;
- }
+ public String getIssuer()
+ {
+ return issuer;
+ }
- public void setIssuer(String issuer) {
- this.issuer = issuer;
- }
+ public void setIssuer(String issuer)
+ {
+ this.issuer = issuer;
+ }
- public String getSubject() {
- return subject;
- }
+ public String getSubject()
+ {
+ return subject;
+ }
- public void setSubject(String subject) {
- this.subject = subject;
- }
-
- public void addAttribute(String urn, String friendlyName,
List<String> values) {
- Map<String, List<String>> data = new HashMap<String,
List<String>>();
- data.put(friendlyName, values);
- attrs.put(urn, data);
- }
+ public void setSubject(String subject)
+ {
+ this.subject = subject;
+ }
- public void removeAttribute(String urn) {
- attrs.remove(urn);
- }
-
- public void clearAttributes() {
- attrs.clear();
- }
-
- public Map<String, Map<String, List<String>>> getAttributes() {
- return attrs;
- }
+ public void addAttribute(String urn, String friendlyName, List<String>
values)
+ {
+ Map<String, List<String>> data = new HashMap<String, List<String>>();
+ data.put(friendlyName, values);
+ attrs.put(urn, data);
+ }
+
+ public void removeAttribute(String urn)
+ {
+ attrs.remove(urn);
+ }
+
+ public void clearAttributes()
+ {
+ attrs.clear();
+ }
+
+ public Map<String, Map<String, List<String>>> getAttributes()
+ {
+ return attrs;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AttrResponse.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AttrResponse.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AttrResponse.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -23,57 +23,64 @@
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
-public class AttrResponse extends AuthNResponse {
- public static final int ATTR_OK_RESPONSE=1;
- public static final int ATTR_BAD_RESPONSE=1;
- public static final String NS_SUBJECT_AA =
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/attr/1.0/";
+public class AttrResponse extends AuthNResponse
+{
+ public static final int ATTR_OK_RESPONSE = 1;
+ public static final int ATTR_BAD_RESPONSE = 1;
+ public static final String NS_SUBJECT_AA =
"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/attr/1.0/";
- private Map<String, List<String>> attributes;
- private String samlRawResponse;
- private XPath xpath;
+ private Map<String, List<String>> attributes;
+ private String samlRawResponse;
+ private XPath xpath;
- public AttrResponse() {
- super();
+ public AttrResponse()
+ {
+ super();
- XPathFactory xfactory = XPathFactory.newInstance();
- xpath = xfactory.newXPath();
- NamespaceContext ctx = new NamespaceContext() {
- @Override
- public String getNamespaceURI(String prefix) {
- String uri;
- if (prefix.equals("samlp"))
- uri =
"urn:oasis:names:tc:SAML:2.0:protocol";
- else if (prefix.equals("saml"))
- uri =
"urn:oasis:names:tc:SAML:2.0:assertion";
- else
- uri = null;
- return uri;
- }
+ XPathFactory xfactory = XPathFactory.newInstance();
+ xpath = xfactory.newXPath();
+ NamespaceContext ctx = new NamespaceContext()
+ {
+ @Override
+ public String getNamespaceURI(String prefix)
+ {
+ String uri;
+ if (prefix.equals("samlp"))
+ uri = "urn:oasis:names:tc:SAML:2.0:protocol";
+ else if (prefix.equals("saml"))
+ uri = "urn:oasis:names:tc:SAML:2.0:assertion";
+ else
+ uri = null;
+ return uri;
+ }
- // Dummy implementation - not used!
- @Override
- public Iterator<?> getPrefixes(String val) {
- return null;
- }
+ // Dummy implementation - not used!
+ @Override
+ public Iterator<?> getPrefixes(String val)
+ {
+ return null;
+ }
- // Dummy implemenation - not used!
- @Override
- public String getPrefix(String uri) {
- return null;
- }
- };
- xpath.setNamespaceContext(ctx);
+ // Dummy implemenation - not used!
+ @Override
+ public String getPrefix(String uri)
+ {
+ return null;
+ }
+ };
+ xpath.setNamespaceContext(ctx);
- attributes = new HashMap<String, List<String>>();
- }
+ attributes = new HashMap<String, List<String>>();
+ }
- public static AttrResponse getAttrResponse(Message message) {
- AttrResponse res=new AttrResponse();
- res.setStatus(AttrResponse.ATTR_OK_RESPONSE);
+ public static AttrResponse getAttrResponse(Message message)
+ {
+ AttrResponse res = new AttrResponse();
+ res.setStatus(AttrResponse.ATTR_OK_RESPONSE);
- Metadata responseMetadata = null;
- EventType et = null;
- Metadata[] metadatas=message.getMetadataArray();
+ Metadata responseMetadata = null;
+ EventType et = null;
+ Metadata[] metadatas = message.getMetadataArray();
for (Metadata metadata : metadatas) {
et = metadata.getEventType();
responseMetadata = metadata;
@@ -81,94 +88,102 @@
if (et != null) {
if (et.getEventType().trim().contains("success.as.attr")) {
- res.setStatus(AttrResponse.ATTR_BAD_RESPONSE);
- res.setResultCode(et.getEventType());
+ res.setStatus(AttrResponse.ATTR_BAD_RESPONSE);
+ res.setResultCode(et.getEventType());
}
}
- if (res.getStatus()==AttrResponse.ATTR_OK_RESPONSE) {
- Iterator<?> it = responseMetadata.getChildIterator();
- while (it.hasNext()) {
- Element elem = (Element)it.next();
- System.out.println(elem.getNamespaceURI()+" ----
"+elem.getNodeName());
- if
(elem.getNamespaceURI().equals("http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/attr/1.0/")&&
- elem.getNodeName().equals("subject"))
{
- String samlResponse = elem.getTextContent();
- res.setSAMLResponse(samlResponse);
- res.loadAttributes();
- }
- }
+ if (res.getStatus() == AttrResponse.ATTR_OK_RESPONSE) {
+ Iterator<?> it = responseMetadata.getChildIterator();
+ while (it.hasNext()) {
+ Element elem = (Element) it.next();
+ System.out.println(elem.getNamespaceURI() + " ---- " +
elem.getNodeName());
+ if
(elem.getNamespaceURI().equals("http://ggf.org/ns/nmwg/tools/org/perfsonar/service/as/attr/1.0/")
&&
+ elem.getNodeName().equals("subject")) {
+ String samlResponse = elem.getTextContent();
+ res.setSAMLResponse(samlResponse);
+ res.loadAttributes();
+ }
+ }
}
- return res;
- }
+ return res;
+ }
- public void loadAttributes() {
- Document doc = getDocumentFromString(getSAMLResponse());
- try {
- XPathExpression expression =
xpath.compile("//samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute");
- NodeList nodes = (NodeList) expression.evaluate(doc,
XPathConstants.NODESET);
- for (int i = 0; i < nodes.getLength(); i++) {
- org.w3c.dom.Element
elem=(org.w3c.dom.Element)nodes.item(i);
- String friendlyName =
elem.getAttribute("FriendlyName");
- NodeList nodes2 =
elem.getElementsByTagName("saml:AttributeValue");
- for (int j=0; j<nodes2.getLength(); j++) {
- org.w3c.dom.Element
value=(org.w3c.dom.Element)nodes2.item(j);
- String attributeValue =
value.getTextContent().trim();
- addAttribute(friendlyName,
attributeValue);
- }
- }
- } catch (XPathExpressionException e) {
+ public void loadAttributes()
+ {
+ Document doc = getDocumentFromString(getSAMLResponse());
+ try {
+ XPathExpression expression =
xpath.compile("//samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute");
+ NodeList nodes = (NodeList) expression.evaluate(doc,
XPathConstants.NODESET);
+ for (int i = 0; i < nodes.getLength(); i++) {
+ org.w3c.dom.Element elem = (org.w3c.dom.Element)
nodes.item(i);
+ String friendlyName = elem.getAttribute("FriendlyName");
+ NodeList nodes2 =
elem.getElementsByTagName("saml:AttributeValue");
+ for (int j = 0; j < nodes2.getLength(); j++) {
+ org.w3c.dom.Element value = (org.w3c.dom.Element)
nodes2.item(j);
+ String attributeValue = value.getTextContent().trim();
+ addAttribute(friendlyName, attributeValue);
+ }
+ }
+ } catch (XPathExpressionException e) {
- }
- }
+ }
+ }
- public void addAttribute(String key,String value) {
- if (!attributes.containsKey(key)) {
- List<String> list=new LinkedList<String>();
- attributes.put(key, list);
- }
- List<String> list = attributes.get(key);
- list.add(value);
- }
+ public void addAttribute(String key, String value)
+ {
+ if (!attributes.containsKey(key)) {
+ List<String> list = new LinkedList<String>();
+ attributes.put(key, list);
+ }
+ List<String> list = attributes.get(key);
+ list.add(value);
+ }
- public void clearAttributes() {
- attributes.clear();
- }
+ public void clearAttributes()
+ {
+ attributes.clear();
+ }
- public void removeAttribute(String key) {
- if (attributes.containsKey(key)) {
- attributes.remove(key);
- }
- }
+ public void removeAttribute(String key)
+ {
+ if (attributes.containsKey(key)) {
+ attributes.remove(key);
+ }
+ }
- public Map<String, List<String>> getAttributes() {
- return attributes;
- }
+ public Map<String, List<String>> getAttributes()
+ {
+ return attributes;
+ }
- private Document getDocumentFromString(String message) {
- try {
- Document request;
- DocumentBuilderFactory factory =
DocumentBuilderFactory
- .newInstance();
- factory.setNamespaceAware(true);
+ private Document getDocumentFromString(String message)
+ {
+ try {
+ Document request;
+ DocumentBuilderFactory factory = DocumentBuilderFactory
+ .newInstance();
+ factory.setNamespaceAware(true);
- DocumentBuilder builder =
factory.newDocumentBuilder();
- request = builder
- .parse(new
ByteArrayInputStream(message.getBytes()));
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ request = builder
+ .parse(new ByteArrayInputStream(message.getBytes()));
- return request;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
+ return request;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
- public String getSAMLResponse() {
- return samlRawResponse;
- }
+ public String getSAMLResponse()
+ {
+ return samlRawResponse;
+ }
- public void setSAMLResponse(String samlMessage) {
- this.samlRawResponse = samlMessage;
- }
+ public void setSAMLResponse(String samlMessage)
+ {
+ this.samlRawResponse = samlMessage;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthNRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthNRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthNRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,24 +2,29 @@
import org.perfsonar.service.base.authn.tokens.SecurityToken;
-public class AuthNRequest {
- private SecurityToken st;
+public class AuthNRequest
+{
+ private SecurityToken st;
- public AuthNRequest() {
- st=null;
- }
+ public AuthNRequest()
+ {
+ st = null;
+ }
- public AuthNRequest(SecurityToken st) {
- this();
- this.st=st;
- }
+ public AuthNRequest(SecurityToken st)
+ {
+ this();
+ this.st = st;
+ }
- public SecurityToken getSecurityToken() {
- return st;
- }
+ public SecurityToken getSecurityToken()
+ {
+ return st;
+ }
- public void setSecurityToken(SecurityToken st) {
- this.st = st;
- }
+ public void setSecurityToken(SecurityToken st)
+ {
+ this.st = st;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthNResponse.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthNResponse.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthNResponse.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -4,38 +4,45 @@
import org.ggf.ns.nmwg.base.v2_0.Message;
import org.ggf.ns.nmwg.base.v2_0.Metadata;
-public class AuthNResponse {
- public static final int AUTHENTICATED=0;
- public static final int NOT_AUTHENTICATED=1;
-
- private int status;
- private String resultCode;
-
- public AuthNResponse() {
- status=AuthNResponse.NOT_AUTHENTICATED;
- resultCode="";
- }
+public class AuthNResponse
+{
+ public static final int AUTHENTICATED = 0;
+ public static final int NOT_AUTHENTICATED = 1;
- public int getStatus() {
- return status;
- }
+ private int status;
+ private String resultCode;
- public void setStatus(int status) {
- this.status = status;
- }
-
- public String getResultCode() {
- return resultCode;
- }
+ public AuthNResponse()
+ {
+ status = AuthNResponse.NOT_AUTHENTICATED;
+ resultCode = "";
+ }
- public void setResultCode(String codeResult) {
- this.resultCode = codeResult;
- }
+ public int getStatus()
+ {
+ return status;
+ }
- public static AuthNResponse getAuthNResponse(Message message) {
- AuthNResponse res=new AuthNResponse();
-
- Metadata[] metadatas=message.getMetadataArray();
+ public void setStatus(int status)
+ {
+ this.status = status;
+ }
+
+ public String getResultCode()
+ {
+ return resultCode;
+ }
+
+ public void setResultCode(String codeResult)
+ {
+ this.resultCode = codeResult;
+ }
+
+ public static AuthNResponse getAuthNResponse(Message message)
+ {
+ AuthNResponse res = new AuthNResponse();
+
+ Metadata[] metadatas = message.getMetadataArray();
for (Metadata metadata : metadatas) {
EventType et = metadata.getEventType();
res.setResultCode(et.getEventType());
@@ -45,7 +52,7 @@
res.setStatus(AuthNResponse.NOT_AUTHENTICATED);
}
}
-
- return res;
- }
+
+ return res;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthRRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthRRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthRRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,56 +2,67 @@
import org.perfsonar.service.base.authn.tokens.SecurityToken;
-public class AuthRRequest extends AuthNRequest {
- public static final String URN_PREFIX_ACTION =
"urn:geant:edugain:action:perfsonar:";
- public static final String DEFAULT_ACTION = "send";
-
- String messageType;
- String resource;
- String action;
- String subject;
+public class AuthRRequest extends AuthNRequest
+{
+ public static final String URN_PREFIX_ACTION =
"urn:geant:edugain:action:perfsonar:";
+ public static final String DEFAULT_ACTION = "send";
- public AuthRRequest() {
- super();
- }
+ String messageType;
+ String resource;
+ String action;
+ String subject;
- public AuthRRequest(SecurityToken st,String messageType) {
- super(st);
-
- this.messageType = messageType;
- setAction(messageType);
- }
+ public AuthRRequest()
+ {
+ super();
+ }
- public String getMessageType() {
- return messageType;
- }
+ public AuthRRequest(SecurityToken st, String messageType)
+ {
+ super(st);
- public void setMessageType(String messageType) {
- this.messageType = messageType;
- }
+ this.messageType = messageType;
+ setAction(messageType);
+ }
- public String getAction() {
- return action;
- }
+ public String getMessageType()
+ {
+ return messageType;
+ }
- public void setAction(String action) {
- this.action = URN_PREFIX_ACTION + action;
- }
+ public void setMessageType(String messageType)
+ {
+ this.messageType = messageType;
+ }
- public String getResource() {
- return resource;
- }
+ public String getAction()
+ {
+ return action;
+ }
- public void setResource(String resource) {
- this.resource = resource;
- }
+ public void setAction(String action)
+ {
+ this.action = URN_PREFIX_ACTION + action;
+ }
- public String getSubject() {
- return subject;
- }
+ public String getResource()
+ {
+ return resource;
+ }
- public void setSubject(String subject) {
- this.subject = subject;
- }
+ public void setResource(String resource)
+ {
+ this.resource = resource;
+ }
+ public String getSubject()
+ {
+ return subject;
+ }
+
+ public void setSubject(String subject)
+ {
+ this.subject = subject;
+ }
+
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthRResponse.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthRResponse.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/AuthRResponse.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -4,14 +4,16 @@
import org.ggf.ns.nmwg.base.v2_0.Message;
import org.ggf.ns.nmwg.base.v2_0.Metadata;
-public class AuthRResponse extends AuthNResponse {
- public static final int AUTHORIZED=0;
- public static final int NOT_AUTHORIZED=1;
+public class AuthRResponse extends AuthNResponse
+{
+ public static final int AUTHORIZED = 0;
+ public static final int NOT_AUTHORIZED = 1;
- public static AuthRResponse getAuthRResponse(Message message) {
- AuthRResponse res=new AuthRResponse();
-
- Metadata[] metadatas=message.getMetadataArray();
+ public static AuthRResponse getAuthRResponse(Message message)
+ {
+ AuthRResponse res = new AuthRResponse();
+
+ Metadata[] metadatas = message.getMetadataArray();
for (Metadata metadata : metadatas) {
EventType et = metadata.getEventType();
res.setResultCode(et.getEventType());
@@ -21,7 +23,7 @@
res.setStatus(AuthRResponse.NOT_AUTHORIZED);
}
}
-
- return res;
- }
+
+ return res;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,8 +2,11 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-public interface SecTokenManager {
- public boolean hasSTInRequest() throws PerfSONARException;
- public Object getSTFromRequest() throws PerfSONARException;
- public Object getSTValue() throws PerfSONARException;
+public interface SecTokenManager
+{
+ public boolean hasSTInRequest() throws PerfSONARException;
+
+ public Object getSTFromRequest() throws PerfSONARException;
+
+ public Object getSTValue() throws PerfSONARException;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenManagerFactory.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenManagerFactory.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenManagerFactory.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,8 +2,10 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-public class SecTokenManagerFactory {
- public static SecTokenManager getDefaultSecTokenManager() throws
PerfSONARException {
- return new SecTokenSOAPManager();
- }
+public class SecTokenManagerFactory
+{
+ public static SecTokenManager getDefaultSecTokenManager() throws
PerfSONARException
+ {
+ return new SecTokenSOAPManager();
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenSOAPManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenSOAPManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecTokenSOAPManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -42,58 +42,63 @@
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
-public class SecTokenSOAPManager implements SecTokenManager {
- private final String
WSSECHEADER_NS="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
- private final String WSSECHEADER="Security";
- private static final String URN_USER_FED = ":user:";
-
- private LoggerComponent logger = null;
+public class SecTokenSOAPManager implements SecTokenManager
+{
+ private final String WSSECHEADER_NS =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
+ private final String WSSECHEADER = "Security";
+ private static final String URN_USER_FED = ":user:";
- public SecTokenSOAPManager() throws PerfSONARException {
- logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
+ private LoggerComponent logger = null;
- if (logger == null) {
- String m = "SecTokenSOAPManager: can't obtain Logger
object";
- throw new
PerfSONARException("error.common.no_logger", m);
- }
- }
+ public SecTokenSOAPManager() throws PerfSONARException
+ {
+ logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
- @Override
- public Object getSTFromRequest() throws PerfSONARException {
- if (!hasSTInRequest())
- return null;
- MessageContext mc=MessageContext.getCurrentContext();
- try {
- Message m=mc.getCurrentMessage();
- SOAPHeader sh=(SOAPHeader)m.getSOAPHeader();
- return sh;
- } catch (SOAPException e) {
- String m = "Error getting the SOAP header";
- logger.error(m);
- throw new PerfSONARException("error.authn.soap", m);
- }
- }
+ if (logger == null) {
+ String m = "SecTokenSOAPManager: can't obtain Logger object";
+ throw new PerfSONARException("error.common.no_logger", m);
+ }
+ }
- @Override
- public boolean hasSTInRequest() throws PerfSONARException {
- MessageContext mc=MessageContext.getCurrentContext();
- try {
- SOAPHeader
sh=(SOAPHeader)mc.getCurrentMessage().getSOAPHeader();
- NodeList
nl=sh.getElementsByTagNameNS(WSSECHEADER_NS,WSSECHEADER);
- return nl.getLength()>0;
- } catch (SOAPException e) {
- String m = "Error checking the WS-SEC header";
- logger.error(m);
- throw new PerfSONARException("error.authn.soap", m);
- }
- }
+ @Override
+ public Object getSTFromRequest() throws PerfSONARException
+ {
+ if (!hasSTInRequest())
+ return null;
+ MessageContext mc = MessageContext.getCurrentContext();
+ try {
+ Message m = mc.getCurrentMessage();
+ SOAPHeader sh = (SOAPHeader) m.getSOAPHeader();
+ return sh;
+ } catch (SOAPException e) {
+ String m = "Error getting the SOAP header";
+ logger.error(m);
+ throw new PerfSONARException("error.authn.soap", m);
+ }
+ }
- @Override
- public Object getSTValue() throws PerfSONARException {
- if (!hasSTInRequest())
- return null;
- Object res=null;
- SOAPHeader sh=(SOAPHeader)getSTFromRequest();
+ @Override
+ public boolean hasSTInRequest() throws PerfSONARException
+ {
+ MessageContext mc = MessageContext.getCurrentContext();
+ try {
+ SOAPHeader sh = (SOAPHeader)
mc.getCurrentMessage().getSOAPHeader();
+ NodeList nl = sh.getElementsByTagNameNS(WSSECHEADER_NS,
WSSECHEADER);
+ return nl.getLength() > 0;
+ } catch (SOAPException e) {
+ String m = "Error checking the WS-SEC header";
+ logger.error(m);
+ throw new PerfSONARException("error.authn.soap", m);
+ }
+ }
+
+ @Override
+ public Object getSTValue() throws PerfSONARException
+ {
+ if (!hasSTInRequest())
+ return null;
+ Object res = null;
+ SOAPHeader sh = (SOAPHeader) getSTFromRequest();
/* Iterator it=sh.examineAllHeaderElements();
while (it.hasNext()) {
SOAPHeaderElement he=(SOAPHeaderElement)it.next();
@@ -112,67 +117,68 @@
}
}
if (res==null) { */
- try {
- Document doc=sh.getAsDocument();
- Crypto crypto = new DynamicCrypto();
- WSSecurityEngine secEngine = new
WSSecurityEngine();
- // If there is any problem validating the
SOAP header, it throws an exception
- secEngine.processSecurityHeader(doc, null,
null, crypto);
+ try {
+ Document doc = sh.getAsDocument();
+ Crypto crypto = new DynamicCrypto();
+ WSSecurityEngine secEngine = new WSSecurityEngine();
+ // If there is any problem validating the SOAP header, it throws
an exception
+ secEngine.processSecurityHeader(doc, null, null, crypto);
- XPathFactory factory =
XPathFactory.newInstance();
- XPath xpath = factory.newXPath();
- xpath.setNamespaceContext(new
WSSENamespaceContext());
- XPathExpression expr =
xpath.compile("//wsse:BinarySecurityToken");
- Object result = expr.evaluate(doc,
XPathConstants.NODESET);
- NodeList nodes = (NodeList) result;
- for (int i = 0; i < nodes.getLength(); i++) {
- Element e=(Element)nodes.item(i);
- if
(e.getAttribute("ValueType").equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"))
{
- byte[]
bytes=Base64.decode(e.getTextContent());
- ByteArrayInputStream bais=new
ByteArrayInputStream(bytes);
- X509Certificate
cert=crypto.loadCertificate(bais);
- res=cert;
- }
- else if
(e.getAttribute("ValueType").equals("#SAMLBase64Binary")) {
- byte[]
bytes=Base64.decode(e.getTextContent());
- ByteArrayInputStream bais=new
ByteArrayInputStream(bytes);
- SAMLAssertion as=new
SAMLAssertion(bais);
- res=as;
- }
- }
- } catch (Throwable t) {
- String m = "SecTokenSOAPManager:
"+t.getMessage();
- logger.info(m);
- throw new
PerfSONARException("error.authn.getting_sec_token",m);
- }
+ XPathFactory factory = XPathFactory.newInstance();
+ XPath xpath = factory.newXPath();
+ xpath.setNamespaceContext(new WSSENamespaceContext());
+ XPathExpression expr =
xpath.compile("//wsse:BinarySecurityToken");
+ Object result = expr.evaluate(doc, XPathConstants.NODESET);
+ NodeList nodes = (NodeList) result;
+ for (int i = 0; i < nodes.getLength(); i++) {
+ Element e = (Element) nodes.item(i);
+ if
(e.getAttribute("ValueType").equals("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"))
{
+ byte[] bytes = Base64.decode(e.getTextContent());
+ ByteArrayInputStream bais = new
ByteArrayInputStream(bytes);
+ X509Certificate cert = crypto.loadCertificate(bais);
+ res = cert;
+ } else if
(e.getAttribute("ValueType").equals("#SAMLBase64Binary")) {
+ byte[] bytes = Base64.decode(e.getTextContent());
+ ByteArrayInputStream bais = new
ByteArrayInputStream(bytes);
+ SAMLAssertion as = new SAMLAssertion(bais);
+ res = as;
+ }
+ }
+ } catch (Throwable t) {
+ String m = "SecTokenSOAPManager: " + t.getMessage();
+ logger.info(m);
+ throw new PerfSONARException("error.authn.getting_sec_token", m);
+ }
// }
return res;
- }
+ }
- public static boolean isDelegated(SecurityToken token) throws
TransformerException {
- boolean isDelegated=false;
-
- javax.xml.soap.SOAPHeader
header=(javax.xml.soap.SOAPHeader)token.getSecToken();
- Iterator<?> it=header.examineAllHeaderElements();
- while (it.hasNext()) {
- SOAPHeaderElement he=(SOAPHeaderElement)it.next();
- NodeList nodelist2 =
org.apache.xpath.XPathAPI.selectNodeList(he, "//wsse:BinarySecurityToken");
- for (int i = 0; i < nodelist2.getLength(); i++) {
- Element e=(Element)nodelist2.item(i);
- if
(e.getAttribute("ValueType").equals("#SAMLBase64Binary")) {
- isDelegated = true;
- }
- }
- }
-
- return isDelegated;
- }
-
- public static String getSubject(SecurityToken token) throws
TransformerException, CertificateParsingException,
UnsupportedEncodingException, SAMLException {
- Object stValue=token.getSecTokenValue();
- if (!isDelegated(token)) {
- X509Certificate cert=(X509Certificate)stValue;
- Collection subjectAltNames =
cert.getSubjectAlternativeNames();
+ public static boolean isDelegated(SecurityToken token) throws
TransformerException
+ {
+ boolean isDelegated = false;
+
+ javax.xml.soap.SOAPHeader header = (javax.xml.soap.SOAPHeader)
token.getSecToken();
+ Iterator<?> it = header.examineAllHeaderElements();
+ while (it.hasNext()) {
+ SOAPHeaderElement he = (SOAPHeaderElement) it.next();
+ NodeList nodelist2 =
org.apache.xpath.XPathAPI.selectNodeList(he, "//wsse:BinarySecurityToken");
+ for (int i = 0; i < nodelist2.getLength(); i++) {
+ Element e = (Element) nodelist2.item(i);
+ if (e.getAttribute("ValueType").equals("#SAMLBase64Binary"))
{
+ isDelegated = true;
+ }
+ }
+ }
+
+ return isDelegated;
+ }
+
+ public static String getSubject(SecurityToken token) throws
TransformerException, CertificateParsingException,
UnsupportedEncodingException, SAMLException
+ {
+ Object stValue = token.getSecTokenValue();
+ if (!isDelegated(token)) {
+ X509Certificate cert = (X509Certificate) stValue;
+ Collection subjectAltNames = cert.getSubjectAlternativeNames();
if (subjectAltNames != null) {
for (Object subjectAltName : subjectAltNames) {
List<?> values = (List<?>) subjectAltName;
@@ -185,44 +191,47 @@
}
}
}
- }
- else {
- SAMLAssertion assertion=(SAMLAssertion)stValue;
- Iterator it=assertion.getStatements();
- while (it.hasNext()) {
- SAMLStatement
statement=(SAMLStatement)it.next();
- if (statement instanceof
SAMLAuthenticationStatement) {
- SAMLAuthenticationStatement
authSt=(SAMLAuthenticationStatement)statement;
- SAMLSubject
subject=authSt.getSubject();
-
- Element
confData=subject.getConfirmationData();
- SAMLAssertion relayed=new
SAMLAssertion((Element)confData.getFirstChild());
-
- return
relayed.getIssuer()+SecTokenSOAPManager.URN_USER_FED+subject.getNameIdentifier().getName();
- }
- }
- }
-
- return "";
- }
-
- class WSSENamespaceContext implements NamespaceContext {
-
- @Override
- public String getNamespaceURI(String prefix) {
- return
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
- }
-
- // This method isn't necessary for XPath processing either.
- @Override
- public String getPrefix(String uri) {
- throw new UnsupportedOperationException();
- }
+ } else {
+ SAMLAssertion assertion = (SAMLAssertion) stValue;
+ Iterator it = assertion.getStatements();
+ while (it.hasNext()) {
+ SAMLStatement statement = (SAMLStatement) it.next();
+ if (statement instanceof SAMLAuthenticationStatement) {
+ SAMLAuthenticationStatement authSt =
(SAMLAuthenticationStatement) statement;
+ SAMLSubject subject = authSt.getSubject();
- // This method isn't necessary for XPath processing either.
- @Override
- public Iterator<?> getPrefixes(String uri) {
- throw new UnsupportedOperationException();
- }
- }
+ Element confData = subject.getConfirmationData();
+ SAMLAssertion relayed = new SAMLAssertion((Element)
confData.getFirstChild());
+
+ return relayed.getIssuer() +
SecTokenSOAPManager.URN_USER_FED + subject.getNameIdentifier().getName();
+ }
+ }
+ }
+
+ return "";
+ }
+
+ class WSSENamespaceContext implements NamespaceContext
+ {
+
+ @Override
+ public String getNamespaceURI(String prefix)
+ {
+ return
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
+ }
+
+ // This method isn't necessary for XPath processing either.
+ @Override
+ public String getPrefix(String uri)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ // This method isn't necessary for XPath processing either.
+ @Override
+ public Iterator<?> getPrefixes(String uri)
+ {
+ throw new UnsupportedOperationException();
+ }
+ }
}
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecurityToken.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecurityToken.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/authn/tokens/SecurityToken.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,39 +2,47 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-public class SecurityToken {
- private SecTokenManager tm;
- private Object secToken;
- private Object secTokenValue;
+public class SecurityToken
+{
+ private SecTokenManager tm;
+ private Object secToken;
+ private Object secTokenValue;
- public SecurityToken(SecTokenManager tm) {
- this.tm=tm;
- this.secToken=null;
- this.secTokenValue=null;
- }
+ public SecurityToken(SecTokenManager tm)
+ {
+ this.tm = tm;
+ this.secToken = null;
+ this.secTokenValue = null;
+ }
- public Object getSecToken() {
- return secToken;
- }
+ public Object getSecToken()
+ {
+ return secToken;
+ }
- public void setSecToken(Object secToken) {
- this.secToken = secToken;
- }
-
- public void setSecTokenFromRequest() throws PerfSONARException {
- setSecToken(tm.getSTFromRequest());
- setSecTokenValue(tm.getSTValue());
- }
-
- public boolean hasSecTokenInRequest() throws PerfSONARException {
- return tm.hasSTInRequest();
- }
+ public void setSecToken(Object secToken)
+ {
+ this.secToken = secToken;
+ }
- public Object getSecTokenValue() {
- return secTokenValue;
- }
+ public void setSecTokenFromRequest() throws PerfSONARException
+ {
+ setSecToken(tm.getSTFromRequest());
+ setSecTokenValue(tm.getSTValue());
+ }
- public void setSecTokenValue(Object secTokenValue) {
- this.secTokenValue = secTokenValue;
- }
+ public boolean hasSecTokenInRequest() throws PerfSONARException
+ {
+ return tm.hasSTInRequest();
+ }
+
+ public Object getSecTokenValue()
+ {
+ return secTokenValue;
+ }
+
+ public void setSecTokenValue(Object secTokenValue)
+ {
+ this.secTokenValue = secTokenValue;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/container/listeners/StartupInitializer.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/container/listeners/StartupInitializer.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/container/listeners/StartupInitializer.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -19,23 +19,25 @@
* service (un)initialization.
*
* @author Uros Juvan
- *
*/
-public class StartupInitializer implements ServletContextListener {
+public class StartupInitializer implements ServletContextListener
+{
// --------------------------------------------------------- Public
methods
+
/**
* Context initialized event handler.
*
* @param sce servlet context event
*/
@Override
- public void contextInitialized(ServletContextEvent sce) {
- String location = sce.getServletContext().getRealPath("/WEB-INF/");
- AuxiliaryComponentManager.setWebInfLocation(location);
-
+ public void contextInitialized(ServletContextEvent sce)
+ {
+ String location = sce.getServletContext().getRealPath("/WEB-INF/");
+ AuxiliaryComponentManager.setWebInfLocation(location);
+
File tempDirectory = (File)
sce.getServletContext().getAttribute("javax.servlet.context.tempdir");
AuxiliaryComponentManager.setTempDirectory(tempDirectory);
-
+
try {
AuxiliaryComponentManager.getInstance();
} catch (Exception e) {
@@ -43,14 +45,15 @@
e.printStackTrace();
}
}
+
/**
* Context uninitialized event handler.
*
- *
* @param sce servlet context event
*/
@Override
- public void contextDestroyed(ServletContextEvent sce) {
+ public void contextDestroyed(ServletContextEvent sce)
+ {
// Stop all the component threads (running in a separate thread).
// They should implement AuxiliaryThreadedComponent instead of
// AuxiliaryComponent
@@ -66,9 +69,9 @@
System.out.println(
"Stopping perfSONAR component thread for "
- + e.getKey()
- + " component ");
- ((AuxiliaryThreadedComponent)e.getValue()).stopThread();
+ + e.getKey()
+ + " component ");
+ ((AuxiliaryThreadedComponent) e.getValue()).stopThread();
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ActionType.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ActionType.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ActionType.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -6,45 +6,45 @@
package org.perfsonar.service.base.engine;
/**
- * Class holding static values of action types that can be asked from
service engines
+ * Class holding static values of action types that can be asked from
service engines
*
- * @author loukik
- * @author Maciej Glowiak
- * @author romradz
- *
+ * @author loukik
+ * @author Maciej Glowiak
+ * @author romradz
*/
-public class ActionType {
+public class ActionType
+{
// ----------------------------------------- Measurement Archive Actions
/**
- * Action type to ask for a key for the specified metadata
+ * Action type to ask for a key for the specified metadata
*/
public static final String GET_KEY = "GET_KEY";
/**
- * Action type to ask for data
+ * Action type to ask for data
*/
public static final String GET_DATA = "GET_DATA";
/**
- * Action type to store measurements
+ * Action type to store measurements
*/
public static final String STORE_DATA = "STORE_DATA";
/**
- * Action type to store keys
+ * Action type to store keys
*/
public static final String STORE_KEY = "STORE_KEY";
/**
- * Action type to replace complete metadata configuration file
+ * Action type to replace complete metadata configuration file
*/
public static final String STORE_METADATA_CONFIGURATION =
"STORE_METADATA_CONFIGURATION";
@@ -53,31 +53,31 @@
/**
- * Action type to request a measurement
+ * Action type to request a measurement
*/
public static final String LS_REGISTER = "LS_REGISTER";
/**
- * Action type to request a measurement
+ * Action type to request a measurement
*/
public static final String LS_LOOKUP = "LS_LOOKUP";
/**
- * Action type to request a measurement
+ * Action type to request a measurement
*/
public static final String LS_DEREGISTER = "LS_DEREGISTER";
/**
- * Action type to request a measurement
+ * Action type to request a measurement
*/
public static final String LS_KEEPALIVE = "LS_KEEPALIVE";
/**
- * Action type to LS Cleanup
+ * Action type to LS Cleanup
*/
public static final String LS_CLEANUP = "LS_CLEANUP";
@@ -92,7 +92,7 @@
/**
- * Action type to check service status
+ * Action type to check service status
*/
public static final String ECHO = "ECHO";
@@ -101,7 +101,7 @@
/**
- * Action type to request information set of the service
+ * Action type to request information set of the service
*/
public static final String GET_LOOKUP_INFO = "GET_LOOKUP_INFO";
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ServiceEngine.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ServiceEngine.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ServiceEngine.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -11,34 +11,32 @@
import org.perfsonar.base.exceptions.PerfSONARException;
/**
- * Interface specification for all types of Service Engines
+ * Interface specification for all types of Service Engines
*
- * @author loukik
+ * @author loukik
*/
-public interface ServiceEngine {
+public interface ServiceEngine
+{
/**
- * Returns the type of Service Engine.
+ * Returns the type of Service Engine.
*
- * @return String type of Service Engine
+ * @return String type of Service Engine
*/
public String getType();
/**
- * Executes an action.
+ * Executes an action.
*
- * @param actionType Parameter from the static list defined in
ActionType
- * which specifies the necessary action to be taken
- * @param request Message object containing the request
- * @return Message final result of of performed action
- *
- * @throws PerfSONARException if the system encountered an internal
error
- * while satisfying this request
- *
- * @see org.perfsonar.service.commons.engine.ActionType
- * @see org.perfsonar.service.commons.engine.ServiceEngineRequest
- * @see org.perfsonar.service.commons.engine.ServiceEngineResponse
- *
+ * @param actionType Parameter from the static list defined in ActionType
+ * which specifies the necessary action to be taken
+ * @param request Message object containing the request
+ * @return Message final result of of performed action
+ * @throws PerfSONARException if the system encountered an internal error
+ * while satisfying this request
+ * @see org.perfsonar.service.commons.engine.ActionType
+ * @see org.perfsonar.service.commons.engine.ServiceEngineRequest
+ * @see org.perfsonar.service.commons.engine.ServiceEngineResponse
*/
public Message takeAction(String actionType, Message request) throws
PerfSONARException;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ServiceEngineFactory.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ServiceEngineFactory.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/engine/ServiceEngineFactory.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -11,26 +11,25 @@
import org.perfsonar.base.exceptions.PerfSONARException;
/**
- * Factory class which can be used to get ServiceEngine instances
+ * Factory class which can be used to get ServiceEngine instances
*
- * @author loukik
- *
- * @see org.perfsonar.service.commons.engine.ServiceEngine
- * TODO provided a
{@link
ServiceEngine} is state-less
{@link
ServiceEngine}'s should be cached.
+ * @author loukik
+ * @see org.perfsonar.service.commons.engine.ServiceEngine
+ * TODO provided a
{@link
ServiceEngine} is state-less
{@link
ServiceEngine}'s should be cached.
*/
-public class ServiceEngineFactory {
+public class ServiceEngineFactory
+{
- /**
- * Returns the instance of Service Engine.
+ /**
+ * Returns the instance of Service Engine.
*
- * @param engineClassName class name of a service engine
- *
- * @return String type of Service Engine
- *
- * @throws PerfSONARException if an error was encountered while
- * getting the instance
+ * @param engineClassName class name of a service engine
+ * @return String type of Service Engine
+ * @throws PerfSONARException if an error was encountered while
+ * getting the instance
*/
- public static ServiceEngine getServiceEngine(String engineClassName)
throws PerfSONARException {
+ public static ServiceEngine getServiceEngine(String engineClassName)
throws PerfSONARException
+ {
// get a logger
LoggerComponent logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
@@ -42,10 +41,10 @@
engineClass = Class.forName(engineClassName);
} catch (ClassNotFoundException e) {
// class not found
- logger.fatal("ServiceEngineFactory: class not found for name:
"+engineClassName);
+ logger.fatal("ServiceEngineFactory: class not found for name: "
+ engineClassName);
throw new PerfSONARException(
- "error.common.service_engine.creation_failure",
- "ServiceEngineFactory: ClassNotFound: "+
engineClassName
+ "error.common.service_engine.creation_failure",
+ "ServiceEngineFactory: ClassNotFound: " + engineClassName
);
}
@@ -53,24 +52,24 @@
// get an instance of it
try {
- engine = (ServiceEngine) engineClass.newInstance();
+ engine = (ServiceEngine) engineClass.newInstance();
} catch (ClassCastException e1) {
logger.fatal("ServiceEngineFactory: specified class doesn't
implement ServiceEngine: " + engineClassName);
throw new PerfSONARException(
- "error.common.service_engine.creation_failure",
- "ServiceEngineFactory: specified class("+engineClassName+")
doesn't implement ServiceEngine"
+ "error.common.service_engine.creation_failure",
+ "ServiceEngineFactory: specified class(" + engineClassName +
") doesn't implement ServiceEngine"
);
} catch (InstantiationException e1) {
- logger.fatal("ServiceEngineFactory: Couldn't instanciate class
("+engineClassName+") Perhaps there isn't a no arg constructor?");
+ logger.fatal("ServiceEngineFactory: Couldn't instanciate class
(" + engineClassName + ") Perhaps there isn't a no arg constructor?");
throw new PerfSONARException(
- "error.common.service_engine.creation_failure",
- "ServiceEngineFactory: Couldn't instanciate class
("+engineClassName+") Perhaps there isn't a no arg constructor?"
+ "error.common.service_engine.creation_failure",
+ "ServiceEngineFactory: Couldn't instanciate class (" +
engineClassName + ") Perhaps there isn't a no arg constructor?"
);
} catch (IllegalAccessException e1) {
logger.fatal("ServiceEngineFactory: IllegalAccessException
couldn't instanciate: " + engineClassName);
throw new PerfSONARException(
- "error.common.service_engine.creation_failure",
- "ServiceEngineFactory: IllegalAccessException couldn't
instanciate: "+engineClassName
+ "error.common.service_engine.creation_failure",
+ "ServiceEngineFactory: IllegalAccessException couldn't
instanciate: " + engineClassName
);
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/measurementExecutor/MeasurementExecutor.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/measurementExecutor/MeasurementExecutor.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/measurementExecutor/MeasurementExecutor.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -12,27 +12,27 @@
* This is an interface specification for MeasurementExecutor
*
* @author Loukik
- *
*/
-public interface MeasurementExecutor {
-
- // ---------------------------------- public methods
-
- /**
- * @return the type of MeasurementExecutor
- */
- public String getType();
-
- /**
- * Operation which takes in a Message and gives out a Message.
Implementations
- * should implement this definition to make measurements and return
data or handle or
- * anything else appropriate
- *
- * @param request MeasurementExecutorRequest object containing the
request
- * @return MeasurementExecutorResponse object containing response
from MeasurementExecutor
- * @throws SystemException
- * @throws RequestException
- */
- public Message makeMeasurement(Message request) throws
PerfSONARException;
-
+public interface MeasurementExecutor
+{
+
+ // ---------------------------------- public methods
+
+ /**
+ * @return the type of MeasurementExecutor
+ */
+ public String getType();
+
+ /**
+ * Operation which takes in a Message and gives out a Message.
Implementations
+ * should implement this definition to make measurements and return data
or handle or
+ * anything else appropriate
+ *
+ * @param request MeasurementExecutorRequest object containing the
request
+ * @return MeasurementExecutorResponse object containing response from
MeasurementExecutor
+ * @throws SystemException
+ * @throws RequestException
+ */
+ public Message makeMeasurement(Message request) throws
PerfSONARException;
+
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AttrEERequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AttrEERequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AttrEERequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -6,18 +6,21 @@
import org.perfsonar.base.exceptions.PerfSONARException;
import org.perfsonar.service.base.engine.ActionType;
-public class AttrEERequest extends Request {
+public class AttrEERequest extends Request
+{
- public AttrEERequest() throws PerfSONARException {
- super();
+ public AttrEERequest() throws PerfSONARException
+ {
+ super();
logger.debug("AttrEERequest: MessageHandler created");
setType(ActionType.ATTR_EE_REQUEST);
- }
+ }
- @Override
- public Map<String, Metadata> mergeAllMetadata(
- Map<String, Metadata> metadatas) {
- return metadatas;
- }
+ @Override
+ public Map<String, Metadata> mergeAllMetadata(
+ Map<String, Metadata> metadatas)
+ {
+ return metadatas;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AuthNEERequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AuthNEERequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AuthNEERequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -6,18 +6,21 @@
import org.perfsonar.base.exceptions.PerfSONARException;
import org.perfsonar.service.base.engine.ActionType;
-public class AuthNEERequest extends Request {
+public class AuthNEERequest extends Request
+{
- public AuthNEERequest() throws PerfSONARException {
- super();
+ public AuthNEERequest() throws PerfSONARException
+ {
+ super();
logger.debug("AuthNRequest: MessageHandler created");
setType(ActionType.AUTHN_EE_REQUEST);
- }
+ }
- @Override
- public Map<String, Metadata> mergeAllMetadata(
- Map<String, Metadata> metadatas) {
- return metadatas;
- }
+ @Override
+ public Map<String, Metadata> mergeAllMetadata(
+ Map<String, Metadata> metadatas)
+ {
+ return metadatas;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AuthREERequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AuthREERequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/AuthREERequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -6,18 +6,21 @@
import org.perfsonar.base.exceptions.PerfSONARException;
import org.perfsonar.service.base.engine.ActionType;
-public class AuthREERequest extends Request {
+public class AuthREERequest extends Request
+{
- public AuthREERequest() throws PerfSONARException {
- super();
+ public AuthREERequest() throws PerfSONARException
+ {
+ super();
logger.debug("AuthRRequest: MessageHandler created");
setType(ActionType.AUTHR_EE_REQUEST);
- }
+ }
- @Override
- public Map<String, Metadata> mergeAllMetadata(
- Map<String, Metadata> metadatas) {
- return metadatas;
- }
+ @Override
+ public Map<String, Metadata> mergeAllMetadata(
+ Map<String, Metadata> metadatas)
+ {
+ return metadatas;
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/BaseChaining.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/BaseChaining.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/BaseChaining.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -17,29 +17,26 @@
import org.perfsonar.base.exceptions.PerfSONARException;
/**
- * This class handles base chaining of metadata blocks
+ * This class handles base chaining of metadata blocks
*
- * @author romradz
- *
+ * @author romradz
*/
-public abstract class BaseChaining {
+public abstract class BaseChaining
+{
-
// ---------------------------------- class fields
-
protected LoggerComponent logger = null;
-
// ---------------------------------- constructors
+ public BaseChaining() throws PerfSONARException
+ {
- public BaseChaining() throws PerfSONARException {
-
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().getComponent(ComponentNames.LOGGER);
@@ -47,16 +44,15 @@
}
-
// ---------------------------------- public methods
-
/**
- * Returns message object without base chainig (chains of metadata
blocks linked by
- * metadataIdRef attribute).
+ * Returns message object without base chainig (chains of metadata
blocks linked by
+ * metadataIdRef attribute).
*/
- public Message processChaining(Message message) {
+ public Message processChaining(Message message)
+ {
Message newMessage = new Message();
newMessage.setType(message.getType());
@@ -97,7 +93,6 @@
}
-
// ---------------------------------- protected methods
@@ -105,7 +100,8 @@
* Finds base chaining and calls merge method
*/
protected Metadata processMetadataChaining(
- Metadata metadata, Map metadataMap, Metadata newMetadata) {
+ Metadata metadata, Map metadataMap, Metadata newMetadata)
+ {
if (!metadata.getMetadataIdRef().isEmpty()) {
@@ -125,20 +121,17 @@
}
-
// ---------------------------------- abstract methods
-
/**
- * Merges two metadata blocks (metadata1 and metadata2) and put the
result
+ * Merges two metadata blocks (metadata1 and metadata2) and put the
result
* of this operation in newMetadata element.
*/
public abstract void merge(
Metadata metadata1, Metadata metadata2, Metadata newMetadata);
-
} //BaseChaining
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/CompleteMetadataStoreRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/CompleteMetadataStoreRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/CompleteMetadataStoreRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -13,22 +13,21 @@
import org.perfsonar.service.base.engine.ActionType;
-
/**
- * MessageHandler for CompleteMetadataStoreRequest messages.
+ * MessageHandler for CompleteMetadataStoreRequest messages.
*
- * @author romradz
+ * @author romradz
*/
-public class CompleteMetadataStoreRequest extends LinkRequest {
+public class CompleteMetadataStoreRequest extends LinkRequest
+{
-
// ---------------------------------- constructors
+ public CompleteMetadataStoreRequest() throws PerfSONARException
+ {
- public CompleteMetadataStoreRequest() throws PerfSONARException {
-
super();
logger.debug("CompleteMetadataStoreRequest: MessageHandler created");
setType(ActionType.STORE_METADATA_CONFIGURATION);
@@ -38,12 +37,11 @@
// ---------------------------------- public methods
-
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
return metadatas;
}
-
} //SetupDataRequest
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/DataRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/DataRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/DataRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -20,20 +20,20 @@
/**
* Implements common methods needed by Data centric messages.
*
- * @author boote
+ * @author boote
*/
-public abstract class DataRequest extends Request {
+public abstract class DataRequest extends Request
+{
-
// ---------------------------------- class fields
-
// ---------------------------------- constructors
public DataRequest()
- throws PerfSONARException{
+ throws PerfSONARException
+ {
type = "DataRequest";
}
@@ -45,52 +45,52 @@
* at the end.
*/
protected void addChainList(
- Metadata head,
- Map mdMap,
- List<Metadata> mdChain,
- boolean mustKey)
+ Metadata head,
+ Map mdMap,
+ List<Metadata> mdChain,
+ boolean mustKey)
throws PerfSONARException
{
- if(head == null){
+ if (head == null) {
return;
}
Key key = head.getKey();
- if(mustKey){
+ if (mustKey) {
// If this metadata does not hold a key, then the
// chain is not a "key" chain.
- if(key == null){
+ if (key == null) {
logger.fatal(
- "SetupDataRequest: Metadata MUST hold a key " +
+ "SetupDataRequest: Metadata MUST hold a key " +
"for GET_DATA");
throw new PerfSONARException(
- "SetupDataRequest: Metadata MUST hold a key " +
+ "SetupDataRequest: Metadata MUST hold a key " +
"for GET_DATA");
}
}
// filter chaining is done using the Subject element.
org.ggf.ns.nmwg.base.v2_0.Subject subj = head.getSubject();
- if(subj != null){
+ if (subj != null) {
// Recurse again if this metadata is chained
- addChainList((Metadata)mdMap.get(subj.getMetadataIdRef()),
mdMap,mdChain,mustKey);
+ addChainList((Metadata) mdMap.get(subj.getMetadataIdRef()),
mdMap, mdChain, mustKey);
}
// If there was no subject, a key is required or this is an invalid
// metadata
- else if(key == null){
+ else if (key == null) {
logger.fatal(
- "SetupDataRequest: Metadata MUST have subject or key");
+ "SetupDataRequest: Metadata MUST have subject or key");
throw new PerfSONARException(
- "SetupDataRequest: Metadata MUST have subject or key");
+ "SetupDataRequest: Metadata MUST have subject or key");
}
// All chained elements have been added successfully, add this one.
- mdChain.add(0,head);
+ mdChain.add(0, head);
logger.debug(
- "DataRequest.addChainList: Adding metadata(Id=" +
+ "DataRequest.addChainList: Adding metadata(Id=" +
head.getId() + ")");
}
@@ -99,9 +99,10 @@
* the metadata elements.
*/
protected Message metaToKey(
- Message reqMessage,
- Message respMessage)
- throws PerfSONARException {
+ Message reqMessage,
+ Message respMessage)
+ throws PerfSONARException
+ {
/*
* Get Map for MetaData and Data children from reqMessage
@@ -119,11 +120,11 @@
Message atomResp;
- List<Metadata> mdChain = new ArrayList<Metadata>();
+ List<Metadata> mdChain = new ArrayList<Metadata>();
logger.debug("DataRequest.metaToKey: Iterate on data");
- if(dataCollection.size() < 1){
+ if (dataCollection.size() < 1) {
logger.warn("DataRequest.metaToKey: empty request?");
}
@@ -223,8 +224,8 @@
// This signature allows the resp message to be created as new,
// the other signature is used to add to an existing message.
protected Message metaToKey(
- Message reqMessage
- ) throws PerfSONARException
+ Message reqMessage
+ ) throws PerfSONARException
{
Message respMessage = new Message();
@@ -232,7 +233,7 @@
respMessage.setType("MetadataKeyResponse");
logger.debug("MetadataKeyRequest: calling metaToKey");
- return metaToKey(reqMessage,respMessage);
+ return metaToKey(reqMessage, respMessage);
}
// ---------------------------------- public methods
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/EchoRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/EchoRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/EchoRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -19,58 +19,56 @@
/**
- * MessageHandler for EchoRequest messages.
+ * MessageHandler for EchoRequest messages.
*
- * @author romradz
+ * @author romradz
*/
-public class EchoRequest extends Request {
+public class EchoRequest extends Request
+{
-
// ---------------------------------- fields
-
public static final String ECHO_NAMESPACE =
"http://schemas.perfsonar.net/tools/admin/echo/2.0";
-
// ---------------------------------- constructors
+ public EchoRequest() throws PerfSONARException
+ {
- public EchoRequest() throws PerfSONARException {
-
super();
logger.debug("EchoRequest: MessageHandler created");
setType(ActionType.ECHO);
}
-
// ---------------------------------- public methods
-
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
return metadatas;
}
@Override
- public Message execute(Message reqMessage) {
+ public Message execute(Message reqMessage)
+ {
ArrayList<Message> output = new ArrayList<Message>();
- for (Message inputMessage: extractMultipleRequests(reqMessage)) {
+ for (Message inputMessage : extractMultipleRequests(reqMessage)) {
try {
output.add(
- executeEcho(inputMessage));
+ executeEcho(inputMessage));
} catch (PerfSONARException e) {
output.add(
ResultCodesUtil.createResultCodeMetadata(
- null, e));
+ null, e));
}
}
@@ -82,11 +80,11 @@
ResultCodesUtil.createResultCodeMetadata(
respMessage,
new PerfSONARException(
- "warning.common.no_metadata",
- "No output metadata was returned by MessageHandler."+
- " Maybe there was no data trigger, or data trigger "+
+ "warning.common.no_metadata",
+ "No output metadata was returned by MessageHandler." +
+ " Maybe there was no data trigger, or data trigger "
+
" didn't have valid metadataIdRef? ")
- );
+ );
}
@@ -100,7 +98,8 @@
protected Message executeEcho(Message request)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
Data data = request.getDataArray()[0];
Metadata metadata = request.getMetadata(data.getMetadataIdRef());
@@ -108,10 +107,10 @@
EventType eventType = metadata.getEventType();
if (eventType == null) {
logger.debug("EchoRequest.executeEcho: The request does not
contain "
- + "eventType element");
+ + "eventType element");
throw new PerfSONARException(
- "error.request",
- "EchoRequest.executeEcho: The request does not contain "
+ "error.request",
+ "EchoRequest.executeEcho: The request does not contain "
+ "eventType element");
}
@@ -130,7 +129,8 @@
}
- protected Message executeSimpleEcho() {
+ protected Message executeSimpleEcho()
+ {
logger.debug("EchoRequest: executeSimpleEcho()");
@@ -138,8 +138,8 @@
PerfSONARException pex =
new PerfSONARException(
- "success.echo",
- "This is the echo response from the service.");
+ "success.echo",
+ "This is the echo response from the service.");
ResultCodesUtil.createResultCodeMetadata(response, pex);
@@ -148,14 +148,15 @@
}
- protected Message getEmptyEventTypeResponse() {
+ protected Message getEmptyEventTypeResponse()
+ {
Message response = new Message();
PerfSONARException pex =
new PerfSONARException(
- "error.echo",
- "EventType is empty.");
+ "error.echo",
+ "EventType is empty.");
ResultCodesUtil.createResultCodeMetadata(response, pex);
@@ -164,5 +165,4 @@
}
-
} //EchoRequest
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSCleanupRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSCleanupRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSCleanupRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -9,15 +9,16 @@
/**
* @author Maciej Glowiak
- * MessageHandler for LS Cleanup
- *
+ * MessageHandler for LS Cleanup
*/
-public class LSCleanupRequest extends LSRequest {
+public class LSCleanupRequest extends LSRequest
+{
/**
* @throws SystemException
*/
- public LSCleanupRequest() throws PerfSONARException {
+ public LSCleanupRequest() throws PerfSONARException
+ {
super();
logger.debug("LSCleanupRequest: MessageHandler created");
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSDeregisterRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSDeregisterRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSDeregisterRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -9,15 +9,16 @@
/**
* @author Maciej Glowiak
- * MessageHandler for LS DeRegiser Request
- *
+ * MessageHandler for LS DeRegiser Request
*/
-public class LSDeregisterRequest extends LSRequest {
+public class LSDeregisterRequest extends LSRequest
+{
/**
* @throws SystemException
*/
- public LSDeregisterRequest() throws PerfSONARException {
+ public LSDeregisterRequest() throws PerfSONARException
+ {
super();
logger.debug("LSDeRegisterRequest: MessageHandler created");
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSKeepaliveRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSKeepaliveRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSKeepaliveRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -9,15 +9,16 @@
/**
* @author Maciej Glowiak
- * MessageHandler for LS Keep-Alive Request
- *
+ * MessageHandler for LS Keep-Alive Request
*/
-public class LSKeepaliveRequest extends LSRequest {
+public class LSKeepaliveRequest extends LSRequest
+{
/**
* @throws SystemException
*/
- public LSKeepaliveRequest() throws PerfSONARException {
+ public LSKeepaliveRequest() throws PerfSONARException
+ {
super();
logger.debug("LSKeepaliveRequest: MessageHandler created");
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSQueryRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSQueryRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSQueryRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -12,25 +12,27 @@
/**
* @author Maciej Glowiak
- * MessageHandler for LS Query Request
- *
+ * MessageHandler for LS Query Request
*/
-public class LSQueryRequest extends LSRequest {
+public class LSQueryRequest extends LSRequest
+{
/**
* @throws SystemException
*/
- public LSQueryRequest() throws PerfSONARException {
+ public LSQueryRequest() throws PerfSONARException
+ {
super();
logger.debug("LSQueryRequest: MessageHandler created");
setType(ActionType.LS_LOOKUP);
}
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
-
- return metadatas;
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
+ return metadatas;
+
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSRegisterRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSRegisterRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSRegisterRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -18,23 +18,23 @@
/**
* @author Maciej Glowiak
- * MessageHandler for LS Regiser Request
- *
- * Note: It doesn't use Request class because of not clear use data
- * triggers. Generic Request class splits message into separate
- * "requests" by data triggers. LSRegisterRequest has always one
- * metadata and a lot of data elements belonging to it. They're not
- * actually data triggers, and the message shouldn't be splitted
- * into separate requests!
- *
-
+ * MessageHandler for LS Regiser Request
+ * <p/>
+ * Note: It doesn't use Request class because of not clear use data
+ * triggers. Generic Request class splits message into separate
+ * "requests" by data triggers. LSRegisterRequest has always one
+ * metadata and a lot of data elements belonging to it. They're not
+ * actually data triggers, and the message shouldn't be splitted
+ * into separate requests!
*/
-public class LSRegisterRequest extends LSRequest {
+public class LSRegisterRequest extends LSRequest
+{
/**
* @throws SystemException
*/
- public LSRegisterRequest() throws PerfSONARException {
+ public LSRegisterRequest() throws PerfSONARException
+ {
super();
logger.debug("LSRegisterRequest: MessageHandler created");
@@ -43,12 +43,13 @@
}
@Override
- protected List<Message> extractMultipleRequests(Message reqMessage) {
+ protected List<Message> extractMultipleRequests(Message reqMessage)
+ {
ArrayList<Message> messagesList = new ArrayList<Message>();
//data chains container <String metadataIdRef, ArrayList<Data>>
- HashMap<String,Message> dataChains = new HashMap<String,Message>();
+ HashMap<String, Message> dataChains = new HashMap<String, Message>();
//get input data elements
Collection<Data> dataTriggers = reqMessage.getDataMap().values();
@@ -58,7 +59,7 @@
//put all data having the same metadataIdRef to the same
container
String metaref = data.getMetadataIdRef();
- if (dataChains.get(metaref)==null)
+ if (dataChains.get(metaref) == null)
dataChains.put(metaref, new Message());
Message m = dataChains.get(metaref);
m.setData(data);
@@ -80,11 +81,11 @@
//System.out.println("## metadata chain for
["+metadataIdRef+"]");
//find metadata chaining
- Map<String,Metadata> metadatas = new
HashMap<String,Metadata>();
+ Map<String, Metadata> metadatas = new HashMap<String,
Metadata>();
getChaining(reqMessage, metadataIdRef, metadatas);
- Map<String,Metadata> mergedMetadatas =
mergeAllMetadata(metadatas);
+ Map<String, Metadata> mergedMetadatas =
mergeAllMetadata(metadatas);
for (Metadata metadata : mergedMetadatas.values()) {
- message.setMetadata(metadata);
+ message.setMetadata(metadata);
}
//copy id, type from request
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LSRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -13,14 +13,15 @@
* General MessageHangler for LS
*
* @author Maciej Glowiak
- *
*/
-public abstract class LSRequest extends Request {
+public abstract class LSRequest extends Request
+{
/**
* @throws SystemException
*/
- public LSRequest() throws PerfSONARException {
+ public LSRequest() throws PerfSONARException
+ {
super();
setType("LSRequest");
@@ -29,14 +30,16 @@
/**
* Merge chained metadata elements
+ *
* @param metadatas map of metadata elements
* @return metadatas map of merged metadata elements
*/
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
-
- return metadatas;
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
+ return metadatas;
+
}
/*
public Metadata mergeAllMetadata(Map<String,Metadata> metadatas) {
@@ -88,5 +91,4 @@
*/
-
} //LSRequest
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LinkRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LinkRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LinkRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -21,16 +21,17 @@
* Abstract class that does all the things that a "request" message
* handler will need to do.
*
- * @author romradz
-
+ * @author romradz
*/
-public abstract class LinkRequest extends Request {
+public abstract class LinkRequest extends Request
+{
// ---------------------------------- constructors
- public LinkRequest() throws PerfSONARException {
+ public LinkRequest() throws PerfSONARException
+ {
super();
type = "LinkRequest";
@@ -41,16 +42,17 @@
@Override
- protected Map<String,Metadata> getChaining(
- Message inputMessage, String metadataId, Map<String,Metadata>
metadatas)
- throws NoSuchMetadataException {
+ protected Map<String, Metadata> getChaining(
+ Message inputMessage, String metadataId, Map<String, Metadata>
metadatas)
+ throws NoSuchMetadataException
+ {
// node's nodeIdRef might points to a metadata which does not exist
//if (metadataId == null) throw new NoSuchMetadataException();
if (metadataId == null) return metadatas;
- Metadata metadata = inputMessage.getMetadata(metadataId);
+ Metadata metadata = inputMessage.getMetadata(metadataId);
if (metadata == null) throw new NoSuchMetadataException();
@@ -60,13 +62,13 @@
//prevent endless loop
if (metadata.getSubject() != null) {
- if (!(metadata.getSubject().getMetadataIdRef() != null &&
metadata.getSubject().getMetadataIdRef().isEmpty())&&
+ if (!(metadata.getSubject().getMetadataIdRef() != null &&
metadata.getSubject().getMetadataIdRef().isEmpty()) &&
!(metadata.getId().equals(metadata.getSubject().getMetadataIdRef()))) {
getChaining(
- inputMessage,
- metadata.getSubject().getMetadataIdRef(),
- metadatas);
+ inputMessage,
+ metadata.getSubject().getMetadataIdRef(),
+ metadatas);
} else if
(!metadata.getSubject().getChildrenByType("link").isEmpty()) {
@@ -87,7 +89,7 @@
String chainedMetadataId = metadata.getMetadataIdRef();
//get other chain, prevent endless loop
- if (!(chainedMetadataId != null && chainedMetadataId.isEmpty())&&
+ if (!(chainedMetadataId != null && chainedMetadataId.isEmpty()) &&
!(metadata.getId().equals(chainedMetadataId))) {
getChaining(inputMessage, chainedMetadataId, metadatas);
}
@@ -96,7 +98,8 @@
}
- private String getNodeMetadataId(String nodeId, Message inputMessage) {
+ private String getNodeMetadataId(String nodeId, Message inputMessage)
+ {
// searching form metadata with the node (nodeId)
Collection<Metadata> collection =
inputMessage.getMetadataMap().values();
@@ -109,7 +112,7 @@
if ((subject = metadata.getSubject()) != null)
if ((nodes = subject.getChildrenByType("node")).isEmpty())
continue;
- else if ((node = (Node)nodes.get(0)) != null )
+ else if ((node = (Node) nodes.get(0)) != null)
if (nodeId.equals(node.getId()))
return metadata.getId();
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LookupInfoRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LookupInfoRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/LookupInfoRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -28,29 +28,27 @@
/**
- * MessageHandler for LookupInfoRequest messages.
+ * MessageHandler for LookupInfoRequest messages.
*
- * @author romradz
+ * @author romradz
*/
-public class LookupInfoRequest extends Request {
+public class LookupInfoRequest extends Request
+{
-
// ---------------------------------- fields
-
public static final String LOOKUP_INFO_NAMESPACE =
- "http://schemas.perfsonar.net/tools/admin/lookupinfo/2.0";
+ "http://schemas.perfsonar.net/tools/admin/lookupinfo/2.0";
-
// ---------------------------------- constructors
+ public LookupInfoRequest() throws PerfSONARException
+ {
- public LookupInfoRequest() throws PerfSONARException {
-
super();
logger.debug("LookupInfoRequest: MessageHandler created");
setType(ActionType.GET_LOOKUP_INFO);
@@ -58,36 +56,36 @@
}
-
// ---------------------------------- public methods
-
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
-
- return metadatas;
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
+ return metadatas;
+
}
@Override
- public Message execute(Message reqMessage) {
+ public Message execute(Message reqMessage)
+ {
ArrayList<Message> output = new ArrayList<Message>();
- for (Message inputMessage: extractMultipleRequests(reqMessage)) {
+ for (Message inputMessage : extractMultipleRequests(reqMessage)) {
try {
output.add(
- getLookupInfo(inputMessage));
+ getLookupInfo(inputMessage));
} catch (PerfSONARException e) {
output.add(
ResultCodesUtil.createResultCodeMetadata(
- null, e));
+ null, e));
}
@@ -101,11 +99,11 @@
ResultCodesUtil.createResultCodeMetadata(
respMessage,
new PerfSONARException(
- "warning.common.no_metadata",
- "No output metadata was returned by MessageHandler."+
- " Maybe there was no data trigger, or data trigger "+
+ "warning.common.no_metadata",
+ "No output metadata was returned by MessageHandler." +
+ " Maybe there was no data trigger, or data trigger "
+
" didn't have valid metadataIdRef? ")
- );
+ );
}
@@ -118,56 +116,56 @@
}
-
// ---------------------------------- protected methods
-
protected Message getLookupInfo(Message request)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
- Data data = request.getDataArray()[0];
- Metadata metadata = request.getMetadata(data.getMetadataIdRef());
+ Data data = request.getDataArray()[0];
+ Metadata metadata = request.getMetadata(data.getMetadataIdRef());
- EventType eventType = metadata.getEventType();
- if (eventType == null) {
- logger.warn("LookupInfoRequest.executeEcho: The request does
not contain "
- + "eventType element");
- throw new PerfSONARException(
- "error.request",
- "LookupInfoRequest.executeEcho: The request
does not contain "
- + "eventType element");
- }
+ EventType eventType = metadata.getEventType();
+ if (eventType == null) {
+ logger.warn("LookupInfoRequest.executeEcho: The request does not
contain "
+ + "eventType element");
+ throw new PerfSONARException(
+ "error.request",
+ "LookupInfoRequest.executeEcho: The request does not contain
"
+ + "eventType element");
+ }
- Message response;
-
- if (eventType.getEventType().trim().equals(LOOKUP_INFO_NAMESPACE)) {
+ Message response;
- PropertiesServiceDescription serviceDescription =
- new PropertiesServiceDescription();
- Map commonParameters =
serviceDescription.getServiceDescription();
+ if (eventType.getEventType().trim().equals(LOOKUP_INFO_NAMESPACE)) {
- response = getResponse(commonParameters);
+ PropertiesServiceDescription serviceDescription =
+ new PropertiesServiceDescription();
+ Map commonParameters =
serviceDescription.getServiceDescription();
- } else {
+ response = getResponse(commonParameters);
- response = getWrongEventTypeResponse();
+ } else {
- }
+ response = getWrongEventTypeResponse();
- return response;
+ }
+ return response;
+
}
- protected Message getResponse(Map commonParameters) {
+ protected Message getResponse(Map commonParameters)
+ {
- logger.debug("LookupInfoRequest: getResponse()");
+ logger.debug("LookupInfoRequest: getResponse()");
- Message response = new Message();
+ Message response = new Message();
- Metadata metadata = new Metadata();
- response.setMetadata(metadata);
+ Metadata metadata = new Metadata();
+ response.setMetadata(metadata);
//data
Data data = new Data();
@@ -184,7 +182,7 @@
//access point
String accessPointString = (String)
commonParameters.get("access_point");
if (accessPointString == null)
- accessPointString = "";
+ accessPointString = "";
AccessPoint ap = new AccessPoint();
ap.setAccessPoint(accessPointString);
service.setAccessPoint(ap);
@@ -192,7 +190,7 @@
//service name
String serviceNameString = (String)
commonParameters.get("service_name");
if (serviceNameString == null)
- serviceNameString ="";
+ serviceNameString = "";
ServiceName sn = new ServiceName();
sn.setServiceName(serviceNameString);
service.setServiceName(sn);
@@ -200,7 +198,7 @@
//service type
String serviceTypeString = (String)
commonParameters.get("service_type");
if (serviceTypeString == null)
- serviceTypeString = "";
+ serviceTypeString = "";
ServiceType st = new ServiceType();
st.setServiceType(serviceTypeString);
service.setServiceType(st);
@@ -208,7 +206,7 @@
//service description
String serviceDescString = (String)
commonParameters.get("service_description");
if (serviceDescString == null)
- serviceDescString = "";
+ serviceDescString = "";
ServiceDescription sd = new ServiceDescription();
sd.setServiceDescription(serviceDescString);
service.setServiceDescription(sd);
@@ -216,7 +214,7 @@
//service version
String serviceVersionString = (String)
commonParameters.get("service_version");
if (serviceVersionString == null)
- serviceVersionString = "";
+ serviceVersionString = "";
ServiceVersion sv = new ServiceVersion();
sv.setServiceVersion(serviceVersionString);
service.setServiceVersion(sv);
@@ -224,7 +222,7 @@
//organization owning the service
String organizationString = (String)
commonParameters.get("organization_name");
if (organizationString == null)
- organizationString = "";
+ organizationString = "";
Organization organization = new Organization();
organization.setOrganization(organizationString);
service.setOrganization(organization);
@@ -232,7 +230,7 @@
//organization owning the service
String contactEmailString = (String)
commonParameters.get("contact_email");
if (contactEmailString == null)
- contactEmailString = "";
+ contactEmailString = "";
ContactEmail contactEmail = new ContactEmail();
contactEmail.setContactEmail(contactEmailString);
service.setContactEmail(contactEmail);
@@ -242,21 +240,21 @@
}
- protected Message getWrongEventTypeResponse() {
+ protected Message getWrongEventTypeResponse()
+ {
- Message response = new Message();
+ Message response = new Message();
- PerfSONARException pex =
- new PerfSONARException(
- "error.lookup_info",
- "EventType is wrong.");
+ PerfSONARException pex =
+ new PerfSONARException(
+ "error.lookup_info",
+ "EventType is wrong.");
- ResultCodesUtil.createResultCodeMetadata(response, pex);
+ ResultCodesUtil.createResultCodeMetadata(response, pex);
- return response;
+ return response;
}
-
} //LookupInfoRequest
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementArchiveStoreKeyRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementArchiveStoreKeyRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementArchiveStoreKeyRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -12,20 +12,20 @@
import org.perfsonar.service.base.engine.ActionType;
/**
- * MessageHandler for MeasurementArchiveStoreRequest messages.
+ * MessageHandler for MeasurementArchiveStoreRequest messages.
*
- * @author romradz
+ * @author romradz
*/
-public class MeasurementArchiveStoreKeyRequest extends Request {
+public class MeasurementArchiveStoreKeyRequest extends Request
+{
-
// ---------------------------------- constructors
+ public MeasurementArchiveStoreKeyRequest() throws PerfSONARException
+ {
- public MeasurementArchiveStoreKeyRequest() throws PerfSONARException {
-
super();
logger.debug("MeasurementArchiveStoreKeyRequest: MessageHandler
created");
setType(ActionType.STORE_KEY);
@@ -33,19 +33,16 @@
}
-
// ---------------------------------- public methods
-
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
-
- return metadatas;
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
+ return metadatas;
+
}
-
-
} //MeasurementArchiveStoreRequest
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementArchiveStoreRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementArchiveStoreRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementArchiveStoreRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -12,20 +12,20 @@
import org.perfsonar.service.base.engine.ActionType;
/**
- * MessageHandler for MeasurementArchiveStoreRequest messages.
+ * MessageHandler for MeasurementArchiveStoreRequest messages.
*
- * @author romradz
+ * @author romradz
*/
-public class MeasurementArchiveStoreRequest extends Request {
+public class MeasurementArchiveStoreRequest extends Request
+{
-
// ---------------------------------- constructors
+ public MeasurementArchiveStoreRequest() throws PerfSONARException
+ {
- public MeasurementArchiveStoreRequest() throws PerfSONARException {
-
super();
logger.debug("MeasurementArchiveStoreRequest: MessageHandler
created");
setType(ActionType.STORE_DATA);
@@ -33,19 +33,16 @@
}
-
// ---------------------------------- public methods
-
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
-
- return metadatas;
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
+ return metadatas;
+
}
-
-
} //MeasurementArchiveStoreRequest
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MeasurementRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -15,17 +15,18 @@
/**
* MessageHandler for MeasurementRequest messages
*
- * @author boote
+ * @author boote
*/
-public class MeasurementRequest extends Request {
+public class MeasurementRequest extends Request
+{
// ---------------------------------- constructors
-
public MeasurementRequest()
- throws PerfSONARException{
+ throws PerfSONARException
+ {
super();
logger.debug("MeasurementRequest: MessageHandler created");
@@ -37,12 +38,12 @@
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
-
- return metadatas;
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
+ return metadatas;
+
}
-
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MessageHandler.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MessageHandler.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MessageHandler.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -15,25 +15,24 @@
import org.ggf.ns.nmwg.base.v2_0.Message;
import org.perfsonar.base.exceptions.PerfSONARException;
-public interface MessageHandler {
+public interface MessageHandler
+{
-
/**
- * Returns thge type of messagehandler
+ * Returns thge type of messagehandler
*/
public String getType();
/**
* @return Message
- *
- * Runs the correct ServiceEngine for the given request message
- * and returns the result.
+ * <p/>
+ * Runs the correct ServiceEngine for the given request message
+ * and returns the result.
*/
public Message execute(Message reqMessage)
throws PerfSONARException;
-
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MessageHandlerFactory.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MessageHandlerFactory.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MessageHandlerFactory.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -14,26 +14,28 @@
import org.perfsonar.base.exceptions.PerfSONARException;
/**
- * Factory class which can be used to get the appropriate messageHandler
- * for the given message type.
+ * Factory class which can be used to get the appropriate messageHandler
+ * for the given message type.
*
- * @author boote
+ * @author boote
*/
-public class MessageHandlerFactory {
+public class MessageHandlerFactory
+{
private final static Map<String, String> m2c = new Hashtable<String,
String>();
- private final static Object mutex = new Object();
+ private final static Object mutex = new Object();
- public static MessageHandler getMessageHandler(String messageType)
throws PerfSONARException{
+ public static MessageHandler getMessageHandler(String messageType)
throws PerfSONARException
+ {
// get a logger
- LoggerComponent logger =
(LoggerComponent)AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
+ LoggerComponent logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
// one time initialization to determine what message types are
// supported by the service.
- if (m2c.isEmpty()){
- init();
+ if (m2c.isEmpty()) {
+ init();
}
- if (m2c.isEmpty()){
+ if (m2c.isEmpty()) {
logger.error("MessageHandlerFactory: no known allowed Message
Types");
}
@@ -43,10 +45,10 @@
if (className == null) {
throw new PerfSONARException(
- "error.common.action_not_supported",
- "Action ["+messageType+"] is not supported by " +
- "the service or cannot be served - " +
- "cannot instantiate Message Handler"
+ "error.common.action_not_supported",
+ "Action [" + messageType + "] is not supported by " +
+ "the service or cannot be served - " +
+ "cannot instantiate Message Handler"
);
}
@@ -59,49 +61,51 @@
logger.fatal("MessageHandlerFactory: Unable to Instantiate
messageHandler for: " + messageType);
logger.fatal("MessageHandlerFactory: because of Instatiation
Problems " + e.getMessage());
throw new PerfSONARException(
- "error.common.action_not_supported",
- "MessageHandlerFactory: Unable to create messageHandler
for: " + messageType + " because: " + e.getMessage()
+ "error.common.action_not_supported",
+ "MessageHandlerFactory: Unable to create messageHandler for:
" + messageType + " because: " + e.getMessage()
);
} catch (IllegalAccessException e) {
logger.fatal("MessageHandlerFactory: Unable to Instantiate
messageHandler for: " + messageType);
logger.fatal("MessageHandlerFactory: because of illegalAccess" +
e.getMessage());
throw new PerfSONARException(
- "error.common.action_not_supported",
- "MessageHandlerFactory: Unable to create messageHandler
for: " + messageType + " because: " + e.getMessage()
+ "error.common.action_not_supported",
+ "MessageHandlerFactory: Unable to create messageHandler for:
" + messageType + " because: " + e.getMessage()
);
} catch (ClassNotFoundException e) {
logger.fatal("MessageHandlerFactory: Unable to Instantiate
messageHandler for: " + messageType);
logger.fatal("MessageHandlerFactory: because classNotFound :" +
e.getMessage());
throw new PerfSONARException(
- "error.common.action_not_supported",
- "MessageHandlerFactory: Unable to create messageHandler
for: " + messageType + " because: " + e.getMessage()
+ "error.common.action_not_supported",
+ "MessageHandlerFactory: Unable to create messageHandler for:
" + messageType + " because: " + e.getMessage()
);
}
if (handler == null) {
logger.fatal("MessageHandlerFactory: Unable to create
messageHandler for: " + messageType);
throw new PerfSONARException(
- "error.common.action_not_supported",
- "MessageHandlerFactory: Unable to create messageHandler
for: " + messageType
+ "error.common.action_not_supported",
+ "MessageHandlerFactory: Unable to create messageHandler for:
" + messageType
);
}
return handler;
}
- private static void init() throws PerfSONARException {
- synchronized (mutex) {
- if(!m2c.isEmpty()) return; // if the lock was
blocking a other thread then make the second thread do nothing here.
-
- ConfigurationComponent configManager =
(ConfigurationComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONFIG);
+ private static void init() throws PerfSONARException
+ {
+ synchronized (mutex) {
+ if (!m2c.isEmpty())
+ return; // if the lock was blocking a other thread then make
the second thread do nothing here.
- String serviceType =
configManager.getProperty("service.r.type");
- String messageTypes =
configManager.getProperty("service." + serviceType + ".message_types");
- String[] allowedMesgTypes =
messageTypes.split("\\s*,\\s*");
+ ConfigurationComponent configManager = (ConfigurationComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONFIG);
+ String serviceType = configManager.getProperty("service.r.type");
+ String messageTypes = configManager.getProperty("service." +
serviceType + ".message_types");
+ String[] allowedMesgTypes = messageTypes.split("\\s*,\\s*");
+
for (String allowedMesgType : allowedMesgTypes) {
m2c.put(allowedMesgType,
"org.perfsonar.service.base.messages." + allowedMesgType);
}
- }
- }
+ }
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MetadataKeyRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MetadataKeyRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/MetadataKeyRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -12,22 +12,21 @@
import org.perfsonar.service.base.engine.ActionType;
-
/**
* MessageHandler for request-key messages.
*
- * @author romradz
+ * @author romradz
*/
-public class MetadataKeyRequest extends Request {
+public class MetadataKeyRequest extends Request
+{
-
// ---------------------------------- constructors
+ public MetadataKeyRequest() throws PerfSONARException
+ {
- public MetadataKeyRequest() throws PerfSONARException {
-
super();
logger.debug("MetadataKeyRequest: MessageHandler created");
setType(ActionType.GET_KEY);
@@ -35,18 +34,16 @@
}
-
// ---------------------------------- public methods
-
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
-
- return metadatas;
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
+ return metadatas;
+
}
-
} //MetadataKeyRequest
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/Request.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/Request.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/Request.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -28,47 +28,45 @@
* Abstract class that does all the things that a "request" message
* handler will need to do.
*
- * @author mac
- * @author romradz
- * @author boote
+ * @author mac
+ * @author romradz
+ * @author boote
*/
-public abstract class Request implements MessageHandler {
+public abstract class Request implements MessageHandler
+{
-
// ---------------------------------- class fields
+ protected String type = null;
+ protected LoggerComponent logger = null;
+ protected ConfigurationComponent configManager = null;
+ protected String serviceType = null;
+ protected String serviceEngineClassName = null;
+ protected ServiceEngine serviceEngine = null;
- protected String type = null;
- protected LoggerComponent logger = null;
- protected ConfigurationComponent configManager = null;
- protected String serviceType = null;
- protected String serviceEngineClassName = null;
- protected ServiceEngine serviceEngine = null;
-
-
// ---------------------------------- constructors
+ public Request() throws PerfSONARException
+ {
- public Request() throws PerfSONARException {
-
type = "Request";
// get a logger
- logger = (LoggerComponent)AuxiliaryComponentManager.
+ logger = (LoggerComponent) AuxiliaryComponentManager.
getInstance().getComponent(ComponentNames.LOGGER);
// Config manager used to determine MA type
- configManager = (ConfigurationComponent)AuxiliaryComponentManager.
+ configManager = (ConfigurationComponent) AuxiliaryComponentManager.
getInstance().getComponent(ComponentNames.CONFIG);
serviceType = configManager.getProperty("service.r.type");
serviceEngineClassName = configManager.getProperty("service."
- + serviceType
- + ".class_name");
+ + serviceType
+ + ".class_name");
// Fetch ServiceEngine from ServiceEngineFactory
serviceEngine =
@@ -77,20 +75,20 @@
}
-
// ---------------------------------- public methods
-
@Override
- public String getType() {
+ public String getType()
+ {
return type;
}
- public void setType(String type) {
+ public void setType(String type)
+ {
this.type = type;
@@ -101,13 +99,14 @@
* @see
org.perfsonar.commons.messages.MessageHandler#execute(org.ggf.ns.nmwg.base.Message)
*/
@Override
- public Message execute(Message reqMessage) {
+ public Message execute(Message reqMessage)
+ {
logger.debug("Request: MessageHandler.execute()");
ArrayList<Message> output = new ArrayList<Message>();
- for (Message inputMessage: extractMultipleRequests(reqMessage)) {
+ for (Message inputMessage : extractMultipleRequests(reqMessage)) {
try {
@@ -115,7 +114,7 @@
//run service engine and add result to output list
output.add(
- serviceEngine.takeAction(getType(),
+ serviceEngine.takeAction(getType(),
inputMessage));
} catch (PerfSONARException e) {
@@ -125,7 +124,7 @@
output.add(
ResultCodesUtil.createResultCodeMetadata(
- null, e));
+ null, e));
}
@@ -139,11 +138,11 @@
ResultCodesUtil.createResultCodeMetadata(
respMessage,
new PerfSONARException(
- "warning.common.no_metadata",
- "No output metadata was returned by MessageHandler."+
- " Maybe there was no data trigger, or data trigger "+
+ "warning.common.no_metadata",
+ "No output metadata was returned by MessageHandler." +
+ " Maybe there was no data trigger, or data trigger "
+
" didn't have valid metadataIdRef? ")
- );
+ );
}
@@ -156,26 +155,26 @@
}
-
// ---------------------------------- protected methods
-
//TODO: Method doesn't support multiple metadatas in one message
// (M1<-M2<-...Mn<-D1)
// Supports only M1<-D1, M1<-D2, .... M2<-D3, ....
+
/**
* Joins all messages in arraylist
*/
- protected Message mergeMultipleResponses(ArrayList<Message> messages) {
+ protected Message mergeMultipleResponses(ArrayList<Message> messages)
+ {
//how many messages do we have to merge?
//if more than one, it seems there may be the same identifiers
//so change them (add "_number" suffix)
if (messages.size() > 1) {
- int metaid=0;
- int dataid=0;
+ int metaid = 0;
+ int dataid = 0;
//create new common response message
Message respMessage = new Message();
@@ -199,7 +198,7 @@
//get old meta id
String meta1id = meta1.getId();
//compute new meta id
- String newMeta1id = meta1id+"_"+metaid;
+ String newMeta1id = meta1id + "_" + metaid;
//set new id
meta1.setId(newMeta1id);
@@ -232,7 +231,7 @@
//put data
if (data1.getMetadataIdRef().equals(meta1id)) {
- data1.setId(data1.getId() + "_"+dataid);
+ data1.setId(data1.getId() + "_" + dataid);
//change data metadata id ref to new meta id
data1.setMetadataIdRef(newMeta1id);
@@ -254,7 +253,7 @@
for (Message m : messages) {
respMessage = m;
}
- if (respMessage == null) respMessage=new Message();
+ if (respMessage == null) respMessage = new Message();
return respMessage;
}
@@ -262,7 +261,8 @@
}
- protected List<Message> extractMultipleRequests(Message reqMessage) {
+ protected List<Message> extractMultipleRequests(Message reqMessage)
+ {
ArrayList<Message> messages = new ArrayList<Message>();
Collection<Data> dataTriggers = reqMessage.getDataMap().values();
@@ -273,9 +273,9 @@
Message message = new Message();
try {
- Map<String,Metadata> metadatas = new
HashMap<String,Metadata>();
+ Map<String, Metadata> metadatas = new HashMap<String,
Metadata>();
getChaining(reqMessage, metadataIdRef, metadatas);
- Map<String,Metadata> mergedMetadatas =
mergeAllMetadata(metadatas);
+ Map<String, Metadata> mergedMetadatas =
mergeAllMetadata(metadatas);
for (Metadata metadata : mergedMetadatas.values()) {
@@ -309,18 +309,19 @@
/**
* Find metadata chain for metadata ID (the last metadata in chain)
*
- * @param inputMessage message to process (won't be changed)
+ * @param inputMessage message to process (won't be changed)
* @param lastMetadataId id of metadata which is last in chain
* @return map <id,metadata>
* @throws NoSuchMetadataException thrown if there is no metadata with
given ID
*/
- protected Map<String,Metadata> getChaining(
- Message inputMessage, String metadataId, Map<String,Metadata>
metadatas)
- throws NoSuchMetadataException {
+ protected Map<String, Metadata> getChaining(
+ Message inputMessage, String metadataId, Map<String, Metadata>
metadatas)
+ throws NoSuchMetadataException
+ {
if (metadataId == null) throw new NoSuchMetadataException();
- Metadata metadata = inputMessage.getMetadata(metadataId);
+ Metadata metadata = inputMessage.getMetadata(metadataId);
if (metadata == null) throw new NoSuchMetadataException();
@@ -329,20 +330,20 @@
//metadataIdRef in Subject
//prevent endless loop
if (metadata.getSubject() != null) {
- if (!(metadata.getSubject().getMetadataIdRef() != null &&
metadata.getSubject().getMetadataIdRef().isEmpty())&&
+ if (!(metadata.getSubject().getMetadataIdRef() != null &&
metadata.getSubject().getMetadataIdRef().isEmpty()) &&
!(metadata.getId().equals(metadata.getSubject().getMetadataIdRef()))) {
getChaining(
- inputMessage,
- metadata.getSubject().getMetadataIdRef(),
- metadatas);
+ inputMessage,
+ metadata.getSubject().getMetadataIdRef(),
+ metadatas);
}
}
String chainedMetadataId = metadata.getMetadataIdRef();
//get other chain, prevent endless loop
- if (!(chainedMetadataId != null && chainedMetadataId.isEmpty())&&
+ if (!(chainedMetadataId != null && chainedMetadataId.isEmpty()) &&
!(metadata.getId().equals(chainedMetadataId))) {
getChaining(inputMessage, chainedMetadataId, metadatas);
}
@@ -353,38 +354,34 @@
}
-
//------------------------------------------------- abstract method
-
/**
* Merge chained metadata elements
+ *
* @param metadatas map of metadata elements
* @return metadatas map of merged metadata elements
*/
- public abstract Map<String,Metadata>
mergeAllMetadata(Map<String,Metadata> metadatas);
+ public abstract Map<String, Metadata> mergeAllMetadata(Map<String,
Metadata> metadatas);
-
// ------------------------------------------------- inner classes
-
/**
* Exception thrown when Metadata could not be found. It's internal
* Message Handler
* exception.
*
* @author Maciej Glowiak
- *
*/
- protected class NoSuchMetadataException extends Exception {
+ protected class NoSuchMetadataException extends Exception
+ {
private static final long serialVersionUID = -3725261560519487460L;
}
-
} //Request
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SetupDataDBRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SetupDataDBRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SetupDataDBRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -3,11 +3,13 @@
import org.perfsonar.base.exceptions.PerfSONARException;
import org.perfsonar.service.base.engine.ActionType;
-public class SetupDataDBRequest extends TOPSRequest {
+public class SetupDataDBRequest extends TOPSRequest
+{
/**
* @throws PerfSONARException
*/
- public SetupDataDBRequest() throws PerfSONARException {
+ public SetupDataDBRequest() throws PerfSONARException
+ {
super();
logger.debug("SetupDataDBRequest: MessageHandler created");
setType(ActionType.SETUP_DATA_DB);
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SetupDataRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SetupDataRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SetupDataRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -13,22 +13,21 @@
import org.perfsonar.service.base.engine.ActionType;
-
/**
- * MessageHandler for SetupDataRequest messages.
+ * MessageHandler for SetupDataRequest messages.
*
- * @author romradz
+ * @author romradz
*/
-public class SetupDataRequest extends Request {
+public class SetupDataRequest extends Request
+{
-
// ---------------------------------- constructors
+ public SetupDataRequest() throws PerfSONARException
+ {
- public SetupDataRequest() throws PerfSONARException {
-
super();
logger.debug("SetupDataRequest: MessageHandler created");
setType(ActionType.GET_DATA);
@@ -36,18 +35,16 @@
}
-
// ---------------------------------- public methods
-
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
-
- return metadatas;
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
+ return metadatas;
+
}
-
} //SetupDataRequest
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SubscriptionKeepaliveRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SubscriptionKeepaliveRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SubscriptionKeepaliveRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -5,18 +5,21 @@
import org.ggf.ns.nmwg.base.v2_0.Metadata;
import org.perfsonar.base.exceptions.PerfSONARException;
-public class SubscriptionKeepaliveRequest extends Request {
+public class SubscriptionKeepaliveRequest extends Request
+{
- public SubscriptionKeepaliveRequest() throws PerfSONARException {
- super();
- // TODO Auto-generated constructor stub
+ public SubscriptionKeepaliveRequest() throws PerfSONARException
+ {
+ super();
+ // TODO Auto-generated constructor stub
}
@Override
public Map<String, Metadata> mergeAllMetadata(
- Map<String, Metadata> metadatas) {
- // TODO Auto-generated method stub
- return metadatas;
+ Map<String, Metadata> metadatas)
+ {
+ // TODO Auto-generated method stub
+ return metadatas;
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SubscriptionRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SubscriptionRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/SubscriptionRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -5,18 +5,21 @@
import org.ggf.ns.nmwg.base.v2_0.Metadata;
import org.perfsonar.base.exceptions.PerfSONARException;
-public class SubscriptionRequest extends Request {
+public class SubscriptionRequest extends Request
+{
- public SubscriptionRequest() throws PerfSONARException {
- super();
- // TODO Auto-generated constructor stub
+ public SubscriptionRequest() throws PerfSONARException
+ {
+ super();
+ // TODO Auto-generated constructor stub
}
@Override
public Map<String, Metadata> mergeAllMetadata(
- Map<String, Metadata> metadatas) {
- // TODO Auto-generated method stub
- return metadatas;
+ Map<String, Metadata> metadatas)
+ {
+ // TODO Auto-generated method stub
+ return metadatas;
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/TOPSRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/TOPSRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/TOPSRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -12,16 +12,18 @@
/**
* General MessageHangler for TOPS
+ *
* @author Maciej Glowiak, modified by Ulisses Alonso
- *
*/
-public abstract class TOPSRequest extends Request {
+public abstract class TOPSRequest extends Request
+{
/**
* @throws PerfSONARException
*/
- public TOPSRequest() throws PerfSONARException {
+ public TOPSRequest() throws PerfSONARException
+ {
super();
setType("TOPSRequest");
@@ -30,14 +32,16 @@
/**
* Merge chained metadata elements
+ *
* @param metadatas map of metadata elements
* @return metadatas map of merged metadata elements
*/
@Override
- public Map<String,Metadata> mergeAllMetadata(Map<String,Metadata>
metadatas) {
-
- return metadatas;
+ public Map<String, Metadata> mergeAllMetadata(Map<String, Metadata>
metadatas)
+ {
+ return metadatas;
+
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/UnSubscriptionRequest.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/UnSubscriptionRequest.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/messages/UnSubscriptionRequest.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -5,18 +5,21 @@
import org.ggf.ns.nmwg.base.v2_0.Metadata;
import org.perfsonar.base.exceptions.PerfSONARException;
-public class UnSubscriptionRequest extends Request {
+public class UnSubscriptionRequest extends Request
+{
- public UnSubscriptionRequest() throws PerfSONARException {
- super();
- // TODO Auto-generated constructor stub
+ public UnSubscriptionRequest() throws PerfSONARException
+ {
+ super();
+ // TODO Auto-generated constructor stub
}
@Override
public Map<String, Metadata> mergeAllMetadata(
- Map<String, Metadata> metadatas) {
- // TODO Auto-generated method stub
- return metadatas;
+ Map<String, Metadata> metadatas)
+ {
+ // TODO Auto-generated method stub
+ return metadatas;
}
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/GenericServiceLSRegistrator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/GenericServiceLSRegistrator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/GenericServiceLSRegistrator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -20,7 +20,8 @@
*
* @author Maciej Glowiak
*/
-public class GenericServiceLSRegistrator implements ServiceLSRegistrator {
+public class GenericServiceLSRegistrator implements ServiceLSRegistrator
+{
// ----------------------------------------------------- Constants
@@ -33,12 +34,14 @@
private boolean ls;
-
// -------------------------------------------------- Constructors
- public GenericServiceLSRegistrator() {}
+ public GenericServiceLSRegistrator()
+ {
+ }
- public GenericServiceLSRegistrator(ServiceDescription sd, ServiceContent
sc) {
+ public GenericServiceLSRegistrator(ServiceDescription sd, ServiceContent
sc)
+ {
serviceDescription = sd;
serviceContent = sc;
}
@@ -49,9 +52,10 @@
* Initializes Registrator
*/
@Override
- public void initRegistrator() throws PerfSONARException {
+ public void initRegistrator() throws PerfSONARException
+ {
- logger = (LoggerComponent)AuxiliaryComponentManager.
+ logger = (LoggerComponent) AuxiliaryComponentManager.
getInstance().getComponent(ComponentNames.LOGGER);
configuration = (ConfigurationComponent)
AuxiliaryComponentManager.getInstance().
@@ -61,92 +65,94 @@
try {
String typeStr = configuration.getProperty("service.r.type");
if ("ls".equalsIgnoreCase(typeStr))
- ls=true;
+ ls = true;
} catch (Exception ex) {
- ls=false;
+ ls = false;
}
-
-
}
@Override
- public Message register(String lsUrl) throws PerfSONARException {
- if (lsUrl==null) {
- throw new PerfSONARException(
+ public Message register(String lsUrl) throws PerfSONARException
+ {
+ if (lsUrl == null) {
+ throw new PerfSONARException(
"error.lsregistrator.no_ls_url",
"GenericServiceLSRegistrator: Lookup Service URL is null"
);
}
if (lsUrl != null && lsUrl.isEmpty()) {
- throw new PerfSONARException(
+ throw new PerfSONARException(
"error.lsregistrator.no_ls_url",
"GenericServiceLSRegistrator: Lookup Service URL is empty"
);
}
- logger.info("GenericServiceLSRegistrator: register to ["+lsUrl+"]");
+ logger.info("GenericServiceLSRegistrator: register to [" + lsUrl +
"]");
Message message = getLSRegisterRequestMessage();
logger.debug("GenericServiceLSRegistrator: sending via Axis");
//send request Document to url
try {
- logger.debug("GenericServiceLSRegistrator: Getting parser
configuration");
+ logger.debug("GenericServiceLSRegistrator: Getting parser
configuration");
//return response as Message
String parserFile =
configuration.getProperty("service.sax_parser.config");
File file = AuxiliaryComponentManager.lookupFile(parserFile);
- if(file!=null) {
- parserFile = file.getAbsolutePath();
+ if (file != null) {
+ parserFile = file.getAbsolutePath();
}
logger.debug("GenericServiceLSRegistrator: Creating Axis Client
and sending request");
AxisClient client = new AxisClient();
- Message responseMsg = client.sendRequest(lsUrl,message,
parserFile);
+ Message responseMsg = client.sendRequest(lsUrl, message,
parserFile);
return responseMsg;
} catch (ParserConfigurationException e) {
- logger.error("GenericServiceLSRegistrator:
ParserConfigurationException: "+e.getMessage());
- throw new
PerfSONARException("error.common.parse_error","GenericServiceLSRegistrator:
"+e.getMessage());
+ logger.error("GenericServiceLSRegistrator:
ParserConfigurationException: " + e.getMessage());
+ throw new PerfSONARException("error.common.parse_error",
"GenericServiceLSRegistrator: " + e.getMessage());
} catch (FactoryConfigurationError e) {
- logger.error("GenericServiceLSRegistrator:
FactoryConfigurationError: "+e.getMessage());
- throw new
PerfSONARException("error.common.parse_error","GenericServiceLSRegistrator:
"+e.getMessage());
+ logger.error("GenericServiceLSRegistrator:
FactoryConfigurationError: " + e.getMessage());
+ throw new PerfSONARException("error.common.parse_error",
"GenericServiceLSRegistrator: " + e.getMessage());
} catch (Exception e) {
- logger.error("GenericServiceLSRegistrator: "+e.getMessage());
- throw new
PerfSONARException("error.lsregistrator.other","GenericServiceLSRegistrator:
Error while sending request to LS: "+e.getMessage());
+ logger.error("GenericServiceLSRegistrator: " + e.getMessage());
+ throw new PerfSONARException("error.lsregistrator.other",
"GenericServiceLSRegistrator: Error while sending request to LS: " +
e.getMessage());
}
}
@Override
- public Message deregister(String lsUrl, String key) throws
PerfSONARException {
+ public Message deregister(String lsUrl, String key) throws
PerfSONARException
+ {
throw new PerfSONARException("error.common.action_not_implemented",
"Action not implemented");
}
@Override
- public Message update(String lsUrl, String key) throws
PerfSONARException {
+ public Message update(String lsUrl, String key) throws PerfSONARException
+ {
throw new PerfSONARException("error.common.action_not_implemented",
"Action not implemented");
}
@Override
- public Message keepalive(String lsUrl, String key) throws
PerfSONARException {
+ public Message keepalive(String lsUrl, String key) throws
PerfSONARException
+ {
throw new PerfSONARException("error.common.action_not_implemented",
"Action not implemented");
}
/**
- *
* Obtains configuration parameters (service description) and
* service content metadata (service content)
* returms LS Registration Request as NMWG Message
*
* @return Message NMWG
*/
- public Message getLSRegisterRequestMessage() throws PerfSONARException {
+ public Message getLSRegisterRequestMessage() throws PerfSONARException
+ {
- if (serviceDescription==null) {
- throw new PerfSONARException(
- "error.common.lsregistrator.no_service_description",
- "No service description"
+ if (serviceDescription == null) {
+ throw new PerfSONARException(
+ "error.common.lsregistrator.no_service_description",
+ "No service description"
);
}
@@ -159,40 +165,44 @@
if (ls) {
lsRegisterGenerator.setEventType(LSRegisterRequestGenerator.SUMMARY_EVENT_TYPE);
logger.debug(
- "GenericServiceLSRegistrator: " +
- "send registration from hLS to gLS - eventType "+
+ "GenericServiceLSRegistrator: " +
+ "send registration from hLS to gLS - eventType " +
LSRegisterRequestGenerator.SUMMARY_EVENT_TYPE);
}
-
- if (serviceContent!=null) {
- String[] metadata = serviceContent.getServiceContent();
- lsRegisterGenerator.setMetadataElements(metadata);
- } else {
- //String[] metadata = new String[1];
- //metadata[0] = "<nmwg:metadata id=\"empty\" />";
- lsRegisterGenerator.setMetadataElements(new
String[0]);
- }
-
+
+ if (serviceContent != null) {
+ String[] metadata = serviceContent.getServiceContent();
+ lsRegisterGenerator.setMetadataElements(metadata);
+ } else {
+ //String[] metadata = new String[1];
+ //metadata[0] = "<nmwg:metadata id=\"empty\" />";
+ lsRegisterGenerator.setMetadataElements(new String[0]);
+ }
+
Message message = lsRegisterGenerator.generateRequestMessage();
return message;
}
- public ServiceContent getServiceContent() {
+ public ServiceContent getServiceContent()
+ {
return serviceContent;
}
- public void setServiceContent(ServiceContent serviceContent) {
+ public void setServiceContent(ServiceContent serviceContent)
+ {
this.serviceContent = serviceContent;
}
- public ServiceDescription getServiceDescription() {
+ public ServiceDescription getServiceDescription()
+ {
return serviceDescription;
}
- public void setServiceDescription(ServiceDescription serviceDescription)
{
+ public void setServiceDescription(ServiceDescription serviceDescription)
+ {
this.serviceDescription = serviceDescription;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationContextServiceContent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationContextServiceContent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationContextServiceContent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -12,49 +12,54 @@
*
* @author Michael.Bischoff
*/
-public class InformationContextServiceContent implements ServiceContent {
+public class InformationContextServiceContent implements ServiceContent
+{
- protected final LoggerComponent logger;
- protected PerfsonarContextComponent context;
-
- public static final String REGISTRATION_DATA =
"service.ls.registration_data";
-
- /**
- * Creates a InformationContextServiceContent
- * @throws PerfSONARException if it's unable to get a loggerComponent
- */
- public InformationContextServiceContent() throws PerfSONARException {
- logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
- this.context = getContext();
- }
-
- protected PerfsonarContextComponent getContext() throws
PerfSONARException {
- if(context==null) {
- context = (PerfsonarContextComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONTEXT);
- }
- return context;
- }
+ protected final LoggerComponent logger;
+ protected PerfsonarContextComponent context;
- @Override
- public String[] getServiceContent() throws PerfSONARException {
- context = getContext();
- if(context==null) {
- logger.warn("context is null");
- throw new PerfSONARException("We need a
context(AuxiliaryComponent)");
- }
-
- String[] data = null;
- try {
- data = (String[]) context.get(REGISTRATION_DATA);
- } catch(ClassCastException e) {
-
logger.error("InformationContextServiceContent.getServiceContent: Wrong type
of "+REGISTRATION_DATA+" in context!");
- }
- if(data==null) {
-
logger.warn("InformationContextServiceContent.getServiceContent: No value for
" + REGISTRATION_DATA + " on the context.");
- return new String[] { "" };
- }
-
- return data;
- }
+ public static final String REGISTRATION_DATA =
"service.ls.registration_data";
+ /**
+ * Creates a InformationContextServiceContent
+ *
+ * @throws PerfSONARException if it's unable to get a loggerComponent
+ */
+ public InformationContextServiceContent() throws PerfSONARException
+ {
+ logger = (LoggerComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.LOGGER);
+ this.context = getContext();
+ }
+
+ protected PerfsonarContextComponent getContext() throws
PerfSONARException
+ {
+ if (context == null) {
+ context = (PerfsonarContextComponent)
AuxiliaryComponentManager.getInstance().getComponent(ComponentNames.CONTEXT);
+ }
+ return context;
+ }
+
+ @Override
+ public String[] getServiceContent() throws PerfSONARException
+ {
+ context = getContext();
+ if (context == null) {
+ logger.warn("context is null");
+ throw new PerfSONARException("We need a
context(AuxiliaryComponent)");
+ }
+
+ String[] data = null;
+ try {
+ data = (String[]) context.get(REGISTRATION_DATA);
+ } catch (ClassCastException e) {
+
logger.error("InformationContextServiceContent.getServiceContent: Wrong type
of " + REGISTRATION_DATA + " in context!");
+ }
+ if (data == null) {
+ logger.warn("InformationContextServiceContent.getServiceContent:
No value for " + REGISTRATION_DATA + " on the context.");
+ return new String[]{""};
+ }
+
+ return data;
+ }
+
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationExistDbXmlrpcServiceContent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationExistDbXmlrpcServiceContent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationExistDbXmlrpcServiceContent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -9,9 +9,9 @@
/**
* Get metadatas from eXist xml database
- *
*/
-public class InformationExistDbXmlrpcServiceContent implements
ServiceContent {
+public class InformationExistDbXmlrpcServiceContent implements ServiceContent
+{
// ----------------------------------------------------- Constants
@@ -19,13 +19,14 @@
private static final String GET_METADATA_XPATH =
"declare namespace nmwg='http://ggf.org/ns/nmwg/base/2.0/'; \n"
- + "/nmwg:store/nmwg:metadata";
+ + "/nmwg:store/nmwg:metadata";
// --------------------------------------------------- Constructor
- public InformationExistDbXmlrpcServiceContent() {
+ public InformationExistDbXmlrpcServiceContent()
+ {
}
@@ -38,35 +39,36 @@
* @return array of Strings
*/
@Override
- public String[] getServiceContent() throws PerfSONARException {
+ public String[] getServiceContent() throws PerfSONARException
+ {
XmlDbDataRepository dataRepository =
ExistDbFactory.getDataRepositoryByProperties(
- ExistDbFactory.EXIST_XMLRPC,
- "component.ma.xmldb.db_uri",
- "component.ma.xmldb.db_username",
- "component.ma.xmldb.db_password");
+ ExistDbFactory.EXIST_XMLRPC,
+ "component.ma.xmldb.db_uri",
+ "component.ma.xmldb.db_username",
+ "component.ma.xmldb.db_password");
XmlDbStorageManager storageManager =
ExistDbFactory.getXMLStorageManager(
- ExistDbFactory.EXIST_XMLRPC, dataRepository);
+ ExistDbFactory.EXIST_XMLRPC, dataRepository);
storageManager.setResultType(
- XmlDbStorageManager.STRING_ARRAY_TYPE);
+ XmlDbStorageManager.STRING_ARRAY_TYPE);
- String[] results =
(String[])storageManager.fetch(GET_METADATA_XPATH);
+ String[] results = (String[])
storageManager.fetch(GET_METADATA_XPATH);
if (results == null)
throw new PerfSONARException(
- "warning.ls.register",
- "InformationExistDbXmlrpcServiceContent.fetch: "
+ "warning.ls.register",
+ "InformationExistDbXmlrpcServiceContent.fetch: "
+ "Fetch method of storage manager returned null");
if (results.length == 0)
throw new PerfSONARException(
- "warning.ls.register",
- "InformationExistDbXmlrpcServiceContent.fetch: "
+ "warning.ls.register",
+ "InformationExistDbXmlrpcServiceContent.fetch: "
+ "No metadata elements in the metadata configuration");
return results;
@@ -74,5 +76,4 @@
}
-
} //InformationExistDbXmlrpcServiceContent
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationXMLFileServiceContent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationXMLFileServiceContent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/InformationXMLFileServiceContent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -8,50 +8,55 @@
* Get metadatas from XML Information File
*
* @author Maciej Glowiak
- *
*/
-public class InformationXMLFileServiceContent implements ServiceContent {
+public class InformationXMLFileServiceContent implements ServiceContent
+{
- // ----------------------------------------------------- Constants
+ // ----------------------------------------------------- Constants
- private static final String GET_METADATA_XPATH =
"/nmwg:store/nmwg:metadata";
+ private static final String GET_METADATA_XPATH =
"/nmwg:store/nmwg:metadata";
- // -------------------------------------------- Instance variables
+ // -------------------------------------------- Instance variables
- private String xmlInformationFilename;
+ private String xmlInformationFilename;
- // --------------------------------------------------- Constructor
+ // --------------------------------------------------- Constructor
- public InformationXMLFileServiceContent(String filename) {
- xmlInformationFilename = filename;
- }
+ public InformationXMLFileServiceContent(String filename)
+ {
+ xmlInformationFilename = filename;
+ }
- // ------------------------------------------------------- Methods
+ // ------------------------------------------------------- Methods
- /**
- * Get metadata blocks from RRD information file
- *
- * @return array of Strings
- */
- public String[] getServiceContent(String filename) throws
PerfSONARException {
- XmlFileDataRepository dr = new
XmlFileDataRepository(filename);
- XmlFileStorageManager sm = new XmlFileStorageManager();
- sm.initStorage(dr);
- String[] results = (String[]) sm.fetch(GET_METADATA_XPATH);
- return results;
- }
+ /**
+ * Get metadata blocks from RRD information file
+ *
+ * @return array of Strings
+ */
+ public String[] getServiceContent(String filename) throws
PerfSONARException
+ {
+ XmlFileDataRepository dr = new XmlFileDataRepository(filename);
+ XmlFileStorageManager sm = new XmlFileStorageManager();
+ sm.initStorage(dr);
+ String[] results = (String[]) sm.fetch(GET_METADATA_XPATH);
+ return results;
+ }
- @Override
- public String[] getServiceContent() throws PerfSONARException {
- return getServiceContent(xmlInformationFilename);
- }
+ @Override
+ public String[] getServiceContent() throws PerfSONARException
+ {
+ return getServiceContent(xmlInformationFilename);
+ }
- public String getXmlInformationFilename() {
- return xmlInformationFilename;
- }
+ public String getXmlInformationFilename()
+ {
+ return xmlInformationFilename;
+ }
- public void setXmlInformationFilename(String xmlInformationFilename) {
- this.xmlInformationFilename = xmlInformationFilename;
- }
+ public void setXmlInformationFilename(String xmlInformationFilename)
+ {
+ this.xmlInformationFilename = xmlInformationFilename;
+ }
} // InformationXMLFileServiceContent
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSListAddresses.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSListAddresses.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSListAddresses.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -13,19 +13,21 @@
* This class populates list of LS urls to register to
*
* @author Maciej Glowiak
- *
*/
-public class LSListAddresses {
+public class LSListAddresses
+{
/**
* Populates urls collection with multiple urls from list separated by
comma sign , )
+ *
* @param urls
* @param multiUrlString
* @throws MalformedURLException
* @throws IOException
*/
- public void addFromString(Collection<String> urls, String
multiUrlString) {
+ public void addFromString(Collection<String> urls, String multiUrlString)
+ {
try {
String[] u = multiUrlString.split(",");
for (String urlString : u) {
@@ -33,18 +35,21 @@
if (!s.isEmpty())
urls.add(s);
}
- } catch (RuntimeException ex) { }
+ } catch (RuntimeException ex) {
+ }
}
/**
* Populates urls collection with multiple remote resources (list in
multiUrlString separated by comma sign , )
+ *
* @param urls
* @param multiUrlString
* @throws MalformedURLException
* @throws IOException
*/
- public void addFromMultipleURLs(Collection<String> urls, String
multiUrlString) {
+ public void addFromMultipleURLs(Collection<String> urls, String
multiUrlString)
+ {
try {
String[] u = multiUrlString.split(",");
for (String urlString : u) {
@@ -54,23 +59,26 @@
addFromURL(urls, s);
} catch (Exception ex) { /* just omit */ }
}
- } catch (RuntimeException rex) {}
+ } catch (RuntimeException rex) {
+ }
}
/**
* Populates urls collection with urls/lines downloaded from urlString
+ *
* @param urls
* @param urlString
* @throws MalformedURLException
* @throws IOException
*/
- public void addFromURL(Collection<String> urls, String urlString) throws
MalformedURLException,IOException {
+ public void addFromURL(Collection<String> urls, String urlString) throws
MalformedURLException, IOException
+ {
URL rootHintsUrl = new URL(urlString);
URLConnection rhc = rootHintsUrl.openConnection();
BufferedReader in = new BufferedReader(
- new InputStreamReader(
- rhc.getInputStream()));
+ new InputStreamReader(
+ rhc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
try {
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSRegistrationComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSRegistrationComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSRegistrationComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -21,10 +21,10 @@
*
* @author Maciej Glowiak (main author)
* @author romradz (contributor)
- *
*/
public class LSRegistrationComponent implements SchedulerAction,
- AuxiliaryComponent {
+ AuxiliaryComponent
+{
// ----------------------------------------------------- constants
@@ -41,7 +41,8 @@
*/
private static final String SERVICE_CONTENT_TYPE =
"service.ls.service_content_type";
- private enum ContentType {
+ private enum ContentType
+ {
EMPTY(null),
FILE("file"),
XMLDB("xmldb"),
@@ -51,13 +52,15 @@
private String name;
- ContentType(String name) {
+ ContentType(String name)
+ {
this.name = name;
}
- static ContentType getByName(String name) {
+ static ContentType getByName(String name)
+ {
if (name == null) {
return EMPTY;
@@ -90,22 +93,23 @@
// ---------------------------------- constructors
- public LSRegistrationComponent() throws PerfSONARException {
+ public LSRegistrationComponent() throws PerfSONARException
+ {
try {
this.logger = (LoggerComponent) AuxiliaryComponentManager
- .getInstance().getComponent(ComponentNames.LOGGER);
+ .getInstance().getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException("error.common.no_logger",
- "LSRegistrationComponent.initComponent: Cannot get
logger component");
+ "LSRegistrationComponent.initComponent: Cannot get logger
component");
}
try {
this.configuration = (ConfigurationComponent)
AuxiliaryComponentManager
- .getInstance().getComponent(ComponentNames.CONFIG);
+ .getInstance().getComponent(ComponentNames.CONFIG);
} catch (PerfSONARException e) {
throw new PerfSONARException("error.common.no_configuration",
- "LSRegistrationComponent.initComponent: Cannot get
config component");
+ "LSRegistrationComponent.initComponent: Cannot get config
component");
}
}
@@ -117,39 +121,40 @@
* Scheduler action
*/
@Override
- public void runAction() {
+ public void runAction()
+ {
try {
ContentType type = ContentType
- .getByName(getServiceContentPropery());
+ .getByName(getServiceContentPropery());
ServiceContent content = null;
switch (type) {
- case EMPTY:
- case FILE: {
- content = getXMLFileContent();
- }
- break;
+ case EMPTY:
+ case FILE: {
+ content = getXMLFileContent();
+ }
+ break;
- case XMLDB: {
- content = getXMLDBContent();
- }
- break;
+ case XMLDB: {
+ content = getXMLDBContent();
+ }
+ break;
- case CONTEXT: {
- content = getContextContent();
- }
- break;
+ case CONTEXT: {
+ content = getContextContent();
+ }
+ break;
- case LSSUMMARY: {
- content = getLSSummaryContent();
- }
- break;
+ case LSSUMMARY: {
+ content = getLSSummaryContent();
}
+ break;
+ }
logger.debug("LSRegistrationComponent.runAction: register
ServiceContent = " + content);
ServiceLSRegistrator registrator = new
GenericServiceLSRegistrator(
- new PropertiesServiceDescription(), content);
+ new PropertiesServiceDescription(), content);
//initialize Registration
registrator.initRegistrator();
@@ -160,7 +165,7 @@
String rootHints = getProperty("service.r.root_hints");
//if no LS to register with throw exception
- if ((localLsUrls == null)&&(rootHints == null))
+ if ((localLsUrls == null) && (rootHints == null))
throw new
PerfSONARException("error.lsregistration.no_ls_url");
logger.debug("LSRegistrationComponent.runAction: register to
gLS-es");
@@ -171,23 +176,23 @@
if (localLsUrls != null) {
ArrayList<String> urls = new ArrayList<String>();
list.addFromString(urls, localLsUrls);
- int i = 1;
- for (String url : urls) {
- logger.debug("LSRegistrationComponent send to [" + i
+ "/" + urls.size() + "] url: [" + url + "]: ");
- registerToLS(registrator, url);
- i++;
- }
+ int i = 1;
+ for (String url : urls) {
+ logger.debug("LSRegistrationComponent send to [" + i +
"/" + urls.size() + "] url: [" + url + "]: ");
+ registerToLS(registrator, url);
+ i++;
+ }
}
if (rootHints != null) {
- //register to one of LSes from root.hints (
service.r.root_hints prop.)
+ //register to one of LSes from root.hints (
service.r.root_hints prop.)
ArrayList<String> remoteUrls = new ArrayList<String>();
list.addFromMultipleURLs(remoteUrls, rootHints);
- for (String url : remoteUrls) {
- logger.debug("LSRegistrationComponent send to gLS url
from roots.hints: [" + url + "]: ");
- if (registerToLS(registrator, url) == true)
- break; //break after first success
- }
+ for (String url : remoteUrls) {
+ logger.debug("LSRegistrationComponent send to gLS url
from roots.hints: [" + url + "]: ");
+ if (registerToLS(registrator, url) == true)
+ break; //break after first success
+ }
}
} catch (PerfSONARException e) {
logger.error("LSRegistrationComponent.runAction: Error while
registration: " + e.getMessage());
@@ -195,17 +200,19 @@
}
- private String getProperty(String key) {
- try {
- return configuration.getProperty(key);
- } catch (PerfSONARException e) {
- logger.warn("Property with key('"+key+"') not found");
- return null;
- }
- }
+ private String getProperty(String key)
+ {
+ try {
+ return configuration.getProperty(key);
+ } catch (PerfSONARException e) {
+ logger.warn("Property with key('" + key + "') not found");
+ return null;
+ }
+ }
- protected boolean registerToLS(ServiceLSRegistrator registrator,
String url) {
+ protected boolean registerToLS(ServiceLSRegistrator registrator, String
url)
+ {
try {
@@ -215,37 +222,37 @@
responseMessages.add(rspMsg);
return true;
- } catch (Exception ex) {
- String errorMsg = "LSRegistrationComponent error sending to
[" + url + "]: " + ex.getClass().getName() + "->"+ ex.getMessage();
-
- StackTraceElement[] stack = ex.getStackTrace();
- if(stack!=null && stack.length > 0) {
- errorMsg += " at " + stack[0].getClassName() + ":" +
stack[0].getLineNumber();
- }
-
- if(ex.getCause() != null) {
- errorMsg += " underlaying cause: " +
ex.getCause().getMessage();
- }
- logger.error(errorMsg);
+ } catch (Exception ex) {
+ String errorMsg = "LSRegistrationComponent error sending to [" +
url + "]: " + ex.getClass().getName() + "->" + ex.getMessage();
+
+ StackTraceElement[] stack = ex.getStackTrace();
+ if (stack != null && stack.length > 0) {
+ errorMsg += " at " + stack[0].getClassName() + ":" +
stack[0].getLineNumber();
+ }
+
+ if (ex.getCause() != null) {
+ errorMsg += " underlaying cause: " +
ex.getCause().getMessage();
+ }
+ logger.error(errorMsg);
}
return false;
}
+ private ServiceContent getLSSummaryContent()
+ {
-
- private ServiceContent getLSSummaryContent() {
-
return new LSSummaryServiceContent();
}
- protected ServiceContent getXMLFileContent() throws PerfSONARException {
+ protected ServiceContent getXMLFileContent() throws PerfSONARException
+ {
String registrationFile = configuration
- .getProperty(LSRegistrationComponent.REGISTRATION_FILE);
+ .getProperty(LSRegistrationComponent.REGISTRATION_FILE);
if (registrationFile != null && !registrationFile.isEmpty()) {
return new InformationXMLFileServiceContent(registrationFile);
@@ -254,24 +261,27 @@
}
- protected ServiceContent getXMLDBContent() throws PerfSONARException {
+ protected ServiceContent getXMLDBContent() throws PerfSONARException
+ {
return new InformationExistDbXmlrpcServiceContent();
}
- protected ServiceContent getContextContent() throws PerfSONARException {
+ protected ServiceContent getContextContent() throws PerfSONARException
+ {
return new InformationContextServiceContent();
}
- private String getServiceContentPropery() {
+ private String getServiceContentPropery()
+ {
String contentType = null;
try {
contentType = configuration
-
.getProperty(LSRegistrationComponent.SERVICE_CONTENT_TYPE);
+ .getProperty(LSRegistrationComponent.SERVICE_CONTENT_TYPE);
} catch (PerfSONARException e) {
logger.debug("LSRegistrationComponent:
service.ls.service_content_type could not be read.");
}
@@ -282,7 +292,8 @@
}
- public Message getResponseMessage() {
+ public Message getResponseMessage()
+ {
return responseMessage;
}
@@ -293,7 +304,8 @@
* Takes interval in seconds from config file
*/
@Override
- public void initComponent() throws PerfSONARException {
+ public void initComponent() throws PerfSONARException
+ {
// Get configuration
// get interval - parameter "component.CName.interval"
@@ -302,7 +314,7 @@
try {
//get interval in seconds
String intervalVal = configuration.getProperty("component."
- + componentName + ".interval");
+ + componentName + ".interval");
interval = Integer.parseInt(intervalVal) * 1000; //multiply to
have it in ms
} catch (RuntimeException e) {
// possibly not an integer - keep default interval
@@ -314,34 +326,34 @@
if (interval < LSRegistrationComponent.MINIMAL_RUN_INTERVAL) {
logger.debug("LSRegistrationComponent.initComponent: parameter
RUN_INTERVAL="
- + interval+" smaller than
MINIMAL="+LSRegistrationComponent.MINIMAL_RUN_INTERVAL);
+ + interval + " smaller than MINIMAL=" +
LSRegistrationComponent.MINIMAL_RUN_INTERVAL);
interval = LSRegistrationComponent.MINIMAL_RUN_INTERVAL;
}
logger.debug("LSRegistrationComponent.initComponent:
LSRegistrationComponent: parameter RUN_INTERVAL = "
- + interval);
+ + interval);
// get scheduler - parameter "component.CName.scheduler_component"
try {
String schedulerVal = configuration.getProperty("component."
- + componentName + ".scheduler_component");
+ + componentName + ".scheduler_component");
logger.debug("LSRegistrationComponent.initComponent:
LSRegistrationComponent: parameter SCHEDULER = "
- + schedulerVal);
+ + schedulerVal);
scheduler = (Scheduler) AuxiliaryComponentManager.getInstance()
- .getComponent(schedulerVal);
+ .getComponent(schedulerVal);
} catch (PerfSONARException e) {
throw new PerfSONARException("error.rrdma.no_scheduler",
- "LSRegistrationComponent.initComponent: "
- + "LSCleanupLoader: no [component." +
componentName
- + ".scheduler_component] parameter. "
- + e.getMessage());
+ "LSRegistrationComponent.initComponent: "
+ + "LSCleanupLoader: no [component." + componentName
+ + ".scheduler_component] parameter. "
+ + e.getMessage());
}
if (scheduler == null) {
throw new PerfSONARException(
- "error.rrdma.no_scheduler",
- "LSRegistrationComponent.initComponent: No scheduler
component in AuxiliaryComponentManager");
+ "error.rrdma.no_scheduler",
+ "LSRegistrationComponent.initComponent: No scheduler
component in AuxiliaryComponentManager");
}
// add cleanup action to scheduler
scheduler.addSchedulerTask(interval, this);
@@ -349,14 +361,16 @@
@Override
- public String getComponentName() {
+ public String getComponentName()
+ {
return componentName;
}
@Override
- public void setComponentName(String name) {
+ public void setComponentName(String name)
+ {
componentName = name;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSSummaryServiceContent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSSummaryServiceContent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/LSSummaryServiceContent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -22,10 +22,11 @@
/**
* This class get data and summarize
+ *
* @author Maciej Glowiak
- *
*/
-public class LSSummaryServiceContent implements ServiceContent {
+public class LSSummaryServiceContent implements ServiceContent
+{
private static int counter = 0;
@@ -35,7 +36,7 @@
private static final int KEYWORD = 400;
private static final String XMLNS_DEF =
- " xmlns:nmwg=\"http://ggf.org/ns/nmwg/base/2.0/\" "+
+ " xmlns:nmwg=\"http://ggf.org/ns/nmwg/base/2.0/\" " +
"
xmlns:nmtb=\"http://ogf.org/schema/network/topology/base/20070828/\" " +
"
xmlns:nmtl3=\"http://ogf.org/schema/network/topology/l3/20070828/\" " +
"
xmlns:summary=\"http://ggf.org/ns/nmwg/tools/org/perfsonar/service/lookup/summarization/2.0/\"
";
@@ -58,24 +59,28 @@
// ----------------------------------------------------------------------
- public LSSummaryServiceContent() {
+ public LSSummaryServiceContent()
+ {
try {
this.logger = (LoggerComponent) AuxiliaryComponentManager
- .getInstance().getComponent(ComponentNames.LOGGER);
- } catch (PerfSONARException e) { }
+ .getInstance().getComponent(ComponentNames.LOGGER);
+ } catch (PerfSONARException e) {
+ }
try {
this.config = (ConfigurationComponent) AuxiliaryComponentManager
- .getInstance().getComponent(ComponentNames.CONFIG);
- } catch (PerfSONARException e) { }
+ .getInstance().getComponent(ComponentNames.CONFIG);
+ } catch (PerfSONARException e) {
+ }
}
/**
* Translate to HTTP uri if necessary
*/
- private String getHTTPUri(String uri) {
+ private String getHTTPUri(String uri)
+ {
if (uri.startsWith("xmldb:exist://")) {
uri = uri.replace("xmldb:exist://", "http://");
@@ -87,7 +92,8 @@
/**
* Translate to HTTP uri if necessary
*/
- private String getXMLRPCUri(String uri) {
+ private String getXMLRPCUri(String uri)
+ {
if (uri.startsWith("http://")) {
uri = uri.replace("http://", "xmldb:exist://");
@@ -98,27 +104,29 @@
/**
* Initializes Database access (from configuration)
+ *
* @throws PerfSONARException
*/
- private void init() {
+ private void init()
+ {
//wait 60 sec; to avoid first failed registration (when service is
//starting)
long time = 60000;
- if (LSSummaryServiceContent.counter==0)
+ if (LSSummaryServiceContent.counter == 0)
- logger.debug("LSSummaryServiceContent: Wait ["+
- (time/1000)+
- "] seconds until other components are initialized...");
+ logger.debug("LSSummaryServiceContent: Wait [" +
+ (time / 1000) +
+ "] seconds until other components are initialized...");
- synchronized (this) {
- try {
- Thread.sleep(60000);
- } catch (InterruptedException e) {
+ synchronized (this) {
+ try {
+ Thread.sleep(60000);
+ } catch (InterruptedException e) {
- }
}
+ }
LSSummaryServiceContent.counter++;
@@ -127,55 +135,55 @@
try {
//get data from configuration
switch (connectionType) {
- case HTTP:
- logger.debug("Connection type for
LSSUmmaryServiceContent is HTTP");
- dbCollection =
getHTTPUri(config.getProperty("service.ls.db_uri"));
- break;
- case XMLRPC:
- logger.debug("Connection type for
LSSUmmaryServiceContent is XMLRPC");
- dbCollection =
getXMLRPCUri(config.getProperty("service.ls.db_uri"));
- break;
+ case HTTP:
+ logger.debug("Connection type for LSSUmmaryServiceContent is
HTTP");
+ dbCollection =
getHTTPUri(config.getProperty("service.ls.db_uri"));
+ break;
+ case XMLRPC:
+ logger.debug("Connection type for LSSUmmaryServiceContent is
XMLRPC");
+ dbCollection =
getXMLRPCUri(config.getProperty("service.ls.db_uri"));
+ break;
}
- dbUsername = config.getProperty("service.ls.db_username");
- dbPassword = config.getProperty("service.ls.db_password");
+ dbUsername = config.getProperty("service.ls.db_username");
+ dbPassword = config.getProperty("service.ls.db_password");
if (dbCollection == null || dbUsername == null || dbPassword ==
null)
throw new PerfSONARException();
logger.debug(
- "LSSummaryServiceContent: database access details: "+
- "(url="+dbCollection+", username="+dbUsername+",
"+dbPassword+")");
+ "LSSummaryServiceContent: database access details: " +
+ "(url=" + dbCollection + ", username=" + dbUsername + ",
" + dbPassword + ")");
switch (connectionType) {
- case HTTP:
- ExistDbHttpXmlDataRepository httpDataRepository =
+ case HTTP:
+ ExistDbHttpXmlDataRepository httpDataRepository =
new ExistDbHttpXmlDataRepository(dbCollection,
dbUsername, dbPassword);
- //initialize storage manager
- storage = new ExistDbHttpXmlStorageManager();
-
storage.setResultType(ExistDbHttpXmlStorageManager.STRING_ARRAY_TYPE);
- storage.initStorage(httpDataRepository);
- break;
- case XMLRPC:
- //initialize data repository object - XML RPC
- ExistDbXmlrpcXmlDataRepository xmlrpcDataRepository
- = new ExistDbXmlrpcXmlDataRepository(
- dbCollection, dbUsername, dbPassword);
- storage = (ExistDbGenericStorageManager)
- ExistDbFactory.getXMLStorageManager(
- ExistDbFactory.EXIST_XMLRPC,
xmlrpcDataRepository);
-
storage.setResultType(XmlDbStorageManager.STRING_ARRAY_TYPE);
+ //initialize storage manager
+ storage = new ExistDbHttpXmlStorageManager();
+
storage.setResultType(ExistDbHttpXmlStorageManager.STRING_ARRAY_TYPE);
+ storage.initStorage(httpDataRepository);
+ break;
+ case XMLRPC:
+ //initialize data repository object - XML RPC
+ ExistDbXmlrpcXmlDataRepository xmlrpcDataRepository
+ = new ExistDbXmlrpcXmlDataRepository(
+ dbCollection, dbUsername, dbPassword);
+ storage = (ExistDbGenericStorageManager)
+ ExistDbFactory.getXMLStorageManager(
+ ExistDbFactory.EXIST_XMLRPC, xmlrpcDataRepository);
+ storage.setResultType(XmlDbStorageManager.STRING_ARRAY_TYPE);
- logger.debug("XML RPC initialized");
+ logger.debug("XML RPC initialized");
- break;
+ break;
}
logger.debug("LSSummaryServiceContent: storage initiated");
} catch (PerfSONARException e) {
- logger.error("LSSummaryServiceContent: Wrong XML DB settings
(url="+
- dbCollection+", username="+dbUsername+", "+dbPassword+
- ") or cannot instantiate StorageManager");
+ logger.error("LSSummaryServiceContent: Wrong XML DB settings
(url=" +
+ dbCollection + ", username=" + dbUsername + ", " +
dbPassword +
+ ") or cannot instantiate StorageManager");
}
}
@@ -185,7 +193,8 @@
* Method that is executed by Registration component, MAIN method of the
class
*/
@Override
- public String[] getServiceContent() throws PerfSONARException {
+ public String[] getServiceContent() throws PerfSONARException
+ {
//initialize
logger.debug("LSSummaryServiceConetent: init");
@@ -207,7 +216,7 @@
//boolean doIPSummarization =
config.getProperty("service.ls.do_ip_summarization");
//work on the same data - summarize and store in "summaries"
structure
- for (ServiceSummary s :summaries.values()) {
+ for (ServiceSummary s : summaries.values()) {
//summarize IPs
logger.debug("Summarize domains");
@@ -229,9 +238,9 @@
String[] resultArray = new String[summaries.size()];
- int i=0;
+ int i = 0;
//for every single summary get XML
- for (ServiceSummary s :summaries.values()) {
+ for (ServiceSummary s : summaries.values()) {
StringBuilder sb = new StringBuilder();
@@ -243,9 +252,9 @@
for (String ip : s.ipAddresses) {
//split results - ip/netmask or assume 32 as netmask if
wrong format
- String[] ipvals = ip.split("/",2);
- if(ipvals .length != 2) {
- ipvals = new String[] {ip, "32"};
+ String[] ipvals = ip.split("/", 2);
+ if (ipvals.length != 2) {
+ ipvals = new String[]{ip, "32"};
}
sb.append(" <nmtl3:network>\n");
@@ -275,7 +284,7 @@
//to be printed
int paramsSum = s.eventTypes.size() + s.keywords.size();
//if it is at least one, put it.
- if (paramsSum>0) {
+ if (paramsSum > 0) {
sb.append(" <summary:parameters id=\"summmary.md.1\">\n");
for (String evt : s.eventTypes) {
sb.append(" <nmwg:parameter name=\"eventType\"
value=\"").append(evt).append("\" />\n");
@@ -292,7 +301,7 @@
//convert StringBuffer to String
String res = sb.toString();
- logger.debug("LSSummaryServicecontent: Summary data is:\n"+res);
+ logger.debug("LSSummaryServicecontent: Summary data is:\n" +
res);
//store in array
resultArray[i] = res;
@@ -306,9 +315,11 @@
/**
* Get topology data and eventTypes from all services
* store it in Map<String, ServiceSummary>
+ *
* @return
*/
- private Map<String, ServiceSummary> getAllServicesSummaries() throws
PerfSONARException {
+ private Map<String, ServiceSummary> getAllServicesSummaries() throws
PerfSONARException
+ {
Map<String, ServiceSummary> summaries = new HashMap<String,
ServiceSummary>();
@@ -317,10 +328,19 @@
String[] eventTypeResults = queryEventTypeResults();
String[] keywordResults = queryKeywordResults();
- logger.debug("LSSummaryServiceContent.getAllServicesSummaries: got
summary from database. Number of: " );
- try { logger.debug(" - IP: ["+ipResults.length+"]"); } catch
(Exception ex) {}
- try { logger.debug(" - domains:
["+domainResults.length+"]"); } catch (Exception ex) {}
- try { logger.debug(" - eventvTypes:
["+eventTypeResults.length+"]"); } catch (Exception ex) {}
+ logger.debug("LSSummaryServiceContent.getAllServicesSummaries: got
summary from database. Number of: ");
+ try {
+ logger.debug(" - IP: [" + ipResults.length + "]");
+ } catch (Exception ex) {
+ }
+ try {
+ logger.debug(" - domains: [" + domainResults.length +
"]");
+ } catch (Exception ex) {
+ }
+ try {
+ logger.debug(" - eventvTypes: [" +
eventTypeResults.length + "]");
+ } catch (Exception ex) {
+ }
populateSummary(summaries, ipResults, IP);
populateSummary(summaries, domainResults, DOMAIN);
@@ -335,26 +355,28 @@
/**
* Get subdomains for domain. For example for input string
"www.man.poznan.pl"
* and limit=3 it will return collection of "pl", "poznan.pl" and
"man.poznan.pl"
+ *
* @param domain input domain e.g. "www.man.poznan.pl"
- * @param limit number of subdomains to be returned. Value -1 means "all"
- * @param list collection where results are to be added
+ * @param limit number of subdomains to be returned. Value -1 means
"all"
+ * @param list collection where results are to be added
* @return updated Collection
*/
- public Collection<String> getSubDomains(String domain, int limit,
Collection<String> list) {
+ public Collection<String> getSubDomains(String domain, int limit,
Collection<String> list)
+ {
- if (domain==null) return null;
+ if (domain == null) return null;
int last = domain.length();
- for (int current=last-1; current>=0; current--) {
+ for (int current = last - 1; current >= 0; current--) {
- if (limit==0) break;
+ if (limit == 0) break;
if (domain.charAt(current) == '.') {
- String subdomain = domain.substring(current+1);
+ String subdomain = domain.substring(current + 1);
if (subdomain != null && !subdomain.isEmpty())
list.add(subdomain);
- limit--;
+ limit--;
}
}
return list;
@@ -364,10 +386,12 @@
/**
* Do IPs summarization. Returns new, summarized set of data
* Input data is not changed.
+ *
* @param data
* @return
*/
- private HashSet<String> summarizeIPAddresses(HashSet<String>
ipAddresses) {
+ private HashSet<String> summarizeIPAddresses(HashSet<String> ipAddresses)
+ {
HashSet<String> result;
@@ -375,7 +399,7 @@
result = SummarizeIpAddrs.getSummary(ipAddresses);
} catch (Exception ex) {
logger.error("LSSummaryServiceContent: IP summarization failed.
" +
- "Exception: "+ex+" : "+ex.getMessage());
+ "Exception: " + ex + " : " + ex.getMessage());
result = ipAddresses;
}
return result;
@@ -386,10 +410,12 @@
/**
* Do domains summarization. Returns new, summarized set of data
* Input data is not changed.
+ *
* @param data
* @return
*/
- private HashSet<String> summarizeDomains(HashSet<String> data) {
+ private HashSet<String> summarizeDomains(HashSet<String> data)
+ {
HashSet<String> summarizedData = new HashSet<String>();
for (String s : data) {
@@ -402,21 +428,23 @@
/**
* Extracts data from lines (DB results) and put them into the right
place
* in summaries
+ *
* @param summaries
- * @param lines results from DB
- * @param type type of field to be populated
+ * @param lines results from DB
+ * @param type type of field to be populated
*/
- private void populateSummary(Map<String, ServiceSummary> summaries,
String[] lines, int type) {
+ private void populateSummary(Map<String, ServiceSummary> summaries,
String[] lines, int type)
+ {
//split and store results
for (String line : lines) {
//split result
- String[] params = line.split(",",2);
+ String[] params = line.split(",", 2);
- if(params.length != 2) {
- logger.debug("LSSummaryServiceContent: suppressing line;
invalid format(value='"+line+"')");
- break;
+ if (params.length != 2) {
+ logger.debug("LSSummaryServiceContent: suppressing line;
invalid format(value='" + line + "')");
+ break;
}
String key = params[0];
@@ -425,25 +453,25 @@
//get or create summary for the service
ServiceSummary summary = summaries.get(key);
- if (summary==null) {
+ if (summary == null) {
summary = new ServiceSummary();
summaries.put(key, summary);
}
//fill the right field
switch (type) {
- case IP:
- summary.ipAddresses.add(content);
- break;
- case DOMAIN:
- summary.domains.add(content);
- break;
- case EVENT_TYPE:
- summary.eventTypes.add(content);
- break;
- case KEYWORD:
- summary.keywords.add(content);
- break;
+ case IP:
+ summary.ipAddresses.add(content);
+ break;
+ case DOMAIN:
+ summary.domains.add(content);
+ break;
+ case EVENT_TYPE:
+ summary.eventTypes.add(content);
+ break;
+ case KEYWORD:
+ summary.keywords.add(content);
+ break;
}
}
@@ -453,19 +481,21 @@
/**
* Perform XQuery with storage manager
+ *
* @param xq
* @return
*/
- private String[] xquery(String xq) throws PerfSONARException{
+ private String[] xquery(String xq) throws PerfSONARException
+ {
try {
String[] s = (String[]) storage.fetch(xq);
return s;
} catch (Exception e) {
- logger.error("LSSummaryServiceContent: Cannot perform xquery
["+xq+"]: "+e.getMessage()+"\n"+e.toString());
- if (e instanceof PerfSONARException) throw (PerfSONARException)e;
+ logger.error("LSSummaryServiceContent: Cannot perform xquery ["
+ xq + "]: " + e.getMessage() + "\n" + e.toString());
+ if (e instanceof PerfSONARException) throw (PerfSONARException)
e;
else
- throw new
PerfSONARException("error.lsregistration.db_error", "Cannot perform xquery
["+xq+"] : "+e.getLocalizedMessage());
+ throw new
PerfSONARException("error.lsregistration.db_error", "Cannot perform xquery ["
+ xq + "] : " + e.getLocalizedMessage());
}
@@ -473,77 +503,85 @@
/**
* Return set of IP addresses used by services
+ *
* @return
*/
- private String[] queryIpResults() throws PerfSONARException {
+ private String[] queryIpResults() throws PerfSONARException
+ {
String xq =
- " declare namespace nmwg=\"http://ggf.org/ns/nmwg/base/2.0/\"; \n"+
- " for $d in
/nmwg:store[@type='LSStore']/nmwg:data
\n"+
- " let $metaIdRef := data($d/@metadataIdRef) \n"+
- " for $val in $d/nmwg:metadata/*:subject//*:ifAddress/text() \n"+
- " return if (empty($val)) then $val else concat($metaIdRef,',',$val)
\n";
+ " declare namespace nmwg=\"http://ggf.org/ns/nmwg/base/2.0/\";
\n" +
+ " for $d in
/nmwg:store[@type='LSStore']/nmwg:data
\n" +
+ " let $metaIdRef := data($d/@metadataIdRef) \n" +
+ " for $val in
$d/nmwg:metadata/*:subject//*:ifAddress/text() \n" +
+ " return if (empty($val)) then $val else
concat($metaIdRef,',',$val) \n";
return xquery(xq);
}
/**
* Return set of domains used by services
+ *
* @return
*/
- private String[] queryDomainResults() throws PerfSONARException {
+ private String[] queryDomainResults() throws PerfSONARException
+ {
String xq =
- " declare namespace nmwg=\"http://ggf.org/ns/nmwg/base/2.0/\";
\n"+
- " for $d in
/nmwg:store[@type='LSStore']/nmwg:data
\n"+
- " let $metaIdRef := data($d/@metadataIdRef) \n"+
- " for $val in $d/nmwg:metadata/*:subject//*:hostName/text()
\n"+
- " return if (empty($val)) then $val else
concat($metaIdRef,',',$val) \n";
+ " declare namespace nmwg=\"http://ggf.org/ns/nmwg/base/2.0/\";
\n" +
+ " for $d in
/nmwg:store[@type='LSStore']/nmwg:data
\n" +
+ " let $metaIdRef := data($d/@metadataIdRef) \n" +
+ " for $val in
$d/nmwg:metadata/*:subject//*:hostName/text() \n" +
+ " return if (empty($val)) then $val else
concat($metaIdRef,',',$val) \n";
return xquery(xq);
}
/**
* Return set of eventTypes used by services
+ *
* @return
*/
- private String[] queryEventTypeResults() throws PerfSONARException {
+ private String[] queryEventTypeResults() throws PerfSONARException
+ {
String xq =
- " declare namespace nmwg='http://ggf.org/ns/nmwg/base/2.0/'; \n"+
- " declare namespace
nmwgt='http://ggf.org/ns/nmwg/topology/2.0/';\n"+
- " for $d in
/nmwg:store[@type='LSStore']/nmwg:data
\n"+
- " let $metaIdRef := data($d/@metadataIdRef) \n"+
- " for $e in $d/nmwg:metadata/nmwg:eventType \n"+
- " let $val := $e/text() \n"+
- " return concat($metaIdRef,',',$val)\n";
+ " declare namespace nmwg='http://ggf.org/ns/nmwg/base/2.0/'; \n"
+
+ " declare namespace
nmwgt='http://ggf.org/ns/nmwg/topology/2.0/';\n" +
+ " for $d in
/nmwg:store[@type='LSStore']/nmwg:data
\n" +
+ " let $metaIdRef := data($d/@metadataIdRef) \n" +
+ " for $e in $d/nmwg:metadata/nmwg:eventType \n" +
+ " let $val := $e/text() \n" +
+ " return concat($metaIdRef,',',$val)\n";
return xquery(xq);
}
-
/**
* Return set of keywords
* Takes either //nmwg:parameter/@value or //nmwg:parameter/text()
+ *
* @return
*/
- private String[] queryKeywordResults() throws PerfSONARException {
+ private String[] queryKeywordResults() throws PerfSONARException
+ {
String xq =
- " declare namespace nmwg='http://ggf.org/ns/nmwg/base/2.0/';
"+
- " declare namespace
nmwgt='http://ggf.org/ns/nmwg/topology/2.0/'; "+
- " for $d in
/nmwg:store[@type='LSStore']/nmwg:data
"+
- " for $p in
$d/nmwg:metadata/*:parameters/nmwg:parameter[@name='keyword']
"+
- " let $val1 := $p/text() "+
- " let $val2 :=$p/@value "+
- " let $metaIdRef := data($d/@metadataIdRef) "+
- " return "+
- " if (empty($val1)) then
concat($metaIdRef,',',data($val2)) "+
- " else concat($metaIdRef,',', $val1)";
+ " declare namespace nmwg='http://ggf.org/ns/nmwg/base/2.0/'; " +
+ " declare namespace
nmwgt='http://ggf.org/ns/nmwg/topology/2.0/'; " +
+ " for $d in
/nmwg:store[@type='LSStore']/nmwg:data
" +
+ " for $p in
$d/nmwg:metadata/*:parameters/nmwg:parameter[@name='keyword']
" +
+ " let $val1 := $p/text() " +
+ " let $val2 :=$p/@value " +
+ " let $metaIdRef := data($d/@metadataIdRef) " +
+ " return " +
+ " if (empty($val1)) then
concat($metaIdRef,',',data($val2)) " +
+ " else concat($metaIdRef,',', $val1)";
return xquery(xq);
}
- private void showSummary(Map<String, ServiceSummary> summaries) {
+ private void showSummary(Map<String, ServiceSummary> summaries)
+ {
for (Entry<String, ServiceSummary> e : summaries.entrySet()) {
logger.debug("\n==== " + e.getKey() + " ====\n");
logger.debug(e.getValue().toString());
@@ -556,40 +594,42 @@
/**
* Contains summary from a single service
+ *
* @author Maciej Glowiak
- *
*/
- class ServiceSummary {
+ class ServiceSummary
+ {
public HashSet<String> eventTypes = new HashSet<String>();
- public HashSet<String> domains = new HashSet<String>();
+ public HashSet<String> domains = new HashSet<String>();
public HashSet<String> ipAddresses = new HashSet<String>();
public HashSet<String> keywords = new HashSet<String>();
- public String toString() {
+ public String toString()
+ {
StringBuilder sb = new StringBuilder();
sb.append("1. eventTypes:\n");
- for (String s:eventTypes) {
+ for (String s : eventTypes) {
sb.append(" -- ");
sb.append(s);
sb.append("\n");
}
sb.append("2. domains:\n");
- for (String s:domains) {
+ for (String s : domains) {
sb.append(" -- ");
sb.append(s);
sb.append("\n");
}
sb.append("3. IPs:\n");
- for (String s:ipAddresses) {
+ for (String s : ipAddresses) {
sb.append(" -- ");
sb.append(s);
sb.append("\n");
}
sb.append("4. Keywords:\n");
- for (String s:keywords) {
+ for (String s : keywords) {
sb.append(" -- ");
sb.append(s);
sb.append("\n");
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/PropertiesServiceDescription.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/PropertiesServiceDescription.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/PropertiesServiceDescription.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -12,10 +12,11 @@
/**
* Class gets all registration properties from properties config file
+ *
* @author Maciej Glowiak
- *
*/
-public class PropertiesServiceDescription implements ServiceDescription {
+public class PropertiesServiceDescription implements ServiceDescription
+{
// ----------------------------------------------------- Constnats
@@ -35,23 +36,24 @@
// ------------------------------------------------ Public methods
@Override
- public Map<String,String> getServiceDescription() throws
PerfSONARException{
+ public Map<String, String> getServiceDescription() throws
PerfSONARException
+ {
ConfigurationComponent configuration = (ConfigurationComponent)
AuxiliaryComponentManager.getInstance().
getComponent(ComponentNames.CONFIG);
Enumeration<?> paramNames =
configuration.getProperties().propertyNames();
- Map<String,String> serviceDesc = new HashMap<String,String>();
+ Map<String, String> serviceDesc = new HashMap<String, String>();
while (paramNames.hasMoreElements()) {
- String paramName = (String)paramNames.nextElement();
+ String paramName = (String) paramNames.nextElement();
if (paramName.startsWith(registrationPrefix)) {
serviceDesc.put(paramName.substring(
- registrationPrefix.length()),
- configuration.getProperty(paramName));
+ registrationPrefix.length()),
+ configuration.getProperty(paramName));
}
}
@@ -60,14 +62,16 @@
}
- public String getRegistrationPrefix() {
+ public String getRegistrationPrefix()
+ {
return registrationPrefix;
}
- public void setRegistrationPrefix(String registrationPrefix) {
+ public void setRegistrationPrefix(String registrationPrefix)
+ {
this.registrationPrefix = registrationPrefix;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceContent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceContent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceContent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -2,7 +2,8 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-public interface ServiceContent {
+public interface ServiceContent
+{
String[] getServiceContent() throws PerfSONARException;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceDescription.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceDescription.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceDescription.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -4,8 +4,9 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-public interface ServiceDescription {
+public interface ServiceDescription
+{
- Map <String,String> getServiceDescription() throws PerfSONARException;
+ Map<String, String> getServiceDescription() throws PerfSONARException;
} //ServiceDescription
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceLSRegistrator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceLSRegistrator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/registration/ServiceLSRegistrator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -4,13 +4,13 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-
/**
* Service LS Registrator
*
* @author Maciej Glowiak
*/
-public interface ServiceLSRegistrator {
+public interface ServiceLSRegistrator
+{
public abstract void initRegistrator() throws PerfSONARException;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/DataRepository.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/DataRepository.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/DataRepository.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -7,38 +7,36 @@
import org.perfsonar.base.exceptions.PerfSONARException;
/**
- * This interface defines the data repository.
+ * This interface defines the data repository.
*
- * @author Roman Lapacz
- *
+ * @author Roman Lapacz
*/
-public interface DataRepository {
+public interface DataRepository
+{
-
/**
- * Sets type of a data repository.
+ * Sets type of a data repository.
*/
public void setType(String type);
/**
- * Returns the type of a data repository.
+ * Returns the type of a data repository.
*/
public String getType();
/**
- * Opens the acces to a data repository.
+ * Opens the acces to a data repository.
*/
- public void open() throws PerfSONARException;
+ public void open() throws PerfSONARException;
/**
- * Closes the acces to a data repository.
+ * Closes the acces to a data repository.
*/
public void close() throws PerfSONARException;
-
} //DataRepository
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/GenericXmlStorageManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/GenericXmlStorageManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/GenericXmlStorageManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -9,19 +9,17 @@
/**
- * This interface declares methods to have
- * an access to a data storage.
+ * This interface declares methods to have
+ * an access to a data storage.
*
- * @author Roman Lapacz
- *
+ * @author Roman Lapacz
*/
-public interface GenericXmlStorageManager extends StorageManager {
+public interface GenericXmlStorageManager extends StorageManager
+{
-
-
/**
- * Fetches data from a data repository.
+ * Fetches data from a data repository.
*/
@Override
public Object fetch(Object dataQuery)
@@ -29,12 +27,11 @@
/**
- * Stores data in a data repository.
+ * Stores data in a data repository.
*/
@Override
public Object store(Object dataSet)
throws PerfSONARException;
-
} //StorageManager
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/NMWGStorageManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/NMWGStorageManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/NMWGStorageManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -11,52 +11,52 @@
/**
- * This interface declares methods to have
- * an access to a data storage.
+ * This interface declares methods to have
+ * an access to a data storage.
*
- * @author Roman Lapacz
- *
+ * @author Roman Lapacz
*/
-public interface NMWGStorageManager {
+public interface NMWGStorageManager
+{
/**
- * Inits an object of this class with data repository object.
+ * Inits an object of this class with data repository object.
*/
public void initStorage(Key dataRepository)
throws PerfSONARException;
/**
- * Fetches data from a data repository.
+ * Fetches data from a data repository.
*/
public Message fetch(Message dataQuery)
throws PerfSONARException;
/**
- * Stores data in a data repository.
+ * Stores data in a data repository.
*/
public Message store(Message dataSet)
throws PerfSONARException;
/**
- * Removes certain data in a data repository.
+ * Removes certain data in a data repository.
*/
public Message remove(Message dataSet)
throws PerfSONARException;
/**
- * Removes all data in a data repository.
+ * Removes all data in a data repository.
*/
public void removeAll()
throws PerfSONARException;
/**
- * Updates data in a data repository.
+ * Updates data in a data repository.
*/
public Message update(Message dataSet)
throws PerfSONARException;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/StorageManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/StorageManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/StorageManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -9,35 +9,34 @@
/**
- * This interface declares methods to have
- * an access to a data storage.
+ * This interface declares methods to have
+ * an access to a data storage.
*
- * @author Roman Lapacz
- *
+ * @author Roman Lapacz
*/
-public interface StorageManager {
+public interface StorageManager
+{
/**
- * Inits an object of this class with data repository object.
+ * Inits an object of this class with data repository object.
*/
public void initStorage(DataRepository dataRepository)
throws PerfSONARException;
/**
- * Fetches data from a data repository.
+ * Fetches data from a data repository.
*/
public Object fetch(Object dataQuery)
throws PerfSONARException;
/**
- * Stores data in a data repository.
+ * Stores data in a data repository.
*/
public Object store(Object dataSet)
throws PerfSONARException;
-
} //StorageManager
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbConstants.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbConstants.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbConstants.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -1,21 +1,22 @@
package org.perfsonar.service.base.storage.xmldb;
-public interface XmlDbConstants {
+public interface XmlDbConstants
+{
/**
* Return results as XmlDbResult
*/
- public static final int RETURN_XML_DB_RESULT = 0x0100;
+ public static final int RETURN_XML_DB_RESULT = 0x0100;
/**
* Return results as XmlDbResult
*/
- public static final int RETURN_STRING_ARRAY = 0x0200;
+ public static final int RETURN_STRING_ARRAY = 0x0200;
/**
* Return results as String
*/
- public static final int RETURN_STRING = 0x0400;
+ public static final int RETURN_STRING = 0x0400;
} //XmlDbConstants
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbDataRepository.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbDataRepository.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbDataRepository.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -7,15 +7,14 @@
import org.perfsonar.service.base.storage.DataRepository;
-
/**
* Generic DataRepository for XML databases. Contains common parameters such
as
* URI of the XML Collection DB username and DB password
-
+ *
* @author Maciej Glowiak
- *
*/
-public abstract class XmlDbDataRepository implements DataRepository,
XmlDbConstants {
+public abstract class XmlDbDataRepository implements DataRepository,
XmlDbConstants
+{
/**
* Database username
@@ -36,7 +35,7 @@
/**
- * The object to log control/debugging messages
+ * The object to log control/debugging messages
*/
protected LoggerComponent logger = null;
@@ -47,10 +46,11 @@
// ----------------------------------- Constructor --------------------
- protected XmlDbDataRepository() {
+ protected XmlDbDataRepository()
+ {
try {
- logger = (LoggerComponent)AuxiliaryComponentManager.
+ logger = (LoggerComponent) AuxiliaryComponentManager.
getInstance().getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
}
@@ -60,42 +60,48 @@
}
- public String getDbPassword() {
+ public String getDbPassword()
+ {
return dbPassword;
}
- public void setDbPassword(String dbPassword) {
+ public void setDbPassword(String dbPassword)
+ {
this.dbPassword = dbPassword;
}
- public String getDbUri() {
+ public String getDbUri()
+ {
return dbUri;
}
- public void setDbUri(String dbUri) {
+ public void setDbUri(String dbUri)
+ {
this.dbUri = dbUri;
}
- public String getDbUsername() {
+ public String getDbUsername()
+ {
return dbUsername;
}
- public void setDbUsername(String dbUsername) {
+ public void setDbUsername(String dbUsername)
+ {
this.dbUsername = dbUsername;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbResult.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbResult.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbResult.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -8,9 +8,9 @@
* number of returned elements (count)
*
* @author Maciej Glowiak
- *
*/
-public class XmlDbResult {
+public class XmlDbResult
+{
// ----------------------------------------------------- Constants
@@ -25,7 +25,8 @@
public XmlDbResult(
- String[] results, int total, int start, int count) {
+ String[] results, int total, int start, int count)
+ {
this.results = results;
this.total = total;
@@ -35,7 +36,8 @@
public XmlDbResult(
- String result, int total, int start, int count) {
+ String result, int total, int start, int count)
+ {
String[] s = {result};
this.results = s;
@@ -48,10 +50,10 @@
// ------------------------------------------------ Public methods
+ public String getResultAsString()
+ {
- public String getResultAsString() {
-
- if (results.length==1) return results[0];
+ if (results.length == 1) return results[0];
else {
StringWriter sw = new StringWriter();
for (String result : results) sw.append(result);
@@ -60,41 +62,43 @@
}
- public String[] getResultAsStringArray() {
+ public String[] getResultAsStringArray()
+ {
return results;
}
-
@Override
- public String toString() {
+ public String toString()
+ {
String s = getResultAsString();
- return "XmlDbResult (total["+
- total+"] first["+
- start+"] count["+
- count+"] result=["+
- ((s.length()<200)?s:s.substring(0,200)+"...")+
+ return "XmlDbResult (total[" +
+ total + "] first[" +
+ start + "] count[" +
+ count + "] result=[" +
+ ((s.length() < 200) ? s : s.substring(0, 200) + "...") +
"])";
}
- public int getCount() {
+ public int getCount()
+ {
return count;
}
- public int getStart() {
+ public int getStart()
+ {
return start;
}
- public int getTotal() {
+ public int getTotal()
+ {
return total;
}
-
-
} //XmlDbResult
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbStorageManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbStorageManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/XmlDbStorageManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -4,11 +4,13 @@
/**
* Storage Manager for XML Databases
+ *
* @author Maciej Glowiak
*/
-public interface XmlDbStorageManager extends StorageManager {
+public interface XmlDbStorageManager extends StorageManager
+{
- public final static String STRING_ARRAY_TYPE = "String[]";
+ public final static String STRING_ARRAY_TYPE = "String[]";
public final static String XML_DB_RESULT_TYPE = "XmlDbResult";
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/ExistDbFactory.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/ExistDbFactory.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/ExistDbFactory.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -10,7 +10,8 @@
import
org.perfsonar.service.base.storage.xmldb.exist.rest.ExistDbHttpXmlDataRepository;
import
org.perfsonar.service.base.storage.xmldb.exist.xmlrpc.ExistDbXmlrpcXmlDataRepository;
-public class ExistDbFactory {
+public class ExistDbFactory
+{
// ----------------------------------------------------- Constants
@@ -22,10 +23,11 @@
public static XmlDbDataRepository getDataRepositoryByProperties(
- String type,
- String uriPropName,
- String usernamePropName,
- String passwordPropName) throws PerfSONARException {
+ String type,
+ String uriPropName,
+ String usernamePropName,
+ String passwordPropName) throws PerfSONARException
+ {
LoggerComponent logger = getLogger();
ConfigurationComponent configuration = getConfig();
@@ -39,26 +41,26 @@
if (type.equalsIgnoreCase(EXIST_XMLRPC)) {
logger.debug("ExistDbFactory: Creating XML RPC Data Repository:
("
- + uri + ", " + username + ", " + password + ")");
+ + uri + ", " + username + ", " + password + ")");
dataRepository =
- new ExistDbXmlrpcXmlDataRepository( uri, username, password
);
+ new ExistDbXmlrpcXmlDataRepository(uri, username, password);
return dataRepository;
} else if (type.equalsIgnoreCase(EXIST_HTTP)) {
logger.debug("ExistDbFactory: Creating HTTP/REST Data
Repository: ("
- + uri + ", " + username + ", " + password + ")");
+ + uri + ", " + username + ", " + password + ")");
dataRepository =
- new ExistDbHttpXmlDataRepository( uri, username, password );
+ new ExistDbHttpXmlDataRepository(uri, username, password);
return dataRepository;
} else {
//default - HTTP
logger.debug("ExistDbFactory: Creating default HTTP/REST Data
Repository: ("
- + uri + ", " + username + ", " + password + ")");
+ + uri + ", " + username + ", " + password + ")");
dataRepository =
- new ExistDbHttpXmlDataRepository( uri, username, password );
+ new ExistDbHttpXmlDataRepository(uri, username, password);
return dataRepository;
}
@@ -66,11 +68,11 @@
}
-
public static XmlDbStorageManager getXMLStorageManager(
- String type,
- XmlDbDataRepository dataRepository )
- throws PerfSONARException {
+ String type,
+ XmlDbDataRepository dataRepository)
+ throws PerfSONARException
+ {
XmlDbStorageManager sm;
LoggerComponent logger = getLogger();
@@ -87,11 +89,11 @@
} else {
- logger.error("ExistDbFactory: Cannot initialize ["+
- type+"] type Storage Manager for accessing XML" +
- " Lookup Service Database. Taking defaults");
+ logger.error("ExistDbFactory: Cannot initialize [" +
+ type + "] type Storage Manager for accessing XML" +
+ " Lookup Service Database. Taking defaults");
sm = ExistDbFactory.getXMLStorageManager(
- EXIST_HTTP, dataRepository);
+ EXIST_HTTP, dataRepository);
}
@@ -105,18 +107,20 @@
// ---------------------------------------- private static methods
private static LoggerComponent getLogger()
- throws PerfSONARException {
+ throws PerfSONARException
+ {
- return (LoggerComponent)AuxiliaryComponentManager.
+ return (LoggerComponent) AuxiliaryComponentManager.
getInstance().getComponent(ComponentNames.LOGGER);
}
private static ConfigurationComponent getConfig()
- throws PerfSONARException {
+ throws PerfSONARException
+ {
- return (ConfigurationComponent)AuxiliaryComponentManager.
+ return (ConfigurationComponent) AuxiliaryComponentManager.
getInstance().getComponent(ComponentNames.CONFIG);
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/ExistDbGenericStorageManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/ExistDbGenericStorageManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/ExistDbGenericStorageManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -13,10 +13,10 @@
/**
* @author Maciej Glowiak
- *
*/
public abstract class ExistDbGenericStorageManager
- implements XmlDbStorageManager, AuxiliaryComponent {
+ implements XmlDbStorageManager, AuxiliaryComponent
+{
// -------------------------------------------- Instance variables
@@ -27,7 +27,7 @@
/**
- * The object to log control/debugging messages
+ * The object to log control/debugging messages
*/
private LoggerComponent logger = null;
@@ -44,7 +44,8 @@
// ------------------------------------------------ Public methods
@Override
- public String getComponentName() {
+ public String getComponentName()
+ {
return componentName;
@@ -52,7 +53,8 @@
@Override
- public void setComponentName(String componentName) {
+ public void setComponentName(String componentName)
+ {
this.componentName = componentName;
@@ -60,7 +62,8 @@
@Override
- public void setResultType(String type) {
+ public void setResultType(String type)
+ {
if (STRING_ARRAY_TYPE.equals(type)) {
@@ -79,17 +82,19 @@
}
- protected int getResultType() {
+ protected int getResultType()
+ {
return resultFlag;
}
- protected LoggerComponent getLogger() throws PerfSONARException {
+ protected LoggerComponent getLogger() throws PerfSONARException
+ {
- if (logger==null) {
+ if (logger == null) {
//get logger
- logger = (LoggerComponent)AuxiliaryComponentManager.
+ logger = (LoggerComponent) AuxiliaryComponentManager.
getInstance().getComponent(ComponentNames.LOGGER);
}
@@ -97,6 +102,4 @@
}
-
-
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbErrorException.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbErrorException.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbErrorException.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -4,10 +4,11 @@
* Represents Exist XML DB error or response message (e.g.Unauthorized...)
*
* @author Maciej Glowiak
- *
- * $id$
+ * <p/>
+ * $id$
*/
-public class ExistDbErrorException extends Exception {
+public class ExistDbErrorException extends Exception
+{
// ----------------------------------------------------- Constants
@@ -33,10 +34,11 @@
// --------------------------------------------------- Constructor
- public ExistDbErrorException(int code, String description) {
+ public ExistDbErrorException(int code, String description)
+ {
- super("eXist DB responsed with HTTP error code code ["+
- code+"] additional message was ["+description+"]");
+ super("eXist DB responsed with HTTP error code code [" +
+ code + "] additional message was [" + description + "]");
httpCode = code;
httpMessage = description;
@@ -46,28 +48,32 @@
// ------------------------------------------------ Public methods
- public int getHttpCode() {
+ public int getHttpCode()
+ {
return httpCode;
}
- public void setHttpCode(int httpCode) {
+ public void setHttpCode(int httpCode)
+ {
this.httpCode = httpCode;
}
- public String getHttpMessage() {
+ public String getHttpMessage()
+ {
return httpMessage;
}
- public void setHttpMessage(String httpMessage) {
+ public void setHttpMessage(String httpMessage)
+ {
this.httpMessage = httpMessage;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHTTPAccess.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHTTPAccess.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHTTPAccess.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -15,11 +15,11 @@
* Supports HTTP authorization, results parsing
*
* @author Maciej Glowiak
- *
- * $Id$
- *
+ * <p/>
+ * $Id$
*/
-public class ExistDbHTTPAccess extends HTTPAccess implements XmlDbConstants {
+public class ExistDbHTTPAccess extends HTTPAccess implements XmlDbConstants
+{
// ---------------------------------------------Instance variables
@@ -45,18 +45,18 @@
public int sendExistXUpdateRequest(
- String url,
- String updateString,
- String username,
- String password) throws IOException, ExistDbErrorException {
+ String url,
+ String updateString,
+ String username,
+ String password) throws IOException, ExistDbErrorException
+ {
- HTTPResult result = sendPOSTRequest(url, updateString,username,
password);
+ HTTPResult result = sendPOSTRequest(url, updateString, username,
password);
return result.getResultCode();
}
/**
- *
* @param url
* @param content
* @param username
@@ -67,23 +67,24 @@
* @throws IOException
*/
public HTTPResult sendXQueryPOSTRequest(
- String url,
- String content,
- String username,
- String password,
- int start,
- int limit) throws IOException {
+ String url,
+ String content,
+ String username,
+ String password,
+ int start,
+ int limit) throws IOException
+ {
//prepare XQuery
- content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
- "<query xmlns=\"http://exist.sourceforge.net/NS/exist\" "+
- "start=\""+String.valueOf(start)+"\" max=\""+
- String.valueOf(limit)+"\" cache=\"no\"> "+
+ content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<query xmlns=\"http://exist.sourceforge.net/NS/exist\" " +
+ "start=\"" + String.valueOf(start) + "\" max=\"" +
+ String.valueOf(limit) + "\" cache=\"no\"> " +
" <text>" +
- "<![CDATA["+
+ "<![CDATA[" +
content +
"]]>" +
- " </text> "+
+ " </text> " +
" <properties>" +
" <property name=\"indent\" value=\"yes\"/>" + //temp
" <property name=\"encoding\" value=\"UTF-8\"/>" +
//temp
@@ -96,18 +97,19 @@
public XmlDbResult sendExistXQueryRequest(
- String url,
- String query,
- String username,
- String password,
- int start,
- int limit) throws IOException, ExistDbErrorException {
+ String url,
+ String query,
+ String username,
+ String password,
+ int start,
+ int limit) throws IOException, ExistDbErrorException
+ {
/* ******************************************************** */
//send HTTP request and encapsulate query
HTTPResult httpResult = sendXQueryPOSTRequest(
- url, query, username, password, start, limit);
+ url, query, username, password, start, limit);
/* ******************************************************** */
@@ -116,23 +118,23 @@
//parse XML result returned by eXist DB XML
XmlDbResult xmlResult = parseExistXMLReponse(
- httpResult.getResponse());
+ httpResult.getResponse());
return xmlResult;
} else {
throw new ExistDbErrorException(
- resultCode, httpResult.getResultMessage());
+ resultCode, httpResult.getResultMessage());
}
}
-
private XmlDbResult parseExistXMLReponse(
- InputStream inputStream) throws IOException {
+ InputStream inputStream) throws IOException
+ {
- int hits=-1, first=-1, count=-1;
+ int hits = -1, first = -1, count = -1;
String result;
String[] resultArray = null;
@@ -141,7 +143,7 @@
//read response
BufferedReader rd = new BufferedReader(
- new InputStreamReader(inputStream));
+ new InputStreamReader(inputStream));
//<exist:result...> parsed?
boolean exResult = false;
@@ -154,7 +156,7 @@
while ((str = rd.readLine()) != null) {
if (debug) {
- System.out.println("[->] read line: ["+str+"]");
+ System.out.println("[->] read line: [" + str + "]");
}
boolean doParseLine = true;
@@ -163,47 +165,50 @@
if (str.startsWith("<exist:result")) {
- if (debug) System.out.println(
- "[HEAD] ["+str+"]");
+ if (debug) System.out.println(
+ "[HEAD] [" + str + "]");
doParseLine = false;
- exResult=true;
+ exResult = true;
//if full results, parse hits/count/total as well
try {
- hits=Integer.parseInt(
- XMLUtils.extractXMLAttributeValue(
- str,"exist:hits"));
- } catch (RuntimeException e) {}
+ hits = Integer.parseInt(
+ XMLUtils.extractXMLAttributeValue(
+ str, "exist:hits"));
+ } catch (RuntimeException e) {
+ }
try {
- count=Integer.parseInt(
- XMLUtils.extractXMLAttributeValue(
- str,"exist:count"));
- } catch (RuntimeException e) {}
+ count = Integer.parseInt(
+ XMLUtils.extractXMLAttributeValue(
+ str, "exist:count"));
+ } catch (RuntimeException e) {
+ }
try {
- first=Integer.parseInt(
- XMLUtils.extractXMLAttributeValue(
- str,"exist:start"));
- } catch (RuntimeException e) {}
+ first = Integer.parseInt(
+ XMLUtils.extractXMLAttributeValue(
+ str, "exist:start"));
+ } catch (RuntimeException e) {
+ }
if (debug) System.out.println(
- "[RESV] hits="+hits);
+ "[RESV] hits=" + hits);
if (debug) System.out.println(
- "[RESV] start="+first);
+ "[RESV] start=" + first);
if (debug) System.out.println(
- "[RESV] count="+count);
+ "[RESV] count=" + count);
//Case if exist:result in one line
//if <exist:result>anything</exist:result>
String content = XMLUtils.extractXMLTag(
- str,"exist:result");
+ str, "exist:result");
- if (content!=null) {
+ if (content != null) {
//take only content
- str=content;
- doParseLine=true; //this time parse line, because
+ str = content;
+ doParseLine = true; //this time parse line, because
//it may contain more data to be parsed
- if (debug) System.out.println("[D] Results in one
line, parsing content ["+str+"]...");
+ if (debug) System.out.println("[D] Results in one
line, parsing content [" + str + "]...");
}
} //<exist:result>
@@ -211,24 +216,23 @@
} else {
if (str.startsWith("</exist:result")) {
- if (debug) System.out.println(
- "[FOOT] ["+str+"]");
+ if (debug) System.out.println(
+ "[FOOT] [" + str + "]");
doParseLine = false;
}
} //</exist:result>
-
//parse (if inside <exist:result></exist:result>
if (doParseLine) {
if (allowRemoveExistValue) {
//remove <exist:value...
- String content =
XMLUtils.extractXMLTag(str,"exist:value");
- if (content!=null) {
- str=content;
+ String content = XMLUtils.extractXMLTag(str,
"exist:value");
+ if (content != null) {
+ str = content;
//add to list
if (!(str != null && str.isEmpty()))
responseList.add(str);
@@ -249,7 +253,7 @@
//add Line Feed sign at the end of each line
response.append("\n");
- if (debug) System.out.println("[LINE] ["+str+"]");
+ if (debug) System.out.println("[LINE] [" + str + "]");
} //parse
@@ -263,35 +267,37 @@
resultArray = responseList.
toArray(new String[responseList.size()]);
- if (resultArray!=null)
+ if (resultArray != null)
return new XmlDbResult(resultArray, hits, first, count);
//return XmlDbResult
else
- return new XmlDbResult(result, hits, first, count); //return
XmlDbResult
+ return new XmlDbResult(result, hits, first, count); //return
XmlDbResult
}
- public boolean isDebug() {
+ public boolean isDebug()
+ {
return debug;
}
- public void setDebug(boolean debug) {
+ public void setDebug(boolean debug)
+ {
this.debug = debug;
}
-
// --------------------------------------------------- test method
/**
* Test method
*/
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws Exception
+ {
// String query =
// "declare namespace " +
@@ -343,26 +349,24 @@
ExistDbHTTPAccess a = new ExistDbHTTPAccess();
a.setDebug(true);
XmlDbResult result = a.sendExistXQueryRequest(
- "http://localhost:8680/exist/rest/db/test",
- query,
- "lookupservice",
- "sonar",
- FIRST,
- ALL_RESULTS);
+ "http://localhost:8680/exist/rest/db/test",
+ query,
+ "lookupservice",
+ "sonar",
+ FIRST,
+ ALL_RESULTS);
a.disconnectHTTPServer();
long t1 = System.currentTimeMillis(); //----------------time 1
- for (int i=0; i<result.getResultAsStringArray().length; i++) {
+ for (int i = 0; i < result.getResultAsStringArray().length; i++) {
String x = result.getResultAsStringArray()[i];
- System.out.println("RESULT["+i+"]:
"+((x.length()<1000)?x:"..."+x.substring(1000)+"..."));
+ System.out.println("RESULT[" + i + "]: " + ((x.length() < 1000)
? x : "..." + x.substring(1000) + "..."));
}
- System.out.println("TIME: "+(t1-t0)+"ms");
+ System.out.println("TIME: " + (t1 - t0) + "ms");
-
-
}
} //ExistDbHTTPAccess
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHttpXmlDataRepository.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHttpXmlDataRepository.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHttpXmlDataRepository.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -3,19 +3,24 @@
import org.perfsonar.base.exceptions.PerfSONARException;
import org.perfsonar.service.base.storage.xmldb.XmlDbDataRepository;
-public class ExistDbHttpXmlDataRepository extends XmlDbDataRepository {
+public class ExistDbHttpXmlDataRepository extends XmlDbDataRepository
+{
@Override
- public void setType(String type) {}
+ public void setType(String type)
+ {
+ }
@Override
- public String getType() {
+ public String getType()
+ {
return "http://exist-db.org/rest";
}
- public ExistDbHttpXmlDataRepository(String uri, String username, String
password) {
+ public ExistDbHttpXmlDataRepository(String uri, String username, String
password)
+ {
super();
@@ -27,9 +32,13 @@
@Override
- public void open() throws PerfSONARException {}
+ public void open() throws PerfSONARException
+ {
+ }
@Override
- public void close() throws PerfSONARException {}
+ public void close() throws PerfSONARException
+ {
+ }
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHttpXmlStorageManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHttpXmlStorageManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/ExistDbHttpXmlStorageManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -13,33 +13,32 @@
/**
- * This class is StorageManager for Exist DB XML
- * (http://exist-db.org/)
+ * This class is StorageManager for Exist DB XML
+ * (http://exist-db.org/)
+ * <p/>
+ * It provides fetch (XPath/XQuery expression as an input) and
+ * store (XUpdate XML expression as an input).
+ * <p/>
+ * Results of fetch/store are
+ * String - if type is set to STRING_TYPE //not implemented
+ * String[] - if type is set to STRING_ARRAY_TYPE
+ * XmlDbResult if type is set to XML_DB_RESULT_TYPE
*
- * It provides fetch (XPath/XQuery expression as an input) and
- * store (XUpdate XML expression as an input).
- *
- * Results of fetch/store are
- * String - if type is set to STRING_TYPE //not implemented
- * String[] - if type is set to STRING_ARRAY_TYPE
- * XmlDbResult if type is set to XML_DB_RESULT_TYPE
- *
- * @author Roman Lapacz
- * @author Maciej Glowiak
- *
+ * @author Roman Lapacz
+ * @author Maciej Glowiak
*/
public class ExistDbHttpXmlStorageManager
extends ExistDbGenericStorageManager
- implements XmlDbStorageManager, AuxiliaryComponent {
+ implements XmlDbStorageManager, AuxiliaryComponent
+{
+ // -------------------------------------- InstanceVariables
- // -------------------------------------- InstanceVariables
-
/**
* Data repository object
*/
- protected XmlDbDataRepository dataRepository = null;
+ protected XmlDbDataRepository dataRepository = null;
protected ExistDbHTTPAccess httpAccess = null;
@@ -47,15 +46,14 @@
// -------------------------------------- constructors
+ public ExistDbHttpXmlStorageManager()
+ {
- public ExistDbHttpXmlStorageManager() {
-
httpAccess = new ExistDbHTTPAccess();
}
-
// -------------------------------------- public methods
@@ -66,19 +64,20 @@
*/
@Override
public void initStorage(DataRepository dataRepository)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
- try {
+ try {
this.dataRepository = (XmlDbDataRepository) dataRepository;
} catch (ClassCastException ex) {
getLogger().error("ExistDbXmlrpcXmlStorageManager.initStorage: "
- + "wrong data repository class ("
- + dataRepository.getClass().getName()
- + ")! Data repository must implement "
- + "ExistDbXmlrpcXmlDataRepository class");
+ + "wrong data repository class ("
+ + dataRepository.getClass().getName()
+ + ")! Data repository must implement "
+ + "ExistDbXmlrpcXmlDataRepository class");
}
@@ -86,14 +85,15 @@
@Override
- public void initComponent() throws PerfSONARException {
+ public void initComponent() throws PerfSONARException
+ {
- dataRepository = ExistDbFactory.getDataRepositoryByProperties(
+ dataRepository = ExistDbFactory.getDataRepositoryByProperties(
ExistDbFactory.EXIST_HTTP,
"component." + getComponentName() + ".db_uri",
- "component."+getComponentName() + ".db_username",
- "component."+getComponentName() + ".db_password"
- );
+ "component." + getComponentName() + ".db_username",
+ "component." + getComponentName() + ".db_password"
+ );
//Init Storage Manager with DataRepository
initStorage(dataRepository);
@@ -109,9 +109,10 @@
*/
@Override
public Object fetch(Object dataQuery)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
- return xqueryHttp(dataQuery);
+ return xqueryHttp(dataQuery);
}
@@ -124,79 +125,77 @@
*/
@Override
public Object store(Object dataSet)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
- return xupdateHttp(dataSet);
+ return xupdateHttp(dataSet);
}
// -------------------------------------- protected methods
-
protected Object xqueryHttp(Object query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
getLogger().debug("ExistDbHttpXmlStorageManager: XQuery");
XmlDbResult results;
try {
results = httpAccess.sendExistXQueryRequest(
- dataRepository.getDbUri(),
- (String)query,
- dataRepository.getDbUsername(),
- dataRepository.getDbPassword(),
- ExistDbHTTPAccess.FIRST,
- ExistDbHTTPAccess.ALL_RESULTS);
+ dataRepository.getDbUri(),
+ (String) query,
+ dataRepository.getDbUsername(),
+ dataRepository.getDbPassword(),
+ ExistDbHTTPAccess.FIRST,
+ ExistDbHTTPAccess.ALL_RESULTS);
} catch (Exception ex) {
throw new PerfSONARException(
- "error.common.storage.xmldb.open",
- "XQuery by HTTP failed. "
+ "error.common.storage.xmldb.open",
+ "XQuery by HTTP failed. "
+ "Could not connect to eXist via pure http, "
- + " nested exception was: "+
- ex.getClass()+" : "+ex.getMessage());
+ + " nested exception was: " +
+ ex.getClass() + " : " + ex.getMessage());
}
- if (getResultType()==XmlDbConstants.RETURN_STRING_ARRAY)
- return results.getResultAsStringArray();
+ if (getResultType() == XmlDbConstants.RETURN_STRING_ARRAY)
+ return results.getResultAsStringArray();
else return results;
-
+
}
-
protected Object xupdateHttp(Object xml)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
getLogger().debug("ExistDbHttpXmlStorageManager: XUpdate");
int results;
try {
results = httpAccess.sendExistXUpdateRequest(
- dataRepository.getDbUri(),
- (String)xml,
- dataRepository.getDbUsername(),
- dataRepository.getDbPassword());
+ dataRepository.getDbUri(),
+ (String) xml,
+ dataRepository.getDbUsername(),
+ dataRepository.getDbPassword());
} catch (Exception ex) {
throw new PerfSONARException(
- "error.common.storage.xmldb.open",
- "XUpdate by HTTP failed. "
+ "error.common.storage.xmldb.open",
+ "XUpdate by HTTP failed. "
+ "Could not connect to eXist via pure http, "
- + " nested exception was: "+
- ex.getClass()+" : "+ex.getMessage());
+ + " nested exception was: " +
+ ex.getClass() + " : " + ex.getMessage());
}
return results; // String, String[] or XmlDbResult
- // - depends on getResultType()
+ // - depends on getResultType()
}
// ---------------------------------------------
-
-
-
} //ExistDbXmlStorageManager
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/HTTPAccess.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/HTTPAccess.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/HTTPAccess.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -12,9 +12,9 @@
* to other HTTP databases or servers
*
* @author Maciej Glowiak
- *
*/
-public class HTTPAccess {
+public class HTTPAccess
+{
// --------------------------------------------- Private variables
@@ -29,6 +29,7 @@
/**
* POST - Sends text content to the server
+ *
* @param url
* @param content
* @param username
@@ -37,24 +38,26 @@
* @throws IOException
*/
public HTTPResult sendPOSTRequest(
- String url,
- String content,
- String username,
- String password) throws IOException {
+ String url,
+ String content,
+ String username,
+ String password) throws IOException
+ {
return sendHTTPRequest(
- url,
- "POST",
- "application/x- www-form-urlencoded",
- content,
- true, true,
- username, password);
+ url,
+ "POST",
+ "application/x- www-form-urlencoded",
+ content,
+ true, true,
+ username, password);
}
/**
* DELETE - removes remote resource from the server
+ *
* @param url
* @param username
* @param password
@@ -62,22 +65,24 @@
* @throws IOException
*/
public HTTPResult sendDELETERequest(
- String url,
- String username,
- String password) throws IOException {
+ String url,
+ String username,
+ String password) throws IOException
+ {
return sendHTTPRequest(
- url,
- "DELETE",
- null, null,
- false, true, //no input, output=result
- username, password);
+ url,
+ "DELETE",
+ null, null,
+ false, true, //no input, output=result
+ username, password);
}
/**
* PUT - sends resource to the server
+ *
* @param url
* @param content
* @param username
@@ -86,23 +91,25 @@
* @throws IOException
*/
public HTTPResult sendPUTRequest(
- String url,
- String content,
- String username,
- String password) throws IOException {
+ String url,
+ String content,
+ String username,
+ String password) throws IOException
+ {
return sendHTTPRequest(
- url,
- "PUT",
- null, content,
- true, true,
- username, password);
+ url,
+ "PUT",
+ null, content,
+ true, true,
+ username, password);
}
/**
* GET - downloads remote document from the server
+ *
* @param url
* @param username
* @param password
@@ -110,16 +117,17 @@
* @throws IOException
*/
public HTTPResult sendGETRequest(
- String url,
- String username,
- String password) throws IOException {
+ String url,
+ String username,
+ String password) throws IOException
+ {
return sendHTTPRequest(
- url,
- "GET",
- null, null,
- false, true,
- username, password);
+ url,
+ "GET",
+ null, null,
+ false, true,
+ username, password);
}
@@ -139,17 +147,18 @@
* @throws IOException
*/
protected HTTPResult sendHTTPRequest(
- String url,
- String method,
- String contentType,
- String content,
- boolean isRequest,
- boolean isResponse,
- String username,
- String password) throws IOException {
+ String url,
+ String method,
+ String contentType,
+ String content,
+ boolean isRequest,
+ boolean isResponse,
+ String username,
+ String password) throws IOException
+ {
//temp//
- boolean debug=false;
+ boolean debug = false;
//connect by HTTP with /exist/rest/db/COLLECTION
URL _url = new URL(url);
@@ -168,26 +177,26 @@
httpUrlConnection.setDoInput(isResponse);
//set content length
- if (content!=null)
+ if (content != null)
httpUrlConnection.setRequestProperty(
"Content-Length",
String.valueOf(content.length()));
//HTTP Authorization, set "Authorization: Basic " if necessary
- if (username!=null) {
+ if (username != null) {
- if (password==null) password=""; //if null make it empty String
+ if (password == null) password = ""; //if null make it empty
String
if (!(username != null && username.isEmpty())) {
- if (debug) System.out.println("[D] authorization Basic "+
- username+":"+password);
+ if (debug) System.out.println("[D] authorization Basic " +
+ username + ":" + password);
String basicAuth = "Basic " +
(new sun.misc.BASE64Encoder().
- encode((username+":"+password).getBytes()));
+ encode((username + ":" + password).getBytes()));
httpUrlConnection.setRequestProperty(
- "Authorization", basicAuth);
+ "Authorization", basicAuth);
}
}
@@ -204,7 +213,7 @@
int responseCode = httpUrlConnection.getResponseCode();
String responseMessage = httpUrlConnection.getResponseMessage();
- if (debug) System.out.println("[D] Response code: "+ responseCode+"
("+responseMessage+")");
+ if (debug) System.out.println("[D] Response code: " + responseCode +
" (" + responseMessage + ")");
InputStream response = null;
if (isResponse) {
@@ -216,7 +225,8 @@
}
- public void disconnectHTTPServer() {
+ public void disconnectHTTPServer()
+ {
httpUrlConnection.disconnect();
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/HTTPResult.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/HTTPResult.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/rest/HTTPResult.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -6,31 +6,37 @@
* Represents HTTP results
*
* @author Maciej Glowiak
- *
*/
-public class HTTPResult {
+public class HTTPResult
+{
private InputStream response;
private int resultCode;
private String resultMessage;
public HTTPResult(
- InputStream response,
- int resultCode,
- String resultMessage) {
+ InputStream response,
+ int resultCode,
+ String resultMessage)
+ {
this.response = response;
this.resultCode = resultCode;
this.resultMessage = resultMessage;
}
- public InputStream getResponse() {
+ public InputStream getResponse()
+ {
return response;
}
- public int getResultCode() {
+
+ public int getResultCode()
+ {
return resultCode;
}
- public String getResultMessage() {
+
+ public String getResultMessage()
+ {
return resultMessage;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/xmlrpc/ExistDbXmlrpcXmlDataRepository.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/xmlrpc/ExistDbXmlrpcXmlDataRepository.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/xmlrpc/ExistDbXmlrpcXmlDataRepository.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -13,9 +13,9 @@
* Exist JARs.
*
* @author Maciej Glowiak
- *
*/
-public class ExistDbXmlrpcXmlDataRepository extends XmlDbDataRepository {
+public class ExistDbXmlrpcXmlDataRepository extends XmlDbDataRepository
+{
/**
* Default driver class for Exist XML DB.
@@ -49,7 +49,8 @@
//
-----------------------------------------------------------------------
Constructor
- public ExistDbXmlrpcXmlDataRepository(String driverClassname, String
uri, String username, String password) {
+ public ExistDbXmlrpcXmlDataRepository(String driverClassname, String
uri, String username, String password)
+ {
this();
setDbDriverClassname(driverClassname);
@@ -60,7 +61,8 @@
}
- public ExistDbXmlrpcXmlDataRepository(String uri, String username,
String password) {
+ public ExistDbXmlrpcXmlDataRepository(String uri, String username,
String password)
+ {
this();
setDbPassword(password);
@@ -70,7 +72,8 @@
}
- public ExistDbXmlrpcXmlDataRepository() {
+ public ExistDbXmlrpcXmlDataRepository()
+ {
// nothing to do here, all parameters are default
}
@@ -82,7 +85,8 @@
* Get database driver classname, default for Exist DB XML
* is "org.exist.xmldb.DatabaseImpl"
*/
- public String getDbDriverClassname() {
+ public String getDbDriverClassname()
+ {
return dbDriverClassname;
@@ -92,7 +96,8 @@
* Set database driver classname, default for Exist DB XML
* is "org.exist.xmldb.DatabaseImpl"
*/
- public void setDbDriverClassname(String dbDriverClassname) {
+ public void setDbDriverClassname(String dbDriverClassname)
+ {
this.dbDriverClassname = dbDriverClassname;
@@ -102,7 +107,8 @@
/**
* Get XML Collection (exist DB XML object). Null if not connected
*/
- public Collection getExistCollection() {
+ public Collection getExistCollection()
+ {
return existCollection;
@@ -112,7 +118,8 @@
/**
* Get XML Database (exist DB XML object). Null if not connected
*/
- public Database getExistDatabase() {
+ public Database getExistDatabase()
+ {
return existDatabase;
@@ -123,14 +130,16 @@
@Override
- public String getType() {
+ public String getType()
+ {
return DB_TYPE;
}
@Override
- public void setType(String type) {
+ public void setType(String type)
+ {
// ??
// Nothing to do here. What is this method for?
// ??
@@ -138,48 +147,49 @@
@Override
- public void open() throws PerfSONARException {
+ public void open() throws PerfSONARException
+ {
logger.debug("ExistDbXmlrpcXmlDataRepository: connect");
- if (existDatabase==null) {
+ if (existDatabase == null) {
try {
Class<?> cl = Class.forName(dbDriverClassname);
- existDatabase = (Database)cl.newInstance();
+ existDatabase = (Database) cl.newInstance();
DatabaseManager.registerDatabase(existDatabase);
- existCollection = DatabaseManager.getCollection(
- dbUri, dbUsername, dbPassword);
+ existCollection = DatabaseManager.getCollection(
+ dbUri, dbUsername, dbPassword);
} catch (ClassNotFoundException e) {
throw new
PerfSONARException("error.common.storage.xmldb.open",
- "ExistDbXmlrpcXmlDataRepository: Can't find eXist DB
XML driver "
- +dbDriverClassname+", "+e.getMessage());
+ "ExistDbXmlrpcXmlDataRepository: Can't find eXist DB XML
driver "
+ + dbDriverClassname + ", " + e.getMessage());
} catch (InstantiationException e) {
throw new
PerfSONARException("error.common.storage.xmldb.open",
- "ExistDbXmlrpcXmlDataRepository: " +
+ "ExistDbXmlrpcXmlDataRepository: " +
"Can't create eXist DB XML driver instance "
- +dbDriverClassname+", "+e.getMessage());
+ + dbDriverClassname + ", " + e.getMessage());
} catch (IllegalAccessException e) {
throw new
PerfSONARException("error.common.storage.xmldb.open",
- "ExistDbXmlrpcXmlDataRepository: " +
- "IllegalAccessException, "+e.getMessage());
+ "ExistDbXmlrpcXmlDataRepository: " +
+ "IllegalAccessException, " + e.getMessage());
} catch (XMLDBException e) {
throw new
PerfSONARException("error.common.storage.xmldb.open",
- "ExistDbXmlrpcXmlDataRepository: XML DB Exception
"+e.getMessage());
+ "ExistDbXmlrpcXmlDataRepository: XML DB Exception " +
e.getMessage());
} catch (NullPointerException e) {
throw new
PerfSONARException("error.common.storage.xmldb.open",
- "ExistDbXmlrpcXmlDataRepository:
NullPointerException [" +
- "database="+existDatabase+",
collection="+existCollection+
- ", driver="+dbDriverClassname+", params: "+dbUri+" :
"+
- dbUsername+" : "+dbPassword+"] "+e.getMessage());
+ "ExistDbXmlrpcXmlDataRepository: NullPointerException ["
+
+ "database=" + existDatabase + ", collection=" +
existCollection +
+ ", driver=" + dbDriverClassname + ", params: " +
dbUri + " : " +
+ dbUsername + " : " + dbPassword + "] " +
e.getMessage());
}
} else {
- logger.error("ExistDbXmlrpcXmlDataRepository: error connecting
database - " +
+ logger.error("ExistDbXmlrpcXmlDataRepository: error connecting
database - " +
"database connection has been already opened; close it
first!");
}
@@ -189,32 +199,31 @@
@Override
- public void close() throws PerfSONARException {
+ public void close() throws PerfSONARException
+ {
- if (existDatabase!=null) {
+ if (existDatabase != null) {
try {
logger.debug("ExistDbXmlrpcXmlDataRepository: close
connection");
DatabaseManager.deregisterDatabase(existDatabase);
- existDatabase=null;
- existCollection=null;
+ existDatabase = null;
+ existCollection = null;
} catch (XMLDBException e) {
throw new
PerfSONARException("error.common.storage.xmldb.close",
- "ExistDbXmlrpcXmlDataRepository: Can't deregister
database, "
- +e.getMessage());
+ "ExistDbXmlrpcXmlDataRepository: Can't deregister
database, "
+ + e.getMessage());
}
} else {
logger.error("ExistDbXmlrpcXmlDataRepository: can't close
connection; " +
- "database is not connected");
+ "database is not connected");
}
}
-
-
} //ExistDbXmlrpcXmlDataRepository
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/xmlrpc/ExistDbXmlrpcXmlStorageManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/xmlrpc/ExistDbXmlrpcXmlStorageManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmldb/exist/xmlrpc/ExistDbXmlrpcXmlStorageManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -20,21 +20,20 @@
import org.xmldb.api.modules.XUpdateQueryService;
/**
- * This class is StorageManager for Exist DB XML
- * (http://exist-db.org/)
+ * This class is StorageManager for Exist DB XML
+ * (http://exist-db.org/)
+ * <p/>
+ * It provides fetch (XPath/XQuery expression as an input) and
+ * store (XUpdate XML expression as an input).
*
- * It provides fetch (XPath/XQuery expression as an input) and
- * store (XUpdate XML expression as an input).
- *
- * @author Maciej Glowiak
- *
+ * @author Maciej Glowiak
*/
public class ExistDbXmlrpcXmlStorageManager
extends ExistDbGenericStorageManager
- implements XmlDbStorageManager, AuxiliaryComponent {
+ implements XmlDbStorageManager, AuxiliaryComponent
+{
-
/**
* Data repository object
*/
@@ -57,7 +56,8 @@
//
-----------------------------------------------------------------------
Constructor
- public ExistDbXmlrpcXmlStorageManager() {
+ public ExistDbXmlrpcXmlStorageManager()
+ {
isConnected = false;
@@ -72,19 +72,20 @@
* a PerfSONARException will be thrown!
*/
@Override
- public void initStorage(DataRepository dataRepository) throws
PerfSONARException {
+ public void initStorage(DataRepository dataRepository) throws
PerfSONARException
+ {
getLogger().debug("ExistDbXmlrpcXmlStorageManager: initStorage with
data repository");
try {
- this.dataRepository =
(ExistDbXmlrpcXmlDataRepository)dataRepository;
+ this.dataRepository = (ExistDbXmlrpcXmlDataRepository)
dataRepository;
} catch (ClassCastException ex) {
- getLogger().error("ExistDbXmlrpcXmlStorageManager: wrong data
repository class ("+
- dataRepository.getClass().getName()+
- ")! Data repository must implement
ExistDbXmlrpcXmlDataRepository class");
+ getLogger().error("ExistDbXmlrpcXmlStorageManager: wrong data
repository class (" +
+ dataRepository.getClass().getName() +
+ ")! Data repository must implement
ExistDbXmlrpcXmlDataRepository class");
}
@@ -92,7 +93,8 @@
@Override
- public void initComponent() throws PerfSONARException {
+ public void initComponent() throws PerfSONARException
+ {
getLogger().debug("ExistDbXmlrpcXmlStorageManager: initComponent");
@@ -102,10 +104,10 @@
DataRepository dataRepository =
ExistDbFactory.getDataRepositoryByProperties(
ExistDbFactory.EXIST_XMLRPC,
- "component."+getComponentName()+".db_uri",
- "component."+getComponentName()+".db_username",
- "component."+getComponentName()+".db_password"
- );
+ "component." + getComponentName() + ".db_uri",
+ "component." + getComponentName() + ".db_username",
+ "component." + getComponentName() + ".db_password"
+ );
//Init Storage Manager with DataRepository
@@ -116,26 +118,28 @@
/**
* Fetch data. dataQuery input parameter MUST be a String
+ *
* @param dataQuery Must be String that contain XPath/XQuery expression
* @return always StringArrayDataSet object
*/
@Override
- public Object fetch(Object dataQuery) throws PerfSONARException {
+ public Object fetch(Object dataQuery) throws PerfSONARException
+ {
getLogger().debug("ExistXMLDatabaseAccess: perform XQuery");
String xqueryExpression;
try {
- xqueryExpression = (String)dataQuery;
+ xqueryExpression = (String) dataQuery;
} catch (ClassCastException ex) {
throw new
PerfSONARException("error.common.storage.xmldb.wrong_query",
- "ExistDbXmlrpcXmlStorageManager: This method accepts " +
+ "ExistDbXmlrpcXmlStorageManager: This method accepts " +
"StringData data format only");
}
- if (xqueryExpression==null) {
+ if (xqueryExpression == null) {
throw new
PerfSONARException("error.common.storage.xmldb.empty_query",
- "ExistDbXmlrpcXmlStorageManager: Input DataQuery " +
+ "ExistDbXmlrpcXmlStorageManager: Input DataQuery " +
"contains no data");
}
@@ -146,29 +150,29 @@
XPathQueryService service =
(XPathQueryService)
dataRepository.getExistCollection().getService(
- "XPathQueryService", "1.0");
+ "XPathQueryService", "1.0");
//service.setProperty("indent", "yes");
- if (service==null) getLogger().debug("StorageManager: warning -
service is null");
+ if (service == null) getLogger().debug("StorageManager: warning
- service is null");
ResourceSet result = service.query(xqueryExpression);
- if (result==null) getLogger().debug("StorageManager: warning -
result is null");
+ if (result == null) getLogger().debug("StorageManager: warning -
result is null");
ResourceIterator resIt = result.getIterator();
List<Object> list = new Vector<Object>();
- int i=0;
- while(resIt.hasMoreResources()) {
+ int i = 0;
+ while (resIt.hasMoreResources()) {
Resource r = resIt.nextResource();
- list.add(i,r.getContent());
+ list.add(i, r.getContent());
i++;
}
String[] xml = new String[list.size()];
- for (i=0; i < list.size(); i++) {
- xml[i] = (String)list.get(i);
+ for (i = 0; i < list.size(); i++) {
+ xml[i] = (String) list.get(i);
}
disconnect();
@@ -186,10 +190,10 @@
} catch (XMLDBException e) {
throw new PerfSONARException("error.common.storage.xmldb.query",
- "Can't perform XQuery: "+e.getMessage());
+ "Can't perform XQuery: " + e.getMessage());
} catch (Exception ex) {
throw new PerfSONARException("error.common.storage.xmldb",
- "There is a problem to use xml database; " +
ex.getMessage() + " errorType="+ex.getClass().getName());
+ "There is a problem to use xml database; " + ex.getMessage()
+ " errorType=" + ex.getClass().getName());
}
@@ -199,11 +203,13 @@
/**
* Store data. dataSet input parameter MUST be String
* Yoo may use
org.perfsonar.service.commons.storage.xmldb.StringDataQuery
+ *
* @param dataSet Must be String, contains XUpdate string
* @return null
*/
@Override
- public Object store(Object dataSet) throws PerfSONARException {
+ public Object store(Object dataSet) throws PerfSONARException
+ {
getLogger().debug("ExistDbXmlrpcXmlStorageManager: perform XUpdate");
@@ -211,17 +217,17 @@
String xupdateExpression;
try {
- xupdateExpression = (String)dataSet;
+ xupdateExpression = (String) dataSet;
} catch (ClassCastException ex) {
throw new
PerfSONARException("error.common.storage.xmldb.wrong_query",
- "ExistDbXmlrpcXmlStorageManager: This method accepts " +
+ "ExistDbXmlrpcXmlStorageManager: This method accepts " +
"StringData data format only");
}
- if (xupdateExpression==null) {
+ if (xupdateExpression == null) {
throw new
PerfSONARException("error.common.storage.xmldb.empty_query",
- "ExistDbXmlrpcXmlStorageManager: Input DataQuery " +
+ "ExistDbXmlrpcXmlStorageManager: Input DataQuery " +
"contains no data");
}
try {
@@ -229,8 +235,8 @@
connect();
XUpdateQueryService service =
-
(XUpdateQueryService)dataRepository.getExistCollection().getService(
- "XUpdateQueryService", "1.0");
+ (XUpdateQueryService)
dataRepository.getExistCollection().getService(
+ "XUpdateQueryService", "1.0");
service.setCollection(dataRepository.getExistCollection());
service.update(xupdateExpression);
@@ -239,7 +245,7 @@
} catch (XMLDBException e) {
throw new PerfSONARException("error.common.storage.xmldb.query",
- "ExistDbXmlrpcXmlStorageManager: Can't perform XUpdate:
"+e.getMessage());
+ "ExistDbXmlrpcXmlStorageManager: Can't perform XUpdate: " +
e.getMessage());
}
return null;
@@ -247,11 +253,13 @@
/**
* Check if keepConnection flag is set.
+ *
* @return true if the connection is persistent (common for all DB
requests),
* false if connection is established for each DB request and
then
* it's dropped
*/
- public boolean isKeepConnection() {
+ public boolean isKeepConnection()
+ {
return keepConnection;
@@ -260,12 +268,13 @@
/**
* Set keepConnection flag.
+ *
* @param keepConnection - true if the connection is persistent (common
for all DB requests),
- * false if connection is established for each
DB request and then
- * it's dropped
- *
+ * false if connection is established for each DB
request and then
+ * it's dropped
*/
- public void setKeepConnection(boolean keepConnection) {
+ public void setKeepConnection(boolean keepConnection)
+ {
this.keepConnection = keepConnection;
@@ -277,7 +286,8 @@
/**
* Connect if required
*/
- private void connect() throws PerfSONARException {
+ private void connect() throws PerfSONARException
+ {
if (!isConnected) {
@@ -290,9 +300,11 @@
/**
* Disconnect if required
+ *
* @throws PerfSONARException
*/
- private void disconnect() throws PerfSONARException {
+ private void disconnect() throws PerfSONARException
+ {
if ((isConnected) && (!keepConnection)) {
@@ -309,33 +321,34 @@
/*
* Run query test (XPath/XQuery)
*/
- private static void testQuery(StorageManager storageManager, String
xquery) throws PerfSONARException {
+ private static void testQuery(StorageManager storageManager, String
xquery) throws PerfSONARException
+ {
- String[] result = (String[])storageManager.fetch(
- xquery);
+ String[] result = (String[]) storageManager.fetch(
+ xquery);
- for (int i=0; i<result.length; i++) {
- System.out.println("Result["+i+"]: "+result[i]);
+ for (int i = 0; i < result.length; i++) {
+ System.out.println("Result[" + i + "]: " + result[i]);
}
}
-
// ---------------------------------------------------------- test
/*
* Simple test case. Just for testing
*/
- public static void main(String[] argv) throws Exception {
+ public static void main(String[] argv) throws Exception
+ {
//create Data Repository for Exist DB
ExistDbXmlrpcXmlDataRepository dataRepository = new
ExistDbXmlrpcXmlDataRepository(
- "xmldb:exist://localhost:8680/exist/xmlrpc/db/ls",
- "lookupservice",
- "sonar");
+ "xmldb:exist://localhost:8680/exist/xmlrpc/db/ls",
+ "lookupservice",
+ "sonar");
/*
@@ -355,9 +368,9 @@
storageManager.initStorage(dataRepository);
//run test cases
- testQuery(storageManager,"//nmwgt:hostName");
- testQuery(storageManager,"//nmwgt:ifName");
- testQuery(storageManager,"//nmwgt:ipAddress");
+ testQuery(storageManager, "//nmwgt:hostName");
+ testQuery(storageManager, "//nmwgt:ifName");
+ testQuery(storageManager, "//nmwgt:ipAddress");
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmlfile/XmlFileDataRepository.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmlfile/XmlFileDataRepository.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmlfile/XmlFileDataRepository.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -3,40 +3,48 @@
import org.perfsonar.base.exceptions.PerfSONARException;
import org.perfsonar.service.base.storage.DataRepository;
-public class XmlFileDataRepository implements DataRepository {
+public class XmlFileDataRepository implements DataRepository
+{
private static final String XML_FILE_TYPE = "xml.file";
private String path = null;
- public XmlFileDataRepository(String path) {
+ public XmlFileDataRepository(String path)
+ {
this.path = path;
}
@Override
- public void setType(String type) {
+ public void setType(String type)
+ {
}
@Override
- public String getType() {
+ public String getType()
+ {
return XML_FILE_TYPE;
}
@Override
- public void open() throws PerfSONARException {
+ public void open() throws PerfSONARException
+ {
}
@Override
- public void close() throws PerfSONARException {
+ public void close() throws PerfSONARException
+ {
}
- public String getPath() {
+ public String getPath()
+ {
return path;
}
- public void setPath(String path) {
+ public void setPath(String path)
+ {
this.path = path;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmlfile/XmlFileStorageManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmlfile/XmlFileStorageManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/storage/xmlfile/XmlFileStorageManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -26,7 +26,8 @@
import org.xml.sax.InputSource;
-public class XmlFileStorageManager implements StorageManager {
+public class XmlFileStorageManager implements StorageManager
+{
// ----------------------------------------------------- Instance
variables
@@ -43,13 +44,14 @@
*/
@Override
public void initStorage(DataRepository dataRepository)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
try {
- this.dataRepository = (XmlFileDataRepository)dataRepository;
+ this.dataRepository = (XmlFileDataRepository) dataRepository;
} catch (RuntimeException ex) {
throw new
PerfSONARException("error.common.storage.xml_file.init",
- "XmlFileStorageManager: not XmlFileDataRepository!");
+ "XmlFileStorageManager: not XmlFileDataRepository!");
}
}
@@ -57,21 +59,23 @@
/**
* Returns
+ *
* @param XPath expression as String
* @return String[] XML results
*/
@Override
public Object fetch(Object dataQuery)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
//check if string
String xpathQuery;
try {
- xpathQuery = (String)dataQuery;
+ xpathQuery = (String) dataQuery;
} catch (RuntimeException ex) {
//not a string
throw new PerfSONARException(
- "XmlFileStorageManager: not a String parameter!"
+ "XmlFileStorageManager: not a String parameter!"
);
}
@@ -97,18 +101,18 @@
// Evaluate the xpath expression
XPathResult result = (XPathResult) evaluator.evaluate(
- xpathQuery,
- doc,
- resolver,
- XPathResult.UNORDERED_NODE_ITERATOR_TYPE,
- null
+ xpathQuery,
+ doc,
+ resolver,
+ XPathResult.UNORDERED_NODE_ITERATOR_TYPE,
+ null
);
// Serialize the found nodes, store result in results as vector
// of Strings
Node n;
- while ((n = result.iterateNext())!= null) {
+ while ((n = result.iterateNext()) != null) {
StringBuffer outputBuffer = new StringBuffer();
OutputStream outputStream = new
StringBufferOutputStream(outputBuffer);
//XX if (isTextNode(n)) {
@@ -123,8 +127,8 @@
try {
serializer.transform(
- new DOMSource(n),
- new StreamResult(new
OutputStreamWriter(outputStream))
+ new DOMSource(n),
+ new StreamResult(new
OutputStreamWriter(outputStream))
);
results.add(outputBuffer.toString());
} catch (TransformerException e) {
@@ -135,8 +139,8 @@
//XX }
} catch (Exception ex) {
throw new PerfSONARException(
- "error.common.storage.xml_file.fetch",
- ex.getMessage());
+ "error.common.storage.xml_file.fetch",
+ ex.getMessage());
}
String[] stringResults = new String[results.size()];
@@ -148,20 +152,18 @@
}
-
/**
* UNIMPLEMENTED
*/
@Override
- public Object store(Object dataSet) throws PerfSONARException {
+ public Object store(Object dataSet) throws PerfSONARException
+ {
throw new PerfSONARException("not implemented");
}
-
-
// /**
// * Decide if the node is text, and so must be handled specially
// */
@@ -182,22 +184,23 @@
/*
* TEMPORARY
*/
- public static void main(String[] a) {
+ public static void main(String[] a)
+ {
System.out.println("STARTED");
XmlFileDataRepository dr = new XmlFileDataRepository(
// "/projects/sonar/perfsonar/conf/rrd-database_ESnet.xml");
// "/projects/sonar/perfsonar/conf/rrd-infoFile-GEANT.xml");
- "/projects/sonar/perfsonar/conf/rrd-database_Abilene.xml");
+ "/projects/sonar/perfsonar/conf/rrd-database_Abilene.xml");
System.out.println("Create StorageManager ");
XmlFileStorageManager sm = new XmlFileStorageManager();
System.out.println("Init StorageManager");
try {
sm.initStorage(dr);
System.out.println("Fetch...");
- String[] results =
(String[])sm.fetch("/perfsonar:store/nmwg:metadata");
- for (int i=0; i<results.length; i++)
- System.out.println("Result ["+i+"]: "+results[i]);
+ String[] results = (String[])
sm.fetch("/perfsonar:store/nmwg:metadata");
+ for (int i = 0; i < results.length; i++)
+ System.out.println("Result [" + i + "]: " + results[i]);
System.out.println("END");
} catch (Exception ex) {
ex.printStackTrace();
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/FileTransport.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/FileTransport.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/FileTransport.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -9,9 +9,9 @@
* Interface providing file transport interface methods.
*
* @author urosj
- *
*/
-public interface FileTransport {
+public interface FileTransport
+{
// ---------------------------------- public methods
@@ -21,8 +21,8 @@
* Copy file from source location to destination location.
*
* @param file name
- * @param src source location
- * @param dst destination location
+ * @param src source location
+ * @param dst destination location
* @throws Exception in case of error
*/
public void copy(String file, Location src, Location dst)
@@ -32,7 +32,7 @@
* Delete file at specified location.
*
* @param file name
- * @param loc location
+ * @param loc location
* @throws Exception in case of error
*/
public void delete(String file, Location loc)
@@ -42,7 +42,7 @@
* Check if file exists at specified remote location.
*
* @param file name
- * @param loc location
+ * @param loc location
* @return true if file exists, false otherwise
* @throws Exception in case of error
*/
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/FileTransportFactory.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/FileTransportFactory.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/FileTransportFactory.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -10,9 +10,9 @@
* FileTransport interface.
*
* @author urosj
- *
*/
-public class FileTransportFactory {
+public class FileTransportFactory
+{
// ---------------------------------- constants
@@ -41,28 +41,29 @@
*
* @param impl string representing FileTransport implementation
* (X from XFileTransport implementation class,
- * ssh for SSHFileTransport implementation)
+ * ssh for SSHFileTransport implementation)
* @return one of FileTransport imlementations
* @throws Exception if no such FileTransport implementation exists
* or implementation constructor throws Exception
*/
- public static FileTransport getFileTransport(String impl) throws
Exception {
+ public static FileTransport getFileTransport(String impl) throws
Exception
+ {
- for (Class<?> c: FILE_TRANSPORT_IMPLS) {
+ for (Class<?> c : FILE_TRANSPORT_IMPLS) {
String name = c.getName();
int n = name.lastIndexOf('.');
if (n != -1) {
- name = name.substring(n + 1);
+ name = name.substring(n + 1);
}
if (name.equalsIgnoreCase(impl + "FileTransport")) {
- return (FileTransport)c.newInstance();
+ return (FileTransport) c.newInstance();
}
}
throw new Exception(
"No implementation of FileTransport found for '"
- + impl + "'");
+ + impl + "'");
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/Location.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/Location.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/Location.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -10,21 +10,21 @@
* (Java Bean compatible)
*
* @author urosj
- *
*/
-public class Location implements java.io.Serializable {
+public class Location implements java.io.Serializable
+{
// ---------------------------------- class fields
/**
- *
- */
- private static final long serialVersionUID = 1L;
+ *
+ */
+ private static final long serialVersionUID = 1L;
- /**
+ /**
* Address (IP, Host, e-mail, ....)
* (optional, if null, local location is assumed).
*/
@@ -44,7 +44,7 @@
/**
* Username (optional username used for accessing remote address,
- * null if not used)
+ * null if not used)
*/
private String username = null;
@@ -55,7 +55,8 @@
/**
* Empty constructor.
*/
- public Location() {
+ public Location()
+ {
}
@@ -64,7 +65,8 @@
*
* @param path
*/
- public Location(String path) {
+ public Location(String path)
+ {
this.path = path;
@@ -79,7 +81,8 @@
*
* @param address
*/
- public void setAddress(String address) {
+ public void setAddress(String address)
+ {
this.address = address;
@@ -91,7 +94,8 @@
*
* @return address
*/
- public String getAddress() {
+ public String getAddress()
+ {
return this.address;
@@ -103,7 +107,8 @@
*
* @param path
*/
- public void setPath(String path) {
+ public void setPath(String path)
+ {
this.path = path;
@@ -115,7 +120,8 @@
*
* @return path
*/
- public String getPath() {
+ public String getPath()
+ {
return this.path;
@@ -127,7 +133,8 @@
*
* @param port
*/
- public void setPort(Integer port) {
+ public void setPort(Integer port)
+ {
this.port = port;
@@ -139,7 +146,8 @@
*
* @return port
*/
- public Integer getPort() {
+ public Integer getPort()
+ {
return this.port;
@@ -151,7 +159,8 @@
*
* @param username
*/
- public void setUsername(String username) {
+ public void setUsername(String username)
+ {
this.username = username;
@@ -163,7 +172,8 @@
*
* @return username
*/
- public String getUsername() {
+ public String getUsername()
+ {
return username;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/SSHFileTransport.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/SSHFileTransport.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/transport/SSHFileTransport.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -16,9 +16,9 @@
* Class implementing FileTransport interface using SSH protocol.
*
* @author urosj
- *
*/
-public class SSHFileTransport implements FileTransport {
+public class SSHFileTransport implements FileTransport
+{
// ---------------------------------- constants
@@ -54,13 +54,14 @@
* Copy file from source location to destination location.
*
* @param file name
- * @param src source location
- * @param dst destination location
+ * @param src source location
+ * @param dst destination location
* @throws Exception in case of error
*/
@Override
public void copy(String file, Location src, Location dst)
- throws Exception {
+ throws Exception
+ {
byte[] buf = new byte[8192];
@@ -90,16 +91,16 @@
String localFilePath =
src.getPath()
- + System.getProperty("file.separator")
- + file;
+ + System.getProperty("file.separator")
+ + file;
String remoteFilePath =
dst.getPath()
- + System.getProperty("file.separator")
- + file;
+ + System.getProperty("file.separator")
+ + file;
String remoteAddress =
(dst.getUsername() == null ? "" :
- (dst.getUsername() + "@"))
- + dst.getAddress();
+ (dst.getUsername() + "@"))
+ + dst.getAddress();
// Open local file for reading
FileInputStream fin = new FileInputStream(localFilePath);
@@ -138,23 +139,23 @@
if (ssh.exitValue() != 0)
throw new Exception(
"Error copying local file, exit code "
- + ssh.exitValue());
+ + ssh.exitValue());
- // Destination file is local
+ // Destination file is local
} else if (dst.getAddress() == null) {
String remoteFilePath =
src.getPath()
- + System.getProperty("file.separator")
- + file;
+ + System.getProperty("file.separator")
+ + file;
String remoteAddress =
(src.getUsername() == null ? "" :
- (src.getUsername() + "@"))
- + src.getAddress();
+ (src.getUsername() + "@"))
+ + src.getAddress();
String localFilePath =
dst.getPath()
- + System.getProperty("file.separator")
- + file;
+ + System.getProperty("file.separator")
+ + file;
// Open local file for writing
FileOutputStream fout = new FileOutputStream(localFilePath);
@@ -199,7 +200,7 @@
throw new Exception(
"Error copying remote file, exit code "
- + ssh.exitValue());
+ + ssh.exitValue());
}
}
@@ -210,12 +211,13 @@
* Delete file at specified location.
*
* @param file name
- * @param loc location
+ * @param loc location
* @throws Exception in case of error
*/
@Override
public void delete(String file, Location loc)
- throws Exception {
+ throws Exception
+ {
// Simple verifications
// * file must not be null
@@ -232,12 +234,12 @@
String remoteFilePath =
loc.getPath()
- + System.getProperty("file.separator")
- + file;
+ + System.getProperty("file.separator")
+ + file;
String remoteAddress =
(loc.getUsername() == null ? "" :
- (loc.getUsername() + "@"))
- + loc.getAddress();
+ (loc.getUsername() + "@"))
+ + loc.getAddress();
ArrayList<String> cmdArgs = new ArrayList<String>();
cmdArgs.add(SSH_EXEC);
@@ -263,7 +265,7 @@
if (ssh.exitValue() != 0)
throw new Exception(
"Error removing remote file, exit code "
- + ssh.exitValue());
+ + ssh.exitValue());
}
@@ -272,13 +274,14 @@
* Check if file exists at specified remote location.
*
* @param file name
- * @param loc location
+ * @param loc location
* @return true if file exists, false otherwise
* @throws Exception in case of error
*/
@Override
public boolean exists(String file, Location loc)
- throws Exception {
+ throws Exception
+ {
byte[] buf = new byte[8192];
@@ -297,12 +300,12 @@
String remoteFilePath =
loc.getPath()
- + System.getProperty("file.separator")
- + file;
+ + System.getProperty("file.separator")
+ + file;
String remoteAddress =
(loc.getUsername() == null ? "" :
- (loc.getUsername() + "@"))
- + loc.getAddress();
+ (loc.getUsername() + "@"))
+ + loc.getAddress();
ArrayList<String> cmdArgs = new ArrayList<String>();
cmdArgs.add(SSH_EXEC);
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/util/ResultCodesUtil.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/util/ResultCodesUtil.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/util/ResultCodesUtil.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -14,33 +14,34 @@
*
* @author Maciej Glowiak
*/
-public class ResultCodesUtil {
+public class ResultCodesUtil
+{
-
/**
* Create Metadata element containing result code and (optional)
* reference to other metadata
*
- * @param metadataId Identifier of result code metadata. If null, the
default one will be used
+ * @param metadataId Identifier of result code metadata. If null,
the default one will be used
* @param parentMetadataId Identifier of metadata to be refferred to. If
null, no parent metadata will be used.
- * @param resultCode Textual value of result code.
+ * @param resultCode Textual value of result code.
* @return Metadata element
*/
public static Metadata createResultCodeMetadata(
- String metadataId,
- String parentMetadataIdRef,
- String resultCode) {
+ String metadataId,
+ String parentMetadataIdRef,
+ String resultCode)
+ {
- Metadata metadata = new Metadata();
- if (metadataId==null) metadataId="resultCodeMetadata";
+ Metadata metadata = new Metadata();
+ if (metadataId == null) metadataId = "resultCodeMetadata";
metadata.setId(metadataId);
EventType eventType = new EventType();
eventType.setEventType(resultCode);
metadata.setEventType(eventType);
- if (parentMetadataIdRef!=null) {
+ if (parentMetadataIdRef != null) {
Subject subject = new Subject();
subject.setMetadataIdRef(parentMetadataIdRef);
subject.setId("referenceToMetadata");
@@ -53,19 +54,19 @@
/**
- *
* @param dataId
* @param metadataId
* @param resultDescription
* @return
*/
public static Data createResultDescriptionData(
- String dataId,
- String metadataIdRef,
- String resultDescription) {
+ String dataId,
+ String metadataIdRef,
+ String resultDescription)
+ {
Data data = new Data();
- if (dataId==null) dataId="resultDescriptionData";
+ if (dataId == null) dataId = "resultDescriptionData";
data.setId(dataId);
data.setMetadataIdRef(metadataIdRef);
@@ -83,38 +84,39 @@
* and puts it into given Message object. If given Message is null
* new Message object will be created
*
- * @param message object where to put result code
- * @param pex perfsonar exception containing result code and description
+ * @param message object where to put result code
+ * @param pex perfsonar exception containing result code
and description
* @param parentMetadataIdRef reference to other metadata
* @return
*/
public static Message createResultCodeMetadata(
- Message message,
- PerfSONARException pex,
- String parentMetadataIdRef) {
+ Message message,
+ PerfSONARException pex,
+ String parentMetadataIdRef)
+ {
//metadata
String metadataId;
- if (parentMetadataIdRef!=null)
- metadataId="resultCodeMetadata_for_"+parentMetadataIdRef;
- else metadataId="resultCodeMetadata";
+ if (parentMetadataIdRef != null)
+ metadataId = "resultCodeMetadata_for_" + parentMetadataIdRef;
+ else metadataId = "resultCodeMetadata";
Metadata metadata = createResultCodeMetadata(
- metadataId,
- parentMetadataIdRef,
- pex.getResultCode());
+ metadataId,
+ parentMetadataIdRef,
+ pex.getResultCode());
//data
String dataId;
- dataId="resultDescriptionData_for_"+metadataId;
+ dataId = "resultDescriptionData_for_" + metadataId;
- Data data =
createResultDescriptionData(dataId,metadataId,pex.getResultDescription());
+ Data data = createResultDescriptionData(dataId, metadataId,
pex.getResultDescription());
//create new Message if necessary
- if (message==null) {
- message=new Message();
+ if (message == null) {
+ message = new Message();
message.setId("resultCodeMessage");
}
@@ -129,19 +131,19 @@
* Converts PerfSONARException into metadata+data result code block
* and puts it into given Message object
*
- * @param message object where to put result code
- * @param pex perfsonar exception containing result code and description
+ * @param message object where to put result code
+ * @param pex perfsonar exception containing result code
and description
* @param parentMetadataIdRef reference to other metadata
* @return
*/
public static Message createResultCodeMetadata(
- Message message,
- PerfSONARException pex) {
+ Message message,
+ PerfSONARException pex)
+ {
return createResultCodeMetadata(message, pex, null);
}
-
} //ResultCodesUtil
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/web/RequestHandler.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/web/RequestHandler.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/base/web/RequestHandler.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -30,7 +30,8 @@
* @author Maciej Glowiak
* @author Michael Bischoff
*/
-public class RequestHandler {
+public class RequestHandler
+{
private static final String INIT_SERVICE_MESSAGE_TYPE = "InitService";
private static final String SAX_PARSER_CONFIG =
"service.sax_parser.config";
@@ -39,252 +40,274 @@
private ConfigurationComponent configuration;
private LoggerComponent logger;
private AuthNComponent authnComponent;
- private String saxParserConfig;
-
- private volatile boolean initialised = false;
- private final Object initialisationMutex = new Object();
+ private String saxParserConfig;
+ private volatile boolean initialised = false;
+ private final Object initialisationMutex = new Object();
+
/**
- * Accepts web service based calls and gives back responses
+ * Accepts web service based calls and gives back responses
*
- * @param request org.w3c.dom.Document which contains the XML request
- *
- * @return org.w3c.dom.Document response provided by the service
+ * @param request org.w3c.dom.Document which contains the XML request
+ * @return org.w3c.dom.Document response provided by the service
*/
- public Document acceptCall(Document request) {
- try {
- if(!initialised) init();
- checkAuxiliaryComponents();
- return handleCall(request);
+ public Document acceptCall(Document request)
+ {
+ try {
+ if (!initialised) init();
+ checkAuxiliaryComponents();
+ return handleCall(request);
} catch (PerfSONARException pex) {
- return handleError(pex);
+ return handleError(pex);
}
}
- /**
- * initializes this RequestHandler by creating and retrieving Aux
components
- * @throws PerfSONARException
- */
- protected void init() throws PerfSONARException {
- synchronized (initialisationMutex) {
- if(!initialised) {
- componentManager =
AuxiliaryComponentManager.getInstance();
- configuration =
(ConfigurationComponent)componentManager.getComponent(ComponentNames.CONFIG);
- logger =
(LoggerComponent)componentManager.getComponent(ComponentNames.LOGGER);
- initialised = true;
- }
- }
- }
- /**
- * handles the call: convert the request and calls a
handleRequestMessage and returns the result.
- * @param request
- * @return a document
- * @throws PerfSONARException
- */
- protected Document handleCall(Document request) throws
PerfSONARException {
- long startTime = System.currentTimeMillis();
- String messageType = null;
+
+ /**
+ * initializes this RequestHandler by creating and retrieving Aux
components
+ *
+ * @throws PerfSONARException
+ */
+ protected void init() throws PerfSONARException
+ {
+ synchronized (initialisationMutex) {
+ if (!initialised) {
+ componentManager = AuxiliaryComponentManager.getInstance();
+ configuration = (ConfigurationComponent)
componentManager.getComponent(ComponentNames.CONFIG);
+ logger = (LoggerComponent)
componentManager.getComponent(ComponentNames.LOGGER);
+ initialised = true;
+ }
+ }
+ }
+
+ /**
+ * handles the call: convert the request and calls a
handleRequestMessage and returns the result.
+ *
+ * @param request
+ * @return a document
+ * @throws PerfSONARException
+ */
+ protected Document handleCall(Document request) throws PerfSONARException
+ {
+ long startTime = System.currentTimeMillis();
+ String messageType = null;
String messageId = null;
-
- try {
- logger.info("RequestHandler: Service received a
request");
- logger.debug("RequestHandler: Calling on parser to
parse the request");
-
- Message requestMessage = convertMessage(request);
- checkMessage(requestMessage);
- messageType = requestMessage.getType();
- messageId = requestMessage.getId();
-
- logger.debug("RequestHandler: Message object
constructed from request. Request is of type: " + requestMessage.getType());
- /* Check if it isn't just an InitService message */
- if
(INIT_SERVICE_MESSAGE_TYPE.equalsIgnoreCase(requestMessage.getType())) {
- return handleInitServiceMessage(requestMessage);
- }
-
- assertAuthentication(requestMessage);
- return handleRequestMessage(requestMessage);
- } finally {
- logExecutionTime(startTime , messageId, messageType);
- }
- }
- /**
- * Called when any error occurred, response with result/error code
- * @param exception the error
- * @return Document containing error information.
- */
- protected Document handleError(PerfSONARException exception) {
-
-
- //create common result code with ErrorResponse
- Message responseMessage =
ResultCodesUtil.createResultCodeMetadata(null, exception);
- responseMessage.setType("ErrorResponse");
-
- //convert it into Document
- Document responseDocument = null;
- try {
- responseDocument =
XMLUtils.convertMessageToDOM(responseMessage);
- } catch (PerfSONARException e) {
- //Critical error, cannot convert message to DOM;
- // - parsing error of Error Response, shouldn't happen
- logger.fatal(
- "RequestHandler: Return null response - can
neither create " +
- "response message nor error code message!"
- );
- }
- logger.info("RequestHandler: Service sent a response with
error information");
- return responseDocument;
- }
- /**
- * handles a Init-Service Message.
- * TODO this should probably return a normal document instead of it
being an exception
- * @return document to return
- * @throws PerfSONARException
- */
- protected Document handleInitServiceMessage(Message requestMessage)
throws PerfSONARException {
- //if so, response that service was set up correctly
- throw new PerfSONARException(
- "service.common.success",
- "Service initialized correctly"
- );
- }
- protected Document handleRequestMessage(Message requestMessage)
throws PerfSONARException {
- // Call on the MessageHandlerFactory to get the appropriate
- // message handler for this type of message.
- MessageHandler messageHandler =
MessageHandlerFactory.getMessageHandler(requestMessage.getType());
+ try {
+ logger.info("RequestHandler: Service received a request");
+ logger.debug("RequestHandler: Calling on parser to parse the
request");
- logger.debug("RequestHandler: Calling on MessageHandler
["+messageHandler.getClass()+"] to satisfy request");
+ Message requestMessage = convertMessage(request);
+ checkMessage(requestMessage);
+ messageType = requestMessage.getType();
+ messageId = requestMessage.getId();
- // Call on the messageHandler to "execute" the message and
return a response message.
- // run proper message handler, which will run ServiceEngine
- //****************************************************
-
- Message responseMessage =
messageHandler.execute(requestMessage);
-
- //*****************************************************
+ logger.debug("RequestHandler: Message object constructed from
request. Request is of type: " + requestMessage.getType());
+ /* Check if it isn't just an InitService message */
+ if
(INIT_SERVICE_MESSAGE_TYPE.equalsIgnoreCase(requestMessage.getType())) {
+ return handleInitServiceMessage(requestMessage);
+ }
- // convert response Message into Document
- Document responseDocument =
XMLUtils.convertMessageToDOM(responseMessage);
+ assertAuthentication(requestMessage);
+ return handleRequestMessage(requestMessage);
+ } finally {
+ logExecutionTime(startTime, messageId, messageType);
+ }
+ }
- logger.info("RequestHandler: Service sent a successful
response");
- return responseDocument;
- }
-
- protected void checkAuxiliaryComponents() throws PerfSONARException {
- if (configuration == null) throw new PerfSONARException(
- "error.common.no_configuration",
- "Cannot read configuration file"
- );
- if (logger == null) throw new PerfSONARException(
- "error.common.no_logger",
- "Cannot find logger component"
- );
- }
- /**
- * Checks if something went wrong with parsing
- * @param requestMessage
- * @throws PerfSONARException if the requestMessage is invalid
- */
- protected void checkMessage(Message requestMessage) throws
PerfSONARException {
- if (requestMessage==null) {
- logger.error("RequestHandler: Message object constructed
as null from request");
- throw new PerfSONARException(
- "error.common.parse_error",
- "RequestHandler: Server could not construct a
message object from " +
- "the request due to unknown error. Please check
request and try again"
- );
- }
- }
+ /**
+ * Called when any error occurred, response with result/error code
+ *
+ * @param exception the error
+ * @return Document containing error information.
+ */
+ protected Document handleError(PerfSONARException exception)
+ {
- protected void assertAuthentication(Message requestMessage) throws
PerfSONARException {
- // Check if it's needed authorization for this type of message
- String checkAuthRParam;
- try {
-
checkAuthRParam=configuration.getProperty(AuthNComponent.CHECK_AUTHR_PARAM);
- } catch (PerfSONARException e) {
- checkAuthRParam=null;
- }
- if
(checkAuthRParam!=null&&checkAuthRParam.equals(AuthNComponent.YES_CHECK_AUTHN))
{
- logger.debug("RequestHandler: Authorizating the
message");
- if (authnComponent == null) {
- authnComponent =
(AuthNComponent)componentManager.getComponent(ComponentNames.AUTHN);
- }
-
authnComponent.requestAuthR(requestMessage.getType(),null);
- } else {
- // Check if it's needed authentication for this type of
message
- String checkAuthNParam;
- try {
-
checkAuthNParam=configuration.getProperty(AuthNComponent.CHECK_AUTHN_PARAM);
- } catch (PerfSONARException e) {
- checkAuthNParam=null;
- }
- if
(checkAuthNParam!=null&&checkAuthNParam.equals(AuthNComponent.YES_CHECK_AUTHN))
{
- logger.debug("RequestHandler: Authenticating
the message");
- if (authnComponent == null) {
- authnComponent =
(AuthNComponent)componentManager.getComponent(ComponentNames.AUTHN);
- }
-
authnComponent.requestAuthN(requestMessage.getType());
- } else {
- logger.debug("RequestHandler: Automated
authentication not required");
- }
- }
- }
-
- /**
- * Converts a Document to a Message
- * @param request
- * @return a converted requestMessage or null on failure
- * @throws PerfSONARException
- */
- protected Message convertMessage(Document request) throws
PerfSONARException {
- Message requestMessage;
- try {
- if(saxParserConfig == null) {
- saxParserConfig =
attemptSaxParserConfigLookup();
- }
- logger.debug("Using file: "+saxParserConfig+" as
SAX_PARSER_CONFIG");
- requestMessage = XMLUtils.convertToMessage(request,
saxParserConfig);
- } catch (Exception e) {
- throw new PerfSONARException(
- "error.common.parse_error",
- "Parse/validation error, Cannot convert request to
Message.",
- e
- );
- }
- return requestMessage;
- }
-
- private String attemptSaxParserConfigLookup() throws
PerfSONARException {
- String config;
-
- try {
- config = configuration.getProperty(SAX_PARSER_CONFIG);
- } catch (PerfSONARException e) {
- logger.error("Sax parser config could not be found.
(service.sax_parser.config not specified.)");
- throw e;
- }
-
- File file = AuxiliaryComponentManager.lookupFile(config);
- if(file!=null) {
- return file.getAbsolutePath();
- }
- logger.error("Sax parser config could not be found. (lookup
failed for: "+config+" )");
- throw new PerfSONARException(
- "error.common.no_configuration",
- "specified service.sax_parser.config not found"
- );
- }
+ //create common result code with ErrorResponse
+ Message responseMessage =
ResultCodesUtil.createResultCodeMetadata(null, exception);
+ responseMessage.setType("ErrorResponse");
+ //convert it into Document
+ Document responseDocument = null;
+ try {
+ responseDocument = XMLUtils.convertMessageToDOM(responseMessage);
+ } catch (PerfSONARException e) {
+ //Critical error, cannot convert message to DOM;
+ // - parsing error of Error Response, shouldn't happen
+ logger.fatal(
+ "RequestHandler: Return null response - can neither create "
+
+ "response message nor error code message!"
+ );
+ }
+ logger.info("RequestHandler: Service sent a response with error
information");
+ return responseDocument;
+ }
+
/**
+ * handles a Init-Service Message.
+ * TODO this should probably return a normal document instead of it
being an exception
+ *
+ * @return document to return
+ * @throws PerfSONARException
+ */
+ protected Document handleInitServiceMessage(Message requestMessage)
throws PerfSONARException
+ {
+ //if so, response that service was set up correctly
+ throw new PerfSONARException(
+ "service.common.success",
+ "Service initialized correctly"
+ );
+ }
+
+ protected Document handleRequestMessage(Message requestMessage) throws
PerfSONARException
+ {
+ // Call on the MessageHandlerFactory to get the appropriate
+ // message handler for this type of message.
+ MessageHandler messageHandler =
MessageHandlerFactory.getMessageHandler(requestMessage.getType());
+
+ logger.debug("RequestHandler: Calling on MessageHandler [" +
messageHandler.getClass() + "] to satisfy request");
+
+ // Call on the messageHandler to "execute" the message and return a
response message.
+ // run proper message handler, which will run ServiceEngine
+ //****************************************************
+
+ Message responseMessage = messageHandler.execute(requestMessage);
+
+ //*****************************************************
+
+ // convert response Message into Document
+ Document responseDocument =
XMLUtils.convertMessageToDOM(responseMessage);
+
+ logger.info("RequestHandler: Service sent a successful response");
+ return responseDocument;
+ }
+
+ protected void checkAuxiliaryComponents() throws PerfSONARException
+ {
+ if (configuration == null) throw new PerfSONARException(
+ "error.common.no_configuration",
+ "Cannot read configuration file"
+ );
+ if (logger == null) throw new PerfSONARException(
+ "error.common.no_logger",
+ "Cannot find logger component"
+ );
+ }
+
+ /**
+ * Checks if something went wrong with parsing
+ *
+ * @param requestMessage
+ * @throws PerfSONARException if the requestMessage is invalid
+ */
+ protected void checkMessage(Message requestMessage) throws
PerfSONARException
+ {
+ if (requestMessage == null) {
+ logger.error("RequestHandler: Message object constructed as null
from request");
+ throw new PerfSONARException(
+ "error.common.parse_error",
+ "RequestHandler: Server could not construct a message object
from " +
+ "the request due to unknown error. Please check request
and try again"
+ );
+ }
+ }
+
+ protected void assertAuthentication(Message requestMessage) throws
PerfSONARException
+ {
+ // Check if it's needed authorization for this type of message
+ String checkAuthRParam;
+ try {
+ checkAuthRParam =
configuration.getProperty(AuthNComponent.CHECK_AUTHR_PARAM);
+ } catch (PerfSONARException e) {
+ checkAuthRParam = null;
+ }
+ if (checkAuthRParam != null &&
checkAuthRParam.equals(AuthNComponent.YES_CHECK_AUTHN)) {
+ logger.debug("RequestHandler: Authorizating the message");
+ if (authnComponent == null) {
+ authnComponent = (AuthNComponent)
componentManager.getComponent(ComponentNames.AUTHN);
+ }
+ authnComponent.requestAuthR(requestMessage.getType(), null);
+ } else {
+ // Check if it's needed authentication for this type of message
+ String checkAuthNParam;
+ try {
+ checkAuthNParam =
configuration.getProperty(AuthNComponent.CHECK_AUTHN_PARAM);
+ } catch (PerfSONARException e) {
+ checkAuthNParam = null;
+ }
+ if (checkAuthNParam != null &&
checkAuthNParam.equals(AuthNComponent.YES_CHECK_AUTHN)) {
+ logger.debug("RequestHandler: Authenticating the message");
+ if (authnComponent == null) {
+ authnComponent = (AuthNComponent)
componentManager.getComponent(ComponentNames.AUTHN);
+ }
+ authnComponent.requestAuthN(requestMessage.getType());
+ } else {
+ logger.debug("RequestHandler: Automated authentication not
required");
+ }
+ }
+ }
+
+ /**
+ * Converts a Document to a Message
+ *
+ * @param request
+ * @return a converted requestMessage or null on failure
+ * @throws PerfSONARException
+ */
+ protected Message convertMessage(Document request) throws
PerfSONARException
+ {
+ Message requestMessage;
+ try {
+ if (saxParserConfig == null) {
+ saxParserConfig = attemptSaxParserConfigLookup();
+ }
+ logger.debug("Using file: " + saxParserConfig + " as
SAX_PARSER_CONFIG");
+ requestMessage = XMLUtils.convertToMessage(request,
saxParserConfig);
+ } catch (Exception e) {
+ throw new PerfSONARException(
+ "error.common.parse_error",
+ "Parse/validation error, Cannot convert request to Message.",
+ e
+ );
+ }
+ return requestMessage;
+ }
+
+ private String attemptSaxParserConfigLookup() throws PerfSONARException
+ {
+ String config;
+
+ try {
+ config = configuration.getProperty(SAX_PARSER_CONFIG);
+ } catch (PerfSONARException e) {
+ logger.error("Sax parser config could not be found.
(service.sax_parser.config not specified.)");
+ throw e;
+ }
+
+ File file = AuxiliaryComponentManager.lookupFile(config);
+ if (file != null) {
+ return file.getAbsolutePath();
+ }
+ logger.error("Sax parser config could not be found. (lookup failed
for: " + config + " )");
+ throw new PerfSONARException(
+ "error.common.no_configuration",
+ "specified service.sax_parser.config not found"
+ );
+ }
+
+
+ /**
* Print out time of execution (to log)
+ *
* @param startTime
* @param messageType
* @param messageId
- *
*/
- private void logExecutionTime(long startTime, String messageId, String
messageType) {
+ private void logExecutionTime(long startTime, String messageId, String
messageType)
+ {
long time = System.currentTimeMillis() - startTime;
- logger.info(String.format("Execution Time of message type=[%s]
id=[%s] is [%3$tM]min [%3$tS]secs [%3$tL]milisec", messageType,
messageId,Long.valueOf(time)));
+ logger.info(String.format("Execution Time of message type=[%s]
id=[%s] is [%3$tM]min [%3$tS]secs [%3$tL]milisec", messageType, messageId,
Long.valueOf(time)));
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventType.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventType.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventType.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -6,20 +6,19 @@
/**
- * Implementation of xml element of conf/eventType-map.xml file.
- * This class is be used by digester library to read the configuration
- * from that file.
+ * Implementation of xml element of conf/eventType-map.xml file.
+ * This class is be used by digester library to read the configuration
+ * from that file.
*
- * @author romradz
+ * @author romradz
*/
-public class EventType {
+public class EventType
+{
-
// -------------------------------------- class fields
-
private String name = null;
private String metadataQueryGenerator = null;
private String metadaKeyGenerator = null;
@@ -29,86 +28,99 @@
private String ibatisConfig = null;
-
// -------------------------------------- constructors
- public EventType() {
+ public EventType()
+ {
}
//-------------------------------------- public methods
- public void setName(String name) {
+ public void setName(String name)
+ {
this.name = name;
}
- public String getName() {
+ public String getName()
+ {
return name;
}
- public void setMetadataQueryGenerator(String metadataQueryGenerator) {
+ public void setMetadataQueryGenerator(String metadataQueryGenerator)
+ {
this.metadataQueryGenerator = metadataQueryGenerator;
}
- public String getMetadataQueryGenerator() {
+ public String getMetadataQueryGenerator()
+ {
return metadataQueryGenerator;
}
- public void setMetadataKeyGenerator(String metadaKeyGenerator) {
+ public void setMetadataKeyGenerator(String metadaKeyGenerator)
+ {
this.metadaKeyGenerator = metadaKeyGenerator;
}
- public String getMetadataKeyGenerator() {
+ public String getMetadataKeyGenerator()
+ {
return metadaKeyGenerator;
}
- public void setResponseGenerator(String responseGenerator) {
+ public void setResponseGenerator(String responseGenerator)
+ {
this.responseGenerator = responseGenerator;
}
- public String getResponseGenerator() {
+ public String getResponseGenerator()
+ {
return responseGenerator;
}
- public void setStoreRequestProcess(String storeRequestProcess) {
+ public void setStoreRequestProcess(String storeRequestProcess)
+ {
this.storeRequestProcess = storeRequestProcess;
}
- public String getStoreRequestProcess() {
+ public String getStoreRequestProcess()
+ {
return storeRequestProcess;
}
- public void setBaseChainingMerger(String baseChainingMerger) {
+ public void setBaseChainingMerger(String baseChainingMerger)
+ {
this.baseChainingMerger = baseChainingMerger;
}
- public String getBaseChainingMerger() {
+ public String getBaseChainingMerger()
+ {
return baseChainingMerger;
}
- public String getIbatisConfig() {
+ public String getIbatisConfig()
+ {
return ibatisConfig;
}
- public void setIbatisConfig(String ibatisConfig) {
+ public void setIbatisConfig(String ibatisConfig)
+ {
this.ibatisConfig = ibatisConfig;
}
-
} //EventType
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventTypeConfiguration.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventTypeConfiguration.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventTypeConfiguration.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -9,36 +9,41 @@
import java.util.Map;
/**
- * Container of EventType objects which are specified
- * in the configuration file conf/eventType-map.xml.
- * The object of this class is created by digester library
- * after that configuaration file is read.
+ * Container of EventType objects which are specified
+ * in the configuration file conf/eventType-map.xml.
+ * The object of this class is created by digester library
+ * after that configuaration file is read.
*
- * @author romradz
+ * @author romradz
*/
-public class EventTypeConfiguration {
+public class EventTypeConfiguration
+{
// -------------------------------------- class fields
- private Map<String,EventType> eventTypeMap = null;
+ private Map<String, EventType> eventTypeMap = null;
// -------------------------------------- constructors
- public EventTypeConfiguration() {
- eventTypeMap = new HashMap<String,EventType>();
+ public EventTypeConfiguration()
+ {
+ eventTypeMap = new HashMap<String, EventType>();
}
//-------------------------------------- public methods
- public void setEventType(EventType eventType) {
+ public void setEventType(EventType eventType)
+ {
eventTypeMap.put(eventType.getName(), eventType);
}
- public EventType getEventType(String name) {
+ public EventType getEventType(String name)
+ {
return eventTypeMap.get(name);
}
- public Map<String,EventType> getEventTypeMap() {
+ public Map<String, EventType> getEventTypeMap()
+ {
return eventTypeMap;
}
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventTypeConfigurationComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventTypeConfigurationComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/eventTypeConfig/EventTypeConfigurationComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -21,22 +21,21 @@
/**
- * Auxiliary component that keeps the configuration
- * about eventTypes (nmwg element) supported by the service.
- * The configuration is stored in conf/eventType-map.xml
- * file.
+ * Auxiliary component that keeps the configuration
+ * about eventTypes (nmwg element) supported by the service.
+ * The configuration is stored in conf/eventType-map.xml
+ * file.
*
- * @author romradz
+ * @author romradz
*/
public class EventTypeConfigurationComponent
- implements AuxiliaryComponent {
+ implements AuxiliaryComponent
+{
-
//-------------------------------------------- class fields
-
private String digesterRules = "perfsonar/conf/eventType-rules.xml";
private String digesterInput = "perfsonar/conf/eventType-map.xml";
@@ -48,25 +47,24 @@
private EventTypeConfiguration eventTypeConfiguration = null;
-
//---------------------------------- constructors
+ public EventTypeConfigurationComponent() throws PerfSONARException
+ {
- public EventTypeConfigurationComponent() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "EventTypeConfigurationComponent.initComponent: "
+ "error.common.no_logger",
+ "EventTypeConfigurationComponent.initComponent: "
+ "Cannot get logger component");
}
@@ -74,13 +72,12 @@
}
-
// ---------------------------------- public methods
-
@Override
- public void initComponent() throws PerfSONARException {
+ public void initComponent() throws PerfSONARException
+ {
// getting configuration data using commons digester
@@ -90,14 +87,14 @@
digesterRulesURL = Resources.getResourceURL(digesterRules);
} catch (IOException ioex) {
logger.debug("EventTypeConfigurationComponent.initComponent: "
- + ioex.toString());
+ + ioex.toString());
}
if (digesterRulesURL == null) {
logger.debug("EventTypeConfigurationComponent.initComponent: "
- + "Could not find xml config file " + digesterRules);
+ + "Could not find xml config file " + digesterRules);
throw new PerfSONARException(
- "error.common",
- "EventTypeConfigurationComponent.initComponent: "
+ "error.common",
+ "EventTypeConfigurationComponent.initComponent: "
+ "Could not find xml config file " + digesterRules);
}
@@ -107,14 +104,14 @@
digesterInputStream =
Resources.getResourceAsStream(digesterInput);
} catch (IOException ioex) {
logger.debug("EventTypeConfigurationComponent.initComponent: "
- + ioex.toString());
+ + ioex.toString());
}
if (digesterInputStream == null) {
logger.debug("EventTypeConfigurationComponent.initComponent: "
- + "Could not find xml file " + digesterInput);
+ + "Could not find xml file " + digesterInput);
throw new PerfSONARException(
- "error.common",
- "EventTypeConfigurationComponent.initComponent: "
+ "error.common",
+ "EventTypeConfigurationComponent.initComponent: "
+ "Could not create an input stream of xml config file "
+ digesterInput);
}
@@ -134,11 +131,11 @@
} catch (Exception ex) {
logger.debug("EventTypeConfigurationComponent.initComponent: "
- + "Could not parse " + digesterInput
- + ": " + ex.toString());
+ + "Could not parse " + digesterInput
+ + ": " + ex.toString());
throw new PerfSONARException(
- "error.common",
- "EventTypeConfigurationComponent.initComponent: "
+ "error.common",
+ "EventTypeConfigurationComponent.initComponent: "
+ "Could not parse " + digesterInput);
}
@@ -147,7 +144,8 @@
@Override
- public String getComponentName() {
+ public String getComponentName()
+ {
return componentName;
@@ -155,26 +153,28 @@
@Override
- public void setComponentName(String name) {
+ public void setComponentName(String name)
+ {
componentName = name;
}
- public EventType getEventType(String name) {
+ public EventType getEventType(String name)
+ {
return eventTypeConfiguration.getEventType(name);
}
- public EventTypeConfiguration getEventTypeConfiguration() {
+ public EventTypeConfiguration getEventTypeConfiguration()
+ {
- return eventTypeConfiguration;
+ return eventTypeConfiguration;
}
-
} //EventTypeConfigurationComponent
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/MetadataConfigurationStorageManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/MetadataConfigurationStorageManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/MetadataConfigurationStorageManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -32,11 +32,12 @@
/**
- * This class contains methods to manage metadata configuration data.
+ * This class contains methods to manage metadata configuration data.
*
- * @author romradz
+ * @author romradz
*/
-public class MetadataConfigurationStorageManager implements
NMWGStorageManager {
+public class MetadataConfigurationStorageManager implements
NMWGStorageManager
+{
// -------------------------------------- class fields
@@ -54,7 +55,8 @@
// -------------------------------------- constructors
- public MetadataConfigurationStorageManager() throws PerfSONARException {
+ public MetadataConfigurationStorageManager() throws PerfSONARException
+ {
this.logger = getLogger();
this.configuration = getConfiguration();
@@ -69,7 +71,8 @@
@Override
- public void initStorage(Key dataRepository) throws PerfSONARException {
+ public void initStorage(Key dataRepository) throws PerfSONARException
+ {
this.existDbXmlStorageManager = getStorageManager();
}
@@ -77,7 +80,8 @@
@Override
public Message fetch(Message dataQuery)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
Message message = new Message();
@@ -85,8 +89,8 @@
if (xmlResults == null)
throw new PerfSONARException(
- "error.ma",
- "MetadataConfigurationStorageManager.fetch: "
+ "error.ma",
+ "MetadataConfigurationStorageManager.fetch: "
+ "Result array of metadata search in null");
@@ -97,15 +101,15 @@
if (xmlResults.length == 0)
throw new PerfSONARException(
- "warning.ma.metadata_configuration",
- "MetadataConfigurationStorageManager.fetch: "
+ "warning.ma.metadata_configuration",
+ "MetadataConfigurationStorageManager.fetch: "
+ "No metadata in the metadata configuration");
if (xmlResults.length == 1)
if (xmlResults[0].trim().isEmpty())
throw new PerfSONARException(
- "warning.ma.metadata_configuration",
- "MetadataConfigurationStorageManager.fetch: "
+ "warning.ma.metadata_configuration",
+ "MetadataConfigurationStorageManager.fetch: "
+ "No metadata in the metadata configuration");
@@ -143,19 +147,20 @@
}
- public String[] fetchXmlStorage(Message dataQuery) throws
PerfSONARException {
+ public String[] fetchXmlStorage(Message dataQuery) throws
PerfSONARException
+ {
String query = transformations.getMetadataQuery(dataQuery);
logger.debug("MetadataConfigurationStorageManager.fetchXmlStorage: "
- + "xquery to fetch metadata/data from the metadata
configuration: \n"
- + query);
+ + "xquery to fetch metadata/data from the metadata
configuration: \n"
+ + query);
// if query is an empty string then the method returns empty message
if (query.trim().isEmpty())
throw new PerfSONARException(
- "error.ma.query",
- "MetadataConfigurationStorageManager.fetchXmlStorage: "
+ "error.ma.query",
+ "MetadataConfigurationStorageManager.fetchXmlStorage: "
+ "Empty query to get data from the metadata
configuration");
return executeQuery(query);
@@ -163,7 +168,8 @@
@Override
- public Message store(Message dataSet) throws PerfSONARException {
+ public Message store(Message dataSet) throws PerfSONARException
+ {
if (dataSet.getMetadataMap().size() > 1)
return storeAllElements(dataSet);
@@ -173,30 +179,31 @@
}
- private Message storeSinglePair(Message dataSet) throws
PerfSONARException {
+ private Message storeSinglePair(Message dataSet) throws
PerfSONARException
+ {
Data data = dataSet.getDataArray()[0];
if (data == null) {
logger.error("MetadataConfigurationStorageManager.store: "
- + "No data element to store");
+ + "No data element to store");
throw new PerfSONARException(
- "error.ma.query",
- "MetadataConfigurationStorageManager.store: "
+ "error.ma.query",
+ "MetadataConfigurationStorageManager.store: "
+ "No data block in the message to store data");
}
- String dataXUpdate = "<xu:modifications version=\'1.0\'"
- + " xmlns:xu=\'http://www.xmldb.org/xupdate\'"
- + ">\n"
- + "<xu:append select=\"/*:store\"
child=\"last()\">\n"
- + transformations.serializeXML(data)
- + "\n</xu:append>\n"
- + "</xu:modifications>";
+ String dataXUpdate = "<xu:modifications version=\'1.0\'"
+ + " xmlns:xu=\'http://www.xmldb.org/xupdate\'"
+ + ">\n"
+ + "<xu:append select=\"/*:store\" child=\"last()\">\n"
+ + transformations.serializeXML(data)
+ + "\n</xu:append>\n"
+ + "</xu:modifications>";
logger.debug("RRDConfigurationStorageManagerdata.store: "
- + "Xupdate statement to store data element: \n"
- + dataXUpdate);
+ + "Xupdate statement to store data element: \n"
+ + dataXUpdate);
Metadata metadata =
@@ -206,23 +213,23 @@
+ " No metadata block to store refering to "
+ data.getMetadataIdRef());
throw new PerfSONARException(
- "error.ma.query",
- "MetadataConfigurationStorageManager.store: "
+ "error.ma.query",
+ "MetadataConfigurationStorageManager.store: "
+ "No metadata block in the message to store refering to
"
+ data.getMetadataIdRef());
}
String metaXUpdate = "<xu:modifications version=\'1.0\'"
- + " xmlns:xu=\'http://www.xmldb.org/xupdate\'"
- + ">\n"
- + "<xu:append select=\"/*:store\"
child=\"last()\">\n"
- + transformations.serializeXML(metadata)
- + "\n</xu:append>\n"
- + "</xu:modifications>";
+ + " xmlns:xu=\'http://www.xmldb.org/xupdate\'"
+ + ">\n"
+ + "<xu:append select=\"/*:store\" child=\"last()\">\n"
+ + transformations.serializeXML(metadata)
+ + "\n</xu:append>\n"
+ + "</xu:modifications>";
logger.debug("RRDConfigurationStorageManagerdata.store: "
- + "XUpdate statement to store metadata element: \n"
- + metaXUpdate);
+ + "XUpdate statement to store metadata element: \n"
+ + metaXUpdate);
this.existDbXmlStorageManager.store(metaXUpdate);
@@ -233,7 +240,8 @@
}
- protected Message storeAllElements(Message dataSet) throws
PerfSONARException {
+ protected Message storeAllElements(Message dataSet) throws
PerfSONARException
+ {
storeMetadataElements(dataSet);
storeDataElements(dataSet);
@@ -241,34 +249,37 @@
}
- public void storeMetadataElements(Message dataSet) throws
PerfSONARException {
+ public void storeMetadataElements(Message dataSet) throws
PerfSONARException
+ {
Collection<Element> collection = dataSet.getMetadataMap().values();
storeElements(collection);
}
- protected void storeElements(Collection collection) throws
PerfSONARException {
+ protected void storeElements(Collection collection) throws
PerfSONARException
+ {
String query;
for (Object element : collection) {
- if (isAlreadyStored((Element)element)) continue;
+ if (isAlreadyStored((Element) element)) continue;
- query ="update insert " +
transformations.serializeXML((Element)element) + " into //*:store";
+ query = "update insert " +
transformations.serializeXML((Element) element) + " into //*:store";
logger.debug(query);
executeQuery(query);
}
}
- private boolean isAlreadyStored(Element element) throws
PerfSONARException {
+ private boolean isAlreadyStored(Element element) throws
PerfSONARException
+ {
String query = "let $res := "
- + "for $elem in //*:"+element.getLocalName()+" "
- + "where data($elem/@id)='"+element.getId()+"' "
- + "return 'detected' "
- + "return $res ";
+ + "for $elem in //*:" + element.getLocalName() + " "
+ + "where data($elem/@id)='" + element.getId() + "' "
+ + "return 'detected' "
+ + "return $res ";
logger.debug(query);
String[] results = executeQuery(query);
@@ -280,25 +291,27 @@
}
- protected String[] executeQuery(String query) throws PerfSONARException {
+ protected String[] executeQuery(String query) throws PerfSONARException
+ {
Object object;
try {
object = existDbXmlStorageManager.fetch(query);
} catch (Exception ex) {
logger.error("MetadataConfigurationStorageManager.executeQuery: "
- + "Connection to xml database failed: "
- + ex.toString());
+ + "Connection to xml database failed: "
+ + ex.toString());
throw new PerfSONARException(
- "error.common.storage.xmldb",
- "MetadataConfigurationStorageManager.executeQuery: "
+ "error.common.storage.xmldb",
+ "MetadataConfigurationStorageManager.executeQuery: "
+ "Connection to xml database failed");
}
return ((String[]) object);
}
- public void storeDataElements(Message dataSet) throws PerfSONARException
{
+ public void storeDataElements(Message dataSet) throws PerfSONARException
+ {
String metadataIdRef;
Metadata metadata;
@@ -352,14 +365,16 @@
@Override
- public Message remove(Message dataSet) throws PerfSONARException {
+ public Message remove(Message dataSet) throws PerfSONARException
+ {
// not supported
return null;
}
@Override
- public void removeAll() throws PerfSONARException {
+ public void removeAll() throws PerfSONARException
+ {
String query = "for $elem in //*:store/* return update delete $elem";
logger.debug(query);
@@ -369,13 +384,15 @@
@Override
- public Message update(Message dataSet) throws PerfSONARException {
+ public Message update(Message dataSet) throws PerfSONARException
+ {
// not supported
return null;
}
- protected XmlDbStorageManager getStorageManager() throws
PerfSONARException {
+ protected XmlDbStorageManager getStorageManager() throws
PerfSONARException
+ {
String xmldbAccess = "http";
@@ -390,16 +407,16 @@
XmlDbDataRepository dataRepository =
ExistDbFactory.getDataRepositoryByProperties(
- xmldbAccess.toUpperCase(),
- "component.ma.xmldb.db_uri",
- "component.ma.xmldb.db_username",
- "component.ma.xmldb.db_password");
+ xmldbAccess.toUpperCase(),
+ "component.ma.xmldb.db_uri",
+ "component.ma.xmldb.db_username",
+ "component.ma.xmldb.db_password");
XmlDbStorageManager storageManager =
ExistDbFactory.getXMLStorageManager(
- xmldbAccess, dataRepository);
+ xmldbAccess, dataRepository);
storageManager.setResultType(
- XmlDbStorageManager.STRING_ARRAY_TYPE);
+ XmlDbStorageManager.STRING_ARRAY_TYPE);
return storageManager;
@@ -407,33 +424,34 @@
}
- protected LoggerComponent getLogger() throws PerfSONARException {
+ protected LoggerComponent getLogger() throws PerfSONARException
+ {
try {
- return (LoggerComponent)AuxiliaryComponentManager.getInstance().
- getComponent(ComponentNames.LOGGER);
+ return (LoggerComponent) AuxiliaryComponentManager.getInstance().
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "MetadataConfigurationStorageManager.getLogger: "
+ "error.common.no_logger",
+ "MetadataConfigurationStorageManager.getLogger: "
+ "Cannot get logger component");
}
}
- protected ConfigurationComponent getConfiguration() throws
PerfSONARException {
+ protected ConfigurationComponent getConfiguration() throws
PerfSONARException
+ {
try {
- return configuration =
(ConfigurationComponent)AuxiliaryComponentManager.getInstance().
- getComponent(ComponentNames.CONFIG);
+ return configuration = (ConfigurationComponent)
AuxiliaryComponentManager.getInstance().
+ getComponent(ComponentNames.CONFIG);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_configuration",
- "MetadataConfigurationStorageManager.getConfiguration: "
+ "error.common.no_configuration",
+ "MetadataConfigurationStorageManager.getConfiguration: "
+ "Cannot get config component");
}
}
-
} //MetadataConfigurationStorageManager
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/SimpleMetadataConfigurationStorageManager.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/SimpleMetadataConfigurationStorageManager.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/SimpleMetadataConfigurationStorageManager.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -36,22 +36,21 @@
import org.perfsonar.service.base.storage.NMWGStorageManager;
-
-
/**
- * This class contains methods to manage metadata configuration data.
+ * This class contains methods to manage metadata configuration data.
*
- * @author romradz
+ * @author romradz
*/
public class SimpleMetadataConfigurationStorageManager
- implements NMWGStorageManager {
+ implements NMWGStorageManager
+{
// -------------------------------------- class fields
/**
- * RRD configuration file.
+ * RRD configuration file.
*/
private String xmlFile = null;
@@ -67,7 +66,8 @@
// -------------------------------------- constructors
- public SimpleMetadataConfigurationStorageManager() throws
PerfSONARException {
+ public SimpleMetadataConfigurationStorageManager() throws
PerfSONARException
+ {
this.logger = getLogger();
this.configuration = getConfiguration();
@@ -82,7 +82,8 @@
@Override
- public void initStorage(Key dataRepository) throws PerfSONARException {
+ public void initStorage(Key dataRepository) throws PerfSONARException
+ {
if (dataRepository == null)
this.xmlFile = configuration.getProperty("service.ma.conf_file");
@@ -98,14 +99,15 @@
@Override
public Message fetch(Message dataQuery)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
Message message = new Message();
String query = this.transformations.getMetadataQuery(dataQuery);
logger.debug(
- "SimpleMetadataConfigurationStorageManager.fetch: "
+ "SimpleMetadataConfigurationStorageManager.fetch: "
+ "xquery to fetch metadata/data from the metadata
configuration: \n"
+ query);
@@ -126,10 +128,10 @@
OutputStream sbos = new StringBufferOutputStream(outputBuffer);
QueryResult.serializeSequence(
- iter,
- saxonConfig,
- sbos,
- props);
+ iter,
+ saxonConfig,
+ sbos,
+ props);
String output = "<nmwg:message
xmlns=\"http://ggf.org/ns/nmwg/base/2.0/\" "
+ "xmlns:nmwg=\"http://ggf.org/ns/nmwg/base/2.0/\" "
@@ -144,13 +146,13 @@
if (elements == null)
throw new PerfSONARException(
- "warning.ma.metadata_configuration",
- "SimpleMetadataConfigurationStorageManager.fetch: "
+ "warning.ma.metadata_configuration",
+ "SimpleMetadataConfigurationStorageManager.fetch: "
+ "No metadata in metadata configuration file");
logger.debug("SimpleMetadataConfigurationStorageManager.fetch: "
- + "The number of elements returned as a result of xquery
statement: "
- + elements.size());
+ + "The number of elements returned as a result of xquery
statement: "
+ + elements.size());
Collection<Element> collection = elements.values();
for (Element elem : collection) {
@@ -161,24 +163,24 @@
} catch (XPathException xpex) {
logger.error(
- "SimpleMetadataConfigurationStorageManager.fetch: "
+ "SimpleMetadataConfigurationStorageManager.fetch: "
+ "Unable to complete xquery/xpath query; "
+ xpex.toString());
throw new PerfSONARException(
- "error.ma.fetching",
- "SimpleMetadataConfigurationStorageManager.fetch: "
+ "error.ma.fetching",
+ "SimpleMetadataConfigurationStorageManager.fetch: "
+ "Unable to complete xquery/xpath query; "
+ xpex.toString());
} catch (IOException ioex) {
logger.error(
- "SimpleMetadataConfigurationStorageManager.fetch: "
+ "SimpleMetadataConfigurationStorageManager.fetch: "
+ "Unable to complete fetch operation; "
+ ioex.toString());
throw new PerfSONARException(
- "error.ma.fetching",
- "SimpleMetadataConfigurationStorageManager.fetch: "
+ "error.ma.fetching",
+ "SimpleMetadataConfigurationStorageManager.fetch: "
+ "Unable to complete fetch operation; "
+ ioex.toString());
@@ -191,15 +193,16 @@
@Override
public Message store(Message dataSet)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
// This method is not implemented in
SimpleMetadataConfigurationStorageManager
// class. If you want this functionality you must take
RRDConfigurationStorageManager
// and configure xml db (eXist).
throw new PerfSONARException(
- "warning.ma.writing",
- "SimpleMetadataConfigurationStorageManager.store: "
+ "warning.ma.writing",
+ "SimpleMetadataConfigurationStorageManager.store: "
+ "Writing is not supported");
//return null;
@@ -208,27 +211,31 @@
@Override
- public Message remove(Message dataSet) throws PerfSONARException {
+ public Message remove(Message dataSet) throws PerfSONARException
+ {
// not supported
return null;
}
@Override
- public void removeAll() throws PerfSONARException {
+ public void removeAll() throws PerfSONARException
+ {
// not supported
}
@Override
- public Message update(Message dataSet) throws PerfSONARException {
+ public Message update(Message dataSet) throws PerfSONARException
+ {
// not supported
return null;
}
public DocumentInfo getMetaConfigDoc(StaticQueryContext staticContext)
- throws Exception {
+ throws Exception
+ {
if (metaConfigDoc != null) {
return metaConfigDoc;
@@ -236,13 +243,14 @@
metaConfigDoc = staticContext.buildDocument(new StreamSource(new
File(this.xmlFile)));
logger.debug("SimpleMetadataConfigurationStorageManager.getMetaConfigDoc:
metaConfigDoc is "
- + metaConfigDoc);
+ + metaConfigDoc);
return metaConfigDoc;
}
public SequenceIterator getQueryResult(
- String query, Configuration saxonConfig) throws PerfSONARException {
+ String query, Configuration saxonConfig) throws PerfSONARException
+ {
StaticQueryContext staticContext = new
StaticQueryContext(saxonConfig);
SequenceIterator elements;
@@ -258,12 +266,12 @@
} catch (Exception ex) {
logger.error(
-
"SimpleMetadataConfigurationStorageManager.getQueryResult: "
+ "SimpleMetadataConfigurationStorageManager.getQueryResult: "
+ "Unable to complete xquery/xpath query; "
+ ex.toString());
throw new PerfSONARException(
- "error.ma.fetching",
-
"SimpleMetadataConfigurationStorageManager.getQueryResult: "
+ "error.ma.fetching",
+ "SimpleMetadataConfigurationStorageManager.getQueryResult: "
+ "Unable to complete xquery/xpath query; "
+ ex.toString());
@@ -274,29 +282,31 @@
}
- protected LoggerComponent getLogger() throws PerfSONARException {
+ protected LoggerComponent getLogger() throws PerfSONARException
+ {
try {
- return (LoggerComponent)AuxiliaryComponentManager.getInstance().
- getComponent(ComponentNames.LOGGER);
+ return (LoggerComponent) AuxiliaryComponentManager.getInstance().
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "SimpleMetadataConfigurationStorageManager.getLogger: "
+ "error.common.no_logger",
+ "SimpleMetadataConfigurationStorageManager.getLogger: "
+ "Cannot get logger component");
}
}
- protected ConfigurationComponent getConfiguration() throws
PerfSONARException {
+ protected ConfigurationComponent getConfiguration() throws
PerfSONARException
+ {
try {
- return configuration =
(ConfigurationComponent)AuxiliaryComponentManager.getInstance().
- getComponent(ComponentNames.CONFIG);
+ return configuration = (ConfigurationComponent)
AuxiliaryComponentManager.getInstance().
+ getComponent(ComponentNames.CONFIG);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_configuration",
-
"SimpleMetadataConfigurationStorageManager.getConfiguration: "
+ "error.common.no_configuration",
+ "SimpleMetadataConfigurationStorageManager.getConfiguration:
"
+ "Cannot get config component");
}
}
@@ -305,22 +315,23 @@
// ------------------------------------ inner classes
+ private class StringBufferOutputStream extends OutputStream
+ {
- private class StringBufferOutputStream extends OutputStream {
-
private StringBuffer sb;
- public StringBufferOutputStream (StringBuffer sb) {
+ public StringBufferOutputStream(StringBuffer sb)
+ {
this.sb = sb;
}
@Override
- public void write(int b) throws IOException {
- sb.append((char)b);
+ public void write(int b) throws IOException
+ {
+ sb.append((char) b);
}
}
-
} //SimpleMetadataConfigurationStorageManager
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/Transformations.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/Transformations.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/Transformations.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -21,44 +21,42 @@
/**
- * Access to transformation methods changing metadata into xpath/xquery.
- * It is used while fetching configuration metadata.
+ * Access to transformation methods changing metadata into xpath/xquery.
+ * It is used while fetching configuration metadata.
*
- * @author romradz
+ * @author romradz
*/
-public class Transformations {
+public class Transformations
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
protected ConfigurationComponent configuration = null;
-
// -------------------------------------- constructors
+ public Transformations() throws PerfSONARException
+ {
- public Transformations() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "Transformations.constructor: "
+ "error.common.no_logger",
+ "Transformations.constructor: "
+ "Cannot get logger component");
}
@@ -68,13 +66,13 @@
this.configuration = (ConfigurationComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.CONFIG);
+ getComponent(ComponentNames.CONFIG);
} catch (PerfSONARException e) {
throw new PerfSONARException(
"error.common.no_configuration",
- "Transformations.constructor: "
+ "Transformations.constructor: "
+ "Cannot get config component");
}
@@ -82,17 +80,16 @@
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
//logger.debug("Transformations.getMetadataQuery: "
@@ -101,8 +98,8 @@
if (query == null)
throw new PerfSONARException(
- "error.ma.query",
- "Transformations.getMetadataQuery: "
+ "error.ma.query",
+ "Transformations.getMetadataQuery: "
+ "Input message is null");
@@ -112,11 +109,11 @@
metadata = metadataArray[0];
} catch (Exception ex) {
logger.error("Transformations.getMetadataQuery: "
- + "Unable to get metadata from message; "
- + ex.toString());
+ + "Unable to get metadata from message; "
+ + ex.toString());
throw new PerfSONARException(
- "error.ma.query",
- "Transformations.getMetadataQuery: "
+ "error.ma.query",
+ "Transformations.getMetadataQuery: "
+ "Unable to get metadata from message; "
+ ex.toString());
}
@@ -130,16 +127,16 @@
(metadata.getEventType() != null ?
metadata.getEventType().getEventType().trim() : "");
} catch (NullPointerException npex) {
throw new PerfSONARException(
- "error.ma.query",
- "Transformations.getMetadataQuery: "
+ "error.ma.query",
+ "Transformations.getMetadataQuery: "
+ "eventType in the request is null");
}
} else {
throw new PerfSONARException(
- "error.ma.query",
- "Transformations.getMetadataQuery: "
+ "error.ma.query",
+ "Transformations.getMetadataQuery: "
+ "metadata is missing in the request");
}
@@ -162,13 +159,13 @@
} catch (Exception ex) {
logger.error("Transformations.getMetadataQuery: "
- + "Unable to generate xquery statement "
- + "for the metadata configuration "
- + "from the request metadata. "
- + ex.toString());
+ + "Unable to generate xquery statement "
+ + "for the metadata configuration "
+ + "from the request metadata. "
+ + ex.toString());
throw new PerfSONARException(
- "error.ma.query",
- "Unable to generate xquery statement "
+ "error.ma.query",
+ "Unable to generate xquery statement "
+ "for the metadata configuration "
+ "from the request metadata. "
+ ex.toString());
@@ -181,18 +178,19 @@
/**
- * Returns nmwg objects with specific tag names parsed from xml string
+ * Returns nmwg objects with specific tag names parsed from xml string
*/
public Map<String, Element> transformResults(String xmlPart, String[]
tagNames)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
String f;
try {
f = configuration.getProperty("service.sax_parser.config");
} catch (PerfSONARException sex) {
throw new PerfSONARException(
- "error.common.configuration",
- "Transformations.transformResults: "
+ "error.common.configuration",
+ "Transformations.transformResults: "
+ "Unable to read service.sax_parser.config property
properly");
}
@@ -202,12 +200,12 @@
public String serializeXML(Element element)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
return XMLUtils.serializeXML(element);
}
-
} //Transformations
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/L2PathStatusKeyGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/L2PathStatusKeyGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/L2PathStatusKeyGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -19,12 +19,13 @@
import
org.perfsonar.service.measurementArchive.eventTypeConfig.EventTypeConfigurationComponent;
-public class L2PathStatusKeyGenerator implements MetadataKeyGenerator {
+public class L2PathStatusKeyGenerator implements MetadataKeyGenerator
+{
-
@Override
- public Key getKey(Metadata metadata, Data data) throws
PerfSONARException {
+ public Key getKey(Metadata metadata, Data data) throws PerfSONARException
+ {
if (metadata.getSubject() != null &&
metadata.getSubject().getChildrenByType("link").isEmpty())
return null;
@@ -66,36 +67,38 @@
}
- private ConfigurationComponent getConfiguration() throws
PerfSONARException {
+ private ConfigurationComponent getConfiguration() throws
PerfSONARException
+ {
try {
- return
(ConfigurationComponent)AuxiliaryComponentManager.getInstance().
- getComponent(ComponentNames.CONFIG);
+ return (ConfigurationComponent)
AuxiliaryComponentManager.getInstance().
+ getComponent(ComponentNames.CONFIG);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_configuration",
- "L2PathStatusKeyGenerator.getConfiguration: "
+ "error.common.no_configuration",
+ "L2PathStatusKeyGenerator.getConfiguration: "
+ "Cannot get config component");
}
}
public static Parameter getIbatisConfig(String eventTypeStr)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
EventTypeConfigurationComponent eventTypeConfigurationComponent =
(EventTypeConfigurationComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent("eventType_config");
+ getComponent("eventType_config");
org.perfsonar.service.measurementArchive.eventTypeConfig.EventType
eventType =
eventTypeConfigurationComponent.getEventType(eventTypeStr);
if (eventType == null)
throw new PerfSONARException(
- "error.ma.query",
- "SQLTypeMAServiceEngine.getStoreKey: "
+ "error.ma.query",
+ "SQLTypeMAServiceEngine.getStoreKey: "
+ "eventType " + eventTypeStr + " is not supported");
@@ -112,5 +115,4 @@
}
-
} //L2PathStatusKeyGenerator
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/MetadataKeyGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/MetadataKeyGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/MetadataKeyGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -11,7 +11,8 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-public interface MetadataKeyGenerator {
+public interface MetadataKeyGenerator
+{
public Key getKey(Metadata metadata, Data data) throws
PerfSONARException;
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/MetadataKeyGeneratorFactory.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/MetadataKeyGeneratorFactory.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/keyGenerator/MetadataKeyGeneratorFactory.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -14,22 +14,24 @@
import
org.perfsonar.service.measurementArchive.eventTypeConfig.EventTypeConfigurationComponent;
-public class MetadataKeyGeneratorFactory {
+public class MetadataKeyGeneratorFactory
+{
public static MetadataKeyGenerator getMetadataKeyGenerator(String
eventTypeName)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
LoggerComponent logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
EventTypeConfigurationComponent eventTypeConfigurationComponent =
(EventTypeConfigurationComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent("eventType_config");
+ getComponent("eventType_config");
EventType eventType =
@@ -37,8 +39,8 @@
if (eventType == null)
throw new PerfSONARException(
- "error.ma.query",
- "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "error.ma.query",
+ "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "eventType " + eventTypeName + " is not supported");
@@ -47,8 +49,8 @@
if (className == null || className.trim().isEmpty())
throw new PerfSONARException(
- "error.ma.event_type_mapping_configuration",
- "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "error.ma.event_type_mapping_configuration",
+ "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "Could not find class name for eventType "
+ eventTypeName);
@@ -62,13 +64,13 @@
} catch (Exception ex) {
logger.error(
- "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "Unable to create an object of : "
+ className + ": "
+ ex.toString());
throw new PerfSONARException(
- "error.ma.event_type_mapping_configuration",
- "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "error.ma.event_type_mapping_configuration",
+ "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "Unable to create an object of "
+ className);
@@ -78,12 +80,12 @@
if (metadataKeyGenerator == null) {
logger.error(
- "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "Could not create a metadataQueryGenerator object for "
+ "eventType: " + eventTypeName);
throw new PerfSONARException(
- "error.ma.event_type_mapping_configuration",
- "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "error.ma.event_type_mapping_configuration",
+ "MetadataKeyGeneratorFactory.getMetadataKeyGenerator: "
+ "Could not create a metadataQueryGenerator for "
+ "eventType: " + eventTypeName);
@@ -94,5 +96,4 @@
}
-
} //MetadataKeyGeneratorFactory
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/BwctlQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/BwctlQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/BwctlQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -15,77 +15,73 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-
/**
- * Transforms nmwg message into xquery/xpath
- * (query to fetch metadata with bwctl data)
+ * Transforms nmwg message into xquery/xpath
+ * (query to fetch metadata with bwctl data)
*
- * @author fernandes
- *
+ * @author fernandes
*/
-public class BwctlQueryGenerator implements MetadataQueryGenerator {
+public class BwctlQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
- private final String[] parameters = { "interval", "length",
"windowSize", "unsynchronized",
- "dynamicWindowSize", "concurrentConnections", "bandwidth",
- "duration", "tos", "protocol", "role" };
+ private final String[] parameters = {"interval", "length", "windowSize",
"unsynchronized",
+ "dynamicWindowSize", "concurrentConnections", "bandwidth",
+ "duration", "tos", "protocol", "role"};
// -------------------------------------- constructors
+ public BwctlQueryGenerator() throws PerfSONARException
+ {
- public BwctlQueryGenerator() throws PerfSONARException {
+ try {
- try {
+ this.logger = (LoggerComponent)
+ AuxiliaryComponentManager.
+ getInstance().
+ getComponent(ComponentNames.LOGGER);
+ } catch (PerfSONARException e) {
- this.logger = (LoggerComponent)
- AuxiliaryComponentManager.
- getInstance().
- getComponent(ComponentNames.LOGGER);
- } catch (PerfSONARException e) {
-
throw new PerfSONARException(
- "error.common.no_logger",
- "BwctlQueryGenerator.constructor: "
- + "Cannot get logger component");
+ "error.common.no_logger",
+ "BwctlQueryGenerator.constructor: "
+ + "Cannot get logger component");
}
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
if (query == null)
throw new PerfSONARException(
- "error.ma.query",
- "BwctlQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "BwctlQueryGenerator.getMetadataQuery: "
+ "Input message is null");
- String src = "";
- String dst = "";
- String eventType = "";
+ String src = "";
+ String dst = "";
+ String eventType = "";
Metadata metadata;
try {
@@ -93,69 +89,69 @@
metadata = metadataArray[0];
} catch (Exception ex) {
logger.error(
- "BwctlQueryGenerator.getMetadataQuery: "
- + "Unable to get metadata from the message");
+ "BwctlQueryGenerator.getMetadataQuery: "
+ + "Unable to get metadata from the message");
throw new PerfSONARException(
- "error.ma.query",
- "BwctlQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "BwctlQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message; "
+ ex.toString());
}
- HashMap<String, String> parametersMap = new HashMap<String,String>();
+ HashMap<String, String> parametersMap = new HashMap<String,
String>();
if (metadata != null) {
- eventType = (metadata.getEventType() != null ?
metadata.getEventType().getEventType().trim() : "");
+ eventType = (metadata.getEventType() != null ?
metadata.getEventType().getEventType().trim() : "");
Subject subject = (Subject) metadata.getSubject();
EndPointPair end = subject.getEndPointPair();
-
+
Parameters params = metadata.getParameters();
- for(String parameter : parameters){
- if(params.getParameterByName(parameter) != null)
- parametersMap.put(parameter,
-
(params.getParameterByName(parameter).getParameterValue() != null ?
-
params.getParameterByName(parameter).getParameterValue().trim() : ""));
+ for (String parameter : parameters) {
+ if (params.getParameterByName(parameter) != null)
+ parametersMap.put(parameter,
+
(params.getParameterByName(parameter).getParameterValue() != null ?
+
params.getParameterByName(parameter).getParameterValue().trim() : ""));
}
if (end != null) {
- src = (end.getSourceElement() != null ?
end.getSourceElement().getValue().trim() : "");
- dst = (end.getDestinationElement() != null ?
end.getDestinationElement().getValue().trim() : "");
+ src = (end.getSourceElement() != null ?
end.getSourceElement().getValue().trim() : "");
+ dst = (end.getDestinationElement() != null ?
end.getDestinationElement().getValue().trim() : "");
}
}
String xQuery = "\n"
- + "declare namespace nmwg='http://ggf.org/ns/nmwg/base/2.0/';
"
- + "declare namespace
bwctl='http://ggf.org/ns/nmwg/tools/bwctl/2.0/'; "
- + "declare namespace
nmwgt='http://ggf.org/ns/nmwg/topology/2.0/'; \n\n";
+ + "declare namespace nmwg='http://ggf.org/ns/nmwg/base/2.0/'; "
+ + "declare namespace
bwctl='http://ggf.org/ns/nmwg/tools/bwctl/2.0/'; "
+ + "declare namespace
nmwgt='http://ggf.org/ns/nmwg/topology/2.0/'; \n\n";
- xQuery +=
- " let $res :=
\n"
- + " for $i in //nmwg:metadata \n"
- + " where 1
\n";
+ xQuery +=
+ " let $res :=
\n"
+ + " for $i in //nmwg:metadata \n"
+ + " where 1
\n";
if (!eventType.isEmpty())
- xQuery += "and $i/nmwg:eventType[(text()='" + eventType +
"')]";
+ xQuery += "and $i/nmwg:eventType[(text()='" + eventType + "')]";
if (!src.isEmpty())
xQuery += "and
$i/bwctl:subject/nmwgt:endPointPair/nmwgt:src[@value='"
+ src + "']";
if (!dst.isEmpty())
- xQuery += "and
$i/bwctl:subject/nmwgt:endPointPair/nmwgt:dst[@value='"
+ dst + "']";
+ xQuery += "and
$i/bwctl:subject/nmwgt:endPointPair/nmwgt:dst[@value='"
+ dst + "']";
Set<String> keySet = parametersMap.keySet();
- for(String key : keySet){
- String v = parametersMap.get(key);
- if(!v.isEmpty()){
- xQuery += "and
$i/bwctl:parameters/nmwg:parameter[(text()='" + v + "' and @name='"+key+"') "
- + "or (@value='" + v + "' and
@name='"+key+"')]";
- }
+ for (String key : keySet) {
+ String v = parametersMap.get(key);
+ if (!v.isEmpty()) {
+ xQuery += "and $i/bwctl:parameters/nmwg:parameter[(text()='"
+ v + "' and @name='" + key + "') "
+ + "or (@value='" + v + "' and @name='" + key + "')]";
+ }
}
- xQuery += "\n"
- + " return $i
\n"
- + "
\n"
- + " let $metaids :=
\n"
+ xQuery += "\n"
+ + " return $i
\n"
+ + "
\n"
+ + " let $metaids :=
\n"
+ " for $j in $res
\n"
+ " return fn:data($j/@id)
\n"
+ "
\n"
@@ -182,5 +178,4 @@
}
-
} //BwctlQueryGenerator
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/DiscardsQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/DiscardsQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/DiscardsQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -17,40 +17,38 @@
/**
- * Transforms nmwg message into xquery/xpath
- * (query to fetch metadata with discards metric)
+ * Transforms nmwg message into xquery/xpath
+ * (query to fetch metadata with discards metric)
*
- * @author romradz
+ * @author romradz
*/
-public class DiscardsQueryGenerator implements MetadataQueryGenerator {
+public class DiscardsQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
-
// -------------------------------------- constructors
+ public DiscardsQueryGenerator() throws PerfSONARException
+ {
- public DiscardsQueryGenerator() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "DiscardsQueryGenerator.constructor: "
+ "error.common.no_logger",
+ "DiscardsQueryGenerator.constructor: "
+ "Cannot get logger component");
}
@@ -58,18 +56,17 @@
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
//logger.debug("DiscardsQueryGenerator.getMetadataQuery: "
@@ -96,11 +93,11 @@
metadata = metadataArray[0];
} catch (Exception ex) {
logger.error(
- "DiscardsQueryGenerator.getMetadataQuery: "
+ "DiscardsQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message");
throw new PerfSONARException(
- "error.ma.query",
- "DiscardsQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "DiscardsQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message; "
+ ex.toString());
}
@@ -114,39 +111,39 @@
keyword = keywordParameter.getParameterValue();
if (!keyword.trim().isEmpty())
- keywordQueryPart = " and
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='"+ keyword +"' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] ";
+ keywordQueryPart = " and
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + keyword + "' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] ";
}
Subject subject = (Subject) metadata.getSubject();
if (subject != null) {
Interface interf = subject.getInterface();
if (interf != null) {
- ipAddress = (interf.getIpAddressElement() != null
? interf.getIpAddressElement().getIpAddress().trim() : null);
- hostName = (interf.getHostNameElement() != null
? interf.getHostNameElement().getHostName().trim() : null);
- ifName = (interf.getIfNameElement() != null
? interf.getIfNameElement().getIfName().trim() : null);
- ifDescription = (interf.getIfDescriptionElement() != null
? interf.getIfDescriptionElement().getIfDescription().trim() : null);
- ifAddress = (interf.getIfAddressElement() != null
? interf.getIfAddressElement().getIfAddress().trim() : null);
- ifIndex = (interf.getIfIndexElement() != null
? interf.getIfIndexElement().getIfIndex().trim() : null);
- type = (interf.getTypeElement() != null
? interf.getTypeElement().getType().trim() : null);
- direction = (interf.getDirectionElement() != null
? interf.getDirectionElement().getDirection().trim() : null);
+ ipAddress = (interf.getIpAddressElement() != null ?
interf.getIpAddressElement().getIpAddress().trim() : null);
+ hostName = (interf.getHostNameElement() != null ?
interf.getHostNameElement().getHostName().trim() : null);
+ ifName = (interf.getIfNameElement() != null ?
interf.getIfNameElement().getIfName().trim() : null);
+ ifDescription = (interf.getIfDescriptionElement() != null ?
interf.getIfDescriptionElement().getIfDescription().trim() : null);
+ ifAddress = (interf.getIfAddressElement() != null ?
interf.getIfAddressElement().getIfAddress().trim() : null);
+ ifIndex = (interf.getIfIndexElement() != null ?
interf.getIfIndexElement().getIfIndex().trim() : null);
+ type = (interf.getTypeElement() != null ?
interf.getTypeElement().getType().trim() : null);
+ direction = (interf.getDirectionElement() != null ?
interf.getDirectionElement().getDirection().trim() : null);
classOfService = (interf.getClassOfServiceElement() != null
? interf.getClassOfServiceElement().getClassOfService().trim() : null);
- capacity = (interf.getCapacityElement() != null
? interf.getCapacityElement().getCapacity().trim() : null);
+ capacity = (interf.getCapacityElement() != null ?
interf.getCapacityElement().getCapacity().trim() : null);
try {
- ifAddressType =
(!interf.getIfAddressElement().getType().trim().isEmpty() ?
interf.getIfAddressElement().getType().trim(): null);
+ ifAddressType =
(!interf.getIfAddressElement().getType().trim().isEmpty() ?
interf.getIfAddressElement().getType().trim() : null);
} catch (Exception ex) {
- ifAddressType = null;
+ ifAddressType = null;
}
} else {
- throw new PerfSONARException(
- "error.ma.query",
- "DiscardsQueryGenerator.getMetadataQuery: "
+ throw new PerfSONARException(
+ "error.ma.query",
+ "DiscardsQueryGenerator.getMetadataQuery: "
+ "no interface element in metadata element");
}
} else {
- throw new PerfSONARException(
- "error.ma.query",
- "DiscardsQueryGenerator.getMetadataQuery: "
+ throw new PerfSONARException(
+ "error.ma.query",
+ "DiscardsQueryGenerator.getMetadataQuery: "
+ "no subject element in metadata element");
}
@@ -157,10 +154,10 @@
xQuery +=
"declare namespace functx = 'http://www.functx.com';\n"
- + "declare function functx:trim \n"
- + " ( $arg as xs:string? ) as xs:string { \n"
- + " replace(replace($arg,'\\s+$',''),'^\\s+','') \n"
- + "}; \n\n";
+ + "declare function functx:trim \n"
+ + " ( $arg as xs:string? ) as xs:string { \n"
+ + " replace(replace($arg,'\\s+$',''),'^\\s+','') \n"
+ + "}; \n\n";
if (ipAddress == null &&
@@ -172,25 +169,25 @@
type == null &&
direction == null &&
classOfService == null &&
- capacity == null &&
+ capacity == null &&
keywordParameter == null) {
// getting all metadata
xQuery +=
"let $res :=
\n"
- + " for $i in //nmwg:metadata
\n"
- + " where
\n"
- + "
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + eventType + "'
and functx:trim(@name)='supportedEventType') \n"
- + " or (functx:trim(@value)='" + eventType + "' and
functx:trim(@name)='supportedEventType')] \n"
- + " or
\n"
- + " $i/nmwg:eventType[functx:trim(text())='" +
eventType + "']
\n"
- + " return $i
\n"
- + "\n"
- + "let $datas :=
\n"
- + "
//nmwg:data/nmwg:key/nmwg:parameters/nmwg:parameter[functx:trim(@name)='eventType'
and (functx:trim(text())='" + eventType + "' or functx:trim(@value)='" +
eventType + "')]/parent::*/parent::*/parent::* \n"
- + "\n"
- + "return ($res, $datas) \n";
+ + " for $i in //nmwg:metadata
\n"
+ + " where
\n"
+ + "
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + eventType + "'
and functx:trim(@name)='supportedEventType') \n"
+ + " or (functx:trim(@value)='" + eventType + "'
and functx:trim(@name)='supportedEventType')]
\n"
+ + " or
\n"
+ + " $i/nmwg:eventType[functx:trim(text())='" +
eventType + "']
\n"
+ + " return $i
\n"
+ + "\n"
+ + "let $datas :=
\n"
+ + "
//nmwg:data/nmwg:key/nmwg:parameters/nmwg:parameter[functx:trim(@name)='eventType'
and (functx:trim(text())='" + eventType + "' or functx:trim(@value)='" +
eventType + "')]/parent::*/parent::*/parent::* \n"
+ + "\n"
+ + "return ($res, $datas) \n";
return xQuery;
@@ -199,13 +196,13 @@
xQuery +=
" let $res := \n"
- + " for $i in //nmwg:metadata \n"
- + " where 1 \n";
+ + " for $i in //nmwg:metadata \n"
+ + " where 1 \n";
if (eventType != null)
xQuery += "and $i/nmwg:eventType[functx:trim(text())='" +
eventType + "'] "
- + keywordQueryPart;
+ + keywordQueryPart;
if (ipAddress != null) {
if (ipAddress.isEmpty())
@@ -301,5 +298,4 @@
}
-
} //DiscardsQueryGenerator
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/ErrorsQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/ErrorsQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/ErrorsQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -17,40 +17,38 @@
/**
- * Transforms nmwg message into xquery/xpath
- * (query to fetch metadata with errors metric)
+ * Transforms nmwg message into xquery/xpath
+ * (query to fetch metadata with errors metric)
*
- * @author romradz
+ * @author romradz
*/
-public class ErrorsQueryGenerator implements MetadataQueryGenerator {
+public class ErrorsQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
-
// -------------------------------------- constructors
+ public ErrorsQueryGenerator() throws PerfSONARException
+ {
- public ErrorsQueryGenerator() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "ErrorsQueryGenerator.constructor: "
+ "error.common.no_logger",
+ "ErrorsQueryGenerator.constructor: "
+ "Cannot get logger component");
}
@@ -58,18 +56,17 @@
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
//logger.debug("UtilizationQueryGenerator.getMetadataQuery: "
@@ -96,11 +93,11 @@
metadata = metadataArray[0];
} catch (Exception ex) {
logger.error(
- "ErrorsQueryGenerator.getMetadataQuery: "
+ "ErrorsQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message");
throw new PerfSONARException(
- "error.ma.query",
- "ErrorsQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "ErrorsQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message; "
+ ex.toString());
}
@@ -114,39 +111,39 @@
keyword = keywordParameter.getParameterValue();
if (!keyword.trim().isEmpty())
- keywordQueryPart = " and
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='"+ keyword +"' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] ";
+ keywordQueryPart = " and
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + keyword + "' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] ";
}
Subject subject = (Subject) metadata.getSubject();
if (subject != null) {
Interface interf = subject.getInterface();
if (interf != null) {
- ipAddress = (interf.getIpAddressElement() != null
? interf.getIpAddressElement().getIpAddress().trim() : null);
- hostName = (interf.getHostNameElement() != null
? interf.getHostNameElement().getHostName().trim() : null);
- ifName = (interf.getIfNameElement() != null
? interf.getIfNameElement().getIfName().trim() : null);
- ifDescription = (interf.getIfDescriptionElement() != null
? interf.getIfDescriptionElement().getIfDescription().trim() : null);
- ifAddress = (interf.getIfAddressElement() != null
? interf.getIfAddressElement().getIfAddress().trim() : null);
- ifIndex = (interf.getIfIndexElement() != null
? interf.getIfIndexElement().getIfIndex().trim() : null);
- type = (interf.getTypeElement() != null
? interf.getTypeElement().getType().trim() : null);
- direction = (interf.getDirectionElement() != null
? interf.getDirectionElement().getDirection().trim() : null);
+ ipAddress = (interf.getIpAddressElement() != null ?
interf.getIpAddressElement().getIpAddress().trim() : null);
+ hostName = (interf.getHostNameElement() != null ?
interf.getHostNameElement().getHostName().trim() : null);
+ ifName = (interf.getIfNameElement() != null ?
interf.getIfNameElement().getIfName().trim() : null);
+ ifDescription = (interf.getIfDescriptionElement() != null ?
interf.getIfDescriptionElement().getIfDescription().trim() : null);
+ ifAddress = (interf.getIfAddressElement() != null ?
interf.getIfAddressElement().getIfAddress().trim() : null);
+ ifIndex = (interf.getIfIndexElement() != null ?
interf.getIfIndexElement().getIfIndex().trim() : null);
+ type = (interf.getTypeElement() != null ?
interf.getTypeElement().getType().trim() : null);
+ direction = (interf.getDirectionElement() != null ?
interf.getDirectionElement().getDirection().trim() : null);
classOfService = (interf.getClassOfServiceElement() != null
? interf.getClassOfServiceElement().getClassOfService().trim() : null);
- capacity = (interf.getCapacityElement() != null
? interf.getCapacityElement().getCapacity().trim() : null);
+ capacity = (interf.getCapacityElement() != null ?
interf.getCapacityElement().getCapacity().trim() : null);
try {
- ifAddressType =
(!interf.getIfAddressElement().getType().trim().isEmpty() ?
interf.getIfAddressElement().getType().trim(): null);
+ ifAddressType =
(!interf.getIfAddressElement().getType().trim().isEmpty() ?
interf.getIfAddressElement().getType().trim() : null);
} catch (Exception ex) {
ifAddressType = null;
}
} else {
throw new PerfSONARException(
- "error.ma.query",
- "ErrorsQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "ErrorsQueryGenerator.getMetadataQuery: "
+ "no interface element in metadata element");
}
} else {
throw new PerfSONARException(
- "error.ma.query",
- "ErrorsQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "ErrorsQueryGenerator.getMetadataQuery: "
+ "no subject element in metadata element");
}
@@ -157,10 +154,10 @@
xQuery +=
"declare namespace functx = 'http://www.functx.com';\n"
- + "declare function functx:trim \n"
- + " ( $arg as xs:string? ) as xs:string { \n"
- + " replace(replace($arg,'\\s+$',''),'^\\s+','') \n"
- + "}; \n\n";
+ + "declare function functx:trim \n"
+ + " ( $arg as xs:string? ) as xs:string { \n"
+ + " replace(replace($arg,'\\s+$',''),'^\\s+','') \n"
+ + "}; \n\n";
if (ipAddress == null &&
hostName == null &&
@@ -178,18 +175,18 @@
xQuery +=
"let $res :=
\n"
- + " for $i in //nmwg:metadata
\n"
- + " where
\n"
- + "
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + eventType + "'
and functx:trim(@name)='supportedEventType') \n"
- + " or (functx:trim(@value)='" + eventType + "' and
functx:trim(@name)='supportedEventType')] \n"
- + " or
\n"
- + " $i/nmwg:eventType[functx:trim(text())='" +
eventType + "']
\n"
- + " return $i
\n"
- + "\n"
- + "let $datas :=
\n"
- + "
//nmwg:data/nmwg:key/nmwg:parameters/nmwg:parameter[functx:trim(@name)='eventType'
and (functx:trim(text())='" + eventType + "' or functx:trim(@value)='" +
eventType + "')]/parent::*/parent::*/parent::* \n"
- + "\n"
- + "return ($res, $datas) \n";
+ + " for $i in //nmwg:metadata
\n"
+ + " where
\n"
+ + "
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + eventType + "'
and functx:trim(@name)='supportedEventType') \n"
+ + " or (functx:trim(@value)='" + eventType + "'
and functx:trim(@name)='supportedEventType')]
\n"
+ + " or
\n"
+ + " $i/nmwg:eventType[functx:trim(text())='" +
eventType + "']
\n"
+ + " return $i
\n"
+ + "\n"
+ + "let $datas :=
\n"
+ + "
//nmwg:data/nmwg:key/nmwg:parameters/nmwg:parameter[functx:trim(@name)='eventType'
and (functx:trim(text())='" + eventType + "' or functx:trim(@value)='" +
eventType + "')]/parent::*/parent::*/parent::* \n"
+ + "\n"
+ + "return ($res, $datas) \n";
return xQuery;
@@ -198,13 +195,13 @@
xQuery +=
" let $res := \n"
- + " for $i in //nmwg:metadata \n"
- + " where 1 \n";
+ + " for $i in //nmwg:metadata \n"
+ + " where 1 \n";
if (eventType != null)
xQuery += "and $i/nmwg:eventType[functx:trim(text())='" +
eventType + "'] "
- + keywordQueryPart;
+ + keywordQueryPart;
if (ipAddress != null) {
if (ipAddress.isEmpty())
@@ -300,5 +297,4 @@
}
-
} //ErrorsQueryGenerator
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/IperfQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/IperfQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/IperfQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -25,41 +25,40 @@
/**
- * Transforms nmwg message into xquery/xpath
- * (query to fetch metadata with utilization metric)
+ * Transforms nmwg message into xquery/xpath
+ * (query to fetch metadata with utilization metric)
*
- * @author romradz
+ * @author romradz
*/
-public class IperfQueryGenerator implements MetadataQueryGenerator {
+public class IperfQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
- private final String[] parameters = { "format", "protocol",
"windowSize", "timeDuration", "valueUnits", "numBytesUnits" };
+ private final String[] parameters = {"format", "protocol", "windowSize",
"timeDuration", "valueUnits", "numBytesUnits"};
// -------------------------------------- constructors
+ public IperfQueryGenerator() throws PerfSONARException
+ {
- public IperfQueryGenerator() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "IperfQueryGenerator.constructor: "
+ "error.common.no_logger",
+ "IperfQueryGenerator.constructor: "
+ "Cannot get logger component");
}
@@ -67,18 +66,17 @@
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
//logger.debug("IperfQueryGenerator.getMetadataQuery: "
@@ -96,11 +94,11 @@
metadata = metadataArray[0];
} catch (Exception ex) {
logger.error(
- "IperfQueryGenerator.getMetadataQuery: "
+ "IperfQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message");
throw new PerfSONARException(
- "error.ma.query",
- "IperfQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "IperfQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message; "
+ ex.toString());
}
@@ -114,11 +112,11 @@
keyword = keywordParameter.getParameterValue();
if (!keyword.trim().isEmpty())
- keywordQueryPart = " and
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='"+ keyword +"' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] ";
+ keywordQueryPart = " and
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + keyword + "' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] ";
}
// iperf parameters
- Map<String, String> iperfParametersMap = new
HashMap<String,String>();
+ Map<String, String> iperfParametersMap = new HashMap<String,
String>();
Parameters params;
try {
// iperf:parameters
@@ -130,9 +128,9 @@
if (params != null) {
for (String parameter : parameters) {
if (params.getParameterByName(parameter) != null)
- iperfParametersMap.put(parameter,
-
(params.getParameterByName(parameter).getParameterValue() != null ?
-
params.getParameterByName(parameter).getParameterValue().trim() : ""));
+ iperfParametersMap.put(parameter,
+
(params.getParameterByName(parameter).getParameterValue() != null ?
+
params.getParameterByName(parameter).getParameterValue().trim() : ""));
}
}
@@ -150,14 +148,14 @@
dst = (destinationElement != null ?
destinationElement.getValue().trim() : null);
} else {
throw new PerfSONARException(
- "error.ma.query",
- "IperfQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "IperfQueryGenerator.getMetadataQuery: "
+ "no endPointPair element in metadata element");
}
} else {
throw new PerfSONARException(
- "error.ma.query",
- "IperfQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "IperfQueryGenerator.getMetadataQuery: "
+ "no subject element in metadata element");
}
@@ -168,10 +166,10 @@
xQuery +=
"declare namespace functx = 'http://www.functx.com';\n"
- + "declare function functx:trim \n"
- + " ( $arg as xs:string? ) as xs:string { \n"
- + " replace(replace($arg,'\\s+$',''),'^\\s+','') \n"
- + "}; \n\n";
+ + "declare function functx:trim \n"
+ + " ( $arg as xs:string? ) as xs:string { \n"
+ + " replace(replace($arg,'\\s+$',''),'^\\s+','') \n"
+ + "}; \n\n";
if (src == null && dst == null && keywordParameter == null) {
@@ -179,18 +177,18 @@
xQuery +=
"let $res :=
\n"
- + " for $i in //nmwg:metadata
\n"
- + " where
\n"
- + "
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + eventType + "'
and functx:trim(@name)='supportedEventType') \n"
- + " or (functx:trim(@value)='" + eventType + "' and
functx:trim(@name)='supportedEventType')] \n"
- + " or
\n"
- + " $i/nmwg:eventType[functx:trim(text())='" +
eventType + "']
\n"
- + " return $i
\n"
- + "\n"
- + "let $datas :=
\n"
- + "
//nmwg:data/nmwg:key/nmwg:parameters/nmwg:parameter[functx:trim(@name)='eventType'
and (functx:trim(text())='" + eventType + "' or functx:trim(@value)='" +
eventType + "')]/parent::*/parent::*/parent::* \n"
- + "\n"
- + "return ($res, $datas) \n";
+ + " for $i in //nmwg:metadata
\n"
+ + " where
\n"
+ + "
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + eventType + "'
and functx:trim(@name)='supportedEventType') \n"
+ + " or (functx:trim(@value)='" + eventType + "'
and functx:trim(@name)='supportedEventType')]
\n"
+ + " or
\n"
+ + " $i/nmwg:eventType[functx:trim(text())='" +
eventType + "']
\n"
+ + " return $i
\n"
+ + "\n"
+ + "let $datas :=
\n"
+ + "
//nmwg:data/nmwg:key/nmwg:parameters/nmwg:parameter[functx:trim(@name)='eventType'
and (functx:trim(text())='" + eventType + "' or functx:trim(@value)='" +
eventType + "')]/parent::*/parent::*/parent::* \n"
+ + "\n"
+ + "return ($res, $datas) \n";
return xQuery;
@@ -199,8 +197,8 @@
xQuery +=
" let $res := \n"
- + " for $i in //nmwg:metadata \n"
- + " where 1 \n";
+ + " for $i in //nmwg:metadata \n"
+ + " where 1 \n";
/*
@@ -209,11 +207,11 @@
*/
if (eventType != null)
xQuery += "and
(($i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + eventType + "'
and functx:trim(@name)='supportedEventType') "
- + "or
(functx:trim(@value)='" + eventType + "' and
functx:trim(@name)='supportedEventType')]) "
- + "or "
- + "($i/nmwg:eventType[functx:trim(text())='" +
eventType + "'])"
- + ") "
- + keywordQueryPart;
+ + "or (functx:trim(@value)='" + eventType + "' and
functx:trim(@name)='supportedEventType')]) "
+ + "or "
+ + "($i/nmwg:eventType[functx:trim(text())='" + eventType +
"'])"
+ + ") "
+ + keywordQueryPart;
if (src != null) {
@@ -241,7 +239,7 @@
Set<String> keySet = iperfParametersMap.keySet();
- for(String key : keySet){
+ for (String key : keySet) {
String v = iperfParametersMap.get(key);
if (!v.isEmpty()) {
xQuery += "and $i/iperf:parameters/nmwg:parameter[(text()='"
+ v + "' and @name='" + key + "') "
@@ -266,7 +264,6 @@
+ " return ($res, $datas)
\n";
-
//logger.debug(
// "IperfQueryGenerator.getMetadataQuery: "
// + "meta query: "
@@ -278,5 +275,4 @@
}
-
} //IperfQueryGenerator
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/L2PathStatusQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/L2PathStatusQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/L2PathStatusQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -18,41 +18,39 @@
/**
- * Transforms nmwg message into xquery/xpath
- * (query to fetch metadata with L2 path status metric)
+ * Transforms nmwg message into xquery/xpath
+ * (query to fetch metadata with L2 path status metric)
*
- * @author romradz
+ * @author romradz
*/
-public class L2PathStatusQueryGenerator implements MetadataQueryGenerator {
+public class L2PathStatusQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
-
// -------------------------------------- constructors
+ public L2PathStatusQueryGenerator() throws PerfSONARException
+ {
- public L2PathStatusQueryGenerator() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "L2PathStatusQueryGenerator.constructor: "
+ "error.common.no_logger",
+ "L2PathStatusQueryGenerator.constructor: "
+ "Cannot get logger component");
}
@@ -60,18 +58,17 @@
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
Metadata metadata;
@@ -80,12 +77,12 @@
metadata = metadataArray[0];
} catch (Exception ex) {
logger.error(
- "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from message; "
+ ex.toString());
throw new PerfSONARException(
- "error.ma.query",
- "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from message; "
+ ex.toString());
}
@@ -103,7 +100,6 @@
+ "};
\n\n";
-
Subject subject = metadata.getSubject();
Parameter keywordParameter = metadata.getParameterByName("keyword");
@@ -112,7 +108,7 @@
String keyword = keywordParameter.getParameterValue();
if (!keyword.trim().isEmpty())
- keywordQueryPart = " and
$k/nmwg:parameters/nmwg:parameter[(functx:trim(text())='"+ keyword +"' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] \n";
+ keywordQueryPart = " and
$k/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + keyword + "' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] \n";
}
// situation when only eventType is provided in the request
@@ -120,34 +116,34 @@
xQuery =
" let $nodeMetadata :=
\n"
- + " for $i in //nmwg:metadata
\n"
- + " where $i/nmwg:subject/nmwgtopo3:node
\n"
- + " return $i
\n"
- + "
\n"
- + " let $linkMetadata :=
\n"
- + " for $k in //nmwg:metadata
\n"
- + " where
($k/nmwg:eventType[functx:trim(text())='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status']
\n"
- + " or
\n"
- + "
$k/nmwg:parameters/nmwg:parameter[(functx:trim(text())='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status'
and functx:trim(@name)='supportedEventType') \n"
- + " or
(functx:trim(@value)='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status' and
functx:trim(@name)='supportedEventType')]) \n"
- + keywordQueryPart
- + " return $k
\n"
- + "
\n"
- + " let $metaids :=
\n"
- + " for $j in $linkMetadata
\n"
- + " return fn:data($j/@id)
\n"
- + "
\n"
- + " let $datas :=
\n"
- + " for $k in $metaids
\n"
- + " let $d :=
\n"
- + " for $l in //nmwg:data
\n"
- + " where fn:data($l/@metadataIdRef) = $k
\n"
- + " return $l
\n"
- + " return $d
\n"
- + "
\n"
- + " return if ($linkMetadata != '')
\n"
- + " then ($nodeMetadata, $linkMetadata, $datas)
\n"
- + " else ''
";
+ + " for $i in //nmwg:metadata
\n"
+ + " where $i/nmwg:subject/nmwgtopo3:node
\n"
+ + " return $i
\n"
+ + "
\n"
+ + " let $linkMetadata :=
\n"
+ + " for $k in //nmwg:metadata
\n"
+ + " where
($k/nmwg:eventType[functx:trim(text())='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status']
\n"
+ + " or
\n"
+ + "
$k/nmwg:parameters/nmwg:parameter[(functx:trim(text())='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status'
and functx:trim(@name)='supportedEventType') \n"
+ + " or
(functx:trim(@value)='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status' and
functx:trim(@name)='supportedEventType')]) \n"
+ + keywordQueryPart
+ + " return $k
\n"
+ + "
\n"
+ + " let $metaids :=
\n"
+ + " for $j in $linkMetadata
\n"
+ + " return fn:data($j/@id)
\n"
+ + "
\n"
+ + " let $datas :=
\n"
+ + " for $k in $metaids
\n"
+ + " let $d :=
\n"
+ + " for $l in //nmwg:data
\n"
+ + " where fn:data($l/@metadataIdRef) = $k
\n"
+ + " return $l
\n"
+ + " return $d
\n"
+ + "
\n"
+ + " return if ($linkMetadata != '')
\n"
+ + " then ($nodeMetadata, $linkMetadata, $datas)
\n"
+ + " else ''
";
xQuery = ns + xQuery;
@@ -173,45 +169,45 @@
if (!linkGlobalName.isEmpty()) {
xQuery = ""
- + "\n"
- + " let $globalName := '" + linkGlobalName + "'
\n"
- + "
\n"
- + " let $linkMetadata :=
\n"
- + " if ($globalName != '') then
\n"
- + " for $m in //nmwg:metadata
\n"
- + " where
functx:trim(fn:lower-case($m/nmwg:subject/nmtl2:link/nmtl2:globalName)) =
functx:trim(fn:lower-case($globalName)) \n"
- + " and (
\n"
- + "
$m/nmwg:eventType[functx:trim(text())='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status']
\n"
- + " or
\n"
- + "
$m/nmwg:parameters/nmwg:parameter[(functx:trim(text())='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status'
and functx:trim(@name)='supportedEventType') \n"
- + " or
(functx:trim(@value)='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status' and
functx:trim(@name)='supportedEventType')] \n"
- + " )
\n"
- + " return $m
\n"
- + " else
\n"
- + " ''
\n"
- + "
\n"
- + " let $nodeMetadata :=
\n"
- + " if ($linkMetadata != '') then
\n"
- + " for $n in //nmwg:metadata
\n"
- + " where
fn:data($n/nmwg:subject/nmwgtopo3:node/@id) =
\n"
- + "
fn:data($linkMetadata/nmwg:subject/nmtl2:link/nmwgtopo3:node/@nodeIdRef)
\n"
- + " return $n
\n"
- + " else
\n"
- + " ''
\n"
- + "
\n"
- + " let $metaids :=
\n"
- + " for $j in $linkMetadata
\n"
- + " return fn:data($j/@id)
\n"
- + "
\n"
- + " let $datas :=
\n"
- + " for $k in $metaids
\n"
- + " let $d :=
\n"
- + " for $l in //nmwg:data
\n"
- + " where fn:data($l/@metadataIdRef) = $k
\n"
- + " return $l
\n"
- + " return $d
\n"
- + "
\n"
- + " return ($linkMetadata, $nodeMetadata, $datas)
";
+ + "\n"
+ + " let $globalName := '" + linkGlobalName + "'
\n"
+ + "
\n"
+ + " let $linkMetadata :=
\n"
+ + " if ($globalName != '') then
\n"
+ + " for $m in //nmwg:metadata
\n"
+ + " where
functx:trim(fn:lower-case($m/nmwg:subject/nmtl2:link/nmtl2:globalName)) =
functx:trim(fn:lower-case($globalName)) \n"
+ + " and (
\n"
+ + "
$m/nmwg:eventType[functx:trim(text())='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status']
\n"
+ + " or
\n"
+ + "
$m/nmwg:parameters/nmwg:parameter[(functx:trim(text())='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status'
and functx:trim(@name)='supportedEventType') \n"
+ + " or
(functx:trim(@value)='http://ggf.org/ns/nmwg/topology/l2/3.0/link/status' and
functx:trim(@name)='supportedEventType')] \n"
+ + " )
\n"
+ + " return $m
\n"
+ + " else
\n"
+ + " ''
\n"
+ + "
\n"
+ + " let $nodeMetadata :=
\n"
+ + " if ($linkMetadata != '') then
\n"
+ + " for $n in //nmwg:metadata
\n"
+ + " where
fn:data($n/nmwg:subject/nmwgtopo3:node/@id) =
\n"
+ + "
fn:data($linkMetadata/nmwg:subject/nmtl2:link/nmwgtopo3:node/@nodeIdRef)
\n"
+ + " return $n
\n"
+ + " else
\n"
+ + " ''
\n"
+ + "
\n"
+ + " let $metaids :=
\n"
+ + " for $j in $linkMetadata
\n"
+ + " return fn:data($j/@id)
\n"
+ + "
\n"
+ + " let $datas :=
\n"
+ + " for $k in $metaids
\n"
+ + " let $d :=
\n"
+ + " for $l in //nmwg:data
\n"
+ + " where fn:data($l/@metadataIdRef) = $k
\n"
+ + " return $l
\n"
+ + " return $d
\n"
+ + "
\n"
+ + " return ($linkMetadata, $nodeMetadata, $datas)
";
} else {
@@ -219,96 +215,111 @@
if (nodeArray == null) {
logger.error(
- "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "No node element(s) in the request metadata");
throw new PerfSONARException(
- "error.ma.query",
- "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "No node element(s) in the request metadata");
}
if (nodeArray.length > 2 || nodeArray.length == 0) {
logger.error(
- "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "0 or more than 2 node element(s) in the request
metadata");
throw new PerfSONARException(
- "error.ma.query",
- "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "L2PathStatusQueryGenerator.getMetadataQuery: "
+ "0 or more than 2 node element(s) in the request
metadata");
}
if (nodeArray.length == 2) {
- String node1Name = "";
- String node1Country = "";
- String node1City = "";
+ String node1Name = "";
+ String node1Country = "";
+ String node1City = "";
String node1Institution = "";
- try { node1Name =
nodeArray[0].getNameElement().getName().trim(); } catch
(Exception ex) {
+ try {
+ node1Name =
nodeArray[0].getNameElement().getName().trim();
+ } catch (Exception ex) {
}
- try { node1Country =
nodeArray[0].getCountryElement().getCountry().trim(); } catch
(Exception ex) {
+ try {
+ node1Country =
nodeArray[0].getCountryElement().getCountry().trim();
+ } catch (Exception ex) {
}
- try { node1City =
nodeArray[0].getCityElement().getCity().trim(); } catch
(Exception ex) {
+ try {
+ node1City =
nodeArray[0].getCityElement().getCity().trim();
+ } catch (Exception ex) {
}
- try { node1Institution =
nodeArray[0].getInstitutionElement().getInstitution().trim(); } catch
(Exception ex) {
+ try {
+ node1Institution =
nodeArray[0].getInstitutionElement().getInstitution().trim();
+ } catch (Exception ex) {
}
- String node2Name = "";
- String node2Country = "";
- String node2City = "";
+ String node2Name = "";
+ String node2Country = "";
+ String node2City = "";
String node2Institution = "";
- try { node2Name =
nodeArray[1].getNameElement().getName().trim(); } catch
(Exception ex) {
+ try {
+ node2Name =
nodeArray[1].getNameElement().getName().trim();
+ } catch (Exception ex) {
}
- try { node2Country =
nodeArray[1].getCountryElement().getCountry().trim(); } catch
(Exception ex) {
+ try {
+ node2Country =
nodeArray[1].getCountryElement().getCountry().trim();
+ } catch (Exception ex) {
}
- try { node2City =
nodeArray[1].getCityElement().getCity().trim(); } catch
(Exception ex) {
+ try {
+ node2City =
nodeArray[1].getCityElement().getCity().trim();
+ } catch (Exception ex) {
}
- try { node2Institution =
nodeArray[1].getInstitutionElement().getInstitution().trim(); } catch
(Exception ex) {
+ try {
+ node2Institution =
nodeArray[1].getInstitutionElement().getInstitution().trim();
+ } catch (Exception ex) {
}
-
String node1;
if (node1Name.isEmpty() && node1Country.isEmpty() &&
node1City.isEmpty() && node1Institution.isEmpty())
node1 = " let $node1_metadata := '' \n"
- + " let $node1_id := '' ";
+ + " let $node1_id := '' ";
else
node1 = " let $node1_metadata :=
\n"
- + " for $i in //nmwg:metadata
\n"
- + " where 1
\n"
- + (!node1Name.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + node1Name + "') \n" : "")
- + (!node1Country.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + node1Country + "') \n" : "")
- + (!node1City.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + node1City + "') \n" : "")
- + (!node1Institution.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + node1Institution + "') \n" : "")
- + " return $i
\n"
- + "
\n"
- + " let $node1_id :=
\n"
- + " if ($node1_metadata) then
\n"
- + "
fn:data($node1_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
- + " else
\n"
- + " ''
\n";
+ + " for $i in //nmwg:metadata
\n"
+ + " where 1
\n"
+ + (!node1Name.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + node1Name + "') \n" : "")
+ + (!node1Country.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + node1Country + "') \n" : "")
+ + (!node1City.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + node1City + "') \n" : "")
+ + (!node1Institution.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + node1Institution + "') \n" : "")
+ + " return $i
\n"
+ + "
\n"
+ + " let $node1_id :=
\n"
+ + " if ($node1_metadata) then
\n"
+ + "
fn:data($node1_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
+ + " else
\n"
+ + " ''
\n";
String node2;
if (node2Name.isEmpty() && node2Country.isEmpty() &&
node2City.isEmpty() && node2Institution.isEmpty())
node2 = " let $node2_metadata := '' \n"
- + " let $node2_id := '' ";
+ + " let $node2_id := '' ";
else
node2 = " let $node2_metadata :=
\n"
- + " for $j in //nmwg:metadata
\n"
- + " where 1
\n"
- + (!node2Name.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + node2Name + "') \n" : "")
- + (!node2Country.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + node2Country + "') \n" : "")
- + (!node2City.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + node2City + "') \n" : "")
- + (!node2Institution.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + node2Institution + "') \n" : "")
- + " return $j
\n"
- + "
\n"
- + " let $node2_id :=
\n"
- + " if ($node2_metadata) then
\n"
- + "
fn:data($node2_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
- + " else
\n"
- + " ''
\n";
+ + " for $j in //nmwg:metadata
\n"
+ + " where 1
\n"
+ + (!node2Name.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + node2Name + "') \n" : "")
+ + (!node2Country.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + node2Country + "') \n" : "")
+ + (!node2City.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + node2City + "') \n" : "")
+ + (!node2Institution.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + node2Institution + "') \n" : "")
+ + " return $j
\n"
+ + "
\n"
+ + " let $node2_id :=
\n"
+ + " if ($node2_metadata) then
\n"
+ + "
fn:data($node2_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
+ + " else
\n"
+ + " ''
\n";
xQuery = "\n "
@@ -355,41 +366,49 @@
+ " else
\n"
+ " ''
";
- } else if (nodeArray.length == 1){
+ } else if (nodeArray.length == 1) {
- String nodeName = "";
- String nodeCountry = "";
- String nodeCity = "";
+ String nodeName = "";
+ String nodeCountry = "";
+ String nodeCity = "";
String nodeInstitution = "";
- try { nodeName =
nodeArray[0].getNameElement().getName().trim(); } catch
(Exception ex) {
+ try {
+ nodeName =
nodeArray[0].getNameElement().getName().trim();
+ } catch (Exception ex) {
}
- try { nodeCountry =
nodeArray[0].getCountryElement().getCountry().trim(); } catch
(Exception ex) {
+ try {
+ nodeCountry =
nodeArray[0].getCountryElement().getCountry().trim();
+ } catch (Exception ex) {
}
- try { nodeCity =
nodeArray[0].getCityElement().getCity().trim(); } catch
(Exception ex) {
+ try {
+ nodeCity =
nodeArray[0].getCityElement().getCity().trim();
+ } catch (Exception ex) {
}
- try { nodeInstitution =
nodeArray[0].getInstitutionElement().getInstitution().trim(); } catch
(Exception ex) {
+ try {
+ nodeInstitution =
nodeArray[0].getInstitutionElement().getInstitution().trim();
+ } catch (Exception ex) {
}
String node;
if (nodeName.isEmpty() && nodeCountry.isEmpty() &&
nodeCity.isEmpty() && nodeInstitution.isEmpty())
node = " let $node_metadata := '' \n"
- + " let $node_id := '' ";
+ + " let $node_id := '' ";
else
node = " let $node_metadata :=
\n"
- + " for $i in //nmwg:metadata
\n"
- + " where 1
\n"
- + (!nodeName.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + nodeName + "') \n" : "")
- + (!nodeCountry.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + nodeCountry + "') \n" : "")
- + (!nodeCity.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + nodeCity + "') \n" : "")
- + (!nodeInstitution.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + nodeInstitution + "') \n" : "")
- + " return $i
\n"
- + "
\n"
- + " let $node_id :=
\n"
- + " if ($node_metadata) then
\n"
- + "
fn:data($node_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
- + " else
\n"
- + " ''
\n";
+ + " for $i in //nmwg:metadata
\n"
+ + " where 1
\n"
+ + (!nodeName.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + nodeName + "') \n" : "")
+ + (!nodeCountry.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + nodeCountry + "') \n" : "")
+ + (!nodeCity.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + nodeCity + "') \n" : "")
+ + (!nodeInstitution.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + nodeInstitution + "') \n" : "")
+ + " return $i
\n"
+ + "
\n"
+ + " let $node_id :=
\n"
+ + " if ($node_metadata) then
\n"
+ + "
fn:data($node_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
+ + " else
\n"
+ + " ''
\n";
xQuery = "\n "
+ "\n "
+ node
@@ -450,5 +469,4 @@
}
-
} //L2PathStatusQueryGenerator
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/L2PathStatusQueryGeneratorTMP.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/L2PathStatusQueryGeneratorTMP.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/L2PathStatusQueryGeneratorTMP.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -18,44 +18,42 @@
/**
- * Transforms nmwg message into xquery/xpath
- * (query to fetch metadata with L2 path status metric).
- * Warning: this is temporary class because it's using old value
- * of eventType 'Path.Status'. This class will be removed when
- * transition to the new eventType have finished.
+ * Transforms nmwg message into xquery/xpath
+ * (query to fetch metadata with L2 path status metric).
+ * Warning: this is temporary class because it's using old value
+ * of eventType 'Path.Status'. This class will be removed when
+ * transition to the new eventType have finished.
*
- * @author romradz
+ * @author romradz
*/
-public class L2PathStatusQueryGeneratorTMP implements MetadataQueryGenerator
{
+public class L2PathStatusQueryGeneratorTMP implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
-
// -------------------------------------- constructors
+ public L2PathStatusQueryGeneratorTMP() throws PerfSONARException
+ {
- public L2PathStatusQueryGeneratorTMP() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "L2PathStatusQueryGeneratorTMP.constructor: "
+ "error.common.no_logger",
+ "L2PathStatusQueryGeneratorTMP.constructor: "
+ "Cannot get logger component");
}
@@ -63,18 +61,17 @@
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException{
+ throws PerfSONARException
+ {
Metadata metadata;
@@ -83,12 +80,12 @@
metadata = metadataArray[0];
} catch (Exception ex) {
logger.error(
- "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "Unable to get metadata from message; "
+ ex.toString());
throw new PerfSONARException(
- "error.ma.query",
- "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "error.ma.query",
+ "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "Unable to get metadata from message; "
+ ex.toString());
}
@@ -106,7 +103,6 @@
+ "};
\n\n";
-
Subject subject = metadata.getSubject();
Parameter keywordParameter = metadata.getParameterByName("keyword");
@@ -115,7 +111,7 @@
String keyword = keywordParameter.getParameterValue();
if (!keyword.trim().isEmpty())
- keywordQueryPart = " and
$k/nmwg:parameters/nmwg:parameter[(functx:trim(text())='"+ keyword +"' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] \n";
+ keywordQueryPart = " and
$k/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + keyword + "' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] \n";
}
// situation when only eventType is provided in the request
@@ -123,34 +119,34 @@
xQuery =
" let $nodeMetadata :=
\n"
- + " for $i in //nmwg:metadata
\n"
- + " where $i/nmwg:subject/nmwgtopo3:node
\n"
- + " return $i
\n"
- + "
\n"
- + " let $linkMetadata :=
\n"
- + " for $k in //nmwg:metadata
\n"
- + " where
($k/nmwg:eventType[functx:trim(text())='Path.Status']
\n"
- + " or
\n"
- + "
$k/nmwg:parameters/nmwg:parameter[(functx:trim(text())='Path.Status' and
functx:trim(@name)='supportedEventType') \n"
- + " or
(functx:trim(@value)='Path.Status' and
functx:trim(@name)='supportedEventType')]) \n"
- + keywordQueryPart
- + " return $k
\n"
- + "
\n"
- + " let $metaids :=
\n"
- + " for $j in $linkMetadata
\n"
- + " return fn:data($j/@id)
\n"
- + "
\n"
- + " let $datas :=
\n"
- + " for $k in $metaids
\n"
- + " let $d :=
\n"
- + " for $l in //nmwg:data
\n"
- + " where fn:data($l/@metadataIdRef) = $k
\n"
- + " return $l
\n"
- + " return $d
\n"
- + "
\n"
- + " return if ($linkMetadata != '')
\n"
- + " then ($nodeMetadata, $linkMetadata, $datas)
\n"
- + " else ''
";
+ + " for $i in //nmwg:metadata
\n"
+ + " where $i/nmwg:subject/nmwgtopo3:node
\n"
+ + " return $i
\n"
+ + "
\n"
+ + " let $linkMetadata :=
\n"
+ + " for $k in //nmwg:metadata
\n"
+ + " where
($k/nmwg:eventType[functx:trim(text())='Path.Status']
\n"
+ + " or
\n"
+ + "
$k/nmwg:parameters/nmwg:parameter[(functx:trim(text())='Path.Status' and
functx:trim(@name)='supportedEventType') \n"
+ + " or
(functx:trim(@value)='Path.Status' and
functx:trim(@name)='supportedEventType')]) \n"
+ + keywordQueryPart
+ + " return $k
\n"
+ + "
\n"
+ + " let $metaids :=
\n"
+ + " for $j in $linkMetadata
\n"
+ + " return fn:data($j/@id)
\n"
+ + "
\n"
+ + " let $datas :=
\n"
+ + " for $k in $metaids
\n"
+ + " let $d :=
\n"
+ + " for $l in //nmwg:data
\n"
+ + " where fn:data($l/@metadataIdRef) = $k
\n"
+ + " return $l
\n"
+ + " return $d
\n"
+ + "
\n"
+ + " return if ($linkMetadata != '')
\n"
+ + " then ($nodeMetadata, $linkMetadata, $datas)
\n"
+ + " else ''
";
xQuery = ns + xQuery;
@@ -177,45 +173,45 @@
if (!linkGlobalName.isEmpty()) {
xQuery = ""
- + "\n"
- + " let $globalName := '" + linkGlobalName + "'
\n"
- + "
\n"
- + " let $linkMetadata :=
\n"
- + " if ($globalName != '') then
\n"
- + " for $m in //nmwg:metadata
\n"
- + " where
functx:trim(fn:lower-case($m/nmwg:subject/nmtl2:link/nmtl2:globalName)) =
functx:trim(fn:lower-case($globalName)) \n"
- + " and (
\n"
- + "
$m/nmwg:eventType[functx:trim(text())='Path.Status']
\n"
- + " or
\n"
- + "
$m/nmwg:parameters/nmwg:parameter[(functx:trim(text())='Path.Status' and
functx:trim(@name)='supportedEventType') \n"
- + " or
(functx:trim(@value)='Path.Status' and
functx:trim(@name)='supportedEventType')] \n"
- + " )
\n"
- + " return $m
\n"
- + " else
\n"
- + " ''
\n"
- + "
\n"
- + " let $nodeMetadata :=
\n"
- + " if ($linkMetadata != '') then
\n"
- + " for $n in //nmwg:metadata
\n"
- + " where
fn:data($n/nmwg:subject/nmwgtopo3:node/@id) =
\n"
- + "
fn:data($linkMetadata/nmwg:subject/nmtl2:link/nmwgtopo3:node/@nodeIdRef)
\n"
- + " return $n
\n"
- + " else
\n"
- + " ''
\n"
- + "
\n"
- + " let $metaids :=
\n"
- + " for $j in $linkMetadata
\n"
- + " return fn:data($j/@id)
\n"
- + "
\n"
- + " let $datas :=
\n"
- + " for $k in $metaids
\n"
- + " let $d :=
\n"
- + " for $l in //nmwg:data
\n"
- + " where fn:data($l/@metadataIdRef) = $k
\n"
- + " return $l
\n"
- + " return $d
\n"
- + "
\n"
- + " return ($linkMetadata, $nodeMetadata, $datas)
";
+ + "\n"
+ + " let $globalName := '" + linkGlobalName + "'
\n"
+ + "
\n"
+ + " let $linkMetadata :=
\n"
+ + " if ($globalName != '') then
\n"
+ + " for $m in //nmwg:metadata
\n"
+ + " where
functx:trim(fn:lower-case($m/nmwg:subject/nmtl2:link/nmtl2:globalName)) =
functx:trim(fn:lower-case($globalName)) \n"
+ + " and (
\n"
+ + "
$m/nmwg:eventType[functx:trim(text())='Path.Status']
\n"
+ + " or
\n"
+ + "
$m/nmwg:parameters/nmwg:parameter[(functx:trim(text())='Path.Status' and
functx:trim(@name)='supportedEventType') \n"
+ + " or
(functx:trim(@value)='Path.Status' and
functx:trim(@name)='supportedEventType')] \n"
+ + " )
\n"
+ + " return $m
\n"
+ + " else
\n"
+ + " ''
\n"
+ + "
\n"
+ + " let $nodeMetadata :=
\n"
+ + " if ($linkMetadata != '') then
\n"
+ + " for $n in //nmwg:metadata
\n"
+ + " where
fn:data($n/nmwg:subject/nmwgtopo3:node/@id) =
\n"
+ + "
fn:data($linkMetadata/nmwg:subject/nmtl2:link/nmwgtopo3:node/@nodeIdRef)
\n"
+ + " return $n
\n"
+ + " else
\n"
+ + " ''
\n"
+ + "
\n"
+ + " let $metaids :=
\n"
+ + " for $j in $linkMetadata
\n"
+ + " return fn:data($j/@id)
\n"
+ + "
\n"
+ + " let $datas :=
\n"
+ + " for $k in $metaids
\n"
+ + " let $d :=
\n"
+ + " for $l in //nmwg:data
\n"
+ + " where fn:data($l/@metadataIdRef) = $k
\n"
+ + " return $l
\n"
+ + " return $d
\n"
+ + "
\n"
+ + " return ($linkMetadata, $nodeMetadata, $datas)
";
} else {
@@ -223,96 +219,111 @@
if (nodeArray == null) {
logger.error(
- "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "No node element(s) in the request metadata");
throw new PerfSONARException(
- "error.ma.query",
- "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "error.ma.query",
+ "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "No node element(s) in the request metadata");
}
if (nodeArray.length > 2 || nodeArray.length == 0) {
logger.error(
- "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "0 or more than 2 node element(s) in the request
metadata");
throw new PerfSONARException(
- "error.ma.query",
- "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "error.ma.query",
+ "L2PathStatusQueryGeneratorTMP.getMetadataQuery: "
+ "0 or more than 2 node element(s) in the request
metadata");
}
if (nodeArray.length == 2) {
- String node1Name = "";
- String node1Country = "";
- String node1City = "";
+ String node1Name = "";
+ String node1Country = "";
+ String node1City = "";
String node1Institution = "";
- try { node1Name =
nodeArray[0].getNameElement().getName().trim(); } catch
(Exception ex) {
+ try {
+ node1Name =
nodeArray[0].getNameElement().getName().trim();
+ } catch (Exception ex) {
}
- try { node1Country =
nodeArray[0].getCountryElement().getCountry().trim(); } catch
(Exception ex) {
+ try {
+ node1Country =
nodeArray[0].getCountryElement().getCountry().trim();
+ } catch (Exception ex) {
}
- try { node1City =
nodeArray[0].getCityElement().getCity().trim(); } catch
(Exception ex) {
+ try {
+ node1City =
nodeArray[0].getCityElement().getCity().trim();
+ } catch (Exception ex) {
}
- try { node1Institution =
nodeArray[0].getInstitutionElement().getInstitution().trim(); } catch
(Exception ex) {
+ try {
+ node1Institution =
nodeArray[0].getInstitutionElement().getInstitution().trim();
+ } catch (Exception ex) {
}
- String node2Name = "";
- String node2Country = "";
- String node2City = "";
+ String node2Name = "";
+ String node2Country = "";
+ String node2City = "";
String node2Institution = "";
- try { node2Name =
nodeArray[1].getNameElement().getName().trim(); } catch
(Exception ex) {
+ try {
+ node2Name =
nodeArray[1].getNameElement().getName().trim();
+ } catch (Exception ex) {
}
- try { node2Country =
nodeArray[1].getCountryElement().getCountry().trim(); } catch
(Exception ex) {
+ try {
+ node2Country =
nodeArray[1].getCountryElement().getCountry().trim();
+ } catch (Exception ex) {
}
- try { node2City =
nodeArray[1].getCityElement().getCity().trim(); } catch
(Exception ex) {
+ try {
+ node2City =
nodeArray[1].getCityElement().getCity().trim();
+ } catch (Exception ex) {
}
- try { node2Institution =
nodeArray[1].getInstitutionElement().getInstitution().trim(); } catch
(Exception ex) {
+ try {
+ node2Institution =
nodeArray[1].getInstitutionElement().getInstitution().trim();
+ } catch (Exception ex) {
}
-
String node1;
if (node1Name.isEmpty() && node1Country.isEmpty() &&
node1City.isEmpty() && node1Institution.isEmpty())
node1 = " let $node1_metadata := '' \n"
- + " let $node1_id := '' ";
+ + " let $node1_id := '' ";
else
node1 = " let $node1_metadata :=
\n"
- + " for $i in //nmwg:metadata
\n"
- + " where 1
\n"
- + (!node1Name.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + node1Name + "') \n" : "")
- + (!node1Country.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + node1Country + "') \n" : "")
- + (!node1City.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + node1City + "') \n" : "")
- + (!node1Institution.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + node1Institution + "') \n" : "")
- + " return $i
\n"
- + "
\n"
- + " let $node1_id :=
\n"
- + " if ($node1_metadata) then
\n"
- + "
fn:data($node1_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
- + " else
\n"
- + " ''
\n";
+ + " for $i in //nmwg:metadata
\n"
+ + " where 1
\n"
+ + (!node1Name.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + node1Name + "') \n" : "")
+ + (!node1Country.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + node1Country + "') \n" : "")
+ + (!node1City.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + node1City + "') \n" : "")
+ + (!node1Institution.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + node1Institution + "') \n" : "")
+ + " return $i
\n"
+ + "
\n"
+ + " let $node1_id :=
\n"
+ + " if ($node1_metadata) then
\n"
+ + "
fn:data($node1_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
+ + " else
\n"
+ + " ''
\n";
String node2;
if (node2Name.isEmpty() && node2Country.isEmpty() &&
node2City.isEmpty() && node2Institution.isEmpty())
node2 = " let $node2_metadata := '' \n"
- + " let $node2_id := '' ";
+ + " let $node2_id := '' ";
else
node2 = " let $node2_metadata :=
\n"
- + " for $j in //nmwg:metadata
\n"
- + " where 1
\n"
- + (!node2Name.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + node2Name + "') \n" : "")
- + (!node2Country.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + node2Country + "') \n" : "")
- + (!node2City.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + node2City + "') \n" : "")
- + (!node2Institution.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + node2Institution + "') \n" : "")
- + " return $j
\n"
- + "
\n"
- + " let $node2_id :=
\n"
- + " if ($node2_metadata) then
\n"
- + "
fn:data($node2_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
- + " else
\n"
- + " ''
\n";
+ + " for $j in //nmwg:metadata
\n"
+ + " where 1
\n"
+ + (!node2Name.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + node2Name + "') \n" : "")
+ + (!node2Country.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + node2Country + "') \n" : "")
+ + (!node2City.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + node2City + "') \n" : "")
+ + (!node2Institution.isEmpty() ? " and
functx:trim(fn:lower-case($j/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + node2Institution + "') \n" : "")
+ + " return $j
\n"
+ + "
\n"
+ + " let $node2_id :=
\n"
+ + " if ($node2_metadata) then
\n"
+ + "
fn:data($node2_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
+ + " else
\n"
+ + " ''
\n";
xQuery = "\n "
@@ -359,41 +370,49 @@
+ " else
\n"
+ " ''
";
- } else if (nodeArray.length == 1){
+ } else if (nodeArray.length == 1) {
- String nodeName = "";
- String nodeCountry = "";
- String nodeCity = "";
+ String nodeName = "";
+ String nodeCountry = "";
+ String nodeCity = "";
String nodeInstitution = "";
- try { nodeName =
nodeArray[0].getNameElement().getName().trim(); } catch
(Exception ex) {
+ try {
+ nodeName =
nodeArray[0].getNameElement().getName().trim();
+ } catch (Exception ex) {
}
- try { nodeCountry =
nodeArray[0].getCountryElement().getCountry().trim(); } catch
(Exception ex) {
+ try {
+ nodeCountry =
nodeArray[0].getCountryElement().getCountry().trim();
+ } catch (Exception ex) {
}
- try { nodeCity =
nodeArray[0].getCityElement().getCity().trim(); } catch
(Exception ex) {
+ try {
+ nodeCity =
nodeArray[0].getCityElement().getCity().trim();
+ } catch (Exception ex) {
}
- try { nodeInstitution =
nodeArray[0].getInstitutionElement().getInstitution().trim(); } catch
(Exception ex) {
+ try {
+ nodeInstitution =
nodeArray[0].getInstitutionElement().getInstitution().trim();
+ } catch (Exception ex) {
}
String node;
if (nodeName.isEmpty() && nodeCountry.isEmpty() &&
nodeCity.isEmpty() && nodeInstitution.isEmpty())
node = " let $node_metadata := '' \n"
- + " let $node_id := '' ";
+ + " let $node_id := '' ";
else
node = " let $node_metadata :=
\n"
- + " for $i in //nmwg:metadata
\n"
- + " where 1
\n"
- + (!nodeName.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + nodeName + "') \n" : "")
- + (!nodeCountry.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + nodeCountry + "') \n" : "")
- + (!nodeCity.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + nodeCity + "') \n" : "")
- + (!nodeInstitution.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + nodeInstitution + "') \n" : "")
- + " return $i
\n"
- + "
\n"
- + " let $node_id :=
\n"
- + " if ($node_metadata) then
\n"
- + "
fn:data($node_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
- + " else
\n"
- + " ''
\n";
+ + " for $i in //nmwg:metadata
\n"
+ + " where 1
\n"
+ + (!nodeName.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:name))
= fn:lower-case('" + nodeName + "') \n" : "")
+ + (!nodeCountry.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:country))
= fn:lower-case('" + nodeCountry + "') \n" : "")
+ + (!nodeCity.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:city))
= fn:lower-case('" + nodeCity + "') \n" : "")
+ + (!nodeInstitution.isEmpty() ? " and
functx:trim(fn:lower-case($i/nmwg:subject/nmwgtopo3:node/nmwgtopo3:institution))
= fn:lower-case('" + nodeInstitution + "') \n" : "")
+ + " return $i
\n"
+ + "
\n"
+ + " let $node_id :=
\n"
+ + " if ($node_metadata) then
\n"
+ + "
fn:data($node_metadata/nmwg:subject/nmwgtopo3:node/@id) \n"
+ + " else
\n"
+ + " ''
\n";
xQuery = "\n "
+ "\n "
+ node
@@ -454,5 +473,4 @@
}
-
} //L2PathStatusQueryGeneratorTMP
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/MetadataQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/MetadataQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/MetadataQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -10,21 +10,20 @@
/**
- * Transforms nmwg message into xquery/xpath.
+ * Transforms nmwg message into xquery/xpath.
*
- * @author romradz
+ * @author romradz
*/
-public interface MetadataQueryGenerator {
+public interface MetadataQueryGenerator
+{
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
public String getMetadataQuery(Message query)
throws PerfSONARException;
-
} //MetadataQueryGenerator
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/MetadataQueryGeneratorFactory.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/MetadataQueryGeneratorFactory.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/MetadataQueryGeneratorFactory.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -15,33 +15,34 @@
/**
- * Factory class which can be used to get the appropriate
- * MetadataQueryGenerator object for the given eventType.
+ * Factory class which can be used to get the appropriate
+ * MetadataQueryGenerator object for the given eventType.
*
- * @author romradz
+ * @author romradz
*/
-public class MetadataQueryGeneratorFactory {
+public class MetadataQueryGeneratorFactory
+{
-
/**
- * Returns an object which can create a metadata query
- * in order to fetch relevant metadata configuration.
+ * Returns an object which can create a metadata query
+ * in order to fetch relevant metadata configuration.
*/
public static MetadataQueryGenerator getMetadataQueryGenerator(String
eventTypeName)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
LoggerComponent logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
EventTypeConfigurationComponent eventTypeConfigurationComponent =
(EventTypeConfigurationComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent("eventType_config");
+ getComponent("eventType_config");
EventType eventType =
@@ -49,8 +50,8 @@
if (eventType == null)
throw new PerfSONARException(
- "error.ma.query",
-
"MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "error.ma.query",
+ "MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "eventType " + eventTypeName + " is not supported");
@@ -63,8 +64,8 @@
if (className == null || className.trim().isEmpty())
throw new PerfSONARException(
- "error.ma.metadata_query_mapping_configuration",
-
"MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "error.ma.metadata_query_mapping_configuration",
+ "MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "Could not find class name for eventType "
+ eventTypeName);
@@ -80,13 +81,13 @@
} catch (Exception ex) {
logger.error(
-
"MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "Unable to create an object of : "
+ className + ": "
+ ex.toString());
throw new PerfSONARException(
- "error.ma.metadata_query_mapping_configuration",
-
"MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "error.ma.metadata_query_mapping_configuration",
+ "MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "Unable to create an object of "
+ className);
@@ -96,12 +97,12 @@
if (metadataQueryGenerator == null) {
logger.error(
-
"MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "Could not create a metadataQueryGenerator object for "
+ "eventType: " + eventTypeName);
throw new PerfSONARException(
- "error.ma.metadata_query_mapping_configuration",
-
"MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "error.ma.metadata_query_mapping_configuration",
+ "MetadataQueryGeneratorFactory.getMetadataQueryGenerator: "
+ "Could not create a metadataQueryGenerator for "
+ "eventType: " + eventTypeName);
@@ -112,5 +113,4 @@
}
-
} //MetadataQueryGeneratorFactory
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/OwampQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/OwampQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/OwampQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -15,77 +15,74 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-
/**
- * Transforms nmwg message into xquery/xpath
- * (query to fetch metadata with owamp data)
+ * Transforms nmwg message into xquery/xpath
+ * (query to fetch metadata with owamp data)
*
- * @author fernandes
- * @autor <a
;>Piotr
Pikusa</a>
+ * @author fernandes
+ * @autor <a
;>Piotr
Pikusa</a>
*/
-public class OwampQueryGenerator implements MetadataQueryGenerator {
+public class OwampQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
- private final String[] parameters = { "count", "dscp", "phb",
- "wait", "endDelay", "timeOut", "padding", "portRange",
"direction" };
+ private final String[] parameters = {"count", "dscp", "phb",
+ "wait", "endDelay", "timeOut", "padding", "portRange", "direction"};
// -------------------------------------- constructors
+ public OwampQueryGenerator() throws PerfSONARException
+ {
- public OwampQueryGenerator() throws PerfSONARException {
+ try {
- try {
+ this.logger = (LoggerComponent)
+ AuxiliaryComponentManager.
+ getInstance().
+ getComponent(ComponentNames.LOGGER);
+ } catch (PerfSONARException e) {
- this.logger = (LoggerComponent)
- AuxiliaryComponentManager.
- getInstance().
- getComponent(ComponentNames.LOGGER);
- } catch (PerfSONARException e) {
-
throw new PerfSONARException(
- "error.common.no_logger",
- "OwampQueryGenerator.constructor: "
- + "Cannot get logger component");
+ "error.common.no_logger",
+ "OwampQueryGenerator.constructor: "
+ + "Cannot get logger component");
}
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
- if (query == null){
- logger.error("QUERY is null!");
- throw new PerfSONARException(
- "error.ma.query",
- "OwampQueryGenerator.getMetadataQuery: "
- + "Input message is null");
+ if (query == null) {
+ logger.error("QUERY is null!");
+ throw new PerfSONARException(
+ "error.ma.query",
+ "OwampQueryGenerator.getMetadataQuery: "
+ + "Input message is null");
}
- String src = "";
- String dst = "";
- String eventType = "";
+ String src = "";
+ String dst = "";
+ String eventType = "";
Metadata metadata;
try {
@@ -93,74 +90,74 @@
metadata = metadataArray[0];
} catch (Exception ex) {
logger.error(
- "OwampQueryGenerator.getMetadataQuery: "
- + "Unable to get metadata from the message");
+ "OwampQueryGenerator.getMetadataQuery: "
+ + "Unable to get metadata from the message");
throw new PerfSONARException(
- "error.ma.query",
- "OwampQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "OwampQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message; "
+ ex.toString());
}
- HashMap<String, String> parametersMap = new HashMap<String,String>();
+ HashMap<String, String> parametersMap = new HashMap<String,
String>();
if (metadata != null) {
- eventType = (metadata.getEventType() != null ?
metadata.getEventType().getEventType().trim() : "");
+ eventType = (metadata.getEventType() != null ?
metadata.getEventType().getEventType().trim() : "");
Subject subject = (Subject) metadata.getSubject();
EndPointPair end = subject.getEndPointPair();
Parameters params = metadata.getParameters();
- if(params != null){
- for(String parameter : parameters){
- if(params.getParameterByName(parameter) != null)
- parametersMap.put(parameter,
-
(params.getParameterByName(parameter).getParameterValue() != null ?
-
params.getParameterByName(parameter).getParameterValue().trim() : ""));
+ if (params != null) {
+ for (String parameter : parameters) {
+ if (params.getParameterByName(parameter) != null)
+ parametersMap.put(parameter,
+
(params.getParameterByName(parameter).getParameterValue() != null ?
+
params.getParameterByName(parameter).getParameterValue().trim() : ""));
}
}
if (end != null) {
- src = (end.getSourceElement() != null ?
end.getSourceElement().getValue().trim() : "");
- dst = (end.getDestinationElement() != null ?
end.getDestinationElement().getValue().trim() : "");
+ src = (end.getSourceElement() != null ?
end.getSourceElement().getValue().trim() : "");
+ dst = (end.getDestinationElement() != null ?
end.getDestinationElement().getValue().trim() : "");
}
}
String xQuery = "\n"
- + "declare namespace nmwg='http://ggf.org/ns/nmwg/base/2.0/';
"
- + "declare namespace
owamp='http://ggf.org/ns/nmwg/tools/owamp/2.0/'; "
- + "declare namespace
nmwgt='http://ggf.org/ns/nmwg/topology/2.0/'; \n\n";
+ + "declare namespace nmwg='http://ggf.org/ns/nmwg/base/2.0/'; "
+ + "declare namespace
owamp='http://ggf.org/ns/nmwg/tools/owamp/2.0/'; "
+ + "declare namespace
nmwgt='http://ggf.org/ns/nmwg/topology/2.0/'; \n\n";
xQuery +=
- " let $res :=
\n"
- + " for $i in //nmwg:metadata \n"
- + " where 1
\n";
+ " let $res :=
\n"
+ + " for $i in //nmwg:metadata \n"
+ + " where 1
\n";
if (!eventType.isEmpty())
- xQuery += "and $i/nmwg:eventType[(text()='" + eventType +
"')]";
+ xQuery += "and $i/nmwg:eventType[(text()='" + eventType + "')]";
if (!src.isEmpty())
xQuery += "and
$i/owamp:subject/nmwgt:endPointPair/nmwgt:src[@value='"
+ src + "']";
if (!dst.isEmpty())
- xQuery += "and
$i/owamp:subject/nmwgt:endPointPair/nmwgt:dst[@value='"
+ dst + "']";
+ xQuery += "and
$i/owamp:subject/nmwgt:endPointPair/nmwgt:dst[@value='"
+ dst + "']";
Set<String> keySet = parametersMap.keySet();
- for(String key : keySet){
- String v = parametersMap.get(key);
- if(!v.isEmpty()){
- xQuery += "and
$i/owamp:parameters/nmwg:parameter[(text()='" + v + "' and @name='"+key+"') "
- + "or (@value='" + v + "' and
@name='"+key+"')]";
- }
+ for (String key : keySet) {
+ String v = parametersMap.get(key);
+ if (!v.isEmpty()) {
+ xQuery += "and $i/owamp:parameters/nmwg:parameter[(text()='"
+ v + "' and @name='" + key + "') "
+ + "or (@value='" + v + "' and @name='" + key + "')]";
+ }
}
xQuery += "\n"
- + " return $i
\n"
- + "
\n"
- + " let $metaids :=
\n"
+ + " return $i
\n"
+ + "
\n"
+ + " let $metaids :=
\n"
+ " for $j in $res
\n"
+ " return fn:data($j/@id)
\n"
+ "
\n"
@@ -181,5 +178,4 @@
}
-
} //OwampQueryGenerator
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/PingQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/PingQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/PingQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -15,46 +15,42 @@
import org.perfsonar.base.exceptions.PerfSONARException;
-
-
/**
- * Transforms nmwg message into xquery/xpath
- * (query to fetch metadata with owamp data)
+ * Transforms nmwg message into xquery/xpath
+ * (query to fetch metadata with owamp data)
*
- * @author fernandes
- *
+ * @author fernandes
*/
-public class PingQueryGenerator implements MetadataQueryGenerator {
+public class PingQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
- private final String[] parameters = { "count", "interval", "deadline",
"packetSize", "ttl" };
+ private final String[] parameters = {"count", "interval", "deadline",
"packetSize", "ttl"};
// -------------------------------------- constructors
+ public PingQueryGenerator() throws PerfSONARException
+ {
- public PingQueryGenerator() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "OwampQueryGenerator.constructor: "
+ "error.common.no_logger",
+ "OwampQueryGenerator.constructor: "
+ "Cannot get logger component");
}
@@ -62,29 +58,28 @@
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
if (query == null)
throw new PerfSONARException(
- "error.ma.query",
- "PingQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "PingQueryGenerator.getMetadataQuery: "
+ "Input message is null");
- String src = "";
- String dst = "";
- String eventType = "";
+ String src = "";
+ String dst = "";
+ String eventType = "";
Metadata metadata;
try {
@@ -92,19 +87,19 @@
metadata = metadataArray[0];
} catch (Exception ex) {
logger.error(
- "PingQueryGenerator.getMetadataQuery: "
+ "PingQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message");
throw new PerfSONARException(
- "error.ma.query",
- "PingQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "PingQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message; "
+ ex.toString());
}
- HashMap<String, String> parametersMap = new HashMap<String,String>();
+ HashMap<String, String> parametersMap = new HashMap<String,
String>();
if (metadata != null) {
- eventType = (metadata.getEventType() != null ?
metadata.getEventType().getEventType().trim() : "");
+ eventType = (metadata.getEventType() != null ?
metadata.getEventType().getEventType().trim() : "");
Subject subject = (Subject) metadata.getSubject();
EndPointPair end = subject.getEndPointPair();
@@ -115,13 +110,13 @@
for (String parameter : parameters) {
if (params.getParameterByName(parameter) != null)
parametersMap.put(parameter,
-
(params.getParameterByName(parameter).getParameterValue() != null ?
-
params.getParameterByName(parameter).getParameterValue().trim() : ""));
+
(params.getParameterByName(parameter).getParameterValue() != null ?
+
params.getParameterByName(parameter).getParameterValue().trim() : ""));
}
if (end != null) {
- src = (end.getSourceElement() != null ?
end.getSourceElement().getValue().trim() : "");
- dst = (end.getDestinationElement() != null ?
end.getDestinationElement().getValue().trim() : "");
+ src = (end.getSourceElement() != null ?
end.getSourceElement().getValue().trim() : "");
+ dst = (end.getDestinationElement() != null ?
end.getDestinationElement().getValue().trim() : "");
}
}
@@ -131,10 +126,10 @@
+ "declare namespace
ping='http://ggf.org/ns/nmwg/tools/ping/2.0/'; "
+ "declare namespace
nmwgt='http://ggf.org/ns/nmwg/topology/2.0/'; \n\n";
- xQuery +=
+ xQuery +=
" let $res :=
\n"
- + " for $i in //nmwg:metadata \n"
- + " where 1
\n";
+ + " for $i in //nmwg:metadata \n"
+ + " where 1
\n";
if (!eventType.isEmpty())
@@ -149,13 +144,13 @@
Set<String> keySet = parametersMap.keySet();
for (String key : keySet) {
String v = parametersMap.get(key);
- if (!v.isEmpty()){
- xQuery += "and $i/ping:parameters/nmwg:parameter[(text()='"
+ v + "' and @name='"+key+"') "
- + "or (@value='" + v + "' and @name='"+key+"')]";
+ if (!v.isEmpty()) {
+ xQuery += "and $i/ping:parameters/nmwg:parameter[(text()='"
+ v + "' and @name='" + key + "') "
+ + "or (@value='" + v + "' and @name='" + key + "')]";
}
}
- xQuery += "\n"
+ xQuery += "\n"
+ " return $i
\n"
+ "
\n"
+ " let $metaids :=
\n"
@@ -179,5 +174,4 @@
}
-
} //PingQueryGenerator
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/RandomFetchTestQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/RandomFetchTestQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/RandomFetchTestQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -14,62 +14,58 @@
/**
- * Transforms nmwg message into xquery/xpath
+ * Transforms nmwg message into xquery/xpath
*
- * @author romradz
+ * @author romradz
*/
-public class RandomFetchTestQueryGenerator implements MetadataQueryGenerator
{
+public class RandomFetchTestQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
-
// -------------------------------------- constructors
+ public RandomFetchTestQueryGenerator() throws PerfSONARException
+ {
- public RandomFetchTestQueryGenerator() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "XmlDbAccessTestQueryGenerator.constructor: "
+ "error.common.no_logger",
+ "XmlDbAccessTestQueryGenerator.constructor: "
+ "Cannot get logger component");
}
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
String xQuery = "//*:data[1]";
return xQuery;
}
-
} //RandomFetchTestQueryGenerator
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/UtilizationQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/UtilizationQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/UtilizationQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -17,40 +17,38 @@
/**
- * Transforms nmwg message into xquery/xpath
- * (query to fetch metadata with utilization metric)
+ * Transforms nmwg message into xquery/xpath
+ * (query to fetch metadata with utilization metric)
*
- * @author romradz
+ * @author romradz
*/
-public class UtilizationQueryGenerator implements MetadataQueryGenerator {
+public class UtilizationQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
-
// -------------------------------------- constructors
+ public UtilizationQueryGenerator() throws PerfSONARException
+ {
- public UtilizationQueryGenerator() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "UtilizationQueryGenerator.constructor: "
+ "error.common.no_logger",
+ "UtilizationQueryGenerator.constructor: "
+ "Cannot get logger component");
}
@@ -58,18 +56,17 @@
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
//logger.debug("UtilizationQueryGenerator.getMetadataQuery: "
@@ -96,11 +93,11 @@
metadata = metadataArray[0];
} catch (Exception ex) {
logger.error(
- "UtilizationQueryGenerator.getMetadataQuery: "
+ "UtilizationQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message");
throw new PerfSONARException(
- "error.ma.query",
- "UtilizationQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "UtilizationQueryGenerator.getMetadataQuery: "
+ "Unable to get metadata from the message; "
+ ex.toString());
}
@@ -114,39 +111,39 @@
keyword = keywordParameter.getParameterValue();
if (!keyword.trim().isEmpty())
- keywordQueryPart = " and
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='"+ keyword +"' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] ";
+ keywordQueryPart = " and
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + keyword + "' and
functx:trim(@name)='keyword') or (functx:trim(@value)='" + keyword + "' and
functx:trim(@name)='keyword')] ";
}
Subject subject = (Subject) metadata.getSubject();
if (subject != null) {
Interface interf = subject.getInterface();
if (interf != null) {
- ipAddress = (interf.getIpAddressElement() != null
? interf.getIpAddressElement().getIpAddress().trim() : null);
- hostName = (interf.getHostNameElement() != null
? interf.getHostNameElement().getHostName().trim() : null);
- ifName = (interf.getIfNameElement() != null
? interf.getIfNameElement().getIfName().trim() : null);
- ifDescription = (interf.getIfDescriptionElement() != null
? interf.getIfDescriptionElement().getIfDescription().trim() : null);
- ifAddress = (interf.getIfAddressElement() != null
? interf.getIfAddressElement().getIfAddress().trim() : null);
- ifIndex = (interf.getIfIndexElement() != null
? interf.getIfIndexElement().getIfIndex().trim() : null);
- type = (interf.getTypeElement() != null
? interf.getTypeElement().getType().trim() : null);
- direction = (interf.getDirectionElement() != null
? interf.getDirectionElement().getDirection().trim() : null);
+ ipAddress = (interf.getIpAddressElement() != null ?
interf.getIpAddressElement().getIpAddress().trim() : null);
+ hostName = (interf.getHostNameElement() != null ?
interf.getHostNameElement().getHostName().trim() : null);
+ ifName = (interf.getIfNameElement() != null ?
interf.getIfNameElement().getIfName().trim() : null);
+ ifDescription = (interf.getIfDescriptionElement() != null ?
interf.getIfDescriptionElement().getIfDescription().trim() : null);
+ ifAddress = (interf.getIfAddressElement() != null ?
interf.getIfAddressElement().getIfAddress().trim() : null);
+ ifIndex = (interf.getIfIndexElement() != null ?
interf.getIfIndexElement().getIfIndex().trim() : null);
+ type = (interf.getTypeElement() != null ?
interf.getTypeElement().getType().trim() : null);
+ direction = (interf.getDirectionElement() != null ?
interf.getDirectionElement().getDirection().trim() : null);
classOfService = (interf.getClassOfServiceElement() != null
? interf.getClassOfServiceElement().getClassOfService().trim() : null);
- capacity = (interf.getCapacityElement() != null
? interf.getCapacityElement().getCapacity().trim() : null);
+ capacity = (interf.getCapacityElement() != null ?
interf.getCapacityElement().getCapacity().trim() : null);
try {
- ifAddressType =
(!interf.getIfAddressElement().getType().trim().isEmpty() ?
interf.getIfAddressElement().getType().trim(): null);
+ ifAddressType =
(!interf.getIfAddressElement().getType().trim().isEmpty() ?
interf.getIfAddressElement().getType().trim() : null);
} catch (Exception ex) {
ifAddressType = null;
}
} else {
throw new PerfSONARException(
- "error.ma.query",
- "UtilizationQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "UtilizationQueryGenerator.getMetadataQuery: "
+ "no interface element in metadata element");
}
} else {
throw new PerfSONARException(
- "error.ma.query",
- "UtilizationQueryGenerator.getMetadataQuery: "
+ "error.ma.query",
+ "UtilizationQueryGenerator.getMetadataQuery: "
+ "no subject element in metadata element");
}
@@ -157,10 +154,10 @@
xQuery +=
"declare namespace functx = 'http://www.functx.com';\n"
- + "declare function functx:trim \n"
- + " ( $arg as xs:string? ) as xs:string { \n"
- + " replace(replace($arg,'\\s+$',''),'^\\s+','') \n"
- + "}; \n\n";
+ + "declare function functx:trim \n"
+ + " ( $arg as xs:string? ) as xs:string { \n"
+ + " replace(replace($arg,'\\s+$',''),'^\\s+','') \n"
+ + "}; \n\n";
if (ipAddress == null &&
@@ -179,18 +176,18 @@
xQuery +=
"let $res :=
\n"
- + " for $i in //nmwg:metadata
\n"
- + " where
\n"
- + "
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + eventType + "'
and functx:trim(@name)='supportedEventType') \n"
- + " or (functx:trim(@value)='" + eventType + "' and
functx:trim(@name)='supportedEventType')] \n"
- + " or
\n"
- + " $i/nmwg:eventType[functx:trim(text())='" +
eventType + "']
\n"
- + " return $i
\n"
- + "\n"
- + "let $datas :=
\n"
- + "
//nmwg:data/nmwg:key/nmwg:parameters/nmwg:parameter[functx:trim(@name)='eventType'
and (functx:trim(text())='" + eventType + "' or functx:trim(@value)='" +
eventType + "')]/parent::*/parent::*/parent::* \n"
- + "\n"
- + "return ($res, $datas) \n";
+ + " for $i in //nmwg:metadata
\n"
+ + " where
\n"
+ + "
$i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + eventType + "'
and functx:trim(@name)='supportedEventType') \n"
+ + " or (functx:trim(@value)='" + eventType + "'
and functx:trim(@name)='supportedEventType')]
\n"
+ + " or
\n"
+ + " $i/nmwg:eventType[functx:trim(text())='" +
eventType + "']
\n"
+ + " return $i
\n"
+ + "\n"
+ + "let $datas :=
\n"
+ + "
//nmwg:data/nmwg:key/nmwg:parameters/nmwg:parameter[functx:trim(@name)='eventType'
and (functx:trim(text())='" + eventType + "' or functx:trim(@value)='" +
eventType + "')]/parent::*/parent::*/parent::* \n"
+ + "\n"
+ + "return ($res, $datas) \n";
return xQuery;
@@ -199,8 +196,8 @@
xQuery +=
" let $res := \n"
- + " for $i in //nmwg:metadata \n"
- + " where 1 \n";
+ + " for $i in //nmwg:metadata \n"
+ + " where 1 \n";
/*
@@ -209,11 +206,11 @@
*/
if (eventType != null)
xQuery += "and
(($i/nmwg:parameters/nmwg:parameter[(functx:trim(text())='" + eventType + "'
and functx:trim(@name)='supportedEventType') "
- + "or
(functx:trim(@value)='" + eventType + "' and
functx:trim(@name)='supportedEventType')]) "
- + "or "
- + "($i/nmwg:eventType[functx:trim(text())='" +
eventType + "'])"
- + ") "
- + keywordQueryPart;
+ + "or (functx:trim(@value)='" + eventType + "' and
functx:trim(@name)='supportedEventType')]) "
+ + "or "
+ + "($i/nmwg:eventType[functx:trim(text())='" + eventType +
"'])"
+ + ") "
+ + keywordQueryPart;
if (ipAddress != null) {
if (ipAddress.isEmpty())
@@ -309,5 +306,4 @@
}
-
} //UtilizationQueryGenerator
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/XmlDbAccessTestQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/XmlDbAccessTestQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/XmlDbAccessTestQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -14,69 +14,65 @@
/**
- * Transforms nmwg message into xquery/xpath
+ * Transforms nmwg message into xquery/xpath
*
- * @author romradz
+ * @author romradz
*/
-public class XmlDbAccessTestQueryGenerator implements MetadataQueryGenerator
{
+public class XmlDbAccessTestQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
-
// -------------------------------------- constructors
+ public XmlDbAccessTestQueryGenerator() throws PerfSONARException
+ {
- public XmlDbAccessTestQueryGenerator() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "XmlDbAccessTestQueryGenerator.constructor: "
+ "error.common.no_logger",
+ "XmlDbAccessTestQueryGenerator.constructor: "
+ "Cannot get logger component");
}
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
String xQuery = "declare namespace
nmwg='http://ggf.org/ns/nmwg/base/2.0/'; \n"
- + "declare namespace
nmwgr='http://ggf.org/ns/nmwg/result/2.0/'; \n"
- + "let $version := system:get-version() \n"
- + "return \n"
- + " <nmwg:data> \n"
- + " <nmwgr:datum>Xml Database ver. {$version} is
accessible.</nmwgr:datum> \n"
- + " </nmwg:data> \n";
+ + "declare namespace nmwgr='http://ggf.org/ns/nmwg/result/2.0/';
\n"
+ + "let $version := system:get-version() \n"
+ + "return \n"
+ + " <nmwg:data> \n"
+ + " <nmwgr:datum>Xml Database ver. {$version} is
accessible.</nmwgr:datum> \n"
+ + " </nmwg:data> \n";
return xQuery;
}
-
} //XmlDbAccessTestQueryGenerator
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/XmlDbContentTestQueryGenerator.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/XmlDbContentTestQueryGenerator.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/metadataConfig/queryGenerator/XmlDbContentTestQueryGenerator.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -14,71 +14,67 @@
/**
- * Transforms nmwg message into xquery/xpath
+ * Transforms nmwg message into xquery/xpath
*
- * @author romradz
+ * @author romradz
*/
-public class XmlDbContentTestQueryGenerator implements
MetadataQueryGenerator {
+public class XmlDbContentTestQueryGenerator implements MetadataQueryGenerator
+{
-
// -------------------------------------- class fields
-
protected LoggerComponent logger = null;
-
// -------------------------------------- constructors
+ public XmlDbContentTestQueryGenerator() throws PerfSONARException
+ {
- public XmlDbContentTestQueryGenerator() throws PerfSONARException {
-
try {
this.logger = (LoggerComponent)
AuxiliaryComponentManager.
getInstance().
- getComponent(ComponentNames.LOGGER);
+ getComponent(ComponentNames.LOGGER);
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.common.no_logger",
- "XmlDbAccessTestQueryGenerator.constructor: "
+ "error.common.no_logger",
+ "XmlDbAccessTestQueryGenerator.constructor: "
+ "Cannot get logger component");
}
}
-
// -------------------------------------- public methods
-
/**
- * Returns xpath query created using the information
- * stored in Message object.
+ * Returns xpath query created using the information
+ * stored in Message object.
*/
@Override
public String getMetadataQuery(Message query)
- throws PerfSONARException {
+ throws PerfSONARException
+ {
String xQuery = "declare namespace
nmwg='http://ggf.org/ns/nmwg/base/2.0/'; \n"
- + "declare namespace
nmwgr='http://ggf.org/ns/nmwg/result/2.0/'; \n"
- + "let $metadatas : = count(//nmwg:metadata) \n"
- + "let $datas : = count(//nmwg:data) \n"
- + "let $elements : = $metadatas + $datas \n"
- + "return \n"
- + " <nmwg:data> \n"
- + " <nmwgr:datum>Number of all metadata and data
elements in the xml database is {$elements}.</nmwgr:datum> \n"
- + " </nmwg:data> \n";
+ + "declare namespace nmwgr='http://ggf.org/ns/nmwg/result/2.0/';
\n"
+ + "let $metadatas : = count(//nmwg:metadata) \n"
+ + "let $datas : = count(//nmwg:data) \n"
+ + "let $elements : = $metadatas + $datas \n"
+ + "return \n"
+ + " <nmwg:data> \n"
+ + " <nmwgr:datum>Number of all metadata and data elements in
the xml database is {$elements}.</nmwgr:datum> \n"
+ + " </nmwg:data> \n";
return xQuery;
}
-
} //XmlDbContentTestQueryGenerator
\ No newline at end of file
Modified:
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/register/LSRegistrationComponent.java
===================================================================
---
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/register/LSRegistrationComponent.java
2012-10-05 09:22:41 UTC (rev 6009)
+++
trunk/perfsonar_base/src/main/java/org/perfsonar/service/measurementArchive/register/LSRegistrationComponent.java
2012-10-05 09:22:44 UTC (rev 6010)
@@ -28,22 +28,23 @@
* @author romradz (contributor)
* @deprecated use
{@link
org.perfsonar.service.base.registration.LSRegistrationComponent}
*/
-public class LSRegistrationComponent implements SchedulerAction,
AuxiliaryComponent {
+public class LSRegistrationComponent implements SchedulerAction,
AuxiliaryComponent
+{
// ----------------------------------------------------- constants
- private static final int DEFAULT_RUN_INTERVAL = 60; // sec
- private static final int MINIMAL_RUN_INTERVAL = 5; // sec
- private static final String MA_CONFIG_FILE = "service.ma.conf_file";
- private static final String MA_CONFIG_STORE =
"service.ma.conf_file.store_type"; // "xmldb" or "file"
+ private static final int DEFAULT_RUN_INTERVAL = 60; // sec
+ private static final int MINIMAL_RUN_INTERVAL = 5; // sec
+ private static final String MA_CONFIG_FILE = "service.ma.conf_file";
+ private static final String MA_CONFIG_STORE =
"service.ma.conf_file.store_type"; // "xmldb" or "file"
// -------------------------------------------- class fields
- private Message responseMessage = null;
- private String componentName = "ma-registrator";
- private LoggerComponent logger = null;
- private ConfigurationComponent configuration = null;
- private Scheduler scheduler = null;
+ private Message responseMessage = null;
+ private String componentName = "ma-registrator";
+ private LoggerComponent logger = null;
+ private ConfigurationComponent configuration = null;
+ private Scheduler scheduler = null;
String lsURL = null;
String[] lsURLArray = null;
@@ -51,7 +52,8 @@
// ---------------------------------- constructors
- public LSRegistrationComponent() throws PerfSONARException {
+ public LSRegistrationComponent() throws PerfSONARException
+ {
try {
this.logger =
@@ -77,11 +79,12 @@
// ---------------------------------- public methods
- /**
- * Scheduler action
- */
- @Override
- public void runAction() {
+ /**
+ * Scheduler action
+ */
+ @Override
+ public void runAction()
+ {
try {
//String lsURL = configuration.getProperty("service.r.ls_url");
@@ -94,7 +97,7 @@
} catch (PerfSONARException ex) {
logger.debug("LSRegistrationComponent.runAction: "
+ "Can't get property "
- + LSRegistrationComponent.MA_CONFIG_STORE);
+ + LSRegistrationComponent.MA_CONFIG_STORE);
}
ServiceLSRegistrator registrator;
@@ -156,7 +159,8 @@
// ---------------------- component that loads action to scheduler
@Override
- public void initComponent() throws PerfSONARException {
+ public void initComponent() throws PerfSONARException
+ {
// Get configuration
@@ -201,40 +205,42 @@
if (scheduler == null) {
throw new PerfSONARException(
- "error.ma.no_scheduler",
- "LSRegistrationComponent.initComponent: No scheduler
component in AuxiliaryComponentManager"
+ "error.ma.no_scheduler",
+ "LSRegistrationComponent.initComponent: No scheduler
component in AuxiliaryComponentManager"
);
}
} catch (PerfSONARException e) {
throw new PerfSONARException(
- "error.ma.no_scheduler",
- "LSRegistrationComponent.initComponent:"
- + "LSCleanupLoader: no [component." +
componentName
- + ".scheduler_component] parameter. "+
e.getMessage()
+ "error.ma.no_scheduler",
+ "LSRegistrationComponent.initComponent:"
+ + "LSCleanupLoader: no [component." + componentName
+ + ".scheduler_component] parameter. " + e.getMessage()
);
}
// add cleanup action to scheduler
- scheduler.addSchedulerTask(interval*1000, this); // seconds
converted into milliseconds
+ scheduler.addSchedulerTask(interval * 1000, this); // seconds
converted into milliseconds
}
@Override
- public String getComponentName() {
+ public String getComponentName()
+ {
return componentName;
}
@Override
- public void setComponentName(String name) {
+ public void setComponentName(String name)
+ {
componentName = name;
}
// ---------------------------------------------------------- test
main() method
// TODO remove?
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) throws Exception
+ {
AuxiliaryComponentManager.getInstance();
}
-
} // LSRegistrationComponent
\ No newline at end of file
- [pS-dev] [GEANT/SA2/ps-java-services] r6010 - in trunk/perfsonar_base/src/main/java/org/perfsonar: base/auxiliary base/auxiliary/components/authn base/auxiliary/components/authn/wssec base/auxiliary/components/configuration base/auxiliary/components/configuration/properties base/auxiliary/components/context base/auxiliary/components/context/inMemory base/auxiliary/components/logger base/auxiliary/components/logger/log4j base/auxiliary/components/mapping base/auxiliary/components/scheduler base/auxiliary/components/scheduler/actions base/auxiliary/components/simplescheduler base/exceptions base/nmwg/owamp base/util base/util/iptrie service/base/authn service/base/authn/tokens service/base/container/listeners service/base/engine service/base/measurementExecutor service/base/messages service/base/registration service/base/storage service/base/storage/xmldb service/base/storage/xmldb/exist service/base/storage/xmldb/exist/rest service/base/storage/xmldb/exist/xmlrpc service/base/ storage/xmlfile service/base/transport service/base/util service/base/web service/measurementArchive/eventTypeConfig service/measurementArchive/metadataConfig service/measurementArchive/metadataConfig/keyGenerator service/measurementArchive/metadataConfig/queryGenerator service/measurementArchive/register, svn-noreply, 10/05/2012
Archive powered by MHonArc 2.6.16.