001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Anahide Tchertchian
018 */
019package org.nuxeo.ecm.web.resources.wro.processor;
020
021import ro.isdc.wro.config.ReadOnlyContext;
022import ro.isdc.wro.model.group.Inject;
023
024/**
025 * CSS URL rewriting processor, handling basePath variable replacement, and avoiding crash when one given URL cannot be
026 * rewritten.
027 *
028 * @since 7.4
029 */
030public class CssUrlRewritingProcessor extends ro.isdc.wro.model.resource.processor.impl.css.CssUrlRewritingProcessor {
031
032    protected static final String BASE_PATH_REGEXP = "\\$\\{basePath}";
033
034    protected static final String BASE_PATH = "${basePath}";
035
036    @Inject
037    private ReadOnlyContext context;
038
039    @Override
040    protected String replaceImageUrl(String cssUri, String imageUrl) {
041        // Can be null when using standalone context.
042        final String contextPath = context.getRequest() != null ? context.getRequest().getContextPath() : null;
043        String finalImageUrl = imageUrl;
044        if (imageUrl != null) {
045            // some resources begin with ../ instead of BASE_PATH (e.g: ../img/fancybox.png)
046            if (!imageUrl.contains(BASE_PATH) && imageUrl.startsWith("../")) {
047                finalImageUrl = imageUrl.replace("../", contextPath + "/");
048            } else {
049                finalImageUrl = imageUrl.replaceAll(BASE_PATH_REGEXP, contextPath);
050            }
051        }
052        return finalImageUrl;
053    }
054
055}