Skip to content

Commit

Permalink
SITES-18137: core.wcm.components.core: remove non-test use of Guava (#…
Browse files Browse the repository at this point in the history
…2654)

* SITES-18137: core.wcm.components.core: remove non-test use of Guava

Replaced usages of Guava with JavaSE and Apache Commons.

* Update AdaptiveImageServlet.java

Addressed change request by @vladbailescu

* SITES-18137: core.wcm.components.core: remove non-test use of Guava

Created new utility method imitating the bevavior of com.google.common.net.URL_FRAGMENT_ESCAPER
  • Loading branch information
mbaedke authored Jan 17, 2024
1 parent 18694ef commit 48ace5b
Show file tree
Hide file tree
Showing 12 changed files with 89 additions and 37 deletions.
4 changes: 4 additions & 0 deletions bundles/core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,10 @@
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
package com.adobe.cq.wcm.core.components.internal;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
Expand Down Expand Up @@ -54,7 +55,6 @@
import com.day.cq.wcm.api.designer.Designer;
import com.day.cq.wcm.api.designer.Style;
import com.day.cq.wcm.foundation.AllowedComponentList;
import com.google.common.collect.ImmutableSet;

import static com.adobe.cq.wcm.core.components.models.Image.PN_ALT_VALUE_FROM_DAM;
import static com.adobe.cq.wcm.core.components.models.Image.PN_ALT_VALUE_FROM_PAGE_IMAGE;
Expand All @@ -65,12 +65,12 @@ public class Utils {

private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);

private static final Set<String> INTERNAL_PARAMETER = ImmutableSet.of(
":formstart",
"_charset_",
":redirect",
":cq_csrf_token"
);
private static final Set<String> INTERNAL_PARAMETER = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
":formstart",
"_charset_",
":redirect",
":cq_csrf_token"
)));

private Utils() {
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@

import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.google.common.base.Joiner;

public class AdaptiveImageHelper {

Expand Down Expand Up @@ -124,12 +123,12 @@ public static String getRedirectLocation(SlingHttpServletRequest request, long l
}
if (lastModifiedSuffix > 0) {
suffix = StringUtils.replace(suffix, String.valueOf(lastModifiedSuffix), String.valueOf(lastModifiedEpoch));
redirectLocation = Joiner.on('.').join(Text.escapePath(request.getContextPath() + requestPathInfo.getResourcePath()),
requestPathInfo.getSelectorString(), requestPathInfo.getExtension() + Text.escapePath(suffix));
redirectLocation = Text.escapePath(request.getContextPath() + requestPathInfo.getResourcePath()) + "." +
requestPathInfo.getSelectorString() + "." + requestPathInfo.getExtension() + Text.escapePath(suffix);
} else if (request.getResource().isResourceType(IMAGE_RESOURCE_TYPE)) {
redirectLocation = Joiner.on('.').join(Text.escapePath(request.getContextPath() + requestPathInfo.getResourcePath()),
requestPathInfo.getSelectorString(), requestPathInfo.getExtension() + "/" + lastModifiedEpoch,
requestPathInfo.getExtension());
redirectLocation = Text.escapePath(request.getContextPath() + requestPathInfo.getResourcePath()) + "." +
requestPathInfo.getSelectorString() + "." + requestPathInfo.getExtension() + "/" +
lastModifiedEpoch + "." + requestPathInfo.getExtension();
} else {
String resourcePath = request.getPathInfo();
String extension = FilenameUtils.getExtension(resourcePath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.adobe.cq.wcm.core.components.internal.jackson;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
Expand All @@ -26,14 +27,13 @@
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.google.common.collect.ImmutableSet;

public class LinkHtmlAttributesSerializer extends StdSerializer<Map<String, String>> {

/**
* List of the link's ignored html attributes from the Json export.
*/
private static final Set<String> IGNORED_HTML_ATTRIBUTES = ImmutableSet.of("href");
private static final Set<String> IGNORED_HTML_ATTRIBUTES = Collections.singleton("href");

public LinkHtmlAttributesSerializer() { this(null); }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
package com.adobe.cq.wcm.core.components.internal.link;

import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
Expand All @@ -32,7 +33,6 @@
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.collect.ImmutableMap;

/**
* Wraps link information to be used in models.
Expand Down Expand Up @@ -148,7 +148,7 @@ private static Map<String, String> buildHtmlAttributes(String linkURL, Map<Strin
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
attributes.putAll(filteredAttributes);
}
return ImmutableMap.copyOf(attributes);
return Collections.unmodifiableMap(attributes);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import javax.annotation.PostConstruct;

import org.apache.commons.collections4.SetUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
Expand All @@ -37,7 +38,6 @@
import com.day.cq.dam.api.Asset;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.designer.Style;
import com.google.common.collect.ImmutableSet;

import static com.adobe.cq.wcm.core.components.commons.link.Link.PN_LINK_URL;

Expand All @@ -50,7 +50,7 @@ public class LinkManagerImpl implements LinkManager {
* <code>_self</code> is used in the edit dialog but not listed as allowed here as we do not
* want to render a target attribute at all when <code>_self</code> is selected.
*/
public static final Set<String> VALID_LINK_TARGETS = ImmutableSet.of("_blank", "_parent", "_top");
public static final Set<String> VALID_LINK_TARGETS = SetUtils.unmodifiableSet("_blank", "_parent", "_top");

/**
* Name of the resource property that for redirecting pages will indicate if original page or redirect target page should be returned.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,16 @@
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import java.util.stream.Collectors;

import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.lang3.StringUtils;
Expand Down Expand Up @@ -58,6 +61,27 @@ public class LinkUtil {
.collect(Collectors.toList()));
}

//SITES-18137: imitate the exact behavior of com.google.common.net.URL_FRAGMENT_ESCAPER
private static final BitSet URL_FRAGMENT_SAFE_CHARS = new BitSet(256);

static {
//alphanumeric characters
for(int i = 97; i <= 122; i++) {
URL_FRAGMENT_SAFE_CHARS.set(i);
}
for(int i = 65; i <= 90; i++) {
URL_FRAGMENT_SAFE_CHARS.set(i);
}
for(int i = 48; i <= 57; i++) {
URL_FRAGMENT_SAFE_CHARS.set(i);
}
// safe characters from Guava's URL_FRAGMENT_ESCAPER: -._~!$'()*,;&=@:+/?
byte[] nonAlphaNumeric = new byte[] { 45, 46, 95, 126, 33, 36, 39, 40, 41, 42, 44, 59, 38, 61, 64, 58, 43, 47, 63 };
for(int i = 0; i < nonAlphaNumeric.length; i++) {
URL_FRAGMENT_SAFE_CHARS.set(nonAlphaNumeric[i]);
}
}


/**
* Decodes and encoded or escaped URL taking care to not break Adobe Campaign expressions
Expand Down Expand Up @@ -138,6 +162,20 @@ public static String escape(final String path, final String queryString, final S
return unmasked;
}

/**
* Escapes an URI fragment, imitating the exact behavior of com.google.common.net.URL_FRAGMENT_ESCAPER.
* (SITES-18137)
*
* @param fragment The URI fragment
* @return The escaped fragment
*/
public static String escapeFragment(final String fragment) {
if (fragment == null) {
return null;
}
return new String(URLCodec.encodeUrl(URL_FRAGMENT_SAFE_CHARS, fragment.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
}

/**
* Masks a given {@link String} by replacing all occurrences of {@link LinkUtil#PATTERNS} with a placeholder.
* The generated placeholders are put into the given {@link Map} and can be used to unmask a {@link String} later on.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
Expand Down Expand Up @@ -45,7 +46,6 @@
import com.day.cq.wcm.api.policies.ContentPolicy;
import com.day.cq.wcm.api.policies.ContentPolicyManager;
import com.day.cq.wcm.commons.policy.ContentPolicyStyle;
import com.google.common.collect.ImmutableMap;

@Model(
adaptables = SlingHttpServletRequest.class,
Expand Down Expand Up @@ -202,7 +202,7 @@ Style getStyleForWrappedResource(Resource resource) {
@NotNull
protected EmbeddableData getComponentData() {
return DataLayerBuilder.extending(super.getComponentData()).asEmbeddable()
.withEmbeddableDetails(() -> ImmutableMap.of(PN_VIDEO_ID, videoId))
.withEmbeddableDetails(() -> Collections.singletonMap(PN_VIDEO_ID, videoId))
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,14 @@
import com.adobe.cq.wcm.core.components.internal.helper.image.AssetDeliveryHelper;
import com.adobe.cq.wcm.core.components.internal.models.v1.ImageAreaImpl;
import com.adobe.cq.wcm.core.components.internal.servlets.AdaptiveImageServlet;
import com.adobe.cq.wcm.core.components.internal.link.LinkUtil;
import com.adobe.cq.wcm.core.components.models.Image;
import com.adobe.cq.wcm.core.components.models.ImageArea;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.DamConstants;
import com.day.cq.dam.scene7.api.constants.Scene7AssetType;
import com.day.cq.dam.scene7.api.constants.Scene7Constants;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.net.UrlEscapers;

/**
* V2 Image model implementation.
Expand Down Expand Up @@ -187,7 +187,7 @@ protected void initModel() {
//check DM asset - check for "dam:scene7File" metadata value
String dmAssetName = asset.getMetadataValue(Scene7Constants.PN_S7_FILE);
if(isDmFeaturesEnabled && (!StringUtils.isEmpty(dmAssetName))){
dmAssetName = UrlEscapers.urlFragmentEscaper().escape(dmAssetName);
dmAssetName = LinkUtil.escapeFragment(dmAssetName);
//image is DM
dmImage = true;
useAssetDelivery = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
package com.adobe.cq.wcm.core.components.internal.services.seo;

import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.WeakHashMap;
import java.util.function.Predicate;

import org.apache.sling.api.resource.Resource;
Expand All @@ -39,8 +39,6 @@
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.TemplatedResource;
import com.day.cq.wcm.msm.api.LiveRelationshipManager;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
* An implementation of {@link SiteRootSelectionStrategy} that looks for a language navigation component on the given page and uses it's
Expand Down Expand Up @@ -79,7 +77,7 @@ public class LanguageNavigationSiteRootSelectionStrategy implements SiteRootSele
* meaning a consumer will call the public methods of this interface close after each other passing the same {@link Page} object to each
* method call. In this case, we don't need to traverse multiple times.
*/
private final Cache<Page, Optional<Resource>> languageNavigationCache = CacheBuilder.newBuilder().weakKeys().build();
private final WeakHashMap<Page, Optional<Resource>> languageNavigationCache = new WeakHashMap<>();

@Override
@Nullable
Expand All @@ -98,12 +96,15 @@ public int getStructuralDepth(@NotNull Page page) {
}

private Optional<Resource> findLanguageNavigation(Page page) {
try {
return languageNavigationCache.get(page, () -> findLanguageNavigation(page.getContentResource(), page));
} catch (ExecutionException ex) {
LOG.warn("Failed to find language navigation", ex);
return Optional.empty();
Optional<Resource> resource = languageNavigationCache.get(page);
if (resource == null) {
resource = findLanguageNavigation(page.getContentResource(), page);
if (resource == null || !resource.isPresent()) {
resource = Optional.empty();
}
languageNavigationCache.put(page, resource);
}
return resource;
}

private Optional<Resource> findLanguageNavigation(Resource contentResource, Page containingPage) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,6 @@
import com.day.cq.wcm.commons.WCMUtils;
import com.day.cq.wcm.foundation.WCMRenditionPicker;
import com.day.image.Layer;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.net.HttpHeaders;

import static com.adobe.cq.wcm.core.components.internal.Utils.getWrappedImageResourceWithInheritance;
import static com.adobe.cq.wcm.core.components.internal.helper.image.AdaptiveImageHelper.IMAGE_RESOURCE_TYPE;
Expand Down Expand Up @@ -656,7 +653,7 @@ private void stream(@NotNull SlingHttpServletResponse response, @NotNull InputSt
response.setContentType(contentType);
String extension = mimeTypeService.getExtension(contentType);
String disposition = "svg".equalsIgnoreCase(extension) ? "attachment" : "inline";
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, disposition + "; filename=" + URLEncoder.encode(imageName, CharEncoding.UTF_8));
response.setHeader("Content-Disposition", disposition + "; filename=" + URLEncoder.encode(imageName, CharEncoding.UTF_8));
IOUtils.copy(inputStream, response.getOutputStream());
}

Expand Down Expand Up @@ -852,7 +849,13 @@ private List<String> selectorToList(String selector) throws IllegalArgumentExcep
if (StringUtils.isEmpty(selector)) {
throw new IllegalArgumentException("Expected 1, 2 or 3 selectors instead got empty selector");
}
ArrayList<String> selectorList = Lists.newArrayList(Splitter.on('.').omitEmptyStrings().trimResults().split(selector));
ArrayList<String> selectorList = new ArrayList<>();
for (String s : selector.split("\\.")) {
String trimmed = s.trim();
if (!trimmed.isEmpty()) {
selectorList.add(trimmed);
}
}
if (selectorList.size() > 3) {
throw new IllegalArgumentException("Expected 1, 2 or 3 selectors, instead got: " + selectorList.size());
}
Expand Down
7 changes: 7 additions & 0 deletions parent/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,13 @@
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
Expand Down

0 comments on commit 48ace5b

Please sign in to comment.