001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Anahide Tchertchian
016 */
017package org.nuxeo.ecm.web.resources.wro.processor;
018
019import ro.isdc.wro.config.ReadOnlyContext;
020import ro.isdc.wro.model.group.Inject;
021
022/**
023 * CSS URL rewriting processor, handling basePath variable replacement, and avoiding crash when one given URL cannot be
024 * rewritten.
025 *
026 * @since 7.4
027 */
028public class CssUrlRewritingProcessor extends ro.isdc.wro.model.resource.processor.impl.css.CssUrlRewritingProcessor {
029
030    protected static final String BASE_PATH_REGEXP = "\\$\\{basePath}";
031
032    protected static final String BASE_PATH = "${basePath}";
033
034    @Inject
035    private ReadOnlyContext context;
036
037    @Override
038    protected String replaceImageUrl(String cssUri, String imageUrl) {
039        // Can be null when using standalone context.
040        final String contextPath = context.getRequest() != null ? context.getRequest().getContextPath() : null;
041        String finalImageUrl = imageUrl;
042        if (imageUrl != null) {
043            // some resources begin with ../ instead of BASE_PATH (e.g: ../img/fancybox.png)
044            if (!imageUrl.contains(BASE_PATH) && imageUrl.startsWith("../")) {
045                finalImageUrl = imageUrl.replace("../", contextPath + "/");
046            } else {
047                finalImageUrl = imageUrl.replaceAll(BASE_PATH_REGEXP, contextPath);
048            }
049        }
050        return finalImageUrl;
051    }
052
053}