001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.automation.core.operations.blob;
013
014import java.net.URL;
015
016import org.nuxeo.ecm.automation.core.Constants;
017import org.nuxeo.ecm.automation.core.annotations.Operation;
018import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
019import org.nuxeo.ecm.automation.core.annotations.Param;
020import org.nuxeo.ecm.core.api.Blob;
021import org.nuxeo.ecm.core.api.impl.blob.URLBlob;
022
023/**
024 * TODO: detect mine?
025 *
026 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
027 */
028@Operation(id = CreateBlob.ID, category = Constants.CAT_FETCH, label = "File From URL", description = "Creates a file from a given URL. The file parameter specifies how to retrieve the file content. It should be an URL to the file you want to use as the source. You can also use an expression to get an URL from the context. Returns the created file.", aliases = { "Blob.Create" })
029public class CreateBlob {
030
031    public static final String ID = "Blob.CreateFromURL";
032
033    /** For tests. */
034    public static boolean skipProtocolCheck;
035
036    @Param(name = "file")
037    protected URL file;
038
039    @Param(name = "mime-type", required = false)
040    protected String mimeType;
041
042    @Param(name = "filename", required = false)
043    protected String fileName;
044
045    @Param(name = "encoding", required = false)
046    protected String encoding;
047
048    @OperationMethod
049    public Blob run() {
050        String protocol = file.getProtocol();
051        if (!"http".equals(protocol) && !"https".equals(protocol) && !"ftp".equals(protocol)) {
052            // don't let file: through
053            if (!skipProtocolCheck) {
054                return null;
055            }
056        }
057        if (fileName == null) {
058            fileName = file.getPath();
059            int i = fileName.lastIndexOf('/');
060            if (i > -1) {
061                fileName = fileName.substring(i + 1);
062            }
063        }
064        if (mimeType == null) { // TODO detect mime type
065
066        }
067        URLBlob blob = new URLBlob(file, mimeType, encoding);
068        blob.setFilename(fileName);
069        return blob;
070    }
071
072}