001/*
002 * (C) Copyright 2006-2007 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 *     Nuxeo - initial API and implementation
018 *
019 * $Id: DocumentFileCodec.java 29556 2008-01-23 00:59:39Z jcarsique $
020 */
021
022package org.nuxeo.ecm.platform.url.codec;
023
024import java.io.UnsupportedEncodingException;
025import java.net.URLDecoder;
026import java.util.HashMap;
027import java.util.Map;
028import java.util.regex.Matcher;
029import java.util.regex.Pattern;
030
031import org.apache.commons.logging.Log;
032import org.apache.commons.logging.LogFactory;
033import org.nuxeo.common.utils.StringUtils;
034import org.nuxeo.common.utils.URIUtils;
035import org.nuxeo.ecm.core.api.DocumentLocation;
036import org.nuxeo.ecm.core.api.DocumentModel;
037import org.nuxeo.ecm.core.api.DocumentRef;
038import org.nuxeo.ecm.core.api.IdRef;
039import org.nuxeo.ecm.core.api.impl.DocumentLocationImpl;
040import org.nuxeo.ecm.core.utils.DocumentModelUtils;
041import org.nuxeo.ecm.platform.url.DocumentViewImpl;
042import org.nuxeo.ecm.platform.url.api.DocumentView;
043import org.nuxeo.ecm.platform.url.service.AbstractDocumentViewCodec;
044
045public class DocumentFileCodec extends AbstractDocumentViewCodec {
046
047    public static final String FILE_PROPERTY_PATH_KEY = "FILE_PROPERTY_PATH";
048
049    /**
050     * @deprecated soon will be part of the file property, passed as parameter for now
051     */
052    @Deprecated
053    public static final String FILENAME_PROPERTY_PATH_KEY = "FILENAME_PROPERTY_PATH";
054
055    public static final String FILENAME_KEY = "FILENAME";
056
057    private static final Log log = LogFactory.getLog(DocumentFileCodec.class);
058
059    // nxdoc/server/docId/property_path/filename/?requestParams
060    public static final String URLPattern = "/(\\w+)/([a-zA-Z_0-9\\-]+)(/([a-zA-Z_0-9/:\\-\\.\\]\\[]*))+(/([^\\?]*))+(\\?)?(.*)?";
061
062    public DocumentFileCodec() {
063    }
064
065    public DocumentFileCodec(String prefix) {
066        this.prefix = prefix;
067    }
068
069    @Override
070    public String getUrlFromDocumentView(DocumentView docView) {
071        DocumentLocation docLoc = docView.getDocumentLocation();
072        String filepath = docView.getParameter(FILE_PROPERTY_PATH_KEY);
073        String filename = docView.getParameter(FILENAME_KEY);
074        if (docLoc != null && filepath != null && filename != null) {
075            StringBuilder buf = new StringBuilder();
076            buf.append(getPrefix());
077            buf.append("/");
078            buf.append(docLoc.getServerName());
079            buf.append("/");
080            buf.append(docLoc.getDocRef().toString());
081            buf.append("/");
082            buf.append(filepath);
083            buf.append("/");
084            buf.append(URIUtils.quoteURIPathToken(filename));
085            String uri = buf.toString();
086            Map<String, String> requestParams = new HashMap<String, String>(docView.getParameters());
087            requestParams.remove(FILE_PROPERTY_PATH_KEY);
088            requestParams.remove(FILENAME_KEY);
089            return URIUtils.addParametersToURIQuery(uri, requestParams);
090        }
091        return null;
092    }
093
094    /**
095     * Extracts document location from a Zope-like URL ie : server/path_or_docId/view_id/tab_id .
096     */
097    @Override
098    public DocumentView getDocumentViewFromUrl(String url) {
099        final Pattern pattern = Pattern.compile(getPrefix() + URLPattern);
100        Matcher m = pattern.matcher(url);
101        if (m.matches()) {
102            if (m.groupCount() >= 4) {
103
104                // for debug
105                // for (int i = 1; i < m.groupCount() + 1; i++) {
106                // System.err.println(i + ": " + m.group(i));
107                // }
108
109                final String server = m.group(1);
110                String uuid = m.group(2);
111                final DocumentRef docRef = new IdRef(uuid);
112
113                // get other parameters
114
115                Map<String, String> params = new HashMap<String, String>();
116                if (m.groupCount() >= 4) {
117                    String filePropertyPath = m.group(4);
118                    params.put(FILE_PROPERTY_PATH_KEY, filePropertyPath);
119                }
120
121                if (m.groupCount() >= 6) {
122                    String filename = m.group(6);
123                    try {
124                        filename = URLDecoder.decode(filename, "UTF-8");
125                    } catch (UnsupportedEncodingException e) {
126                        filename = StringUtils.toAscii(filename);
127                    }
128                    int jsessionidIndex = filename.indexOf(";jsessionid");
129                    if (jsessionidIndex != -1) {
130                        filename = filename.substring(0, jsessionidIndex);
131                    }
132                    params.put(FILENAME_KEY, filename);
133                }
134
135                if (m.groupCount() >= 8) {
136                    String query = m.group(8);
137                    Map<String, String> requestParams = URIUtils.getRequestParameters(query);
138                    if (requestParams != null) {
139                        params.putAll(requestParams);
140                    }
141                }
142
143                final DocumentLocation docLoc = new DocumentLocationImpl(server, docRef);
144
145                return new DocumentViewImpl(docLoc, null, params);
146            }
147        }
148
149        return null;
150    }
151
152    public static String getFilename(DocumentModel doc, DocumentView docView) {
153        String filename = docView.getParameter(FILENAME_KEY);
154        if (filename == null) {
155            // try to get it from document
156            String propertyPath = docView.getParameter(FILENAME_PROPERTY_PATH_KEY);
157            String propertyName = DocumentModelUtils.decodePropertyName(propertyPath);
158            if (propertyName != null) {
159                filename = (String) DocumentModelUtils.getPropertyValue(doc, propertyName);
160            }
161        }
162        return filename;
163    }
164
165}