Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue 3177 - Automate creation of vanity URLs for each country & lang… #3179

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ The format is based on [Keep a Changelog](http://keepachangelog.com)

## 6.2.0 - 2023-09-14

## Changed

- #3177 - Redirect Mapper: Automate creation of vanity URLs for each country

## Added

- #3151 - New ContentSync utility
Expand Down
2 changes: 1 addition & 1 deletion bundle-cloud/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
<parent>
<groupId>com.adobe.acs</groupId>
<artifactId>acs-aem-commons</artifactId>
<version>6.2.1-SNAPSHOT</version>
<version>6.0.11</version>
</parent>

<!-- ====================================================================== -->
Expand Down
Original file line number Diff line number Diff line change
@@ -1,115 +0,0 @@
/*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2016 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.replication.dispatcher.impl;

import com.adobe.acs.commons.replication.dispatcher.DispatcherFlushRules;
import com.adobe.acs.commons.util.RequireAem;
import com.day.cq.replication.ReplicationAction;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.ReplicationOptions;
import org.apache.sling.discovery.DiscoveryService;
import org.apache.sling.distribution.DistributionRequestType;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;

import static org.apache.sling.distribution.event.DistributionEventProperties.DISTRIBUTION_PATHS;
import static org.apache.sling.distribution.event.DistributionEventProperties.DISTRIBUTION_TYPE;
import static org.apache.sling.distribution.event.DistributionEventTopics.AGENT_PACKAGE_DISTRIBUTED;
import static org.osgi.service.event.EventConstants.EVENT_TOPIC;

@Component(
immediate = true,
service = EventHandler.class,
property = {
EVENT_TOPIC + "=" + AGENT_PACKAGE_DISTRIBUTED
}
)
public class CloudDispatcherFlushRulesExecutor implements EventHandler {

private static final Logger log = LoggerFactory.getLogger(CloudDispatcherFlushRulesExecutor.class);

@Reference(target = "(distribution=cloud-ready)")
private RequireAem requireAem;

@Reference
private DiscoveryService discoveryService;

@Reference
private volatile List<DispatcherFlushRules> dispatcherFlushRules;

@Override
public void handleEvent(Event event) {
String distributionType = (String) event.getProperty(DISTRIBUTION_TYPE);

boolean isLeader = discoveryService.getTopology().getLocalInstance().isLeader();
// process the OSGi event on the leader author instance
if (isLeader) {
String[] distributionPaths = (String[]) event.getProperty(DISTRIBUTION_PATHS);
if (distributionPaths == null || distributionPaths.length == 0) {
log.debug("Skipping processing because the distribution paths are empty");
return;
}
ReplicationActionType actionType = getReplicationActionType(distributionType);
if (actionType != null) {
executeFlushRules(actionType, Arrays.asList(distributionPaths));
}
}
}

private void executeFlushRules(ReplicationActionType actionType, List<String> distributionPaths) {
ReplicationAction action = new ReplicationAction(actionType, distributionPaths.toArray(new String[0]), 0L, "", null);
ReplicationOptions opts = new ReplicationOptions();
log.debug("Executing dispatcher flush rules for distribution paths {}", distributionPaths);
for (DispatcherFlushRules dispatcherFlushRule : dispatcherFlushRules) {
try {
dispatcherFlushRule.preprocess(action, opts);
} catch (ReplicationException e) {
log.warn("Could not execute dispatcher flush rule for distribution paths [{}]", distributionPaths, e);
}
}
if (log.isInfoEnabled()) {
log.info("Executed flush rules for resources [{}]", distributionPaths);
}
}


private ReplicationActionType getReplicationActionType(String distributionType) {
DistributionRequestType requestType = DistributionRequestType.fromName(distributionType);
if (DistributionRequestType.ADD.equals(requestType)) {
return ReplicationActionType.ACTIVATE;
} else if (DistributionRequestType.DELETE.equals(requestType)) {
return ReplicationActionType.DEACTIVATE;
} else if (DistributionRequestType.TEST.equals(requestType)) {
return ReplicationActionType.TEST;
}
log.debug("Distribution request type {} not supported", requestType);
return null;
}


}
Original file line number Diff line number Diff line change
@@ -1,139 +0,0 @@
/*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2016 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.replication.dispatcher.impl;

import com.adobe.acs.commons.replication.dispatcher.DispatcherFlushFilter;
import com.adobe.acs.commons.replication.dispatcher.DispatcherFlusher;
import com.day.cq.replication.Agent;
import com.day.cq.replication.AgentFilter;
import com.day.cq.replication.AgentManager;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.ReplicationResult;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.distribution.DistributionRequest;
import org.apache.sling.distribution.DistributionRequestType;
import org.apache.sling.distribution.DistributionResponse;
import org.apache.sling.distribution.Distributor;
import org.apache.sling.distribution.SimpleDistributionRequest;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.propertytypes.ServiceRanking;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@ServiceRanking(-5000)
@Designate(ocd = CloudDispatcherFlusher.Config.class)
public class CloudDispatcherFlusher implements DispatcherFlusher {

private static final Logger log = LoggerFactory.getLogger(CloudDispatcherFlusher.class);

@ObjectClassDefinition
@interface Config {
@AttributeDefinition(description = "Agent names to trigger when executing a distribute invalidate (ex. publish, preview)")
String[] agent_names() default {"publish"};
}

@Reference
private Distributor distributor;

@Reference
private AgentManager agentManager;

private String[] agentNames;

@Activate
protected void activate(Config config) {
this.agentNames = config.agent_names();
}

@Override
public Map<Agent, ReplicationResult> flush(ResourceResolver resourceResolver, String... paths) {
Map<Agent, ReplicationResult> result = new HashMap<>();
DistributionRequest distributionRequest = new SimpleDistributionRequest(DistributionRequestType.INVALIDATE, false, paths);
for (String agentName : agentNames) {
DistributionResponse distributionResponse = distributor.distribute(agentName, resourceResolver, distributionRequest);
Agent agent = agentManager.getAgents().get(agentName);
if (agent != null) {
result.put(agent, toReplicationResult(distributionResponse));
}
}
log.debug("Executed dispatcher flush for paths {}", Arrays.asList(paths));
return result;
}

@Override
public Map<Agent, ReplicationResult> flush(ResourceResolver resourceResolver, ReplicationActionType actionType, boolean synchronous, String... paths) throws ReplicationException {
// see https://experienceleague.adobe.com/docs/experience-manager-cloud-service/content/implementing/content-delivery/caching.html?lang=en#sling-distribution
log.warn(
"Dispatcher flusher in cloud should use INVALIDATE distribution types from author, no custom action type and synchronous should be set, "
+ "refactor your code to use the DispatcherFlushRules.flush(resourceResolver, paths) method"
);
return flush(resourceResolver, paths);
}

@Override
public Map<Agent, ReplicationResult> flush(ResourceResolver resourceResolver, ReplicationActionType actionType, boolean synchronous, AgentFilter agentFilter, String... paths) throws ReplicationException {
// see https://experienceleague.adobe.com/docs/experience-manager-cloud-service/content/implementing/content-delivery/caching.html?lang=en#sling-distribution
log.warn(
"Dispatcher flusher in cloud should use INVALIDATE distribution types from author, no custom action type and synchronous should be set, "
+ "refactor your code to use the DispatcherFlushRules.flush(resourceResolver, paths) method"
);
return flush(resourceResolver, paths);
}

@Override
public final Agent[] getFlushAgents() {
return this.getAgents(new DispatcherFlushFilter());
}

/**
* {@inheritDoc}
*/
@Override
public final Agent[] getAgents(final AgentFilter agentFilter) {
final List<Agent> flushAgents = new ArrayList<Agent>();

for (final Agent agent : agentManager.getAgents().values()) {
if (agentFilter.isIncluded(agent)) {
flushAgents.add(agent);
}
}
return flushAgents.toArray(new Agent[flushAgents.size()]);
}

private ReplicationResult toReplicationResult(DistributionResponse distributionResponse) {
if (distributionResponse.isSuccessful()) {
return ReplicationResult.OK;
}
return new ReplicationResult(false, 500, distributionResponse.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,20 @@
package com.adobe.acs.commons.redirectmaps.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.ServletException;

import com.drew.lang.annotations.NotNull;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -36,31 +42,56 @@
* Servlet for adding a line into the redirect map text file
*/
@SlingServlet(methods = { "POST" }, resourceTypes = {
"acs-commons/components/utilities/redirectmappage" }, selectors = {
"addentry" }, extensions = { "json" }, metatype = false)
"acs-commons/components/utilities/redirectmappage" }, selectors = {
"addentry" }, extensions = { "json" }, metatype = false)
public class AddEntryServlet extends SlingAllMethodsServlet {

private static final long serialVersionUID = -1704915461516132101L;
private static final Logger log = LoggerFactory.getLogger(AddEntryServlet.class);

public static final String ETC_ACS_COMMONS_LISTS_COUNTRIES_JCR_CONTENT_LIST = "/etc/acs-commons/lists/countries/jcr:content/list";

// Disable this feature on AEM as a Cloud Service
@Reference(target="(distribution=classic)")
transient RequireAem requireAem;

Map<String, String> countries;

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
throws ServletException, IOException {
log.trace("doPost");

String source = request.getParameter("source");
String target = request.getParameter("target");
log.debug("Adding entry with {} {}", source, target);

Resource resource = request.getResourceResolver().getResource(ETC_ACS_COMMONS_LISTS_COUNTRIES_JCR_CONTENT_LIST);
if (Objects.nonNull(resource)) {
countries = new HashMap<>();
@NotNull
Iterable<Resource> children = resource.getChildren();
if(children != null){
for (Resource childResource : children) {
ValueMap valueMap = childResource.getValueMap();
if (valueMap != null) {
String title = valueMap.get("jcr:title", String.class);
String nodeValue = valueMap.get("value", String.class);
countries.put(nodeValue, title);
}
}
}
}
List<String> lines = RedirectEntriesUtils.readEntries(request);
if(countries != null && !countries.isEmpty()){
for (Map.Entry<String,String> country : countries.entrySet()) {
String genericSource = country.getKey()+":" +source;
String genericTarget= "/"+country.getKey()+"/"+country.getValue()+target;
lines.add(genericSource + " " + genericTarget);
}
}else{
lines.add(source + " " + target);
}

lines.add(source + " " + target);
log.debug("Added entry...");

RedirectEntriesUtils.updateRedirectMap(request, lines);
RedirectEntriesUtils.writeEntriesToResponse(request, response, "Added entry " + source + " " + target);
}
Expand Down
Loading
Loading