001/*
002 * (C) Copyright 2016 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 *     Estelle Giuly <egiuly@nuxeo.com>
018 */
019
020package org.nuxeo.ecm.core.io.download;
021
022import java.util.Arrays;
023
024import org.nuxeo.ecm.core.schema.SchemaManager;
025import org.nuxeo.runtime.api.Framework;
026
027/**
028 * This class exposes information of a blob given its download path. For instance, it parses the download path
029 * "default/3727ef6b-cf8c-4f27-ab2c-79de0171a2c8/files:files/0/file/image.png" into:
030 *
031 * <pre>
032 * {
033 *   "repository": "default",
034 *   "docId": "3727ef6b-cf8c-4f27-ab2c-79de0171a2c8",
035 *   "xpath": "files:files/0/file",
036 *   "filename": "image.png"
037 * }
038 * </pre>
039 *
040 * @since 9.1
041 */
042public class DownloadBlobInfo {
043    protected final String repository;
044
045    protected final String docId;
046
047    protected final String xpath;
048
049    protected final String filename;
050
051    public DownloadBlobInfo(String downloadPath) {
052        String[] parts = downloadPath.split("/");
053        int length = parts.length;
054        if (length < 2) {
055            throw new IllegalArgumentException("The path \"" + downloadPath + "\" is not used to download blobs.");
056        }
057        repository = parts[0];
058        docId = parts[1];
059        if (length == 2) {
060            xpath = null;
061            filename = null;
062        } else if (length == 3) {
063            xpath = parts[2];
064            filename = null;
065        } else {
066            String rest = String.join("/", Arrays.asList(parts).subList(2, length));
067            if (Framework.getService(SchemaManager.class).getField(rest) != null) {
068                xpath = rest;
069                filename = null;
070            } else {
071                xpath = String.join("/", Arrays.asList(parts).subList(2, length - 1));
072                filename = parts[length - 1];
073            }
074        }
075    }
076}