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