001    /*
002     * 
003     * $Revision: 15270 $ $Date: 2009-05-25 17:27:57 +0200 (Mon, 25 May 2009) $
004     *
005     * This file is part of ***  M y C o R e  ***
006     * See http://www.mycore.de/ for details.
007     *
008     * This program is free software; you can use it, redistribute it
009     * and / or modify it under the terms of the GNU General Public License
010     * (GPL) as published by the Free Software Foundation; either version 2
011     * of the License or (at your option) any later version.
012     *
013     * This program is distributed in the hope that it will be useful, but
014     * WITHOUT ANY WARRANTY; without even the implied warranty of
015     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016     * GNU General Public License for more details.
017     *
018     * You should have received a copy of the GNU General Public License
019     * along with this program, in a file called gpl.txt or license.txt.
020     * If not, write to the Free Software Foundation Inc.,
021     * 59 Temple Place - Suite 330, Boston, MA  02111-1307 USA
022     */
023    
024    package org.mycore.frontend.fileupload;
025    
026    import java.io.BufferedOutputStream;
027    import java.io.File;
028    import java.io.FileOutputStream;
029    import java.io.IOException;
030    import java.io.InputStream;
031    import java.util.StringTokenizer;
032    
033    import org.mycore.common.MCRUtils;
034    import org.mycore.datamodel.metadata.MCRDerivate;
035    import org.mycore.datamodel.metadata.MCRObjectID;
036    import org.mycore.frontend.workflow.MCRSimpleWorkflowManager;
037    
038    /**
039     * This class stores files uploaded from the client applet as derivates into the
040     * workflow.
041     * 
042     * @author Harald Richter
043     * @author Jens Kupferschmidt
044     * @author Frank L\u00fctzenkirchen
045     * 
046     * @version $Revision: 15270 $ $Date: 2009-05-25 17:27:57 +0200 (Mon, 25 May 2009) $
047     * 
048     * @see MCRUploadHandler
049     */
050    public class MCRSWFUploadHandlerMyCoRe extends MCRUploadHandler {
051        private String mainfile = "";
052    
053        private File dirname;
054    
055        private String docId;
056    
057        private String derId;
058    
059        /**
060         * Creates MCRUploadHandler for MyCoRe
061         * 
062         * @param docId
063         *            document to which derivate belongs
064         * @param derId
065         *            derivate used to add files, if id="0" a new derivate is
066         *            created
067         * @param mode
068         *            "append" add files to derivate, replace old files "replace"
069         *            add files to derivate, delete old files "create" add files to
070         *            new derivate
071         * @param url
072         *            when MCRUploadApplet is finished this url will be shown
073         */
074        public MCRSWFUploadHandlerMyCoRe(String docId, String derId, String mode, String url) {
075            this.url = url;
076            logger.debug("MCRUploadHandlerMyCoRe DocID: " + docId + " DerId: " + derId + " Mode: " + mode);
077    
078            try {
079                new MCRObjectID(docId);
080                this.docId = docId;
081            } catch (Exception e) {
082                logger.debug("Error while creating MCRObjectID : " + docId, e);
083            }
084    
085            try {
086                new MCRObjectID(derId);
087                this.derId = derId;
088            } catch (Exception e) {
089                logger.debug("Error while creating MCRObjectID : " + derId, e);
090            }
091        }
092    
093        /**
094         * Start Upload for MyCoRe
095         */
096        public void startUpload(int numFiles) throws Exception {
097            MCRObjectID ID = new MCRObjectID(docId);
098            File workdir = MCRSimpleWorkflowManager.instance().getDirectoryPath(ID.getTypeId());
099            dirname = new File(workdir, derId);
100        }
101    
102        public long receiveFile(String path, InputStream in, long length, String md5) throws Exception {
103            // prepare to save
104            logger.debug("Upload file path: " + path);
105    
106            // convert path
107            String fname = path.replace(' ', '_');
108            try {
109                if (!dirname.isDirectory()) {
110                    dirname.mkdir();
111                    logger.debug("Create directory " + dirname);
112                }
113            } catch (Exception e) {
114            }
115            File newdir = dirname;
116            StringTokenizer st = new StringTokenizer(fname, "/");
117            int i = st.countTokens();
118            int j = 0;
119    
120            while (j < (i - 1)) {
121                newdir = new File(newdir, st.nextToken());
122                j++;
123    
124                try {
125                    if (!newdir.isDirectory()) {
126                        newdir.mkdir();
127                        logger.debug("Create directory " + newdir);
128                    }
129                } catch (Exception e) {
130                }
131            }
132    
133            String newfile = st.nextToken();
134    
135            // store file
136            File fout = new File(newdir, newfile);
137    
138            try {
139                BufferedOutputStream fouts = new BufferedOutputStream(new FileOutputStream(fout));
140                MCRUtils.copyStream(in, fouts);
141                fouts.close();
142                logger.info("Data object stored under " + fout.getName());
143            } catch (IOException e) {
144                logger.error("Can't store the data object " + fout.getName());
145            }
146    
147            // set mainfile
148            if (mainfile.length() == 0) {
149                mainfile = fname;
150            }
151    
152            long myLength = fout.length();
153            if (myLength >= length)
154                return myLength;
155            else {
156                fout.delete(); // Incomplete file transfer, user canceled upload
157                return 0;
158            }
159        }
160    
161        /**
162         * Finish upload, store derivate
163         * 
164         */
165        public void finishUpload() throws Exception {
166            // check for content
167            if (dirname.list().length == 0) {
168                dirname.delete();
169                logger.warn("No file were uploaded, delete directory " + dirname + " and return.");
170                return;
171            }
172            // add the mainfile entry
173            MCRDerivate der = new MCRDerivate();
174            try {
175                try {
176                    File derXMLFile = new File(dirname.getAbsolutePath() + ".xml");
177                    der.setFromURI(derXMLFile.toURI());
178                } catch (Exception e) {
179                    der = MCRSimpleWorkflowManager.instance().createDerivate(new MCRObjectID(docId), new MCRObjectID(derId));
180                }
181    
182                if (der.getDerivate().getInternals().getMainDoc().length() == 0) {
183                    der.getDerivate().getInternals().setMainDoc(mainfile);
184    
185                    byte[] outxml = MCRUtils.getByteArray(der.createXML());
186    
187                    try {
188                        FileOutputStream out = new FileOutputStream(dirname.getAbsolutePath() + ".xml");
189                        out.write(outxml);
190                        out.flush();
191                    } catch (IOException ex) {
192                        logger.error(ex.getMessage());
193                        logger.error("Exception while store to file " + dirname + ".xml");
194                    }
195                }
196            } catch (Exception e) {
197            }
198        }
199    }