001/*
002 * (C) Copyright 2006-2008 Nuxeo SAS (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.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 *     Alexandre Russel
016 *
017 * $Id$
018 */
019
020package org.nuxeo.ecm.platform.annotations.service;
021
022import java.net.MalformedURLException;
023import java.net.URI;
024import java.net.URISyntaxException;
025
026import org.nuxeo.ecm.core.api.NuxeoException;
027import org.nuxeo.ecm.platform.annotations.api.UriResolver;
028
029/**
030 * @author Alexandre Russel
031 */
032public class DefaultUriResolver implements UriResolver {
033    private static final String NUXEO_ANNOTATIONS = "nuxeo/Annotations/";
034
035    public String getBaseUrl(URI uri) {
036        if (uri == null) {
037            return null;
038        }
039        try {
040            String url = uri.toURL().toString();
041            if (url.contains(NUXEO_ANNOTATIONS)) {
042                return url.substring(0, url.indexOf(NUXEO_ANNOTATIONS) + NUXEO_ANNOTATIONS.length());
043            } else {
044                return url.substring(0, url.indexOf("nuxeo") + "nuxeo".length());
045            }
046        } catch (MalformedURLException e) {
047            return null; // urn
048        }
049    }
050
051    public URI getSearchURI(URI uri) {
052        return uri;
053    }
054
055    public URI translateFromGraphURI(URI uri, String baseUrl) {
056        if (uri.toString().startsWith("urn:annotation:")) {
057            String annId = uri.toString().substring(uri.toString().lastIndexOf(":") + 1);
058            try {
059                return new URI(baseUrl + annId);
060            } catch (URISyntaxException e) {
061                throw new NuxeoException(e);
062            }
063        }
064        return uri;
065    }
066
067    public URI translateToGraphURI(URI uri) {
068        String path = uri.getPath();
069        if (uri.toString().contains(NUXEO_ANNOTATIONS)) {
070            try {
071                return new URI("urn:annotation:" + path.substring(path.lastIndexOf("/") + 1));
072            } catch (URISyntaxException e) {
073                throw new NuxeoException(e);
074            }
075        } else {
076            return uri;
077        }
078    }
079}