From 6bd802a6f92a89dcc79e969d56bab83ee14ecd97 Mon Sep 17 00:00:00 2001 From: Henning Bredel Date: Tue, 22 Sep 2015 13:11:20 +0200 Subject: [PATCH 1/4] add little abstraction tier decoupling repository-manager from singleton pattern --- .../algorithm/SimpleBufferAlgorithmTest.java | 2 - .../ServiceLoaderAlgorithmRepository.java | 8 +- .../AbstractSelfDescribingAlgorithmTest.java | 4 +- .../test/ExecuteRequestBuilderTest.java | 144 ++++++------ .../java/org/n52/wps/commons/WPSConfig.java | 41 ++-- .../wps/webapp/common/AbstractITClass.java | 12 +- .../AbstractITClassForControllerTests.java | 16 +- .../io/test/datahandler/OMGeneratorTest.java | 24 +- .../io/test/datahandler/AbstractTestCase.java | 6 +- .../wps/server/CapabilitiesConfiguration.java | 86 +++---- .../server/CapabilitiesConfigurationV200.java | 206 ++++++++-------- .../org/n52/wps/server/RepositoryManager.java | 222 +++++++++--------- .../RepositoryManagerSingletonWrapper.java | 65 +++++ .../n52/wps/server/WebProcessingService.java | 25 +- .../request/DescribeProcessRequest.java | 65 ++--- .../request/DescribeProcessRequestV200.java | 59 ++--- .../server/request/ExecuteRequestV100.java | 129 +++++----- .../server/request/ExecuteRequestV200.java | 41 ++-- .../n52/wps/server/request/InputHandler.java | 79 ++++--- .../response/ExecuteResponseBuilderV100.java | 9 +- .../response/ExecuteResponseBuilderV200.java | 29 +-- .../n52/wps/server/response/ResponseData.java | 131 ++++++----- ...iesGetProcessDescriptionExceptionTest.java | 25 +- .../server/request/ExecuteRequestTest.java | 1 - .../wps/server/request/InputHandlerTest.java | 28 ++- ...SimpleBufferAlgorithmInputHandlerTest.java | 8 +- .../response/ExecuteResponseBuilderTest.java | 7 +- .../server/response/OutputDataItemTest.java | 15 +- .../n52/wps/server/response/RawDataTest.java | 2 - .../n52/wps/server/response/StatusTest.java | 11 +- .../src/main/resources/dispatcher-servlet.xml | 6 +- .../main/webapp/WEB-INF/spring-mvc-config.xml | 2 +- .../GeneratorsControllerIntegrationTest.java | 1 - ...nfigurationsControllerIntegrationTest.java | 11 +- .../web/ParsersControllerIntegrationTest.java | 1 - ...RepositoriesControllerIntegrationTest.java | 1 - .../web/ServerControllerIntegrationTest.java | 3 +- ...entificationControllerIntegrationTest.java | 11 +- ...viceProviderControllerIntegrationTest.java | 13 +- .../web/UploadControllerIntegrationTest.java | 1 - .../web/UsersControllerIntegrationTest.java | 1 - 41 files changed, 817 insertions(+), 734 deletions(-) create mode 100644 52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java diff --git a/52n-wps-algorithm-geotools/src/test/java/org/n52/wps/server/algorithm/SimpleBufferAlgorithmTest.java b/52n-wps-algorithm-geotools/src/test/java/org/n52/wps/server/algorithm/SimpleBufferAlgorithmTest.java index bc01b3d6b..1643deda1 100644 --- a/52n-wps-algorithm-geotools/src/test/java/org/n52/wps/server/algorithm/SimpleBufferAlgorithmTest.java +++ b/52n-wps-algorithm-geotools/src/test/java/org/n52/wps/server/algorithm/SimpleBufferAlgorithmTest.java @@ -87,8 +87,6 @@ public static void tearDownClass() { @Before public void setUp() { - MockMvcBuilders.webAppContextSetup(this.wac).build(); - WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); } @After diff --git a/52n-wps-algorithm/src/main/java/org/n52/wps/server/ServiceLoaderAlgorithmRepository.java b/52n-wps-algorithm/src/main/java/org/n52/wps/server/ServiceLoaderAlgorithmRepository.java index eeeb45ade..a2c0cb2ce 100644 --- a/52n-wps-algorithm/src/main/java/org/n52/wps/server/ServiceLoaderAlgorithmRepository.java +++ b/52n-wps-algorithm/src/main/java/org/n52/wps/server/ServiceLoaderAlgorithmRepository.java @@ -34,20 +34,20 @@ public class ServiceLoaderAlgorithmRepository implements IAlgorithmRepository { public ServiceLoaderAlgorithmRepository() { this.currentAlgorithms = loadAlgorithms(); } - + private Map> loadAlgorithms() { Map> result = new HashMap>(); ServiceLoader loader = ServiceLoader.load(IAlgorithm.class); - + for (IAlgorithm ia : loader) { logger.debug("Adding algorithm with identifier {} and class {}", ia.getWellKnownName(), ia.getClass().getCanonicalName()); result.put(ia.getWellKnownName(), ia.getClass()); } - + return result; } - + @Override public Collection getAlgorithmNames() { return this.currentAlgorithms.keySet(); diff --git a/52n-wps-algorithm/src/test/java/org/n52/wps/server/AbstractSelfDescribingAlgorithmTest.java b/52n-wps-algorithm/src/test/java/org/n52/wps/server/AbstractSelfDescribingAlgorithmTest.java index f0729aefd..053473c25 100644 --- a/52n-wps-algorithm/src/test/java/org/n52/wps/server/AbstractSelfDescribingAlgorithmTest.java +++ b/52n-wps-algorithm/src/test/java/org/n52/wps/server/AbstractSelfDescribingAlgorithmTest.java @@ -33,14 +33,12 @@ * @author tkunicki */ public class AbstractSelfDescribingAlgorithmTest extends AbstractITClass { - + public AbstractSelfDescribingAlgorithmTest() { } @Before public void setUp() throws Exception { - MockMvcBuilders.webAppContextSetup(this.wac).build(); - WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); } @Test diff --git a/52n-wps-client-lib/src/test/java/org/n52/wps/client/test/ExecuteRequestBuilderTest.java b/52n-wps-client-lib/src/test/java/org/n52/wps/client/test/ExecuteRequestBuilderTest.java index 09bda0ab8..634c04143 100644 --- a/52n-wps-client-lib/src/test/java/org/n52/wps/client/test/ExecuteRequestBuilderTest.java +++ b/52n-wps-client-lib/src/test/java/org/n52/wps/client/test/ExecuteRequestBuilderTest.java @@ -61,28 +61,26 @@ public class ExecuteRequestBuilderTest extends AbstractITClass{ - private ProcessDescription processDescription; - private ProcessDescriptionType processDescriptionType; + private ProcessDescription processDescription; + private ProcessDescriptionType processDescriptionType; private String inputID; private String outputID; private String url = "http://xyz.test.data"; private String complexDataString = "testString"; - + @Before public void setUp(){ - MockMvcBuilders.webAppContextSetup(this.wac).build(); - WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); processDescription = new MultiReferenceBinaryInputAlgorithm().getDescription(); - processDescriptionType = ((ProcessDescriptionType)processDescription.getProcessDescriptionType(WPSConfig.VERSION_100)); + processDescriptionType = ((ProcessDescriptionType)processDescription.getProcessDescriptionType(WPSConfig.VERSION_100)); inputID = processDescriptionType.getDataInputs().getInputArray(0).getIdentifier().getStringValue(); outputID = processDescriptionType.getProcessOutputs().getOutputArray(0).getIdentifier().getStringValue(); } - + @Test public void addComplexDataInputByReference() { ExecuteRequestBuilder executeRequestBuilder = new ExecuteRequestBuilder(processDescriptionType); - + addTestDataByReference(executeRequestBuilder); ExecuteDocument request = executeRequestBuilder.getExecute(); @@ -91,151 +89,151 @@ public void addComplexDataInputByReference() { Assert.assertThat("generated doc contains input url", request.toString(), containsString(url)); Assert.assertThat("document is valid", request.validate(), is(true)); } - + @Test public void addComplexDataInputString() { - + ExecuteRequestBuilder executeRequestBuilder = new ExecuteRequestBuilder(processDescriptionType); - + addTestDataString(executeRequestBuilder); - + ExecuteDocument request = executeRequestBuilder.getExecute(); - + Assert.assertThat("generated doc contains input id", request.toString(), containsString(inputID)); Assert.assertThat("generated doc contains input string", request.toString(), containsString(complexDataString)); Assert.assertThat("document is valid", request.validate(), is(true)); } - + @Test public void setSupportedMimeTypeForOutput(){ ExecuteRequestBuilder executeRequestBuilder = new ExecuteRequestBuilder(processDescriptionType); - + addTestDataByReference(executeRequestBuilder); - + String mimeType = getMimeType(processDescriptionType, false); - + executeRequestBuilder.setMimeTypeForOutput(mimeType, outputID); - + ExecuteDocument request = executeRequestBuilder.getExecute(); - + checkOutputIdentifier(request.getExecute(), outputID); checkOutputMimeType(request.getExecute(), mimeType); Assert.assertThat("document is valid", request.validate(), is(true)); - + } - + @Test public void setDefaultMimeTypeForOutput(){ ExecuteRequestBuilder executeRequestBuilder = new ExecuteRequestBuilder(processDescriptionType); - + addTestDataByReference(executeRequestBuilder); - + String mimeType = getMimeType(processDescriptionType, true); - + ExecuteDocument request = executeRequestBuilder.getExecute(); - + executeRequestBuilder.setMimeTypeForOutput(mimeType, outputID); - + checkOutputIdentifier(request.getExecute(), outputID); checkOutputMimeType(request.getExecute(), mimeType); Assert.assertThat("document is valid", request.validate(), is(true)); - + } - + private void addTestDataByReference(ExecuteRequestBuilder executeRequestBuilder){ - + InputType inputType = InputType.Factory.newInstance(); inputType.addNewIdentifier().setStringValue(inputID); inputType.addNewReference().setHref(url); executeRequestBuilder.addComplexData(inputType); - + } - + private void addTestDataString(ExecuteRequestBuilder executeRequestBuilder){ - + try { executeRequestBuilder.addComplexData(inputID, complexDataString, "", "", "text/plain"); } catch (WPSClientException e) { e.printStackTrace(); } - + } - + private String getMimeType(ProcessDescriptionType processDescriptionType, boolean isGetDefaultMimeType){ - + String result = ""; - + ProcessOutputs processOutputs = processDescriptionType.getProcessOutputs(); - + assertNotNull(processOutputs); - + OutputDescriptionType outputDescriptionType = processOutputs.getOutputArray(0); - + assertNotNull(outputDescriptionType); - + SupportedComplexDataType complexDataType = outputDescriptionType.getComplexOutput(); - + assertNotNull(complexDataType); - + if(isGetDefaultMimeType){ ComplexDataCombinationType defaultFormat = complexDataType.getDefault(); - + assertNotNull(defaultFormat); - + ComplexDataDescriptionType format = defaultFormat.getFormat(); - + assertNotNull(format); - - result = format.getMimeType(); + + result = format.getMimeType(); }else{ ComplexDataCombinationsType supportedFormats = complexDataType.getSupported(); - + assertNotNull(supportedFormats); - + ComplexDataDescriptionType format = supportedFormats.getFormatArray(0); - + assertNotNull(format); - - result = format.getMimeType(); + + result = format.getMimeType(); } - + return result; } private void checkOutputMimeType(Execute execute, String mimeType){ - + DocumentOutputDefinitionType outputDefinitionType = getOutputDefinitionType(execute); - - assertTrue(outputDefinitionType.getMimeType() != null && outputDefinitionType.getMimeType().equals(mimeType)); - + + assertTrue(outputDefinitionType.getMimeType() != null && outputDefinitionType.getMimeType().equals(mimeType)); + } - + private void checkOutputIdentifier(Execute execute, String identifier){ - + DocumentOutputDefinitionType outputDefinitionType = getOutputDefinitionType(execute); - - assertTrue(outputDefinitionType.getIdentifier() != null && outputDefinitionType.getIdentifier().getStringValue().equals(identifier)); - + + assertTrue(outputDefinitionType.getIdentifier() != null && outputDefinitionType.getIdentifier().getStringValue().equals(identifier)); + } - + private DocumentOutputDefinitionType getOutputDefinitionType(Execute execute){ - + ResponseFormType responseFormType = execute.getResponseForm(); - + assertNotNull(responseFormType); - + ResponseDocumentType responseDocumentType = responseFormType.getResponseDocument(); - + assertNotNull(responseDocumentType); - + DocumentOutputDefinitionType outputDefinitionType = responseDocumentType.getOutputArray(0); - - assertNotNull(outputDefinitionType); - + + assertNotNull(outputDefinitionType); + return outputDefinitionType; - + } - + } diff --git a/52n-wps-commons/src/main/java/org/n52/wps/commons/WPSConfig.java b/52n-wps-commons/src/main/java/org/n52/wps/commons/WPSConfig.java index 55b724db3..ca4bd78b1 100644 --- a/52n-wps-commons/src/main/java/org/n52/wps/commons/WPSConfig.java +++ b/52n-wps-commons/src/main/java/org/n52/wps/commons/WPSConfig.java @@ -41,7 +41,7 @@ import org.slf4j.LoggerFactory; /** - * + * * @author Benjamin Pross, Daniel Nüst * */ @@ -66,19 +66,20 @@ public class WPSConfig implements Serializable { public static final String VERSION_100 = "1.0.0"; public static final String VERSION_200 = "2.0.0"; public static final List SUPPORTED_VERSIONS = Arrays.asList(new String[]{VERSION_100, VERSION_200}); - + public static final String JOB_CONTROL_OPTION_SYNC_EXECUTE = "sync-execute"; public static final String JOB_CONTROL_OPTION_ASYNC_EXECUTE = "async-execute"; - + public static final String JOB_CONTROL_OPTIONS_SEPARATOR = " "; - + public static final String OUTPUT_TRANSMISSION_VALUE = "value"; public static final String OUTPUT_TRANSMISSION_REFERENCE = "reference"; - + public static final String OUTPUT_TRANSMISSIONS_SEPARATOR = " "; - + private ConfigurationManager configurationManager; - private Server serverConfigurationModule; + + private Server serverConfigurationModule; public Server getServerConfigurationModule() { @@ -176,46 +177,46 @@ public String getServiceEndpoint() { } public List> getConfigurationEntriesForGeneratorClass( - String name) { + String name) { ConfigurationModule module = getConfigurationModuleForClass(name, ConfigurationCategory.GENERATOR); return (module == null) ? new ArrayList>() : module.getConfigurationEntries(); } - public List getFormatEntriesForGeneratorClass(String name) { + public List getFormatEntriesForGeneratorClass(String name) { ConfigurationModule module = getConfigurationModuleForClass(name, ConfigurationCategory.GENERATOR); return (module == null) ? new ArrayList() : module.getFormatEntries(); } public List> getConfigurationEntriesForParserClass( - String name) { + String name) { ConfigurationModule module = getConfigurationModuleForClass(name, ConfigurationCategory.PARSER); return (module == null) ? new ArrayList>() : module.getConfigurationEntries(); } - public List getFormatEntriesForParserClass(String name) { + public List getFormatEntriesForParserClass(String name) { ConfigurationModule module = getConfigurationModuleForClass(name, ConfigurationCategory.PARSER); return (module == null) ? new ArrayList() : module.getFormatEntries(); } - + public ConfigurationModule getConfigurationModuleForClass(String name, ConfigurationCategory moduleCategorie){ - + Map activeModules = getActiveConfigurationModules(moduleCategorie); - + for (String moduleName : activeModules.keySet()) { - + ConfigurationModule tmpModule = activeModules.get(moduleName); - + if(!(tmpModule instanceof ClassKnowingModule)){ continue; } - + if(((ClassKnowingModule)tmpModule).getClassName().equals(name)){ - return tmpModule; - } + return tmpModule; + } } return null; } - + private Map getActiveConfigurationModules(ConfigurationCategory moduleCategorie){ return configurationManager.getConfigurationServices().getActiveConfigurationModulesByCategory(moduleCategorie); } diff --git a/52n-wps-commons/src/test/java/org/n52/wps/webapp/common/AbstractITClass.java b/52n-wps-commons/src/test/java/org/n52/wps/webapp/common/AbstractITClass.java index 1d1f23f8d..5e44ee00a 100644 --- a/52n-wps-commons/src/test/java/org/n52/wps/webapp/common/AbstractITClass.java +++ b/52n-wps-commons/src/test/java/org/n52/wps/webapp/common/AbstractITClass.java @@ -16,20 +16,30 @@ */ package org.n52.wps.webapp.common; +import org.junit.Before; import org.junit.runner.RunWith; +import org.n52.wps.commons.WPSConfig; +import org.n52.wps.webapp.api.ConfigurationManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:applicationContext.xml", +@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:dispatcher-servlet.xml"}) @WebAppConfiguration @ActiveProfiles("test") public class AbstractITClass { @Autowired protected WebApplicationContext wac; + + @Before + public void setup() { + MockMvcBuilders.webAppContextSetup(this.wac).build(); + WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); + } } diff --git a/52n-wps-commons/src/test/java/org/n52/wps/webapp/common/AbstractITClassForControllerTests.java b/52n-wps-commons/src/test/java/org/n52/wps/webapp/common/AbstractITClassForControllerTests.java index f7060c59d..ffd493e78 100644 --- a/52n-wps-commons/src/test/java/org/n52/wps/webapp/common/AbstractITClassForControllerTests.java +++ b/52n-wps-commons/src/test/java/org/n52/wps/webapp/common/AbstractITClassForControllerTests.java @@ -16,26 +16,36 @@ */ package org.n52.wps.webapp.common; +import org.junit.Before; import org.junit.runner.RunWith; +import org.n52.wps.commons.WPSConfig; +import org.n52.wps.webapp.api.ConfigurationManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; /** - * Loads Testmodules, which are omitted for other tests. - * + * Loads Testmodules, which are omitted for other tests. + * * @author Benjamin Pross * */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:applicationContext.xml", +@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:dispatcher-servlet.xml"}) @WebAppConfiguration @ActiveProfiles("controller-test") public class AbstractITClassForControllerTests { @Autowired protected WebApplicationContext wac; + + @Before + public void setup() { + MockMvcBuilders.webAppContextSetup(this.wac).build(); + WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); + } } diff --git a/52n-wps-io-geotools/src/test/java/org/n52/wps/io/test/datahandler/OMGeneratorTest.java b/52n-wps-io-geotools/src/test/java/org/n52/wps/io/test/datahandler/OMGeneratorTest.java index 18f2b042a..f225d2bd7 100644 --- a/52n-wps-io-geotools/src/test/java/org/n52/wps/io/test/datahandler/OMGeneratorTest.java +++ b/52n-wps-io-geotools/src/test/java/org/n52/wps/io/test/datahandler/OMGeneratorTest.java @@ -79,36 +79,36 @@ /** * @author Eike Hinderk Jürrens - * + * * @since 4.0.0 * */ public class OMGeneratorTest extends AbstractTestCase { - + private static final String SCHEMA = "http://www.opengis.net/om/2.0"; private static final String MIME_TYPE = "application/om+xml; version=2.0"; - + @Test public void shouldReturnNullIfInputIsWrong() throws IOException { InputStream result = dataHandler.generateStream(null, null, null); assertThat(result, is(nullValue())); - + result = dataHandler.generateStream(null, "test", null); assertThat(result, is(nullValue())); - + result = dataHandler.generateStream(null, MIME_TYPE, null); assertThat(result, is(nullValue())); - + result = dataHandler.generateStream(null, MIME_TYPE, "test"); assertThat(result, is(nullValue())); - + result = dataHandler.generateStream(null, MIME_TYPE, SCHEMA); assertThat(result, is(nullValue())); - + result = dataHandler.generateStream(new OMObservationBinding(null), MIME_TYPE, SCHEMA); assertThat(result, is(nullValue())); } - + @Test @Ignore("no xmloptions injected yet") public void shouldEncodeSingleOMObservationToXML() throws IOException { @@ -158,14 +158,14 @@ public void shouldEncodeSingleOMObservationToXML() throws IOException { InputStream generatedStream = dataHandler.generateStream(dataToEncode, MIME_TYPE, SCHEMA); assertThat(generatedStream, is(not(nullValue()))); assertThat(generatedStream, instanceOf(InputStream.class)); - + OMObservationBinding parsedObservationBinding = new OMParser().parse(generatedStream, MIME_TYPE, SCHEMA); assertThat(parsedObservationBinding, is(not(nullValue()))); OmObservation parsedObservation = parsedObservationBinding.getPayload(); assertThat(parsedObservation.getDescription(), is(description)); assertThat(parsedObservation.getIdentifier(), is(identifier)); assertThat(parsedObservation.getPhenomenonTime(), is((Time)time)); - assertThat((double)parsedObservation.getValue().getValue().getValue(), is(new Double(value))); + assertThat((Double)parsedObservation.getValue().getValue().getValue(), is(new Double(value))); assertThat(parsedObservation.getValue().getValue().getUnit(), is(unit)); assertThat(parsedObservation.getResultTime().isReferenced(), is(true)); assertThat(parsedObservation.getResultTime().getReference(), is("phenomenonTime")); @@ -187,5 +187,5 @@ public void shouldEncodeSingleOMObservationToXML() throws IOException { protected void initializeDataHandler() { dataHandler = new OMGenerator(); } - + } diff --git a/52n-wps-io/src/test/java/org/n52/wps/io/test/datahandler/AbstractTestCase.java b/52n-wps-io/src/test/java/org/n52/wps/io/test/datahandler/AbstractTestCase.java index 31344f4f1..b9db92d08 100644 --- a/52n-wps-io/src/test/java/org/n52/wps/io/test/datahandler/AbstractTestCase.java +++ b/52n-wps-io/src/test/java/org/n52/wps/io/test/datahandler/AbstractTestCase.java @@ -34,16 +34,14 @@ public abstract class AbstractTestCase extends Abs protected T dataHandler; - public AbstractTestCase() { + public AbstractTestCase() { File f = new File(this.getClass().getProtectionDomain().getCodeSource() .getLocation().getFile()); projectRoot = f.getParentFile().getParentFile().getParent(); } - + @Before public void setUp(){ - MockMvcBuilders.webAppContextSetup(this.wac).build(); - WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); initializeDataHandler(); } diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/CapabilitiesConfiguration.java b/52n-wps-server/src/main/java/org/n52/wps/server/CapabilitiesConfiguration.java index 34e7bf45d..b9680ada5 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/CapabilitiesConfiguration.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/CapabilitiesConfiguration.java @@ -62,10 +62,10 @@ * {@linkplain #getInstance(java.io.File) file}, {@linkplain #getInstance(java.net.URL) URL}, * {@linkplain #getInstance(java.lang.String) path} or * {@linkplain #getInstance(net.opengis.wps.x100.CapabilitiesDocument) instance}. - * + * * @author foerster * @author Christian Autermann - * + * */ public class CapabilitiesConfiguration { private static final Logger LOG = LoggerFactory.getLogger(CapabilitiesConfiguration.class); @@ -88,12 +88,12 @@ private CapabilitiesConfiguration() { * Gets the WPS Capabilities using the specified file to obtain the skeleton. All future calls to * {@link #getInstance()} and {@link #getInstance(boolean) * } will use this file to obtain the skeleton. - * + * * @param filePath * the File pointing to a skeleton - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -107,12 +107,12 @@ public static CapabilitiesDocument getInstance(String filePath) throws XmlExcept * Gets the WPS Capabilities using the specified file to obtain the skeleton. All future calls to * {@link #getInstance()} and {@link #getInstance(boolean) * } will use this file to obtain the skeleton. - * + * * @param file * the File pointing to a skeleton - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -126,12 +126,12 @@ public static CapabilitiesDocument getInstance(File file) throws XmlException, I * Gets the WPS Capabilities using the specified URL to obtain the skeleton. All future calls to * {@link #getInstance()} and {@link #getInstance(boolean) * } will use this URL to obtain the skeleton. - * + * * @param url * the URL pointing to a skeleton - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -144,12 +144,12 @@ public static CapabilitiesDocument getInstance(URL url) throws XmlException, IOE /** * Gets the WPS Capabilities using the specified skeleton. All future calls to {@link #getInstance()} and * {@link #getInstance(boolean) } will use this skeleton. - * + * * @param skel * the skeleton - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -162,12 +162,12 @@ public static CapabilitiesDocument getInstance(CapabilitiesDocument skel) throws /** * Gets the WPS Capabilities using the specified strategy. All future calls to {@link #getInstance()} and * {@link #getInstance(boolean) } will use this strategy. - * + * * @param strategy * the strategy to load the skeleton - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -192,9 +192,9 @@ private static CapabilitiesDocument getInstance(CapabilitiesSkeletonLoadingStrat /** * Get the WPS Capabilities for this service. The capabilities are reloaded if caching is not enabled in * the WPS configuration. - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -207,12 +207,12 @@ public static CapabilitiesDocument getInstance() throws XmlException, IOExceptio /** * Get the WPS Capabilities for this service and optionally force a reload. - * + * * @param reload * if the capabilities should be reloaded - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -234,10 +234,10 @@ public static CapabilitiesDocument getInstance(boolean reload) throws XmlExcepti /** * Enriches a capabilities skeleton by adding the endpoint URL and creating the process offerings. - * + * * @param skel * the skeleton to enrich - * + * * @throws UnknownHostException * if the local host name can not be obtained */ @@ -252,21 +252,21 @@ private static void initSkeleton(CapabilitiesDocument skel) throws UnknownHostEx /** * Enriches the capabilities skeleton by creating the process offerings. - * + * * @param skel * the skeleton to enrich */ private static void initProcessOfferings(CapabilitiesDocument skel) { ProcessOfferings processes = skel.getCapabilities() .addNewProcessOfferings(); - RepositoryManager rm = RepositoryManager.getInstance(); + RepositoryManager rm = RepositoryManagerSingletonWrapper.getInstance(); List algorithms = rm.getAlgorithms(); if (algorithms.isEmpty()) LOG.warn("No algorithms found in repository manager."); for (String algorithmName : algorithms) { try { - ProcessDescriptionType description = (ProcessDescriptionType) RepositoryManager + ProcessDescriptionType description = (ProcessDescriptionType) RepositoryManagerSingletonWrapper .getInstance().getProcessDescription(algorithmName).getProcessDescriptionType(WPSConfig.VERSION_100); if (description != null) { ProcessBriefType process = processes.addNewProcess(); @@ -277,7 +277,7 @@ private static void initProcessOfferings(CapabilitiesDocument skel) { process.setProcessVersion(processVersion); process.setTitle(title); LOG.trace("Added algorithm to process offerings: {}\n\t\t{}", algorithmName, process); - } + } } catch (RuntimeException e) { LOG.warn("Exception during instantiation of process {}", algorithmName, e); @@ -287,12 +287,12 @@ private static void initProcessOfferings(CapabilitiesDocument skel) { /** * Enriches a capabilities skeleton by adding the endpoint URL to the operations meta data. - * + * * @param skel * the skeleton to enrich * @param endpointUrl * the endpoint URL of the service - * + * */ private static void initOperationsMetadata(CapabilitiesDocument skel, String endpointUrl) { if (skel.getCapabilities().getOperationsMetadata() != null) { @@ -313,9 +313,9 @@ private static void initOperationsMetadata(CapabilitiesDocument skel, String end /** * Gets the endpoint URL of this service by checking the configuration file and the local host name. - * + * * @return the endpoint URL - * + * * @throws UnknownHostException * if the local host name could not be resolved into an address */ @@ -326,7 +326,7 @@ private static String getEndpointURL() throws UnknownHostException { /** * Force a reload of the capabilities skeleton. - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -338,7 +338,7 @@ public static void reloadSkeleton() throws XmlException, IOException { /** * Checks if the capabilities document is loaded. - * + * * @return if the capabilities are ready. */ public static boolean ready() { @@ -350,7 +350,7 @@ public static boolean ready() { lock.unlock(); } } - + public static Server getServerConfigurationModule() { if (serverConfigurationModule == null) { @@ -375,7 +375,7 @@ private static class URLLoadingStrategy implements CapabilitiesSkeletonLoadingSt /** * Creates a new strategy using the specified URL. - * + * * @param file * the file */ @@ -405,7 +405,7 @@ public int hashCode() { /** * Gets the URL of this strategy. - * + * * @return the URL; */ public URL getUrl() { @@ -420,7 +420,7 @@ private static class FileLoadingStrategy extends URLLoadingStrategy { /** * Creates a new strategy using the specified file. - * + * * @param file * the file */ @@ -430,7 +430,7 @@ private static class FileLoadingStrategy extends URLLoadingStrategy { /** * Creates a new strategy using the specified file. - * + * * @param file * the path to the file */ @@ -448,7 +448,7 @@ private static class InstanceStrategy implements CapabilitiesSkeletonLoadingStra /** * Creates a new strategy using the specified instance. - * + * * @param instance * the instance */ @@ -477,7 +477,7 @@ public int hashCode() { /** * Gets the instance of this strategy. - * + * * @return the instance */ public CapabilitiesDocument getInstance() { @@ -491,9 +491,9 @@ public CapabilitiesDocument getInstance() { private interface CapabilitiesSkeletonLoadingStrategy { /** * Loads a CapabilitiesDocument skeleton. Every call to this method should return another instance. - * + * * @return the capabilities skeleton - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/CapabilitiesConfigurationV200.java b/52n-wps-server/src/main/java/org/n52/wps/server/CapabilitiesConfigurationV200.java index 59fde2478..f7530dd18 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/CapabilitiesConfigurationV200.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/CapabilitiesConfigurationV200.java @@ -74,11 +74,11 @@ * {@linkplain #getInstance(java.io.File) file}, {@linkplain #getInstance(java.net.URL) URL}, * {@linkplain #getInstance(java.lang.String) path} or * {@linkplain #getInstance(net.opengis.wps.x200.CapabilitiesDocument) instance}. - * + * * @author foerster * @author Christian Autermann * @author Benjamin Pross - * + * */ public class CapabilitiesConfigurationV200 { private static final Logger LOG = LoggerFactory.getLogger(CapabilitiesConfigurationV200.class); @@ -90,8 +90,8 @@ public class CapabilitiesConfigurationV200 { private static CapabilitiesSkeletonLoadingStrategy loadingStrategy; private static ConfigurationManager configurationManager; - private static org.n52.wps.webapp.entities.ServiceIdentification serviceIdentificationConfigurationModule; - private static org.n52.wps.webapp.entities.ServiceProvider serviceProviderConfigurationModule; + private static org.n52.wps.webapp.entities.ServiceIdentification serviceIdentificationConfigurationModule; + private static org.n52.wps.webapp.entities.ServiceProvider serviceProviderConfigurationModule; private CapabilitiesConfigurationV200() { /* nothing here */ @@ -101,12 +101,12 @@ private CapabilitiesConfigurationV200() { * Gets the WPS Capabilities using the specified file to obtain the skeleton. All future calls to * {@link #getInstance()} and {@link #getInstance(boolean) * } will use this file to obtain the skeleton. - * + * * @param filePath * the File pointing to a skeleton - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -120,12 +120,12 @@ public static CapabilitiesDocument getInstance(String filePath) throws XmlExcept * Gets the WPS Capabilities using the specified file to obtain the skeleton. All future calls to * {@link #getInstance()} and {@link #getInstance(boolean) * } will use this file to obtain the skeleton. - * + * * @param file * the File pointing to a skeleton - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -139,12 +139,12 @@ public static CapabilitiesDocument getInstance(File file) throws XmlException, I * Gets the WPS Capabilities using the specified URL to obtain the skeleton. All future calls to * {@link #getInstance()} and {@link #getInstance(boolean) * } will use this URL to obtain the skeleton. - * + * * @param url * the URL pointing to a skeleton - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -157,12 +157,12 @@ public static CapabilitiesDocument getInstance(URL url) throws XmlException, IOE /** * Gets the WPS Capabilities using the specified skeleton. All future calls to {@link #getInstance()} and * {@link #getInstance(boolean) } will use this skeleton. - * + * * @param skel * the skeleton - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -175,12 +175,12 @@ public static CapabilitiesDocument getInstance(CapabilitiesDocument skel) throws /** * Gets the WPS Capabilities using the specified strategy. All future calls to {@link #getInstance()} and * {@link #getInstance(boolean) } will use this strategy. - * + * * @param strategy * the strategy to load the skeleton - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -205,9 +205,9 @@ private static CapabilitiesDocument getInstance(CapabilitiesSkeletonLoadingStrat /** * Get the WPS Capabilities for this service. The capabilities are reloaded if caching is not enabled in * the WPS configuration. - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -220,12 +220,12 @@ public static CapabilitiesDocument getInstance() throws XmlException, IOExceptio /** * Get the WPS Capabilities for this service and optionally force a reload. - * + * * @param reload * if the capabilities should be reloaded - * + * * @return the capabilities document - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -235,11 +235,11 @@ public static CapabilitiesDocument getInstance(boolean reload) throws XmlExcepti lock.lock(); try { if (capabilitiesDocumentObj == null || reload) { - + if(loadingStrategy == null){ loadingStrategy = new CreateInstanceStrategy(); } - + capabilitiesDocumentObj = loadingStrategy.loadSkeleton(); initSkeleton(capabilitiesDocumentObj); } @@ -252,10 +252,10 @@ public static CapabilitiesDocument getInstance(boolean reload) throws XmlExcepti /** * Enriches a capabilities skeleton by adding the endpoint URL and creating the process offerings. - * + * * @param skel * the skeleton to enrich - * + * * @throws UnknownHostException * if the local host name can not be obtained */ @@ -270,21 +270,21 @@ private static void initSkeleton(CapabilitiesDocument skel) throws UnknownHostEx /** * Enriches the capabilities skeleton by creating the process offerings. - * + * * @param skel * the skeleton to enrich */ private static void initProcessOfferings(CapabilitiesDocument skel) { Contents contents = skel.getCapabilities() .addNewContents(); - for (String algorithmName : RepositoryManager.getInstance() + for (String algorithmName : RepositoryManagerSingletonWrapper.getInstance() .getAlgorithms()) { try { - ProcessOffering offering = (ProcessOffering) RepositoryManager + ProcessOffering offering = (ProcessOffering) RepositoryManagerSingletonWrapper .getInstance().getProcessDescription(algorithmName).getProcessDescriptionType(WPSConfig.VERSION_200); - + ProcessDescriptionType description = offering.getProcess(); - + if (description != null) { ProcessSummaryType process = contents.addNewProcessSummary(); CodeType ct = process.addNewIdentifier(); @@ -292,21 +292,21 @@ private static void initProcessOfferings(CapabilitiesDocument skel) { //a title is mandatory for a process offering LanguageStringType title = null; try { - title = description.getTitleArray(0); + title = description.getTitleArray(0); } catch (Exception e) { throw new RuntimeException(String.format("Process offering for process '{}' not valid. No title specified.", algorithmName)); } String processVersion = offering.getProcessVersion(); process.setProcessVersion(processVersion); - + process.setJobControlOptions(offering.getJobControlOptions()); - + process.setOutputTransmission(offering.getOutputTransmission()); process.addNewTitle().setStringValue(title.getStringValue()); - + LOG.trace("Added algorithm to process offerings: {}\n\t\t{}", algorithmName, process); - } + } } catch (RuntimeException e) { LOG.warn("Exception during instantiation of process {}", algorithmName, e); @@ -316,12 +316,12 @@ private static void initProcessOfferings(CapabilitiesDocument skel) { /** * Enriches a capabilities skeleton by adding the endpoint URL to the operations meta data. - * + * * @param skel * the skeleton to enrich * @param endpointUrl * the endpoint URL of the service - * + * */ private static void initOperationsMetadata(CapabilitiesDocument skel, String endpointUrl) { if (skel.getCapabilities().getOperationsMetadata() != null) { @@ -342,9 +342,9 @@ private static void initOperationsMetadata(CapabilitiesDocument skel, String end /** * Gets the endpoint URL of this service by checking the configuration file and the local host name. - * + * * @return the endpoint URL - * + * * @throws UnknownHostException * if the local host name could not be resolved into an address */ @@ -354,7 +354,7 @@ private static String getEndpointURL() throws UnknownHostException { /** * Force a reload of the capabilities skeleton. - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException @@ -366,7 +366,7 @@ public static void reloadSkeleton() throws XmlException, IOException { /** * Checks if the capabilities document is loaded. - * + * * @return if the capabilities are ready. */ public static boolean ready() { @@ -378,7 +378,7 @@ public static boolean ready() { lock.unlock(); } } - + public static ConfigurationManager getConfigurationManager() { if (configurationManager == null) { @@ -396,7 +396,7 @@ private static class URLLoadingStrategy implements CapabilitiesSkeletonLoadingSt /** * Creates a new strategy using the specified URL. - * + * * @param file * the file */ @@ -426,7 +426,7 @@ public int hashCode() { /** * Gets the URL of this strategy. - * + * * @return the URL; */ public URL getUrl() { @@ -441,7 +441,7 @@ private static class FileLoadingStrategy extends URLLoadingStrategy { /** * Creates a new strategy using the specified file. - * + * * @param file * the file */ @@ -451,7 +451,7 @@ private static class FileLoadingStrategy extends URLLoadingStrategy { /** * Creates a new strategy using the specified file. - * + * * @param file * the path to the file */ @@ -469,7 +469,7 @@ private static class InstanceStrategy implements CapabilitiesSkeletonLoadingStra /** * Creates a new strategy using the specified instance. - * + * * @param instance * the instance */ @@ -498,7 +498,7 @@ public int hashCode() { /** * Gets the instance of this strategy. - * + * * @return the instance */ public CapabilitiesDocument getInstance() { @@ -514,100 +514,100 @@ private static class CreateInstanceStrategy implements CapabilitiesSkeletonLoadi /** * Creates a new strategy using the specified instance. - * + * * @param instance * the instance */ CreateInstanceStrategy() { this.instance = CapabilitiesDocument.Factory.newInstance(); - + serviceIdentificationConfigurationModule = getConfigurationManager().getCapabilitiesServices().getServiceIdentification(); - + serviceProviderConfigurationModule = getConfigurationManager().getCapabilitiesServices().getServiceProvider(); - + WPSCapabilitiesType wpsCapabilities = instance.addNewCapabilities(); - + XmlCursor c = instance.newCursor(); c.toFirstChild(); c.toLastAttribute(); c.setAttributeText(new QName(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation"), "http://www.opengis.net/wps/2.0 http://schemas.opengis.net/wps/2.0/wps.xsd"); - + wpsCapabilities.addNewService().setStringValue("WPS");//Fixed to WPS TODO: put in WPSConfig or so - + wpsCapabilities.setVersion(WPSConfig.VERSION_200); - + ServiceProvider serviceProvider = wpsCapabilities.addNewServiceProvider(); - + serviceProvider.setProviderName(serviceProviderConfigurationModule.getProviderName() != null ? serviceProviderConfigurationModule.getProviderName() : ""); - + serviceProvider.addNewProviderSite().setHref(serviceProviderConfigurationModule.getProviderSite() != null ? serviceProviderConfigurationModule.getProviderSite() : ""); - + ResponsiblePartySubsetType responsiblePartySubsetType = serviceProvider.addNewServiceContact(); - + responsiblePartySubsetType.setIndividualName(serviceProviderConfigurationModule.getIndividualName() != null ? serviceProviderConfigurationModule.getIndividualName() : ""); - + ContactType contactType = responsiblePartySubsetType.addNewContactInfo(); - + AddressType addressType = contactType.addNewAddress(); - + addressType.setAdministrativeArea(serviceProviderConfigurationModule.getAdministrativeArea() != null ? serviceProviderConfigurationModule.getAdministrativeArea() : ""); - + addressType.setCity(serviceProviderConfigurationModule.getCity() != null ? serviceProviderConfigurationModule.getCity() : ""); - + addressType.setCountry(serviceProviderConfigurationModule.getCountry() != null ? serviceProviderConfigurationModule.getCountry() : ""); - + addressType.setPostalCode(serviceProviderConfigurationModule.getPostalCode() != null ? serviceProviderConfigurationModule.getPostalCode() : ""); - + addressType.addDeliveryPoint(serviceProviderConfigurationModule.getDeliveryPoint() != null ? serviceProviderConfigurationModule.getDeliveryPoint() : ""); - + addressType.addElectronicMailAddress(serviceProviderConfigurationModule.getEmail() != null ? serviceProviderConfigurationModule.getEmail() : ""); - + ServiceIdentification serviceIdentification = wpsCapabilities.addNewServiceIdentification(); - + serviceIdentification.addNewTitle().setStringValue(serviceIdentificationConfigurationModule.getTitle() != null ? serviceIdentificationConfigurationModule.getTitle() : ""); - + serviceIdentification.addAccessConstraints(serviceIdentificationConfigurationModule.getAccessConstraints() != null ? serviceIdentificationConfigurationModule.getAccessConstraints() : ""); - + serviceIdentification.addNewAbstract().setStringValue(serviceIdentificationConfigurationModule.getServiceAbstract() != null ? serviceIdentificationConfigurationModule.getServiceAbstract() : ""); - + serviceIdentification.addNewServiceType().setStringValue("WPS");//Fixed to WPS - - String[] versionArray = serviceIdentificationConfigurationModule.getServiceTypeVersions().split(";"); - + + String[] versionArray = serviceIdentificationConfigurationModule.getServiceTypeVersions().split(";"); + for (String version : versionArray) { if(version.trim() != ""){ serviceIdentification.addNewServiceTypeVersion().setStringValue(version); } } - + serviceIdentification.setFees(serviceIdentificationConfigurationModule.getFees() != null ? serviceIdentificationConfigurationModule.getFees() : ""); - - String[] keywordArray = serviceIdentificationConfigurationModule.getKeywords().split(";"); - + + String[] keywordArray = serviceIdentificationConfigurationModule.getKeywords().split(";"); + KeywordsType keywordsType = serviceIdentification.addNewKeywords(); - + for (String keyword : keywordArray) { if(keyword.trim() != ""){ keywordsType.addNewKeyword().setStringValue(keyword); } } - + OperationsMetadata operationsMetadata = wpsCapabilities.addNewOperationsMetadata(); - + String wpsWebappPath = WPSConfig.getInstance().getServiceBaseUrl(); - + String getHREF = wpsWebappPath.endsWith("/") ? wpsWebappPath.substring(0, wpsWebappPath.length()-1) : wpsWebappPath; - + getHREF = getHREF.concat("?"); - + String postHREF = wpsWebappPath; - + addOperation(operationsMetadata, "GetCapabilities", getHREF, postHREF); addOperation(operationsMetadata, "DescribeProcess", getHREF, postHREF); addOperation(operationsMetadata, "Execute", "", postHREF); addOperation(operationsMetadata, "GetStatus", getHREF, postHREF); addOperation(operationsMetadata, "GetResult", getHREF, postHREF); - + wpsCapabilities.addNewLanguages().addLanguage("en-US"); } @@ -632,40 +632,40 @@ public int hashCode() { /** * Gets the instance of this strategy. - * + * * @return the instance */ public CapabilitiesDocument getInstance() { return instance; } - + private void addOperation(OperationsMetadata operationsMetadata, String operationName, String getHREF, String postHREF){ - + Operation operation = operationsMetadata.addNewOperation(); - + operation.setName(operationName); - + HTTP http = operation.addNewDCP().addNewHTTP(); - + if(getHREF != null && !getHREF.equals("")){ - http.addNewGet().setHref(getHREF); + http.addNewGet().setHref(getHREF); } if(postHREF != null && !postHREF.equals("")){ - http.addNewPost().setHref(postHREF); + http.addNewPost().setHref(postHREF); } - + } } - + /** * Strategy to load a capabilities skeleton. */ private interface CapabilitiesSkeletonLoadingStrategy { /** * Loads a CapabilitiesDocument skeleton. Every call to this method should return another instance. - * + * * @return the capabilities skeleton - * + * * @throws XmlException * if the Capabilities skeleton is not valid * @throws IOException diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java index 1a24d6d30..5f82d811d 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java @@ -40,102 +40,106 @@ import org.n52.wps.webapp.api.ConfigurationModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanNotOfRequiredTypeException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; /** * @author Bastian Schaeffer, University of Muenster * */ -public class RepositoryManager { - - private static RepositoryManager instance; +public class RepositoryManager implements ApplicationContextAware { + private static Logger LOGGER = LoggerFactory.getLogger(RepositoryManager.class); - private Map repositories; - private ProcessIDRegistry globalProcessIDs = ProcessIDRegistry.getInstance(); - private UpdateThread updateThread; - - private RepositoryManager(){ - - // clear registry + + private ApplicationContext applicationContext; + + private Map repositories = new HashMap<>(); + + private ProcessIDRegistry globalProcessIDs = ProcessIDRegistry.getInstance(); + + private UpdateThread updateThread; + + public void init() { + RepositoryManagerSingletonWrapper.init(this); + globalProcessIDs.clearRegistry(); - - // initialize all Repositories loadAllRepositories(); // FvK: added Property Change Listener support // creates listener and register it to the wpsConfig instance. - WPSConfig.getInstance().addPropertyChangeListener(WPSConfig.WPSCONFIG_PROPERTY_EVENT_NAME, new PropertyChangeListener() { - public void propertyChange( - final PropertyChangeEvent propertyChangeEvent) { - LOGGER.info("Received Property Change Event: {}", - propertyChangeEvent.getPropertyName()); - loadAllRepositories(); - } - }); - + WPSConfig.getInstance().addPropertyChangeListener(WPSConfig.WPSCONFIG_PROPERTY_EVENT_NAME, + (final PropertyChangeEvent propertyChangeEvent) -> { + LOGGER.info("Received Property Change Event: {}", + propertyChangeEvent.getPropertyName()); + loadAllRepositories(); + }); + Double updateHours = WPSConfig.getInstance().getWPSConfig().getServerConfigurationModule().getRepoReloadInterval(); - if (updateHours != 0){ LOGGER.info("Setting repository update period to {} hours.", updateHours); updateHours = updateHours * 3600 * 1000; // make milliseconds long updateInterval = updateHours.longValue(); - this.updateThread = new UpdateThread(updateInterval); + this.updateThread = new UpdateThread(this, updateInterval); updateThread.start(); } - - - } + } + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } private List getRepositoryNames(){ - + List repositoryNames = new ArrayList<>(); - - Map repositoryMap = WPSConfig.getInstance().getRegisteredAlgorithmRepositoryConfigModules(); - + + Map repositoryMap = WPSConfig.getInstance() + .getRegisteredAlgorithmRepositoryConfigModules(); + for (ConfigurationModule repository : repositoryMap.values()) { - if(repository.isActive()==false){ continue; } - - String repositoryClassName = ""; - + if(repository instanceof ClassKnowingModule){ - repositoryClassName = ((ClassKnowingModule)repository).getClassName(); + String repositoryClassName = ((ClassKnowingModule)repository).getClassName(); repositoryNames.add(repositoryClassName); if(!repositories.containsKey(repositoryClassName)){ loadRepository(repository.getClass().getCanonicalName(), repositoryClassName, repositoryMap); } } - + } - + return repositoryNames; } - + private void loadAllRepositories(){ repositories = new HashMap(); LOGGER.debug("Loading all repositories: {} (doing a gc beforehand...)", repositories);//FIXME not sure log statement makes a lot of sense System.gc(); - Map repositoryMap = WPSConfig.getInstance().getRegisteredAlgorithmRepositoryConfigModules(); - + Map repositoryMap = WPSConfig.getInstance() + .getRegisteredAlgorithmRepositoryConfigModules(); + for (String repositoryName : repositoryMap.keySet()) { ConfigurationModule repository = repositoryMap.get(repositoryName); - - String repositoryClassName = ""; if (repository instanceof ClassKnowingModule) { - repositoryClassName = ((ClassKnowingModule) repository) - .getClassName(); + String repositoryClassName = ((ClassKnowingModule) repository).getClassName(); loadRepository(repositoryName, repositoryClassName, repositoryMap); - }else{ + } else { LOGGER.warn("Repository {} not instanceof ClassKnowingModule. Will not load it.", repositoryName); } } } - + private void loadRepository(String repositoryName, String repositoryClassName, Map repositoryMap) { LOGGER.debug("Loading repository: {}", repositoryName); @@ -151,57 +155,42 @@ private void loadRepository(String repositoryName, String repositoryClassName, M return; } - try { - IAlgorithmRepository algorithmRepository = null; + //registerNewRepository(repositoryClassName); + registerRepository(repositoryName, repositoryClassName); + } - Class repositoryClass = RepositoryManager.class.getClassLoader() - .loadClass(repositoryClassName); + private void registerRepository(String name, String className) { + try { + repositories.put(className, applicationContext.getBean(name, IAlgorithmRepository.class)); + } catch (NoSuchBeanDefinitionException e) { + LOGGER.warn("Try creating repository the old fashioned way.", className, name); + registerNewRepository(className); + } catch (BeansException e) { + LOGGER.warn("Could not create algorithm repository for class '{}' and name '{}'", className, name, e); + } + } - algorithmRepository = (IAlgorithmRepository) repositoryClass + private void registerNewRepository(String repositoryClassName) { + try { + Class repositoryClass = RepositoryManager.class + .getClassLoader() + .loadClass(repositoryClassName); + IAlgorithmRepository algorithmRepository = (IAlgorithmRepository) repositoryClass .newInstance(); - - LOGGER.info("Algorithm Repository {} initialized", - repositoryClassName); + + LOGGER.info("Algorithm Repository {} initialized", repositoryClassName); repositories.put(repositoryClassName, algorithmRepository); - } catch (InstantiationException e) { - LOGGER.warn( - "An error occured while registering AlgorithmRepository: {}", - repositoryClassName); - } catch (IllegalAccessException e) { - // in case of an singleton - LOGGER.warn( - "An error occured while registering AlgorithmRepository: {}", - repositoryClassName); - } catch (ClassNotFoundException e) { - LOGGER.warn( - "An error occured while registering AlgorithmRepository: {}", - repositoryClassName, e.getMessage()); - } catch (IllegalArgumentException e) { + } catch (InstantiationException | IllegalAccessException e) { LOGGER.warn( "An error occured while registering AlgorithmRepository: {}", - repositoryClassName, e.getMessage()); - } catch (SecurityException e) { + repositoryClassName, e); + } catch (ClassNotFoundException | IllegalArgumentException | SecurityException e) { LOGGER.warn( "An error occured while registering AlgorithmRepository: {}", - repositoryClassName, e.getMessage()); + repositoryClassName, e); } - } - - public static RepositoryManager getInstance(){ - if(instance==null){ - instance = new RepositoryManager(); - } - return instance; - } - - /** - * Allows to reInitialize the RepositoryManager... This should not be called to often. - * - */ - public static void reInitialize() { - instance = new RepositoryManager(); - } - + } + /** * Allows to reInitialize the Repositories * @@ -209,7 +198,7 @@ public static void reInitialize() { protected void reloadRepositories() { loadAllRepositories(); } - + /** * Methods looks for Algorithm in all Repositories. * The first match is returned. @@ -220,7 +209,7 @@ protected void reloadRepositories() { * @throws Exception */ public IAlgorithm getAlgorithm(String className){ - + for (String repositoryClassName : getRepositoryNames()) { IAlgorithmRepository repository = repositories.get(repositoryClassName); if(repository.containsAlgorithm(className)){ @@ -229,9 +218,9 @@ public IAlgorithm getAlgorithm(String className){ } return null; } - + /** - * + * * @return allAlgorithms */ public List getAlgorithms(){ @@ -241,7 +230,7 @@ public List getAlgorithms(){ allAlgorithmNamesCollection.addAll(repository.getAlgorithmNames()); } return allAlgorithmNamesCollection; - + } public boolean containsAlgorithm(String algorithmName) { @@ -253,7 +242,7 @@ public boolean containsAlgorithm(String algorithmName) { } return false; } - + public IAlgorithmRepository getRepositoryForAlgorithm(String algorithmName){ for (String repositoryClassName : getRepositoryNames()) { IAlgorithmRepository repository = repositories.get(repositoryClassName); @@ -263,33 +252,33 @@ public IAlgorithmRepository getRepositoryForAlgorithm(String algorithmName){ } return null; } - + public Class getInputDataTypeForAlgorithm(String algorithmIdentifier, String inputIdentifier){ IAlgorithm algorithm = getAlgorithm(algorithmIdentifier); return algorithm.getInputDataType(inputIdentifier); - + } - + public Class getOutputDataTypeForAlgorithm(String algorithmIdentifier, String inputIdentifier){ IAlgorithm algorithm = getAlgorithm(algorithmIdentifier); return algorithm.getOutputDataType(inputIdentifier); - + } - + public boolean registerAlgorithm(String id, IAlgorithmRepository repository){ if (globalProcessIDs.addID(id)){ return true; } else return false; } - + public boolean unregisterAlgorithm(String id){ if (globalProcessIDs.removeID(id)){ return true; } else return false; } - + public IAlgorithmRepository getAlgorithmRepository(String name){ for (String repositoryClassName : getRepositoryNames()) { IAlgorithmRepository repository = repositories.get(repositoryClassName); @@ -310,7 +299,7 @@ public IAlgorithmRepository getRepositoryForClassName( } return null; } - + public ProcessDescription getProcessDescription(String processClassName){ for (String repositoryClassName : getRepositoryNames()) { IAlgorithmRepository repository = repositories.get(repositoryClassName); @@ -320,20 +309,24 @@ public ProcessDescription getProcessDescription(String processClassName){ } return new ProcessDescription(); } - + static class UpdateThread extends Thread { - + private final long interval; + private boolean firstrun = true; - - public UpdateThread (long interval){ + + private final RepositoryManager repositoryManager; + + public UpdateThread (RepositoryManager repositoryManager, long interval){ + this.repositoryManager = repositoryManager; this.interval = interval; } - + @Override public void run() { LOGGER.debug("UpdateThread started"); - + try { // never terminate the run method while (true){ @@ -341,25 +334,26 @@ public void run() { if (!firstrun){ LOGGER.info("Reloading repositories - this might take a while ..."); long timestamp = System.currentTimeMillis(); - RepositoryManager.getInstance().reloadRepositories(); + repositoryManager.reloadRepositories(); LOGGER.info("Repositories reloaded - going to sleep. Took {} seconds.", (System.currentTimeMillis() - timestamp) / 1000); } else { firstrun = false; } - + // sleep for a given INTERVAL - sleep(interval); + Thread.sleep(interval); } } catch (InterruptedException e) { LOGGER.debug("Interrupt received - Terminating the UpdateThread."); } } - + } - + // shut down the update thread - public void finalize(){ + public void finalize() throws Throwable { + super.finalize(); if (updateThread != null){ updateThread.interrupt(); } diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java new file mode 100644 index 000000000..594ded839 --- /dev/null +++ b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java @@ -0,0 +1,65 @@ +/** + * Copyright (C) 2007 - 2014 52°North Initiative for Geospatial Open Source + * Software GmbH + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 as published + * by the Free Software Foundation. + * + * If the program is linked with libraries which are licensed under one of + * the following licenses, the combination of the program with the linked + * library is not considered a "derivative work" of the program: + * + * • Apache License, version 2.0 + * • Apache Software License, version 1.0 + * • GNU Lesser General Public License, version 3 + * • Mozilla Public License, versions 1.0, 1.1 and 2.0 + * • Common Development and Distribution License (CDDL), version 1.0 + * + * Therefore the distribution of the program linked with libraries licensed + * under the aforementioned licenses, is permitted by the copyright holders + * if the distribution is compliant with both the GNU General Public + * License version 2 and the aforementioned licenses. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General + * Public License for more details. + */ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.n52.wps.server; + +/** + * Wraps {@link RepositoryManager} as it got refactored to IoC managable. This class + * determines an intermediate refactor step. To use {@link RepositoryManager} instance + * define dependency injection or just {@link Autowire} it. + * + * @author Henning Bredel + */ +public class RepositoryManagerSingletonWrapper { + + private static RepositoryManager instance; + + public static void init(RepositoryManager repositoryManager) { + if (repositoryManager == null) { + throw new NullPointerException("RepositoryManager is null."); + } + instance = repositoryManager; + } + + public static RepositoryManager getInstance() { + if (instance == null) { + throw new IllegalStateException("RepositoryManager has not been initialized yet."); + } + return instance; + } + + public static void reInitialize() { + RepositoryManager rm = getInstance(); + rm.reInitialize(); + } +} diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/WebProcessingService.java b/52n-wps-server/src/main/java/org/n52/wps/server/WebProcessingService.java index 461e30afd..919cfea5e 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/WebProcessingService.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/WebProcessingService.java @@ -29,8 +29,6 @@ package org.n52.wps.server; // FvK: added Property Change Listener support -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; @@ -92,12 +90,15 @@ public class WebProcessingService implements ServletContextAware, ServletConfigA protected static Logger LOGGER = LoggerFactory.getLogger(WebProcessingService.class); private static String applicationBaseDir = null; - + private ServletContext servletContext; @Autowired private ConfigurationManager configurationManager; + @Autowired + private RepositoryManager repositoryManager; + public WebProcessingService() { LOGGER.info("NEW {}", this); } @@ -142,13 +143,13 @@ private static OutputStream getConfiguredOutputStream(HttpServletRequest hsReque public void init() { LOGGER.info("*** WebProcessingService initializing... ***"); WPSConfig conf = WPSConfig.getInstance(servletContext); - + WPSConfig.getInstance().setConfigurationManager(configurationManager); - + // this is important to set the lon lat support for correct CRS transformation. // TODO: Might be changed to an additional configuration parameter. System.setProperty("org.geotools.referencing.forceXY", "true"); - + try { if (conf == null) { LOGGER.error("Initialization failed! Please look at the properties file!"); @@ -172,8 +173,8 @@ public void init() { GeneratorFactory.initialize(generatorMap); LOGGER.info("Initialized {}", GeneratorFactory.getInstance()); - RepositoryManager repoManager = RepositoryManager.getInstance(); - LOGGER.info("Initialized {}", repoManager); + repositoryManager.init(); + LOGGER.info("Initialized {}", repositoryManager); IDatabase database = DatabaseFactory.getDatabase(); LOGGER.info("Initialized {}", database); @@ -191,7 +192,7 @@ public void init() { LOGGER.info("Service base url is {} | Service endpoint is {}", conf.getServiceBaseUrl(), conf.getServiceEndpoint()); - + LOGGER.info("*** WPS up and running! ***"); } @@ -207,7 +208,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse res) throws Ser OutputStream out = res.getOutputStream(); // closed by res.flushBuffer(); RequestHandler handler = new RequestHandler(req.getParameterMap(), out); String mimeType = handler.getResponseMimeType(); - requestedVersion = handler.getRequestedVersion(); + requestedVersion = handler.getRequestedVersion(); res.setContentType(mimeType); handler.handle(); @@ -234,7 +235,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse res) throws Se BufferedReader reader = null; String requestedVersion = null; - + try { String contentType = req.getContentType(); String characterEncoding = req.getCharacterEncoding(); @@ -353,6 +354,6 @@ public void setServletConfig(ServletConfig servletConfig) {} @Override public void setServletContext(ServletContext servletContext) { - this.servletContext = servletContext; + this.servletContext = servletContext; } } \ No newline at end of file diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/request/DescribeProcessRequest.java b/52n-wps-server/src/main/java/org/n52/wps/server/request/DescribeProcessRequest.java index 6dbfd6dc0..392d76ac3 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/request/DescribeProcessRequest.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/request/DescribeProcessRequest.java @@ -41,6 +41,7 @@ import org.apache.commons.collections.map.CaseInsensitiveMap; import org.apache.xmlbeans.XmlCursor; import org.n52.wps.commons.WPSConfig; +import org.n52.wps.server.RepositoryManagerSingletonWrapper; import org.n52.wps.server.ExceptionReport; import org.n52.wps.server.RepositoryManager; import org.n52.wps.server.WebProcessingService; @@ -53,12 +54,12 @@ /** * Handles a DescribeProcessRequest - * @see Request + * @see Request */ public class DescribeProcessRequest extends Request { private ProcessDescriptionsDocument document; - + /** * Creates a DescribeProcessRequest based on a Map (HTTP_GET) * @param ciMap The client input @@ -67,7 +68,7 @@ public class DescribeProcessRequest extends Request { public DescribeProcessRequest(CaseInsensitiveMap ciMap) throws ExceptionReport{ super(ciMap); } - + /** * Creates a DescribeProcessRequest based on a Document (SOAP?) * @param doc The client input @@ -75,28 +76,28 @@ public DescribeProcessRequest(CaseInsensitiveMap ciMap) throws ExceptionReport{ */ public DescribeProcessRequest(Document doc) throws ExceptionReport{ super(doc); - + //put the respective elements of the document in the map NamedNodeMap nnm = doc.getFirstChild().getAttributes(); - + map = new CaseInsensitiveMap(); - + for (int i = 0; i < nnm.getLength(); i++) { - + Node n = nnm.item(i); if(n.getLocalName().equalsIgnoreCase("service")){ map.put(n.getLocalName(), new String[]{n.getNodeValue()}); }else if(n.getLocalName().equalsIgnoreCase("version")){ - map.put(n.getLocalName(), new String[]{n.getNodeValue()}); + map.put(n.getLocalName(), new String[]{n.getNodeValue()}); } } //get identifier - String identifierList = ""; - + String identifierList = ""; + NodeList nList = doc.getFirstChild().getChildNodes(); - + boolean identifierParameterExists = false; - + for (int i = 0; i < nList.getLength(); i++) { Node n = nList.item(i); if(n.getLocalName() != null && n.getLocalName().equalsIgnoreCase("identifier")){ @@ -111,7 +112,7 @@ public DescribeProcessRequest(Document doc) throws ExceptionReport{ map.put("identifier", new String[]{identifierList}); } } - + /** * Validates the client input @@ -119,15 +120,15 @@ public DescribeProcessRequest(Document doc) throws ExceptionReport{ * @return True if the input is valid, False otherwise */ public boolean validate() throws ExceptionReport{ - getMapValue("version", true, new String[]{"1.0.0"}); // required + getMapValue("version", true, new String[]{"1.0.0"}); // required getMapValue("identifier", true); // required! return true; } - + public Object getAttachedResult(){ return document; } - + /** * Actually serves the Request. * @throws ExceptionReport @@ -135,50 +136,50 @@ public Object getAttachedResult(){ */ public Response call() throws ExceptionReport { validate(); - + document = ProcessDescriptionsDocument.Factory.newInstance(); document.addNewProcessDescriptions(); XmlCursor c = document.newCursor(); c.toFirstChild(); c.toLastAttribute(); c.setAttributeText(new QName(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "schemaLocation"), "http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsDescribeProcess_response.xsd"); - + String[] identifiers = getMapValue("identifier", true).split(","); document.getProcessDescriptions().setLang(WebProcessingService.DEFAULT_LANGUAGE); document.getProcessDescriptions().setService("WPS"); document.getProcessDescriptions().setVersion("1.0.0");//FIXME set to requested version - + if(identifiers.length==1 && identifiers[0].equalsIgnoreCase("all")){ - List identifierList = RepositoryManager.getInstance().getAlgorithms(); + List identifierList = RepositoryManagerSingletonWrapper.getInstance().getAlgorithms(); identifiers = new String[identifierList.size()]; for(int i = 0;i identifierList = RepositoryManager.getInstance().getAlgorithms(); + List identifierList = RepositoryManagerSingletonWrapper.getInstance().getAlgorithms(); identifiers = new String[identifierList.size()]; for(int i = 0;i processOfferings = new ArrayList<>(identifiers.length); - + for(String algorithmName : identifiers) { - if(!RepositoryManager.getInstance().containsAlgorithm(algorithmName)) { - throw new ExceptionReport("Algorithm does not exist: " + algorithmName, - ExceptionReport.INVALID_PARAMETER_VALUE, + if(!RepositoryManagerSingletonWrapper.getInstance().containsAlgorithm(algorithmName)) { + throw new ExceptionReport("Algorithm does not exist: " + algorithmName, + ExceptionReport.INVALID_PARAMETER_VALUE, "identifier"); } - ProcessOffering offering = (ProcessOffering) RepositoryManager.getInstance().getProcessDescription(algorithmName).getProcessDescriptionType(WPSConfig.VERSION_200); + ProcessOffering offering = (ProcessOffering) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription(algorithmName).getProcessDescriptionType(WPSConfig.VERSION_200); processOfferings.add(offering); } document.getProcessOfferings().setProcessOfferingArray(processOfferings.toArray(new ProcessOffering[identifiers.length])); - + LOGGER.info("Handled Request successfully for: " + getMapValue("identifier", true)); return new DescribeProcessResponse(this); } diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/request/ExecuteRequestV100.java b/52n-wps-server/src/main/java/org/n52/wps/server/request/ExecuteRequestV100.java index ac3ba2da8..d3fb316b0 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/request/ExecuteRequestV100.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/request/ExecuteRequestV100.java @@ -72,6 +72,7 @@ import org.n52.wps.io.data.IComplexData; import org.n52.wps.io.data.IData; import org.n52.wps.server.AbstractTransactionalAlgorithm; +import org.n52.wps.server.RepositoryManagerSingletonWrapper; import org.n52.wps.server.ExceptionReport; import org.n52.wps.server.IAlgorithm; import org.n52.wps.server.RepositoryManager; @@ -96,12 +97,12 @@ public class ExecuteRequestV100 extends ExecuteRequest implements IObserver { private ExecuteDocument execDom; private Map returnResults; private ExecuteResponseBuilderV100 execRespType; - - + + /** * Creates an ExecuteRequest based on a Document (HTTP_POST) - * + * * @param doc * The clients submission * @throws ExceptionReport @@ -127,7 +128,7 @@ public ExecuteRequestV100(Document doc) throws ExceptionReport { // create an initial response execRespType = new ExecuteResponseBuilderV100(this); - + storeRequest(execDom); } @@ -147,9 +148,9 @@ public ExecuteRequestV100(CaseInsensitiveMap ciMap) throws ExceptionReport { storeRequest(ciMap); } - + public void getKVPDataInputs(){ - + } /** @@ -164,7 +165,7 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { this.execDom = ExecuteDocument.Factory.newInstance(); Execute execute = execDom.addNewExecute(); String processID = getMapValue("Identifier", true); - if (!RepositoryManager.getInstance().containsAlgorithm(processID)) { + if (!RepositoryManagerSingletonWrapper.getInstance().containsAlgorithm(processID)) { throw new ExceptionReport("Process does not exist", ExceptionReport.INVALID_PARAMETER_VALUE); } @@ -173,7 +174,7 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { String dataInputString = getMapValue("DataInputs", true); dataInputString = dataInputString.replace("&","&"); String[] inputs = dataInputString.split(";"); - + // Handle data inputs for (String inputString : inputs) { int position = inputString.indexOf("="); @@ -193,8 +194,8 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { value = inputString.substring(position + 1); } } - ProcessDescriptionType description = (ProcessDescriptionType) RepositoryManager.getInstance().getProcessDescription(processID).getProcessDescriptionType(WPSConfig.VERSION_100); - + ProcessDescriptionType description = (ProcessDescriptionType) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription(processID).getProcessDescriptionType(WPSConfig.VERSION_100); + if (description == null) { throw new ExceptionReport("Data Identifier not supported: " + key, ExceptionReport.MISSING_PARAMETER_VALUE); @@ -239,7 +240,7 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { try { attributeValue = URLDecoder.decode(attributeValue, "UTF-8"); } catch (UnsupportedEncodingException e) { - throw new ExceptionReport("Something went wrong while trying to decode value of " + attributeName, ExceptionReport.NO_APPLICABLE_CODE, e); + throw new ExceptionReport("Something went wrong while trying to decode value of " + attributeName, ExceptionReport.NO_APPLICABLE_CODE, e); } if (attributeName.equalsIgnoreCase("encoding")) { encodingAttribute = attributeValue; @@ -281,9 +282,9 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { // Handling ComplexData else { ComplexDataType data = input.addNewData().addNewComplexData(); - + InputStream stream = new ByteArrayInputStream(value.getBytes()); - + try { data.set(XmlObject.Factory.parse(stream)); } catch (Exception e) { @@ -296,7 +297,7 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { ExceptionReport.NO_APPLICABLE_CODE, e1); } } - + if (schemaAttribute != null) { data.setSchema(schemaAttribute); } @@ -307,7 +308,7 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { data.setEncoding(encodingAttribute); } } - + } else if (inputDesc.isSetLiteralData()) { LiteralDataType data = input.addNewData().addNewLiteralData(); if (value == null) { @@ -325,7 +326,7 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { } else if (inputDesc.isSetBoundingBoxData()) { BoundingBoxType data = input.addNewData().addNewBoundingBoxData(); String[] values = value.split(","); - + if(values.length<4){ throw new ExceptionReport("Invalid Number of BBOX Values: " + inputDesc.getIdentifier().getStringValue(), @@ -335,16 +336,16 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { lowerCorner.add(values[0]); lowerCorner.add(values[1]); data.setLowerCorner(lowerCorner); - + List upperCorner = new ArrayList(); upperCorner.add(values[2]); upperCorner.add(values[3]); data.setUpperCorner(upperCorner); - + if(values.length>4){ data.setCrs(values[4]); } - + if(values.length>5){ data.setDimensions(BigInteger.valueOf(Long.valueOf(values[5]))); } @@ -379,7 +380,7 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { outputDataInput = outputID; } outputDataInput = outputDataInput.replace("=", ""); - ProcessDescriptionType description = (ProcessDescriptionType) RepositoryManager.getInstance().getProcessDescription(processID).getProcessDescriptionType(WPSConfig.VERSION_100); + ProcessDescriptionType description = (ProcessDescriptionType) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription(processID).getProcessDescriptionType(WPSConfig.VERSION_100); OutputDescriptionType outputDesc = XMLBeansHelper .findOutputByID(outputDataInput, description.getProcessOutputs() .getOutputArray()); @@ -407,7 +408,7 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { try{ attributeValue = URLDecoder.decode(attributeValue, "UTF-8"); } catch (UnsupportedEncodingException e) { - throw new ExceptionReport("Something went wrong while trying to decode value of " + attributeName, ExceptionReport.NO_APPLICABLE_CODE, e); + throw new ExceptionReport("Something went wrong while trying to decode value of " + attributeName, ExceptionReport.NO_APPLICABLE_CODE, e); } if (attributeName.equalsIgnoreCase("mimeType")) { output.setMimeType(attributeValue); @@ -429,9 +430,9 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { } else { rawDataInput = rawData; } - ProcessDescriptionType description = (ProcessDescriptionType) RepositoryManager.getInstance().getProcessDescription(processID).getProcessDescriptionType(WPSConfig.VERSION_100); + ProcessDescriptionType description = (ProcessDescriptionType) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription(processID).getProcessDescriptionType(WPSConfig.VERSION_100); OutputDescriptionType outputDesc = XMLBeansHelper.findOutputByID( - rawDataInput, + rawDataInput, description.getProcessOutputs().getOutputArray()); if (outputDesc == null) { throw new ExceptionReport( @@ -458,7 +459,7 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { try{ attributeValue = URLDecoder.decode(attributeValue, "UTF-8"); } catch (UnsupportedEncodingException e) { - throw new ExceptionReport("Something went wrong while trying to decode value of " + attributeName, ExceptionReport.NO_APPLICABLE_CODE, e); + throw new ExceptionReport("Something went wrong while trying to decode value of " + attributeName, ExceptionReport.NO_APPLICABLE_CODE, e); } if (attributeName.equalsIgnoreCase("mimeType")) { output.setMimeType(attributeValue); @@ -482,14 +483,14 @@ private void initForGET(CaseInsensitiveMap ciMap) throws ExceptionReport { /** * Validates the client request - * + * * @return True if the input is valid, False otherwise */ public boolean validate() throws ExceptionReport { // Identifier must be specified. /* * Only for HTTP_GET: String identifier = getMapValue("identifier"); - * + * * try{ // Specifies if all complex valued output(s) of this process * should be stored by process // as web-accessible resources store = * getMapValue("store").equals("true"); @@ -503,7 +504,7 @@ public boolean validate() throws ExceptionReport { * 0) { throw new ExceptionReport("Incorrect number of arguments for * parameter dataInputs, please only a even number of parameter values", * ExceptionReport.INVALID_PARAMETER_VALUE); } - * + * */ if (!WPSConfig.SUPPORTED_VERSIONS.contains(execDom.getExecute().getVersion())) { throw new ExceptionReport("Specified version is not supported.", @@ -513,15 +514,15 @@ public boolean validate() throws ExceptionReport { //Fix for bug https://bugzilla.52north.org/show_bug.cgi?id=906 String identifier = getAlgorithmIdentifier(); - + if(identifier == null){ throw new ExceptionReport( "No process identifier supplied.", - ExceptionReport.MISSING_PARAMETER_VALUE, "identifier"); + ExceptionReport.MISSING_PARAMETER_VALUE, "identifier"); } - + // check if the algorithm is in our repository - if (!RepositoryManager.getInstance().containsAlgorithm( + if (!RepositoryManagerSingletonWrapper.getInstance().containsAlgorithm( identifier)) { throw new ExceptionReport( "Specified process identifier does not exist", @@ -530,7 +531,7 @@ public boolean validate() throws ExceptionReport { } // validate if the process can be executed - ProcessDescriptionType desc = (ProcessDescriptionType) RepositoryManager.getInstance().getProcessDescription(getAlgorithmIdentifier()).getProcessDescriptionType(WPSConfig.VERSION_100); + ProcessDescriptionType desc = (ProcessDescriptionType) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription(getAlgorithmIdentifier()).getProcessDescriptionType(WPSConfig.VERSION_100); // We need a description of the inputs for the algorithm if (desc == null) { LOGGER.warn("desc == null"); @@ -538,17 +539,17 @@ public boolean validate() throws ExceptionReport { } // Get the inputdescriptions of the algorithm - + if(desc.getDataInputs()!=null){ InputDescriptionType[] inputDescs = desc.getDataInputs().getInputArray(); - + //prevent NullPointerException for zero input values in execute request (if only default values are used) InputType[] inputs; if(getExecute().getDataInputs()==null) inputs=new InputType[0]; else inputs = getExecute().getDataInputs().getInputArray(); - + // For each input supplied by the client for (InputType input : inputs) { boolean identifierMatched = false; @@ -631,7 +632,7 @@ public boolean validate() throws ExceptionReport { /** * Actually serves the Request. - * + * * @throws ExceptionReport */ public Response call() throws ExceptionReport { @@ -647,44 +648,44 @@ public Response call() throws ExceptionReport { else { context = new ExecutionContext(); } - + // register so that any function that calls ExecuteContextFactory.getContext() gets the instance registered with this thread ExecutionContextFactory.registerContext(context); - + LOGGER.debug("started with execution"); - + updateStatusStarted(); - + // parse the input InputType[] inputs = new InputType[0]; if( getExecute().getDataInputs()!=null){ inputs = getExecute().getDataInputs().getInputArray(); } InputHandler parser = new InputHandler.Builder(new Input(inputs), getAlgorithmIdentifier()).build(); - + // we got so far: // get the algorithm, and run it with the clients input - + /* * IAlgorithm algorithm = * RepositoryManager.getInstance().getAlgorithm(getAlgorithmIdentifier()); * returnResults = algorithm.run((Map)parser.getParsedInputLayers(), * (Map)parser.getParsedInputParameters()); */ - algorithm = RepositoryManager.getInstance().getAlgorithm(getAlgorithmIdentifier()); - + algorithm = RepositoryManagerSingletonWrapper.getInstance().getAlgorithm(getAlgorithmIdentifier()); + if(algorithm instanceof ISubject){ ISubject subject = (ISubject) algorithm; subject.addObserver(this); - + } - + if(algorithm instanceof AbstractTransactionalAlgorithm){ returnResults = ((AbstractTransactionalAlgorithm)algorithm).run(execDom); } else { inputMap = parser.getParsedInputData(); returnResults = algorithm.run(inputMap); - } + } List errorList = algorithm.getErrors(); if (errorList != null && !errorList.isEmpty()) { @@ -739,15 +740,15 @@ public Response call() throws ExceptionReport { } } } - + ExecuteResponse response = new ExecuteResponse(this); return response; } - + /** * Gets the identifier of the algorithm the client requested - * + * * @return An identifier */ public String getAlgorithmIdentifier() { @@ -757,10 +758,10 @@ public String getAlgorithmIdentifier() { } return null; } - + /** * Gets the Execute that is associated with this Request - * + * * @return The Execute */ public Execute getExecute() { @@ -808,12 +809,12 @@ public boolean isRawData() { } } - + public void update(ISubject subject) { Object state = subject.getState(); LOGGER.info("Update received from Subject, state changed to : " + state); StatusType status = StatusType.Factory.newInstance(); - + int percentage = 0; if (state instanceof Integer) { percentage = (Integer) state; @@ -823,25 +824,25 @@ public void update(ISubject subject) { } updateStatus(status); } - + public void updateStatusAccepted() { StatusType status = StatusType.Factory.newInstance(); status.setProcessAccepted("Process Accepted"); updateStatus(status); } - + public void updateStatusStarted() { StatusType status = StatusType.Factory.newInstance(); status.addNewProcessStarted().setPercentCompleted(0); updateStatus(status); } - + public void updateStatusSuccess() { StatusType status = StatusType.Factory.newInstance(); status.setProcessSucceeded("Process successful"); updateStatus(status); - } - + } + public void updateStatusError(String errorMessage) { StatusType status = StatusType.Factory.newInstance(); net.opengis.ows.x11.ExceptionReportDocument.ExceptionReport excRep = status @@ -852,7 +853,7 @@ public void updateStatusError(String errorMessage) { excType.setExceptionCode(ExceptionReport.NO_APPLICABLE_CODE); updateStatus(status); } - + private void updateStatus(StatusType status) { getExecuteResponseBuilder().setStatus(status); try { @@ -873,7 +874,7 @@ private void updateStatus(StatusType status) { throw new RuntimeException(e); } } - + private void storeRequest(ExecuteDocument executeDocument) { InputStream is = null; try { @@ -886,9 +887,9 @@ private void storeRequest(ExecuteDocument executeDocument) { IOUtils.closeQuietly(is); } } - + private void storeRequest(CaseInsensitiveMap map) { - + BufferedWriter w = null; ByteArrayOutputStream os = null; ByteArrayInputStream is = null; @@ -897,7 +898,7 @@ private void storeRequest(CaseInsensitiveMap map) { w = new BufferedWriter(new OutputStreamWriter(os)); for (Object key : map.keySet()) { Object value = map.get(key); - String valueString = ""; + String valueString = ""; if(value instanceof String[]){ valueString = ((String[])value)[0]; }else{ diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/request/ExecuteRequestV200.java b/52n-wps-server/src/main/java/org/n52/wps/server/request/ExecuteRequestV200.java index c591a8c87..9beb7a57a 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/request/ExecuteRequestV200.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/request/ExecuteRequestV200.java @@ -46,6 +46,7 @@ import org.n52.wps.commons.context.ExecutionContextFactory; import org.n52.wps.io.data.IComplexData; import org.n52.wps.io.data.IData; +import org.n52.wps.server.RepositoryManagerSingletonWrapper; import org.n52.wps.server.ExceptionReport; import org.n52.wps.server.IAlgorithm; import org.n52.wps.server.RepositoryManager; @@ -73,7 +74,7 @@ public class ExecuteRequestV200 extends ExecuteRequest implements IObserver { /** * Creates an ExecuteRequest based on a Document (HTTP_POST) - * + * * @param doc * The clients submission * @throws ExceptionReport @@ -105,7 +106,7 @@ public ExecuteRequestV200(Document doc) throws ExceptionReport { /** * Validates the client request - * + * * @return True if the input is valid, False otherwise */ public boolean validate() throws ExceptionReport { @@ -126,7 +127,7 @@ public boolean validate() throws ExceptionReport { } // check if the algorithm is in our repository - if (!RepositoryManager.getInstance().containsAlgorithm(identifier)) { + if (!RepositoryManagerSingletonWrapper.getInstance().containsAlgorithm(identifier)) { throw new ExceptionReport( "Specified process identifier does not exist", ExceptionReport.INVALID_PARAMETER_VALUE, "identifier=" @@ -134,7 +135,7 @@ public boolean validate() throws ExceptionReport { } // validate if the process can be executed - ProcessOffering desc = (ProcessOffering) RepositoryManager + ProcessOffering desc = (ProcessOffering) RepositoryManagerSingletonWrapper .getInstance().getProcessDescription(getAlgorithmIdentifier()) .getProcessDescriptionType(WPSConfig.VERSION_200); // We need a description of the inputs for the algorithm @@ -144,16 +145,16 @@ public boolean validate() throws ExceptionReport { } //TODO validate in-/outputs - + //TODO check for null rawData = execDom.getExecute().getResponse().equals(ExecuteRequestType.Response.RAW); - + return true; } - + /** * Gets the Execute that is associated with this Request - * + * * @return The Execute */ public ExecuteRequestType getExecute() { @@ -162,7 +163,7 @@ public ExecuteRequestType getExecute() { /** * Actually serves the Request. - * + * * @throws ExceptionReport */ public Response call() throws ExceptionReport { @@ -171,7 +172,7 @@ public Response call() throws ExceptionReport { try { //TODO add outputs to execution context ExecutionContext context = new ExecutionContext(); - + // register so that any function that calls // ExecuteContextFactory.getContext() gets the instance registered // with this thread @@ -191,8 +192,8 @@ public Response call() throws ExceptionReport { // we got so far: // get the algorithm, and run it with the clients input - - algorithm = RepositoryManager.getInstance().getAlgorithm( + + algorithm = RepositoryManagerSingletonWrapper.getInstance().getAlgorithm( getAlgorithmIdentifier()); if (algorithm instanceof ISubject) { @@ -201,7 +202,7 @@ public Response call() throws ExceptionReport { } inputMap = parser.getParsedInputData(); - returnResults = algorithm.run(inputMap); + returnResults = algorithm.run(inputMap); List errorList = algorithm.getErrors(); if (errorList != null && !errorList.isEmpty()) { @@ -270,7 +271,7 @@ public Response call() throws ExceptionReport { /** * Gets the identifier of the algorithm the client requested - * + * * @return An identifier */ public String getAlgorithmIdentifier() { @@ -296,7 +297,7 @@ public boolean isRawData() { public void update(ISubject subject) { Object state = subject.getState(); LOGGER.info("Update received from Subject, state changed to : " + state); - + StatusInfo status = StatusInfo.Factory.newInstance(); int percentage = 0; @@ -308,25 +309,25 @@ public void update(ISubject subject) { updateStatus(status); } - public void updateStatusAccepted() { + public void updateStatusAccepted() { StatusInfo status = StatusInfo.Factory.newInstance(); status.setStatus(ExecuteResponseBuilderV200.Status.Accepted.toString()); updateStatus(status); } - public void updateStatusSuccess() { + public void updateStatusSuccess() { StatusInfo status = StatusInfo.Factory.newInstance(); status.setStatus(ExecuteResponseBuilderV200.Status.Succeeded.toString()); updateStatus(status); } - public void updateStatusFailed() { + public void updateStatusFailed() { StatusInfo status = StatusInfo.Factory.newInstance(); status.setStatus(ExecuteResponseBuilderV200.Status.Failed.toString()); updateStatus(status); } - public void updateStatusStarted() { + public void updateStatusStarted() { StatusInfo status = StatusInfo.Factory.newInstance(); status.setStatus(ExecuteResponseBuilderV200.Status.Running.toString()); status.setPercentCompleted(0); @@ -374,6 +375,6 @@ public boolean isStoreResponse() { @Override public void updateStatusError(String errorMessage) { - // TODO Auto-generated method stub + // TODO Auto-generated method stub } } \ No newline at end of file diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/request/InputHandler.java b/52n-wps-server/src/main/java/org/n52/wps/server/request/InputHandler.java index 1edf6b315..b91b781ab 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/request/InputHandler.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/request/InputHandler.java @@ -91,6 +91,7 @@ import org.w3c.dom.Node; import com.google.common.primitives.Doubles; +import org.n52.wps.server.RepositoryManagerSingletonWrapper; /** * Handles the input of the client and stores it into a Map. @@ -142,8 +143,8 @@ public InputHandler build() throws ExceptionReport { */ private InputHandler(Builder builder) throws ExceptionReport { this.algorithmIdentifier = builder.algorithmIdentifier; - this.processDesc = (ProcessDescriptionType) RepositoryManager.getInstance().getProcessDescription(algorithmIdentifier).getProcessDescriptionType(WPSConfig.VERSION_100); - this.processOffering = (ProcessOffering) RepositoryManager.getInstance().getProcessDescription(algorithmIdentifier).getProcessDescriptionType(WPSConfig.VERSION_200); + this.processDesc = (ProcessDescriptionType) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription(algorithmIdentifier).getProcessDescriptionType(WPSConfig.VERSION_100); + this.processOffering = (ProcessOffering) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription(algorithmIdentifier).getProcessDescriptionType(WPSConfig.VERSION_200); if (processDesc == null) { throw new ExceptionReport("Error while accessing the process description for " + algorithmIdentifier, @@ -153,11 +154,11 @@ private InputHandler(Builder builder) throws ExceptionReport { Map inputInterceptors = resolveInputInterceptors(algorithmIdentifier); InputType[] inputsV100 = builder.inputs.getInputsV100(); - + DataInputType[] inputsV200 = builder.inputs.getInputsV200(); - + if(inputsV100 != null){ - + for (InputType input : inputsV100) { String inputId = input.getIdentifier().getStringValue().trim(); if (inputInterceptors.containsKey(inputId)) { @@ -190,7 +191,7 @@ else if(input.getReference() != null) { } } }else if(inputsV200 != null){ - + for (DataInputType input : inputsV200) { String inputId = input.getId().trim(); if (inputInterceptors.containsKey(inputId)) { @@ -204,11 +205,11 @@ else if(input.getReference() != null) { } if(input.getData() != null) { - + net.opengis.wps.x20.InputDescriptionType inputDescription = XMLBeansHelper.findInputByID(inputId, processOffering.getProcess()); - + DataDescriptionType dataDesc = inputDescription.getDataDescription(); - + if(dataDesc instanceof net.opengis.wps.x20.ComplexDataType) { handleComplexData(input, inputId); } @@ -228,7 +229,7 @@ else if(input.getReference() != null) { } } } - + } Map resolveInputInterceptors(String algorithmClassName) { @@ -554,7 +555,7 @@ protected void handleComplexData(InputType input, String inputId) throws Excepti " mimeType: " + dataMimeType + " encoding: " + formatEncoding); - Class algorithmInput = RepositoryManager.getInstance().getInputDataTypeForAlgorithm(this.algorithmIdentifier, inputId); + Class algorithmInput = RepositoryManagerSingletonWrapper.getInstance().getInputDataTypeForAlgorithm(this.algorithmIdentifier, inputId); parser = ParserFactory.getInstance().getParser(formatSchema, dataMimeType, formatEncoding, algorithmInput); } catch (RuntimeException e) { throw new ExceptionReport("Error obtaining input data", ExceptionReport.NO_APPLICABLE_CODE, e); @@ -610,11 +611,11 @@ protected ComplexDataDescriptionType findComplexDataDescriptionType(InputDescrip return result; } - + /** * Handles the complexValue, which in this case should always include XML * which can be parsed into a FeatureCollection. - * + * * @param input * The client input * @param inputId @@ -687,11 +688,11 @@ private void handleComplexData(DataInputType input, String inputId) formatSchema = format.getSchema(); } } else { - + Format[] formatArray = inputReferenceDesc.getDataDescription().getFormatArray(); - + Format defaultFormat = getDefaultFormat(formatArray); - + // mimeType not in request if (StringUtils.isBlank(dataMimeType) && !data.isSetEncoding() && !data.isSetSchema()) { @@ -838,7 +839,7 @@ private void handleComplexData(DataInputType input, String inputId) * NullPointerException if one of the * supported types is given by mimetype and * not by schema: - * + * * old code: * if(tempFormat.getEncoding().equalsIgnoreCase * (data.getSchema())){ @@ -890,7 +891,7 @@ private void handleComplexData(DataInputType input, String inputId) + formatSchema + " mimeType: " + dataMimeType + " encoding: " + formatEncoding); - Class algorithmInput = RepositoryManager.getInstance() + Class algorithmInput = RepositoryManagerSingletonWrapper.getInstance() .getInputDataTypeForAlgorithm(this.algorithmIdentifier, inputId); parser = ParserFactory.getInstance().getParser(formatSchema, @@ -917,10 +918,10 @@ private void handleComplexData(DataInputType input, String inputId) list.add(collection); inputData.put(inputId, list); } - + /** * Handles the ComplexValueReference - * + * * @param input * The client input * @throws ExceptionReport @@ -1413,7 +1414,7 @@ private void handleComplexValueReference(DataInputType input) IParser parser = null; try { - Class algorithmInputClass = RepositoryManager.getInstance() + Class algorithmInputClass = RepositoryManagerSingletonWrapper.getInstance() .getInputDataTypeForAlgorithm(this.algorithmIdentifier, inputID); if (algorithmInputClass == null) { @@ -1454,9 +1455,9 @@ private void handleComplexValueReference(DataInputType input) } } - + private Format getDefaultFormat(Format[] formatArray){ - + for (Format format : formatArray) { if(format.isSetDefault()){ return format; @@ -1465,17 +1466,17 @@ private Format getDefaultFormat(Format[] formatArray){ //TODO throw RuntimeException, as there must be a default format? return null; } - + private Format findFormat(net.opengis.wps.x20.InputDescriptionType inputReferenceDesc, String dataMimeType, String dataSchema, String dataEncoding, String potentialFormatSchema, String potentialFormatEncoding) { Format result = null; boolean canUseDefault = false; - + Format[] formatArray = inputReferenceDesc.getDataDescription().getFormatArray(); - + Format defaultFormat = getDefaultFormat(formatArray); - + String defaultMimeType = defaultFormat.getMimeType(); if (defaultMimeType.equalsIgnoreCase(dataMimeType)) { @@ -1509,7 +1510,7 @@ private Format findFormat(net.opengis.wps.x20.InputDescriptionType inputReferenc } return result; } - + private Format getNonDefaultFormat( net.opengis.wps.x20.InputDescriptionType inputRefDesc, String dataMimeType, String dataSchema, String dataEncoding) { @@ -1548,7 +1549,7 @@ private Format getNonDefaultFormat( } return null; } - + protected IData parseComplexValue(String formatEncoding, String complexValue, String dataMimeType, String formatSchema, IParser parser) throws ExceptionReport { IData idata; String complexValueCopy = complexValue.toString(); @@ -1700,13 +1701,13 @@ private void handleLiteralData(DataInputType input) throws ExceptionReport { } net.opengis.wps.x20.InputDescriptionType inputDesc = XMLBeansHelper.findInputByID(inputID, processOffering.getProcess()); - + LiteralDataDomain literalDataDomain = ((LiteralDataType)inputDesc.getDataDescription()).getLiteralDataDomainArray(0); - - + + net.opengis.ows.x20.DomainMetadataType dataType = literalDataDomain.getDataType(); String xmlDataType = dataType != null ? dataType.getReference() : null; - + //still null, assume string as default if(xmlDataType == null) { xmlDataType = BasicXMLTypeFactory.STRING_URI; @@ -1767,7 +1768,7 @@ private void handleLiteralData(DataInputType input) throws ExceptionReport { } } - + private boolean checkRange(IData parameterObj, RangeType allowedRange){ List l = allowedRange.getRangeClosure(); @@ -1887,7 +1888,7 @@ private boolean checkRangeV200(IData parameterObj, net.opengis.ows.x20.RangeType return false; } - + /** * Handles the ComplexValueReference * @param input The client input @@ -2270,7 +2271,7 @@ private void handleComplexValueReference(InputType input) throws ExceptionReport IParser parser = null; try { - Class algorithmInputClass = RepositoryManager.getInstance().getInputDataTypeForAlgorithm(this.algorithmIdentifier, inputID); + Class algorithmInputClass = RepositoryManagerSingletonWrapper.getInstance().getInputDataTypeForAlgorithm(this.algorithmIdentifier, inputID); if(algorithmInputClass == null) { throw new RuntimeException("Could not determine internal input class for input" + inputID); } @@ -2406,14 +2407,14 @@ private IData parseBoundingBox(BoundingBoxType bbt) */ private void handleBBoxValue(DataInputType input) throws ExceptionReport { - + net.opengis.ows.x20.BoundingBoxType boundingBoxType = null; try { boundingBoxType = net.opengis.ows.x20.BoundingBoxType.Factory.parse(input.getData().getDomNode()); } catch (XmlException e) { LOGGER.error("XmlException occurred while trying to parse bounding box: " + (boundingBoxType == null ? null : boundingBoxType.toString()), e); } - + IData envelope = parseBoundingBox(boundingBoxType); List resultList = inputData.get(input.getId()); @@ -2467,7 +2468,7 @@ private IData parseBoundingBox(net.opengis.ows.x20.BoundingBoxType bbt) } return new BoundingBoxData(lower, upper, bbt.getCrs()); } - + private double[] parseCoordinate(List ordinates) throws NumberFormatException { List coordinate = new ArrayList(ordinates.size()); diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/response/ExecuteResponseBuilderV100.java b/52n-wps-server/src/main/java/org/n52/wps/server/response/ExecuteResponseBuilderV100.java index 60d806626..572b6fe64 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/response/ExecuteResponseBuilderV100.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/response/ExecuteResponseBuilderV100.java @@ -50,6 +50,7 @@ import org.n52.wps.commons.WPSConfig; import org.n52.wps.io.data.IBBOXData; import org.n52.wps.io.data.IData; +import org.n52.wps.server.RepositoryManagerSingletonWrapper; import org.n52.wps.server.ExceptionReport; import org.n52.wps.server.ProcessDescription; import org.n52.wps.server.RepositoryManager; @@ -97,7 +98,7 @@ public ExecuteResponseBuilderV100(ExecuteRequestV100 request) throws ExceptionRe this.identifier = request.getExecute().getIdentifier().getStringValue().trim(); ExecuteResponse responseElem = doc.getExecuteResponse(); responseElem.addNewProcess().addNewIdentifier().setStringValue(identifier); - superDescription = RepositoryManager.getInstance().getProcessDescription(this.identifier); + superDescription = RepositoryManagerSingletonWrapper.getInstance().getProcessDescription(this.identifier); description = (ProcessDescriptionType) superDescription.getProcessDescriptionType(WPSConfig.VERSION_100); if(description==null){ throw new RuntimeException("Error while accessing the process description for "+ identifier); @@ -186,7 +187,7 @@ else if (desc.isSetBoundingBoxOutput()) { // THIS IS A WORKAROUND AND ACTUALLY NOT COMPLIANT TO THE SPEC. - ProcessDescriptionType description = (ProcessDescriptionType) RepositoryManager.getInstance().getProcessDescription(request.getExecute().getIdentifier().getStringValue()).getProcessDescriptionType(WPSConfig.VERSION_100); + ProcessDescriptionType description = (ProcessDescriptionType) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription(request.getExecute().getIdentifier().getStringValue()).getProcessDescriptionType(WPSConfig.VERSION_100); if(description==null){ throw new RuntimeException("Error while accessing the process description for "+ request.getExecute().getIdentifier().getStringValue()); } @@ -378,12 +379,12 @@ public InputStream getAsStream() throws ExceptionReport{ } public void setStatus(XmlObject statusObject) { - + if(statusObject instanceof StatusType){ StatusType status = (StatusType)statusObject; //workaround, should be generated either at the creation of the document or when the process has been finished. status.setCreationTime(creationTime); - doc.getExecuteResponse().setStatus(status); + doc.getExecuteResponse().setStatus(status); }else{ LOGGER.warn(String.format("XMLObject not of type \"net.opengis.wps.x100.StatusType\", but {}. Cannot not set status. ", statusObject.getClass())); } diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/response/ExecuteResponseBuilderV200.java b/52n-wps-server/src/main/java/org/n52/wps/server/response/ExecuteResponseBuilderV200.java index 104c7f337..ced176be5 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/response/ExecuteResponseBuilderV200.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/response/ExecuteResponseBuilderV200.java @@ -49,6 +49,7 @@ import org.n52.wps.commons.WPSConfig; import org.n52.wps.io.data.IBBOXData; import org.n52.wps.io.data.IData; +import org.n52.wps.server.RepositoryManagerSingletonWrapper; import org.n52.wps.server.ExceptionReport; import org.n52.wps.server.ProcessDescription; import org.n52.wps.server.RepositoryManager; @@ -76,22 +77,22 @@ public class ExecuteResponseBuilderV200 implements ExecuteResponseBuilder{ private ProcessOffering description; private ProcessDescription superDescription; private static Logger LOGGER = LoggerFactory.getLogger(ExecuteResponseBuilderV200.class); - + public static enum Status { Accepted, Failed, Succeeded, Running } - + public ExecuteResponseBuilderV200(ExecuteRequestV200 request) throws ExceptionReport{ this.request = request; resultDoc = ResultDocument.Factory.newInstance(); resultDoc.addNewResult(); resultDoc.getResult().setJobID(request.getUniqueId().toString()); XMLBeansHelper.addSchemaLocationToXMLObject(resultDoc, "http://www.opengis.net/wps/2.0 http://schemas.opengis.net/wps/2.0/wpsGetResult.xsd"); - statusInfoDoc = StatusInfoDocument.Factory.newInstance(); + statusInfoDoc = StatusInfoDocument.Factory.newInstance(); statusInfoDoc.addNewStatusInfo(); XMLBeansHelper.addSchemaLocationToXMLObject(statusInfoDoc, "http://www.opengis.net/wps/2.0 http://schemas.opengis.net/wps/2.0/wpsGetStatus.xsd"); this.identifier = request.getAlgorithmIdentifier().trim(); - superDescription = RepositoryManager.getInstance().getProcessDescription(this.identifier); + superDescription = RepositoryManagerSingletonWrapper.getInstance().getProcessDescription(this.identifier); description = (ProcessOffering) superDescription.getProcessDescriptionType(WPSConfig.VERSION_200); if(description==null){ throw new RuntimeException("Error while accessing the process description for "+ identifier); @@ -123,9 +124,9 @@ else if (desc.getDataDescription() instanceof LiteralDataType) { String mimeType = null; String schema = null; String encoding = null; - + LiteralDataType literalDataType = (LiteralDataType)desc.getDataDescription(); - + DomainMetadataType dataType = literalDataType.getLiteralDataDomainArray(0).getDataType(); String reference = dataType != null ? dataType.getReference() : null; generateLiteralDataOutput(id, resultDoc, true, reference, schema, mimeType, encoding, desc.getTitleArray(0)); @@ -148,16 +149,16 @@ else if (desc.getDataDescription() instanceof BoundingBoxType) { String mimeType = getMimeType(definition); String schema = getSchema(definition); String encoding = getEncoding(definition); - + generateComplexDataOutput(responseID, definition.getTransmission().equals(DataTransmissionModeType.REFERENCE), false, schema, mimeType, encoding, desc.getTitleArray(0)); } else if (desc.getDataDescription() instanceof LiteralDataType) { String mimeType = null; String schema = null; String encoding = null; - + LiteralDataType literalDataType = (LiteralDataType)desc.getDataDescription(); - + DomainMetadataType dataType = literalDataType.getLiteralDataDomainArray(0).getDataType(); String reference = dataType != null ? dataType.getReference() : null; generateLiteralDataOutput(responseID, resultDoc, false, reference, schema, mimeType, encoding, desc.getTitleArray(0)); @@ -287,7 +288,7 @@ public InputStream getAsStream() throws ExceptionReport{ if(request.isRawData() && rawDataHandler != null) { return rawDataHandler.getAsStream(); } - + if(request.getExecute().getMode().equals(ExecuteRequestType.Mode.SYNC)){ return resultDoc.newInputStream(XMLBeansHelper.getXmlOptions()); }else if(statusInfoDoc.getStatusInfo().getStatus().equals(Status.Succeeded.toString())){ @@ -296,16 +297,16 @@ public InputStream getAsStream() throws ExceptionReport{ request.getUniqueId().toString(), statusInfoDoc.newInputStream(XMLBeansHelper.getXmlOptions())); return resultDoc.newInputStream(XMLBeansHelper.getXmlOptions()); } - + return statusInfoDoc.newInputStream(XMLBeansHelper.getXmlOptions()); } public void setStatus(XmlObject statusObject) { - + if(statusObject instanceof StatusInfo){ - + StatusInfo status = (StatusInfo)statusObject; - + statusInfoDoc.setStatusInfo(status); }else{ LOGGER.warn(String.format("XMLObject not of type \"net.opengis.wps.x20.StatusInfoDocument.StatusInfo\", but {}. Cannot not set status. ", statusObject.getClass())); diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/response/ResponseData.java b/52n-wps-server/src/main/java/org/n52/wps/server/response/ResponseData.java index 391751e8a..5c2705fee 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/response/ResponseData.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/response/ResponseData.java @@ -41,6 +41,7 @@ import org.n52.wps.io.GeneratorFactory; import org.n52.wps.io.IGenerator; import org.n52.wps.io.data.IData; +import org.n52.wps.server.RepositoryManagerSingletonWrapper; import org.n52.wps.server.ExceptionReport; import org.n52.wps.server.ProcessDescription; import org.n52.wps.server.RepositoryManager; @@ -50,9 +51,9 @@ * This and the inheriting classes in charge of populating the ExecuteResponseDocument. */ public abstract class ResponseData { - - private static Logger LOGGER = LoggerFactory.getLogger(ResponseData.class); - + + private static Logger LOGGER = LoggerFactory.getLogger(ResponseData.class); + protected IData obj = null; protected String id; protected String schema; @@ -61,53 +62,53 @@ public abstract class ResponseData { protected IGenerator generator = null; protected String algorithmIdentifier = null; protected ProcessDescription description = null; - - - public ResponseData(IData obj, String id, String schema, String encoding, + + + public ResponseData(IData obj, String id, String schema, String encoding, String mimeType, String algorithmIdentifier, ProcessDescription description) throws ExceptionReport { - + this.obj = obj; this.id = id; this.algorithmIdentifier = algorithmIdentifier; this.description = description; this.encoding = encoding; - + OutputDescriptionType outputType =null; - + OutputDescriptionType[] describeProcessOutput = ((ProcessDescriptionType)description.getProcessDescriptionType(WPSConfig.VERSION_100)).getProcessOutputs().getOutputArray(); for(OutputDescriptionType tempOutputType : describeProcessOutput){ if(tempOutputType.getIdentifier().getStringValue().equalsIgnoreCase(id)){ outputType = tempOutputType; } } - - - + + + //select generator - + //0. complex output set? --> no: skip //1. mimeType set? //yes--> set it //1.1 schema/encoding set? //yes-->set it //not-->set default values for parser with matching mime type - + //no--> schema or/and encoding are set? //yes-->use it, look if only one mime type can be found //not-->use default values - - + + String finalSchema = null; String finalMimeType = null; String finalEncoding = null; - + if (outputType.isSetComplexOutput()){ if (mimeType != null){ //mime type in request ComplexDataDescriptionType format = null; - + String defaultMimeType = outputType.getComplexOutput().getDefault().getFormat().getMimeType(); - + boolean canUseDefault = false; if(defaultMimeType.equalsIgnoreCase(mimeType)){ ComplexDataDescriptionType potenitalFormat = outputType.getComplexOutput().getDefault().getFormat(); @@ -122,20 +123,20 @@ public ResponseData(IData obj, String id, String schema, String encoding, canUseDefault = true; format = potenitalFormat; } - + } if(schema != null && encoding != null){ if(schema.equalsIgnoreCase(potenitalFormat.getSchema()) && encoding.equalsIgnoreCase(potenitalFormat.getEncoding())){ canUseDefault = true; format = potenitalFormat; } - + } if(schema == null && encoding == null){ canUseDefault = true; format = potenitalFormat; } - + } if(!canUseDefault){ ComplexDataDescriptionType[] formats =outputType.getComplexOutput().getSupported().getFormatArray(); @@ -150,13 +151,13 @@ public ResponseData(IData obj, String id, String schema, String encoding, if(encoding.equalsIgnoreCase(potenitalFormat.getEncoding()) || potenitalFormat.getEncoding() == null){ format = potenitalFormat; } - + } if(schema != null && encoding != null){ if(schema.equalsIgnoreCase(potenitalFormat.getSchema()) && ((encoding.equalsIgnoreCase(potenitalFormat.getEncoding()) || potenitalFormat.getEncoding() == null) )){ format = potenitalFormat; } - + } if(schema == null && encoding == null){ format = potenitalFormat; @@ -167,32 +168,32 @@ public ResponseData(IData obj, String id, String schema, String encoding, if(format == null){ throw new ExceptionReport("Could not determine output format", ExceptionReport.INVALID_PARAMETER_VALUE); } - + finalMimeType = format.getMimeType(); - + if(format.isSetEncoding()){ //no encoding provided--> select default one for mimeType finalEncoding = format.getEncoding(); } - + if(format.isSetSchema()){ //no encoding provided--> select default one for mimeType finalSchema = format.getSchema(); } - + }else{ - + //mimeType not in request if(mimeType==null && encoding==null && schema == null){ //nothing set, use default values finalSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema(); finalMimeType = outputType.getComplexOutput().getDefault().getFormat().getMimeType(); finalEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding(); - + }else{ //do a smart search an look if a mimeType can be found for either schema and/or encoding - - if(mimeType==null){ + + if(mimeType==null){ if(encoding!=null && schema==null){ //encoding set only ComplexDataDescriptionType encodingFormat = null; @@ -213,7 +214,7 @@ public ResponseData(IData obj, String id, String schema, String encoding, } } } - + if(found == 1){ finalEncoding = foundEncoding; finalMimeType = encodingFormat.getMimeType(); @@ -223,7 +224,7 @@ public ResponseData(IData obj, String id, String schema, String encoding, }else{ throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding not unique]", ExceptionReport.MISSING_PARAMETER_VALUE); } - + } if(schema != null && encoding==null){ //schema set only @@ -245,7 +246,7 @@ public ResponseData(IData obj, String id, String schema, String encoding, } } } - + if(found == 1){ finalSchema = foundSchema; finalMimeType = schemaFormat.getMimeType(); @@ -255,20 +256,20 @@ public ResponseData(IData obj, String id, String schema, String encoding, }else{ throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given schema not unique]", ExceptionReport.MISSING_PARAMETER_VALUE); } - + } if(encoding!=null && schema!=null){ //schema and encoding set - - + + //encoding String defaultEncoding = outputType.getComplexOutput().getDefault().getFormat().getEncoding(); - + List foundEncodingList = new ArrayList(); if(defaultEncoding.equalsIgnoreCase(encoding)){ foundEncodingList.add(outputType.getComplexOutput().getDefault().getFormat()); - - + + }else{ ComplexDataDescriptionType[] formats = outputType.getComplexOutput().getSupported().getFormatArray(); for(ComplexDataDescriptionType tempFormat : formats){ @@ -276,10 +277,10 @@ public ResponseData(IData obj, String id, String schema, String encoding, foundEncodingList.add(tempFormat); } } - - - - + + + + //schema List foundSchemaList = new ArrayList(); String defaultSchema = outputType.getComplexOutput().getDefault().getFormat().getSchema(); @@ -293,8 +294,8 @@ public ResponseData(IData obj, String id, String schema, String encoding, } } } - - + + //results ComplexDataDescriptionType foundCommonFormat = null; for(ComplexDataDescriptionType encodingFormat : foundEncodingList){ @@ -303,10 +304,10 @@ public ResponseData(IData obj, String id, String schema, String encoding, foundCommonFormat = encodingFormat; } } - - + + } - + if(foundCommonFormat!=null){ mimeType = foundCommonFormat.getMimeType(); if(foundCommonFormat.isSetEncoding()){ @@ -318,44 +319,44 @@ public ResponseData(IData obj, String id, String schema, String encoding, }else{ throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding and schema are not unique]", ExceptionReport.MISSING_PARAMETER_VALUE); } - + } - + } - + } } - + } } - + this.schema = finalSchema; if(this.encoding==null){ this.encoding = finalEncoding; } this.mimeType = finalMimeType; - - - - + + + + } protected void prepareGenerator() throws ExceptionReport { - Class algorithmOutput = RepositoryManager.getInstance().getOutputDataTypeForAlgorithm(this.algorithmIdentifier, id); - + Class algorithmOutput = RepositoryManagerSingletonWrapper.getInstance().getOutputDataTypeForAlgorithm(this.algorithmIdentifier, id); + LOGGER.debug("Looking for matching Generator: schema: {}, mimeType {}, encoding: {}", schema, mimeType, encoding); - + GeneratorFactory factory = GeneratorFactory.getInstance(); this.generator = factory.getGenerator(this.schema, this.mimeType, this.encoding, algorithmOutput); - - if(this.generator != null){ + + if(this.generator != null){ LOGGER.info("Using generator " + generator.getClass().getName() + " for Schema: " + schema); } if(this.generator == null) { throw new ExceptionReport("Could not find an appropriate generator based on given mimetype/schema/encoding for output", ExceptionReport.NO_APPLICABLE_CODE); } } - + } diff --git a/52n-wps-server/src/test/java/org/n52/wps/server/CapabilitiesGetProcessDescriptionExceptionTest.java b/52n-wps-server/src/test/java/org/n52/wps/server/CapabilitiesGetProcessDescriptionExceptionTest.java index 83eb9adca..3d64927c5 100644 --- a/52n-wps-server/src/test/java/org/n52/wps/server/CapabilitiesGetProcessDescriptionExceptionTest.java +++ b/52n-wps-server/src/test/java/org/n52/wps/server/CapabilitiesGetProcessDescriptionExceptionTest.java @@ -47,40 +47,41 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; public class CapabilitiesGetProcessDescriptionExceptionTest extends AbstractITClass { - - public static final String IDENTIFIER = "CatchMeIfYouCan"; + + public static final String IDENTIFIER = "CatchMeIfYouCan"; public static boolean algorithmTriedToInstantiate; @Before public void setUp(){ - MockMvcBuilders.webAppContextSetup(this.wac).build(); - WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); + RepositoryManager repositoryManager = new RepositoryManager(); + repositoryManager.setApplicationContext(this.wac); + repositoryManager.init(); } - + @Test public void shouldIgnoreExceptionousProcess() throws XmlException, IOException { // MockUtil.getMockConfig(); CapabilitiesDocument caps = CapabilitiesConfiguration.getInstance(CapabilitiesDocument.Factory.newInstance()); - + Assert.assertTrue("Erroneous algorithm was never instantiated!", algorithmTriedToInstantiate); - + boolean found = false; for (ProcessBriefType pbt : caps.getCapabilities().getProcessOfferings().getProcessArray()) { if (IDENTIFIER.equals(pbt.getIdentifier().getStringValue())) { found = true; } } - + Assert.assertFalse("Algo found but was not expected!", found); } @Algorithm(version = "0.1", identifier = CapabilitiesGetProcessDescriptionExceptionTest.IDENTIFIER) public static class InstantiationExceptionAlgorithm extends AbstractAnnotatedAlgorithm { - + public InstantiationExceptionAlgorithm() { CapabilitiesGetProcessDescriptionExceptionTest.algorithmTriedToInstantiate = true; } - + private String output; @LiteralDataInput(identifier = "input") @@ -95,12 +96,12 @@ public String getOutput() { public void thisMethodsWillNeverEverByCalled() { this.output = "w0000t"; } - + @Override public synchronized ProcessDescription getDescription() { throw new RuntimeException("Gotcha!"); } - + } } diff --git a/52n-wps-server/src/test/java/org/n52/wps/server/request/ExecuteRequestTest.java b/52n-wps-server/src/test/java/org/n52/wps/server/request/ExecuteRequestTest.java index 166c0bf9d..76daa3bcc 100644 --- a/52n-wps-server/src/test/java/org/n52/wps/server/request/ExecuteRequestTest.java +++ b/52n-wps-server/src/test/java/org/n52/wps/server/request/ExecuteRequestTest.java @@ -76,7 +76,6 @@ public void setUp(){ fac = DocumentBuilderFactory.newInstance(); fac.setNamespaceAware(true); - MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test diff --git a/52n-wps-server/src/test/java/org/n52/wps/server/request/InputHandlerTest.java b/52n-wps-server/src/test/java/org/n52/wps/server/request/InputHandlerTest.java index 6f72b3f5e..3174c80fe 100644 --- a/52n-wps-server/src/test/java/org/n52/wps/server/request/InputHandlerTest.java +++ b/52n-wps-server/src/test/java/org/n52/wps/server/request/InputHandlerTest.java @@ -55,14 +55,16 @@ import org.n52.wps.commons.WPSConfig; import org.n52.wps.server.ExceptionReport; import org.n52.wps.server.RepositoryManager; +import org.n52.wps.server.RepositoryManagerSingletonWrapper; import org.n52.wps.server.handler.DataInputInterceptors.InterceptorInstance; import org.n52.wps.util.XMLBeansHelper; +import org.n52.wps.webapp.common.AbstractITClass; /** * * @author isuftin */ -public class InputHandlerTest { +public class InputHandlerTest extends AbstractITClass { private static File simpleBufferAlgorithmFile = null; private static File dummyTestClassAlgorithmFile = null; @@ -84,6 +86,10 @@ public void setUp() throws XmlException, IOException { dummyTestClassAlgorithmFile = new File("src/test/resources/DummyTestClass.xml"); dummyTestClassAlgorithmExecDoc = ExecuteDocument.Factory.parse(dummyTestClassAlgorithmFile); dummyTestClassAlgorithmInputArray = dummyTestClassAlgorithmExecDoc.getExecute().getDataInputs().getInputArray(); + + RepositoryManager repositoryManager = new RepositoryManager(); + repositoryManager.setApplicationContext(this.wac); + repositoryManager.init(); } @After @@ -116,9 +122,9 @@ public void testInputHandlerResolveInputDescriptionTypes() throws ExceptionRepor System.out.println("Testing testInputHandlerResolveInputDescriptionTypes..."); new InputHandler.Builder(new Input(simpleBufferAlgorithmInputArray), "org.n52.wps.server.algorithm.SimpleBufferAlgorithm").build(); - - ProcessDescriptionType processDescriptionType = (ProcessDescriptionType) RepositoryManager.getInstance().getProcessDescription("org.n52.wps.server.algorithm.SimpleBufferAlgorithm").getProcessDescriptionType(WPSConfig.VERSION_100); - + + ProcessDescriptionType processDescriptionType = (ProcessDescriptionType) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription("org.n52.wps.server.algorithm.SimpleBufferAlgorithm").getProcessDescriptionType(WPSConfig.VERSION_100); + InputDescriptionType idt = XMLBeansHelper.findInputByID("data", processDescriptionType.getDataInputs()); assertThat(idt, is(notNullValue())); assertThat(idt.getMaxOccurs().intValue(), equalTo(1)); @@ -126,8 +132,8 @@ public void testInputHandlerResolveInputDescriptionTypes() throws ExceptionRepor new InputHandler.Builder(new Input(dummyTestClassAlgorithmInputArray), "org.n52.wps.server.algorithm.test.DummyTestClass").build(); - processDescriptionType = (ProcessDescriptionType) RepositoryManager.getInstance().getProcessDescription("org.n52.wps.server.algorithm.test.DummyTestClass").getProcessDescriptionType(WPSConfig.VERSION_100); - + processDescriptionType = (ProcessDescriptionType) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription("org.n52.wps.server.algorithm.test.DummyTestClass").getProcessDescriptionType(WPSConfig.VERSION_100); + idt = XMLBeansHelper.findInputByID("BBOXInputData", processDescriptionType.getDataInputs()); assertThat(idt, is(notNullValue())); assertThat(idt.getMaxOccurs().intValue(), equalTo(1)); @@ -139,8 +145,8 @@ public void testInputHandlerGetNonDefaultFormat() throws ExceptionReport, XmlExc System.out.println("Testing testInputHandlerGetNonDefaultFormat..."); InputHandler instance = new InputHandler.Builder(new Input(simpleBufferAlgorithmInputArray), "org.n52.wps.server.algorithm.SimpleBufferAlgorithm").build(); - ProcessDescriptionType processDescriptionType = (ProcessDescriptionType) RepositoryManager.getInstance().getProcessDescription("org.n52.wps.server.algorithm.SimpleBufferAlgorithm").getProcessDescriptionType(WPSConfig.VERSION_100); - + ProcessDescriptionType processDescriptionType = (ProcessDescriptionType) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription("org.n52.wps.server.algorithm.SimpleBufferAlgorithm").getProcessDescriptionType(WPSConfig.VERSION_100); + InputDescriptionType idt = XMLBeansHelper.findInputByID("data", processDescriptionType.getDataInputs()); String dataMimeType = "text/xml; subtype=gml/3.1.0"; String dataSchema = "http://schemas.opengis.net/gml/3.1.0/base/feature.xsd"; @@ -152,13 +158,13 @@ public void testInputHandlerGetNonDefaultFormat() throws ExceptionReport, XmlExc assertThat(cddt.getSchema(), is(equalTo("http://schemas.opengis.net/gml/3.1.0/base/feature.xsd"))); instance = new InputHandler.Builder(new Input(dummyTestClassAlgorithmInputArray), "org.n52.wps.server.algorithm.test.DummyTestClass").build(); - processDescriptionType = (ProcessDescriptionType) RepositoryManager.getInstance().getProcessDescription("org.n52.wps.server.algorithm.test.DummyTestClass").getProcessDescriptionType(WPSConfig.VERSION_100); - + processDescriptionType = (ProcessDescriptionType) RepositoryManagerSingletonWrapper.getInstance().getProcessDescription("org.n52.wps.server.algorithm.test.DummyTestClass").getProcessDescriptionType(WPSConfig.VERSION_100); + idt = XMLBeansHelper.findInputByID("BBOXInputData", processDescriptionType.getDataInputs()); cddt = instance.getNonDefaultFormat(idt, dataMimeType, dataSchema, dataEncoding); assertThat(cddt, is(nullValue())); } - + @Test public void testInputHandlerGetComplexValueNodeString() throws ExceptionReport, XmlException, IOException { System.out.println("Testing testInputHandlerGetComplexValueNodeString..."); diff --git a/52n-wps-server/src/test/java/org/n52/wps/server/request/SimpleBufferAlgorithmInputHandlerTest.java b/52n-wps-server/src/test/java/org/n52/wps/server/request/SimpleBufferAlgorithmInputHandlerTest.java index 9962e7b03..34b2decaf 100644 --- a/52n-wps-server/src/test/java/org/n52/wps/server/request/SimpleBufferAlgorithmInputHandlerTest.java +++ b/52n-wps-server/src/test/java/org/n52/wps/server/request/SimpleBufferAlgorithmInputHandlerTest.java @@ -53,6 +53,7 @@ import org.n52.wps.commons.WPSConfig; import org.n52.wps.io.data.IData; import org.n52.wps.server.ExceptionReport; +import org.n52.wps.server.RepositoryManager; import org.n52.wps.webapp.api.ConfigurationManager; import org.n52.wps.webapp.common.AbstractITClass; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -61,7 +62,7 @@ * * @author isuftin */ -public class SimpleBufferAlgorithmInputHandlerTest extends AbstractITClass{ +public class SimpleBufferAlgorithmInputHandlerTest extends AbstractITClass { private static String sampleFileName = null; private static File sampleFile = null; @@ -83,8 +84,9 @@ public static void tearDownClass() { @Before public void setUp() throws XmlException, IOException { - MockMvcBuilders.webAppContextSetup(this.wac).build(); - WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); + RepositoryManager repositoryManager = new RepositoryManager(); + repositoryManager.setApplicationContext(this.wac); + repositoryManager.init(); } @After diff --git a/52n-wps-server/src/test/java/org/n52/wps/server/response/ExecuteResponseBuilderTest.java b/52n-wps-server/src/test/java/org/n52/wps/server/response/ExecuteResponseBuilderTest.java index 13b5339f4..97a2caeff 100644 --- a/52n-wps-server/src/test/java/org/n52/wps/server/response/ExecuteResponseBuilderTest.java +++ b/52n-wps-server/src/test/java/org/n52/wps/server/response/ExecuteResponseBuilderTest.java @@ -45,6 +45,8 @@ import org.junit.BeforeClass; import org.junit.Test; import org.n52.wps.commons.WPSConfig; +import org.n52.wps.server.RepositoryManagerSingletonWrapper; +import org.n52.wps.server.RepositoryManager; import org.n52.wps.server.request.ExecuteRequestV100; import org.n52.wps.webapp.api.ConfigurationManager; import org.n52.wps.webapp.common.AbstractITClass; @@ -75,8 +77,9 @@ public void setUp() throws Exception { fac = DocumentBuilderFactory.newInstance(); fac.setNamespaceAware(true); - MockMvcBuilders.webAppContextSetup(this.wac).build(); - WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); + RepositoryManager repositoryManager = new RepositoryManager(); + repositoryManager.setApplicationContext(wac); + repositoryManager.init(); } @Test diff --git a/52n-wps-server/src/test/java/org/n52/wps/server/response/OutputDataItemTest.java b/52n-wps-server/src/test/java/org/n52/wps/server/response/OutputDataItemTest.java index 55a4233bb..35da93f5e 100644 --- a/52n-wps-server/src/test/java/org/n52/wps/server/response/OutputDataItemTest.java +++ b/52n-wps-server/src/test/java/org/n52/wps/server/response/OutputDataItemTest.java @@ -78,12 +78,12 @@ /** * @author BenjaminPross(bpross-52n) - * + * * This class is for testing the updateResponseForLiteralData() method of the class OutputDataItem.java. * */ public class OutputDataItemTest extends AbstractITClass{ - + private ProcessDescriptionType descriptionsType; private ProcessDescription description; private String processID = "org.n52.wps.server.response.OutputDataItemTest"; @@ -97,9 +97,6 @@ public class OutputDataItemTest extends AbstractITClass{ @Before public void setUp() { - MockMvcBuilders.webAppContextSetup(this.wac).build(); - WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); - literalDataList = new ArrayList(); String url = ""; @@ -111,7 +108,7 @@ public void setUp() { } String uuid = UUID.randomUUID().toString(); - + literalDataList.add(new LiteralBase64BinaryBinding(uuid.getBytes())); literalDataList.add(new LiteralBooleanBinding(true)); literalDataList.add(new LiteralByteBinding((byte) 127)); @@ -205,7 +202,7 @@ private void testLiteralOutput(ILiteralData literalDataBinding) .concat((int) bytes[i] + ", "); }else{ bytesAsIntegerValues = bytesAsIntegerValues - .concat((int) bytes[i] + "]"); + .concat((int) bytes[i] + "]"); } } startText = startText.concat("" + bytesAsIntegerValues); @@ -228,9 +225,9 @@ private void testLiteralOutput(ILiteralData literalDataBinding) outputType.addNewDataType().setStringValue(dataTypeAsString); description = new ProcessDescription(); - + description.addProcessDescriptionForVersion(descriptionsType, WPSConfig.VERSION_100); - + OutputDataItem ouDI = new OutputDataItem(literalDataBinding, "output", null, null, null, outputTitle, processID, description); diff --git a/52n-wps-server/src/test/java/org/n52/wps/server/response/RawDataTest.java b/52n-wps-server/src/test/java/org/n52/wps/server/response/RawDataTest.java index ff43c52df..166572304 100644 --- a/52n-wps-server/src/test/java/org/n52/wps/server/response/RawDataTest.java +++ b/52n-wps-server/src/test/java/org/n52/wps/server/response/RawDataTest.java @@ -65,8 +65,6 @@ public static void setUpClass() { @Before public void setUp(){ - MockMvcBuilders.webAppContextSetup(this.wac).build(); - WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); algorithm = new DummyTestClass(); processDescription = algorithm.getDescription(); identifier = algorithm.getWellKnownName(); diff --git a/52n-wps-server/src/test/java/org/n52/wps/server/response/StatusTest.java b/52n-wps-server/src/test/java/org/n52/wps/server/response/StatusTest.java index 461167e5c..6408cf563 100644 --- a/52n-wps-server/src/test/java/org/n52/wps/server/response/StatusTest.java +++ b/52n-wps-server/src/test/java/org/n52/wps/server/response/StatusTest.java @@ -58,6 +58,7 @@ import org.xml.sax.SAXException; import static org.junit.Assert.assertTrue; +import org.n52.wps.server.RepositoryManagerSingletonWrapper; public class StatusTest extends AbstractITClass { @@ -67,11 +68,13 @@ public class StatusTest extends AbstractITClass { @Before public void setUp() { - MockMvcBuilders.webAppContextSetup(this.wac).build(); - WPSConfig.getInstance().setConfigurationManager(this.wac.getBean(ConfigurationManager.class)); fac = DocumentBuilderFactory.newInstance(); fac.setNamespaceAware(true); algorithm = new StatusTestingProcess(); + + RepositoryManager repositoryManager = new RepositoryManager(); + repositoryManager.setApplicationContext(wac); + repositoryManager.init(); } @Test @@ -87,7 +90,7 @@ public void testGetStatusV200() { final String requestID = executeRequestV200.getUniqueId().toString(); - algorithm = RepositoryManager.getInstance().getAlgorithm(executeRequestV200.getAlgorithmIdentifier()); + algorithm = RepositoryManagerSingletonWrapper.getInstance().getAlgorithm(executeRequestV200.getAlgorithmIdentifier()); if (algorithm instanceof ISubject) { ISubject subject = (ISubject) algorithm; @@ -98,7 +101,7 @@ public void update(ISubject o) { try { StatusInfoDocument statusInfoDocument = StatusInfoDocument.Factory.parse(DatabaseFactory.getDatabase().lookupStatus(requestID)); assertTrue(statusInfoDocument.getStatusInfo().getStatus() != null); - + } catch (ExceptionReport | XmlException | IOException e) { e.printStackTrace(); } diff --git a/52n-wps-webapp/src/main/resources/dispatcher-servlet.xml b/52n-wps-webapp/src/main/resources/dispatcher-servlet.xml index b6cb0993f..04bba1cd3 100644 --- a/52n-wps-webapp/src/main/resources/dispatcher-servlet.xml +++ b/52n-wps-webapp/src/main/resources/dispatcher-servlet.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd -http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd +http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> @@ -14,6 +14,8 @@ http://www.springframework.org/schema/mvc http://www.springframework.org/schema/ + + @@ -37,7 +39,7 @@ http://www.springframework.org/schema/mvc http://www.springframework.org/schema/ - + diff --git a/52n-wps-webapp/src/main/webapp/WEB-INF/spring-mvc-config.xml b/52n-wps-webapp/src/main/webapp/WEB-INF/spring-mvc-config.xml index ec0f6745a..437df3ee7 100644 --- a/52n-wps-webapp/src/main/webapp/WEB-INF/spring-mvc-config.xml +++ b/52n-wps-webapp/src/main/webapp/WEB-INF/spring-mvc-config.xml @@ -15,7 +15,7 @@ - + diff --git a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/GeneratorsControllerIntegrationTest.java b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/GeneratorsControllerIntegrationTest.java index c0466e57d..715912217 100644 --- a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/GeneratorsControllerIntegrationTest.java +++ b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/GeneratorsControllerIntegrationTest.java @@ -57,7 +57,6 @@ public class GeneratorsControllerIntegrationTest extends AbstractITClassForContr @Before public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test diff --git a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/LogConfigurationsControllerIntegrationTest.java b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/LogConfigurationsControllerIntegrationTest.java index a344e76b7..a65c85eab 100644 --- a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/LogConfigurationsControllerIntegrationTest.java +++ b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/LogConfigurationsControllerIntegrationTest.java @@ -57,16 +57,15 @@ public class LogConfigurationsControllerIntegrationTest extends AbstractITClassF @Autowired ConfigurationManager configurationManager; - + @Autowired private JDomUtil jDomUtil; - + @Autowired private ResourcePathUtil resourcePathUtil; - + @Before public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test @@ -81,7 +80,7 @@ public void display() throws Exception { public void processPost_success() throws Exception { String path = resourcePathUtil.getClassPathResourcePath(XmlLogConfigurationsDAO.FILE_NAME); Document originalDoc = jDomUtil.parse(path); - + RequestBuilder request = post("/log") .param("wpsfileAppenderFileNamePattern", "testFileAppenderFileNamePattern") .param("wpsfileAppenderEncoderPattern", "testFileAppenderFileNamePattern") @@ -96,7 +95,7 @@ public void processPost_success() throws Exception { result.andExpect(status().isOk()); LogConfigurations logConfigurations = configurationManager.getLogConfigurationsServices().getLogConfigurations(); assertEquals("testFileAppenderFileNamePattern", logConfigurations.getWpsfileAppenderFileNamePattern()); - + //reset document to original state jDomUtil.write(originalDoc, path); } diff --git a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ParsersControllerIntegrationTest.java b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ParsersControllerIntegrationTest.java index fc790194b..badb50923 100644 --- a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ParsersControllerIntegrationTest.java +++ b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ParsersControllerIntegrationTest.java @@ -57,7 +57,6 @@ public class ParsersControllerIntegrationTest extends AbstractITClassForControll @Before public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test diff --git a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/RepositoriesControllerIntegrationTest.java b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/RepositoriesControllerIntegrationTest.java index 0d4624b9f..b442e94b9 100644 --- a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/RepositoriesControllerIntegrationTest.java +++ b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/RepositoriesControllerIntegrationTest.java @@ -57,7 +57,6 @@ public class RepositoriesControllerIntegrationTest extends AbstractITClassForCon @Before public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test diff --git a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServerControllerIntegrationTest.java b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServerControllerIntegrationTest.java index b21b81ac3..f6a2b1b92 100644 --- a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServerControllerIntegrationTest.java +++ b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServerControllerIntegrationTest.java @@ -52,10 +52,9 @@ public class ServerControllerIntegrationTest extends AbstractITClassForControlle @Autowired private Server server; - + @Before public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test diff --git a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServiceIdentificationControllerIntegrationTest.java b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServiceIdentificationControllerIntegrationTest.java index 881dfc311..66e8cb256 100644 --- a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServiceIdentificationControllerIntegrationTest.java +++ b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServiceIdentificationControllerIntegrationTest.java @@ -54,19 +54,18 @@ public class ServiceIdentificationControllerIntegrationTest extends AbstractITClassForControllerTests { private MockMvc mockMvc; - + @Autowired ConfigurationManager configurationManager; - + @Autowired private JDomUtil jDomUtil; - + @Autowired private ResourcePathUtil resourcePathUtil; @Before public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test @@ -81,7 +80,7 @@ public void display() throws Exception { public void processPost_success() throws Exception { String path = resourcePathUtil.getWebAppResourcePath(XmlCapabilitiesDAO.FILE_NAME); Document originalDoc = jDomUtil.parse(path); - + RequestBuilder request = post("/service_identification") .param("title", "Posted Title") .param("serviceAbstract", "Posted Service Abstract") @@ -94,7 +93,7 @@ public void processPost_success() throws Exception { result.andExpect(status().isOk()); ServiceIdentification serviceIdentification = configurationManager.getCapabilitiesServices().getServiceIdentification(); assertEquals("Posted Title", serviceIdentification.getTitle()); - + //reset document to original state jDomUtil.write(originalDoc, path); } diff --git a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServiceProviderControllerIntegrationTest.java b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServiceProviderControllerIntegrationTest.java index 6c970d5b0..ec20dcb79 100644 --- a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServiceProviderControllerIntegrationTest.java +++ b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/ServiceProviderControllerIntegrationTest.java @@ -57,16 +57,15 @@ public class ServiceProviderControllerIntegrationTest extends AbstractITClassFor @Autowired private ConfigurationManager configurationManager; - + @Autowired private JDomUtil jDomUtil; - + @Autowired private ResourcePathUtil resourcePathUtil; - + @Before public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test @@ -81,7 +80,7 @@ public void display() throws Exception { public void processPost_success() throws Exception { String path = resourcePathUtil.getWebAppResourcePath(XmlCapabilitiesDAO.FILE_NAME); Document originalDoc = jDomUtil.parse(path); - + RequestBuilder request = post("/service_provider") .param("providerName", "providerName") .param("providerSite", "providerSite") @@ -99,12 +98,12 @@ public void processPost_success() throws Exception { result.andExpect(status().isOk()); ServiceProvider serviceProvider = configurationManager.getCapabilitiesServices().getServiceProvider(); assertEquals("providerName", serviceProvider.getProviderName()); - + //reset document to original state jDomUtil.write(originalDoc, path); } - //not needed anymore in this form, as all provider parameters are optional now + //not needed anymore in this form, as all provider parameters are optional now // @Test // public void processPost_failure() throws Exception { // RequestBuilder request = post("/service_provider") diff --git a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/UploadControllerIntegrationTest.java b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/UploadControllerIntegrationTest.java index 2905a1540..464497db7 100644 --- a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/UploadControllerIntegrationTest.java +++ b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/UploadControllerIntegrationTest.java @@ -72,7 +72,6 @@ public class UploadControllerIntegrationTest extends AbstractITClassForControlle @Before public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test diff --git a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/UsersControllerIntegrationTest.java b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/UsersControllerIntegrationTest.java index 244ace461..62f60c417 100644 --- a/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/UsersControllerIntegrationTest.java +++ b/52n-wps-webapp/src/test/java/org/n52/wps/webapp/web/UsersControllerIntegrationTest.java @@ -61,7 +61,6 @@ public class UsersControllerIntegrationTest extends AbstractITClassForController @Before public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test From c05523427d31f5f6cc5d6115185119cc13154a4a Mon Sep 17 00:00:00 2001 From: Henning Bredel Date: Tue, 22 Sep 2015 13:47:47 +0200 Subject: [PATCH 2/4] remove not needed method --- .../n52/wps/server/RepositoryManagerSingletonWrapper.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java index 594ded839..468a5f800 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java @@ -57,9 +57,4 @@ public static RepositoryManager getInstance() { } return instance; } - - public static void reInitialize() { - RepositoryManager rm = getInstance(); - rm.reInitialize(); - } } From db04d7dd9f48515e26303e24b14d4ec5c1552468 Mon Sep 17 00:00:00 2001 From: Henning Bredel Date: Tue, 22 Sep 2015 15:50:08 +0200 Subject: [PATCH 3/4] intialize repository manager --- .../n52/wps/server/RepositoryManagerSingletonWrapper.java | 2 +- .../java/org/n52/wps/server/request/ExecuteRequestTest.java | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java index 468a5f800..f264cd726 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManagerSingletonWrapper.java @@ -1,5 +1,5 @@ /** - * Copyright (C) 2007 - 2014 52°North Initiative for Geospatial Open Source + * Copyright (C) 2007 - 2014 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it diff --git a/52n-wps-server/src/test/java/org/n52/wps/server/request/ExecuteRequestTest.java b/52n-wps-server/src/test/java/org/n52/wps/server/request/ExecuteRequestTest.java index d13f24557..c59f3417b 100644 --- a/52n-wps-server/src/test/java/org/n52/wps/server/request/ExecuteRequestTest.java +++ b/52n-wps-server/src/test/java/org/n52/wps/server/request/ExecuteRequestTest.java @@ -49,6 +49,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.n52.wps.server.ExceptionReport; +import org.n52.wps.server.RepositoryManager; import org.n52.wps.server.database.DatabaseFactory; import org.n52.wps.server.request.ExecuteRequestV100; import org.n52.wps.webapp.common.AbstractITClass; @@ -76,6 +77,10 @@ public void setUp(){ fac = DocumentBuilderFactory.newInstance(); fac.setNamespaceAware(true); + + RepositoryManager repositoryManager = new RepositoryManager(); + repositoryManager.setApplicationContext(this.wac); + repositoryManager.init(); } @Test From 492e6d664dcff40174471d0984a68bdb42a22094 Mon Sep 17 00:00:00 2001 From: Henning Bredel Date: Tue, 22 Sep 2015 18:36:54 +0200 Subject: [PATCH 4/4] initiating WPS4R repository --- .../server/r/LocalRAlgorithmRepository.java | 3 +- .../wps/server/r/RConfigurationModule.java | 13 +--- .../org/n52/wps/server/RepositoryManager.java | 69 ++++++++----------- .../src/main/resources/db/initial-data.sql | 3 +- 4 files changed, 35 insertions(+), 53 deletions(-) diff --git a/52n-wps-r/src/main/java/org/n52/wps/server/r/LocalRAlgorithmRepository.java b/52n-wps-r/src/main/java/org/n52/wps/server/r/LocalRAlgorithmRepository.java index 5ed635746..c15ac9df1 100644 --- a/52n-wps-r/src/main/java/org/n52/wps/server/r/LocalRAlgorithmRepository.java +++ b/52n-wps-r/src/main/java/org/n52/wps/server/r/LocalRAlgorithmRepository.java @@ -75,7 +75,8 @@ public class LocalRAlgorithmRepository implements ITransactionalAlgorithmReposit private static final Logger LOGGER = LoggerFactory.getLogger(LocalRAlgorithmRepository.class); - public static final String COMPONENT_NAME = "RAlgorithmRepository"; +// static final String COMPONENT_NAME = "RAlgorithmRepository"; + static final String COMPONENT_NAME = "org.n52.wps.server.r.RConfigurationModule"; private static final String DESCRPTION_VERSION_FOR_VALIDATION = WPSConfig.VERSION_100; diff --git a/52n-wps-r/src/main/java/org/n52/wps/server/r/RConfigurationModule.java b/52n-wps-r/src/main/java/org/n52/wps/server/r/RConfigurationModule.java index d035999e8..2a39c3e96 100644 --- a/52n-wps-r/src/main/java/org/n52/wps/server/r/RConfigurationModule.java +++ b/52n-wps-r/src/main/java/org/n52/wps/server/r/RConfigurationModule.java @@ -42,7 +42,9 @@ import org.n52.wps.webapp.api.types.StringConfigurationEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +//@Component("rActualConfigurationModule") public class RConfigurationModule extends ClassKnowingModule { private static final Logger LOGGER = LoggerFactory.getLogger(RConfigurationModule.class); @@ -103,14 +105,6 @@ public class RConfigurationModule extends ClassKnowingModule { private boolean scriptDownloadEnabled; private boolean sessionInfoDownloadEnabled; -// private AlgorithmEntry algorithmEntry = new AlgorithmEntry("org.n52.wps.server.algorithm.JTSConvexHullAlgorithm", true); -// private AlgorithmEntry algorithmEntry1 = new AlgorithmEntry("org.n52.wps.server.algorithm.test.DummyTestClass", true); -// private AlgorithmEntry algorithmEntry2 = new AlgorithmEntry("org.n52.wps.server.algorithm.test.LongRunningDummyTestClass", true); -// private AlgorithmEntry algorithmEntry3 = new AlgorithmEntry("org.n52.wps.server.algorithm.test.MultipleComplexInAndOutputsDummyTestClass", true); -// private AlgorithmEntry algorithmEntry4 = new AlgorithmEntry("org.n52.wps.server.algorithm.test.MultiReferenceInputAlgorithm", true); -// private AlgorithmEntry algorithmEntry5 = new AlgorithmEntry("org.n52.wps.server.algorithm.test.MultiReferenceBinaryInputAlgorithm", true); -// private AlgorithmEntry algorithmEntry6 = new AlgorithmEntry("org.n52.wps.server.algorithm.test.EchoProcess", true); - private List algorithmEntries; private List> configurationEntries = Arrays.asList(enableBatchStartEntry,datatypeConfigEntry, @@ -119,8 +113,7 @@ public class RConfigurationModule extends ClassKnowingModule { importDownloadEnabledEntry,scriptDownloadEnabledEntry,sessionInfoDownloadEnabledEntry); public RConfigurationModule() { - algorithmEntries = new ArrayList<>(); -// algorithmEntries.addAll(Arrays.asList(algorithmEntry, algorithmEntry1, algorithmEntry2, algorithmEntry3, algorithmEntry4, algorithmEntry5, algorithmEntry6)); + algorithmEntries = new ArrayList<>(); } @Override diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java index 7175eae44..8c3896748 100644 --- a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java +++ b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java @@ -100,18 +100,14 @@ private List getRepositoryNames(){ Map repositoryMap = WPSConfig.getInstance() .getRegisteredAlgorithmRepositoryConfigModules(); - for (ConfigurationModule repository : repositoryMap.values()) { - if(repository.isActive()==false){ - continue; - } - - if(repository instanceof ClassKnowingModule){ - String repositoryClassName = ((ClassKnowingModule)repository).getClassName(); - repositoryNames.add(repositoryClassName); - if(!repositories.containsKey(repositoryClassName)){ - loadRepository(repository.getClass().getCanonicalName(), repositoryClassName, repositoryMap); - } - } + for (ConfigurationModule configModule : repositoryMap.values()) { + if(configModule.isActive() && configModule instanceof ClassKnowingModule) { + String repositoryClassName = ((ClassKnowingModule)configModule).getClassName(); + repositoryNames.add(repositoryClassName); + if( !repositories.containsKey(repositoryClassName)){ + loadRepository(configModule.getClass().getCanonicalName(), (ClassKnowingModule) configModule); + } + } } @@ -124,49 +120,40 @@ private void loadAllRepositories(){ System.gc(); - Map repositoryMap = WPSConfig.getInstance() + Map repositoryConfigModules = WPSConfig.getInstance() .getRegisteredAlgorithmRepositoryConfigModules(); - for (String repositoryName : repositoryMap.keySet()) { + for (String configModuleName : repositoryConfigModules.keySet()) { - ConfigurationModule repository = repositoryMap.get(repositoryName); + ConfigurationModule configModule = repositoryConfigModules.get(configModuleName); - if (repository instanceof ClassKnowingModule) { - String repositoryClassName = ((ClassKnowingModule) repository).getClassName(); - loadRepository(repositoryName, repositoryClassName, repositoryMap); + if (configModule instanceof ClassKnowingModule) { + loadRepository(configModuleName, (ClassKnowingModule) configModule); } else { - LOGGER.warn("Repository {} not instanceof ClassKnowingModule. Will not load it.", repositoryName); + LOGGER.warn("ConfigModule {} not instanceof ClassKnowingModule. Will not load it.", configModuleName); } } } - private void loadRepository(String repositoryName, String repositoryClassName, Map repositoryMap) { - LOGGER.debug("Loading repository: {}", repositoryName); - - if(repositoryMap == null){ - repositoryMap = WPSConfig - .getInstance().getRegisteredAlgorithmRepositoryConfigModules(); - } - - ConfigurationModule repository = repositoryMap.get(repositoryName); - - if (repository.isActive() == false) { - LOGGER.warn("Repository {} not active. Will not load it.", repositoryName); - return; - } - - //registerNewRepository(repositoryClassName); - registerRepository(repositoryName, repositoryClassName); + private void loadRepository(String configModuleName, ClassKnowingModule configModule) { + if (configModule.isActive()) { + LOGGER.debug("Loading module '{}'", configModuleName); + registerRepository(configModuleName, configModule); + } else { + LOGGER.warn("Won't load inactive module '{}'", configModuleName); + } } - private void registerRepository(String name, String className) { + private void registerRepository(String configModuleName, ClassKnowingModule configModule) { + String repositoryClassName = configModule.getClassName(); try { - repositories.put(className, applicationContext.getBean(name, IAlgorithmRepository.class)); + // XXX configModuleName != COMPONENT_NAME of LocalRAlgorithmRepository + repositories.put(repositoryClassName, applicationContext.getBean(configModuleName, IAlgorithmRepository.class)); } catch (NoSuchBeanDefinitionException e) { - LOGGER.warn("Try creating repository the old fashioned way.", className, name); - registerNewRepository(className); + LOGGER.info("Hard wiring '{}' for module '{}'.", repositoryClassName, configModuleName); + registerNewRepository(repositoryClassName); } catch (BeansException e) { - LOGGER.warn("Could not create algorithm repository for class '{}' and name '{}'", className, name, e); + LOGGER.warn("Could not create '{}' for module '{}'", repositoryClassName, configModuleName, e); } } diff --git a/52n-wps-webapp/src/main/resources/db/initial-data.sql b/52n-wps-webapp/src/main/resources/db/initial-data.sql index e4dfd7700..49ee7f372 100644 --- a/52n-wps-webapp/src/main/resources/db/initial-data.sql +++ b/52n-wps-webapp/src/main/resources/db/initial-data.sql @@ -19,6 +19,7 @@ INSERT INTO ALGORITHMENTRY VALUES('test.echo','org.n52.wps.server.r.RConfigurati INSERT INTO ALGORITHMENTRY VALUES('test.calculator','org.n52.wps.server.r.RConfigurationModule',TRUE); INSERT INTO ALGORITHMENTRY VALUES('test.metadata','org.n52.wps.server.r.RConfigurationModule',TRUE); INSERT INTO ALGORITHMENTRY VALUES('test.geo','org.n52.wps.server.r.RConfigurationModule',TRUE); +INSERT INTO ALGORITHMENTRY VALUES('test.image','org.n52.wps.server.r.RConfigurationModule',TRUE); INSERT INTO ALGORITHMENTRY VALUES('test.wpsOff','org.n52.wps.server.r.RConfigurationModule',TRUE); INSERT INTO ALGORITHMENTRY VALUES('test.session','org.n52.wps.server.r.RConfigurationModule',TRUE); INSERT INTO ALGORITHMENTRY VALUES('geo.poly.attribute-sum','org.n52.wps.server.r.RConfigurationModule',TRUE); @@ -661,7 +662,7 @@ INSERT INTO FORMATENTRY VALUES('application/x-geotiff', '', 'base64', 'org.n52.w INSERT INTO FORMATENTRY VALUES('application/hdf4-eos', '', 'base64', 'org.n52.wps.io.modules.parser.GenericRasterFileParserCM', TRUE); INSERT INTO FORMATENTRY VALUES('text/plain', '', 'base64', 'org.n52.wps.io.modules.parser.GenericRasterFileParserCM', TRUE); INSERT INTO FORMATENTRY VALUES('application/img', '', '', 'org.n52.wps.io.modules.parser.GenericRasterFileParserCM', TRUE); -INSERT INTO FORMATENTRY VALUES('image/tiff', '', '', 'org.n52.wps.io.modules.parser.GenericRasterFileParserCM', TRUE); +INSERT INTO FORMATENTRY VALUES('image/tiff', '', '', 'org.n52.wps.io.modules.parser.GenericRasterFileParserCM', TRUE); INSERT INTO FORMATENTRY VALUES('image/geotiff', '', '', 'org.n52.wps.io.modules.parser.GenericRasterFileParserCM', TRUE); INSERT INTO FORMATENTRY VALUES('application/geotiff', '', '', 'org.n52.wps.io.modules.parser.GenericRasterFileParserCM', TRUE); INSERT INTO FORMATENTRY VALUES('application/dbase', '', '', 'org.n52.wps.io.modules.parser.GenericRasterFileParserCM', TRUE);