001/*
002 * (C) Copyright 2006-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 *     Nuxeo - initial API and implementation
018 */
019package org.nuxeo.ecm.platform.filemanager.utils;
020
021import java.io.File;
022import java.io.FileInputStream;
023import java.io.IOException;
024import java.io.InputStream;
025import java.net.MalformedURLException;
026import java.net.URL;
027import java.text.Normalizer;
028
029import org.apache.commons.io.IOUtils;
030import org.nuxeo.common.utils.IdUtils;
031import org.nuxeo.ecm.core.api.CoreSession;
032import org.nuxeo.ecm.core.api.DocumentModel;
033import org.nuxeo.ecm.core.api.DocumentModelList;
034import org.nuxeo.ecm.core.api.LifeCycleConstants;
035import org.nuxeo.ecm.core.api.PathRef;
036
037public final class FileManagerUtils {
038
039    // This is an utility class
040    private FileManagerUtils() {
041    }
042
043    /**
044     * Returns the contents of the file in a byte array.
045     *
046     * @deprecated since 7.2, use {@link IOUtils#toByteArray} instead
047     */
048    @Deprecated
049    public static byte[] getBytesFromFile(File file) throws IOException {
050        try (InputStream in = new FileInputStream(file)) {
051            return IOUtils.toByteArray(in);
052        }
053    }
054
055    /**
056     * Returns the fileName of a file.
057     */
058    public static String fetchFileName(File file) throws MalformedURLException {
059        // Fetching filename
060        URL pathUrl = file.toURI().toURL();
061        String[] pathArray = pathUrl.getFile().split("/");
062        return pathArray[pathArray.length - 1];
063    }
064
065    /**
066     * Returns the fileName of an uploaded file.
067     *
068     * @param fullName the full name that we need to parse
069     * @return the FileName String
070     */
071    // FIXME: badly named method
072    // FIXME: doesn't work in some corner cases, for instance a Unix filename
073    // with a \, or a DOS file with a /
074    public static String fetchFileName(String fullName) {
075        // Fetching filename
076        String ret = fullName;
077        int lastWinSeparator = fullName.lastIndexOf('\\');
078        int lastUnixSeparator = fullName.lastIndexOf('/');
079        int lastSeparator = Math.max(lastWinSeparator, lastUnixSeparator);
080        if (lastSeparator != -1) {
081            ret = fullName.substring(lastSeparator + 1, fullName.length());
082        }
083        return ret;
084    }
085
086    /**
087     * Returns the title.
088     *
089     * @param filename the file name
090     * @return the title
091     */
092    public static String fetchTitle(String filename) {
093        String title = filename.trim();
094        if (title.length() == 0) {
095            title = IdUtils.generateStringId();
096        }
097        return title;
098    }
099
100    /**
101     * Looks if an existing Document with the same filename exists.
102     */
103    public static DocumentModel getExistingDocByFileName(CoreSession documentManager, String path, String filename) {
104        // We must use the "file:content/name" sub-property which is the only
105        // one on which we can rely
106        // Note that the "file:content" property is handled in a particular way
107        // by NXQL, so we must use "content/name" instead of
108        // "file:content/name".
109        return getExistingDocByPropertyName(documentManager, path, filename, "content/name");
110    }
111
112    /**
113     * Looks if an existing Document with the same title exists.
114     */
115    public static DocumentModel getExistingDocByTitle(CoreSession documentManager, String path, String title) {
116        return getExistingDocByPropertyName(documentManager, path, title, "dc:title");
117    }
118
119    /**
120     * Looks if an existing Document has the same value for a given property.
121     */
122    public static DocumentModel getExistingDocByPropertyName(CoreSession documentManager, String path, String value,
123            String propertyName) {
124        value = Normalizer.normalize(value, Normalizer.Form.NFC);
125        DocumentModel existing = null;
126        String parentId = documentManager.getDocument(new PathRef(path)).getId();
127        String query = "SELECT * FROM Document WHERE ecm:parentId = '" + parentId + "' AND " + propertyName + " = '"
128                + value.replace("'", "\\\'") + "' AND ecm:currentLifeCycleState != '" + LifeCycleConstants.DELETED_STATE
129                + "'";
130        DocumentModelList docs = documentManager.query(query, 1);
131        if (docs.size() > 0) {
132            existing = docs.get(0);
133        }
134        return existing;
135    }
136
137}