001/*
002 * (C) Copyright Nuxeo Corp. (http://nuxeo.com/)
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 *     Antoine Taillefer <ataillefer@nuxeo.com>
018 */
019package org.nuxeo.web.ui.url.codec;
020
021import java.util.ArrayList;
022import java.util.Arrays;
023import java.util.List;
024
025import org.apache.commons.lang.StringUtils;
026import org.nuxeo.ecm.core.api.DocumentLocation;
027import org.nuxeo.ecm.core.api.IdRef;
028import org.nuxeo.ecm.core.api.impl.DocumentLocationImpl;
029import org.nuxeo.ecm.platform.url.DocumentViewImpl;
030import org.nuxeo.ecm.platform.url.api.DocumentView;
031import org.nuxeo.ecm.platform.url.service.AbstractDocumentViewCodec;
032
033/**
034 * Codec handling document URL pointing to the Web UI for notification templates.
035 *
036 * @since 8.10
037 */
038public class WebNotificationDocumentIdCodec extends AbstractDocumentViewCodec {
039
040    protected static final List<String> WEB_UI_URL_PREFIXES = Arrays.asList("ui", "#!");
041
042    @Override
043    public String getUrlFromDocumentView(DocumentView docView) {
044        DocumentLocation docLoc = docView.getDocumentLocation();
045        if (docLoc == null) {
046            return null;
047        }
048        IdRef docRef = docLoc.getIdRef();
049        if (docRef == null) {
050            return null;
051        }
052        List<String> fragments = new ArrayList<String>();
053        fragments.addAll(WEB_UI_URL_PREFIXES);
054        fragments.add(getPrefix());
055        fragments.add(docLoc.getServerName());
056        fragments.add(docRef.toString());
057        return StringUtils.join(fragments, "/");
058    }
059
060    @Override
061    public DocumentView getDocumentViewFromUrl(String url) {
062        String path = url;
063        if (path.startsWith("/")) {
064            path = path.substring(1);
065        }
066        String[] fragments = path.split("/");
067        int prefixCount = WEB_UI_URL_PREFIXES.size();
068        if (fragments.length < prefixCount + 3 || !getPrefix().equals(fragments[prefixCount])) {
069            return null;
070        }
071        return new DocumentViewImpl(
072                new DocumentLocationImpl(fragments[prefixCount + 1], new IdRef(fragments[prefixCount + 2])));
073    }
074
075}