diff --git a/contrib/extensions/replication/core/pom.xml b/contrib/extensions/replication/core/pom.xml deleted file mode 100644 index daab3c11197..00000000000 --- a/contrib/extensions/replication/core/pom.xml +++ /dev/null @@ -1,228 +0,0 @@ - - - - 4.0.0 - - - - - org.apache.sling - sling - 19 - - - - - - org.apache.sling - org.apache.sling.replication - 0.0.1-SNAPSHOT - bundle - - Apache Sling Replication - - The Apache Sling Replication bundle provides a set of utilities to replicate content from / to other Sling instances. - - - - scm:svn:http://svn.apache.org/repos/asf/sling/trunk/contrib/extensions/replication - scm:svn:https://svn.apache.org/repos/asf/sling/trunk/contrib/extensions/replication - http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/replication - - - - - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.sling - maven-sling-plugin - - - org.apache.felix - maven-bundle-plugin - true - - - org.apache.sling.replication - SLING-CONTENT/libs/sling/replication/config;path:=/libs/sling/replication/install;overwrite:=true - - org.apache.sling.replication.agent, - org.apache.sling.replication.transport.authentication, - org.apache.sling.replication.transport, - org.apache.sling.replication.communication, - org.apache.sling.replication.event, - org.apache.sling.replication.queue, - org.apache.sling.replication.rule, - org.apache.sling.replication.serialization - - httpasyncclient - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - - - - - - - - - junit - junit - test - - - org.mockito - mockito-core - 1.9.5 - test - - - - org.apache.sling - org.apache.sling.api - 2.3.0 - - - org.apache.sling - org.apache.sling.commons.osgi - 2.2.0 - - - org.apache.sling - org.apache.sling.commons.scheduler - 2.4.0 - - - org.apache.sling - org.apache.sling.jcr.api - 2.1.0 - - - org.apache.sling - org.apache.sling.event - 3.3.0 - provided - - - org.apache.sling - org.apache.sling.hc.core - 1.0.6 - provided - - - org.apache.sling - org.apache.sling.settings - 1.3.0 - provided - - - - org.slf4j - slf4j-api - 1.6.2 - - - org.slf4j - slf4j-simple - 1.6.2 - runtime - - - - javax.jcr - jcr - 2.0 - - - javax.servlet - servlet-api - - - org.osgi - org.osgi.core - - - org.osgi - org.osgi.compendium - - - - org.apache.jackrabbit.vault - org.apache.jackrabbit.vault - 3.0.0 - - - - org.apache.httpcomponents - fluent-hc - 4.3.2 - - - org.apache.httpcomponents - httpasyncclient - 4.0 - - - org.apache.httpcomponents - httpcore-osgi - 4.3.1 - - - org.apache.httpcomponents - httpclient-osgi - 4.3.2 - - - - org.apache.jackrabbit - jackrabbit-jcr-commons - 2.6.2 - provided - - - - commons-io - commons-io - 2.4 - provided - - - - - - org.codehaus.mojo - findbugs-maven-plugin - 2.5.3 - - - - diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/AgentConfigurationException.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/AgentConfigurationException.java deleted file mode 100644 index a064a874664..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/AgentConfigurationException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent; - -/** - * Represents errors happened during {@link ReplicationAgent} configuration - */ -@SuppressWarnings("serial") -public class AgentConfigurationException extends Exception { - - public AgentConfigurationException(Exception e) { - super(e); - } - - public AgentConfigurationException(String string) { - super(string); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/AgentReplicationException.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/AgentReplicationException.java deleted file mode 100644 index 57537454acc..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/AgentReplicationException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent; - -/** - * Represents errors happened while {@link ReplicationAgent}s do replications. - */ -@SuppressWarnings("serial") -public class AgentReplicationException extends Exception { - - public AgentReplicationException(Exception e) { - super(e); - } - - public AgentReplicationException(String string) { - super(string); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgent.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgent.java deleted file mode 100644 index 98034e3b5e1..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgent.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent; - -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.communication.ReplicationResponse; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueException; -import org.apache.sling.replication.serialization.ReplicationPackage; - -/** - * A replication agent is responsible for delivering content to another instance - */ -public interface ReplicationAgent { - - /** - * get agent name - * - * @return the agent name as a String - */ - String getName(); - - /** - * get the agent queue with the given name - * - * @param name a queue name as a String - * @return a {@link ReplicationQueue} with the given name bound to this agent, if it exists, null otherwise - * @throws ReplicationQueueException - */ - ReplicationQueue getQueue(String name) throws ReplicationQueueException; - - /** - * Synchronously sends a {@link ReplicationRequest} waiting for a {@link ReplicationResponse} - * - * @param replicationRequest the replication request - * @return a {@link ReplicationResponse} - * @throws AgentReplicationException - */ - ReplicationResponse execute(ReplicationRequest replicationRequest) throws AgentReplicationException; - - /** - * Asynchronously sends a {@link ReplicationRequest} without waiting for any response - * - * @param replicationRequest the replication request - * @throws AgentReplicationException - */ - void send(ReplicationRequest replicationRequest) throws AgentReplicationException; - - /** - * removes a package from the top of the queue - * @param queueName - * the name of a {@link ReplicationQueue} bound to this agent - * @return the ReplicationPackage popped from the underlying ReplicationQueue - * @throws ReplicationQueueException - */ - ReplicationPackage removeHead(String queueName) throws ReplicationQueueException; - - /** - * enables the current {@link ReplicationAgent} - */ - void enable(); - - /** - * disables the current {@link ReplicationAgent} - */ - void disable(); -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgentConfiguration.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgentConfiguration.java deleted file mode 100644 index d99a38f3f4f..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgentConfiguration.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent; - -import java.util.Arrays; -import java.util.Dictionary; -import java.util.Enumeration; -import org.apache.sling.commons.osgi.PropertiesUtil; - -/** - * configuration for {@link ReplicationAgent}s - */ -public class ReplicationAgentConfiguration { - - public static final String TRANSPORT = "TransportHandler.target"; - - public static final String TRANSPORT_AUTHENTICATION_FACTORY = "TransportAuthenticationProviderFactory.target"; - - public static final String QUEUEPROVIDER = "ReplicationQueueProvider.target"; - - public static final String PACKAGING = "ReplicationPackageBuilder.target"; - - public static final String NAME = "name"; - - public static final String ENDPOINT = "endpoints"; - - public static final String ENDPOINT_STRATEGY = "endpoints.strategy"; - - public static final String AUTHENTICATION_PROPERTIES = "authentication.properties"; - - public static final String QUEUE_DISTRIBUTION = "ReplicationQueueDistributionStrategy.target"; - public static final String RULES = "rules"; - - public static final String ENABLED = "enabled"; - - public static final String USE_AGGREGATE_PATHS = "useAggregatePaths"; - - public static final String[] COMPONENTS = {TRANSPORT, PACKAGING}; - - public static final String RUNMODES = "runModes"; - - private final boolean enabled; - - private final String name; - - private final String endpoint; - - private final String targetTransportHandler; - - private final String targetReplicationPackageBuilder; - - private final String targetReplicationQueueProvider; - - private final String targetReplicationQueueDistributionStrategy; - - private final String targetAuthenticationHandlerFactory; - - private final String[] authenticationProperties; - - private final String[] rules; - - private final boolean useAggregatePaths; - - private final String[] runModes; - - private final Dictionary componentConfiguration; - - public ReplicationAgentConfiguration(Dictionary dictionary, Dictionary componentConfiguration) { - this.name = PropertiesUtil.toString(dictionary.get(NAME), ""); - this.enabled = PropertiesUtil.toBoolean(dictionary.get(ENABLED), true); - this.endpoint = PropertiesUtil.toString(dictionary.get(ENDPOINT), ""); - this.targetAuthenticationHandlerFactory = PropertiesUtil.toString( - dictionary.get(TRANSPORT_AUTHENTICATION_FACTORY), ""); - this.targetReplicationPackageBuilder = PropertiesUtil.toString(dictionary.get(PACKAGING), ""); - this.targetReplicationQueueProvider = PropertiesUtil.toString( - dictionary.get(QUEUEPROVIDER), ""); - this.targetReplicationQueueDistributionStrategy = PropertiesUtil.toString(dictionary.get(QUEUE_DISTRIBUTION), ""); - this.targetTransportHandler = PropertiesUtil.toString(dictionary.get(TRANSPORT), ""); - String[] ap = PropertiesUtil.toStringArray(dictionary.get(AUTHENTICATION_PROPERTIES)); - this.authenticationProperties = ap != null ? ap : new String[0]; - this.rules = PropertiesUtil.toStringArray(dictionary.get(RULES), new String[0]); - this.useAggregatePaths = PropertiesUtil.toBoolean(dictionary.get(USE_AGGREGATE_PATHS), true); - this.runModes = PropertiesUtil.toStringArray(dictionary.get(RUNMODES), new String[0]); - - this.componentConfiguration = componentConfiguration; - } - - - public String[] getAuthenticationProperties() { - return authenticationProperties; - } - - public String getEndpoint() { - return endpoint; - } - - public String getName() { - return name; - } - - public String[] getRules() { return rules; } - - public String getTargetAuthenticationHandlerFactory() { - return targetAuthenticationHandlerFactory; - } - - public String getTargetReplicationPackageBuilder() { - return targetReplicationPackageBuilder; - } - - public String getTargetReplicationQueueProvider() { - return targetReplicationQueueProvider; - } - - public String getTargetTransportHandler() { - return targetTransportHandler; - } - - public String getTargetReplicationQueueDistributionStrategy() { - return targetReplicationQueueDistributionStrategy; - } - - public String[] getRunModes() { return runModes; } - - @Override - public String toString() { - String result = "{\""; - - result += NAME + "\":\"" + name + "\", \"" - + ENDPOINT + "\":\"" + endpoint + "\", \"" - + TRANSPORT + "\":\"" + targetTransportHandler + "\", \"" - + PACKAGING + "\":\"" + targetReplicationPackageBuilder + "\", \"" - + QUEUEPROVIDER + "\":\"" + targetReplicationQueueProvider + "\", \"" - + QUEUE_DISTRIBUTION + "\":\"" + targetReplicationQueueDistributionStrategy + "\", \"" - + TRANSPORT_AUTHENTICATION_FACTORY + "\":\"" + targetAuthenticationHandlerFactory + "\", \"" - + USE_AGGREGATE_PATHS + "\":\"" + useAggregatePaths + "\", \"" - + AUTHENTICATION_PROPERTIES + "\":\"" + Arrays.toString(authenticationProperties) + "\", \""; - - result += toComponentString(); - - result += RULES + "\":\"" + Arrays.toString(rules); - result += RUNMODES +"\":\"" + Arrays.toString(runModes); - result += "\"}"; - return result; - } - - - private String toComponentString() { - - String result = ""; - - if (componentConfiguration == null) - return result; - - for (String component : COMPONENTS) { - Dictionary properties = componentConfiguration.get(component); - if (properties == null) continue; - - Enumeration keys = properties.keys(); - - while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - Object value = properties.get(key); - - if (key.equals("service.pid")) continue; - - result += component + "." + key + "\":\"" + PropertiesUtil.toString(value, "") + "\", \""; - } - } - - return result; - } - - public String toSimpleString() { - return "{\"" + NAME + "\": \"" + name + "\"" - + ", \"" + ENABLED + "\": " + enabled + "}"; - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgentConfigurationManager.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgentConfigurationManager.java deleted file mode 100644 index 94a7cd35af7..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgentConfigurationManager.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent; - -import java.util.Map; - -/** - * Facade class for dealing with {@link ReplicationAgent}s' {@link ReplicationAgentConfiguration}s - */ -public interface ReplicationAgentConfigurationManager { - - /** - * retrieve a {@link ReplicationAgentConfiguration} for a given {@link ReplicationAgent} - * - * @param agentName the name of a {@link org.apache.sling.replication.agent.ReplicationAgent} - * @return a {@link ReplicationAgentConfiguration} for the given agent - * @throws AgentConfigurationException - */ - ReplicationAgentConfiguration getConfiguration(String agentName) - throws AgentConfigurationException; - - /** - * updates the {@link ReplicationAgentConfiguration} of a certain {@link ReplicationAgent} - * - * @param agentName the name of a {@link org.apache.sling.replication.agent.ReplicationAgent} - * @param properties a {@link java.util.Map} of properties used to update the configuration - * @return the updated {@link ReplicationAgentConfiguration} for the given agent - * @throws AgentConfigurationException - */ - ReplicationAgentConfiguration updateConfiguration(String agentName, Map properties) - throws AgentConfigurationException; - - /** - * creates a configuration for a {@link ReplicationAgent} - * - * - * @param agentName name of the agent - * @param properties the configuration of the agent to create - * @throws AgentConfigurationException - */ - void createAgentConfiguration(String agentName, Map properties) - throws AgentConfigurationException; - - /** - * deletes a configuration for a {@link ReplicationAgent} * - * - * @param agentName name of the agent - * @throws AgentConfigurationException - */ - void deleteAgentConfiguration(String agentName) - throws AgentConfigurationException; - - /** - * lists all configurations for {@link ReplicationAgent} - * - */ - ReplicationAgentConfiguration[] listAllAgentConfigurations() - throws AgentConfigurationException; - - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgentsManager.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgentsManager.java deleted file mode 100644 index dbd048afea3..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/ReplicationAgentsManager.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent; - -import java.util.Collection; -import java.util.SortedSet; -import org.apache.sling.replication.communication.ReplicationActionType; - -/** - * A manager for {@link ReplicationAgent}s - */ -public interface ReplicationAgentsManager { - - /** - * get agents which can handle the given action on the given paths - * - * @param action a {@link ReplicationActionType} - * @param paths the paths such agents should be able to handle - * @return a {@link SortedSet} of {@link ReplicationAgent}s - */ - SortedSet getAgentsFor(ReplicationActionType action, String... paths); - - /** - * get all the agents registered and active in the system - * - * @return a Collection of {@link ReplicationAgent}s - */ - Collection getAllAvailableAgents(); -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/DefaultReplicationAgentConfigurationManager.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/DefaultReplicationAgentConfigurationManager.java deleted file mode 100644 index 12865261436..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/DefaultReplicationAgentConfigurationManager.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent.impl; - -import java.util.Arrays; -import java.util.Dictionary; -import java.util.Hashtable; -import java.util.Map; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.replication.agent.AgentConfigurationException; -import org.apache.sling.replication.agent.ReplicationAgentConfiguration; -import org.apache.sling.replication.agent.ReplicationAgentConfigurationManager; -import org.osgi.service.cm.Configuration; -import org.osgi.service.cm.ConfigurationAdmin; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Default implementation of {@link ReplicationAgentConfigurationManager} - */ -@Component(immediate = true, label = "Default Replication Agent Configuration Manager") -@Service(value = ReplicationAgentConfigurationManager.class) -public class DefaultReplicationAgentConfigurationManager implements - ReplicationAgentConfigurationManager { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Reference - private ConfigurationAdmin configAdmin; - - public ReplicationAgentConfiguration getConfiguration(String agentName) - throws AgentConfigurationException { - - log.info("retrieving configuration for agent {}", agentName); - - try { - Dictionary agentProperties = getOrSetProperties(agentName, null); - Dictionary componentProperties = getOrSetComponentProperties(agentName, null); - - log.info("configuration for agent {} found {}", agentName, agentProperties); - - return new ReplicationAgentConfiguration(agentProperties, componentProperties); - - } catch (Exception e) { - - log.error("configuration for agent {} cannot be found", agentName); - throw new AgentConfigurationException(e); - } - } - - private Dictionary getOrSetProperties(String agentName, Dictionary properties) throws Exception { - Configuration agentConfiguration = getAgentConfiguration(agentName); - - if (agentConfiguration == null) - throw new Exception("no configuration found"); - - if (properties != null) - agentConfiguration.update(properties); - return agentConfiguration.getProperties(); - } - - - private Dictionary getOrSetComponentProperties(String agentName, Dictionary properties) throws Exception { - Dictionary result = new Hashtable(); - - Configuration agentConfiguration = getAgentConfiguration(agentName); - - for (String component : ReplicationAgentConfiguration.COMPONENTS) { - Configuration componentConfiguration = getComponentConfiguration(agentConfiguration, component); - - if (componentConfiguration == null) - continue; - - if (properties != null) { - Dictionary componentProperties = properties.get(component); - if (componentProperties != null) - componentConfiguration.update(componentProperties); - } - - result.put(component, componentConfiguration.getProperties()); - } - - return result; - } - - private Configuration getAgentConfiguration(String agentName) throws Exception { - String filter = "(name=" + agentName + ")"; - return getOsgiConfiguration(filter); - } - - private Configuration getComponentConfiguration(Configuration agentConfiguration, String component) { - try { - String filter = PropertiesUtil.toString(agentConfiguration.getProperties().get(component), ""); - return getOsgiConfiguration(filter); - } catch (Exception ex) { - return null; - } - } - - private Configuration getOsgiConfiguration(String filter) throws Exception { - Configuration[] configurations = getAllOsgiConfigurations(filter); - if (configurations == null || configurations.length == 0) { - log.info("no configurations for filter {}", filter); - return null; - } else if (configurations.length == 1) { - log.info("found configuration {} for filter {}", configurations[0], filter); - return configurations[0]; - } else { - log.error("{} configurations for filter {} found", configurations.length, filter); - throw new Exception("too many configurations found"); - } - } - - private Configuration[] getAllOsgiConfigurations(String filter) throws Exception { - return configAdmin.listConfigurations(filter); - } - - public ReplicationAgentConfiguration updateConfiguration(String agentName, - Map updateProperties) throws AgentConfigurationException { - try { - - String configName = PropertiesUtil.toString(updateProperties.get("name"), ""); - - if (agentName == null || agentName.length() == 0) - throw new Exception("agent name cannot be empty"); - - if (!agentName.equals(configName)) - throw new Exception("cannot change name of a configuration"); - - Dictionary agentProperties = getOrSetProperties(agentName, null); - Dictionary componentProperties = getOrSetComponentProperties(agentName, null); - - for (Map.Entry entry : updateProperties.entrySet()) { - String key = entry.getKey(); - if (key.startsWith("X-replication-")) { - key = key.substring(0, 14); - } - - - String component = extractComponent(key); - if (component != null) { - key = key.substring(component.length() + 1); - Dictionary dictionary = componentProperties.get(component); - if (dictionary != null) - dictionary.put(key, entry.getValue()); - } else { - agentProperties.put(key, entry.getValue()); - } - } - - agentProperties = getOrSetProperties(agentName, agentProperties); - componentProperties = getOrSetComponentProperties(agentName, componentProperties); - - return new ReplicationAgentConfiguration(agentProperties, componentProperties); - - } catch (Exception e) { - log.error("configuration for agent {} was not found", agentName); - - throw new AgentConfigurationException(e); - } - } - - - String extractComponent(String string) { - for (String component : ReplicationAgentConfiguration.COMPONENTS) { - if (string.startsWith(component + ".")) - return component; - } - return null; - } - - public void createAgentConfiguration(String agentName, Map properties) throws AgentConfigurationException { - - if (agentName != null) { - try { - - Configuration configuration = getAgentConfiguration(agentName); - - if (configuration != null) - throw new Exception("the agent name is already in use"); - - configuration = configAdmin.createFactoryConfiguration(ReplicationAgentServiceFactory.SERVICE_PID); - - if (configuration == null) - throw new Exception("configuration cannot be created"); - - @SuppressWarnings("unchecked") - Dictionary configurationProperties = new Hashtable(); - - for (Map.Entry entry : properties.entrySet()) { - String key = entry.getKey(); - if (key.startsWith("X-replication-")) { - key = key.substring(0, 14); - } - String value = parseString(entry.getValue()); - configurationProperties.put(key, value); - } - configuration.update(configurationProperties); - - } catch (Exception e) { - log.error("cannot create agent {} ", agentName); - - throw new AgentConfigurationException(e); - } - } else { - throw new AgentConfigurationException("a (unique) name is needed in order to create an agent"); - } - } - - - public void deleteAgentConfiguration(String agentName) throws AgentConfigurationException { - - if (agentName != null) { - try { - Configuration configuration = getAgentConfiguration(agentName); - - configuration.delete(); - } catch (Exception e) { - log.error("cannot delete agent {} ", agentName); - - throw new AgentConfigurationException(e); - } - } else { - throw new AgentConfigurationException("a (unique) name is needed in order to create an agent"); - } - } - - public ReplicationAgentConfiguration[] listAllAgentConfigurations() throws AgentConfigurationException { - try { - String filter = "(" + ConfigurationAdmin.SERVICE_FACTORYPID + "=" + ReplicationAgentServiceFactory.SERVICE_PID + ")"; - Configuration[] configurations = getAllOsgiConfigurations(filter); - - ReplicationAgentConfiguration[] result = new ReplicationAgentConfiguration[configurations.length]; - for (int i = 0; i < configurations.length; i++) { - String agentName = (String) configurations[i].getProperties().get("name"); - result[i] = getConfiguration(agentName); - } - - return result; - - } catch (Exception e) { - log.error("configurations for agents cannot be retrieved"); - throw new AgentConfigurationException(e); - } - } - - private String parseString(Object object) { - String value; - if (object instanceof String[]) { - String arrayString = Arrays.toString((String[]) object); - value = arrayString.substring(1, arrayString.length() - 1); - } else { - value = String.valueOf(object); - } - return value; - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/DefaultReplicationAgentsManager.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/DefaultReplicationAgentsManager.java deleted file mode 100644 index c6493e54d19..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/DefaultReplicationAgentsManager.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent.impl; - -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Map; -import java.util.SortedSet; -import java.util.TreeSet; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.ReferenceCardinality; -import org.apache.felix.scr.annotations.ReferencePolicy; -import org.apache.felix.scr.annotations.References; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.agent.ReplicationAgentsManager; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Default implementation of {@link ReplicationAgentsManager} - */ -@Component -@References({ - @Reference(name = "replicationAgent", - referenceInterface = ReplicationAgent.class, - cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, - policy = ReferencePolicy.DYNAMIC, - bind = "bindReplicationAgent", - unbind = "unbindReplicationAgent") -}) -@Service(value = ReplicationAgentsManager.class) -public class DefaultReplicationAgentsManager implements ReplicationAgentsManager { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final SortedSet replicationAgents = new TreeSet(new ReplicationAgentComparator()); - - public SortedSet getAgentsFor(ReplicationActionType action, String... paths) { - // TODO : implement the filtering based on rules here - return Collections.unmodifiableSortedSet(replicationAgents); - } - - public Collection getAllAvailableAgents() { - return Collections.unmodifiableCollection(replicationAgents); - } - - @Deactivate - protected void deactivate() { - replicationAgents.clear(); - } - - protected void bindReplicationAgent(final ReplicationAgent replicationAgent, - Map properties) { - synchronized (replicationAgents) { - replicationAgents.add(replicationAgent); - } - log.debug("Registering replication agent {} ", replicationAgent); - } - - protected void unbindReplicationAgent(final ReplicationAgent replicationAgent, - Map properties) { - synchronized (replicationAgents) { - replicationAgents.remove(replicationAgent); - } - log.debug("Unregistering replication agent {} ", replicationAgent); - } - - private final class ReplicationAgentComparator implements Comparator { - public int compare(ReplicationAgent o1, ReplicationAgent o2) { - return o1.getName().compareTo(o2.getName()); - } - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/ReplicationAgentServiceFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/ReplicationAgentServiceFactory.java deleted file mode 100644 index 0650ba99119..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/ReplicationAgentServiceFactory.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent.impl; - -import java.util.Dictionary; -import java.util.Hashtable; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.ConfigurationPolicy; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.ReferencePolicy; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.replication.agent.AgentConfigurationException; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.agent.ReplicationAgentConfiguration; -import org.apache.sling.replication.event.ReplicationEventFactory; -import org.apache.sling.replication.queue.ReplicationQueueDistributionStrategy; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.apache.sling.replication.queue.impl.SingleQueueDistributionStrategy; -import org.apache.sling.replication.queue.impl.jobhandling.JobHandlingReplicationQueueProvider; -import org.apache.sling.replication.rule.ReplicationRuleEngine; -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.serialization.impl.vlt.FileVaultReplicationPackageBuilder; -import org.apache.sling.replication.transport.TransportHandler; -import org.apache.sling.replication.transport.impl.NopTransportHandler; -import org.apache.sling.settings.SlingSettingsService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * An OSGi service factory for {@link ReplicationAgent}s - */ -@Component(metatype = true, - label = "Replication Agents Factory", - description = "OSGi configuration based ReplicationAgent service factory", - name = ReplicationAgentServiceFactory.SERVICE_PID, - configurationFactory = true, - specVersion = "1.1", - policy = ConfigurationPolicy.REQUIRE -) -public class ReplicationAgentServiceFactory { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - static final String SERVICE_PID = "org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory"; - - private static final String TRANSPORT = ReplicationAgentConfiguration.TRANSPORT; - - private static final String QUEUEPROVIDER = ReplicationAgentConfiguration.QUEUEPROVIDER; - - private static final String PACKAGING = ReplicationAgentConfiguration.PACKAGING; - - private static final String QUEUE_DISTRIBUTION = ReplicationAgentConfiguration.QUEUE_DISTRIBUTION; - - private static final String DEFAULT_PACKAGING = "(name=" - + FileVaultReplicationPackageBuilder.NAME + ")"; - - private static final String DEFAULT_QUEUEPROVIDER = "(name=" - + JobHandlingReplicationQueueProvider.NAME + ")"; - - private static final String DEFAULT_DISTRIBUTION = "(name=" - + SingleQueueDistributionStrategy.NAME + ")"; - - private static final String DEFAULT_TRANSPORT = "(name=" - + NopTransportHandler.NAME + ")"; - - @Property(boolValue = true, label = "Enabled") - private static final String ENABLED = ReplicationAgentConfiguration.ENABLED; - - @Property(label = "Name") - private static final String NAME = ReplicationAgentConfiguration.NAME; - - @Property(label = "Rules") - private static final String RULES = ReplicationAgentConfiguration.RULES; - - @Property(boolValue = true, label = "Replicate using aggregated paths") - private static final String USE_AGGREGATE_PATHS = ReplicationAgentConfiguration.USE_AGGREGATE_PATHS; - - @Property(label = "Target TransportHandler", name = TRANSPORT, value = "(name=" + NopTransportHandler.NAME + ")") - @Reference(name = "TransportHandler", target = "(name=" + NopTransportHandler.NAME + ")", policy = ReferencePolicy.DYNAMIC) - private TransportHandler transportHandler; - - @Property(label = "Target ReplicationPackageBuilder", name = PACKAGING, value = DEFAULT_PACKAGING) - @Reference(name = "ReplicationPackageBuilder", target = DEFAULT_PACKAGING, policy = ReferencePolicy.DYNAMIC) - private ReplicationPackageBuilder packageBuilder; - - @Property(label = "Target ReplicationQueueProvider", name = QUEUEPROVIDER, value = DEFAULT_QUEUEPROVIDER) - @Reference(name = "ReplicationQueueProvider", target = DEFAULT_QUEUEPROVIDER, policy = ReferencePolicy.DYNAMIC) - private ReplicationQueueProvider queueProvider; - - @Property(label = "Target QueueDistributionStrategy", name = QUEUE_DISTRIBUTION, value = DEFAULT_DISTRIBUTION) - @Reference(name = "ReplicationQueueDistributionStrategy", target = DEFAULT_DISTRIBUTION, policy = ReferencePolicy.DYNAMIC) - private ReplicationQueueDistributionStrategy queueDistributionStrategy; - - @Property(label = "Runmodes") - private static final String RUNMODES = ReplicationAgentConfiguration.RUNMODES; - - private ServiceRegistration agentReg; - - @Reference - private ReplicationRuleEngine replicationRuleEngine; - - @Reference - private ReplicationEventFactory replicationEventFactory; - - @Reference - private SlingSettingsService settingsService; - - @Activate - public void activate(BundleContext context, Map config) throws Exception { - - // inject configuration - Dictionary props = new Hashtable(); - - boolean enabled = PropertiesUtil.toBoolean(config.get(ENABLED), true); - - if (enabled) { - props.put(ENABLED, true); - - String[] runModes = PropertiesUtil.toStringArray(config.get(RUNMODES), new String[0]); - props.put(RUNMODES, runModes); - - String name = PropertiesUtil - .toString(config.get(NAME), String.valueOf(new Random().nextInt(1000))); - props.put(NAME, name); - - String transport = PropertiesUtil.toString(config.get(TRANSPORT), ""); - props.put(TRANSPORT, transport); - - String packaging = PropertiesUtil.toString(config.get(PACKAGING), ""); - props.put(PACKAGING, packaging); - - String queue = PropertiesUtil.toString(config.get(QUEUEPROVIDER), ""); - props.put(QUEUEPROVIDER, queue); - - String distribution = PropertiesUtil.toString(config.get(QUEUE_DISTRIBUTION), ""); - props.put(QUEUE_DISTRIBUTION, distribution); - - String[] rules = PropertiesUtil.toStringArray(config.get(RULES), new String[0]); - props.put(RULES, rules); - - - boolean useAggregatePaths = PropertiesUtil.toBoolean(config.get(USE_AGGREGATE_PATHS), true); - props.put(USE_AGGREGATE_PATHS, useAggregatePaths); - - // check configuration is valid - if (name == null || packageBuilder == null || queueProvider == null || queueDistributionStrategy == null) { - throw new AgentConfigurationException("configuration for this agent is not valid"); - } - - - if (log.isInfoEnabled()) { - log.info("bound services for {} : {} - {} - {} - {} - {} - {}", new Object[]{name, - transportHandler, packageBuilder, queueProvider, queueDistributionStrategy}); - } - - ReplicationAgent agent = new SimpleReplicationAgent(name, rules, useAggregatePaths, - transportHandler, packageBuilder, queueProvider, queueDistributionStrategy, replicationEventFactory, replicationRuleEngine); - - - // only enable if instance runmodes match configured ones - if (matchRunmodes(runModes)) { - // register agent service - agentReg = context.registerService(ReplicationAgent.class.getName(), agent, props); - agent.enable(); - } - } - } - - private boolean matchRunmodes(String[] configuredRunModes) { - boolean match = configuredRunModes == null || configuredRunModes.length == 0; - if (!match) { - Set activeRunModes = settingsService.getRunModes(); - for (String activeRunMode : activeRunModes) { - for (String configuredRunMode : configuredRunModes) { - if (activeRunMode.equals(configuredRunMode)) { - match = true; - break; - } - } - } - } - return match; - } - - @Deactivate - private void deactivate(BundleContext context) { - if (agentReg != null) { - ServiceReference reference = agentReg.getReference(); - ReplicationAgent replicationAgent = (ReplicationAgent) context.getService(reference); - replicationAgent.disable(); - agentReg.unregister(); - } - - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/SimpleReplicationAgent.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/SimpleReplicationAgent.java deleted file mode 100644 index d32cd04b90f..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/agent/impl/SimpleReplicationAgent.java +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent.impl; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Dictionary; -import java.util.List; -import java.util.Properties; -import org.apache.sling.replication.agent.AgentReplicationException; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.communication.ReplicationResponse; -import org.apache.sling.replication.event.ReplicationEventFactory; -import org.apache.sling.replication.event.ReplicationEventType; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueDistributionStrategy; -import org.apache.sling.replication.queue.ReplicationQueueException; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.apache.sling.replication.rule.ReplicationRuleEngine; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.serialization.ReplicationPackageBuildingException; -import org.apache.sling.replication.serialization.ReplicationPackageReadingException; -import org.apache.sling.replication.transport.ReplicationTransportException; -import org.apache.sling.replication.transport.TransportHandler; -import org.apache.sling.replication.transport.impl.NopTransportHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Basic implementation of a {@link ReplicationAgent} - */ -public class SimpleReplicationAgent implements ReplicationAgent { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final ReplicationPackageBuilder packageBuilder; - - private final ReplicationQueueProvider queueProvider; - - private final TransportHandler transportHandler; - - private final ReplicationQueueDistributionStrategy queueDistributionStrategy; - - private final ReplicationEventFactory replicationEventFactory; - - private final String name; - - private final String[] rules; - - private final boolean useAggregatePaths; - - private final ReplicationRuleEngine ruleEngine; - - private final String RESPONSE_QUEUE = "response"; - - public SimpleReplicationAgent(String name, String[] rules, - boolean useAggregatePaths, - TransportHandler transportHandler, - ReplicationPackageBuilder packageBuilder, - ReplicationQueueProvider queueProvider, - ReplicationQueueDistributionStrategy queueDistributionHandler, - ReplicationEventFactory replicationEventFactory, ReplicationRuleEngine ruleEngine) { - this.name = name; - this.rules = rules; - this.transportHandler = transportHandler; - this.packageBuilder = packageBuilder; - this.queueProvider = queueProvider; - this.queueDistributionStrategy = queueDistributionHandler; - this.useAggregatePaths = useAggregatePaths; - this.replicationEventFactory = replicationEventFactory; - this.ruleEngine = ruleEngine; - } - - public ReplicationResponse execute(ReplicationRequest replicationRequest) - throws AgentReplicationException { - - // create packages from request - ReplicationPackage[] replicationPackages = buildPackages(replicationRequest); - - return schedule(replicationPackages, false); - } - - public void send(ReplicationRequest replicationRequest) throws AgentReplicationException { - // create packages from request - ReplicationPackage[] replicationPackages = buildPackages(replicationRequest); - - schedule(replicationPackages, true); - } - - public boolean isPassive() { - return transportHandler == null || transportHandler instanceof NopTransportHandler; // TODO : improve this - } - - - private ReplicationPackage buildPackage(ReplicationRequest replicationRequest) throws AgentReplicationException { - // create package from request - ReplicationPackage replicationPackage; - try { - replicationPackage = packageBuilder.createPackage(replicationRequest); - } catch (ReplicationPackageBuildingException e) { - throw new AgentReplicationException(e); - } - - return replicationPackage; - } - - private ReplicationPackage[] buildPackages(ReplicationRequest replicationRequest) throws AgentReplicationException { - - List packages = new ArrayList(); - - if (useAggregatePaths) { - ReplicationPackage replicationPackage = buildPackage(replicationRequest); - packages.add(replicationPackage); - } else { - for (String path : replicationRequest.getPaths()) { - ReplicationPackage replicationPackage = buildPackage(new ReplicationRequest(replicationRequest.getTime(), - replicationRequest.getAction(), - path)); - - packages.add(replicationPackage); - } - } - - return packages.toArray(new ReplicationPackage[packages.size()]); - } - - // offer option throws an exception at first error - private ReplicationResponse schedule(ReplicationPackage[] packages, boolean offer) throws AgentReplicationException { - ReplicationResponse replicationResponse = new ReplicationResponse(); - - for (ReplicationPackage replicationPackage : packages) { - ReplicationResponse currentReplicationResponse = schedule(replicationPackage, offer); - - replicationResponse.setSuccessful(currentReplicationResponse.isSuccessful()); - replicationResponse.setStatus(currentReplicationResponse.getStatus()); - } - - return replicationResponse; - } - - private ReplicationResponse schedule(ReplicationPackage replicationPackage, boolean offer) throws AgentReplicationException { - ReplicationResponse replicationResponse = new ReplicationResponse(); - ReplicationQueueItem replicationQueueItem = new ReplicationQueueItem(replicationPackage.getId(), - replicationPackage.getPaths(), - replicationPackage.getAction(), - replicationPackage.getType()); - - if (offer) { - try { - queueDistributionStrategy.offer(getName(), replicationQueueItem, queueProvider); - if (isPassive()) { - generatePackageQueuedEvent(replicationQueueItem); - } - } catch (ReplicationQueueException e) { - replicationResponse.setSuccessful(false); - throw new AgentReplicationException(e); - } - } else { - // send the replication package to the queue distribution handler - try { - ReplicationQueueItemState state = queueDistributionStrategy.add(getName(), replicationQueueItem, - queueProvider); - if (isPassive()) { - generatePackageQueuedEvent(replicationQueueItem); - } - if (state != null) { - replicationResponse.setStatus(state.getItemState().toString()); - replicationResponse.setSuccessful(state.isSuccessful()); - } else { - replicationResponse.setStatus(ReplicationQueueItemState.ItemState.ERROR.toString()); - replicationResponse.setSuccessful(false); - } - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("an error happened during queue processing", e); - } - replicationResponse.setSuccessful(false); - } - } - return replicationResponse; - } - - private void generatePackageQueuedEvent(ReplicationQueueItem replicationQueueItem) { - Dictionary properties = new Properties(); - properties.put("replication.package.paths", replicationQueueItem.getPaths()); - properties.put("replication.agent.name", name); - replicationEventFactory.generateEvent(ReplicationEventType.PACKAGE_QUEUED, properties); - } - - public ReplicationPackage removeHead(String queueName) throws ReplicationQueueException { - ReplicationPackage replicationPackage = null; - if (isPassive()) { - ReplicationQueue queue = getQueue(queueName); - ReplicationQueueItem info = queue.getHead(); - if (info != null) { - queue.removeHead(); - replicationPackage = packageBuilder.getPackage(info.getId()); - } - return replicationPackage; - } else { - throw new ReplicationQueueException("cannot explicitly fetch items from not-passive agents"); - } - } - - public String getName() { - return name; - } - - public ReplicationQueue getQueue(String name) throws ReplicationQueueException { - ReplicationQueue queue; - if (name != null && name.length() > 0) { - queue = queueProvider.getQueue(getName(), name); - } else { - queue = queueProvider.getDefaultQueue(getName()); - } - return queue; - } - - - public void enable() { - log.info("enabling agent"); - // apply rules if any - if (rules.length > 0) { - ruleEngine.applyRules(this, rules); - } - - if (!isPassive()) { - queueProvider.enableQueueProcessing(getName(), new PackageQueueProcessor()); - transportHandler.enableProcessing(getName(), new ResponseProcessor()); - } - } - - public void disable() { - log.info("disabling agent"); - if (rules != null) { - ruleEngine.unapplyRules(this, rules); - } - - if (!isPassive()) { - queueProvider.disableQueueProcessing(getName()); - transportHandler.disableProcessing(getName()); - } - } - - private boolean processResponseQueue(ReplicationQueueItem queueItem) { - InputStream stream = new ByteArrayInputStream(queueItem.getBytes()); - log.debug("reading package from stream {}", stream); - try { - ReplicationPackage replicationPackage = packageBuilder.readPackage(stream, true); - replicationPackage.delete(); - return true; - } catch (ReplicationPackageReadingException e) { - return false; - } - } - - private boolean processTransportQueue(ReplicationQueueItem queueItem) { - try { - ReplicationPackage replicationPackage = packageBuilder.getPackage(queueItem.getId()); - if (replicationPackage == null) { - return false; - } - if (transportHandler != null) { - transportHandler.transport(getName(), replicationPackage); - replicationPackage.delete(); - return true; - } else { - log.info("agent {} processing skipped", name); - return false; - } - } catch (ReplicationTransportException e) { - log.error("transport error", e); - return false; - } - } - - class PackageQueueProcessor implements ReplicationQueueProcessor { - public boolean process(String queueName, ReplicationQueueItem packageInfo) { - log.info("running package queue processor"); - if (RESPONSE_QUEUE.equalsIgnoreCase(queueName)) { - return processResponseQueue(packageInfo); - } else { - return processTransportQueue(packageInfo); - } - } - } - - class ResponseProcessor implements ReplicationQueueProcessor { - public boolean process(String queueName, ReplicationQueueItem queueItem) { - log.info("running response processor"); - try { - return getQueue(RESPONSE_QUEUE).add(queueItem); - } catch (Exception e) { - return false; - } - } - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationActionType.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationActionType.java deleted file mode 100644 index ffe4cfb72fb..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationActionType.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.communication; - -/** - * The type of a specific replication action, used to decide what to do with specific replication - * items / requests. - */ -public enum ReplicationActionType { - - /** - * Content is added - */ - ADD("Add"), - - /** - * Content is deleted - */ - DELETE("Delete"), - - /** - * Content is polled - */ - POLL("Poll"); - - /** - * internal human readable name - */ - private final String name; - - /** - * Create a type - * - * @param name - * name - */ - private ReplicationActionType(String name) { - this.name = name; - } - - /** - * Returns the human readable type name of this type. - * - * @return the name - */ - public String getName() { - return name; - } - - /** - * Creates an action type for the given name. if the name cannot be mapped to a enum type or if - * it's null, null is returned. - * - * @param n - * the name - * @return the type or null - */ - public static ReplicationActionType fromName(String n) { - if (n == null) { - return null; - } - try { - return ReplicationActionType.valueOf(n.toUpperCase()); - } catch (IllegalArgumentException e) { - return null; - } - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationAgentHistory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationAgentHistory.java deleted file mode 100644 index ff36d24b4e2..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationAgentHistory.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.communication; - -import java.util.SortedMap; - -/** - * The communication history for a certain agent - */ -public interface ReplicationAgentHistory { - - SortedMap getCommunication(); - - ReplicationResponse getResponseFor(ReplicationRequest request); - - ReplicationResponse getResponseFor(String requestId); -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationEndpoint.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationEndpoint.java deleted file mode 100644 index 6b7a09f4571..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationEndpoint.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.communication; - -import java.net.URI; - -/** - * A replication endpoint - */ -public class ReplicationEndpoint { - - private final URI uri; - - public ReplicationEndpoint(URI uri) { - this.uri = uri; - } - - public ReplicationEndpoint(String uriString) { - this.uri = URI.create(uriString); - } - - public URI getUri() { - return uri; - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationHeader.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationHeader.java deleted file mode 100644 index 7e78d0f0037..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationHeader.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.communication; - -/** - * HTTP headers {@link Enum} for replication - */ -public enum ReplicationHeader { - - TYPE("X-replication-type"), - ACTION("X-replication-action"), - PATH("X-replication-path"); - - private final String name; - - ReplicationHeader(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationParameter.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationParameter.java deleted file mode 100644 index 8a115a622b2..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationParameter.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.communication; - -/** - * HTTP Parameters for replication - */ -public enum ReplicationParameter { - - QUEUE("queue"); - - private final String name; - - ReplicationParameter(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationRequest.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationRequest.java deleted file mode 100644 index 275c695bde8..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationRequest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.communication; - -/** - * A replication request - */ -public class ReplicationRequest { - - private final long time; - - private final ReplicationActionType action; - - private final String[] paths; - - public ReplicationRequest(long time, ReplicationActionType action, String... paths) { - this.time = time; - this.action = action; - this.paths = paths; - } - - public long getTime() { - return time; - } - - public ReplicationActionType getAction() { - return action; - } - - public String[] getPaths() { - return paths; - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationResponse.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationResponse.java deleted file mode 100644 index 95c8e4d5dca..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/communication/ReplicationResponse.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.communication; - -/** - * A replication response - */ -public class ReplicationResponse { - private boolean successful; - - private String status; - - public boolean isSuccessful() { - return successful; - } - - public void setSuccessful(boolean successful) { - this.successful = successful; - } - - @Override - public String toString() { - return "{\"success\":" + successful + ", \"status\":\"" + status + "\"}"; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/ReplicationEvent.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/ReplicationEvent.java deleted file mode 100644 index 201d8f311d6..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/ReplicationEvent.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.event; - -import java.util.Dictionary; -import org.osgi.service.event.Event; - -/** - * A replication related event - */ -public class ReplicationEvent extends Event { - - public static final String EVENT_TOPIC = "org/apache/sling/replication/event"; - - public ReplicationEvent(ReplicationEventType type, Dictionary properties) { - super(getTopic(type), properties); - } - - public static String getTopic(ReplicationEventType type) { - return EVENT_TOPIC + '/' + type.toString(); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/ReplicationEventFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/ReplicationEventFactory.java deleted file mode 100644 index 91f53d96c6b..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/ReplicationEventFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.event; - -import java.util.Dictionary; - -/** - * generate replication related events - */ -public interface ReplicationEventFactory { - - /** - * generate a replication event - * @param replicationEventType the type of event to be generated - * @param properties a dictionary of properties to be attached to the event - */ - void generateEvent(ReplicationEventType replicationEventType, Dictionary properties); -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/ReplicationEventType.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/ReplicationEventType.java deleted file mode 100644 index c5565363578..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/ReplicationEventType.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.event; - -/** - * an enum of the possible types of events related to replication - */ -public enum ReplicationEventType { - - PACKAGE_CREATED, - PACKAGE_QUEUED, - PACKAGE_DELETED, - PACKAGE_REPLICATED, - PACKAGE_INSTALLED, - AGENT_CREATED, - AGENT_MODIFIED, - AGENT_DELETED - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/impl/DefaultReplicationEventFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/impl/DefaultReplicationEventFactory.java deleted file mode 100644 index b231ae87c5c..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/event/impl/DefaultReplicationEventFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.event.impl; - -import java.util.Dictionary; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.replication.event.ReplicationEvent; -import org.apache.sling.replication.event.ReplicationEventFactory; -import org.apache.sling.replication.event.ReplicationEventType; -import org.osgi.service.event.EventAdmin; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * {@link ReplicationEventFactory} OSGi service - */ -@Component(immediate = true, label = "Event Factory for Replication Events") -@Service(value = ReplicationEventFactory.class) -public class DefaultReplicationEventFactory implements ReplicationEventFactory { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Reference - private EventAdmin eventAdmin; - - public void generateEvent(ReplicationEventType replicationEventType, Dictionary properties) { - ReplicationEvent replicationEvent = new ReplicationEvent(replicationEventType, properties); - eventAdmin.postEvent(replicationEvent); - if (log.isDebugEnabled()) { - log.debug("replication event posted {}", replicationEvent); - } - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/monitor/ReplicationQueueHealthCheck.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/monitor/ReplicationQueueHealthCheck.java deleted file mode 100644 index f19088e1757..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/monitor/ReplicationQueueHealthCheck.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.monitor; - -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Properties; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.PropertyUnbounded; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.ReferenceCardinality; -import org.apache.felix.scr.annotations.ReferencePolicy; -import org.apache.felix.scr.annotations.References; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.hc.api.HealthCheck; -import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.util.FormattingResultLog; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * {@link HealthCheck} that checks if replication queues' first item has been retried more than a configurable amount - * of times - */ -@Component(immediate = true, - metatype = true, - label = "Apache Sling Replication Queue Health Check") -@Properties({ - @Property(name = HealthCheck.NAME, value = "SlingReplicationQueueHC", description = "Health Check name", label = "Name"), - @Property(name = HealthCheck.TAGS, unbounded = PropertyUnbounded.ARRAY, description = "Health Check tags", label = "Tags"), - @Property(name = HealthCheck.MBEAN_NAME, value = "slingReplicationQueue", description = "Health Check MBean name", label = "MBean name") -}) -@References({ - @Reference(name = "replicationQueueProvider", - referenceInterface = ReplicationQueueProvider.class, - cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, - policy = ReferencePolicy.DYNAMIC, - bind = "bindReplicationQueueProvider", - unbind = "unbindReplicationQueueProvider") -}) - -@Service(value = HealthCheck.class) -public class ReplicationQueueHealthCheck implements HealthCheck { - - private static final Logger log = LoggerFactory.getLogger(ReplicationQueueHealthCheck.class); - - private static final int DEFAULT_NUMBER_OF_RETRIES_ALLOWED = 3; - - private int numberOfRetriesAllowed; - - @Property(intValue = DEFAULT_NUMBER_OF_RETRIES_ALLOWED, description = "Number of allowed retries", label = "Allowed retries") - private static final String NUMBER_OF_RETRIES_ALLOWED = "numberOfRetriesAllowed"; - - private final Collection replicationQueueProviders = new LinkedList(); - - @Activate - public void activate(final Map properties) { - numberOfRetriesAllowed = PropertiesUtil.toInteger(properties.get(NUMBER_OF_RETRIES_ALLOWED), DEFAULT_NUMBER_OF_RETRIES_ALLOWED); - log.info("Activated, numberOfRetriesAllowed={}", numberOfRetriesAllowed); - } - - @Deactivate - protected void deactivate() { - replicationQueueProviders.clear(); - } - - protected void bindReplicationQueueProvider(final ReplicationQueueProvider replicationQueueProvider) { - synchronized (replicationQueueProviders) { - replicationQueueProviders.add(replicationQueueProvider); - } - log.debug("Registering replication queue provider {} ", replicationQueueProvider); - } - - protected void unbindReplicationQueueProvider(final ReplicationQueueProvider replicationQueueProvider) { - synchronized (replicationQueueProviders) { - replicationQueueProviders.remove(replicationQueueProvider); - } - log.debug("Unregistering replication queue provider {} ", replicationQueueProvider); - } - - public Result execute() { - final FormattingResultLog resultLog = new FormattingResultLog(); - Map failures = new HashMap(); - if (replicationQueueProviders.size() > 0) { - - for (ReplicationQueueProvider replicationQueueProvider : replicationQueueProviders) { - for (ReplicationQueue q : replicationQueueProvider.getAllQueues()) - try { - ReplicationQueueItem item = q.getHead(); - if (item != null) { - ReplicationQueueItemState status = q.getStatus(item); - if (status.getAttempts() <= numberOfRetriesAllowed) { - resultLog.debug("Queue: [{}], first item: [{}], number of retries: {}", q.getName(), item.getId(), status.getAttempts()); - } else { - // the no. of attempts is higher than the configured threshold - resultLog.warn("Queue: [{}], first item: [{}], number of retries: {}, expected number of retries <= {}", - q.getName(), item.getId(), status.getAttempts(), numberOfRetriesAllowed); - failures.put(q.getName(), status.getAttempts()); - } - } else { - resultLog.debug("No items in queue [{}]", q.getName()); - } - - } catch (Exception e) { - resultLog.warn("Exception while inspecting replication queue [{}]: {}", q.getName(), e); - } - } - } else { - resultLog.debug("No replication queue providers found"); - } - - if (failures.size() > 0) { - // a specific log entry (using markdown) to provide a recommended user action - for (Map.Entry entry : failures.entrySet()) { - resultLog.warn("Replication queue {}'s first item in the default queue has been retried {} times (threshold: {})", - entry.getKey(), entry.getValue(), numberOfRetriesAllowed); - } - } - - return new Result(resultLog); - } - -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueue.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueue.java deleted file mode 100644 index f2405386b4c..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueue.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue; - -import java.util.Collection; - -/** - * a queue for handling {@link org.apache.sling.replication.agent.ReplicationAgent}s' requests - */ -public interface ReplicationQueue { - - /** - * get this queue name - * - * @return queue name as a String - */ - String getName(); - - /** - * add a replication package to this queue - * - * - * @param replicationPackage a replication package to replicate - * @return true if the replication package was added correctly to the queue, - * falsetrue if the queue is empty, false otherwise - */ - boolean isEmpty(); - - /** - * get the items in the queue - * - * @return a Collection of {@link org.apache.sling.replication.serialization.ReplicationPackage}s - */ - Collection getItems(); - - /** - * remove an item from the queue by specifying its id - * @param id String representing an item's identifier - */ - void remove(String id); -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueDistributionStrategy.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueDistributionStrategy.java deleted file mode 100644 index aac0f91ab35..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueDistributionStrategy.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue; - -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.serialization.ReplicationPackage; - -/** - * a {@link ReplicationQueueDistributionStrategy} implements an algorithm for the distribution of - * replication packages among the available queues for a certain agent - */ -public interface ReplicationQueueDistributionStrategy { - - /** - * synchronously distribute a {@link ReplicationPackage} to a {@link ReplicationAgent} to a {@link ReplicationQueue} - * provided by the given {@link ReplicationQueueProvider} - * - * @param agentName the name of a {@link ReplicationAgent} - * @param replicationPackage a {@link org.apache.sling.replication.serialization.ReplicationPackage} to distribute - * @param queueProvider the {@link ReplicationQueueProvider} used to provide the queue to be used for the given package - * @return a {@link ReplicationQueueItemState} representing the state of the package in the queue after its distribution - * @throws ReplicationQueueException - */ - ReplicationQueueItemState add(String agentName, ReplicationQueueItem replicationPackage, - ReplicationQueueProvider queueProvider) throws ReplicationQueueException; - - /** - * asynchronously distribute a {@link ReplicationPackage} to a {@link ReplicationAgent} to a {@link ReplicationQueue} - * provided by the given {@link ReplicationQueueProvider} - * - * @param agentName the name of a {@link ReplicationAgent} - * @param replicationPackage a {@link org.apache.sling.replication.serialization.ReplicationPackage} to distribute - * @param queueProvider the {@link ReplicationQueueProvider} used to provide the queue to be used for the given package - * @return true if the package could be distributed to a {@link ReplicationQueue}, false otherwise - * @throws ReplicationQueueException - */ - boolean offer(String agentName, ReplicationQueueItem replicationPackage, - ReplicationQueueProvider queueProvider) throws ReplicationQueueException; - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueException.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueException.java deleted file mode 100644 index f766e8f8d34..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueException.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue; - -import javax.jcr.RepositoryException; - -/** - * Represents errors happening during queue operations - */ -@SuppressWarnings("serial") -public class ReplicationQueueException extends Exception { - - public ReplicationQueueException(String message, Exception e) { - super(message, e); - } - - public ReplicationQueueException(String string) { - super(string); - } - - public ReplicationQueueException(RepositoryException e) { - super(e); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueItem.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueItem.java deleted file mode 100644 index ffe9498176c..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueItem.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue; - -/** - * An item in a {@link org.apache.sling.replication.queue.ReplicationQueue} - */ -public class ReplicationQueueItem { - - private final String id; - - private final String[] paths; - - private final String action; - - private final String type; - - private final byte[] bytes; - - private ReplicationQueueItem(String id, String[] paths, String action, String type, byte[] bytes) { - this.id = id; - this.paths = paths; - this.action = action; - this.type = type; - this.bytes = bytes; - } - - public ReplicationQueueItem(String id, String[] paths, String action, String type) { - this(id, paths, action, type, null); - } - - public ReplicationQueueItem(String[] paths, String action, String type, byte[] bytes) { - this(null, paths, action, type, bytes); - } - - public String getId() { - return id; - } - - public String[] getPaths() { - return paths; - } - - public String getAction() { - return action; - } - - public String getType() { - return type; - } - - public byte[] getBytes() { - return bytes; - } - - public boolean isTransient(){ - return id == null; - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueItemState.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueItemState.java deleted file mode 100644 index f017a1ea55a..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueItemState.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue; - -import java.util.Calendar; - -/** - * the current status of a certain item in a {@link ReplicationQueue} - */ - -public class ReplicationQueueItemState { - - private int attempts; - - private ItemState state; - - private Calendar entered; - - public boolean isSuccessful() { - return ItemState.SUCCEEDED.equals(state); - } - - public void setSuccessful(boolean successful) { - state = successful ? ItemState.SUCCEEDED : ItemState.ERROR; - } - - public int getAttempts() { - return attempts; - } - - public void setAttempts(int attempts) { - this.attempts = attempts; - } - - public ItemState getItemState() { - return state; - } - - public void setItemState(ItemState status) { - this.state = status; - } - - @Override - public String toString() { - return "{\"attempts\":\"" + attempts + "\",\"" + "successful\":\"" + isSuccessful() + "\",\"" + "state\":\"" + state + "\"}"; - } - - public Calendar getEntered() { - return entered; - } - - public void setEntered(Calendar entered) { - this.entered = entered; - } - - public enum ItemState { - QUEUED, // waiting in queue after adding or for restart after failing - ACTIVE, // job is currently in processing - SUCCEEDED, // processing finished successfully - STOPPED, // processing was stopped by a user - GIVEN_UP, // number of retries reached - ERROR, // processing signaled CANCELLED or throw an exception - DROPPED // dropped jobs - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueProcessor.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueProcessor.java deleted file mode 100644 index 4ea0e13b72a..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueProcessor.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue; - -/** - * Processor of {@link org.apache.sling.replication.queue.ReplicationQueueItem}s - */ -public interface ReplicationQueueProcessor { - - /** - * Process an item from a certain ReplicationQueue - * - * @param queueName the name of the ReplicationQueue to be processed - * @param replicationQueueItem the ReplicationQueueItem to be processed - * @return true if the item was successfully processed, false otherwise - */ - public boolean process(String queueName, ReplicationQueueItem replicationQueueItem); -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueProvider.java deleted file mode 100644 index 141ebe66e40..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/ReplicationQueueProvider.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue; - -import java.util.Collection; - -/** - * A provider for {@link ReplicationQueue}s - */ -public interface ReplicationQueueProvider { - - /** - * provide the queue to be used for a certain agent and package or creates it if it doesn't - * exist - * - * - * @param agentName - * the replication agent needing the queue - * @param name - * the name of the queue to retrieve - * @return a replication queue to be used for the given parameters - * @throws ReplicationQueueException - */ - ReplicationQueue getQueue(String agentName, String name) - throws ReplicationQueueException; - - - /** - * get the default queue to be used for a certain agent - * - * - * @param agentName - * a replication agent - * @return the default replication queue for the given agent - * @throws ReplicationQueueException - */ - ReplicationQueue getDefaultQueue(String agentName) - throws ReplicationQueueException; - - /** - * get all the available queues from this provider - * - * @return a collection of replication queues - */ - Collection getAllQueues(); - - /** - * removes an existing queue owned by this provider - * - * @param queue - * a replication queue to be removed - * @throws ReplicationQueueException - */ - void removeQueue(ReplicationQueue queue) throws ReplicationQueueException; - - /** - * enables queue driven processing for an agent. - * @param agentName - * a replication agent - * @param queueProcessor the queue processor to be used - */ - void enableQueueProcessing(String agentName, ReplicationQueueProcessor queueProcessor); - - - /** - * disables queue driven processing for an agent - * @param agentName - * a replication agent - */ - void disableQueueProcessing(String agentName); -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/AbstractReplicationQueueProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/AbstractReplicationQueueProvider.java deleted file mode 100644 index 546207ee1ec..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/AbstractReplicationQueueProvider.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl; - -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueException; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * abstract base implementation of a {@link ReplicationQueueProvider} - */ -public abstract class AbstractReplicationQueueProvider implements ReplicationQueueProvider { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final Map queueMap = new ConcurrentHashMap(); - - public ReplicationQueue getQueue(String agentName, String queueName) - throws ReplicationQueueException { - String key = agentName + queueName; - - ReplicationQueue queue = queueMap.get(key); - if (queue == null) { - log.info("creating a queue with key {}", key); - queue = getOrCreateQueue(agentName, queueName); - queueMap.put(key, queue); - log.info("queue created {}", queue); - } - return queue; - } - - public ReplicationQueue getDefaultQueue(String agentName) - throws ReplicationQueueException { - return getQueue(agentName, ""); - } - - public Collection getAllQueues() { - return queueMap.values(); - } - - public void removeQueue(ReplicationQueue queue) throws ReplicationQueueException { - deleteQueue(queue); - // flush cache - if (queueMap.containsValue(queue)) { - if (!queueMap.values().remove(queue)) { - throw new ReplicationQueueException("could not remove the queue " + queue); - } - } - } - - protected abstract ReplicationQueue getOrCreateQueue(String agentName, String queueName) throws ReplicationQueueException; - - protected abstract void deleteQueue(ReplicationQueue queue); - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/ErrorAwareQueueDistributionStrategy.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/ErrorAwareQueueDistributionStrategy.java deleted file mode 100644 index 48042057c85..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/ErrorAwareQueueDistributionStrategy.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl; - -import java.util.Calendar; -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.PropertyOption; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueDistributionStrategy; -import org.apache.sling.replication.queue.ReplicationQueueException; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueItemState.ItemState; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.osgi.service.component.ComponentContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The error strategy for delivering packages to queues. Each agent manages a single queue for - * delivering packages with an error queue which can be used when an item is stuck in the default - * queue for too much time, then the stuck item is moved to the error queue or dropped. - */ -@Component(immediate = true, metatype = true, label = "Error Aware Queue Distribution Strategy") -@Service(value = ReplicationQueueDistributionStrategy.class) -@Property(name = "name", value = ErrorAwareQueueDistributionStrategy.NAME, propertyPrivate = true) -public class ErrorAwareQueueDistributionStrategy implements ReplicationQueueDistributionStrategy { - - private static final String ERROR = "ERROR"; - - public static final String NAME = "error"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Property(intValue = 100, label = "no. of maximum queue item processing attempts") - private static final String ATTEMPTS_THRESHOLD = "attempts.threshold"; - - @Property(intValue = 600000, label = "no. of maximum amount of milliseconds in the queue") - private static final String TIME_THRESHOLD = "time.threshold"; - - @Property(label = "Stuck Queue Handling", options = { - @PropertyOption(name = "ERROR", value = "Error"), - @PropertyOption(name = "DROP", value = "Drop")}, value = ERROR) - private static final String STUCK_HANDLING = "stuck.handling"; - - private String stuckQueueHandling; - - private Integer attemptsThreshold; - - private Integer timeThreshold; - - @Activate - protected void activate(final ComponentContext ctx) { - stuckQueueHandling = PropertiesUtil - .toString(ctx.getProperties().get(STUCK_HANDLING), ERROR); - attemptsThreshold = PropertiesUtil.toInteger(ctx.getProperties().get(ATTEMPTS_THRESHOLD), 100); - timeThreshold = PropertiesUtil.toInteger(ctx.getProperties().get(TIME_THRESHOLD), 600000); - } - - public ReplicationQueueItemState add(String agentName, ReplicationQueueItem replicationPackage, - ReplicationQueueProvider queueProvider) - throws ReplicationQueueException { - try { - if (log.isInfoEnabled()) { - log.info("using error aware queue distribution"); - } - ReplicationQueueItemState state = new ReplicationQueueItemState(); - ReplicationQueue queue = queueProvider.getDefaultQueue(agentName); - if (log.isInfoEnabled()) { - log.info("obtained queue {}", queue); - } - if (queue != null) { - if (queue.add(replicationPackage)) { - if (log.isInfoEnabled()) { - log.info("replication status: {}", state); - } - state = queue.getStatus(replicationPackage); - } else { - if (log.isErrorEnabled()) { - log.error("could not add the item to the queue {}", queue); - } - state.setItemState(ItemState.ERROR); - state.setSuccessful(false); - } - return state; - } else { - throw new ReplicationQueueException("could not get a queue for agent " + agentName); - } - } finally { - checkAndRemoveStuckItems(agentName, queueProvider); - } - } - - public boolean offer(String agentName, ReplicationQueueItem replicationPackage, - ReplicationQueueProvider queueProvider) throws ReplicationQueueException { - boolean added; - ReplicationQueue queue = queueProvider.getDefaultQueue(agentName); - if (queue != null) { - added = queue.add(replicationPackage); - } else { - throw new ReplicationQueueException("could not get a queue for agent " + agentName); - } - checkAndRemoveStuckItems(agentName, queueProvider); - return added; - } - - private void checkAndRemoveStuckItems(String agent, - ReplicationQueueProvider queueProvider) throws ReplicationQueueException { - ReplicationQueue defaultQueue = queueProvider.getDefaultQueue(agent); - // get first item in the queue with its status - ReplicationQueueItem firstItem = defaultQueue.getHead(); - if (firstItem != null) { - ReplicationQueueItemState status = defaultQueue.getStatus(firstItem); - // if item is still in the queue after a max no. of attempts, move it to the error queue - int attempts = status.getAttempts(); - Calendar entered = status.getEntered(); - log.info("item {} entered {} was attempted {} times", new Object[]{firstItem, entered, attempts}); - if (attempts > attemptsThreshold || (entered != null && Calendar.getInstance().getTimeInMillis() - entered.getTimeInMillis() > timeThreshold)) { - if (ERROR.equals(stuckQueueHandling)) { - log.warn("item {} moved to the error queue", firstItem); - - ReplicationQueue errorQueue = queueProvider.getQueue(agent, "-error"); - if (!errorQueue.add(firstItem)) { - log.error("failed to move item {} the queue {}", firstItem, errorQueue); - throw new ReplicationQueueException("could not move an item to the error queue"); - } - } - log.warn("item {} dropped from the default queue", firstItem); - defaultQueue.removeHead(); - } - } - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/PriorityPathDistributionStrategy.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/PriorityPathDistributionStrategy.java deleted file mode 100644 index 24b15075489..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/PriorityPathDistributionStrategy.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl; - -import java.util.Arrays; - -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.replication.queue.*; -import org.osgi.service.component.ComponentContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.sling.replication.queue.ReplicationQueueItemState.ItemState; - -/** - * Distribution algorithm which keeps one specific queue to handle specific paths and another queue - * for handling all the other paths - */ -@Component(immediate = true, metatype = true, label = "Priority Path Queue Distribution Strategy") -@Service(value = ReplicationQueueDistributionStrategy.class) -@Property(name = "name", value = PriorityPathDistributionStrategy.NAME, propertyPrivate = true) -public class PriorityPathDistributionStrategy implements ReplicationQueueDistributionStrategy { - - public static final String NAME = "priority"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Property(value = { "/content" }) - private static final String PRIORITYPATHS = "priority.paths"; - - private String[] priorityPaths; - - @Activate - protected void activate(ComponentContext context) { - priorityPaths = PropertiesUtil.toStringArray(context.getProperties().get(PRIORITYPATHS)); - } - - public ReplicationQueueItemState add(String agentName, ReplicationQueueItem replicationPackage, - ReplicationQueueProvider queueProvider) - throws ReplicationQueueException { - if (log.isInfoEnabled()) { - log.info("using path priority based queue distribution"); - } - ReplicationQueueItemState state = new ReplicationQueueItemState(); - - ReplicationQueue queue = getQueue(agentName, replicationPackage, queueProvider); - if (log.isInfoEnabled()) { - log.info("obtained queue {}", queue); - } - - if (queue != null) { - if (queue.add(replicationPackage)) { - if (log.isInfoEnabled()) { - log.info("replication status: {}", state); - } - state = queue.getStatus(replicationPackage); - } else { - if (log.isErrorEnabled()) { - log.error("could not add the item to the queue {}", queue); - } - state.setItemState(ItemState.ERROR); - state.setSuccessful(false); - } - return state; - } else { - throw new ReplicationQueueException("could not get a queue for agent " + agentName); - } - - } - - private ReplicationQueue getQueue(String agentName, ReplicationQueueItem replicationPackage, - ReplicationQueueProvider queueProvider) - throws ReplicationQueueException { - String[] paths = replicationPackage.getPaths(); - - if (log.isInfoEnabled()) { - log.info("calculating priority for paths {}", Arrays.toString(paths)); - } - - boolean usePriorityQueue = false; - String pp = null; - for (String path : paths) { - for (String priorityPath : priorityPaths) { - if (path.startsWith(priorityPath)) { - usePriorityQueue = true; - pp = priorityPath; - break; - } - } - } - - ReplicationQueue queue; - if (usePriorityQueue) { - if (log.isInfoEnabled()) { - log.info("using priority queue for path {}", pp); - } - queue = queueProvider.getQueue(agentName, pp); - } else { - if (log.isInfoEnabled()) { - log.info("using default queue"); - } - queue = queueProvider.getDefaultQueue(agentName); - } - return queue; - } - - public boolean offer(String agentName, ReplicationQueueItem replicationPackage, - ReplicationQueueProvider queueProvider) throws ReplicationQueueException { - ReplicationQueue queue = getQueue(agentName, replicationPackage, queueProvider); - if (queue != null) { - return queue.add(replicationPackage); - } else { - throw new ReplicationQueueException("could not get a queue for agent " + agentName); - } - - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/SingleQueueDistributionStrategy.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/SingleQueueDistributionStrategy.java deleted file mode 100644 index dfa84a8916f..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/SingleQueueDistributionStrategy.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.replication.queue.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.sling.replication.queue.ReplicationQueueItemState.ItemState; - -/** - * The default strategy for delivering packages to queues. Each agent just manages a single queue, - * no failure / stuck handling where each package is put regardless of anything. - */ -@Component(immediate = true, label = "Single Queue Distribution Strategy") -@Service(value = ReplicationQueueDistributionStrategy.class) -@Property(name = "name", value = SingleQueueDistributionStrategy.NAME) -public class SingleQueueDistributionStrategy implements ReplicationQueueDistributionStrategy { - - public static final String NAME = "single"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - public ReplicationQueueItemState add(String agentName, ReplicationQueueItem replicationPackage, - ReplicationQueueProvider queueProvider) - throws ReplicationQueueException { - log.info("using single queue distribution"); - - ReplicationQueueItemState state = new ReplicationQueueItemState(); - ReplicationQueue queue = queueProvider.getDefaultQueue(agentName); - log.info("obtained queue {}", queue); - - if (queue != null) { - if (queue.add(replicationPackage)) { - state = queue.getStatus(replicationPackage); - log.info("replication status: {}", state); - } else { - log.error("could not add the item to the queue {}", queue); - state.setItemState(ItemState.ERROR); - state.setSuccessful(false); - } - return state; - } else { - throw new ReplicationQueueException("could not get a queue for agent " + agentName); - } - - } - - public boolean offer(String agentName, ReplicationQueueItem replicationPackage, - ReplicationQueueProvider queueProvider) throws ReplicationQueueException { - ReplicationQueue queue = queueProvider.getDefaultQueue(agentName); - if (queue != null) { - return queue.add(replicationPackage); - } else { - throw new ReplicationQueueException("could not get a queue for agent " + agentName); - } - - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingReplicationQueue.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingReplicationQueue.java deleted file mode 100644 index 75ca282c4a4..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingReplicationQueue.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl.jobhandling; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.Map; -import org.apache.sling.event.jobs.Job; -import org.apache.sling.event.jobs.JobManager; -import org.apache.sling.event.jobs.JobManager.QueryType; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueException; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueItemState.ItemState; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * a {@link ReplicationQueue} based on Sling Job Handling facilities - */ -public class JobHandlingReplicationQueue implements ReplicationQueue { - - public final static String REPLICATION_QUEUE_TOPIC = "org/apache/sling/replication/queue"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final String name; - - private final String topic; - - private final JobManager jobManager; - - protected JobHandlingReplicationQueue(String name, String topic, JobManager jobManager) { - this.name = name; - this.topic = topic; - this.jobManager = jobManager; - } - - public String getName() { - return name; - } - - public boolean add(ReplicationQueueItem replicationPackage) { - boolean result = true; - try { - Map properties = JobHandlingUtils - .createFullPropertiesFromPackage(replicationPackage); - - Job job = jobManager.createJob(topic).properties(properties).add(); - if (log.isInfoEnabled()) { - log.info("job {} added", job.getId()); - } - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("could not add an item to the queue", e); - } - result = false; - } - return result; - } - - public ReplicationQueueItemState getStatus(ReplicationQueueItem replicationPackage) - throws ReplicationQueueException { - ReplicationQueueItemState itemStatus = new ReplicationQueueItemState(); - try { - Map properties = JobHandlingUtils - .createIdPropertiesFromPackage(replicationPackage); - Job job = jobManager.getJob(topic, properties); - if (job != null) { - itemStatus.setAttempts(job.getRetryCount()); - itemStatus.setItemState(ItemState.valueOf(job.getJobState().toString())); - itemStatus.setEntered(job.getCreated()); - if (log.isInfoEnabled()) { - log.info("status of job {} is {}", job.getId(), job.getJobState()); - } - } else { - itemStatus.setItemState(ItemState.DROPPED); - } - } catch (Exception e) { - throw new ReplicationQueueException("unable to retrieve the queue status", e); - } - return itemStatus; - } - - public ReplicationQueueItem getHead() { - Job firstItem = getFirstItem(); - if (firstItem != null) { - return JobHandlingUtils.getPackage(firstItem); - } else { - return null; - } - } - - public void removeHead() { - Job firstItem = getFirstItem(); - if (firstItem != null) { - jobManager.removeJobById(firstItem.getId()); - } - } - - @SuppressWarnings("unchecked") - private Job getFirstItem() { - if (log.isInfoEnabled()) { - log.info("getting first item in the queue"); - } - - HashMap props = new HashMap(); - Collection jobs = jobManager.findJobs(QueryType.QUEUED, topic, -1, props); - jobs.addAll(jobManager.findJobs(QueryType.ACTIVE, topic, -1, props)); - if (jobs.size() > 0) { - ArrayList list = new ArrayList(jobs); - Collections.sort(list, new Comparator() { - public int compare(Job o1, Job o2) { - return o2.getRetryCount() - o1.getRetryCount(); - } - }); - Job firstItem = list.get(0); - if (log.isInfoEnabled()) { - log.info("first item in the queue is {}, retried {} times", firstItem.getId(), - firstItem.getRetryCount()); - } - return firstItem; - } - return null; - } - - public boolean isEmpty() { - return getItems().isEmpty(); - } - - public Collection getItems() { - Collection items = new LinkedList(); - Collection jobs = jobManager.findJobs(QueryType.ALL, topic, -1); - for (Job job : jobs) { - items.add(JobHandlingUtils.getPackage(job)); - } - return Collections.unmodifiableCollection(items); - } - - public void remove(String id) { - boolean removed = jobManager.removeJobById(id); - if (log.isInfoEnabled()) { - log.info("item with id {} removed from the queue: {}", id, removed); - } - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingReplicationQueueProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingReplicationQueueProvider.java deleted file mode 100644 index 7e31411f59c..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingReplicationQueueProvider.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl.jobhandling; - -import java.io.IOException; -import java.util.Dictionary; -import java.util.Hashtable; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.event.impl.jobs.config.ConfigurationConstants; -import org.apache.sling.event.jobs.JobManager; -import org.apache.sling.event.jobs.Queue; -import org.apache.sling.event.jobs.QueueConfiguration; -import org.apache.sling.event.jobs.consumer.JobConsumer; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueException; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.apache.sling.replication.queue.impl.AbstractReplicationQueueProvider; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.osgi.service.cm.Configuration; -import org.osgi.service.cm.ConfigurationAdmin; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Component(metatype = false, label = "Sling Job handling based Replication Queue Provider") -@Service(value = ReplicationQueueProvider.class) -@Property(name = "name", value = JobHandlingReplicationQueueProvider.NAME) -public class JobHandlingReplicationQueueProvider extends AbstractReplicationQueueProvider - implements ReplicationQueueProvider { - - public static final String NAME = "sjh"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Reference - private JobManager jobManager; - - @Reference - private ConfigurationAdmin configAdmin; - - private final Map jobs = new ConcurrentHashMap(); - private BundleContext context; - - @Override - protected ReplicationQueue getOrCreateQueue(String agentName, String queueName) - throws ReplicationQueueException { - try { - String name = agentName; - if (queueName.length() > 0) { - name += "/" + queueName; - } - String topic = JobHandlingReplicationQueue.REPLICATION_QUEUE_TOPIC + '/' + name; - if (jobManager.getQueue(name) == null) { - Configuration config = configAdmin.createFactoryConfiguration( - QueueConfiguration.class.getName(), null); - Dictionary props = new Hashtable(); - props.put(ConfigurationConstants.PROP_NAME, name); - props.put(ConfigurationConstants.PROP_TYPE, QueueConfiguration.Type.ORDERED.name()); - props.put(ConfigurationConstants.PROP_TOPICS, new String[]{topic}); - props.put(ConfigurationConstants.PROP_RETRIES, -1); - props.put(ConfigurationConstants.PROP_RETRY_DELAY, 2000L); - props.put(ConfigurationConstants.PROP_KEEP_JOBS, true); - props.put(ConfigurationConstants.PROP_PRIORITY, "MAX"); - config.update(props); - } - return new JobHandlingReplicationQueue(name, topic, jobManager); - } catch (IOException e) { - throw new ReplicationQueueException("could not create a queue", e); - } - } - - @Override - protected void deleteQueue(ReplicationQueue queue) { - Queue q = jobManager.getQueue(queue.getName()); - q.removeAll(); - } - - public void enableQueueProcessing(String agentName, ReplicationQueueProcessor queueProcessor) { - // eventually register job consumer for sling job handling based queues - Dictionary jobProps = new Hashtable(); - String topic = JobHandlingReplicationQueue.REPLICATION_QUEUE_TOPIC + '/' + agentName; - String childTopic = topic + "/*"; - jobProps.put(JobConsumer.PROPERTY_TOPICS, new String[]{topic, childTopic}); - synchronized (jobs) { - log.info("registering job consumer for agent {}", agentName); - ServiceRegistration jobReg = context.registerService(JobConsumer.class.getName(), - new ReplicationAgentJobConsumer(queueProcessor), jobProps); - jobs.put(agentName, jobReg); - log.info("job consumer for agent {} registered", agentName); - } - } - - public void disableQueueProcessing(String agentName) { - synchronized (jobs) { - log.info("unregistering job consumer for agent {}", agentName); - ServiceRegistration jobReg = jobs.remove(agentName); - if (jobReg != null) { - jobReg.unregister(); - log.info("job consumer for agent {} unregistered", agentName); - } - } - } - - @Activate - private void activate(BundleContext context) { - this.context = context; - } - - @Deactivate - private void deactivate(BundleContext context) { - for (ServiceRegistration jobReg : jobs.values()) { - jobReg.unregister(); - } - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingUtils.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingUtils.java deleted file mode 100644 index 480a013b34b..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingUtils.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl.jobhandling; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import org.apache.sling.event.jobs.Job; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class JobHandlingUtils { - - private static final Logger log = LoggerFactory.getLogger(JobHandlingUtils.class.getName()); - - private static final String PATHS = "replication.package.paths"; - - public static final String ID = "replication.package.id"; - - private static final String TYPE = "replication.package.type"; - - protected static final String ACTION = "replication.package.action"; - - protected static final String BYTES = "replication.package.bytes"; - - - public static ReplicationQueueItem getPackage(final Job job) { - String id = (String) job.getProperty(ID); - if (id != null) { - return new ReplicationQueueItem((String) job.getProperty(ID), - (String[]) job.getProperty(PATHS), - String.valueOf(job.getProperty(ACTION)), - String.valueOf(job.getProperty(TYPE))); - } else { - return new ReplicationQueueItem((String[]) job.getProperty(PATHS), - String.valueOf(job.getProperty(ACTION)), - String.valueOf(job.getProperty(TYPE)), - unBox((Byte[]) job.getProperty(BYTES))); - } - } - - public static Map createFullPropertiesFromPackage( - ReplicationQueueItem replicationPackage) { - Map properties = new HashMap(); - - if (replicationPackage.getId() != null) - properties.put(ID, replicationPackage.getId()); - properties.put(PATHS, replicationPackage.getPaths()); - properties.put(ACTION, replicationPackage.getAction()); - properties.put(TYPE, replicationPackage.getType()); - - if (replicationPackage.getBytes() != null) - properties.put(BYTES, box(replicationPackage.getBytes())); - - return properties; - } - - public static Map createIdPropertiesFromPackage( - ReplicationQueueItem replicationPackage) { - Map properties = new HashMap(); - properties.put(ID, replicationPackage.getId()); - return properties; - } - - public static Byte[] box(byte[] bytes) { - if (bytes == null) return null; - Byte[] result = new Byte[bytes.length]; - for (int i = 0; i < bytes.length; i++) { - result[i] = bytes[i]; - } - return result; - } - - public static byte[] unBox(Byte[] bytes) { - if (bytes == null) return null; - byte[] result = new byte[bytes.length]; - for (int i = 0; i < bytes.length; i++) { - result[i] = bytes[i]; - } - return result; - } - - public static String getQueueName(Job job) { - - String topic = job.getTopic(); - if (topic == null || !topic.startsWith(JobHandlingReplicationQueue.REPLICATION_QUEUE_TOPIC)) return null; - - String queue = topic.substring(JobHandlingReplicationQueue.REPLICATION_QUEUE_TOPIC.length() + 1); - int idx = queue.indexOf("/"); - - if (idx < 0) return ""; - - return queue.substring(idx + 1); - } - - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/ReplicationAgentJobConsumer.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/ReplicationAgentJobConsumer.java deleted file mode 100644 index d29cf559c8c..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/jobhandling/ReplicationAgentJobConsumer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl.jobhandling; - -import org.apache.sling.event.jobs.Job; -import org.apache.sling.event.jobs.consumer.JobConsumer; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * {@link JobConsumer} for {@link ReplicationAgent}s using {@link org.apache.sling.replication.queue.impl.jobhandling.JobHandlingReplicationQueue} - */ -public class ReplicationAgentJobConsumer implements JobConsumer { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final ReplicationQueueProcessor queueProcessor; - - public ReplicationAgentJobConsumer(ReplicationQueueProcessor queueProcessor) { - this.queueProcessor = queueProcessor; - } - - public JobResult process(Job job) { - log.debug("processing job {}", job.getId()); - String queueName = JobHandlingUtils.getQueueName(job); - ReplicationQueueItem info = JobHandlingUtils.getPackage(job); - log.info("processing item {} in queue {}", info.getId(), queueName); - boolean processingResult = queueProcessor.process(queueName, info); - JobResult jobResult = processingResult ? JobResult.OK : JobResult.FAILED; - log.info("item {} processed {} with result {}", new Object[]{info.getId(), jobResult, jobResult}); - return jobResult; - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/simple/ScheduledReplicationQueueProcessor.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/simple/ScheduledReplicationQueueProcessor.java deleted file mode 100644 index ff7fea150cd..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/simple/ScheduledReplicationQueueProcessor.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl.simple; - -import java.util.Arrays; - -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * a simple scheduled {@link SimpleReplicationQueue}s processor - */ -public class ScheduledReplicationQueueProcessor implements Runnable { - - private final Logger log = LoggerFactory.getLogger(getClass()); - private final ReplicationQueueProvider queueProvider; - private final ReplicationQueueProcessor queueProcessor; - - public ScheduledReplicationQueueProcessor(ReplicationQueueProvider queueProvider, - ReplicationQueueProcessor queueProcessor){ - - this.queueProvider = queueProvider; - this.queueProcessor = queueProcessor; - } - - - public void run() { - try { - for (ReplicationQueue queue : queueProvider.getAllQueues()) { - while (!queue.isEmpty()) { - // synchronized (queue) { - ReplicationQueueItem item = queue.getHead(); - if (item != null) { - if (queueProcessor.process(queue.getName(), item)) { - queue.removeHead(); - } else { - log.warn("processing of item {} failed", - Arrays.toString(item.getPaths())); - - } - } - // } - } - } - } catch (Exception e) { - log.error("error while processing queue {}", e); - } - - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/simple/SimpleReplicationQueue.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/simple/SimpleReplicationQueue.java deleted file mode 100644 index 41f04b1b1ca..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/simple/SimpleReplicationQueue.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl.simple; - -import java.util.Calendar; -import java.util.Collection; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueItemState.ItemState; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A simple implementation of a {@link ReplicationQueue}. - *

- * Note that, at the moment, this is a transient in memory queue not persisted on the repository and - * therefore not usable for production. - */ -public class SimpleReplicationQueue implements ReplicationQueue { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final String name; - - private final BlockingQueue queue; - - private final Map statusMap; - - public SimpleReplicationQueue(String agentName, String name) { - if (log.isInfoEnabled()) { - log.info("starting a simple queue for agent {}", agentName); - } - this.name = name; - this.queue = new LinkedBlockingQueue(); - this.statusMap = new WeakHashMap(10); - } - - public String getName() { - return name; - } - - public boolean add(ReplicationQueueItem replicationPackage) { - ReplicationQueueItemState status = new ReplicationQueueItemState(); - boolean result = false; - try { - result = queue.offer(replicationPackage, 10, TimeUnit.SECONDS); - status.setEntered(Calendar.getInstance()); - } catch (InterruptedException e) { - log.error("cannot add an item to the queue", e); - status.setSuccessful(false); - } finally { - statusMap.put(replicationPackage, status); - } - return result; - } - - public ReplicationQueueItemState getStatus(ReplicationQueueItem replicationPackage) { - ReplicationQueueItemState status = statusMap.get(replicationPackage); - if (queue.contains(replicationPackage)) { - status.setItemState(ItemState.QUEUED); - } else { - status.setItemState(ItemState.SUCCEEDED); - } - return status; - } - - public ReplicationQueueItem getHead() { - ReplicationQueueItem element = queue.peek(); - if (element != null) { - ReplicationQueueItemState replicationQueueItemStatus = statusMap.get(element); - replicationQueueItemStatus.setAttempts(replicationQueueItemStatus.getAttempts() + 1); - } - return element; - } - - public void removeHead() { - ReplicationQueueItem element = queue.remove(); - statusMap.get(element).setSuccessful(true); - } - - public boolean isEmpty() { - return queue.isEmpty(); - } - - public Collection getItems() { - return queue; - } - - public void remove(String id) { - ReplicationQueueItem toRemove = null; - for (ReplicationQueueItem item : queue) { - if (id.equals(item.getId())) { - toRemove = item; - } - } - boolean removed = false; - if (toRemove != null) { - removed = queue.remove(toRemove); - } - if (log.isInfoEnabled()) { - log.info("item with id {} removed from the queue: {}", id, removed); - } - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/simple/SimpleReplicationQueueProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/simple/SimpleReplicationQueueProvider.java deleted file mode 100644 index 99ba9e638b8..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/queue/impl/simple/SimpleReplicationQueueProvider.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl.simple; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.commons.scheduler.ScheduleOptions; -import org.apache.sling.commons.scheduler.Scheduler; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueException; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.apache.sling.replication.queue.impl.AbstractReplicationQueueProvider; - -/** - * an OSGi service implementing {@link ReplicationQueueProvider} for simple in memory - * {@link ReplicationQueue}s - */ -@Component(metatype = false, label = "In memory Replication Queue Provider") -@Service(value = ReplicationQueueProvider.class) -@Property(name = "name", value = SimpleReplicationQueueProvider.NAME) -public class SimpleReplicationQueueProvider extends AbstractReplicationQueueProvider implements - ReplicationQueueProvider { - - @Reference - Scheduler scheduler; - - public static final String NAME = "simple"; - - protected ReplicationQueue getOrCreateQueue(String agentName, String selector) - throws ReplicationQueueException { - return new SimpleReplicationQueue(agentName, selector); - } - - protected void deleteQueue(ReplicationQueue queue) { - // do nothing as queues just exist in the cache - } - - public void enableQueueProcessing(String agentName, ReplicationQueueProcessor queueProcessor) { - ScheduleOptions options = scheduler.NOW(-1, 10) - .canRunConcurrently(false) - .name(getJobName(agentName)); - scheduler.schedule(new ScheduledReplicationQueueProcessor(this, queueProcessor), options); - } - - public void disableQueueProcessing(String agentName) { - scheduler.unschedule(getJobName(agentName)); - } - - private String getJobName(String agentName){ - return SimpleReplicationQueueProvider.NAME+"-queueProcessor-"+agentName; - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/ReplicationConstants.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/ReplicationConstants.java deleted file mode 100644 index 3a254249037..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/ReplicationConstants.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.sling.replication.resources; - -public class ReplicationConstants { - public static final String AGENT_RESOURCE_TYPE = "replication/agent"; - public static final String AGENT_QUEUE_RESOURCE_TYPE = "replication/agent/queue"; - public static final String AGENT_QUEUE_EVENT_RESOURCE_TYPE = "replication/agent/queue"; - public static final String AGENT_ROOT_RESOURCE_TYPE = "replication/agents"; - public static final String IMPORTER_ROOT_RESOURCE_TYPE = "replication/importers"; - public static final String IMPORTER_RESOURCE_TYPE = "replication/importer"; - - public static final String SUFFIX_AGENT_QUEUE = "/queue"; - public static final String SUFFIX_AGENT_QUEUE_EVENT = "/queue/event"; -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiConfigurationResourceProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiConfigurationResourceProvider.java deleted file mode 100644 index e0bb613cc6a..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiConfigurationResourceProvider.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.resources.impl; - - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Dictionary; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.apache.sling.api.resource.ModifyingResourceProvider; -import org.apache.sling.api.resource.PersistenceException; -import org.apache.sling.api.resource.Resource; -import org.apache.sling.api.resource.ResourceProvider; -import org.apache.sling.api.resource.ResourceResolver; -import org.apache.sling.replication.resources.impl.common.AbstractModifyingResourceProvider; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.service.cm.Configuration; -import org.osgi.service.cm.ConfigurationAdmin; - -/** - * {@link ResourceProvider} for Osgi configurations for a specific configuration factory. - * All CRUD operations are supported for the underlying resources. - * The accepted path is resourceRoot/{friendlyNameProperty}/childResourceName. - */ -public class OsgiConfigurationResourceProvider extends AbstractModifyingResourceProvider implements ResourceProvider, ModifyingResourceProvider { - - private final ConfigurationAdmin configurationAdmin; - private final String configFactory; - private final String friendlyNameProperty; - - public OsgiConfigurationResourceProvider(ConfigurationAdmin configurationAdmin, - String configFactory, - String friendlyNameProperty, - String resourceRoot, - Map additionalResourceProperties) { - super(resourceRoot, additionalResourceProperties); - - this.configurationAdmin = configurationAdmin; - this.configFactory = configFactory; - this.friendlyNameProperty = friendlyNameProperty; - } - - @Override - protected void save(ResourceResolver resourceResolver, Map> changedResources, - Set deletedResources) throws PersistenceException { - try { - for (Map.Entry> entry : changedResources.entrySet()) { - String configName = entry.getKey(); - Map properties = entry.getValue(); - properties.put(friendlyNameProperty, configName); - - Configuration configuration = getConfiguration(configName); - - if (configuration == null) { - configuration = configurationAdmin.createFactoryConfiguration(configFactory); - } - configuration.update(toDictionary(properties)); - } - - for (String configName : deletedResources) { - Configuration configuration = getConfiguration(configName); - if (configuration != null) { - configuration.delete(); - } - } - } catch (IOException e) { - throw new PersistenceException("Resources cannot be commited", e); - } - } - - @Override - protected Map getResourceRootProperties() { - Configuration[] configurations = getConfigurations(null); - configurations = configurations == null ? new Configuration[0] : configurations; - - List nameList = new ArrayList(); - - for (Configuration configuration : configurations) { - String configName = (String) configuration.getProperties().get(friendlyNameProperty); - - if (configName != null) { - nameList.add(configName); - } - } - - Map result = new HashMap(); - result.put("items", nameList.toArray(new String[nameList.size()])); - - return result; - } - - @Override - protected Map getResourceProperties(String resourceName) { - - Configuration configuration = getConfiguration(resourceName); - - - if (configuration == null) { - return null; - } - - if (!configFactory.equals(configuration.getFactoryPid())) { - return null; - } - - - return toMap(configuration); - } - - - public Iterator listChildren(Resource parent) { - return null; - } - - Configuration getConfiguration(String configName) { - Configuration[] configurations = getConfigurations(configName); - - if (configurations == null || configurations.length != 1) { - return null; - } - - return configurations[0]; - } - - Configuration[] getConfigurations(String configName) { - try { - String filter = getFilter(configName); - - return configurationAdmin.listConfigurations(filter); - } catch (IOException e) { - return null; - } catch (InvalidSyntaxException e) { - return null; - } - } - - String getFilter(String configName) { - if (configName != null) { - return "(&(" + ConfigurationAdmin.SERVICE_FACTORYPID + "=" + OsgiUtils.escape(configFactory) + ")(" - + friendlyNameProperty + "=" + OsgiUtils.escape(configName) + "))"; - } else if (configFactory != null) { - return "(" + ConfigurationAdmin.SERVICE_FACTORYPID + "=" + OsgiUtils.escape(configFactory) + ")"; - } - - return null; - } - - - private Map toMap(Configuration configuration) { - return fromDictionary(configuration.getProperties()); - } - - - public static Map fromDictionary(Dictionary dictionary) { - if (dictionary == null) { - return null; - } - Map map = new HashMap(dictionary.size()); - Enumeration keys = dictionary.keys(); - while (keys.hasMoreElements()) { - K key = keys.nextElement(); - map.put(key, dictionary.get(key)); - } - return map; - } - - public static Dictionary toDictionary(Map map) { - if (map == null) { - return null; - } - Dictionary dictionary = new Hashtable(map.size()); - for (Map.Entry entry : map.entrySet()) { - dictionary.put(entry.getKey(), entry.getValue()); - } - - return dictionary; - - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiPropertiesResourceProviderFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiPropertiesResourceProviderFactory.java deleted file mode 100644 index f93f16aa197..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiPropertiesResourceProviderFactory.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.sling.replication.resources.impl; - -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.ConfigurationPolicy; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Properties; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.api.resource.LoginException; -import org.apache.sling.api.resource.ResourceProvider; -import org.apache.sling.api.resource.ResourceProviderFactory; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.osgi.framework.BundleContext; -import org.osgi.service.cm.ConfigurationAdmin; -import org.osgi.util.tracker.ServiceTracker; - -import java.util.Map; - - -@Component(label="Osgi Service Properties Resource Provider Factory", - description="Osgi Service Properties Resource Provider Factory", - configurationFactory=true, - policy= ConfigurationPolicy.REQUIRE, - name = OsgiPropertiesResourceProviderFactory.SERVICE_PID, - metatype=true) -@Service(value=ResourceProviderFactory.class) -@Properties({ - @Property(name= ResourceProvider.ROOTS), - @Property(name = ResourceProvider.OWNS_ROOTS, boolValue=true, propertyPrivate=true) -}) -public class OsgiPropertiesResourceProviderFactory implements ResourceProviderFactory { - public final static String SERVICE_PID = "org.apache.sling.replication.resources.impl.OsgiPropertiesResourceProviderFactory"; - - /** - * The name of the class that is used for resource resolution. - * For Osgi configuration this is the factoryPid. - * For Osgi services this is the service interface. - */ - @Property - public final static String SERVICE_INTERFACE = "serviceType"; - - public final static String DEFAULT_FRIENDLY_NAME_PROPERTY = "name"; - /** - * nameProperty contains the name of the property that will be used to expose - * the underlying resources. - * - * resourceRoot/resourceName/childResourceName - */ - @Property(value = DEFAULT_FRIENDLY_NAME_PROPERTY) - public final static String FRIENDLY_NAME_PROPERTY = "nameProperty"; - - /** - * resourceProperties contains the list of properties returned by this provider. - * Properties can be configured for the main resource, for the root resource and for child resources. - * Root resource properties are static and can be configured as follows: - * ../rootResourcePropertyName = rootResourcePropertyValue - * - * Main resource properties can be static or dynamic (depending on the underlying resource) are configured as follows: - * mainResourceStaticPropertyName = mainResourceStaticPropertyValue - * mainResourceDynamicPropertyName = {mainResourceSourcePropertyName} - * - * Child resource properties are static an can be configured as follows: - * childResourceName/childResourcePropertyName=childResourcePropertyValue - * - */ - @Property(cardinality = 100) - public final static String RESOURCE_PROPERTIES = "resourceProperties"; - - public final static String DEFAULT_PROVIDER_TYPE = "osgiService"; - /** - * The providerType can be osgiService or osgiConfig. - * A provider of type osgiService will allow read only access to osgi service properties of a particuar interface. - * The resource can be adapted to the underlying service instance. - * - * A provider of type osgiConfig will allow CRUD access to osgi configurations registered for a particular factory. * - */ - @Property(value = DEFAULT_PROVIDER_TYPE) - public final static String PROVIDER_TYPE = "providerType"; - - @Reference - public ConfigurationAdmin configurationAdmin; - - private ServiceTracker serviceTracker; - private ResourceProvider resourceProvider; - - @Activate - public void activate(BundleContext context, Map properties) { - String friendlyNameProperty = PropertiesUtil.toString(properties.get(FRIENDLY_NAME_PROPERTY), DEFAULT_FRIENDLY_NAME_PROPERTY); - String type = PropertiesUtil.toString(properties.get(SERVICE_INTERFACE), null); - String resourceRoot = PropertiesUtil.toString(properties.get(ResourceProvider.ROOTS), null); - - Map additionalResourceProperties = PropertiesUtil.toMap(properties.get(RESOURCE_PROPERTIES), - new String[]{friendlyNameProperty + "=" + friendlyNameProperty}); - boolean isConfig = !DEFAULT_PROVIDER_TYPE.equalsIgnoreCase(PropertiesUtil.toString(properties.get(PROVIDER_TYPE), DEFAULT_PROVIDER_TYPE)); - - - if (isConfig) { - resourceProvider = new OsgiConfigurationResourceProvider(configurationAdmin, - type, - friendlyNameProperty, - resourceRoot, - additionalResourceProperties); - - } - else { - OsgiServicePropertiesResourceProvider servicePropertiesResourceProvider; - resourceProvider = servicePropertiesResourceProvider = new OsgiServicePropertiesResourceProvider(context, - type, - friendlyNameProperty, - resourceRoot, - additionalResourceProperties); - - serviceTracker = new ServiceTracker(context, type, servicePropertiesResourceProvider); - serviceTracker.open(); - } - } - - @Deactivate - public void deactivate(BundleContext context) { - if (serviceTracker != null) { - serviceTracker.close(); - serviceTracker = null; - } - } - - public ResourceProvider getResourceProvider(Map authenticationInfo) throws LoginException { - return resourceProvider; - } - - public ResourceProvider getAdministrativeResourceProvider(Map authenticationInfo) throws LoginException { - return getResourceProvider(authenticationInfo); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiServicePropertiesResourceProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiServicePropertiesResourceProvider.java deleted file mode 100644 index 2b387ab5f40..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiServicePropertiesResourceProvider.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.sling.replication.resources.impl; - - -import org.apache.sling.api.resource.Resource; -import org.apache.sling.api.resource.ResourceProvider; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.replication.resources.impl.common.AbstractReadableResourceProvider; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.util.tracker.ServiceTrackerCustomizer; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * {@link ResourceProvider} for Osgi services for a specific service interface. - * The main resource contains a list of service properties and can be adapted to the underlying service. - * The accepted path is resourceRoot/{friendlyNameProperty}/childResourceName. - */ -public class OsgiServicePropertiesResourceProvider extends AbstractReadableResourceProvider implements ServiceTrackerCustomizer { - - private final BundleContext context; - private final String friendlyNameProperty; - - private final Map services = new ConcurrentHashMap(); - private final Map> serviceProperties = new ConcurrentHashMap>(); - - public OsgiServicePropertiesResourceProvider(BundleContext context, - String serviceInterface, - String friendlyNameProperty, - String resourceRoot, - Map additionalResourceProperties) { - super(resourceRoot, additionalResourceProperties); - this.context = context; - String serviceInterface1 = serviceInterface; - this.friendlyNameProperty = friendlyNameProperty; - } - - @Override - protected Map getResourceProperties(String resourceName) { - Map properties = serviceProperties.get(resourceName); - Object service = services.get(resourceName); - - if (service != null && properties != null) { - properties.put(ADAPTABLE_PROPERTY_NAME, service); - return properties; - } - - return null; - } - - @Override - protected Map getResourceRootProperties() { - Set serviceNames = services.keySet(); - - Collection serviceObjects = services.values(); - - Map result = new HashMap(); - - result.put("items", serviceNames.toArray(new String[serviceNames.size()])); - result.put(ADAPTABLE_PROPERTY_NAME, serviceObjects.toArray(new Object[serviceObjects.size()])); - - return result; - } - - public Iterator listChildren(Resource parent) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - public Object addingService(ServiceReference serviceReference) { - String serviceName = PropertiesUtil.toString(serviceReference.getProperty(friendlyNameProperty), null); - - if (serviceName == null) return null; - - Map properties = new HashMap(); - - for (String key : serviceReference.getPropertyKeys()) { - properties.put(key, serviceReference.getProperty(key)); - } - - Object service = context.getService(serviceReference); - - services.put(serviceName, service); - serviceProperties.put(serviceName, properties); - - - return service; - } - - public void modifiedService(ServiceReference serviceReference, Object o) { - // do nothing - } - - public void removedService(ServiceReference serviceReference, Object o) { - String serviceName = PropertiesUtil.toString(serviceReference.getProperty(friendlyNameProperty), null); - - if (serviceName == null) return; - - services.remove(serviceName); - serviceProperties.remove(serviceName); - - context.ungetService(serviceReference); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiUtils.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiUtils.java deleted file mode 100644 index 9a2288a2914..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/OsgiUtils.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.resources.impl; - -public class OsgiUtils { - /** - * Encode the value for the ldap filter: \, *, (, and ) should be escaped. - */ - public static String escape(final String value) { - return value.replace("\\", "\\\\") - .replace("*", "\\*") - .replace("(", "\\(") - .replace(")", "\\)"); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/AbstractModifyingResourceProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/AbstractModifyingResourceProvider.java deleted file mode 100644 index e6c393aa2d8..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/AbstractModifyingResourceProvider.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.resources.impl.common; - - -import org.apache.sling.api.resource.ModifyingResourceProvider; -import org.apache.sling.api.resource.PersistenceException; -import org.apache.sling.api.resource.Resource; -import org.apache.sling.api.resource.ResourceResolver; - -import javax.jcr.Session; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public abstract class AbstractModifyingResourceProvider extends AbstractReadableResourceProvider - implements ModifyingResourceProvider { - - private final Map> changedResources = new HashMap>(); - private final Set deletedResources = new HashSet(); - - public AbstractModifyingResourceProvider(String resourceRoot, - Map additionalResourceProperties){ - super(resourceRoot, additionalResourceProperties); - - } - - public Resource create(ResourceResolver resolver, String path, Map properties) throws PersistenceException { - SimplePathInfo pathInfo = extractPathInfo(path); - - if (pathInfo == null) { - throw new PersistenceException("Invalid path: " + path, null); - } - - if (!hasPermission(resolver, pathInfo.getResourcePath(), Session.ACTION_ADD_NODE)) { - throw new PersistenceException("Not enough permissions"); - } - - - String resourceName = pathInfo.getMainResourceName(); - - final boolean deleted = this.deletedResources.remove(resourceName); - Map existingResource = getMainResourceProperties(resourceName); - if (!deleted && existingResource != null) { - throw new PersistenceException("Resource already exists at " + path, null, resourceName, null); - } - - properties = unbindMainResourceProperties(properties); - this.changedResources.put(resourceName, properties); - - return buildMainResource(resolver, pathInfo, properties); - } - - public void delete(ResourceResolver resolver, String requestPath) throws PersistenceException { - SimplePathInfo pathInfo = extractPathInfo(requestPath); - - if (pathInfo == null) { - throw new PersistenceException("Invalid path: " + requestPath, null); - } - - if (!hasPermission(resolver, pathInfo.getResourcePath(), Session.ACTION_REMOVE)) { - throw new PersistenceException("Not enough permissions"); - } - - String resourceName = pathInfo.getMainResourceName(); - - if (!deletedResources.contains(resourceName)) { - deletedResources.add(resourceName); - changedResources.remove(resourceName); - } - } - - public void revert(ResourceResolver resolver) { - changedResources.clear(); - deletedResources.clear(); - } - - public void commit(ResourceResolver resolver) throws PersistenceException { - save(resolver, changedResources, deletedResources); - revert(resolver); - } - - public boolean hasChanges(ResourceResolver resolver) { - return changedResources.size() > 0 || deletedResources.size() > 0; - } - - public void change(ResourceResolver resourceResolver, String requestPath, Map properties) { - SimplePathInfo pathInfo = extractPathInfo(requestPath); - - if (pathInfo == null) { - return; - } - - if (!hasPermission(resourceResolver, pathInfo.getResourcePath(), Session.ACTION_SET_PROPERTY)) { - return; - } - - String resourceName = pathInfo.getMainResourceName(); - - this.deletedResources.remove(resourceName); - - properties = unbindMainResourceProperties(properties); - this.changedResources.put(resourceName, properties); - } - - @Override - public Map getMainResourceProperties(String resourceName) { - - if (deletedResources.contains(resourceName)) { - return null; - } - - if (changedResources.containsKey(resourceName)) { - return changedResources.get(resourceName); - } - - return super.getMainResourceProperties(resourceName); - } - - @Override - protected Resource buildMainResource(ResourceResolver resourceResolver, SimplePathInfo pathInfo, Map properties, Object... adapters) { - return new SimpleModifiableResource(resourceResolver, this, pathInfo.getResourcePath(), properties); - } - - protected abstract void save(ResourceResolver resourceResolver, - Map> changedResources, - Set deletedResources) throws PersistenceException; - - - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/AbstractReadableResourceProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/AbstractReadableResourceProvider.java deleted file mode 100644 index d4027efa808..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/AbstractReadableResourceProvider.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.sling.replication.resources.impl.common; - - -import org.apache.sling.api.resource.Resource; -import org.apache.sling.api.resource.ResourceProvider; -import org.apache.sling.api.resource.ResourceResolver; - -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.servlet.http.HttpServletRequest; -import java.util.HashMap; -import java.util.Map; - -public abstract class AbstractReadableResourceProvider implements ResourceProvider { - - protected static final String ADAPTABLE_PROPERTY_NAME = "adaptable"; - - private static final String MAIN_RESOURCE_PREFIX = "."; - private static final String ROOT_RESOURCE_PREFIX = ".."; - - private final String resourceRoot; - private final Map> additionalResourcePropertiesMap = new HashMap>(); - - public AbstractReadableResourceProvider(String resourceRoot, - Map additionalResourceProperties) { - - this.resourceRoot = resourceRoot; - - additionalResourcePropertiesMap.put(ROOT_RESOURCE_PREFIX, new HashMap()); - additionalResourcePropertiesMap.put(MAIN_RESOURCE_PREFIX, new HashMap()); - for (Map.Entry entry : additionalResourceProperties.entrySet()) { - String resourceName = MAIN_RESOURCE_PREFIX; - String propertyName = entry.getKey(); - int idx =propertyName.indexOf("/"); - if (idx >=0) { - resourceName = propertyName.substring(0, idx); - propertyName = propertyName.substring(idx+1); - } - - if (!additionalResourcePropertiesMap.containsKey(resourceName)) { - additionalResourcePropertiesMap.put(resourceName, new HashMap()); - } - - additionalResourcePropertiesMap.get(resourceName).put(propertyName, entry.getValue()); - } - } - - public Resource getResource(ResourceResolver resourceResolver, HttpServletRequest request, String path) { - return getResource(resourceResolver, path); - } - - public Resource getResource(ResourceResolver resourceResolver, String path) { - SimplePathInfo pathInfo = extractPathInfo(path); - - if (pathInfo == null) { - return null; - } - - if (pathInfo.getResourcePathInfo() != null && pathInfo.getResourcePathInfo().length() > 0) { - return null; - } - - if(!hasPermission(resourceResolver, pathInfo.getResourcePath(), Session.ACTION_READ)) { - return null; - } - - Resource resource = null; - - if (pathInfo.isRoot()) { - - Map properties = getResourceRootProperties(); - - if (properties != null) { - Object adaptable = properties.remove(ADAPTABLE_PROPERTY_NAME); - - Map additionalProperties = additionalResourcePropertiesMap.get(ROOT_RESOURCE_PREFIX); - properties.putAll(additionalProperties); - - resource = new SimpleReadableResource(resourceResolver, pathInfo.getResourcePath(), properties, adaptable); - } - } - else if (pathInfo.isMain()) { - Map properties = getMainResourceProperties(pathInfo.getMainResourceName()); - - if (properties != null) { - Object adaptable = properties.remove(ADAPTABLE_PROPERTY_NAME); - - properties = bindMainResourceProperties(properties); - - resource = buildMainResource(resourceResolver, pathInfo, properties, adaptable); - } - } - else if (pathInfo.isChild()) { - Map mainProperties = getMainResourceProperties(pathInfo.getMainResourceName()); - Map childProperties = additionalResourcePropertiesMap.get(pathInfo.getChildResourceName()); - - if (mainProperties != null && childProperties != null) { - Object adaptable = mainProperties.remove(ADAPTABLE_PROPERTY_NAME); - - Map properties = new HashMap(); - properties.putAll(childProperties); - resource = new SimpleReadableResource(resourceResolver, pathInfo.getResourcePath(), properties, adaptable); - } - } - - return resource; - } - - protected Map getMainResourceProperties(String resourceName) { - return getResourceProperties(resourceName); - } - - protected Map bindMainResourceProperties(Map properties) { - Map result = new HashMap(); - - Map resourcePropertyTemplates = additionalResourcePropertiesMap.get(MAIN_RESOURCE_PREFIX); - - for (Map.Entry propertyTemplateEntry : resourcePropertyTemplates.entrySet()) { - String templateName = propertyTemplateEntry.getKey(); - String templateValue = propertyTemplateEntry.getValue(); - - Object propertyValue = templateValue; - if (templateValue.startsWith("{") && templateValue.endsWith("}")) { - String propertyName = templateValue.substring(1, templateValue.length()-1); - propertyValue = properties.get(propertyName); - } - - if (propertyValue != null) { - result.put(templateName, propertyValue); - } - - - } - return result; - } - - protected Map unbindMainResourceProperties(Map requestProperties) { - Map result = new HashMap(); - - Map resourcePropertyTemplates = additionalResourcePropertiesMap.get(MAIN_RESOURCE_PREFIX); - - for (Map.Entry propertyTemplateEntry : resourcePropertyTemplates.entrySet()) { - String templateName = propertyTemplateEntry.getKey(); - String templateValue = propertyTemplateEntry.getValue(); - - if (templateValue.startsWith("{") && templateValue.endsWith("}")) { - String propertyName = templateValue.substring(1, templateValue.length()-1); - Object propertyValue = requestProperties.get(templateName); - if (propertyValue != null) { - result.put(propertyName, propertyValue); - } - } - } - return result; - } - - protected Resource buildMainResource(ResourceResolver resourceResolver, - SimplePathInfo pathInfo, - Map properties, - Object... adapters) { - return new SimpleReadableResource(resourceResolver, pathInfo.getResourcePath(), properties, adapters); - } - - protected SimplePathInfo extractPathInfo(String path) { - return SimplePathInfo.parsePathInfo(resourceRoot, path); - } - - protected boolean hasPermission(ResourceResolver resourceResolver, String resourcePath, String permission) { - - boolean hasPermission = false; - Session session = resourceResolver.adaptTo(Session.class); - - if (session != null) { - try { - hasPermission = session.hasPermission(resourcePath, permission); - } catch (RepositoryException e) { - hasPermission = false; - } - } - - return hasPermission; - } - - - protected abstract Map getResourceProperties(String resourceName); - protected abstract Map getResourceRootProperties(); -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimpleModifiableResource.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimpleModifiableResource.java deleted file mode 100644 index 6dded54abab..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimpleModifiableResource.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.resources.impl.common; - -import org.apache.sling.api.resource.ModifiableValueMap; -import org.apache.sling.api.resource.ResourceResolver; -import org.apache.sling.api.resource.ValueMap; - -import java.util.Map; - -/** - * Resource that can be adapted to a ModifiableValueMap - */ -public class SimpleModifiableResource extends SimpleReadableResource { - - private final AbstractModifyingResourceProvider resourceProvider; - - public SimpleModifiableResource(ResourceResolver resourceResolver, AbstractModifyingResourceProvider resourceProvider, - String resourcePath, - Map properties) { - super(resourceResolver, resourcePath, properties); - this.resourceProvider = resourceProvider; - } - - @Override - public AdapterType adaptTo(Class type) { - - if (type == ValueMap.class || type == Map.class) { - return (AdapterType) new SimpleModifiableValueMap(getResourceResolver(), resourceProvider, this); - - } else if (type == ModifiableValueMap.class) { - return (AdapterType) new SimpleModifiableValueMap(getResourceResolver(), resourceProvider, this); - } - - return super.adaptTo(type); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimpleModifiableValueMap.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimpleModifiableValueMap.java deleted file mode 100644 index 1a59300932c..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimpleModifiableValueMap.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.resources.impl.common; - -import org.apache.sling.api.resource.ModifiableValueMap; -import org.apache.sling.api.resource.ResourceResolver; -import org.apache.sling.api.wrappers.ModifiableValueMapDecorator; -import org.apache.sling.replication.resources.impl.common.AbstractModifyingResourceProvider; - -import java.util.HashMap; -import java.util.Map; - -/** - * ValueMap that signals to the underlying resource provider the its values are changed. - */ -public class SimpleModifiableValueMap extends ModifiableValueMapDecorator - implements ModifiableValueMap { - - private final ResourceResolver resourceResolver; - private final AbstractModifyingResourceProvider resourceProvider; - private final SimpleModifiableResource resource; - - public SimpleModifiableValueMap(ResourceResolver resourceResolver, - AbstractModifyingResourceProvider resourceProvider, - SimpleModifiableResource resource) { - super(resource.getProperties()); - this.resourceResolver = resourceResolver; - this.resourceProvider = resourceProvider; - this.resource = resource; - } - - @Override - public Object put(String key, Object value) { - Object result = super.put(key, value); - changed(); - return result; - } - - @Override - public Object remove(Object key) { - Object result = super.remove(key); - changed(); - return result; - } - - @Override - public void putAll(Map t) { - super.putAll(t); - changed(); - } - - @Override - public void clear() { - super.clear(); - changed(); - } - - private void changed() { - Map newProperties = new HashMap(); - for (Entry entry : entrySet()) { - newProperties.put(entry.getKey(), entry.getValue()); - } - resourceProvider.change(resourceResolver, resource.getPath(), newProperties); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimplePathInfo.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimplePathInfo.java deleted file mode 100644 index c02624bb483..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimplePathInfo.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.sling.replication.resources.impl.common; - -/** - * Path info representing a main resource. - * The requestPath = resourcePath + resourcePathInfo - * The identified resource can be of three types: - * root - resourcePath = resourceRoot - * main - resourcePath = resourceRoot + mainResourceName - * child - resourcePath = resourceRoot + mainResourceName + childResourceName - */ -public class SimplePathInfo { - - final String resourcePathInfo; - - // resourcePath = resourceRoot + "/" + mainResourceName + "/" + childResourceName - private final String resourceRoot; - private final String mainResourceName; - private final String childResourceName; - - public SimplePathInfo(String resourcePathInfo, String resourceRoot, String resourceName, String childResourceName) { - - this.resourcePathInfo = resourcePathInfo; - this.resourceRoot = resourceRoot; - this.mainResourceName = resourceName; - this.childResourceName = childResourceName; - } - - public String getResourcePathInfo() { - return resourcePathInfo; - } - - public String getMainResourceName() { - return mainResourceName; - } - - public String getChildResourceName() { - return childResourceName; - } - - public boolean isRoot() { - return mainResourceName == null; - } - - public boolean isMain() { - return mainResourceName != null && childResourceName == null; - } - - public boolean isChild() { - return mainResourceName != null && childResourceName != null; - } - - public String getResourcePath() { - if (isRoot()) { - return resourceRoot; - } - else if (isMain()) { - return resourceRoot + "/" + mainResourceName; - } - else if (isChild()) { - return resourceRoot + "/" + mainResourceName + "/" + childResourceName; - } - - return null; - } - - - public static SimplePathInfo parsePathInfo(String resourceRoot, String requestPath) { - if (!requestPath.startsWith(resourceRoot)) { - return null; - } - - String resourceName = null; - String resourcePathInfo = null; - - if(requestPath.startsWith(resourceRoot + "/")) { - resourceName = requestPath.substring(resourceRoot.length()+1); - int idx = resourceName.indexOf("."); - if (idx >= 0) { - resourcePathInfo = resourceName.substring(idx); - resourceName = resourceName.substring(0, idx); - } - } - else { - int idx = requestPath.indexOf("."); - if (requestPath.contains(".")) { - resourcePathInfo = requestPath.substring(idx); - } - } - - String childResourceName = null; - - if (resourceName != null) { - int idx = resourceName.indexOf("/"); - if (idx >= 0) { - childResourceName = resourceName.substring(idx+1); - resourceName = resourceName.substring(0, idx); - } - } - return new SimplePathInfo(resourcePathInfo, resourceRoot, resourceName, childResourceName); - } -} - - diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimpleReadableResource.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimpleReadableResource.java deleted file mode 100644 index db7bd8f6f19..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/resources/impl/common/SimpleReadableResource.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.sling.replication.resources.impl.common; - - -import org.apache.sling.api.resource.AbstractResource; -import org.apache.sling.api.resource.ResourceMetadata; -import org.apache.sling.api.resource.ResourceResolver; -import org.apache.sling.api.resource.ValueMap; -import org.apache.sling.api.wrappers.ValueMapDecorator; - -import java.lang.reflect.Array; -import java.util.Map; - -/** - * Read only resource that can adapt to one of the object provided as parameter. - */ -public class SimpleReadableResource extends AbstractResource { - - private final ResourceResolver resourceResolver; - private final String resourcePath; - private final Map properties; - private final Object[] adapters; - - private final ResourceMetadata metadata = new ResourceMetadata(); - - - public SimpleReadableResource(ResourceResolver resourceResolver, String resourcePath, - Map properties, Object... adapters) { - - this.resourceResolver = resourceResolver; - this.resourcePath = resourcePath; - this.properties = properties; - this.adapters = adapters; - } - - public String getPath() { - return resourcePath; - } - - public String getResourceType() { - // get resource type from data - final Object rt = this.properties.get("sling:resourceType"); - if ( rt != null ) { - return rt.toString(); - } - return "nt:unstructured"; - } - - public String getResourceSuperType() { - // get resource type from data - final Object rt = this.properties.get("sling:resourceSuperType"); - if ( rt != null ) { - return rt.toString(); - } - return "nt:unstructured"; - } - - public ResourceMetadata getResourceMetadata() { - return metadata; - } - - public ResourceResolver getResourceResolver() { - return resourceResolver; - } - - public Map getProperties() { - return properties; - } - - - @Override - public AdapterType adaptTo(Class type) { - - if (type == ValueMap.class || type == Map.class) { - return (AdapterType) new ValueMapDecorator(getProperties()); - } - else { - if (adapters != null) { - for (Object adapter : adapters) { - if (adapter == null) continue; - - if (type.isArray()) { - if (adapter.getClass().isArray()) { - Object[] adapterArray = (Object[]) adapter; - - return convertArray(type, adapterArray); - } - } - else if (type.isAssignableFrom(adapter.getClass())) { - return (AdapterType) adapter; - } - } - } - } - return super.adaptTo(type); - } - - - private ArrayType convertArray(Class arrayType, Object[] array) { - Object[] result = (Object[]) Array.newInstance(arrayType.getComponentType(), array.length); - for (int i=0; i < array.length; i++) { - if (array[i] != null && !arrayType.getComponentType().isAssignableFrom(array[i].getClass())) { - return null; - } - result[i] = array[i]; - } - - return (ArrayType) result; - } -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/ReplicationRule.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/ReplicationRule.java deleted file mode 100644 index e5157021a8e..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/ReplicationRule.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule; - -import org.apache.sling.replication.agent.ReplicationAgent; - -/** - * A replication rule - */ -public interface ReplicationRule { - - /** - * get the signature of this rule - * - * @return a String for this rule's signature - */ - String getSignature(); - - /** - * checks if the given rule String matches this {@link ReplicationRule}'s signature - * - * @param ruleString a rule String - * @return true if the given rule String matches this rule's signature, false otherwise - */ - boolean signatureMatches(String ruleString); - - /** - * apply this rule to a replication agent - * - * @param ruleString the rule to apply to the agent - * @param agent {@link ReplicationAgent agent} the agent to apply the rule to - */ - void apply(String ruleString, ReplicationAgent agent); - - /** - * undo the application of this rule to the given agent - * - * @param agent the {@link ReplicationAgent agent} on which undoing this rule application - */ - void undo(String ruleString, ReplicationAgent agent); -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/ReplicationRuleEngine.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/ReplicationRuleEngine.java deleted file mode 100644 index 384c28385dc..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/ReplicationRuleEngine.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule; - -import org.apache.sling.replication.agent.ReplicationAgent; - -/** - * A replication rule engine - */ -public interface ReplicationRuleEngine { - - /** - * reads a String, transforms it into a {@link ReplicationRule} and applies it to the - * given {@link ReplicationAgent} - * - * @param agent the {@link ReplicationAgent} to apply the rule to - * @param ruleStrings the String array to be read as a {@link ReplicationRule}s - */ - void applyRules(ReplicationAgent agent, String... ruleStrings); - - /** - * reads a String, transforms it into a {@link ReplicationRule} and un-applies it to the - * given {@link ReplicationAgent} - * - * @param agent the {@link ReplicationAgent} to un-apply the rule to - * @param ruleStrings the String array to be read as a {@link ReplicationRule}s - */ - void unapplyRules(ReplicationAgent agent, String... ruleStrings); - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/ChainReplicateReplicationRule.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/ChainReplicateReplicationRule.java deleted file mode 100644 index 2a853d1c5ed..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/ChainReplicateReplicationRule.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule.impl; - -import java.util.Dictionary; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Map; -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.replication.agent.AgentReplicationException; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.event.ReplicationEvent; -import org.apache.sling.replication.event.ReplicationEventType; -import org.apache.sling.replication.rule.ReplicationRule; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.osgi.service.event.Event; -import org.osgi.service.event.EventConstants; -import org.osgi.service.event.EventHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * a rule for triggering a chain replication upon replication package installation {@link org.apache.sling.replication.event.ReplicationEventType.PACKAGE_INSTALLED} - */ -@Component(immediate = true, label = "Rule for Chain Replication") -@Service(value = ReplicationRule.class) -public class ChainReplicateReplicationRule implements ReplicationRule { - - private static final String PREFIX = "chain on path:"; - private static final String SIGNATURE = "chain on path: ${path}"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private BundleContext bundleContext; - private final Map registrations = new HashMap(); - - @Activate - protected void activate(BundleContext bundleContext) { - this.bundleContext = bundleContext; - } - - @Deactivate - protected void deactivate() { - for (Map.Entry entry : registrations.entrySet()) { - if (entry.getValue() != null) { - entry.getValue().unregister(); - } - } - registrations.clear(); - } - - public String getSignature() { - return SIGNATURE; - } - - public void apply(String ruleString, ReplicationAgent agent) { - if (signatureMatches(ruleString)) { - // register an event handler on replication package install (on a certain path) which triggers the chain replication of that same package - Dictionary properties = new Hashtable(); - properties.put(EventConstants.EVENT_TOPIC, ReplicationEvent.getTopic(ReplicationEventType.PACKAGE_INSTALLED)); - String path = ruleString.substring(ruleString.indexOf(':') + 1).trim(); - if (log.isInfoEnabled()) { - log.info("agent {} will chain replication on path '{}'", agent.getName(), path); - } -// properties.put(EventConstants.EVENT_FILTER, "(path=" + path + "/*)"); - if (bundleContext != null) { - ServiceRegistration triggerPathEventRegistration = bundleContext.registerService(EventHandler.class.getName(), new TriggerAgentEventListener(agent, path), properties); - registrations.put(agent.getName() + ruleString, triggerPathEventRegistration); - } else { - if (log.isErrorEnabled()) { - log.error("cannot register trigger since bundle context is null"); - } - } - } else { - if (log.isWarnEnabled()) { - log.warn("rule {} doesn't match signature: {}", ruleString, SIGNATURE); - } - } - - } - - public boolean signatureMatches(String ruleString) { - return ruleString.startsWith(PREFIX) && ruleString.substring(PREFIX.length() + 1).matches("\\s*(\\/\\w+)+"); - } - - public void undo(String ruleString, ReplicationAgent agent) { - if (signatureMatches(ruleString)) { - ServiceRegistration serviceRegistration = registrations.get(agent.getName() + ruleString); - if (serviceRegistration != null) { - serviceRegistration.unregister(); - } - } else { - if (log.isWarnEnabled()) { - log.warn("rule {} doesn't match signature: {}", ruleString, SIGNATURE); - } - } - } - - - private class TriggerAgentEventListener implements EventHandler { - - private final ReplicationAgent agent; - private final String path; - - public TriggerAgentEventListener(ReplicationAgent agent, String path) { - this.agent = agent; - this.path = path; - } - - public void handleEvent(Event event) { - Object actionProperty = event.getProperty("replication.action"); - Object pathProperty = event.getProperty("replication.path"); - if (actionProperty != null && pathProperty != null) { - String[] paths = (String[]) pathProperty; - for (String p : paths) { - if (p.startsWith(path)) { - if (log.isInfoEnabled()) { - log.info("triggering chain replication from event {}", event); - } - ReplicationActionType action = ReplicationActionType.valueOf(String.valueOf(actionProperty)); - try { - agent.send(new ReplicationRequest(System.currentTimeMillis(), action, paths)); - } catch (AgentReplicationException e) { - if (log.isErrorEnabled()) { - log.error("triggered replication resulted in an error {}", e); - } - } - break; - } - } - } - } - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/DefaultReplicationRuleEngine.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/DefaultReplicationRuleEngine.java deleted file mode 100644 index 5f4d70367fc..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/DefaultReplicationRuleEngine.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule.impl; - -import java.util.Collection; -import java.util.LinkedList; -import java.util.Map; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.ReferenceCardinality; -import org.apache.felix.scr.annotations.ReferencePolicy; -import org.apache.felix.scr.annotations.References; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.rule.ReplicationRule; -import org.apache.sling.replication.rule.ReplicationRuleEngine; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * default implementation of {@link ReplicationRuleEngine} - */ -@Component(label = "Replication Rule Engine") -@References({ - @Reference(name = "replicationRule", - referenceInterface = ReplicationRule.class, - cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, - policy = ReferencePolicy.DYNAMIC, - bind = "bindReplicationRule", - unbind = "unbindReplicationRule") -}) -@Service(value = ReplicationRuleEngine.class) -public class DefaultReplicationRuleEngine implements ReplicationRuleEngine { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final Collection replicationRules = new LinkedList(); - - @Deactivate - protected void deactivate() { - replicationRules.clear(); - } - - protected void bindReplicationRule(final ReplicationRule replicationRule, - Map properties) { - synchronized (replicationRules) { - replicationRules.add(replicationRule); - } - log.debug("Registering replication rule {} ", replicationRule); - } - - protected void unbindReplicationRule(final ReplicationRule replicationRule, - Map properties) { - synchronized (replicationRules) { - replicationRules.remove(replicationRule); - } - log.debug("Unregistering replication rule {} ", replicationRule); - } - - public void applyRules(ReplicationAgent agent, String... ruleStrings) { - for (String ruleString : ruleStrings) { - - for (ReplicationRule rule : replicationRules) { - if (rule.signatureMatches(ruleString)) { - if (log.isInfoEnabled()) { - log.info("applying rule {} with string {} to agent {}", new Object[]{rule, ruleString, agent}); - } - rule.apply(ruleString, agent); - break; - } - } - - } - } - - public void unapplyRules(ReplicationAgent agent, String... ruleStrings) { - for (String ruleString : ruleStrings) { - - for (ReplicationRule rule : replicationRules) { - if (rule.signatureMatches(ruleString)) { - if (log.isInfoEnabled()) { - log.info("un-applying rule {} with string {} to agent {}", new Object[]{rule, ruleString, agent}); - } - rule.undo(ruleString, agent); - break; - } - } - - } - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/ReplicateOnQueueEventRule.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/ReplicateOnQueueEventRule.java deleted file mode 100644 index 6e9370ad5a3..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/ReplicateOnQueueEventRule.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule.impl; - -import java.io.IOException; -import java.net.URI; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Future; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.Service; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.utils.URIUtils; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; -import org.apache.http.impl.nio.client.HttpAsyncClients; -import org.apache.http.nio.ContentDecoder; -import org.apache.http.nio.IOControl; -import org.apache.http.nio.protocol.BasicAsyncRequestProducer; -import org.apache.http.nio.protocol.BasicAsyncResponseConsumer; -import org.apache.sling.commons.scheduler.ScheduleOptions; -import org.apache.sling.commons.scheduler.Scheduler; -import org.apache.sling.replication.agent.AgentReplicationException; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.agent.ReplicationAgentConfiguration; -import org.apache.sling.replication.agent.ReplicationAgentConfigurationManager; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.resources.ReplicationConstants; -import org.apache.sling.replication.rule.ReplicationRule; -import org.apache.sling.replication.transport.TransportHandler; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * {@link org.apache.sling.replication.rule.ReplicationRule} to trigger - */ -@Component(immediate = true, label = "Rule for generating Server Sent Events for Queues") -@Service(value = ReplicationRule.class) -public class ReplicateOnQueueEventRule implements ReplicationRule { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private static final String SIGNATURE = "queue event based {action} [on ${path}]"; - - private static final String SIGNATURE_REGEX = "(queue\\sevent\\sbased)\\s(add|delete|poll)(\\s(on)\\s(\\/\\w+)+)?"; - - private static final Pattern signaturePattern = Pattern.compile(SIGNATURE_REGEX); - - @Reference - private ReplicationAgentConfigurationManager replicationAgentConfigurationManager; - - @Reference - private Scheduler scheduler; - - private BundleContext context; - - private Map> requests; - - @Activate - protected void activate(BundleContext context) { - this.context = context; - this.requests = new ConcurrentHashMap>(); - } - - public String getSignature() { - return SIGNATURE; - } - - public boolean signatureMatches(String ruleString) { - return ruleString.matches(SIGNATURE_REGEX); - } - - public void apply(String ruleString, ReplicationAgent agent) { - Matcher matcher = signaturePattern.matcher(ruleString); - if (matcher.find()) { - String action = matcher.group(2); - ReplicationActionType actionType = ReplicationActionType.fromName(action.toUpperCase()); - String path = matcher.group(5); // can be null - try { - log.info("applying queue event replication rule"); - // get configuration - ReplicationAgentConfiguration configuration = replicationAgentConfigurationManager.getConfiguration(agent.getName()); - - // get URI of the event queue - String targetTransport = configuration.getTargetTransportHandler(); - - log.info("found target transport {}", targetTransport); - - ScheduleOptions options = scheduler.NOW(); - options.name(agent.getName() + " " + ruleString); - scheduler.schedule(new EventBasedReplication(agent, actionType, path, targetTransport), options); - - } catch (Exception e) { - log.error("{}", e); - log.error("cannot apply rule {} to agent {}", ruleString, agent); - } - - } - } - - public void undo(String ruleString, ReplicationAgent agent) { - Future httpResponseFuture = requests.remove(agent.getName()); - if (httpResponseFuture != null) { - httpResponseFuture.cancel(true); - } - } - - private class SSEResponseConsumer extends BasicAsyncResponseConsumer { - - private final ReplicationAgent agent; - private final ReplicationActionType action; - private final String path; - - private SSEResponseConsumer(ReplicationAgent agent, ReplicationActionType action, String path) { - this.agent = agent; - this.action = action; - this.path = path == null ? "/" : path; - } - - @Override - protected void onContentReceived(ContentDecoder decoder, IOControl ioctrl) throws IOException { -// log.info("complete ? ", decoder.isCompleted()); -// ByteBuffer buffer = ByteBuffer.allocate(1024); -// decoder.read(buffer); -// log.info("content {} received {},{}", new Object[]{buffer, decoder, ioctrl}); - log.info("event received"); - - try { - asyncReplicate(agent, action, path); - log.info("replication request to agent {} sent ({} on {})", new Object[]{agent.getName(), action, path}); - } catch (AgentReplicationException e) { - log.error("cannot replicate to agent {}, {}", agent.getName(), e); - } - - super.onContentReceived(decoder, ioctrl); - } - - @Override - protected void onResponseReceived(HttpResponse response) throws IOException { - log.info("response received {}", response); - super.onResponseReceived(response); - } - } - - private void asyncReplicate(ReplicationAgent agent, ReplicationActionType action, String path) throws AgentReplicationException { - agent.send(new ReplicationRequest(System.currentTimeMillis(), action, path)); - } - - private class EventBasedReplication implements Runnable { - private final ReplicationAgent agent; - private final ReplicationActionType actionType; - private final String targetTransport; - private final String path; - - public EventBasedReplication(ReplicationAgent agent, ReplicationActionType actionType, String path, String targetTransport) { - this.agent = agent; - this.actionType = actionType; - this.targetTransport = targetTransport; - this.path = path; - } - - public void run() { - try { - ServiceReference[] serviceReferences = context.getServiceReferences(TransportHandler.class.getName(), targetTransport); - - log.info("reference transport for {} found {}", targetTransport, serviceReferences != null); - - if (serviceReferences != null && serviceReferences.length == 1) { - - Object endpointsProperty = serviceReferences[0].getProperty("endpoints"); - Object authenticationPropertiesProperty = serviceReferences[0].getProperty("authentication.properties"); - - log.info("endpoint prop: {} authentication properties prop: {}", endpointsProperty, authenticationPropertiesProperty); - - String[] endpoints = (String[]) endpointsProperty; - Map authenticationProperties = (Map) authenticationPropertiesProperty; - - log.info("endpoint {} props {}", endpoints, authenticationProperties); - // only works with HTTP - if (endpoints.length == 1 && endpoints[0].startsWith("http") && authenticationProperties != null) { - log.info("getting event queue URI"); - URI eventEndpoint = URI.create(endpoints[0] + ReplicationConstants.SUFFIX_AGENT_QUEUE_EVENT); - String userName = authenticationProperties.get("user"); - String password = authenticationProperties.get("password"); - - log.info("preparing request"); - CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials( - new AuthScope(eventEndpoint.getHost(), eventEndpoint.getPort()), - new UsernamePasswordCredentials(userName, password)); - CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom() - .setDefaultCredentialsProvider(credentialsProvider) - .build(); - try { - HttpGet get = new HttpGet(eventEndpoint); - HttpHost target = URIUtils.extractHost(get.getURI()); - BasicAsyncRequestProducer basicAsyncRequestProducer = new BasicAsyncRequestProducer(target, get); - httpClient.start(); - log.info("sending request"); - Future futureResponse = httpClient.execute( - basicAsyncRequestProducer, - new SSEResponseConsumer(agent, actionType, path), null); - requests.put(agent.getName(), futureResponse); - futureResponse.get(); - - } finally { - httpClient.close(); - } - log.info("request finished"); - } - } - } catch (Exception e) { - log.error("cannot execute event based replication"); - } - } - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/ScheduleReplicateReplicationRule.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/ScheduleReplicateReplicationRule.java deleted file mode 100644 index cb7762d7bc6..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/ScheduleReplicateReplicationRule.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule.impl; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.commons.scheduler.ScheduleOptions; -import org.apache.sling.commons.scheduler.Scheduler; -import org.apache.sling.replication.agent.AgentReplicationException; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.rule.ReplicationRule; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * {@link org.apache.sling.replication.rule.ReplicationRule} to schedule replications on a certain {@link org.apache.sling.replication.agent.ReplicationAgent} - */ -@Component(immediate = true, label = "Rule for Scheduled Replications") -@Service(value = ReplicationRule.class) -public class ScheduleReplicateReplicationRule implements ReplicationRule { - private static final String SIGNATURE = "scheduled {action} [on ${path} ]every {seconds} sec"; - - private static final String SIGNATURE_REGEX = "(scheduled)\\s(add|delete|poll)+\\s((on)\\s(\\/\\w+)+\\s)?(every)\\s(\\d+)\\s(sec)"; - - private static final Pattern signaturePattern = Pattern.compile(SIGNATURE_REGEX); - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Reference - private Scheduler scheduler; - - public String getSignature() { - return SIGNATURE; - } - - public boolean signatureMatches(String ruleString) { - return ruleString.matches(SIGNATURE_REGEX); - } - - public void apply(String ruleString, ReplicationAgent agent) { - if (signatureMatches(ruleString)) { - Matcher matcher = signaturePattern.matcher(ruleString); - if (matcher.find()) { - String action = matcher.group(2); - ReplicationActionType actionType = ReplicationActionType.fromName(action.toUpperCase()); - String path = matcher.group(5); // can be null - int seconds = Integer.parseInt(matcher.group(7)); - ScheduleOptions options = scheduler.NOW(-1, seconds); - options.name(agent.getName() + " " + ruleString); - scheduler.schedule(new ScheduledReplication(agent, actionType, path), options); - } - } - } - - public void undo(String ruleString, ReplicationAgent agent) { - if (signatureMatches(ruleString)) { - scheduler.unschedule(agent.getName() + " " + ruleString); - } - } - - private class ScheduledReplication implements Runnable { - private final ReplicationAgent agent; - private final ReplicationActionType action; - private final String path; - - public ScheduledReplication(ReplicationAgent agent, ReplicationActionType action, String path) { - this.agent = agent; - this.action = action; - this.path = path != null ? path : "/"; - } - - public void run() { - try { - agent.send(new ReplicationRequest(System.currentTimeMillis(), action, path)); - } catch (AgentReplicationException e) { - if (log.isErrorEnabled()) { - log.error("failed scheduled replication {} on agent {} for path {}", new Object[]{ - action.name(), agent.getName(), path}, e); - } - } - } - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/TriggerPathReplicationRule.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/TriggerPathReplicationRule.java deleted file mode 100644 index 2a1b220af67..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/rule/impl/TriggerPathReplicationRule.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule.impl; - -import java.util.Dictionary; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Map; -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.api.SlingConstants; -import org.apache.sling.replication.agent.AgentReplicationException; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.rule.ReplicationRule; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.osgi.service.event.Event; -import org.osgi.service.event.EventConstants; -import org.osgi.service.event.EventHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * a rule for triggering a specific agent upon node / properties being changed under a certain path - */ -@Component(immediate = true, label = "Rule for triggering replications for changes under certain paths") -@Service(value = ReplicationRule.class) -public class TriggerPathReplicationRule implements ReplicationRule { - - // private static final Pattern p = Pattern.compile("(\\/\\w+)+\\/?"); - private static final String PREFIX = "trigger on path:"; - private static final String SIGNATURE = "trigger on path: ${path}"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private BundleContext bundleContext; - private final Map registrations = new HashMap(); - - @Activate - protected void activate(BundleContext bundleContext) { - this.bundleContext = bundleContext; - } - - @Deactivate - protected void deactivate() { - for (Map.Entry entry : registrations.entrySet()) { - if (entry.getValue() != null) { - entry.getValue().unregister(); - } - } - registrations.clear(); - } - - public String getSignature() { - return SIGNATURE; - } - - public void apply(String ruleString, ReplicationAgent agent) { - if (signatureMatches(ruleString)) { - // register an event handler on path which triggers the agent on node / property changes / addition / removals - Dictionary properties = new Hashtable(); - properties.put(EventConstants.EVENT_TOPIC, new String[]{SlingConstants.TOPIC_RESOURCE_ADDED, - SlingConstants.TOPIC_RESOURCE_CHANGED, SlingConstants.TOPIC_RESOURCE_REMOVED}); - String path = ruleString.substring(ruleString.indexOf(':') + 1).trim(); - if (log.isInfoEnabled()) { - log.info("trigger agent {} on path '{}'", agent.getName(), path); - } - properties.put(EventConstants.EVENT_FILTER, "(path=" + path + "/*)"); - if (bundleContext != null) { - ServiceRegistration triggerPathEventRegistration = bundleContext.registerService(EventHandler.class.getName(), new TriggerAgentEventListener(agent), properties); - registrations.put(agent.getName() + ruleString, triggerPathEventRegistration); - } else { - if (log.isErrorEnabled()) { - log.error("cannot register trigger since bundle context is null"); - } - } - } else { - if (log.isWarnEnabled()) { - log.warn("rule {} doesn't match signature: {}", ruleString, SIGNATURE); - } - } - - } - - public boolean signatureMatches(String ruleString) { - return ruleString.startsWith(PREFIX) && ruleString.substring(PREFIX.length() + 1).matches("\\s*(\\/\\w+)+"); - } - - public void undo(String ruleString, ReplicationAgent agent) { - if (signatureMatches(ruleString)) { - ServiceRegistration serviceRegistration = registrations.get(agent.getName() + ruleString); - if (serviceRegistration != null) { - serviceRegistration.unregister(); - } - } else { - if (log.isWarnEnabled()) { - log.warn("rule {} doesn't match signature: {}", ruleString, SIGNATURE); - } - } - } - - - private class TriggerAgentEventListener implements EventHandler { - - private final ReplicationAgent agent; - - public TriggerAgentEventListener(ReplicationAgent agent) { - this.agent = agent; - } - - public void handleEvent(Event event) { - ReplicationActionType action = SlingConstants.TOPIC_RESOURCE_REMOVED.equals(event.getTopic()) ? ReplicationActionType.DELETE : ReplicationActionType.ADD; - if (log.isInfoEnabled()) { - log.info("triggering replication from event {}", event); - } - Object eventProperty = event.getProperty("path"); - if (eventProperty != null) { - String replicatingPath = String.valueOf(eventProperty); - try { - agent.send(new ReplicationRequest(System.currentTimeMillis(), action, replicatingPath)); - } catch (AgentReplicationException e) { - if (log.isErrorEnabled()) { - log.error("triggered replication resulted in an error", e); - } - } - } - } - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackage.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackage.java deleted file mode 100644 index a6c9b479327..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackage.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; - -/** - * A replication package - */ -public interface ReplicationPackage extends Serializable { - - /** - * get package id - * @return the package id as a String - */ - String getId(); - - /** - * get the paths covered by this package - * @return an array of String paths - */ - String[] getPaths(); - - /** - * get the action this package is used for - * @return the action as a String - */ - String getAction(); - - /** - * get the type of package - * @return the package type as a String - */ - String getType(); - - /** - * creates a package stream. - * a new stream is created for each call and it is the caller's obligation to close the stream. - * @return an {@link InputStream} - * @throws IOException - */ - InputStream createInputStream() throws IOException; - - /** - * get package stream length - * @return the package length as a long - */ - long getLength(); - - - /** - * releases resources associated with this object - */ - void close(); - - /** - * releases all resources associated with the package id - */ - void delete(); - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageBuilder.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageBuilder.java deleted file mode 100644 index 8e0f1e0248b..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageBuilder.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization; - -import java.io.InputStream; - -import org.apache.sling.replication.communication.ReplicationRequest; - -/** - * A builder for {@link ReplicationPackage}s - */ -public interface ReplicationPackageBuilder { - /** - * creates a {@link ReplicationPackage} for a specific {@link ReplicationRequest} - * - * @param request the {@link ReplicationRequest} to create the package for - * @return a {@link ReplicationPackage} - * @throws ReplicationPackageBuildingException - * - */ - ReplicationPackage createPackage(ReplicationRequest request) throws ReplicationPackageBuildingException; - - /** - * reads a stream and tries to convert it to a {@link ReplicationPackage} this provider can read and install - * - * @param stream the {@link InputStream} of the package to read - * @param install if true then if the package can be read from the stream then it will try also - * to install it into the repository - * @return a {@link ReplicationPackage} if it can read it from the stream - * @throws ReplicationPackageReadingException - * when the stream cannot be read as a {@link ReplicationPackage} - */ - ReplicationPackage readPackage(InputStream stream, boolean install) throws ReplicationPackageReadingException; - - /** - * get an already created (and saved into the repository) {@link ReplicationPackage} by its id - * - * @param id a String representing the unique identifier of an already created {@link ReplicationPackage} - * @return a {@link ReplicationPackage} if one with such an id exists, null otherwise - */ - ReplicationPackage getPackage(String id); - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageBuilderProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageBuilderProvider.java deleted file mode 100644 index 735d58c36b3..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageBuilderProvider.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization; - -import java.util.Collection; - -/** - * A provider for {@link ReplicationPackageBuilder}s - */ -public interface ReplicationPackageBuilderProvider { - - /** - * get all the available {@link ReplicationPackageBuilder}s in the system - * - * @return a {@link Collection} of {@link ReplicationPackageBuilder} - */ - Collection getAvailableReplicationPackageBuilders(); - - /** - * get the {@link ReplicationPackageBuilder} with the specified name - * - * @param name the name of the {@link ReplicationPackageBuilder} as a String - * @return the {@link ReplicationPackageBuilder} with the given name, if it exists, null otherwise - */ - ReplicationPackageBuilder getReplicationPackageBuilder(String name); - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageBuildingException.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageBuildingException.java deleted file mode 100644 index 2c28cd78524..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageBuildingException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization; - -/** - * This represents an error happening while building a {@link ReplicationPackage} - */ -@SuppressWarnings("serial") -public class ReplicationPackageBuildingException extends Exception { - - public ReplicationPackageBuildingException(String message) { - super(message); - } - - public ReplicationPackageBuildingException(Throwable t) { - super(t); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageImporter.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageImporter.java deleted file mode 100644 index 509eb283b3a..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageImporter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization; - -import java.io.InputStream; - -/** - * A {@link org.apache.sling.replication.serialization.ReplicationPackage} importer - */ -public interface ReplicationPackageImporter { - - /** - * Synchronously import the stream of a {@link org.apache.sling.replication.serialization.ReplicationPackage} - * - * @param stream the InputStream of the given ReplicationPackage - * @param type the String representing the ({@link ReplicationPackage#getType() type} of the given package - * @return true if successfully imported, false otherwise - */ - boolean importStream(InputStream stream, String type); - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageReadingException.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageReadingException.java deleted file mode 100644 index 482a0fb8dbc..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/ReplicationPackageReadingException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization; - -/** - * This represents an error happening while reading / installing a - * {@link org.apache.sling.replication.serialization.ReplicationPackage} - */ -@SuppressWarnings("serial") -public class ReplicationPackageReadingException extends Exception { - - public ReplicationPackageReadingException(String message) { - super(message); - } - - public ReplicationPackageReadingException(Throwable t) { - super(t); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/AbstractReplicationPackageBuilder.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/AbstractReplicationPackageBuilder.java deleted file mode 100644 index ecb12063e43..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/AbstractReplicationPackageBuilder.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl; - -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.serialization.ReplicationPackageBuildingException; -import org.apache.sling.replication.serialization.ReplicationPackageReadingException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * base abstract implementation of a {@link ReplicationPackageBuilder} - */ -public abstract class AbstractReplicationPackageBuilder implements ReplicationPackageBuilder { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - public ReplicationPackage createPackage(ReplicationRequest request) - throws ReplicationPackageBuildingException { - ReplicationPackage replicationPackage; - if (ReplicationActionType.ADD.equals(request.getAction())) { - replicationPackage = createPackageForAdd(request); - } else if (ReplicationActionType.DELETE.equals(request.getAction())) { - replicationPackage = new VoidReplicationPackage(request, getName()); - } else if (ReplicationActionType.POLL.equals(request.getAction())) { - replicationPackage = new VoidReplicationPackage(request, getName()); // TODO : change this - } else { - throw new ReplicationPackageBuildingException("unknown action type " - + request.getAction()); - } - return replicationPackage; - } - - protected abstract ReplicationPackage createPackageForAdd(ReplicationRequest request) - throws ReplicationPackageBuildingException; - - public ReplicationPackage readPackage(InputStream stream, - boolean install) throws ReplicationPackageReadingException { - ReplicationPackage replicationPackage = null; - if (!stream.markSupported()) { - stream = new BufferedInputStream(stream); - } - try { - stream.mark(6); - byte[] buffer = new byte[6]; - int bytesRead = stream.read(buffer, 0, 6); - stream.reset(); - String s = new String(buffer); - if (log.isInfoEnabled()) { - log.info("read {} bytes as {}", bytesRead, s); - } - if (bytesRead > 0 && buffer[0] > 0 && s.startsWith("DEL")) { - replicationPackage = readPackageForDelete(stream); - } - } catch (Exception e) { - log.warn("cannot parse stream", e); - } - stream.mark(-1); - if (replicationPackage == null) { - replicationPackage = readPackageForAdd(stream, install); - } - return replicationPackage; - } - - private ReplicationPackage readPackageForDelete(InputStream stream) throws ReplicationPackageReadingException { - ReplicationPackage replicationPackage = null; - Session session = null; - try { - replicationPackage = VoidReplicationPackage.fromStream(stream); - - if(replicationPackage != null){ - session = getSession(); - for (String path : replicationPackage.getPaths()) { - if (session.itemExists(path)) { - session.removeItem(path); - } - } - session.save(); - } - } catch (Exception e) { - throw new ReplicationPackageReadingException(e); - } finally { - if (session != null) { - session.logout(); - } - } - - return replicationPackage; - } - - public ReplicationPackage getPackage(String id) { - ReplicationPackage replicationPackage = null; - try { - replicationPackage = VoidReplicationPackage.fromStream(new ByteArrayInputStream(id.getBytes())); - } - catch (IOException ex){ - // not a void package - } - - if(replicationPackage == null) { - replicationPackage = getPackageInternal(id); - } - return replicationPackage; - } - - protected abstract String getName(); - - protected abstract Session getSession() throws RepositoryException; - - protected abstract ReplicationPackage readPackageForAdd(InputStream stream, boolean install) - throws ReplicationPackageReadingException; - - - protected abstract ReplicationPackage getPackageInternal(String id); - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/DefaultReplicationPackageBuilderProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/DefaultReplicationPackageBuilderProvider.java deleted file mode 100644 index 0e4b99877ec..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/DefaultReplicationPackageBuilderProvider.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.ReferenceCardinality; -import org.apache.felix.scr.annotations.ReferencePolicy; -import org.apache.felix.scr.annotations.References; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.serialization.ReplicationPackageBuilderProvider; - -/** - * Default implementation of {@link org.apache.sling.replication.serialization.ReplicationPackageBuilderProvider} - */ -@Component(label = "Default Replication Package Builder Provider") -@References({ - @Reference(name = "replicationPackageBuilder", - referenceInterface = ReplicationPackageBuilder.class, - cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE, - policy = ReferencePolicy.DYNAMIC, - bind = "bindReplicationPackageBuilder", - unbind = "unbindReplicationPackageBuilder") - }) -@Service(value = ReplicationPackageBuilderProvider.class) -public class DefaultReplicationPackageBuilderProvider implements ReplicationPackageBuilderProvider { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final Map replicationPackageBuilders = new HashMap(); - - @Deactivate - protected void deactivate() { - replicationPackageBuilders.clear(); - } - - protected void bindReplicationPackageBuilder( - final ReplicationPackageBuilder replicationPackageBuilder, - Map properties) { - synchronized (replicationPackageBuilders) { - String name = PropertiesUtil.toString(properties.get("name"), ""); - replicationPackageBuilders.put(name, replicationPackageBuilder); - } - log.debug("Registering Replication Package Builder {} ", replicationPackageBuilder); - } - - protected void unbindReplicationPackageBuilder( - final ReplicationPackageBuilder replicationPackageBuilder, - Map properties) { - synchronized (replicationPackageBuilders) { - replicationPackageBuilders.remove(String.valueOf("name")); - } - log.debug("Unregistering Replication PackageBuilder {} ", replicationPackageBuilder); - } - - public Collection getAvailableReplicationPackageBuilders() { - return replicationPackageBuilders.values(); - } - - public ReplicationPackageBuilder getReplicationPackageBuilder(String name) { - return replicationPackageBuilders.get(name); - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/DefaultReplicationPackageImporter.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/DefaultReplicationPackageImporter.java deleted file mode 100644 index 0465a95d9b4..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/DefaultReplicationPackageImporter.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl; - -import java.io.InputStream; -import java.util.Arrays; -import java.util.Dictionary; -import java.util.Hashtable; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.replication.event.ReplicationEventFactory; -import org.apache.sling.replication.event.ReplicationEventType; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.serialization.ReplicationPackageBuilderProvider; -import org.apache.sling.replication.serialization.ReplicationPackageImporter; -import org.apache.sling.replication.serialization.ReplicationPackageReadingException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Default implementation of {@link org.apache.sling.replication.serialization.ReplicationPackageImporter} - */ -@Component(label = "Default Replication Package Importer") -@Service(value = ReplicationPackageImporter.class) -@Property(name = "name", value = DefaultReplicationPackageImporter.NAME) -public class DefaultReplicationPackageImporter implements ReplicationPackageImporter { - - public static final String NAME = "default"; - - private static final String QUEUE_NAME = "replication-package-import"; - private static final String QUEUE_TOPIC = "org/apache/sling/replication/import"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Reference - private ReplicationPackageBuilderProvider replicationPackageBuilderProvider; - - @Reference - private ReplicationEventFactory replicationEventFactory; - - - public boolean importStream(InputStream stream, String type) { - boolean success = false; - try { - ReplicationPackage replicationPackage = getReplicationPackage(stream, type, true); - - if (replicationPackage != null) { - if (log.isInfoEnabled()) { - log.info("replication package read and installed for path(s) {}", - Arrays.toString(replicationPackage.getPaths())); - } - - Dictionary dictionary = new Hashtable(); - dictionary.put("replication.action", replicationPackage.getAction()); - dictionary.put("replication.path", replicationPackage.getPaths()); - replicationEventFactory.generateEvent(ReplicationEventType.PACKAGE_INSTALLED, dictionary); - success = true; - - replicationPackage.delete(); - } else { - if (log.isWarnEnabled()) { - log.warn("could not read a replication package"); - } - } - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("cannot import a package from the given stream of type {}", type); - } - } - return success; - } - - private ReplicationPackage getReplicationPackage(InputStream stream, String type, boolean install) throws ReplicationPackageReadingException { - ReplicationPackage replicationPackage = null; - if (type != null) { - ReplicationPackageBuilder replicationPackageBuilder = replicationPackageBuilderProvider.getReplicationPackageBuilder(type); - if (replicationPackageBuilder != null) { - replicationPackage = replicationPackageBuilder.readPackage(stream, install); - } else { - if (log.isWarnEnabled()) { - log.warn("cannot read streams of type {}", type); - } - } - } else { - throw new ReplicationPackageReadingException("could not get a replication package of type 'null'"); - } - return replicationPackage; - } - - - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/ReplicationPackageAdapterFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/ReplicationPackageAdapterFactory.java deleted file mode 100644 index 57496025fba..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/ReplicationPackageAdapterFactory.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl; - -import java.io.InputStream; -import java.util.Arrays; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Properties; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.adapter.AdapterFactory; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.serialization.ReplicationPackageBuilderProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * {@link AdapterFactory} for - * {@link org.apache.sling.replication.serialization.ReplicationPackage}s - */ -@Component(label = "Adapter Factory for Replication Packages") -@Service(value = org.apache.sling.api.adapter.AdapterFactory.class) -@Properties({ - @Property(name = "adaptables", value = { "org.apache.sling.api.SlingHttpServletRequest" }), - @Property(name = "adapters", value = { "org.apache.sling.replication.serialization.ReplicationPackage" }) }) -@Deprecated -public class ReplicationPackageAdapterFactory implements AdapterFactory { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Reference - private ReplicationPackageBuilderProvider packageBuilderProvider; - - @SuppressWarnings("unchecked") - public AdapterType getAdapter(Object adaptable, Class type) { - if (log.isInfoEnabled()) { - log.info("adapting package (from {} to {})", new Object[] { adaptable, type }); - } - ReplicationPackage pkg = null; - try { - if (adaptable instanceof SlingHttpServletRequest) { - SlingHttpServletRequest request = (SlingHttpServletRequest) adaptable; - String name = request.getHeader("Type"); - ReplicationPackageBuilder replicationPackageBuilder = packageBuilderProvider - .getReplicationPackageBuilder(name); - if (log.isInfoEnabled()) { - log.info("using {} package builder", replicationPackageBuilder); - } - if (replicationPackageBuilder != null) { - InputStream stream = request.getInputStream(); - pkg = replicationPackageBuilder.readPackage(stream, true); - if (pkg != null) { - if (log.isInfoEnabled()) { - log.info("package {} created", Arrays.toString(pkg.getPaths())); - } - } else { - if (log.isWarnEnabled()) { - log.warn("could not read a package"); - } - } - } else { - if (log.isErrorEnabled()) { - log.error("could not read packages of type {}", type); - } - } - } - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("error while adapting stream to a replication package", e); - } - } - return (AdapterType) pkg; - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/VoidReplicationPackage.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/VoidReplicationPackage.java deleted file mode 100644 index 9aa82bf354f..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/VoidReplicationPackage.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.util.Arrays; -import org.apache.commons.io.IOUtils; -import org.apache.jackrabbit.vault.util.Text; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.serialization.ReplicationPackage; - -/** - * A void {@link ReplicationPackage} is used for deletion of certain paths on the target instance - */ -public class VoidReplicationPackage implements ReplicationPackage { - - private final String type; - - private final String[] paths; - - private final String id; - - private final String action; - - public VoidReplicationPackage(ReplicationRequest request, String type) { - this.type = type; - this.paths = request.getPaths(); - this.action = request.getAction().toString(); - this.id = request.getAction().toString() - + ':' + Arrays.toString(request.getPaths()) - + ':' + request.getTime() - + ':' + type; - } - - public static VoidReplicationPackage fromStream(InputStream stream) throws IOException { - String streamString = IOUtils.toString(stream); - - String[] parts = streamString.split(":"); - - if(parts.length < 4) return null; - - String actionString = parts[0]; - String pathsString = parts[1]; - String timeString = parts[2]; - String typeString = parts[3]; - - ReplicationActionType replicationActionType = ReplicationActionType.fromName(actionString); - - VoidReplicationPackage replicationPackage = null; - if(replicationActionType != null){ - pathsString = Text.unescape(pathsString); - String[] paths = pathsString.replaceAll("\\[", "").replaceAll("\\]", "").split(", "); - - ReplicationRequest request = new ReplicationRequest(Long.valueOf(timeString), - replicationActionType, paths); - replicationPackage = new VoidReplicationPackage(request, typeString); - } - - return replicationPackage; - } - - - private static final long serialVersionUID = 1L; - - public String getType() { - return type; - } - - public String[] getPaths() { - return paths; - } - - public long getLength() { - return id.getBytes().length; - } - - - public InputStream createInputStream() throws IOException { - return new ByteArrayInputStream(id.getBytes()); - } - - public String getId() { - return id; - } - - public String getAction() { - return action; - } - - public void close() { - } - - public void delete() { - - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/VoidReplicationPackageBuilder.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/VoidReplicationPackageBuilder.java deleted file mode 100644 index c3a8e584962..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/VoidReplicationPackageBuilder.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.serialization.ReplicationPackageBuildingException; -import org.apache.sling.replication.serialization.ReplicationPackageReadingException; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -@Component(metatype = false, label = "Void Replication Package Builder") -@Service(value = ReplicationPackageBuilder.class) -@Property(name = "name", value = VoidReplicationPackageBuilder.NAME) -public class VoidReplicationPackageBuilder implements ReplicationPackageBuilder { - public static final String NAME = "void"; - - public ReplicationPackage createPackage(ReplicationRequest request) throws ReplicationPackageBuildingException { - return new VoidReplicationPackage(request, "VOID"); - } - - public ReplicationPackage readPackage(InputStream stream, boolean install) throws ReplicationPackageReadingException { - try { - return VoidReplicationPackage.fromStream(stream); - } catch (Exception e) { - throw new ReplicationPackageReadingException(e); - } - } - - public ReplicationPackage getPackage(String id) { - try { - return VoidReplicationPackage.fromStream(new ByteArrayInputStream(id.getBytes())); - } - catch (IOException ex){ - return null; - } - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/vlt/FileVaultReplicationPackage.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/vlt/FileVaultReplicationPackage.java deleted file mode 100644 index d386c7a06be..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/vlt/FileVaultReplicationPackage.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl.vlt; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -import org.apache.jackrabbit.vault.fs.api.PathFilterSet; -import org.apache.jackrabbit.vault.packaging.VaultPackage; - -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.serialization.ReplicationPackage; - -/** - * a FileVault {@link ReplicationPackage} - */ -public class FileVaultReplicationPackage implements ReplicationPackage { - - private static final long serialVersionUID = 1L; - - private final String id; - - private final String[] paths; - - private final VaultPackage pkg; - - private final String action; - - public FileVaultReplicationPackage(VaultPackage pkg) { - this.pkg = pkg; - List filterSets = pkg.getMetaInf().getFilter().getFilterSets(); - String[] paths = new String[filterSets.size()]; - for (int i = 0; i < paths.length; i++) { - paths[i] = filterSets.get(i).getRoot(); - } - this.paths = paths; - this.id = pkg.getFile().getAbsolutePath(); - this.action = ReplicationActionType.ADD.toString(); - } - - public String getId() { - return id; - } - - public String[] getPaths() { - return paths; - } - - public InputStream createInputStream() throws IOException { - return new FileInputStream(pkg.getFile()); - } - - public long getLength() { - return pkg.getFile().length(); - } - - public String getType() { - return FileVaultReplicationPackageBuilder.NAME; - } - - public String getAction() { - return action; - } - - public void close() { - pkg.close(); - } - - public void delete() { - close(); - try { - File file = new File(id); - if (file.exists()) { - file.delete(); - } - } catch (Exception e) { - } - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/vlt/FileVaultReplicationPackageBuilder.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/vlt/FileVaultReplicationPackageBuilder.java deleted file mode 100644 index 537e17bf3ef..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/serialization/impl/vlt/FileVaultReplicationPackageBuilder.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl.vlt; - -import java.io.File; -import java.io.InputStream; -import java.util.Properties; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.SimpleCredentials; -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Modified; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.Service; -import org.apache.jackrabbit.vault.fs.api.PathFilterSet; -import org.apache.jackrabbit.vault.fs.config.DefaultMetaInf; -import org.apache.jackrabbit.vault.fs.config.DefaultWorkspaceFilter; -import org.apache.jackrabbit.vault.fs.io.ImportOptions; -import org.apache.jackrabbit.vault.packaging.ExportOptions; -import org.apache.jackrabbit.vault.packaging.JcrPackage; -import org.apache.jackrabbit.vault.packaging.Packaging; -import org.apache.jackrabbit.vault.packaging.VaultPackage; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.jcr.api.SlingRepository; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.serialization.ReplicationPackageBuildingException; -import org.apache.sling.replication.serialization.ReplicationPackageReadingException; -import org.apache.sling.replication.serialization.impl.AbstractReplicationPackageBuilder; -import org.osgi.service.component.ComponentContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * a {@link ReplicationPackageBuilder} based on Apache Jackrabbit FileVault. - *

- * Each {@link ReplicationPackage} created by FileVaultReplicationPackageBuilder is - * backed by a {@link VaultPackage}.  - */ -@Component(metatype = true, - label = "FileVault based Replication Package Builder", - description = "OSGi configuration based PackageBuilder service factory", - name = FileVaultReplicationPackageBuilder.SERVICE_PID) -@Service(value = ReplicationPackageBuilder.class) -@Property(name = "name", value = FileVaultReplicationPackageBuilder.NAME) -public class FileVaultReplicationPackageBuilder extends AbstractReplicationPackageBuilder implements - ReplicationPackageBuilder { - - static final String SERVICE_PID = "org.apache.sling.replication.serialization.impl.vlt.FileVaultReplicationPackageBuilder"; - - public static final String NAME = "vlt"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Property - private static final String USERNAME = "username"; - - @Property - private static final String PASSWORD = "password"; - - @Reference - private SlingRepository repository; - - @Reference - private Packaging packaging; - - - private String username; - private String password; - - protected ReplicationPackage createPackageForAdd(ReplicationRequest request) - throws ReplicationPackageBuildingException { - Session session = null; - try { - session = getSession(); - - final String[] paths = request.getPaths(); - - DefaultWorkspaceFilter filter = new DefaultWorkspaceFilter(); - DefaultMetaInf inf = new DefaultMetaInf(); - ExportOptions opts = new ExportOptions(); - for (String path : paths) { - filter.add(new PathFilterSet(path)); - } - inf.setFilter(filter); - - Properties props = new Properties(); - String packageGroup = "sling/replication"; - props.setProperty(VaultPackage.NAME_GROUP, packageGroup); - String packageName = String.valueOf(request.getTime()); - props.setProperty(VaultPackage.NAME_NAME, packageName); - if (log.isInfoEnabled()) { - log.info("assembling package {}", packageGroup + '/' + packageName); - } - inf.setProperties(props); - - opts.setMetaInf(inf); - opts.setRootPath("/"); - File tmpFile = File.createTempFile("vlt-rp-" + System.nanoTime(), ".zip"); - VaultPackage pkg = packaging.getPackageManager().assemble(session, opts, tmpFile); - return new FileVaultReplicationPackage(pkg); - } catch (Exception e) { - throw new ReplicationPackageBuildingException(e); - } finally { - if (session != null) { - session.logout(); - } - } - } - - @Override - protected String getName() { - return NAME; - } - - @Override - protected Session getSession() throws RepositoryException { - return repository.login(new SimpleCredentials(username, password.toCharArray())); - } - - @Override - protected ReplicationPackage readPackageForAdd(final InputStream stream, boolean install) - throws ReplicationPackageReadingException { - if (log.isInfoEnabled()) { - log.info("reading a stream {}", stream); - } - Session session = null; - ReplicationPackage pkg = null; - try { - log.info("reading package for addition"); - - session = getSession(); - if (session != null) { - final JcrPackage jcrPackage = packaging.getPackageManager(session).upload(stream, true, - false); - if (install) { - jcrPackage.install(new ImportOptions()); - } - pkg = new FileVaultReplicationPackage(jcrPackage.getPackage()); - } - } catch (Exception e) { - log.error("could not read / install the package", e); - throw new ReplicationPackageReadingException(e); - } finally { - if (session != null) { - session.logout(); - } - } - return pkg; - } - - @Override - protected ReplicationPackage getPackageInternal(String id) { - ReplicationPackage replicationPackage = null; - try { - File file = new File(id); - if (file.exists()) { - VaultPackage pkg = packaging.getPackageManager().open(file); - replicationPackage = new FileVaultReplicationPackage(pkg); - } - } catch (Exception e) { - log.info("could not find a package with id : {}", id); - } - return replicationPackage; - } - - @Activate - @Modified - protected void activate(ComponentContext ctx) { - username = PropertiesUtil.toString(ctx.getProperties().get(USERNAME), "").trim(); - password = PropertiesUtil.toString(ctx.getProperties().get(PASSWORD), "").trim(); - } - - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentQueueEventServlet.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentQueueEventServlet.java deleted file mode 100644 index 7cbcf208bdf..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentQueueEventServlet.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Arrays; -import java.util.Collection; -import java.util.Dictionary; -import java.util.Hashtable; -import java.util.LinkedList; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import javax.servlet.Servlet; -import javax.servlet.ServletException; -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Properties; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.SlingHttpServletResponse; -import org.apache.sling.api.servlets.SlingAllMethodsServlet; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.event.ReplicationEvent; -import org.apache.sling.replication.event.ReplicationEventType; -import org.apache.sling.replication.resources.ReplicationConstants; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.osgi.service.event.Event; -import org.osgi.service.event.EventConstants; -import org.osgi.service.event.EventHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Queue Server Sent Events servlet - */ -@SuppressWarnings("serial") -@Component(metatype = false) -@Service(value = Servlet.class) -@Properties({ - @Property(name = "sling.servlet.resourceTypes", value = ReplicationConstants.AGENT_QUEUE_EVENT_RESOURCE_TYPE), - @Property(name = "sling.servlet.methods", value = "GET") -}) -public class ReplicationAgentQueueEventServlet extends SlingAllMethodsServlet { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private static final Map> cachedEvents = new ConcurrentHashMap>(); - - private ServiceRegistration registration; - - @Activate - protected void activate(BundleContext context) { - log.info("activating SSE"); - Dictionary properties = new Hashtable(); - properties.put(EventConstants.EVENT_TOPIC, ReplicationEvent.getTopic(ReplicationEventType.PACKAGE_QUEUED)); - registration = context.registerService(EventHandler.class.getName(), new SSEListener(), properties); - if (log.isInfoEnabled()) { - log.info("SSE activated : {}", registration != null); - } - } - - @Deactivate - protected void deactivate() { - log.info("deactivating SSE"); - if (registration != null) { - registration.unregister(); - } - synchronized (cachedEvents) { - cachedEvents.clear(); - cachedEvents.notifyAll(); - } - } - - - @Override - protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { - - // setup SSE headers - response.setContentType("text/event-stream"); - response.setCharacterEncoding("UTF-8"); - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("Connection", "keep-alive"); - // needed to allow the JavaScript EventSource API to make a call from author to this server and listen for the events - response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); - response.setHeader("Access-Control-Allow-Credentials", "true"); - - String agentName = request.getResource().getParent().getParent().adaptTo(ReplicationAgent.class).getName(); - PrintWriter writer = response.getWriter(); - while (true) { - try { - synchronized (cachedEvents) { - cachedEvents.wait(); - Collection eventsForAgent = cachedEvents.get(agentName); - if (eventsForAgent != null) { - for (String event : eventsForAgent) { - writeEvent(writer, agentName + "-queue-event", event); - } - } - } - } catch (InterruptedException e) { - if (log.isErrorEnabled()) { - log.error("error during SSE", e); - } - throw new ServletException(e); - } - } - - } - - /* Write a single server-sent event to the response stream for the given event and message */ - private void writeEvent(PrintWriter writer, String event, String message) { - - // write the event type (make sure to include the double newline) - writer.write("id: " + System.nanoTime() + "\n"); - - // write the actual data - // this could be simple text or could be JSON-encoded text that the - // client then decodes - writer.write("data: " + message + "\n\n"); - - // flush the buffers to make sure the container sends the bytes - writer.flush(); - if (log.isInfoEnabled()) { - log.info("SSE event {}: {}", event, message); - } - } - - private class SSEListener implements EventHandler { - public void handleEvent(Event event) { - if (log.isInfoEnabled()) { - log.info("SSE listener running on event {}", event); - } - Object pathProperty = event.getProperty("replication.package.paths"); - Object agentNameProperty = event.getProperty("replication.agent.name"); - if (log.isInfoEnabled()) { - log.info("cached events {}", cachedEvents.size()); - } - if (pathProperty != null && agentNameProperty != null) { - String agentName = String.valueOf(agentNameProperty); - String[] paths = (String[]) pathProperty; - synchronized (cachedEvents) { - if (log.isInfoEnabled()) { - log.info("queue event for agent {} on paths {}", agentName, Arrays.toString(paths)); - } - Collection eventsForAgent = cachedEvents.get(agentName); - if (eventsForAgent == null) { - eventsForAgent = new LinkedList(); - } - eventsForAgent.add(Arrays.toString(paths)); - cachedEvents.put(agentName, eventsForAgent); - cachedEvents.notifyAll(); - } - } - } - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentQueueServlet.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentQueueServlet.java deleted file mode 100644 index 9961567cadf..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentQueueServlet.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.servlet; - -import java.io.IOException; -import javax.servlet.Servlet; -import javax.servlet.ServletException; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Properties; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.SlingHttpServletResponse; -import org.apache.sling.api.servlets.SlingAllMethodsServlet; - -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.communication.ReplicationParameter; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.resources.ReplicationConstants; - -/** - * Servlet to retrieve a {@link org.apache.sling.replication.queue.ReplicationQueue} status. - */ -@SuppressWarnings("serial") -@Component(metatype = false) -@Service(value = Servlet.class) -@Properties({ - @Property(name = "sling.servlet.resourceTypes", value = ReplicationConstants.AGENT_QUEUE_RESOURCE_TYPE), - @Property(name = "sling.servlet.methods", value = { "GET", "POST", "DELETE" } ) }) -public class ReplicationAgentQueueServlet extends SlingAllMethodsServlet { - - @Override - protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { - response.setContentType("application/json"); - - String queueName = request.getParameter(ReplicationParameter.QUEUE.toString()); - - ReplicationAgent agent = request.getResource().adaptTo(ReplicationAgent.class); - - if (agent != null) { - try { - ReplicationQueue queue = agent.getQueue(queueName); - - response.getWriter().write(toJSoN(queue)); - } catch (Exception e) { - response.getWriter().write("{\"status\" : \"error\",\"message\":\"error reading from the queue\"}"); - } - } else { - response.getWriter().write("{\"status\" : \"error\",\"message\":\"queue not found\"}"); - } - } - - - @Override - protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { - @SuppressWarnings("unchecked") - String operation = request.getParameter(":operation"); - - if("delete".equals(operation)) { - doDelete(request, response); - } - } - - - @Override - protected void doDelete(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { - ReplicationQueue queue = request.getResource().adaptTo(ReplicationQueue.class); - - while(!queue.isEmpty()){ - queue.removeHead(); - } - } - - private String toJSoN(ReplicationQueue queue) throws Exception { - StringBuilder builder = new StringBuilder("{\"name\":\"" + queue.getName() + "\",\"empty\":" + queue.isEmpty()); - if (!queue.isEmpty()) { - builder.append(",\"items\":["); - for (ReplicationQueueItem item : queue.getItems()) { - builder.append('{'); - builder.append(toJSoN(item)); - builder.append(','); - builder.append(toJSoN(queue.getStatus(item))); - builder.append("},"); - } - if (queue.getItems().size() > 0) { - builder.deleteCharAt(builder.length() - 1); - } - builder.append(']'); - } - builder.append('}'); - return builder.toString(); - } - - private String toJSoN(ReplicationQueueItemState status) { - return "\"attempts\":" + status.getAttempts() + ",\"state\":\"" + status.getItemState().name() + "\",\"entered\":\"" + status.getEntered().getTime() + "\""; - } - - private String toJSoN(ReplicationQueueItem item) { - StringBuilder builder = new StringBuilder(); - builder.append("\"id\":\"").append(item.getId().replace("\\", "\\\\")); - builder.append("\",\"paths\":["); - for (int i = 0; i < item.getPaths().length; i++) { - builder.append("\""); - builder.append(item.getPaths()[i]); - builder.append("\","); - } - builder.deleteCharAt(builder.length() - 1); - builder.append(']'); - builder.append(",\"action\":\"").append(item.getAction()); - builder.append("\",\"type\":\"").append(item.getType()); - builder.append("\""); - return builder.toString(); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentRootServlet.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentRootServlet.java deleted file mode 100644 index 5031990226d..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentRootServlet.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.servlet; - -import java.io.IOException; - -import javax.servlet.Servlet; -import javax.servlet.ServletException; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Properties; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.SlingHttpServletResponse; -import org.apache.sling.api.servlets.SlingAllMethodsServlet; -import org.apache.sling.replication.resources.ReplicationConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.apache.sling.replication.agent.AgentReplicationException; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationRequest; - -/** - * Servlet for aggregate replication on all agents - */ -@SuppressWarnings("serial") -@Component(metatype = false) -@Service(value = Servlet.class) -@Properties({ - @Property(name = "sling.servlet.resourceTypes", value = ReplicationConstants.AGENT_ROOT_RESOURCE_TYPE), - @Property(name = "sling.servlet.methods", value = {"POST" }) -}) -public class ReplicationAgentRootServlet extends SlingAllMethodsServlet { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private static final String PATH_PARAMETER = "path"; - - private static final String ACTION_PARAMETER = "action"; - - - @Override - protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { - - ReplicationAgent[] agents = request.getResource().adaptTo(ReplicationAgent[].class); - - String a = request.getParameter(ACTION_PARAMETER); - String[] paths = request.getParameterValues(PATH_PARAMETER); - - ReplicationActionType action = ReplicationActionType.fromName(a); - - - ReplicationRequest replicationRequest = new ReplicationRequest(System.currentTimeMillis(), - action, paths); - - boolean failed = false; - for (ReplicationAgent agent : agents) { - try { - agent.send(replicationRequest); - } catch (AgentReplicationException e) { - log.warn("agent {} failed", agent.getName(), e); - - response.getWriter().append("error :'").append(e.toString()).append("'"); - if (!failed) { - failed = true; - } - } - } - if (failed) { - response.setStatus(503); - response.getWriter().append("status : ").append("503"); - } - else { - response.setStatus(200); - } - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentServlet.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentServlet.java deleted file mode 100644 index cb3adc45b70..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationAgentServlet.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.servlet; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; - -import javax.servlet.Servlet; -import javax.servlet.ServletException; - -import org.apache.commons.io.IOUtils; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Properties; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.http.entity.ContentType; -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.SlingHttpServletResponse; -import org.apache.sling.api.servlets.SlingAllMethodsServlet; - -import org.apache.sling.replication.agent.AgentReplicationException; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.communication.*; -import org.apache.sling.replication.queue.ReplicationQueueItemState.ItemState; -import org.apache.sling.replication.resources.ReplicationConstants; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Servlet to ask {@link ReplicationAgent}s to replicate (via HTTP POST). - */ -@SuppressWarnings("serial") -@Component(metatype = false) -@Service(value = Servlet.class) -@Properties({ - @Property(name = "sling.servlet.resourceTypes", value = ReplicationConstants.AGENT_RESOURCE_TYPE), - @Property(name = "sling.servlet.methods", value = "POST") }) -public class ReplicationAgentServlet extends SlingAllMethodsServlet { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Override - protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { - String action = request.getHeader(ReplicationHeader.ACTION.toString()); - - if(ReplicationActionType.POLL.getName().equalsIgnoreCase(action)){ - doRemove(request, response); - } - else { - doCreate(request, response); - } - } - - private void doCreate(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws IOException { - - response.setContentType("application/json"); - - String action = request.getHeader(ReplicationHeader.ACTION.toString()); - String[] path = toStringArray(request.getHeaders(ReplicationHeader.PATH.toString())); - - ReplicationRequest replicationRequest = new ReplicationRequest(System.currentTimeMillis(), - ReplicationActionType.valueOf(action), path); - - ReplicationAgent agent = request.getResource().adaptTo(ReplicationAgent.class); - - if (agent != null) { - try { - ReplicationResponse replicationResponse = agent.execute(replicationRequest); - if (replicationResponse.isSuccessful() - || ItemState.DROPPED.toString().equals( - replicationResponse.getStatus())) { - response.setStatus(200); - } else if (ItemState.QUEUED.toString().equals(replicationResponse.getStatus()) - || ItemState.ACTIVE.toString().equals( - replicationResponse.getStatus())) { - response.setStatus(202); - } else { - response.setStatus(400); - } - response.getWriter().append(replicationResponse.toString()); - } catch (AgentReplicationException e) { - response.setStatus(503); - response.getWriter().append("{\"error\" : \"").append(e.toString()).append("\"}"); - } - } else { - response.setStatus(404); - response.getWriter().append("{\"error\" : \"agent ").append(request.getServletPath()) - .append(" not found\"}"); - } - } - - private void doRemove(SlingHttpServletRequest request, SlingHttpServletResponse response) { - - response.setContentType(ContentType.APPLICATION_OCTET_STREAM.toString()); - - String queueName = request.getParameter(ReplicationParameter.QUEUE.toString()); - - ReplicationAgent agent = request.getResource().adaptTo(ReplicationAgent.class); - - /* directly polling an agent queue is only possible if such an agent doesn't have its own endpoint - (that is it just adds items to its queue to be polled remotely)*/ - if (agent != null) { - try { - // TODO : consider using queue distribution strategy and validating who's making this request - log.info("getting item from queue {}", queueName); - - // get first item - ReplicationPackage head = agent.removeHead(queueName); - - if (head != null) { - InputStream inputStream = null; - int bytesCopied = -1; - try { - inputStream = head.createInputStream(); - bytesCopied = IOUtils.copy(inputStream, response.getOutputStream()); - } - finally { - IOUtils.closeQuietly(inputStream); - } - - setPackageHeaders(response, head); - - // delete the package permanently - head.delete(); - - log.info("{} bytes written into the response", bytesCopied); - - } else { - log.info("nothing to fetch"); - } - } catch (Exception e) { - response.setStatus(503); - log.error("error while reverse replicating from agent", e); - } - // everything ok - response.setStatus(200); - } else { - response.setStatus(404); - } - } - - String[] toStringArray(Enumeration e){ - List l = new ArrayList(); - while (e.hasMoreElements()){ - l.add(e.nextElement()); - } - - return l.toArray(new String[l.size()]); - - } - - void setPackageHeaders(SlingHttpServletResponse response, ReplicationPackage replicationPackage){ - response.setHeader(ReplicationHeader.TYPE.toString(), replicationPackage.getType()); - response.setHeader(ReplicationHeader.ACTION.toString(), replicationPackage.getAction()); - for (String path : replicationPackage.getPaths()){ - response.setHeader(ReplicationHeader.PATH.toString(), path); - } - - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationPackageImporterServlet.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationPackageImporterServlet.java deleted file mode 100644 index 455d777bc20..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/servlet/ReplicationPackageImporterServlet.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.servlet; - -import java.io.IOException; -import java.io.InputStream; -import javax.servlet.Servlet; -import javax.servlet.ServletException; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Properties; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.api.SlingHttpServletRequest; -import org.apache.sling.api.SlingHttpServletResponse; -import org.apache.sling.api.servlets.SlingAllMethodsServlet; -import org.apache.sling.replication.communication.ReplicationHeader; -import org.apache.sling.replication.resources.ReplicationConstants; -import org.apache.sling.replication.serialization.ReplicationPackageImporter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Servlet to handle reception of replication content. - */ -@SuppressWarnings("serial") -@Component(metatype = false) -@Service(value = Servlet.class) -@Properties({ - @Property(name = "sling.servlet.resourceTypes", value = ReplicationConstants.IMPORTER_RESOURCE_TYPE), - @Property(name = "sling.servlet.methods", value = "POST")}) -public class ReplicationPackageImporterServlet extends SlingAllMethodsServlet { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - @Override - protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) - throws ServletException, IOException { - - ReplicationPackageImporter replicationPackageImporter = request - .getResource() - .adaptTo(ReplicationPackageImporter.class); - - boolean success = false; - final long start = System.currentTimeMillis(); - response.setContentType("text/plain"); - response.setCharacterEncoding("utf-8"); - - InputStream stream = request.getInputStream(); - String type = request.getHeader(ReplicationHeader.TYPE.toString()); - try { - success = replicationPackageImporter.importStream(stream, type); - } catch (final Exception e) { - response.setStatus(400); - if (log.isErrorEnabled()) { - log.error("Error during replication: {}", e.getMessage(), e); - } - response.getWriter().print("error: " + e.toString()); - } finally { - final long end = System.currentTimeMillis(); - if (log.isInfoEnabled()) { - log.info("Processed replication request in {}ms: : {}", new Object[]{ - end - start, success}); - } - } - - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/ReplicationTransportException.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/ReplicationTransportException.java deleted file mode 100644 index 649948dab1b..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/ReplicationTransportException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport; - -/** - * Represents an error happened while a {@link TransportHandler} is delivering a replication item to - * and endpoint. - */ -@SuppressWarnings("serial") -public class ReplicationTransportException extends Exception { - - public ReplicationTransportException(Exception e) { - super(e); - } - - public ReplicationTransportException(String string) { - super(string); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/TransportHandler.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/TransportHandler.java deleted file mode 100644 index 735fc65cdae..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/TransportHandler.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport; - -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; - -/** - * A TransportHandler is responsible for implementing the transport of a - * {@link ReplicationPackage}s to / from another instance described by a {@link ReplicationEndpoint} - */ -public interface TransportHandler { - - /** - * Executes the transport of a given {@link ReplicationPackage} to a specific {@link ReplicationEndpoint} using this - * transport and the supplied {@link TransportAuthenticationProvider} for authenticating the endpoint - * - * @param agentName a replication agent name - * @param replicationPackage a {@link ReplicationPackage} to transport - * @throws ReplicationTransportException if any error occurs during the transport - */ - void transport(String agentName, ReplicationPackage replicationPackage) throws ReplicationTransportException; - - - /** - * Enables response processing for this TransportHandler for a certain ReplicationAgent - * - * @param agentName the name of the ReplicationAgent - * @param responseProcessor a ReplicationQueueProcessor that is called by the TransportHandler - * whenever a response is received - */ - void enableProcessing(String agentName, ReplicationQueueProcessor responseProcessor); - - /** - * - * Disables response processing for this TransportHandler - * - * @param agentName the name of the ReplicationAgent - */ - void disableProcessing(String agentName); - -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationContext.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationContext.java deleted file mode 100644 index 54e96cff2de..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationContext.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication; - -import java.util.HashMap; -import java.util.Map; - -public class TransportAuthenticationContext { - private final Map attributes = new HashMap(); - - @SuppressWarnings("unchecked") - public T getAttribute(String name, Class klass) { - T result = null; - Object object = attributes.get(name); - if (klass.isInstance(object)) { - result = (T) object; - } - return result; - } - - public void addAttribute(String name, T object) { - attributes.put(name, object); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationException.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationException.java deleted file mode 100644 index 27a1aaa63fd..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication; - - -@SuppressWarnings("serial") -public class TransportAuthenticationException extends Exception { - - public TransportAuthenticationException(String string) { - super(string); - } - - public TransportAuthenticationException(Exception e) { - super(e); - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationProvider.java deleted file mode 100644 index 563680df95f..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication; - - -/** - * A TransportAuthenticationProvider is responsible for authentication of instances sending and - * receiving replication items via {@link org.apache.sling.replication.transport.TransportHandler}s - */ -public interface TransportAuthenticationProvider { - - boolean canAuthenticate(Class authenticable); - - T authenticate(A authenticable, TransportAuthenticationContext context) - throws TransportAuthenticationException; - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationProviderFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationProviderFactory.java deleted file mode 100644 index 84eafbfa46a..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/TransportAuthenticationProviderFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication; - -import java.util.Map; - -/** - * Factory for {@link TransportAuthenticationProvider}s - */ -public interface TransportAuthenticationProviderFactory { - - TransportAuthenticationProvider createAuthenticationProvider(Map properties); - - String getType(); -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/NopTransportAuthenticationProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/NopTransportAuthenticationProvider.java deleted file mode 100644 index cc05e460029..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/NopTransportAuthenticationProvider.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication.impl; - -import org.apache.sling.replication.transport.TransportHandler; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationContext; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationException; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; - -/** - * {@link org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider} used when no authentication is required - */ -public class NopTransportAuthenticationProvider implements TransportAuthenticationProvider { - - public boolean supportsTransportHandler(TransportHandler transportHandler) { - return true; - } - - public Object authenticate(Object authenticable, TransportAuthenticationContext context) - throws TransportAuthenticationException { - return authenticable; - } - - public boolean canAuthenticate(Class authenticable) { - return true; - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/NopTransportAuthenticationProviderFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/NopTransportAuthenticationProviderFactory.java deleted file mode 100644 index 14bc906ceb7..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/NopTransportAuthenticationProviderFactory.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication.impl; - -import java.util.Map; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProviderFactory; - - -@Component(immediate = true, label = "Factory for Nop Authentication Providers") -@Service(value = TransportAuthenticationProviderFactory.class) -@Property(name = "name", value = NopTransportAuthenticationProviderFactory.TYPE) -public class NopTransportAuthenticationProviderFactory implements TransportAuthenticationProviderFactory { - public static final String TYPE = "nop"; - - private static final TransportAuthenticationProvider NOP_TRANSPORT_AUTHENTICATION_PROVIDER = new NopTransportAuthenticationProvider(); - - public TransportAuthenticationProvider createAuthenticationProvider(Map properties) { - return NOP_TRANSPORT_AUTHENTICATION_PROVIDER; - } - - public String getType() { - return TYPE; - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/RepositoryTransportAuthenticationProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/RepositoryTransportAuthenticationProvider.java deleted file mode 100644 index 2bf5b2c8f32..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/RepositoryTransportAuthenticationProvider.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication.impl; - -import javax.jcr.Credentials; -import javax.jcr.RepositoryException; -import javax.jcr.Session; -import javax.jcr.SimpleCredentials; -import org.apache.sling.jcr.api.SlingRepository; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationContext; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationException; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RepositoryTransportAuthenticationProvider implements TransportAuthenticationProvider { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final Credentials credentials; - - public RepositoryTransportAuthenticationProvider(String user, String password) { - this.credentials = new SimpleCredentials(user, password.toCharArray()); - } - - public boolean canAuthenticate(Class authenticable) { - return SlingRepository.class.isAssignableFrom(authenticable); - } - - public Session authenticate(SlingRepository authenticable, TransportAuthenticationContext context) - throws TransportAuthenticationException { - String path = context.getAttribute("path", String.class); - if (path != null) { - Session session = null; - try { - session = authenticable.login(credentials); - if (!session.nodeExists(path)) { - throw new TransportAuthenticationException("failed to read path " + path); - } else { - if (log.isInfoEnabled()) { - log.info("authenticated path {} ", path); - } - return session; - } - } catch (RepositoryException re) { - if (session != null) { - session.logout(); - } - throw new TransportAuthenticationException(re); - } - } else { - throw new TransportAuthenticationException( - "the path to authenticate is missing from the context"); - } - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/RepositoryTransportAuthenticationProviderFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/RepositoryTransportAuthenticationProviderFactory.java deleted file mode 100644 index ccb3d370be4..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/RepositoryTransportAuthenticationProviderFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication.impl; - -import java.util.Map; -import javax.jcr.Session; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.jcr.api.SlingRepository; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProviderFactory; - - -@Component(immediate = true, label = "Factory for Repository Transport Authentication Providers") -@Service(value = TransportAuthenticationProviderFactory.class) -@Property(name = "name", value = RepositoryTransportAuthenticationProviderFactory.TYPE) -public class RepositoryTransportAuthenticationProviderFactory implements TransportAuthenticationProviderFactory { - public static final String TYPE = "repo-user"; - - public TransportAuthenticationProvider createAuthenticationProvider(Map properties) { - String user = null; - Object userProp = properties.get("user"); - if (userProp != null) { - user = String.valueOf(userProp); - } - String password = null; - Object passwordProp = properties.get("password"); - if (passwordProp != null) { - password = String.valueOf(passwordProp); - } - return new RepositoryTransportAuthenticationProvider(user, password); - } - - public String getType() { - return TYPE; - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/UserCredentialsTransportAuthenticationProvider.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/UserCredentialsTransportAuthenticationProvider.java deleted file mode 100644 index 49106e32c00..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/UserCredentialsTransportAuthenticationProvider.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication.impl; - -import org.apache.http.HttpHost; -import org.apache.http.client.fluent.Executor; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationContext; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationException; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class UserCredentialsTransportAuthenticationProvider implements - TransportAuthenticationProvider { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final String username; - - private final String password; - - public UserCredentialsTransportAuthenticationProvider(String username, String password) { - this.username = username; - this.password = password; - } - - public Executor authenticate(Executor authenticable, TransportAuthenticationContext context) - throws TransportAuthenticationException { - ReplicationEndpoint endpoint = context.getAttribute("endpoint", - ReplicationEndpoint.class); - if (endpoint != null) { - Executor authenticated = authenticable.auth(new HttpHost(endpoint - .getUri().getHost()), username, password); - if (log.isInfoEnabled()) { - log.info("authenticated executor {} with user and password", authenticated); - } - return authenticated; - } else { - throw new TransportAuthenticationException( - "the endpoint to authenticate is missing from the context"); - } - } - - public boolean canAuthenticate(Class authenticable) { - return Executor.class.isAssignableFrom(authenticable); - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/UserCredentialsTransportAuthenticationProviderFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/UserCredentialsTransportAuthenticationProviderFactory.java deleted file mode 100644 index e22ece9cf24..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/authentication/impl/UserCredentialsTransportAuthenticationProviderFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication.impl; - -import java.util.Map; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.http.client.fluent.Executor; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProviderFactory; - - -@Component(immediate = true, label = "Factory for User based Transport Authentication Providers") -@Service(value = TransportAuthenticationProviderFactory.class) -@Property(name = "name", value = UserCredentialsTransportAuthenticationProviderFactory.TYPE) -public class UserCredentialsTransportAuthenticationProviderFactory implements TransportAuthenticationProviderFactory { - public static final String TYPE = "user"; - - public TransportAuthenticationProvider createAuthenticationProvider( - Map properties) { - String user = null; - Object userProp = properties.get("user"); - if (userProp != null) { - user = String.valueOf(userProp); - } - String password = null; - Object passwordProp = properties.get("password"); - if (passwordProp != null) { - password = String.valueOf(passwordProp); - } - return new UserCredentialsTransportAuthenticationProvider(user, password); - } - - public String getType() { - return TYPE; - } - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/AbstractTransportHandler.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/AbstractTransportHandler.java deleted file mode 100644 index c2b48921490..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/AbstractTransportHandler.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.transport.ReplicationTransportException; -import org.apache.sling.replication.transport.TransportHandler; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public abstract class AbstractTransportHandler implements TransportHandler { - private final ReplicationEndpoint[] endpoints; - private final TransportEndpointStrategyType endpointStrategyType; - - private int lastSuccessfulEnpointId = 0; - - - private final Map responseProcessorMap = new ConcurrentHashMap(); - - public AbstractTransportHandler(ReplicationEndpoint[] endpoints, TransportEndpointStrategyType endpointStrategyType) { - this.endpoints = endpoints; - this.endpointStrategyType = endpointStrategyType; - } - - public void transport(String agentName, ReplicationPackage replicationPackage) - throws ReplicationTransportException { - - ReplicationQueueProcessor responseProcessor = responseProcessorMap.get(agentName); - - ReplicationTransportException lastException = null; - int offset = 0; - if (endpointStrategyType.equals(TransportEndpointStrategyType.OneSuccessful)) { - offset = lastSuccessfulEnpointId; - } - - for (int i = 0; i < endpoints.length; i++) { - int currentId = (offset + i) % endpoints.length; - - ReplicationEndpoint replicationEndpoint = endpoints[currentId]; - try { - deliverPackage(replicationPackage, replicationEndpoint, responseProcessor); - lastSuccessfulEnpointId = currentId; - if (endpointStrategyType.equals(TransportEndpointStrategyType.FirstSuccessful) || - endpointStrategyType.equals(TransportEndpointStrategyType.OneSuccessful)) - break; - } catch (ReplicationTransportException ex) { - lastException = ex; - } - } - - if (lastException != null) - throw lastException; - } - - - public void enableProcessing(String agentName, ReplicationQueueProcessor responseProcessor){ - responseProcessorMap.put(agentName, responseProcessor); - } - - public void disableProcessing(String agentName){ - responseProcessorMap.remove(agentName); - } - - - private void deliverPackage(ReplicationPackage replicationPackage, - ReplicationEndpoint replicationEndpoint, - ReplicationQueueProcessor responseProcessor) - throws ReplicationTransportException { - if (!validateEndpoint(replicationEndpoint)) - throw new ReplicationTransportException("invalid endpoint " + replicationEndpoint.getUri()); - - try { - deliverPackageToEndpoint(replicationPackage, replicationEndpoint, responseProcessor); - } catch (Exception e) { - throw new ReplicationTransportException(e); - } - } - - protected abstract void deliverPackageToEndpoint(ReplicationPackage replicationPackage, - ReplicationEndpoint replicationEndpoint, - ReplicationQueueProcessor responseProcessor) - throws Exception; - - protected abstract boolean validateEndpoint(ReplicationEndpoint endpoint); - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/AbstractTransportHandlerFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/AbstractTransportHandlerFactory.java deleted file mode 100644 index 0e73ba01c4a..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/AbstractTransportHandlerFactory.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import java.util.ArrayList; -import java.util.Dictionary; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.Random; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.replication.agent.ReplicationAgentConfiguration; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.transport.TransportHandler; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProviderFactory; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; - -public abstract class AbstractTransportHandlerFactory { - - private ServiceRegistration serviceRegistration; - - protected void activate(BundleContext context, Map config) throws Exception { - - // inject configuration - Dictionary props = new Hashtable(); - - boolean enabled = PropertiesUtil.toBoolean(config.get(ReplicationAgentConfiguration.ENABLED), true); - if (enabled) { - String name = PropertiesUtil - .toString(config.get(ReplicationAgentConfiguration.NAME), String.valueOf(new Random().nextInt(1000))); - props.put(ReplicationAgentConfiguration.NAME, name); - - Map authenticationProperties = PropertiesUtil.toMap(config.get(ReplicationAgentConfiguration.AUTHENTICATION_PROPERTIES), new String[0]); - props.put(ReplicationAgentConfiguration.AUTHENTICATION_PROPERTIES, authenticationProperties); - - String[] endpoints = PropertiesUtil.toStringArray(config.get(ReplicationAgentConfiguration.ENDPOINT), new String[0]); - props.put(ReplicationAgentConfiguration.ENDPOINT, endpoints); - - String endpointStrategyName = PropertiesUtil.toString(config.get(ReplicationAgentConfiguration.ENDPOINT_STRATEGY), "All"); - props.put(ReplicationAgentConfiguration.ENDPOINT_STRATEGY, endpointStrategyName); - - TransportEndpointStrategyType transportEndpointStrategyType = TransportEndpointStrategyType.valueOf(endpointStrategyName); - - - TransportAuthenticationProviderFactory transportAuthenticationProviderFactory = getAuthenticationFactory(); - TransportAuthenticationProvider transportAuthenticationProvider = null; - if (transportAuthenticationProviderFactory != null) { - transportAuthenticationProvider = transportAuthenticationProviderFactory.createAuthenticationProvider(authenticationProperties); - } - - List replicationEndpoints = new ArrayList(); - - for (String endpoint : endpoints) { - if (endpoint != null && endpoint.length() > 0) { - replicationEndpoints.add(new ReplicationEndpoint(endpoint)); - } - } - - // register transport handler - TransportHandler transportHandler = createTransportHandler(config, - props, - transportAuthenticationProvider, - replicationEndpoints.toArray(new ReplicationEndpoint[replicationEndpoints.size()]), - transportEndpointStrategyType); - - - if (transportHandler == null) { - throw new Exception("could not create transport handler"); - } - - serviceRegistration = context.registerService(TransportHandler.class.getName(), transportHandler, props); - } - } - - protected void deactivate() { - if (serviceRegistration != null) { - serviceRegistration.unregister(); - serviceRegistration = null; - } - } - - protected abstract TransportHandler createTransportHandler(Map config, - Dictionary props, - TransportAuthenticationProvider transportAuthenticationProvider, - ReplicationEndpoint[] endpoints, - TransportEndpointStrategyType endpointStrategyType); - - protected abstract TransportAuthenticationProviderFactory getAuthenticationFactory(); - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/HttpTransportHandler.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/HttpTransportHandler.java deleted file mode 100644 index 20820e3fff2..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/HttpTransportHandler.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.apache.commons.io.IOUtils; -import org.apache.http.client.fluent.Content; -import org.apache.http.client.fluent.Executor; -import org.apache.http.client.fluent.Request; -import org.apache.http.client.fluent.Response; -import org.apache.http.entity.ContentType; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.communication.ReplicationHeader; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.transport.TransportHandler; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationContext; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * basic HTTP POST {@link TransportHandler} - */ -public class HttpTransportHandler extends AbstractTransportHandler - implements TransportHandler { - - private static final String PATH_VARIABLE_NAME = "{path}"; - - private static final Logger log = LoggerFactory.getLogger(HttpTransportHandler.class); - - private final TransportAuthenticationProvider transportAuthenticationProvider; - - private final boolean useCustomHeaders; - - private final String[] customHeaders; - - private final boolean useCustomBody; - - private final String customBody; - - public HttpTransportHandler(boolean useCustomHeaders, - String[] customHeaders, - boolean useCustomBody, - String customBody, - TransportAuthenticationProvider transportAuthenticationProvider, - ReplicationEndpoint[] replicationEndpoints, - TransportEndpointStrategyType endpointStrategyType) { - - super(replicationEndpoints, endpointStrategyType); - - this.useCustomHeaders = useCustomHeaders; - this.customHeaders = customHeaders; - this.useCustomBody = useCustomBody; - this.customBody = customBody; - this.transportAuthenticationProvider = transportAuthenticationProvider; - - } - - @Override - public void deliverPackageToEndpoint(ReplicationPackage replicationPackage, - ReplicationEndpoint replicationEndpoint, ReplicationQueueProcessor responseProcessor) throws Exception { - log.info("delivering package {} to {} using auth {}", - new Object[]{replicationPackage.getId(), - replicationEndpoint.getUri(), transportAuthenticationProvider}); - - - Executor executor = Executor.newInstance(); - TransportAuthenticationContext context = new TransportAuthenticationContext(); - context.addAttribute("endpoint", replicationEndpoint); - executor = transportAuthenticationProvider.authenticate(executor, context); - - deliverPackage(executor, replicationPackage, replicationEndpoint); - } - - @Override - protected boolean validateEndpoint(ReplicationEndpoint endpoint) { - return true; - } - - public static String[] getCustomizedHeaders(String[] additionalHeaders, String action, String[] paths){ - List headers = new ArrayList(); - - for(String additionalHeader : additionalHeaders){ - int idx = additionalHeader.indexOf("->"); - - if(idx < 0){ - headers.add(additionalHeader); - } else { - String actionSelector = additionalHeader.substring(0, idx).trim(); - String header = additionalHeader.substring(idx+2).trim(); - - if(actionSelector.equalsIgnoreCase(action) || actionSelector.equals("*")){ - headers.add(header); - } - } - } - - StringBuilder sb = new StringBuilder(); - - if(paths != null && paths.length > 0) { - sb.append(paths[0]); - for(int i=1; i < paths.length; i++){ - sb.append(", ").append(paths[i]); - } - } - - String path = sb.toString(); - - List boundHeaders = new ArrayList(); - - for(String header : headers){ - boundHeaders.add(header.replace(PATH_VARIABLE_NAME, path)); - } - - return boundHeaders.toArray(new String[boundHeaders.size()]); - } - - private void deliverPackage(Executor executor, ReplicationPackage replicationPackage, - ReplicationEndpoint replicationEndpoint) throws IOException{ - String type = replicationPackage.getType(); - - - Request req = Request.Post(replicationEndpoint.getUri()).useExpectContinue(); - - if(useCustomHeaders){ - String[] customizedHeaders = getCustomizedHeaders(customHeaders, replicationPackage.getAction(), replicationPackage.getPaths()); - for(String header : customizedHeaders){ - addHeader(req, header); - } - } - else { - req.addHeader(ReplicationHeader.TYPE.toString(), type); - } - - InputStream inputStream = null; - Response response = null; - try{ - if (useCustomBody) { - String body = customBody == null ? "" : customBody; - inputStream = new ByteArrayInputStream(body.getBytes()); - } - else { - inputStream = replicationPackage.createInputStream(); - } - - if(inputStream != null) { - req = req.bodyStream(inputStream, ContentType.APPLICATION_OCTET_STREAM); - } - - response = executor.execute(req); - } - finally { - IOUtils.closeQuietly(inputStream); - } - - if (response != null) { - Content content = response.returnContent(); - if (log.isInfoEnabled()) { - log.info("Replication content of type {} for {} delivered: {}", new Object[]{ - type, Arrays.toString(replicationPackage.getPaths()), content}); - } - } - else { - throw new IOException("response is empty"); - } - } - - private static void addHeader(Request req, String header){ - int idx = header.indexOf(":"); - if(idx < 0) return; - String headerName = header.substring(0, idx).trim(); - String headerValue = header.substring(idx+1).trim(); - req.addHeader(headerName, headerValue); - } -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/HttpTransportHandlerFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/HttpTransportHandlerFactory.java deleted file mode 100644 index 9f8104246c6..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/HttpTransportHandlerFactory.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import org.apache.felix.scr.annotations.*; -import org.apache.http.client.fluent.Executor; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.replication.agent.ReplicationAgentConfiguration; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.transport.TransportHandler; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProviderFactory; -import org.apache.sling.replication.transport.authentication.impl.UserCredentialsTransportAuthenticationProviderFactory; -import org.osgi.framework.BundleContext; - -import java.util.Dictionary; -import java.util.Map; - -@Component(metatype = true, - label = "Replication Transport Handler Factory - Http Push", - description = "OSGi configuration based HttpTransportHandler service factory", - name = HttpTransportHandlerFactory.SERVICE_PID, - configurationFactory = true, - specVersion = "1.1", - policy = ConfigurationPolicy.REQUIRE) -public class HttpTransportHandlerFactory extends AbstractTransportHandlerFactory { - static final String SERVICE_PID = "org.apache.sling.replication.transport.impl.HttpTransportHandlerFactory"; - - private static final String DEFAULT_AUTHENTICATION_FACTORY = "(name=" + UserCredentialsTransportAuthenticationProviderFactory.TYPE + ")"; - - @Property(boolValue = true) - private static final String ENABLED = "enabled"; - - @Property - private static final String NAME = "name"; - - @Property(cardinality = 1000) - private static final String ENDPOINT = ReplicationAgentConfiguration.ENDPOINT; - - @Property(options = { - @PropertyOption(name = "All", - value = "all endpoints" - ), - @PropertyOption(name = "OneSuccessful", - value = "one successful endpoint" - ), - @PropertyOption(name = "FirstSuccessful", - value = "first successful endpoint" - )}, - value = "All" - ) - private static final String ENDPOINT_STRATEGY = ReplicationAgentConfiguration.ENDPOINT_STRATEGY; - - @Property(name = ReplicationAgentConfiguration.TRANSPORT_AUTHENTICATION_FACTORY, value = DEFAULT_AUTHENTICATION_FACTORY) - @Reference(name = "TransportAuthenticationProviderFactory", target = DEFAULT_AUTHENTICATION_FACTORY, policy = ReferencePolicy.DYNAMIC) - private TransportAuthenticationProviderFactory transportAuthenticationProviderFactory; - - @Property - private static final String AUTHENTICATION_PROPERTIES = ReplicationAgentConfiguration.AUTHENTICATION_PROPERTIES; - - @Property(boolValue = false) - private static final String USE_CUSTOM_HEADERS = "useCustomHeaders"; - - @Property(cardinality = 50) - private static final String CUSTOM_HEADERS = "customHeaders"; - - @Property(boolValue = false) - private static final String USE_CUSTOM_BODY = "useCustomBody"; - - @Property - private static final String CUSTOM_BODY = "customBody"; - - protected TransportHandler createTransportHandler(Map config, - Dictionary props, - TransportAuthenticationProvider transportAuthenticationProvider, - ReplicationEndpoint[] endpoints, TransportEndpointStrategyType endpointStrategyType) { - boolean useCustomHeaders = PropertiesUtil.toBoolean(config.get(USE_CUSTOM_HEADERS), false); - props.put(USE_CUSTOM_HEADERS, useCustomHeaders); - - String[] customHeaders = PropertiesUtil.toStringArray(config.get(CUSTOM_HEADERS), new String[0]); - props.put(CUSTOM_HEADERS, customHeaders); - - boolean useCustomBody = PropertiesUtil.toBoolean(config.get(USE_CUSTOM_BODY), false); - props.put(USE_CUSTOM_BODY, useCustomBody); - - String customBody = PropertiesUtil.toString(config.get(CUSTOM_BODY), ""); - props.put(CUSTOM_BODY, customBody); - - return new HttpTransportHandler(useCustomHeaders, - customHeaders, - useCustomBody, - customBody, - (TransportAuthenticationProvider) transportAuthenticationProvider, - endpoints, - endpointStrategyType); - } - - @Override - protected TransportAuthenticationProviderFactory getAuthenticationFactory() { - return transportAuthenticationProviderFactory; - } - - @Activate - protected void activate(BundleContext context, Map config) throws Exception { - super.activate(context, config); - } - - @Deactivate - protected void deactivate() { - super.deactivate(); - } - - -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/NopTransportHandler.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/NopTransportHandler.java deleted file mode 100644 index d1ac41d5346..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/NopTransportHandler.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Service; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.transport.ReplicationTransportException; -import org.apache.sling.replication.transport.TransportHandler; - -/** - * A no-operation {@link org.apache.sling.replication.transport.TransportHandler} - */ -@Component(metatype = false, label = "Nop Transport Handler") -@Service(value = TransportHandler.class) -@Property(name = "name", value = NopTransportHandler.NAME) -public class NopTransportHandler implements TransportHandler { - public static final String NAME = "nop"; - - public void transport(String agentName, ReplicationPackage replicationPackage) throws ReplicationTransportException { - } - - public void enableProcessing(String agentName, ReplicationQueueProcessor responseProcessor) { - } - - public void disableProcessing(String agentName) { - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/PollingTransportHandler.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/PollingTransportHandler.java deleted file mode 100644 index 66b01c7271b..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/PollingTransportHandler.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import org.apache.commons.io.IOUtils; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.fluent.Executor; -import org.apache.http.client.fluent.Request; -import org.apache.http.conn.HttpHostConnectException; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.communication.ReplicationHeader; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.transport.TransportHandler; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationContext; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * basic HTTP GET {@link TransportHandler} - */ -public class PollingTransportHandler extends AbstractTransportHandler - implements TransportHandler { - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final TransportAuthenticationProvider transportAuthenticationProvider; - private final int pollItems; - - public PollingTransportHandler(int pollItems, - TransportAuthenticationProvider transportAuthenticationProvider, - ReplicationEndpoint[] replicationEndpoints){ - super(replicationEndpoints, TransportEndpointStrategyType.All); - this.pollItems = pollItems; - this.transportAuthenticationProvider = transportAuthenticationProvider; - } - - @Override - public void deliverPackageToEndpoint(ReplicationPackage replicationPackage, - ReplicationEndpoint replicationEndpoint, - ReplicationQueueProcessor responseProcessor) - throws Exception { - if (log.isDebugEnabled()) { - log.debug("polling from {}", replicationEndpoint.getUri()); - } - - Executor executor = Executor.newInstance(); - TransportAuthenticationContext context = new TransportAuthenticationContext(); - context.addAttribute("endpoint", replicationEndpoint); - executor = transportAuthenticationProvider.authenticate(executor, context); - - Request req = Request.Post(replicationEndpoint.getUri()) - .addHeader(ReplicationHeader.ACTION.toString(), ReplicationActionType.POLL.getName()) - .useExpectContinue(); - // TODO : add queue parameter - - int polls = pollItems; - - // continuously requests package streams as long as type header is received with the response (meaning there's a package of a certain type) - HttpResponse httpResponse; - try { - while ((httpResponse = executor.execute(req).returnResponse()).containsHeader(ReplicationHeader.TYPE.toString()) - && polls != 0) { - ReplicationQueueItem queueItem = readPackageHeaders(httpResponse); - - if (responseProcessor != null) - responseProcessor.process("poll", queueItem); - polls--; - } - } catch (HttpHostConnectException e) { - if (log.isWarnEnabled()) { - log.warn("could not connect to {} - skipping", replicationEndpoint.getUri()); - } - } - - } - - - ReplicationQueueItem readPackageHeaders(HttpResponse httpResponse) throws IOException { - Header typeHeader = httpResponse.getFirstHeader(ReplicationHeader.TYPE.toString()); - Header actionHeader = httpResponse.getFirstHeader(ReplicationHeader.ACTION.toString()); - Header[] pathHeaders = httpResponse.getHeaders(ReplicationHeader.PATH.toString()); - List pathList = new ArrayList(); - - for(Header pathHeader : pathHeaders){ - pathHeader.getValue(); - pathList.add(pathHeader.getValue()); - } - - HttpEntity entity = httpResponse.getEntity(); - byte[] bytes = IOUtils.toByteArray(entity.getContent()); - - - return new ReplicationQueueItem(pathList.toArray(new String[pathList.size()]), - actionHeader.getValue(), - typeHeader.getValue(), - bytes); - - } - - @Override - protected boolean validateEndpoint(ReplicationEndpoint endpoint) { - return true; - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/PollingTransportHandlerFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/PollingTransportHandlerFactory.java deleted file mode 100644 index 21dafa9b74d..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/PollingTransportHandlerFactory.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import java.util.Dictionary; -import java.util.Map; -import org.apache.felix.scr.annotations.Activate; -import org.apache.felix.scr.annotations.Component; -import org.apache.felix.scr.annotations.ConfigurationPolicy; -import org.apache.felix.scr.annotations.Deactivate; -import org.apache.felix.scr.annotations.Property; -import org.apache.felix.scr.annotations.Reference; -import org.apache.felix.scr.annotations.ReferencePolicy; -import org.apache.http.client.fluent.Executor; -import org.apache.sling.commons.osgi.PropertiesUtil; -import org.apache.sling.replication.agent.ReplicationAgentConfiguration; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.transport.TransportHandler; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProviderFactory; -import org.apache.sling.replication.transport.authentication.impl.UserCredentialsTransportAuthenticationProviderFactory; -import org.osgi.framework.BundleContext; - -@Component(metatype = true, - label = "Replication Transport Handler Factory - Http Poll", - description = "OSGi configuration based PollingTransportHandler service factory", - name = PollingTransportHandlerFactory.SERVICE_PID, - configurationFactory = true, - specVersion = "1.1", - policy = ConfigurationPolicy.REQUIRE) -public class PollingTransportHandlerFactory extends AbstractTransportHandlerFactory { - static final String SERVICE_PID = "org.apache.sling.replication.transport.impl.PollingTransportHandlerFactory"; - - private static final String DEFAULT_AUTHENTICATION_FACTORY = "(name=" + UserCredentialsTransportAuthenticationProviderFactory.TYPE + ")"; - - @Property(boolValue = true) - private static final String ENABLED = "enabled"; - - @Property - private static final String NAME = "name"; - - @Property(cardinality = 1000) - private static final String ENDPOINT = ReplicationAgentConfiguration.ENDPOINT; - - @Property(name = ReplicationAgentConfiguration.TRANSPORT_AUTHENTICATION_FACTORY, value = DEFAULT_AUTHENTICATION_FACTORY) - @Reference(name = "TransportAuthenticationProviderFactory", target = DEFAULT_AUTHENTICATION_FACTORY, policy = ReferencePolicy.DYNAMIC) - private TransportAuthenticationProviderFactory transportAuthenticationProviderFactory; - - @Property - private static final String AUTHENTICATION_PROPERTIES = ReplicationAgentConfiguration.AUTHENTICATION_PROPERTIES; - - @Property(name = "poll items", description = "number of subsequent poll requests to make", intValue = -1) - private static final String POLL_ITEMS = "poll.items"; - - - protected TransportHandler createTransportHandler(Map config, - Dictionary props, - TransportAuthenticationProvider transportAuthenticationProvider, - ReplicationEndpoint[] endpoints, TransportEndpointStrategyType endpointStrategyType) { - int pollItems = PropertiesUtil.toInteger(config.get(POLL_ITEMS), -1); - props.put(POLL_ITEMS, pollItems); - - - - return new PollingTransportHandler(pollItems, - (TransportAuthenticationProvider) transportAuthenticationProvider, - endpoints); - } - - @Override - protected TransportAuthenticationProviderFactory getAuthenticationFactory() { - return transportAuthenticationProviderFactory; - } - - @Activate - protected void activate(BundleContext context, Map config) throws Exception { - super.activate(context, config); - } - - @Deactivate - protected void deactivate() { - super.deactivate(); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/RepositoryTransportHandler.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/RepositoryTransportHandler.java deleted file mode 100644 index acfba66a7d7..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/RepositoryTransportHandler.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import java.io.InputStream; -import java.net.URI; -import java.util.Dictionary; -import java.util.Properties; -import javax.jcr.Node; -import javax.jcr.Session; -import javax.jcr.nodetype.NodeType; -import org.apache.commons.io.IOUtils; -import org.apache.jackrabbit.JcrConstants; -import org.apache.jackrabbit.util.Text; -import org.apache.sling.jcr.api.SlingRepository; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.event.ReplicationEventFactory; -import org.apache.sling.replication.event.ReplicationEventType; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.transport.TransportHandler; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationContext; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class RepositoryTransportHandler extends AbstractTransportHandler - implements TransportHandler { - - private static final String REPO_SCHEME = "repo"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private final SlingRepository repository; - private final ReplicationEventFactory replicationEventFactory; - private final TransportAuthenticationProvider transportAuthenticationProvider; - - - public RepositoryTransportHandler(SlingRepository repository, ReplicationEventFactory replicationEventFactory, - TransportAuthenticationProvider transportAuthenticationProvider, - ReplicationEndpoint[] replicationEndpoints){ - super(replicationEndpoints, TransportEndpointStrategyType.All); - - - this.repository = repository; - this.replicationEventFactory = replicationEventFactory; - this.transportAuthenticationProvider = transportAuthenticationProvider; - } - - @Override - public void deliverPackageToEndpoint(ReplicationPackage replicationPackage, ReplicationEndpoint replicationEndpoint, ReplicationQueueProcessor responseProcessor) - throws Exception { - - Session session = null; - try { - TransportAuthenticationContext transportAuthenticationContext = new TransportAuthenticationContext(); - String path = replicationEndpoint.getUri().toString().replace("repo:/", ""); - transportAuthenticationContext.addAttribute("path", path); - session = transportAuthenticationProvider.authenticate(repository, transportAuthenticationContext); - int lastSlash = replicationPackage.getId().lastIndexOf('/'); - String nodeName = Text.escape(lastSlash < 0 ? replicationPackage.getId() : replicationPackage.getId().substring(lastSlash + 1)); - log.info("creating node {} in {}", replicationPackage.getId(), nodeName); - - if (session != null) { - Node addedNode = session.getNode(path).addNode(nodeName, - NodeType.NT_FILE); - Node contentNode = addedNode.addNode(JcrConstants.JCR_CONTENT, NodeType.NT_RESOURCE); - if (contentNode != null) { - InputStream inputStream = null; - try { - inputStream = replicationPackage.createInputStream(); - contentNode.setProperty(JcrConstants.JCR_DATA, session.getValueFactory().createBinary(inputStream)); - session.save(); - } - finally { - IOUtils.closeQuietly(inputStream); - } - } - log.info("package {} delivered to the repository as node {} ", - replicationPackage.getId(), addedNode.getPath()); - - Dictionary props = new Properties(); - props.put("path", replicationPackage.getPaths()); - replicationEventFactory.generateEvent(ReplicationEventType.PACKAGE_REPLICATED, props); - - } else { - throw new Exception("could not get a Session to deliver package to the repository"); - } - } finally { - if (session != null) { - session.logout(); - } - } - } - - @Override - protected boolean validateEndpoint(ReplicationEndpoint replicationEndpoint) { - URI uri = replicationEndpoint.getUri(); - return REPO_SCHEME.equals(uri.getScheme()) && uri.getHost() != null; - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/RepositoryTransportHandlerFactory.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/RepositoryTransportHandlerFactory.java deleted file mode 100644 index 9789ca568d4..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/RepositoryTransportHandlerFactory.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import org.apache.felix.scr.annotations.*; -import org.apache.sling.jcr.api.SlingRepository; -import org.apache.sling.replication.agent.ReplicationAgentConfiguration; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.event.ReplicationEventFactory; -import org.apache.sling.replication.transport.TransportHandler; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProviderFactory; -import org.apache.sling.replication.transport.authentication.impl.RepositoryTransportAuthenticationProviderFactory; -import org.osgi.framework.BundleContext; - -import javax.jcr.Session; -import java.util.Dictionary; -import java.util.Map; - -@Component(metatype = true, - label = "Replication Transport Handler Factory - Repository", - description = "OSGi configuration based RepositoryTransportHandler service factory", - name = RepositoryTransportHandlerFactory.SERVICE_PID, - configurationFactory = true, - specVersion = "1.1", - policy = ConfigurationPolicy.REQUIRE) -public class RepositoryTransportHandlerFactory extends AbstractTransportHandlerFactory { - static final String SERVICE_PID = "org.apache.sling.replication.transport.impl.RepositoryTransportHandlerFactory"; - - private static final String DEFAULT_AUTHENTICATION_FACTORY = "(name=" + RepositoryTransportAuthenticationProviderFactory.TYPE + ")"; - - - @Property(boolValue = true) - private static final String ENABLED = "enabled"; - - @Property - private static final String NAME = "name"; - - @Property(cardinality = 1000) - private static final String ENDPOINT = ReplicationAgentConfiguration.ENDPOINT; - - @Property(name = ReplicationAgentConfiguration.TRANSPORT_AUTHENTICATION_FACTORY, value = DEFAULT_AUTHENTICATION_FACTORY) - @Reference(name = "TransportAuthenticationProviderFactory", target = DEFAULT_AUTHENTICATION_FACTORY, policy = ReferencePolicy.DYNAMIC) - private TransportAuthenticationProviderFactory transportAuthenticationProviderFactory; - - @Property - private static final String AUTHENTICATION_PROPERTIES = ReplicationAgentConfiguration.AUTHENTICATION_PROPERTIES; - - - @Reference - private SlingRepository repository; - - @Reference - private ReplicationEventFactory replicationEventFactory; - - @Override - protected TransportHandler createTransportHandler(Map config, - Dictionary props, - TransportAuthenticationProvider transportAuthenticationProvider, - ReplicationEndpoint[] endpoints, TransportEndpointStrategyType endpointStrategyType) { - - - return new RepositoryTransportHandler(repository, - replicationEventFactory, - (TransportAuthenticationProvider) transportAuthenticationProvider, - endpoints); - } - - @Override - protected TransportAuthenticationProviderFactory getAuthenticationFactory() { - return transportAuthenticationProviderFactory; - } - - @Activate - protected void activate(BundleContext context, Map config) throws Exception { - super.activate(context, config); - } - - @Deactivate - protected void deactivate() { - super.deactivate(); - } -} diff --git a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/TransportEndpointStrategyType.java b/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/TransportEndpointStrategyType.java deleted file mode 100644 index 757c7bb716e..00000000000 --- a/contrib/extensions/replication/core/src/main/java/org/apache/sling/replication/transport/impl/TransportEndpointStrategyType.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.apache.sling.replication.transport.impl; - -public enum TransportEndpointStrategyType { - FirstSuccessful, - OneSuccessful, - All -} diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-author.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-author.json deleted file mode 100644 index afe2d01f7be..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-author.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "author", - "TransportHandler.target" : "(name=http-author-receive)", - "ReplicationPackageBuilder.target" : "(name=vlt)", - "ReplicationQueueProvider.target" : "(name=sjh)", - "ReplicationQueueDistributionStrategy.target" : "(name=error)", - "rules" : ["trigger on path: /content/usergenerated"], - "enabled" : false, - "runModes" : ["publish"] -} diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-cache-flush.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-cache-flush.json deleted file mode 100644 index 71955345515..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-cache-flush.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "cache-flush", - "TransportHandler.target" : "(name=http-cache-flush)", - "useAggregatePaths" : false, - "ReplicationPackageBuilder.target" : "(name=void)", - "ReplicationQueueProvider.target" : "(name=simple)", - "ReplicationQueueDistributionStrategy.target" : "(name=single)", - "rules" : ["trigger on path: /content/usergenerated"], - "enabled" : false, - "runModes" : ["publish"] -} diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-publish-reverse.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-publish-reverse.json deleted file mode 100644 index 9ebf2a9779a..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-publish-reverse.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "publish-reverse", - "TransportHandler.target" : "(name=http-publish-poll)", - "ReplicationPackageBuilder.target" : "(name=vlt)", - "ReplicationQueueProvider.target" : "(name=sjh)", - "ReplicationQueueDistributionStrategy.target" : "(name=error)", - "rules" : ["scheduled poll every 30 sec"], - "runModes" : ["author"] -} diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-publish.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-publish.json deleted file mode 100644 index 750521548a3..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-publish.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "publish", - "TransportHandler.target" : "(name=http-publish-receive)", - "ReplicationPackageBuilder.target" : "(name=vlt)", - "ReplicationQueueProvider.target" : "(name=sjh)", - "ReplicationQueueDistributionStrategy.target" : "(name=single)", - "runModes" : ["author"] -} diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-reverserepo.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-reverserepo.json deleted file mode 100644 index 29b9baff2d8..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory-reverserepo.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "reverserepo", - "ReplicationPackageBuilder.target" : "(name=vlt)", - "ReplicationQueueProvider.target" : "(name=sjh)", - "ReplicationQueueDistributionStrategy.target" : "(name=error)", - "rules" : ["trigger on path: /content/usergenerated"], - "runModes" : ["publish"] -} diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.serialization.impl.vlt.FileVaultReplicationPackageBuilder.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.serialization.impl.vlt.FileVaultReplicationPackageBuilder.json deleted file mode 100644 index 3e8a1a77af0..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.serialization.impl.vlt.FileVaultReplicationPackageBuilder.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "vlt", - "username" : "admin", - "password" : "admin" -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.HttpTransportHandlerFactory-http-author-receive.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.HttpTransportHandlerFactory-http-author-receive.json deleted file mode 100644 index 6840be6a737..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.HttpTransportHandlerFactory-http-author-receive.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "http-author-receive", - "TransportAuthenticationProviderFactory.target" : "(name=user)", - "authentication.properties" : ["user=admin","password=admin"], - "endpoints" : [ "http://localhost:4502/system/replication/receive" ] -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.HttpTransportHandlerFactory-http-cache-flush.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.HttpTransportHandlerFactory-http-cache-flush.json deleted file mode 100644 index 81897a73fce..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.HttpTransportHandlerFactory-http-cache-flush.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "http-cache-flush", - "useCustomHeaders" : true, - "customHeaders" : [ - "Path: {path}", - "add -> Action : REFRESH", - "delete -> Change : REMOVE" ], - "useCustomBody": true, - "customBody" : "", - "TransportAuthenticationProviderFactory.target" : "(name=nop)", - "endpoints" : [ "http://localhost:8000/invalidatecache" ] -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.HttpTransportHandlerFactory-http-publish-receive.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.HttpTransportHandlerFactory-http-publish-receive.json deleted file mode 100644 index 74fb8b73ef3..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.HttpTransportHandlerFactory-http-publish-receive.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "http-publish-receive", - "TransportAuthenticationProviderFactory.target" : "(name=user)", - "authentication.properties" : ["user=admin","password=admin"], - "endpoints" : [ "http://localhost:4503/system/replication/importer/default" ] -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.PollingTransportHandlerFactory-http-publish-poll.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.PollingTransportHandlerFactory-http-publish-poll.json deleted file mode 100644 index 4326b244d54..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/org.apache.sling.replication.transport.impl.PollingTransportHandlerFactory-http-publish-poll.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "http-publish-poll", - "poll.items" : 10, - "TransportAuthenticationProviderFactory.target" : "(name=user)", - "authentication.properties" : ["user=admin","password=admin"], - "endpoints" : [ "http://localhost:4503/system/replication/agent/reverserepo" ] -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/resourceproviders/org.apache.sling.replication.resources.impl.OsgiPropertiesResourceProviderFactory-replicationAgents.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/resourceproviders/org.apache.sling.replication.resources.impl.OsgiPropertiesResourceProviderFactory-replicationAgents.json deleted file mode 100644 index f1cca94cbb2..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/resourceproviders/org.apache.sling.replication.resources.impl.OsgiPropertiesResourceProviderFactory-replicationAgents.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "replicationAgents", - "provider.roots" : [ "/libs/sling/replication/agent" ], - "serviceType" : "org.apache.sling.replication.agent.ReplicationAgent", - "resourceProperties" : [ - "../sling:resourceType=replication/agents", - - "sling:resourceType=replication/agent", - "name={name}", - - "queue/sling:resourceType=replication/agent/queue" - ] -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/resourceproviders/org.apache.sling.replication.resources.impl.OsgiPropertiesResourceProviderFactory-replicationAgentsConfig.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/resourceproviders/org.apache.sling.replication.resources.impl.OsgiPropertiesResourceProviderFactory-replicationAgentsConfig.json deleted file mode 100644 index c2d6ee341c1..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/resourceproviders/org.apache.sling.replication.resources.impl.OsgiPropertiesResourceProviderFactory-replicationAgentsConfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "replicationAgentsConfig", - "provider.roots" : [ "/libs/sling/replication/config/agent" ], - "serviceType" : "org.apache.sling.replication.agent.impl.ReplicationAgentServiceFactory", - "providerType" : "osgiConfig", - "resourceProperties" : [ - "../sling:resourceType=replication/config/agents", - - "sling:resourceType=replication/config/agent", - "name={name}", - "runModes={runModes}", - "queueProvider={ReplicationQueueProvider.target}", - "packageBuilder={ReplicationPackageBuilder.target}", - "queueStrategy={ReplicationQueueDistributionStrategy.target}", - "transportHandler={TransportHandler.target}" - ] - - -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/resourceproviders/org.apache.sling.replication.resources.impl.OsgiPropertiesResourceProviderFactory-replicationImporters.json b/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/resourceproviders/org.apache.sling.replication.resources.impl.OsgiPropertiesResourceProviderFactory-replicationImporters.json deleted file mode 100644 index 2e9dbd67755..00000000000 --- a/contrib/extensions/replication/core/src/main/resources/SLING-CONTENT/libs/sling/replication/config/resourceproviders/org.apache.sling.replication.resources.impl.OsgiPropertiesResourceProviderFactory-replicationImporters.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "jcr:primaryType" : "sling:OsgiConfig", - "name" : "replicationImporters", - "provider.roots" : [ "/libs/sling/replication/importer" ], - "serviceType" : "org.apache.sling.replication.serialization.ReplicationPackageImporter", - "resourceProperties" : [ - "../sling:resourceType=replication/importers", - - "sling:resourceType=replication/importer", - "name={name}" - ] -} \ No newline at end of file diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/ReplicationAgentConfigurationTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/ReplicationAgentConfigurationTest.java deleted file mode 100644 index 949993ab632..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/ReplicationAgentConfigurationTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent; - -import java.util.Properties; -import org.junit.Test; - -import static org.junit.Assert.assertNotNull; - -/** - * Testcase for {@link ReplicationAgentConfiguration} - */ -public class ReplicationAgentConfigurationTest { - @Test - public void testNullsWithDefaultConfiguration() throws Exception { - ReplicationAgentConfiguration replicationAgentConfiguration = new ReplicationAgentConfiguration(new Properties(), null); - assertNotNull(replicationAgentConfiguration.getAuthenticationProperties()); - assertNotNull(replicationAgentConfiguration.getEndpoint()); - assertNotNull(replicationAgentConfiguration.getName()); - assertNotNull(replicationAgentConfiguration.getTargetAuthenticationHandlerFactory()); - assertNotNull(replicationAgentConfiguration.getTargetReplicationPackageBuilder()); - assertNotNull(replicationAgentConfiguration.getTargetReplicationQueueProvider()); - assertNotNull(replicationAgentConfiguration.getTargetReplicationQueueDistributionStrategy()); - assertNotNull(replicationAgentConfiguration.getTargetTransportHandler()); - } - -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/DefaultReplicationAgentConfigurationManagerTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/DefaultReplicationAgentConfigurationManagerTest.java deleted file mode 100644 index 3a38015e56f..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/DefaultReplicationAgentConfigurationManagerTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent.impl; - -import java.lang.reflect.Field; -import java.util.Properties; - -import org.junit.Test; -import org.osgi.service.cm.Configuration; -import org.osgi.service.cm.ConfigurationAdmin; - -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link DefaultReplicationAgentConfigurationManager} - */ -public class DefaultReplicationAgentConfigurationManagerTest { - - @Test - public void testRetrievalWithNoConfigurationAvailable() throws Exception { - ConfigurationAdmin configAdmin = mock(ConfigurationAdmin.class); - - DefaultReplicationAgentConfigurationManager defaultReplicationAgentConfigurationManager = new DefaultReplicationAgentConfigurationManager(); - Field configAdminField = defaultReplicationAgentConfigurationManager.getClass().getDeclaredField("configAdmin"); - configAdminField.setAccessible(true); - configAdminField.set(defaultReplicationAgentConfigurationManager, configAdmin); - - try { - defaultReplicationAgentConfigurationManager.getConfiguration("fake"); - fail("an exception should be thrown when no configuration is available"); - } catch (Exception e) { - // failure is expected - } - } - - @Test - public void testRetrievalWithMultipleConfigurationsAvailable() throws Exception { - ConfigurationAdmin configAdmin = mock(ConfigurationAdmin.class); - - when(configAdmin.listConfigurations("(name=publish)")).thenReturn(new Configuration[]{null, null}); - DefaultReplicationAgentConfigurationManager defaultReplicationAgentConfigurationManager = new DefaultReplicationAgentConfigurationManager(); - Field configAdminField = defaultReplicationAgentConfigurationManager.getClass().getDeclaredField("configAdmin"); - configAdminField.setAccessible(true); - configAdminField.set(defaultReplicationAgentConfigurationManager, configAdmin); - - try { - defaultReplicationAgentConfigurationManager.getConfiguration("publish"); - fail("an exception should be thrown when multiple configurations are available"); - } catch (Exception e) { - // failure is expected - } - } - - @Test - public void testRetrievalWithOneConfigurationAvailable() throws Exception { - Configuration configuration = mock(Configuration.class); - when(configuration.getProperties()).thenReturn(new Properties()); - ConfigurationAdmin configAdmin = mock(ConfigurationAdmin.class); - - when(configAdmin.listConfigurations("(name=publish)")).thenReturn(new Configuration[]{configuration}); - DefaultReplicationAgentConfigurationManager defaultReplicationAgentConfigurationManager = new DefaultReplicationAgentConfigurationManager(); - Field configAdminField = defaultReplicationAgentConfigurationManager.getClass().getDeclaredField("configAdmin"); - configAdminField.setAccessible(true); - configAdminField.set(defaultReplicationAgentConfigurationManager, configAdmin); - defaultReplicationAgentConfigurationManager.getConfiguration("publish"); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/ReplicationAgentJobConsumerTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/ReplicationAgentJobConsumerTest.java deleted file mode 100644 index 523d2a6be48..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/ReplicationAgentJobConsumerTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.apache.sling.replication.agent.impl; - -import org.apache.sling.event.jobs.Job; -import org.apache.sling.event.jobs.consumer.JobConsumer; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueProcessor; -import org.apache.sling.replication.queue.impl.jobhandling.ReplicationAgentJobConsumer; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link org.apache.sling.replication.queue.impl.jobhandling.ReplicationAgentJobConsumer} - */ -public class ReplicationAgentJobConsumerTest { - - @Test - public void testJobWithSuccessfulAgent() throws Exception { - ReplicationQueueProcessor queueProcessor = mock(ReplicationQueueProcessor.class); - when(queueProcessor.process(anyString(), any(ReplicationQueueItem.class))).thenReturn(true); - - ReplicationAgentJobConsumer replicationAgentJobConsumer = new ReplicationAgentJobConsumer(queueProcessor); - Job job = mock(Job.class); - JobConsumer.JobResult jobResult = replicationAgentJobConsumer.process(job); - assertEquals(JobConsumer.JobResult.OK, jobResult); - } - - @Test - public void testJobWithUnsuccessfulAgent() throws Exception { - ReplicationQueueProcessor queueProcessor = mock(ReplicationQueueProcessor.class); - when(queueProcessor.process(anyString(), any(ReplicationQueueItem.class))).thenReturn(false); - - ReplicationAgentJobConsumer replicationAgentJobConsumer = new ReplicationAgentJobConsumer(queueProcessor); - Job job = mock(Job.class); - JobConsumer.JobResult jobResult = replicationAgentJobConsumer.process(job); - assertEquals(JobConsumer.JobResult.FAILED, jobResult); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/ReplicationAgentServiceFactoryTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/ReplicationAgentServiceFactoryTest.java deleted file mode 100644 index 5ecfc28de68..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/ReplicationAgentServiceFactoryTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent.impl; - -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; -import org.apache.sling.replication.agent.AgentConfigurationException; -import org.apache.sling.replication.queue.ReplicationQueueDistributionStrategy; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.transport.TransportHandler; -import org.junit.Test; -import org.osgi.framework.BundleContext; - -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; - -/** - * Testcase for {@link ReplicationAgentServiceFactory} - */ -public class ReplicationAgentServiceFactoryTest { - - @Test - public void testActivationWithAllServicesAndPropertiesBound() throws Exception { - ReplicationAgentServiceFactory serviceFactory = new ReplicationAgentServiceFactory(); - - Field packageBuilderField = serviceFactory.getClass().getDeclaredField("packageBuilder"); - packageBuilderField.setAccessible(true); - ReplicationPackageBuilder packageBuilder = mock(ReplicationPackageBuilder.class); - packageBuilderField.set(serviceFactory, packageBuilder); - - Field distributionField = serviceFactory.getClass().getDeclaredField("queueDistributionStrategy"); - distributionField.setAccessible(true); - ReplicationQueueDistributionStrategy distributionStrategy = mock(ReplicationQueueDistributionStrategy.class); - distributionField.set(serviceFactory, distributionStrategy); - - Field queueField = serviceFactory.getClass().getDeclaredField("queueProvider"); - queueField.setAccessible(true); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - queueField.set(serviceFactory, queueProvider); - - Field transportField = serviceFactory.getClass().getDeclaredField("transportHandler"); - transportField.setAccessible(true); - TransportHandler transportHandler = mock(TransportHandler.class); - transportField.set(serviceFactory, transportHandler); - - - Map dictionary = new HashMap(); - dictionary.put("endpoint", "http://somewhere.com"); - dictionary.put("name", "agent1"); - BundleContext context = mock(BundleContext.class); - serviceFactory.activate(context, dictionary); - } - - @Test - public void testActivationWithNoServicesBound() throws Exception { - try { - ReplicationAgentServiceFactory serviceFactory = new ReplicationAgentServiceFactory(); - Map dictionary = new HashMap(); - BundleContext context = mock(BundleContext.class); - serviceFactory.activate(context, dictionary); - fail("missing / incomplete configuration should trigger agent configuration exception"); - } catch (AgentConfigurationException e) { - // expected - } - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/SimpleReplicationAgentTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/SimpleReplicationAgentTest.java deleted file mode 100644 index 57db6af5aa6..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/agent/impl/SimpleReplicationAgentTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.agent.impl; - -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.communication.ReplicationResponse; -import org.apache.sling.replication.event.ReplicationEventFactory; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueDistributionStrategy; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.apache.sling.replication.queue.impl.simple.SimpleReplicationQueue; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.transport.TransportHandler; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link SimpleReplicationAgent} - */ -public class SimpleReplicationAgentTest { - - @Test - public void testSyncReplicationWithFailingDistributionStrategy() throws Exception { - String name = "sample-agent"; - TransportHandler transportHandler = mock(TransportHandler.class); - ReplicationPackageBuilder packageBuilder = mock(ReplicationPackageBuilder.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueueDistributionStrategy distributionHandler = mock(ReplicationQueueDistributionStrategy.class); - ReplicationEventFactory replicationEventFactory = mock(ReplicationEventFactory.class); - SimpleReplicationAgent agent = new SimpleReplicationAgent(name, new String[0], true, - transportHandler, packageBuilder, queueProvider, distributionHandler, replicationEventFactory, null); - ReplicationRequest request = new ReplicationRequest(System.nanoTime(), - ReplicationActionType.ADD, "/"); - ReplicationPackage replicationPackage = mock(ReplicationPackage.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/"}); - when(packageBuilder.createPackage(request)).thenReturn(replicationPackage); - when(queueProvider.getDefaultQueue(agent.getName())).thenReturn( - new SimpleReplicationQueue(agent.getName(), "name")); - ReplicationResponse response = agent.execute(request); - assertNotNull(response); - assertEquals("ERROR", response.getStatus()); - } - - @Test - public void testSyncReplicationWithWorkingDistributionStrategy() throws Exception { - String name = "sample-agent"; - TransportHandler transportHandler = mock(TransportHandler.class); - ReplicationPackageBuilder packageBuilder = mock(ReplicationPackageBuilder.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueueDistributionStrategy distributionHandler = mock(ReplicationQueueDistributionStrategy.class); - ReplicationEventFactory replicationEventFactory = mock(ReplicationEventFactory.class); - SimpleReplicationAgent agent = new SimpleReplicationAgent(name, new String[0], true, - transportHandler, packageBuilder, queueProvider, distributionHandler, replicationEventFactory, null); - ReplicationRequest request = new ReplicationRequest(System.nanoTime(), - ReplicationActionType.ADD, "/"); - ReplicationPackage replicationPackage = mock(ReplicationPackage.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/"}); - ReplicationQueueItemState state = new ReplicationQueueItemState(); - state.setItemState(ReplicationQueueItemState.ItemState.SUCCEEDED); - when(distributionHandler.add(any(String.class), any(ReplicationQueueItem.class), eq(queueProvider))).thenReturn(state); - when(packageBuilder.createPackage(any(ReplicationRequest.class))).thenReturn(replicationPackage); - when(queueProvider.getDefaultQueue(agent.getName())).thenReturn( - new SimpleReplicationQueue(agent.getName(), "name")); - ReplicationResponse response = agent.execute(request); - assertNotNull(response); - assertEquals("SUCCEEDED", response.getStatus()); - } - - @Test - public void testAsyncReplication() throws Exception { - String name = "sample-agent"; - TransportHandler transportHandler = mock(TransportHandler.class); - ReplicationPackageBuilder packageBuilder = mock(ReplicationPackageBuilder.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueueDistributionStrategy distributionHandler = mock(ReplicationQueueDistributionStrategy.class); - ReplicationEventFactory replicationEventFactory = mock(ReplicationEventFactory.class); - SimpleReplicationAgent agent = new SimpleReplicationAgent(name, new String[0], true, - transportHandler, packageBuilder, queueProvider, distributionHandler, replicationEventFactory, null); - ReplicationRequest request = new ReplicationRequest(System.nanoTime(), - ReplicationActionType.ADD, "/"); - ReplicationPackage replicationPackage = mock(ReplicationPackage.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/"}); - when(packageBuilder.createPackage(request)).thenReturn(replicationPackage); - when(queueProvider.getDefaultQueue(agent.getName())).thenReturn( - new SimpleReplicationQueue(agent.getName(), "name")); - agent.send(request); - } - - @Test - public void testGetDefaultQueue() throws Exception { - String name = "sample-agent"; - TransportHandler transportHandler = mock(TransportHandler.class); - ReplicationPackageBuilder packageBuilder = mock(ReplicationPackageBuilder.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueueDistributionStrategy distributionHandler = mock(ReplicationQueueDistributionStrategy.class); - SimpleReplicationAgent agent = new SimpleReplicationAgent(name, new String[0], true, - transportHandler, packageBuilder, queueProvider, distributionHandler, null, null); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue(agent.getName())).thenReturn(queue); - assertNotNull(agent.getQueue(null)); - } - - @Test - public void testGetExistingNamedQueue() throws Exception { - String name = "sample-agent"; - TransportHandler transportHandler = mock(TransportHandler.class); - ReplicationPackageBuilder packageBuilder = mock(ReplicationPackageBuilder.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueueDistributionStrategy distributionHandler = mock(ReplicationQueueDistributionStrategy.class); - SimpleReplicationAgent agent = new SimpleReplicationAgent(name, new String[0], true, - transportHandler, packageBuilder, queueProvider, distributionHandler, null, null); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getQueue(agent.getName(), "priority")).thenReturn(queue); - assertNotNull(agent.getQueue("priority")); - } - - @Test - public void testGetNonExistingNamedQueue() throws Exception { - String name = "sample-agent"; - TransportHandler transportHandler = mock(TransportHandler.class); - ReplicationPackageBuilder packageBuilder = mock(ReplicationPackageBuilder.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueueDistributionStrategy distributionHandler = mock(ReplicationQueueDistributionStrategy.class); - SimpleReplicationAgent agent = new SimpleReplicationAgent(name, new String[0], true, - transportHandler, packageBuilder, queueProvider, distributionHandler, null, null); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getQueue(agent.getName(), "priority")).thenReturn(queue); - assertNull(agent.getQueue("weird")); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/monitor/ReplicationQueueHealthCheckTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/monitor/ReplicationQueueHealthCheckTest.java deleted file mode 100644 index f413014ab07..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/monitor/ReplicationQueueHealthCheckTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.monitor; - -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import org.apache.sling.hc.api.Result; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link org.apache.sling.replication.monitor.ReplicationQueueHealthCheck} - */ -public class ReplicationQueueHealthCheckTest { - - @Test - public void testWithNoReplicationQueueProvider() throws Exception { - ReplicationQueueHealthCheck replicationQueueHealthCheck = new ReplicationQueueHealthCheck(); - replicationQueueHealthCheck.activate(Collections.emptyMap()); - Result result = replicationQueueHealthCheck.execute(); - assertNotNull(result); - assertTrue(result.isOk()); - } - - @Test - public void testWithNoItemInTheQueue() throws Exception { - ReplicationQueueHealthCheck replicationQueueHealthCheck = new ReplicationQueueHealthCheck(); - - replicationQueueHealthCheck.activate(Collections.emptyMap()); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queue.getHead()).thenReturn(null); - ReplicationQueueProvider replicationQueueProvider = mock(ReplicationQueueProvider.class); - Collection providers = new LinkedList(); - providers.add(queue); - when(replicationQueueProvider.getAllQueues()).thenReturn(providers); - replicationQueueHealthCheck.bindReplicationQueueProvider(replicationQueueProvider); - - Result result = replicationQueueHealthCheck.execute(); - assertNotNull(result); - assertTrue(result.isOk()); - } - - @Test - public void testWithOneOkItemInTheQueue() throws Exception { - ReplicationQueueHealthCheck replicationQueueHealthCheck = new ReplicationQueueHealthCheck(); - - replicationQueueHealthCheck.activate(Collections.emptyMap()); - ReplicationQueue queue = mock(ReplicationQueue.class); - ReplicationQueueItem item = mock(ReplicationQueueItem.class); - ReplicationQueueItemState status = mock(ReplicationQueueItemState.class); - when(status.getAttempts()).thenReturn(1); - when(queue.getStatus(item)).thenReturn(status); - when(queue.getHead()).thenReturn(item); - ReplicationQueueProvider replicationQueueProvider = mock(ReplicationQueueProvider.class); - Collection providers = new LinkedList(); - providers.add(queue); - when(replicationQueueProvider.getAllQueues()).thenReturn(providers); - replicationQueueHealthCheck.bindReplicationQueueProvider(replicationQueueProvider); - - Result result = replicationQueueHealthCheck.execute(); - assertNotNull(result); - assertTrue(result.isOk()); - } - - @Test - public void testWithNotOkItemInTheQueue() throws Exception { - ReplicationQueueHealthCheck replicationQueueHealthCheck = new ReplicationQueueHealthCheck(); - - replicationQueueHealthCheck.activate(Collections.emptyMap()); - ReplicationQueue queue = mock(ReplicationQueue.class); - ReplicationQueueItem item = mock(ReplicationQueueItem.class); - ReplicationQueueItemState status = mock(ReplicationQueueItemState.class); - when(status.getAttempts()).thenReturn(10); - when(queue.getStatus(item)).thenReturn(status); - when(queue.getHead()).thenReturn(item); - ReplicationQueueProvider replicationQueueProvider = mock(ReplicationQueueProvider.class); - Collection providers = new LinkedList(); - providers.add(queue); - when(replicationQueueProvider.getAllQueues()).thenReturn(providers); - replicationQueueHealthCheck.bindReplicationQueueProvider(replicationQueueProvider); - - Result result = replicationQueueHealthCheck.execute(); - assertNotNull(result); - assertFalse(result.isOk()); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/ErrorAwareQueueDistributionStrategyTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/ErrorAwareQueueDistributionStrategyTest.java deleted file mode 100644 index 1521c73ce12..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/ErrorAwareQueueDistributionStrategyTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl; - -import java.util.Dictionary; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.junit.Test; -import org.osgi.service.component.ComponentContext; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link org.apache.sling.replication.queue.impl.ErrorAwareQueueDistributionStrategy} - */ -public class ErrorAwareQueueDistributionStrategyTest { - - @Test - public void testPackageAdditionWithSucceedingItemDelivery() throws Exception { - ErrorAwareQueueDistributionStrategy errorAwareDistributionStrategy = new ErrorAwareQueueDistributionStrategy(); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(state.isSuccessful()).thenReturn(true); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = errorAwareDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - assertTrue(returnedState.isSuccessful()); - } - - @Test - public void testPackageAdditionWithFailingItemDelivery() throws Exception { - ErrorAwareQueueDistributionStrategy errorAwareDistributionStrategy = new ErrorAwareQueueDistributionStrategy(); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(state.isSuccessful()).thenReturn(false); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = errorAwareDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - assertFalse(returnedState.isSuccessful()); - } - - @Test - public void testPackageAdditionWithMultipleFailingItemsDeliveryAndErrorQueue() throws Exception { - ErrorAwareQueueDistributionStrategy errorAwareDistributionStrategy = new ErrorAwareQueueDistributionStrategy(); - ComponentContext context = mock(ComponentContext.class); - Dictionary properties = mock(Dictionary.class); - when(properties.get("attempts.threshold")).thenReturn(new String[]{"1"}); - when(properties.get("stuck.handling")).thenReturn(new String[]{"ERROR"}); - when(context.getProperties()).thenReturn(properties); - errorAwareDistributionStrategy.activate(context); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - when(queue.getHead()).thenReturn(replicationPackage); - ReplicationQueue errorQueue = mock(ReplicationQueue.class); - when(errorQueue.add(replicationPackage)).thenReturn(true); - when(queueProvider.getQueue("agentName", "-error")).thenReturn(errorQueue); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(state.isSuccessful()).thenReturn(false); - when(state.getAttempts()).thenReturn(2); - when(queue.getStatus(any(ReplicationQueueItem.class))).thenReturn(state); - ReplicationQueueItemState returnedState = errorAwareDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - assertFalse(returnedState.isSuccessful()); - } - - @Test - public void testPackageAdditionWithMultipleFailingItemsDeliveryAndDropFromQueue() throws Exception { - ErrorAwareQueueDistributionStrategy errorAwareDistributionStrategy = new ErrorAwareQueueDistributionStrategy(); - ComponentContext context = mock(ComponentContext.class); - Dictionary properties = mock(Dictionary.class); - when(properties.get("attempts.threshold")).thenReturn(new String[]{"1"}); - when(properties.get("stuck.handling")).thenReturn(new String[]{"DROP"}); - when(context.getProperties()).thenReturn(properties); - errorAwareDistributionStrategy.activate(context); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - when(queue.getHead()).thenReturn(replicationPackage); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(state.isSuccessful()).thenReturn(false); - when(state.getAttempts()).thenReturn(2); - when(queue.getStatus(any(ReplicationQueueItem.class))).thenReturn(state); - ReplicationQueueItemState returnedState = errorAwareDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - assertFalse(returnedState.isSuccessful()); - } - - @Test - public void testPackageAdditionWithNullItemStateFromTheQueue() throws Exception { - ErrorAwareQueueDistributionStrategy errorAwareDistributionStrategy = new ErrorAwareQueueDistributionStrategy(); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState returnedState = errorAwareDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNull(returnedState); - } - - @Test - public void testPackageAdditionWithNotNullItemStateFromTheQueue() throws Exception { - ErrorAwareQueueDistributionStrategy errorAwareDistributionStrategy = new ErrorAwareQueueDistributionStrategy(); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = errorAwareDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/PriorityPathQueueDistributionStrategyTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/PriorityPathQueueDistributionStrategyTest.java deleted file mode 100644 index 138b7dec829..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/PriorityPathQueueDistributionStrategyTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl; - -import java.util.Dictionary; - -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.junit.Test; -import org.osgi.service.component.ComponentContext; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link org.apache.sling.replication.queue.impl.PriorityPathDistributionStrategy} - */ -public class PriorityPathQueueDistributionStrategyTest { - - @Test - public void testPackageAdditionWithSucceedingItemDelivery() throws Exception { - PriorityPathDistributionStrategy priorityPathDistributionStrategy = new PriorityPathDistributionStrategy(); - ComponentContext context = mock(ComponentContext.class); - Dictionary properties = mock(Dictionary.class); - when(properties.get("priority.paths")).thenReturn(new String[]{"/content", "/apps"}); - when(context.getProperties()).thenReturn(properties); - priorityPathDistributionStrategy.activate(context); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/etc"}); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(state.isSuccessful()).thenReturn(true); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = priorityPathDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - assertTrue(returnedState.isSuccessful()); - } - - @Test - public void testPackageAdditionWithSucceedingItemDeliveryOnPriorityPath() throws Exception { - PriorityPathDistributionStrategy priorityPathDistributionStrategy = new PriorityPathDistributionStrategy(); - ComponentContext context = mock(ComponentContext.class); - Dictionary properties = mock(Dictionary.class); - when(properties.get("priority.paths")).thenReturn(new String[]{"/content", "/apps"}); - when(context.getProperties()).thenReturn(properties); - priorityPathDistributionStrategy.activate(context); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/content/sample1"}); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getQueue("agentName", "/content")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(state.isSuccessful()).thenReturn(true); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = priorityPathDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - assertTrue(returnedState.isSuccessful()); - } - - @Test - public void testPackageAdditionWithFailingItemDelivery() throws Exception { - PriorityPathDistributionStrategy priorityPathDistributionStrategy = new PriorityPathDistributionStrategy(); - ComponentContext context = mock(ComponentContext.class); - Dictionary properties = mock(Dictionary.class); - when(properties.get("priority.paths")).thenReturn(new String[]{"/content", "/apps"}); - when(context.getProperties()).thenReturn(properties); - priorityPathDistributionStrategy.activate(context); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/etc"}); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(state.isSuccessful()).thenReturn(false); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = priorityPathDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - assertFalse(returnedState.isSuccessful()); - } - - @Test - public void testPackageAdditionWithFailingItemDeliveryOnPriorityPath() throws Exception { - PriorityPathDistributionStrategy priorityPathDistributionStrategy = new PriorityPathDistributionStrategy(); - ComponentContext context = mock(ComponentContext.class); - Dictionary properties = mock(Dictionary.class); - when(properties.get("priority.paths")).thenReturn(new String[]{"/content", "/apps"}); - when(context.getProperties()).thenReturn(properties); - priorityPathDistributionStrategy.activate(context); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/content/sample2"}); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getQueue("agentName", "/content")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(state.isSuccessful()).thenReturn(false); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = priorityPathDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - assertFalse(returnedState.isSuccessful()); - } - - @Test - public void testPackageAdditionWithNullItemStateFromTheQueue() throws Exception { - PriorityPathDistributionStrategy priorityPathDistributionStrategy = new PriorityPathDistributionStrategy(); - ComponentContext context = mock(ComponentContext.class); - Dictionary properties = mock(Dictionary.class); - when(properties.get("priority.paths")).thenReturn(new String[]{"/content", "/apps"}); - when(context.getProperties()).thenReturn(properties); - priorityPathDistributionStrategy.activate(context); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/etc"}); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState returnedState = priorityPathDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNull(returnedState); - } - - @Test - public void testPackageAdditionWithNullItemStateFromTheQueueOnPriorityPath() throws Exception { - PriorityPathDistributionStrategy priorityPathDistributionStrategy = new PriorityPathDistributionStrategy(); - ComponentContext context = mock(ComponentContext.class); - Dictionary properties = mock(Dictionary.class); - when(properties.get("priority.paths")).thenReturn(new String[]{"/content", "/apps"}); - when(context.getProperties()).thenReturn(properties); - priorityPathDistributionStrategy.activate(context); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/apps/some/stuff"}); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getQueue("agentName", "/apps")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState returnedState = priorityPathDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNull(returnedState); - } - - @Test - public void testPackageAdditionWithNotNullItemStateFromTheQueue() throws Exception { - PriorityPathDistributionStrategy priorityPathDistributionStrategy = new PriorityPathDistributionStrategy(); - ComponentContext context = mock(ComponentContext.class); - Dictionary properties = mock(Dictionary.class); - when(properties.get("priority.paths")).thenReturn(new String[]{"/content", "/apps"}); - when(context.getProperties()).thenReturn(properties); - priorityPathDistributionStrategy.activate(context); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/etc"}); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = priorityPathDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - } - - @Test - public void testPackageAdditionWithNotNullItemStateFromTheQueueOnPriorityPath() throws Exception { - PriorityPathDistributionStrategy priorityPathDistributionStrategy = new PriorityPathDistributionStrategy(); - ComponentContext context = mock(ComponentContext.class); - Dictionary properties = mock(Dictionary.class); - when(properties.get("priority.paths")).thenReturn(new String[]{"/content", "/apps"}); - when(context.getProperties()).thenReturn(properties); - priorityPathDistributionStrategy.activate(context); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/apps"}); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getQueue("agentName", "/apps")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = priorityPathDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/SingleQueueDistributionStrategyTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/SingleQueueDistributionStrategyTest.java deleted file mode 100644 index 9e03c1a0a1a..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/SingleQueueDistributionStrategyTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl; - -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueProvider; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link SingleQueueDistributionStrategy} - */ -public class SingleQueueDistributionStrategyTest { - - @Test - public void testPackageAdditionWithSucceedingItemDelivery() throws Exception { - SingleQueueDistributionStrategy singleQueueDistributionStrategy = new SingleQueueDistributionStrategy(); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(state.isSuccessful()).thenReturn(true); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = singleQueueDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - assertTrue(returnedState.isSuccessful()); - } - - @Test - public void testPackageAdditionWithFailingItemDelivery() throws Exception { - SingleQueueDistributionStrategy singleQueueDistributionStrategy = new SingleQueueDistributionStrategy(); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(state.isSuccessful()).thenReturn(false); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = singleQueueDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - assertFalse(returnedState.isSuccessful()); - } - - @Test - public void testPackageAdditionWithNullItemStateFromTheQueue() throws Exception { - SingleQueueDistributionStrategy singleQueueDistributionStrategy = new SingleQueueDistributionStrategy(); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState returnedState = singleQueueDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNull(returnedState); - } - - @Test - public void testPackageAdditionWithNotNullItemStateFromTheQueue() throws Exception { - SingleQueueDistributionStrategy singleQueueDistributionStrategy = new SingleQueueDistributionStrategy(); - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - ReplicationQueueProvider queueProvider = mock(ReplicationQueueProvider.class); - ReplicationQueue queue = mock(ReplicationQueue.class); - when(queueProvider.getDefaultQueue("agentName")).thenReturn(queue); - when(queue.add(replicationPackage)).thenReturn(true); - ReplicationQueueItemState state = mock(ReplicationQueueItemState.class); - when(queue.getStatus(replicationPackage)).thenReturn(state); - ReplicationQueueItemState returnedState = singleQueueDistributionStrategy.add("agentName", replicationPackage, queueProvider); - assertNotNull(returnedState); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingReplicationQueueTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingReplicationQueueTest.java deleted file mode 100644 index 1178c2f94ec..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingReplicationQueueTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl.jobhandling; - -import java.util.Collections; -import java.util.Map; -import org.apache.sling.event.jobs.Job; -import org.apache.sling.event.jobs.JobBuilder; -import org.apache.sling.event.jobs.JobManager; -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.apache.sling.replication.queue.ReplicationQueueItemState.ItemState; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link JobHandlingReplicationQueue} - */ -public class JobHandlingReplicationQueueTest { - - @SuppressWarnings("unchecked") - @Test - public void testPackageAddition() throws Exception { - JobManager jobManager = mock(JobManager.class); - JobBuilder builder = mock(JobBuilder.class); - when(builder.properties(any(Map.class))).thenReturn(builder); - Job job = mock(Job.class); - when(job.getId()).thenReturn("id-123"); - when(builder.add()).thenReturn(job); - String topic = JobHandlingReplicationQueue.REPLICATION_QUEUE_TOPIC + "/aname"; - when(jobManager.createJob(topic)).thenReturn(builder); - when(jobManager.findJobs(JobManager.QueryType.ALL, topic, -1)).thenReturn(Collections.emptySet()); - when(builder.properties(any(Map.class))).thenReturn(builder); - ReplicationQueue queue = new JobHandlingReplicationQueue("aname", topic, jobManager); - ReplicationQueueItem pkg = mock(ReplicationQueueItem.class); - assertTrue(queue.add(pkg)); - } - - @SuppressWarnings("unchecked") - @Test - public void testPackageAdditionAndStatusCheck() throws Exception { - JobManager jobManager = mock(JobManager.class); - JobBuilder builder = mock(JobBuilder.class); - when(builder.properties(any(Map.class))).thenReturn(builder); - Job job = mock(Job.class); - when(job.getId()).thenReturn("id-123"); - when(builder.add()).thenReturn(job); - String topic = JobHandlingReplicationQueue.REPLICATION_QUEUE_TOPIC + "/aname"; - when(jobManager.createJob(topic)).thenReturn(builder); - when(jobManager.findJobs(JobManager.QueryType.ALL, topic, -1)).thenReturn(Collections.emptySet()); - when(builder.properties(any(Map.class))).thenReturn(builder); - ReplicationQueue queue = new JobHandlingReplicationQueue("aname", topic, jobManager); - ReplicationQueueItem pkg = mock(ReplicationQueueItem.class); - assertTrue(queue.add(pkg)); - ReplicationQueueItemState status = queue.getStatus(pkg); - assertNotNull(status); - assertFalse(status.isSuccessful()); - assertEquals(ItemState.DROPPED, status.getItemState()); - } - -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingUtilsTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingUtilsTest.java deleted file mode 100644 index d6a319f2538..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/jobhandling/JobHandlingUtilsTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl.jobhandling; - -import java.io.InputStream; -import java.util.Map; -import org.apache.commons.io.IOUtils; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link JobHandlingUtils} - */ -public class JobHandlingUtilsTest { - @Test - public void testFullPropertiesFromPackageCreation() throws Exception { - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - when(replicationPackage.getAction()).thenReturn("ADD"); - when(replicationPackage.getId()).thenReturn("an-id"); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/content", "/apps"}); - when(replicationPackage.getType()).thenReturn("vlt"); - Map fullPropertiesFromPackage = JobHandlingUtils.createFullPropertiesFromPackage(replicationPackage); - assertNotNull(fullPropertiesFromPackage); - assertEquals(4, fullPropertiesFromPackage.size()); - assertNotNull(fullPropertiesFromPackage.get("replication.package.paths")); - assertNotNull(fullPropertiesFromPackage.get("replication.package.id")); - assertNotNull(fullPropertiesFromPackage.get("replication.package.type")); - assertNotNull(fullPropertiesFromPackage.get("replication.package.action")); - } - - @Test - public void testIdPropertiesFromPackageCreation() throws Exception { - ReplicationQueueItem replicationPackage = mock(ReplicationQueueItem.class); - when(replicationPackage.getId()).thenReturn("an-id"); - Map idPropertiesFromPackage = JobHandlingUtils.createIdPropertiesFromPackage(replicationPackage); - assertNotNull(idPropertiesFromPackage); - assertEquals(1, idPropertiesFromPackage.size()); - assertNotNull(idPropertiesFromPackage.get("replication.package.id")); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/simple/SimpleReplicationQueueTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/simple/SimpleReplicationQueueTest.java deleted file mode 100644 index 5ad621a0314..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/queue/impl/simple/SimpleReplicationQueueTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.queue.impl.simple; - -import org.apache.sling.replication.queue.ReplicationQueue; -import org.apache.sling.replication.queue.ReplicationQueueItem; -import org.apache.sling.replication.queue.ReplicationQueueItemState; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - -/** - * Testcase for {@link SimpleReplicationQueue} - */ -public class SimpleReplicationQueueTest { - - @Test - public void testPackageAddition() throws Exception { - ReplicationQueue queue = new SimpleReplicationQueue("agentName", "default"); - ReplicationQueueItem pkg = mock(ReplicationQueueItem.class); - assertTrue(queue.add(pkg)); - assertFalse(queue.isEmpty()); - } - - @Test - public void testPackageAdditionAndRemoval() throws Exception { - ReplicationQueue queue = new SimpleReplicationQueue("agentName", "default"); - ReplicationQueueItem pkg = mock(ReplicationQueueItem.class); - assertTrue(queue.add(pkg)); - assertFalse(queue.isEmpty()); - queue.removeHead(); - assertTrue(queue.isEmpty()); - ReplicationQueueItemState status = queue.getStatus(pkg); - assertNotNull(status); - assertTrue(status.isSuccessful()); - } - - @Test - public void testPackageAdditionRetrievalAndRemoval() throws Exception { - ReplicationQueue queue = new SimpleReplicationQueue("agentName", "default"); - ReplicationQueueItem pkg = mock(ReplicationQueueItem.class); - assertTrue(queue.add(pkg)); - assertFalse(queue.isEmpty()); - assertEquals(pkg, queue.getHead()); - assertFalse(queue.isEmpty()); - queue.removeHead(); - assertTrue(queue.isEmpty()); - ReplicationQueueItemState status = queue.getStatus(pkg); - assertNotNull(status); - assertTrue(status.isSuccessful()); - assertEquals(1, status.getAttempts()); - } - -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/ChainReplicateReplicationRuleTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/ChainReplicateReplicationRuleTest.java deleted file mode 100644 index ffa051cae9c..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/ChainReplicateReplicationRuleTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule.impl; - -import org.apache.sling.replication.agent.ReplicationAgent; -import org.junit.Test; -import org.osgi.framework.BundleContext; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - -/** - * Testcase for {@link ChainReplicateReplicationRule} - */ -public class ChainReplicateReplicationRuleTest { - - @Test - public void testSignatureNotNull() throws Exception { - ChainReplicateReplicationRule chainPathReplicationRule = new ChainReplicateReplicationRule(); - assertNotNull(chainPathReplicationRule.getSignature()); - } - - @Test - public void testSignatureMatching() throws Exception { - ChainReplicateReplicationRule chainPathReplicationRule = new ChainReplicateReplicationRule(); - assertFalse(chainPathReplicationRule.signatureMatches("")); - assertTrue(chainPathReplicationRule.signatureMatches("chain on path: /apps")); - assertTrue(chainPathReplicationRule.signatureMatches("chain on path: /apps/sling")); - assertFalse(chainPathReplicationRule.signatureMatches("chain on path: /")); - assertFalse(chainPathReplicationRule.signatureMatches("chain on path: foo bar")); - } - - @Test - public void testApplyWithNonMatchingString() throws Exception { - ChainReplicateReplicationRule chainPathReplicationRule = new ChainReplicateReplicationRule(); - String ruleString = ""; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - chainPathReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testApplyWithMatchingString() throws Exception { - ChainReplicateReplicationRule chainPathReplicationRule = new ChainReplicateReplicationRule(); - String ruleString = "chain on path: /foo/bar"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - chainPathReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testApplyWithMatchingStringAndRegisteredContext() throws Exception { - ChainReplicateReplicationRule chainPathReplicationRule = new ChainReplicateReplicationRule(); - String ruleString = "chain on path: /foo/bar"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - BundleContext context = mock(BundleContext.class); - chainPathReplicationRule.activate(context); - chainPathReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testApplyWithNonMatchingStringAndRegisteredContext() throws Exception { - ChainReplicateReplicationRule chainPathReplicationRule = new ChainReplicateReplicationRule(); - String ruleString = "chain on path: 1 2 3"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - BundleContext context = mock(BundleContext.class); - chainPathReplicationRule.activate(context); - chainPathReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testUndoWithNonMatchingString() throws Exception { - ChainReplicateReplicationRule chainPathReplicationRule = new ChainReplicateReplicationRule(); - String ruleString = ""; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - chainPathReplicationRule.undo(ruleString, replicationAgent); - } - - @Test - public void testUndoWithMatchingString() throws Exception { - ChainReplicateReplicationRule chainPathReplicationRule = new ChainReplicateReplicationRule(); - String ruleString = "chain on path: /foo/bar"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - chainPathReplicationRule.undo(ruleString, replicationAgent); - } - - @Test - public void testUndoWithMatchingStringAndRegisteredContext() throws Exception { - ChainReplicateReplicationRule chainPathReplicationRule = new ChainReplicateReplicationRule(); - String ruleString = "chain on path: /foo/bar"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - BundleContext context = mock(BundleContext.class); - chainPathReplicationRule.activate(context); - chainPathReplicationRule.undo(ruleString, replicationAgent); - } - - @Test - public void testUndoWithNonMatchingStringAndRegisteredContext() throws Exception { - ChainReplicateReplicationRule chainPathReplicationRule = new ChainReplicateReplicationRule(); - String ruleString = "chain on path: 1 2 3"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - BundleContext context = mock(BundleContext.class); - chainPathReplicationRule.activate(context); - chainPathReplicationRule.undo(ruleString, replicationAgent); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/DefaultReplicationRuleEngineTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/DefaultReplicationRuleEngineTest.java deleted file mode 100644 index 8339acc3910..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/DefaultReplicationRuleEngineTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule.impl; - -import java.util.Collections; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.apache.sling.replication.rule.ReplicationRule; -import org.junit.Test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link DefaultReplicationRuleEngine} - */ -public class DefaultReplicationRuleEngineTest { - - @Test - public void testApplyWithNoRules() throws Exception { - DefaultReplicationRuleEngine defaultReplicationRuleEngine = new DefaultReplicationRuleEngine(); - String ruleString = "do something sometimes"; - ReplicationAgent agent = mock(ReplicationAgent.class); - defaultReplicationRuleEngine.applyRules(agent, ruleString); - } - - @Test - public void testApplyWithNoMatchingRules() throws Exception { - DefaultReplicationRuleEngine defaultReplicationRuleEngine = new DefaultReplicationRuleEngine(); - String ruleString = "do something sometimes"; - ReplicationRule rule = mock(ReplicationRule.class); - when(rule.signatureMatches(ruleString)).thenReturn(false); - defaultReplicationRuleEngine.bindReplicationRule(rule, Collections.emptyMap()); - ReplicationAgent agent = mock(ReplicationAgent.class); - defaultReplicationRuleEngine.applyRules(agent, ruleString); - } - - @Test - public void testApplyWithMatchingRules() throws Exception { - DefaultReplicationRuleEngine defaultReplicationRuleEngine = new DefaultReplicationRuleEngine(); - String ruleString = "do something sometimes"; - ReplicationRule rule = mock(ReplicationRule.class); - when(rule.signatureMatches(ruleString)).thenReturn(true); - defaultReplicationRuleEngine.bindReplicationRule(rule, Collections.emptyMap()); - ReplicationAgent agent = mock(ReplicationAgent.class); - defaultReplicationRuleEngine.applyRules(agent, ruleString); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/ScheduleReplicateReplicationRuleTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/ScheduleReplicateReplicationRuleTest.java deleted file mode 100644 index 8ab4fd21863..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/ScheduleReplicateReplicationRuleTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule.impl; - -import java.lang.reflect.Field; -import org.apache.sling.commons.scheduler.ScheduleOptions; -import org.apache.sling.commons.scheduler.Scheduler; -import org.apache.sling.replication.agent.ReplicationAgent; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link org.apache.sling.replication.rule.impl.ScheduleReplicateReplicationRule} - */ -public class ScheduleReplicateReplicationRuleTest { - - @Test - public void testSignatureNotNull() throws Exception { - ScheduleReplicateReplicationRule scheduleReplicateReplicationRule = new ScheduleReplicateReplicationRule(); - assertNotNull(scheduleReplicateReplicationRule.getSignature()); - } - - @Test - public void testSignatureMatching() throws Exception { - ScheduleReplicateReplicationRule scheduleReplicateReplicationRule = new ScheduleReplicateReplicationRule(); - assertFalse(scheduleReplicateReplicationRule.signatureMatches("")); - assertTrue(scheduleReplicateReplicationRule.signatureMatches("scheduled poll on /apps every 1 sec")); - assertTrue(scheduleReplicateReplicationRule.signatureMatches("scheduled add on /system every 12 sec")); - assertTrue(scheduleReplicateReplicationRule.signatureMatches("scheduled delete on /libs every 331 sec")); - assertTrue(scheduleReplicateReplicationRule.signatureMatches("scheduled poll every 30 sec")); - } - - @Test - public void testApplyWithNonMatchingString() throws Exception { - ScheduleReplicateReplicationRule scheduleReplicateReplicationRule = new ScheduleReplicateReplicationRule(); - String ruleString = ""; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - scheduleReplicateReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testApplyWithMatchingString() throws Exception { - ScheduleReplicateReplicationRule scheduleReplicateReplicationRule = new ScheduleReplicateReplicationRule(); - Field schedulerField = scheduleReplicateReplicationRule.getClass().getDeclaredField("scheduler"); - schedulerField.setAccessible(true); - Scheduler scheduler = mock(Scheduler.class); - ScheduleOptions options = mock(ScheduleOptions.class); - when(scheduler.NOW(any(Integer.class), any(Integer.class))).thenReturn(options); - schedulerField.set(scheduleReplicateReplicationRule, scheduler); - - String ruleString = "scheduled add on /system every 12 sec"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - scheduleReplicateReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testApplyWithMatchingStringAndRegisteredContext() throws Exception { - ScheduleReplicateReplicationRule scheduleReplicateReplicationRule = new ScheduleReplicateReplicationRule(); - Field schedulerField = scheduleReplicateReplicationRule.getClass().getDeclaredField("scheduler"); - schedulerField.setAccessible(true); - Scheduler scheduler = mock(Scheduler.class); - ScheduleOptions options = mock(ScheduleOptions.class); - when(scheduler.NOW(any(Integer.class), any(Integer.class))).thenReturn(options); - schedulerField.set(scheduleReplicateReplicationRule, scheduler); - - String ruleString = "scheduled add on /system every 12 sec"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - scheduleReplicateReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testApplyWithNonMatchingStringAndRegisteredContext() throws Exception { - ScheduleReplicateReplicationRule scheduleReplicateReplicationRule = new ScheduleReplicateReplicationRule(); - Field schedulerField = scheduleReplicateReplicationRule.getClass().getDeclaredField("scheduler"); - schedulerField.setAccessible(true); - Scheduler scheduler = mock(Scheduler.class); - ScheduleOptions options = mock(ScheduleOptions.class); - when(scheduler.NOW(any(Integer.class), any(Integer.class))).thenReturn(options); - schedulerField.set(scheduleReplicateReplicationRule, scheduler); - - String ruleString = "scheduled add on /system every 12 sec"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - scheduleReplicateReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testUndoWithNonMatchingString() throws Exception { - ScheduleReplicateReplicationRule scheduleReplicateReplicationRule = new ScheduleReplicateReplicationRule(); - Field schedulerField = scheduleReplicateReplicationRule.getClass().getDeclaredField("scheduler"); - schedulerField.setAccessible(true); - Scheduler scheduler = mock(Scheduler.class); - ScheduleOptions options = mock(ScheduleOptions.class); - when(scheduler.NOW(any(Integer.class), any(Integer.class))).thenReturn(options); - schedulerField.set(scheduleReplicateReplicationRule, scheduler); - - String ruleString = ""; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - scheduleReplicateReplicationRule.undo(ruleString, replicationAgent); - } - - @Test - public void testUndoWithMatchingString() throws Exception { - ScheduleReplicateReplicationRule scheduleReplicateReplicationRule = new ScheduleReplicateReplicationRule(); - Field schedulerField = scheduleReplicateReplicationRule.getClass().getDeclaredField("scheduler"); - schedulerField.setAccessible(true); - Scheduler scheduler = mock(Scheduler.class); - ScheduleOptions options = mock(ScheduleOptions.class); - when(scheduler.NOW(any(Integer.class), any(Integer.class))).thenReturn(options); - schedulerField.set(scheduleReplicateReplicationRule, scheduler); - - String ruleString = "scheduled add on /system every 12 sec"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - scheduleReplicateReplicationRule.undo(ruleString, replicationAgent); - } - - @Test - public void testUndoWithMatchingStringAndRegisteredContext() throws Exception { - ScheduleReplicateReplicationRule scheduleReplicateReplicationRule = new ScheduleReplicateReplicationRule(); - Field schedulerField = scheduleReplicateReplicationRule.getClass().getDeclaredField("scheduler"); - schedulerField.setAccessible(true); - Scheduler scheduler = mock(Scheduler.class); - ScheduleOptions options = mock(ScheduleOptions.class); - when(scheduler.NOW(any(Integer.class), any(Integer.class))).thenReturn(options); - schedulerField.set(scheduleReplicateReplicationRule, scheduler); - - String ruleString = "scheduled add on /system every 12 sec"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - scheduleReplicateReplicationRule.undo(ruleString, replicationAgent); - } - - @Test - public void testUndoWithNonMatchingStringAndRegisteredContext() throws Exception { - ScheduleReplicateReplicationRule scheduleReplicateReplicationRule = new ScheduleReplicateReplicationRule(); - Field schedulerField = scheduleReplicateReplicationRule.getClass().getDeclaredField("scheduler"); - schedulerField.setAccessible(true); - Scheduler scheduler = mock(Scheduler.class); - ScheduleOptions options = mock(ScheduleOptions.class); - when(scheduler.NOW(any(Integer.class), any(Integer.class))).thenReturn(options); - schedulerField.set(scheduleReplicateReplicationRule, scheduler); - - String ruleString = "scheduled add on /system every 12 sec"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - scheduleReplicateReplicationRule.undo(ruleString, replicationAgent); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/TriggerPathReplicationRuleTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/TriggerPathReplicationRuleTest.java deleted file mode 100644 index 616746bde78..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/rule/impl/TriggerPathReplicationRuleTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.rule.impl; - -import org.apache.sling.replication.agent.ReplicationAgent; -import org.junit.Test; -import org.osgi.framework.BundleContext; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - -/** - * Testcase for {@link TriggerPathReplicationRule} - */ -public class TriggerPathReplicationRuleTest { - - @Test - public void testSignatureNotNull() throws Exception { - TriggerPathReplicationRule triggerPathReplicationRule = new TriggerPathReplicationRule(); - assertNotNull(triggerPathReplicationRule.getSignature()); - } - - @Test - public void testSignatureMatching() throws Exception { - TriggerPathReplicationRule triggerPathReplicationRule = new TriggerPathReplicationRule(); - assertFalse(triggerPathReplicationRule.signatureMatches("")); - assertTrue(triggerPathReplicationRule.signatureMatches("trigger on path: /apps")); - assertTrue(triggerPathReplicationRule.signatureMatches("trigger on path: /apps/sling")); - assertFalse(triggerPathReplicationRule.signatureMatches("trigger on path: /")); - assertFalse(triggerPathReplicationRule.signatureMatches("trigger on path: foo bar")); - } - - @Test - public void testApplyWithNonMatchingString() throws Exception { - TriggerPathReplicationRule triggerPathReplicationRule = new TriggerPathReplicationRule(); - String ruleString = ""; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - triggerPathReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testApplyWithMatchingString() throws Exception { - TriggerPathReplicationRule triggerPathReplicationRule = new TriggerPathReplicationRule(); - String ruleString = "trigger on path: /foo/bar"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - triggerPathReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testApplyWithMatchingStringAndRegisteredContext() throws Exception { - TriggerPathReplicationRule triggerPathReplicationRule = new TriggerPathReplicationRule(); - String ruleString = "trigger on path: /foo/bar"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - BundleContext context = mock(BundleContext.class); - triggerPathReplicationRule.activate(context); - triggerPathReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testApplyWithNonMatchingStringAndRegisteredContext() throws Exception { - TriggerPathReplicationRule triggerPathReplicationRule = new TriggerPathReplicationRule(); - String ruleString = "trigger on path: 1 2 3"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - BundleContext context = mock(BundleContext.class); - triggerPathReplicationRule.activate(context); - triggerPathReplicationRule.apply(ruleString, replicationAgent); - } - - @Test - public void testUndoWithNonMatchingString() throws Exception { - TriggerPathReplicationRule triggerPathReplicationRule = new TriggerPathReplicationRule(); - String ruleString = ""; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - triggerPathReplicationRule.undo(ruleString, replicationAgent); - } - - @Test - public void testUndoWithMatchingString() throws Exception { - TriggerPathReplicationRule triggerPathReplicationRule = new TriggerPathReplicationRule(); - String ruleString = "trigger on path: /foo/bar"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - triggerPathReplicationRule.undo(ruleString, replicationAgent); - } - - @Test - public void testUndoWithMatchingStringAndRegisteredContext() throws Exception { - TriggerPathReplicationRule triggerPathReplicationRule = new TriggerPathReplicationRule(); - String ruleString = "trigger on path: /foo/bar"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - BundleContext context = mock(BundleContext.class); - triggerPathReplicationRule.activate(context); - triggerPathReplicationRule.undo(ruleString, replicationAgent); - } - - @Test - public void testUndoWithNonMatchingStringAndRegisteredContext() throws Exception { - TriggerPathReplicationRule triggerPathReplicationRule = new TriggerPathReplicationRule(); - String ruleString = "trigger on path: 1 2 3"; - ReplicationAgent replicationAgent = mock(ReplicationAgent.class); - BundleContext context = mock(BundleContext.class); - triggerPathReplicationRule.activate(context); - triggerPathReplicationRule.undo(ruleString, replicationAgent); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/serialization/impl/DefaultReplicationPackageImporterTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/serialization/impl/DefaultReplicationPackageImporterTest.java deleted file mode 100644 index 1a8ba8b2ddf..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/serialization/impl/DefaultReplicationPackageImporterTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl; - -import java.io.InputStream; -import java.lang.reflect.Field; - -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.apache.sling.replication.event.ReplicationEventFactory; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.serialization.ReplicationPackageBuilder; -import org.apache.sling.replication.serialization.ReplicationPackageBuilderProvider; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link org.apache.sling.replication.serialization.impl.DefaultReplicationPackageImporter} - */ -public class DefaultReplicationPackageImporterTest { - - @Test - public void testSynchronousImportWithoutServices() throws Exception { - DefaultReplicationPackageImporter importer = new DefaultReplicationPackageImporter(); - InputStream stream = mock(InputStream.class); - assertFalse(importer.importStream(stream, "some-type")); - assertFalse(importer.importStream(stream, null)); - } - - @Test - public void testSynchronousImportWithNotExistingType() throws Exception { - DefaultReplicationPackageImporter importer = new DefaultReplicationPackageImporter(); - Field replicationEventFactoryField = importer.getClass().getDeclaredField("replicationEventFactory"); - replicationEventFactoryField.setAccessible(true); - ReplicationEventFactory replicationEventFactory = mock(ReplicationEventFactory.class); - replicationEventFactoryField.set(importer, replicationEventFactory); - - Field replicationPackageBuilderProviderField = importer.getClass().getDeclaredField("replicationPackageBuilderProvider"); - replicationPackageBuilderProviderField.setAccessible(true); - ReplicationPackageBuilderProvider replicationPackageBuilderProvider = mock(ReplicationPackageBuilderProvider.class); - ReplicationPackageBuilder packageBuilder = mock(ReplicationPackageBuilder.class); - ReplicationPackage replicationPackage = mock(ReplicationPackage.class); - when(packageBuilder.readPackage(any(InputStream.class), eq(true))).thenReturn(replicationPackage); - when(replicationPackageBuilderProvider.getReplicationPackageBuilder("void")).thenReturn(packageBuilder); - replicationPackageBuilderProviderField.set(importer, replicationPackageBuilderProvider); - - InputStream stream = mock(InputStream.class); - assertFalse(importer.importStream(stream, "some-type")); - assertFalse(importer.importStream(stream, null)); - } - - @Test - public void testSynchronousImportWithTypeParameter() throws Exception { - DefaultReplicationPackageImporter importer = new DefaultReplicationPackageImporter(); - Field replicationEventFactoryField = importer.getClass().getDeclaredField("replicationEventFactory"); - replicationEventFactoryField.setAccessible(true); - ReplicationEventFactory replicationEventFactory = mock(ReplicationEventFactory.class); - replicationEventFactoryField.set(importer, replicationEventFactory); - - Field replicationPackageBuilderProviderField = importer.getClass().getDeclaredField("replicationPackageBuilderProvider"); - replicationPackageBuilderProviderField.setAccessible(true); - ReplicationPackageBuilderProvider replicationPackageBuilderProvider = mock(ReplicationPackageBuilderProvider.class); - ReplicationPackageBuilder packageBuilder = mock(ReplicationPackageBuilder.class); - ReplicationPackage replicationPackage = new VoidReplicationPackage(new ReplicationRequest(System.currentTimeMillis(), ReplicationActionType.DELETE, "/content"), "void"); - when(packageBuilder.readPackage(any(InputStream.class), eq(true))).thenReturn(replicationPackage); - when(replicationPackageBuilderProvider.getReplicationPackageBuilder("void")).thenReturn(packageBuilder); - replicationPackageBuilderProviderField.set(importer, replicationPackageBuilderProvider); - - InputStream stream = mock(InputStream.class); - assertTrue(importer.importStream(stream, "void")); - } - - @Test - public void testSynchronousImportWithoutTypeParameter() throws Exception { - DefaultReplicationPackageImporter importer = new DefaultReplicationPackageImporter(); - Field replicationEventFactoryField = importer.getClass().getDeclaredField("replicationEventFactory"); - replicationEventFactoryField.setAccessible(true); - ReplicationEventFactory replicationEventFactory = mock(ReplicationEventFactory.class); - replicationEventFactoryField.set(importer, replicationEventFactory); - - Field replicationPackageBuilderProviderField = importer.getClass().getDeclaredField("replicationPackageBuilderProvider"); - replicationPackageBuilderProviderField.setAccessible(true); - ReplicationPackageBuilderProvider replicationPackageBuilderProvider = mock(ReplicationPackageBuilderProvider.class); - ReplicationPackageBuilder packageBuilder = mock(ReplicationPackageBuilder.class); - ReplicationPackage replicationPackage = new VoidReplicationPackage(new ReplicationRequest(System.currentTimeMillis(), ReplicationActionType.DELETE, "/content"), "void"); - when(packageBuilder.readPackage(any(InputStream.class), eq(true))).thenReturn(replicationPackage); - replicationPackageBuilderProviderField.set(importer, replicationPackageBuilderProvider); - - InputStream stream = mock(InputStream.class); - assertFalse(importer.importStream(stream, null)); - } - - - -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/serialization/impl/VoidReplicationPackageTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/serialization/impl/VoidReplicationPackageTest.java deleted file mode 100644 index 09b41d9af95..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/serialization/impl/VoidReplicationPackageTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl; - -import java.io.ByteArrayInputStream; -import java.util.Arrays; -import org.apache.commons.io.IOUtils; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * Testcase for {@link VoidReplicationPackage} - */ -public class VoidReplicationPackageTest { - - @Test - public void testCreatedAndReadPackagesEquality() throws Exception { - ReplicationRequest request = new ReplicationRequest(123l, ReplicationActionType.DELETE, "/abc"); - VoidReplicationPackage createdPackage = new VoidReplicationPackage(request, "VOID"); - VoidReplicationPackage readPackage = VoidReplicationPackage.fromStream(new ByteArrayInputStream("DELETE:[/abc]:123:VOID".getBytes())); - assertEquals(createdPackage.getId(), readPackage.getId()); - assertEquals(createdPackage.getAction(), readPackage.getAction()); - assertEquals(createdPackage.getType(), readPackage.getType()); - assertEquals(createdPackage.getLength(), readPackage.getLength()); - assertEquals(Arrays.toString(createdPackage.getPaths()), Arrays.toString(readPackage.getPaths())); - assertTrue(IOUtils.contentEquals(createdPackage.createInputStream(), readPackage.createInputStream())); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/serialization/impl/vlt/FileVaultReplicationPackageBuilderTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/serialization/impl/vlt/FileVaultReplicationPackageBuilderTest.java deleted file mode 100644 index dbddb897641..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/serialization/impl/vlt/FileVaultReplicationPackageBuilderTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.serialization.impl.vlt; - -import java.lang.reflect.Field; -import org.apache.jackrabbit.vault.packaging.Packaging; -import org.apache.sling.jcr.api.SlingRepository; -import org.apache.sling.replication.communication.ReplicationRequest; -import org.junit.Test; - -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; - -/** - * Testcase for {@link FileVaultReplicationPackageBuilder} - */ -public class FileVaultReplicationPackageBuilderTest { - - @Test - public void testCreatePackageForAddWithoutPermissions() throws Exception { - try { - SlingRepository repository = mock(SlingRepository.class); - FileVaultReplicationPackageBuilder fileVaultReplicationPackageBuilder = new FileVaultReplicationPackageBuilder(); - Field repositoryField = fileVaultReplicationPackageBuilder.getClass().getDeclaredField("repository"); - repositoryField.setAccessible(true); - repositoryField.set(fileVaultReplicationPackageBuilder, repository); - - Packaging packaging = mock(Packaging.class); - Field packagingField = fileVaultReplicationPackageBuilder.getClass().getDeclaredField("packaging"); - packagingField.setAccessible(true); - packagingField.set(fileVaultReplicationPackageBuilder, packaging); - - ReplicationRequest request = mock(ReplicationRequest.class); - fileVaultReplicationPackageBuilder.createPackageForAdd(request); - fail("cannot create a package without supplying needed credentials"); - } catch (Throwable t) { - // expected to fail - } - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/authentication/impl/NopTransportAuthenticationProviderTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/authentication/impl/NopTransportAuthenticationProviderTest.java deleted file mode 100644 index ca1138b1c2f..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/authentication/impl/NopTransportAuthenticationProviderTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication.impl; - -import org.apache.http.client.fluent.Executor; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationContext; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * Testcase for {@link NopTransportAuthenticationProvider} - */ -public class NopTransportAuthenticationProviderTest { - - @Test - public void testAuthenticationWithNullAuthenticableAndContext() throws Exception { - NopTransportAuthenticationProvider authenticationHandler = new NopTransportAuthenticationProvider(); - Object authenticable = null; - TransportAuthenticationContext context = null; - assertEquals(authenticable, authenticationHandler.authenticate(authenticable, context)); - } - - @Test - public void testAuthenticationWithAuthenticableAndNullContext() throws Exception { - NopTransportAuthenticationProvider authenticationHandler = new NopTransportAuthenticationProvider(); - Executor authenticable = Executor.newInstance(); - TransportAuthenticationContext context = null; - assertEquals(authenticable, authenticationHandler.authenticate(authenticable, context)); - } - - @Test - public void testAuthenticationWithAuthenticableAndEmptyContext() throws Exception { - NopTransportAuthenticationProvider authenticationHandler = new NopTransportAuthenticationProvider(); - Executor authenticable = Executor.newInstance(); - TransportAuthenticationContext context = new TransportAuthenticationContext(); - assertEquals(authenticable, authenticationHandler.authenticate(authenticable, context)); - } - - @Test - public void testAuthenticationWithAuthenticableAndCorrectContext() throws Exception { - NopTransportAuthenticationProvider authenticationHandler = new NopTransportAuthenticationProvider(); - Executor authenticable = Executor.newInstance(); - TransportAuthenticationContext context = new TransportAuthenticationContext(); - context.addAttribute("endpoint", new ReplicationEndpoint("http://www.apache.org")); - assertEquals(authenticable, authenticationHandler.authenticate(authenticable, context)); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/authentication/impl/UserCredentialsTransportAuthenticationProviderTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/authentication/impl/UserCredentialsTransportAuthenticationProviderTest.java deleted file mode 100644 index d66bf308e39..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/authentication/impl/UserCredentialsTransportAuthenticationProviderTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.authentication.impl; - -import org.apache.http.client.fluent.Executor; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationContext; -import org.junit.Test; - -import static org.junit.Assert.fail; - -/** - * Testcase for {@link UserCredentialsTransportAuthenticationProvider} - */ -public class UserCredentialsTransportAuthenticationProviderTest { - - @Test - public void testAuthenticationWithNullAuthenticableAndContext() throws Exception { - UserCredentialsTransportAuthenticationProvider authenticationHandler = new UserCredentialsTransportAuthenticationProvider( - "foo", "bar"); - Executor authenticable = null; - TransportAuthenticationContext context = null; - try { - authenticationHandler.authenticate(authenticable, context); - fail("could not authenticate a null authenticable"); - } catch (Exception e) { - // expected to fail - } - } - - @Test - public void testAuthenticationWithAuthenticableAndNullContext() throws Exception { - UserCredentialsTransportAuthenticationProvider authenticationHandler = new UserCredentialsTransportAuthenticationProvider( - "foo", "bar"); - Executor authenticable = Executor.newInstance(); - TransportAuthenticationContext context = null; - try { - authenticationHandler.authenticate(authenticable, context); - fail("could not authenticate with a null context"); - } catch (Exception e) { - // expected to fail - } - } - - @Test - public void testAuthenticationWithAuthenticableAndEmptyContext() throws Exception { - UserCredentialsTransportAuthenticationProvider authenticationHandler = new UserCredentialsTransportAuthenticationProvider( - "foo", "bar"); - Executor authenticable = Executor.newInstance(); - TransportAuthenticationContext context = new TransportAuthenticationContext(); - try { - authenticationHandler.authenticate(authenticable, context); - fail("could not authenticate with an empty context"); - } catch (Exception e) { - // expected to fail - } - } - - @Test - public void testAuthenticationWithAuthenticableAndCorrectContext() throws Exception { - UserCredentialsTransportAuthenticationProvider authenticationHandler = new UserCredentialsTransportAuthenticationProvider( - "foo", "bar"); - Executor authenticable = Executor.newInstance(); - TransportAuthenticationContext context = new TransportAuthenticationContext(); - context.addAttribute("endpoint", new ReplicationEndpoint("http://www.apache.org")); - authenticationHandler.authenticate(authenticable, context); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/HttpTransportHandlerCustomHeadersTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/HttpTransportHandlerCustomHeadersTest.java deleted file mode 100644 index ba8a95b45a7..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/HttpTransportHandlerCustomHeadersTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.sling.replication.transport.impl; - - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import java.util.Arrays; - -import static org.junit.Assert.assertArrayEquals; - - -@RunWith(Parameterized.class) -public class HttpTransportHandlerCustomHeadersTest { - - private final String[] inputTransportProperties; - private final String inputSelector; - private final String[] inputPaths; - - private final String[] outputHeaders; - - - @Parameterized.Parameters - public static Iterable data() { - return Arrays.asList(new Object[][]{ - { new String[]{}, "", new String[] {}, - new String[]{}}, - { new String[]{}, "add", new String[] {}, - new String[]{}}, - { new String[]{"add -> Header: Add" }, "add", new String[] {}, - new String[]{ "Header: Add" }}, - { new String[]{"add -> Header: Add", "Header: Always" }, "add", new String[] {}, - new String[]{ "Header: Add", "Header: Always" }}, - { new String[]{"add -> Header: Add", "* -> Header: Always", "delete -> Header:Del" }, "add", new String[] {}, - new String[]{"Header: Add", "Header: Always" }}, - { new String[]{"add -> Header: Add", "Header: Always" }, "delete", new String[] {}, - new String[]{"Header: Always" }}, - { new String[]{"add -> Header: Add", "Header: Always" }, "add", new String[] {}, - new String[] {"Header: Add", "Header: Always" }}, - { new String[]{"add -> Header: Add", "Header: Always", "PathHeader: {path}" }, "add", new String[] { "/content"}, - new String[]{"Header: Add", "Header: Always", "PathHeader: /content"}}, - }); - - } - - public HttpTransportHandlerCustomHeadersTest(String[] inputTransportProperties, String inputSelector, String[] inputPaths, - String[] outputHeaders){ - this.inputTransportProperties = inputTransportProperties; - this.inputSelector = inputSelector; - this.outputHeaders = outputHeaders; - this.inputPaths = inputPaths; - } - - @Test - public void testHttpTransportProperties () { - String[] headers = HttpTransportHandler.getCustomizedHeaders (inputTransportProperties, inputSelector, inputPaths); - - assertArrayEquals(outputHeaders, headers); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/HttpTransportHandlerTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/HttpTransportHandlerTest.java deleted file mode 100644 index 824fed92d54..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/HttpTransportHandlerTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import java.net.URI; - - -import org.apache.http.client.fluent.Content; -import org.apache.http.client.fluent.Executor; -import org.apache.http.client.fluent.Request; -import org.apache.http.client.fluent.Response; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationContext; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.junit.Test; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.times; - -/** - * Testcase for {@link HttpTransportHandler} - */ -public class HttpTransportHandlerTest { - @Test - public void testHttpTransport() throws Exception { - TransportAuthenticationProvider transportAuthenticationProvider = mock(TransportAuthenticationProvider.class); - ReplicationEndpoint replicationEndpoint = new ReplicationEndpoint(new URI("http://localhost:8080/system/replication/receive")); - - - - HttpTransportHandler httpTransportHandler = new HttpTransportHandler(false, null, false, null, - transportAuthenticationProvider, - new ReplicationEndpoint[] { replicationEndpoint }, TransportEndpointStrategyType.All); - ReplicationPackage replicationPackage = mock(ReplicationPackage.class); - when(replicationPackage.getAction()).thenReturn(ReplicationActionType.ADD.toString()); - when(replicationPackage.getType()).thenReturn("test"); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/content"}); - Executor executor = mock(Executor.class); - Response response = mock(Response.class); - Content content = mock(Content.class); - when(response.returnContent()).thenReturn(content); - when(executor.execute(any(Request.class))).thenReturn(response); - when(transportAuthenticationProvider.authenticate(any(Executor.class), any(TransportAuthenticationContext.class))).thenReturn(executor); - httpTransportHandler.transport("agentName", replicationPackage); - } - - @Test - public void testHttpTransportWithMultipleCalls() throws Exception { - TransportAuthenticationProvider transportAuthenticationProvider = mock(TransportAuthenticationProvider.class); - ReplicationEndpoint replicationEndpoint = new ReplicationEndpoint(new URI("http://localhost:8080/system/replication/receive")); - - - HttpTransportHandler httpTransportHandler = new HttpTransportHandler(false, null, false, null, - transportAuthenticationProvider, - new ReplicationEndpoint[] { replicationEndpoint }, TransportEndpointStrategyType.All); - - ReplicationPackage replicationPackage = mock(ReplicationPackage.class); - when(replicationPackage.getAction()).thenReturn(ReplicationActionType.ADD.toString()); - when(replicationPackage.getType()).thenReturn("test"); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/content/a", "/content/b"}); - - Executor executor = mock(Executor.class); - Response response = mock(Response.class); - Content content = mock(Content.class); - when(response.returnContent()).thenReturn(content); - when(executor.execute(any(Request.class))).thenReturn(response); - when(transportAuthenticationProvider.authenticate(any(Executor.class), any(TransportAuthenticationContext.class))).thenReturn(executor); - - httpTransportHandler.transport("agentName", replicationPackage); - - verify(executor, times(1)).execute(any(Request.class)); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/PollingTransportHandlerTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/PollingTransportHandlerTest.java deleted file mode 100644 index bf8c3865fc7..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/PollingTransportHandlerTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import java.net.URI; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.fluent.Executor; -import org.apache.http.client.fluent.Request; -import org.apache.http.client.fluent.Response; -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationContext; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.junit.Test; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link PollingTransportHandler} - */ -public class PollingTransportHandlerTest { - - @Test - public void testPollingTransport() throws Exception { - TransportAuthenticationProvider transportAuthenticationProvider = mock(TransportAuthenticationProvider.class); - ReplicationEndpoint replicationEndpoint = new ReplicationEndpoint(new URI("http://localhost:8080/system/replication/agent/reverse")); - - - PollingTransportHandler pollingTransportHandler = new PollingTransportHandler( -1, - transportAuthenticationProvider, - new ReplicationEndpoint[] { replicationEndpoint }); - ReplicationPackage replicationPackage = mock(ReplicationPackage.class); - when(replicationPackage.getAction()).thenReturn(ReplicationActionType.ADD.toString()); - when(replicationPackage.getType()).thenReturn("test"); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/content"}); - Executor executor = mock(Executor.class); - Response response = mock(Response.class); - HttpEntity entity = mock(HttpEntity.class); - HttpResponse httpResponse = mock(HttpResponse.class); - when(response.returnResponse()).thenReturn(httpResponse); - when(httpResponse.getEntity()).thenReturn(entity); - when(executor.execute(any(Request.class))).thenReturn(response); - when(transportAuthenticationProvider.authenticate(any(Executor.class), any(TransportAuthenticationContext.class))).thenReturn(executor); - pollingTransportHandler.transport("agentName", replicationPackage); - } -} diff --git a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/RepositoryTransportHandlerTest.java b/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/RepositoryTransportHandlerTest.java deleted file mode 100644 index 3f54cdced66..00000000000 --- a/contrib/extensions/replication/core/src/test/java/org/apache/sling/replication/transport/impl/RepositoryTransportHandlerTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.transport.impl; - -import javax.jcr.Credentials; -import javax.jcr.Node; -import javax.jcr.Session; -import org.apache.sling.jcr.api.SlingRepository; -import org.apache.sling.replication.communication.ReplicationEndpoint; -import org.apache.sling.replication.event.ReplicationEventFactory; -import org.apache.sling.replication.serialization.ReplicationPackage; -import org.apache.sling.replication.transport.ReplicationTransportException; -import org.apache.sling.replication.transport.authentication.TransportAuthenticationProvider; -import org.apache.sling.replication.transport.authentication.impl.RepositoryTransportAuthenticationProvider; -import org.junit.Test; - -import static org.junit.Assert.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Testcase for {@link RepositoryTransportHandler} - */ -public class RepositoryTransportHandlerTest { - - @Test - public void testDeliveryWithoutAuthenticatedSession() throws Exception { - TransportAuthenticationProvider transportAuthenticationProvider = mock(TransportAuthenticationProvider.class); - - RepositoryTransportHandler handler = new RepositoryTransportHandler(null, null, - transportAuthenticationProvider, - new ReplicationEndpoint[] { new ReplicationEndpoint("repo://var/outbox/replication/rev1") }); - try { - handler.transport("agentName", null); - fail("cannot deliver without a proper session"); - } catch (ReplicationTransportException re) { - // failure expected - } - } - - @Test - public void testDeliveryWithAuthenticatedSession() throws Exception { - String repoPath = "/var/outbox/replication/rev1"; - - Node addedNode = mock(Node.class); - when(addedNode.getPath()).thenReturn(repoPath + "/some-id"); - - Node node = mock(Node.class); - when(node.addNode(any(String.class), any(String.class))).thenReturn(addedNode); - - Session session = mock(Session.class); - when(session.getNode(repoPath)).thenReturn(node); - when(session.nodeExists(repoPath)).thenReturn(true); - - SlingRepository repo = mock(SlingRepository.class); - when(repo.login(any(Credentials.class))).thenReturn(session); - - ReplicationEventFactory replicationEventFactory = mock(ReplicationEventFactory.class); - - TransportAuthenticationProvider transportAuthenticationProvider = new RepositoryTransportAuthenticationProvider("user-123", "p455w0rd"); - - RepositoryTransportHandler handler = new RepositoryTransportHandler(repo, replicationEventFactory, - transportAuthenticationProvider, - new ReplicationEndpoint[] { new ReplicationEndpoint("repo:/" + repoPath) }); - - - ReplicationPackage replicationPackage = mock(ReplicationPackage.class); - when(replicationPackage.getId()).thenReturn("some-id"); - when(replicationPackage.getPaths()).thenReturn(new String[]{"/apps", "/libs"}); - handler.transport("agentName", replicationPackage); - } -} diff --git a/contrib/extensions/replication/it/pom.xml b/contrib/extensions/replication/it/pom.xml deleted file mode 100644 index 48abb9b1e0d..00000000000 --- a/contrib/extensions/replication/it/pom.xml +++ /dev/null @@ -1,374 +0,0 @@ - - - - - 4.0.0 - - org.apache.sling - sling - 19 - - - org.apache.sling.replication.it - 0.0.1-SNAPSHOT - bundle - - Apache Sling Replication Integration Tests - - Project tests functionality for org.apache.sling.replication bundle - - - - - - - - false - - - - - - - - - - - - - - - -Xmx512m - - - 1.0 - - - - - - -p $JAREXEC_SERVER_PORT$ -Dsling.run.modes=author - - - **/**Test.java - - - - scm:svn:http://svn.apache.org/repos/asf/sling/trunk/contrib/extensions/replication/it - scm:svn:https://svn.apache.org/repos/asf/sling/trunk/contrib/extensions/replication/it - http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/replication/it - - - - - - org.apache.felix - maven-scr-plugin - - - org.apache.sling - maven-sling-plugin - - - org.apache.felix - maven-bundle-plugin - true - - - org.apache.sling.replication.it - SLING-CONTENT/content/test;path:=/content/test;overwrite:=true, - SLING-CONTENT/libs/test;path:=/libs/test;overwrite:=true - - - org.apache.sling.replication.it - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - - maven-clean-plugin - - - - ${basedir} - - - sling/** - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-runnable-jar - - copy-dependencies - - process-resources - - org.apache.sling.launchpad - true - false - false - - - - - copy-additional-bundles - - copy-dependencies - - process-resources - - ${project.build.directory}/sling/additional-bundles - true - false - false - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - reserve-server-port - - reserve-network-port - - process-resources - - - http.port - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - - ** - - - - - org.apache.maven.plugins - maven-failsafe-plugin - - - integration-test - - integration-test - - - - verify - - verify - - - - - ${maven.surefire.debug} - - ${tests.to.run} - - - ${test.server.url} - ${test.server.hostname} - ${test.server.username} - ${test.server.password} - ${http.port} - ${jar.executor.vm.options} - ${project.basedir}/target/dependency - org.apache.sling.launchpad.*jar$ - ${jar.executor.work.folder} - ${jar.executor.jar.options} - - ${project.build.directory},${project.build.directory}/sling/additional-bundles - - ${keepJarRunning} - 60 - ${sling.testing.timeout.multiplier} - - /:script src="system/sling.js" - /.explorer.html:href="/libs/sling/explorer/css/explorer.css" - - /sling-test/sling/sling-test.html:Sling client library tests - - 30 - 20 - - - - - httpcore-osgi - httpclient-osgi - org.apache.sling.hc.core - org.apache.jackrabbit.vault - org.apache.sling.replication- - ${project.build.finalName}.jar - - - - - - - - - - - org.apache.sling - org.apache.sling.testing.tools - 1.0.7-SNAPSHOT - provided - - - org.apache.sling - org.apache.sling.hc.core - 1.0.6 - provided - - - - org.apache.jackrabbit.vault - org.apache.jackrabbit.vault - 3.0.0 - provided - - - - org.apache.httpcomponents - httpcore-osgi - 4.3.1 - - - org.apache.httpcomponents - httpclient-osgi - 4.3.2 - - - - commons-io - commons-io - 2.4 - provided - - - - - org.apache.sling - org.apache.sling.commons.json - 2.0.6 - - - org.apache.sling - org.apache.sling.launchpad - standalone - 7-SNAPSHOT - - - org.slf4j - slf4j-api - 1.5.11 - - - org.slf4j - slf4j-simple - 1.5.11 - test - - - junit - junit - 4.8.2 - test - - - org.apache.sling - org.apache.sling.api - 2.5.0 - - - javax.servlet - servlet-api - 2.4 - - - org.apache.jackrabbit - jackrabbit-api - 2.7.2 - - - org.apache.jackrabbit - jackrabbit-jcr-commons - 2.7.2 - - - javax.jcr - jcr - 2.0 - - - org.apache.sling - org.apache.sling.replication - 0.0.1-SNAPSHOT - - - \ No newline at end of file diff --git a/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationAgentCommandsIntegrationTest.java b/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationAgentCommandsIntegrationTest.java deleted file mode 100644 index a36afe47c21..00000000000 --- a/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationAgentCommandsIntegrationTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.it; - -import org.apache.sling.replication.communication.ReplicationActionType; -import org.apache.sling.replication.communication.ReplicationHeader; -import org.junit.Test; - -/** - * Integration test for commands on {@link org.apache.sling.replication.agent.ReplicationAgent}s - */ -public class ReplicationAgentCommandsIntegrationTest extends ReplicationITBase { - - @Test - public void testAddCommand() throws Exception { - String agentResource = getAgentUrl("publish"); - assertPostResourceWithHeaders(202, agentResource, ReplicationHeader.ACTION.toString(), ReplicationActionType.ADD.toString(), ReplicationHeader.PATH.toString(), "/libs/sling/replication"); - } - - @Test - public void testPollCommand() throws Exception { - String agentResource = getAgentUrl("publish"); - assertPostResourceWithHeaders(200, agentResource, ReplicationHeader.ACTION.toString(), ReplicationActionType.POLL.toString()); - } - - @Test - public void testDeleteCommand() throws Exception { - String agentResource = getAgentUrl("publish"); - assertPostResourceWithHeaders(202, agentResource, ReplicationHeader.ACTION.toString(), ReplicationActionType.DELETE.toString(), ReplicationHeader.PATH.toString(), "/not/existing"); - } - -} \ No newline at end of file diff --git a/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationAgentResourcesIntegrationTest.java b/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationAgentResourcesIntegrationTest.java deleted file mode 100644 index de0ccebad37..00000000000 --- a/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationAgentResourcesIntegrationTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.it; - -import java.io.IOException; -import org.junit.Test; - -/** - * Integration test for {@link org.apache.sling.replication.agent.ReplicationAgent} resources - */ -public class ReplicationAgentResourcesIntegrationTest extends ReplicationITBase { - - @Test - public void testDefaultAgentConfigurationResources() throws IOException { - String[] defaultAgentNames = new String[]{ - "publish", - "publish-reverse", - "reverserepo", - "author", - "cache-flush" - }; - for (String agentName : defaultAgentNames) { - assertResourceExists(getAgentConfigUrl(agentName)); - } - - } - - @Test - public void testDefaultPublishAgentResources() throws IOException { - // these agents do not exist as they are bundled to publish runMode - String[] defaultPublishAgentNames = new String[]{ - "reverserepo", - "author", - "cache-flush" - }; - for (String agentName : defaultPublishAgentNames) { - assertResourceDoesNotExist(getAgentUrl(agentName)); - } - } - - @Test - public void testDefaultAuthorAgentResources() throws IOException { - // these agents exist as they are bundled to author runMode - String[] defaultAuthorAgentNames = new String[]{ - "publish", - "publish-reverse" - }; - for (String agentName : defaultAuthorAgentNames) { - assertResourceExists(getAgentUrl(agentName)); - } - } - - @Test - public void testDefaultPublishAgentQueueResources() throws IOException { - // these agent queues do not exist as they are bundled to publish runMode - String[] defaultPublishAgentNames = new String[]{ - "reverserepo", - "author", - "cache-flush" - }; - for (String agentName : defaultPublishAgentNames) { - assertResourceDoesNotExist(getAgentUrl(agentName)+"/queue"); - } - } - - @Test - public void testDefaultAuthorAgentQueueResources() throws IOException { - // these agent queues exist as they are bundled to author runMode - String[] defaultAuthorAgentNames = new String[]{ - "publish", - "publish-reverse" - }; - for (String agentName : defaultAuthorAgentNames) { - assertResourceExists(getAgentUrl(agentName)+"/queue"); - } - } - - @Test - public void testDefaultAgentsRootResource() throws Exception { - String rootResource = getAgentRootUrl(); - assertResourceExists(rootResource); - assertJsonResponseContains(rootResource, - "sling:resourceType", "replication/agents", - "items", "[\"publish-reverse\",\"publish\"]"); - } - - @Test - public void testAgentConfigurationResourceCreate() throws Exception { - String agentName = "sample-create-config"; - String newConfigResource = getAgentConfigUrl(agentName); - - assertPostResourceWithParameters(201, newConfigResource, "name", agentName, "transportHandler", "(name=author)"); - assertResourceExists(newConfigResource); - assertJsonResponseContains(newConfigResource, - "sling:resourceType", "replication/config/agent", - "name", agentName, - "transportHandler", "(name=author)"); - } - - @Test - public void testAgentConfigurationResourceDelete() throws Exception { - String agentName = "sample-delete-config"; - String newConfigResource = getAgentConfigUrl(agentName); - assertPostResourceWithParameters(201, newConfigResource, "name", agentName, "transportHandler", "(name=author)"); - assertResourceExists(newConfigResource); - assertPostResourceWithParameters(200, newConfigResource, ":operation", "delete"); - assertResourceDoesNotExist(newConfigResource); - } - - - @Test - public void testAgentConfigurationResourceUpdate() throws Exception { - String agentName = "sample-update-config"; - String newConfigResource = getAgentConfigUrl(agentName); - assertPostResourceWithParameters(201, newConfigResource, "name", agentName, "transportHandler", "(name=author)"); - assertResourceExists(newConfigResource); - assertJsonResponseContains(newConfigResource, - "sling:resourceType", "replication/config/agent", - "name", agentName, - "transportHandler", "(name=author)"); - } -} \ No newline at end of file diff --git a/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationITBase.java b/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationITBase.java deleted file mode 100644 index 5314880ff50..00000000000 --- a/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationITBase.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.apache.sling.replication.it; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.http.NameValuePair; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.message.BasicNameValuePair; -import org.apache.sling.testing.tools.http.Request; -import org.apache.sling.testing.tools.sling.SlingTestBase; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * Integration test base class for replication - */ -public abstract class ReplicationITBase extends SlingTestBase { - - private static final String JSON_SELECTOR = ".json"; - private static final String REPLICATION_ROOT_PATH = "/libs/sling/replication"; - - protected void assertGetResource(int status, String path, String... parameters) throws IOException { - getRequestExecutor().execute( - getRequestBuilder().buildGetRequest(path, parameters) - .withCredentials(getServerUsername(), getServerPassword()) - ).assertStatus(status); - } - - protected void assertPostResourceWithParameters(int status, String path, String... parameters) throws IOException { - Request request = getRequestBuilder().buildPostRequest(path); - - if (parameters != null) { - assertEquals(0, parameters.length % 2); - List valuePairList = new ArrayList(); - - for (int i = 0; i < parameters.length; i += 2) { - valuePairList.add(new BasicNameValuePair(parameters[i], parameters[i + 1])); - } - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairList); - request.withEntity(entity); - } - getRequestExecutor().execute( - request.withCredentials(getServerUsername(), getServerPassword()) - ).assertStatus(status); - } - - protected void assertPostResourceWithHeaders(int status, String path, String... headers) throws IOException { - Request request = getRequestBuilder().buildPostRequest(path); - if (headers != null) { - assertEquals(0, headers.length % 2); - for (int i = 0; i < headers.length; i += 2) { - request = request.withHeader(headers[i], headers[i + 1]); - } - } - getRequestExecutor().execute( - request.withCredentials(getServerUsername(), getServerPassword()) - ).assertStatus(status); - } - - protected void assertResourceExists(String path) throws IOException { - if (!path.endsWith(JSON_SELECTOR)) { - path += JSON_SELECTOR; - } - - assertGetResource(200, path); - } - - protected void assertResourceDoesNotExist(String path) throws IOException { - if (!path.endsWith(JSON_SELECTOR)) { - path += JSON_SELECTOR; - } - assertGetResource(404, path); - } - - protected void assertJsonResponseEquals(String resource, String expectedJsonString) throws IOException { - if (!resource.endsWith(JSON_SELECTOR)) { - resource += JSON_SELECTOR; - } - assertEquals(expectedJsonString.trim(), getRequestExecutor().execute( - getRequestBuilder().buildGetRequest(resource) - .withCredentials(getServerUsername(), getServerPassword()) - ).getContent().replaceAll("\n", "").trim()); - - } - - protected void assertJsonResponseContains(String resource, String... parameters) throws IOException { - if (!resource.endsWith(JSON_SELECTOR)) { - resource += JSON_SELECTOR; - } - String content = getRequestExecutor().execute( - getRequestBuilder().buildGetRequest(resource) - .withCredentials(getServerUsername(), getServerPassword()) - ).getContent().replaceAll("\n", "").trim(); - - assertEquals(0, parameters.length % 2); - - for (int i = 0; i < parameters.length; i += 2) { - assertTrue(parameters[i] + ":" + parameters[i + 1] + " is not contained in " + content, - content.contains("\"" + parameters[i] + "\":\"" + parameters[i + 1] + "\"") || - content.contains("\"" + parameters[i] + "\":" + parameters[i + 1]) - ); - } - } - - - protected String getAgentRootUrl() { - return REPLICATION_ROOT_PATH + "/agent"; - } - - protected String getAgentUrl(String agentName) { - return REPLICATION_ROOT_PATH + "/agent/" + agentName; - } - - protected String getAgentConfigUrl(String agentName) { - return REPLICATION_ROOT_PATH + "/config/agent/" + agentName; - } - - - protected String getImporterRootUrl() { - return REPLICATION_ROOT_PATH + "/importer"; - } - - protected String getImporterUrl(String importerName) { - return REPLICATION_ROOT_PATH + "/importer/" + importerName; - } -} diff --git a/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationPackageImporterResourcesIntegrationTest.java b/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationPackageImporterResourcesIntegrationTest.java deleted file mode 100644 index 18a00760251..00000000000 --- a/contrib/extensions/replication/it/src/test/java/org/apache/sling/replication/it/ReplicationPackageImporterResourcesIntegrationTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sling.replication.it; - -import org.junit.Test; - -/** - * Integration test for {@link org.apache.sling.replication.serialization.ReplicationPackageImporter} resources - */ -public class ReplicationPackageImporterResourcesIntegrationTest extends ReplicationITBase { - - @Test - public void testImporterRootResource() throws Exception { - String rootResource = getImporterRootUrl(); - assertResourceExists(rootResource); - assertJsonResponseContains(rootResource, - "sling:resourceType", "replication/importers", - "items", "[\"default\"]"); - } - - @Test - public void testDefaultImporterResource() throws Exception { - String rootResource = getImporterUrl("default"); - assertResourceExists(rootResource); - assertJsonResponseContains(rootResource, - "sling:resourceType", "replication/importer", - "name", "default"); - } -}