001    /**
002     *  Licensed to the Apache Software Foundation (ASF) under one or more
003     *  contributor license agreements.  See the NOTICE file distributed with
004     *  this work for additional information regarding copyright ownership.
005     *  The ASF licenses this file to You under the Apache License, Version 2.0
006     *  (the "License"); you may not use this file except in compliance with
007     *  the License.  You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     *  Unless required by applicable law or agreed to in writing, software
012     *  distributed under the License is distributed on an "AS IS" BASIS,
013     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     *  See the License for the specific language governing permissions and
015     *  limitations under the License.
016     */
017    
018    package org.apache.geronimo.console.repository;
019    
020    import org.apache.commons.fileupload.FileItem;
021    import org.apache.commons.fileupload.FileUploadException;
022    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
023    import org.apache.commons.fileupload.portlet.PortletFileUpload;
024    import org.apache.commons.logging.Log;
025    import org.apache.commons.logging.LogFactory;
026    import org.apache.geronimo.console.BasePortlet;
027    import org.apache.geronimo.console.util.PortletManager;
028    import org.apache.geronimo.kernel.Kernel;
029    import org.apache.geronimo.kernel.KernelRegistry;
030    import org.apache.geronimo.kernel.repository.Artifact;
031    import org.apache.geronimo.kernel.repository.FileWriteMonitor;
032    import org.apache.geronimo.kernel.repository.ListableRepository;
033    import org.apache.geronimo.kernel.repository.WriteableRepository;
034    
035    import javax.portlet.ActionRequest;
036    import javax.portlet.ActionResponse;
037    import javax.portlet.PortletConfig;
038    import javax.portlet.PortletContext;
039    import javax.portlet.PortletException;
040    import javax.portlet.PortletRequestDispatcher;
041    import javax.portlet.RenderRequest;
042    import javax.portlet.RenderResponse;
043    import javax.portlet.WindowState;
044    import java.io.File;
045    import java.io.IOException;
046    import java.util.ArrayList;
047    import java.util.Arrays;
048    import java.util.Collections;
049    import java.util.Iterator;
050    import java.util.List;
051    import java.util.SortedSet;
052    
053    /**
054     * @version $Rev: 706640 $ $Date: 2008-10-21 14:44:05 +0000 (Tue, 21 Oct 2008) $
055     */
056    public class RepositoryViewPortlet extends BasePortlet {
057    
058        private final static Log log = LogFactory.getLog(RepositoryViewPortlet.class);
059    
060        private Kernel kernel;
061    
062        private PortletContext ctx;
063    
064        private PortletRequestDispatcher normalView;
065    
066        private PortletRequestDispatcher helpView;
067    
068        private PortletRequestDispatcher usageView;
069    
070        public void init(PortletConfig portletConfig) throws PortletException {
071            super.init(portletConfig);
072            kernel = KernelRegistry.getSingleKernel();
073            ctx = portletConfig.getPortletContext();
074            normalView = ctx
075                    .getRequestDispatcher("/WEB-INF/view/repository/normal.jsp");
076            helpView = ctx
077                    .getRequestDispatcher("/WEB-INF/view/repository/help.jsp");
078            usageView = ctx
079                    .getRequestDispatcher("/WEB-INF/view/repository/usage.jsp");
080        }
081    
082        public void processAction(ActionRequest actionRequest,
083                                  ActionResponse actionResponse) throws PortletException, IOException {
084            String action = actionRequest.getParameter("action");
085            if(action != null && action.equals("usage")) {
086                // User clicked on a repository entry to view usage
087                String res = actionRequest.getParameter("res");
088                actionResponse.setRenderParameter("mode", "usage");
089                actionResponse.setRenderParameter("res", res);
090                return;
091            }
092    
093            try {
094    
095    
096                List list = new ArrayList();
097                WriteableRepository repo = PortletManager.getCurrentServer(actionRequest).getWritableRepositories()[0];
098    
099                File uploadFile = null;
100                File file = null;
101                String name = null;
102                String basename = null;
103                String fileType = null;
104                String artifact = null;
105                String version = null;
106                String group = null;
107    
108                PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory());
109                try {
110                    List items = uploader.parseRequest(actionRequest);
111                    for (Iterator i = items.iterator(); i.hasNext();) {
112                        FileItem item = (FileItem) i.next();
113                        if (!item.isFormField()) {
114                            String fieldName = item.getFieldName().trim();
115                            name = item.getName().trim();
116    
117                            if (name.length() == 0) {
118                                file = null;
119                            } else {
120                                // IE sends full path while Firefox sends just basename
121                                // in the case of "FullName" we may be able to infer the group
122                                // Note, we can't use File.separatorChar because the file separator
123                                // is dependent upon the client and not the server.
124                                String fileChar = "\\";
125                                int fileNameIndex = name.lastIndexOf(fileChar);
126                                if (fileNameIndex == -1) {
127                                    fileChar = "/";
128                                    fileNameIndex = name.lastIndexOf(fileChar);
129                                }
130                                if (fileNameIndex != -1) {
131                                    basename = name.substring(fileNameIndex + 1);
132                                } else {
133                                    basename = name;
134                                }
135    
136                                // Create the temporary file to be used for import to the server
137                                file = File.createTempFile("geronimo-import", "");
138                                file.deleteOnExit();
139                                log.debug("Writing repository import file to " + file.getAbsolutePath());
140                            }
141    
142                            if ("local".equals(fieldName)) {
143                                uploadFile = file;
144                            }
145    
146                            if (file != null) {
147                                try {
148                                    item.write(file);
149                                } catch (Exception e) {
150                                    throw new PortletException(e);
151                                }
152                            }
153                            // This is not the file itself, but one of the form fields for the URI
154                        } else {
155                            String fieldName = item.getFieldName().trim();
156                            if ("group".equals(fieldName)) {
157                                group = item.getString().trim();
158                            } else if ("artifact".equals(fieldName)) {
159                                artifact = item.getString().trim();
160                            } else if ("version".equals(fieldName)) {
161                                version = item.getString().trim();
162                            } else if ("fileType".equals(fieldName)) {
163                                fileType = item.getString().trim();
164                            }
165                        }
166                    }
167    
168    
169                    repo.copyToRepository(file, new Artifact(group, artifact, version, fileType), new FileWriteMonitor() {
170                        public void writeStarted(String fileDescription, int fileSize) {
171                            log.info("Copying into repository " + fileDescription + "...");
172                        }
173    
174                        public void writeProgress(int bytes) {
175                        }
176    
177                        public void writeComplete(int bytes) {
178                            log.info("Finished.");
179                        }
180                    });
181                } catch (FileUploadException e) {
182                    throw new PortletException(e);
183                }
184            } catch (PortletException e) {
185                throw e;
186            }
187        }
188    
189        protected void doView(RenderRequest request, RenderResponse response)
190                throws PortletException, IOException {
191            // i think generic portlet already does this
192            if (WindowState.MINIMIZED.equals(request.getWindowState())) {
193                return;
194            }
195    
196            String mode = request.getParameter("mode");
197            if(mode != null && mode.equals("usage")) {
198                String res = request.getParameter("res");
199                String[] parts = res.split("/");
200                request.setAttribute("res", res);
201                request.setAttribute("groupId", parts[0]);
202                request.setAttribute("artifactId", parts[1]);
203                request.setAttribute("version", parts[2]);
204                request.setAttribute("type", parts[3]);
205                usageView.include(request, response);
206                return;
207            }
208    
209            try {
210                List list = new ArrayList();
211                ListableRepository[] repos = PortletManager.getCurrentServer(request).getRepositories();
212                for (int i = 0; i < repos.length; i++) {
213                    ListableRepository repo = repos[i];
214                    final SortedSet artifacts = repo.list();
215                    for (Iterator iterator = artifacts.iterator(); iterator.hasNext();) {
216                        String fileName = iterator.next().toString();
217                        list.add(fileName);
218                    }
219                }
220                Collections.sort(list);
221    
222                request.setAttribute("org.apache.geronimo.console.repo.list", list);
223    
224            } catch (Exception e) {
225                throw new PortletException(e);
226            }
227    
228            normalView.include(request, response);
229        }
230    
231        public void doHelp(RenderRequest request, RenderResponse response)
232                throws PortletException, IOException {
233            helpView.include(request, response);
234        }
235    
236        public List listing(File dir, String basepath) throws java.io.IOException {
237            if (dir == null) {
238                throw new IllegalArgumentException("directory argument is null");
239            }
240    
241            if (!dir.isDirectory()) {
242                throw new IllegalArgumentException("directory argument expected");
243            }
244    
245            List listing = new ArrayList();
246    
247            List ls = Arrays.asList(dir.listFiles());
248            Iterator iter = ls.iterator();
249    
250            while (iter.hasNext()) {
251                File f = (File) iter.next();
252    
253                if (f.isDirectory()) {
254                    List listing1 = listing(f, basepath);
255                    listing.addAll(listing1);
256                } else {
257                    listing.add(f.getCanonicalPath().substring(
258                            basepath.length() + 1));
259                }
260            }
261            return listing;
262        }
263    
264    }