Source Code Cross Referenced for ConnectorServlet.java in  » Ajax » zk » org » zkforge » fckez » connector » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Ajax » zk » org.zkforge.fckez.connector 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * FCKeditor - The text editor for internet
003:         * Copyright (C) 2003-2005 Frederico Caldeira Knabben
004:         * 
005:         * Licensed under the terms of the GNU Lesser General Public License:
006:         * 		http://www.opensource.org/licenses/lgpl-license.php
007:         * 
008:         * For further information visit:
009:         * 		http://www.fckeditor.net/
010:         * 
011:         * File Name: ConnectorServlet.java
012:         * 	Java Connector for Resource Manager class.
013:         * 
014:         * Version:  2.3
015:         * Modified: 2005-08-11 16:29:00
016:         * 
017:         * File Authors:
018:         * 		Simone Chiaretta (simo@users.sourceforge.net)
019:         */
020:
021:        package org.zkforge.fckez.connector;
022:
023:        import java.io.*;
024:        import javax.servlet.*;
025:        import javax.servlet.http.*;
026:        import java.util.*;
027:
028:        import org.apache.commons.fileupload.*;
029:        import org.apache.commons.fileupload.disk.DiskFileItemFactory;
030:        import org.apache.commons.fileupload.servlet.ServletFileUpload;
031:
032:        import javax.xml.parsers.*;
033:        import org.w3c.dom.*;
034:        import javax.xml.transform.*;
035:        import javax.xml.transform.dom.DOMSource;
036:        import javax.xml.transform.stream.StreamResult;
037:
038:        /**
039:         * Servlet to upload and browse files.<br>
040:         * 
041:         * This servlet accepts 4 commands used to retrieve and create files and folders
042:         * from a server directory. The allowed commands are:
043:         * <ul>
044:         * <li>GetFolders: Retrive the list of directory under the current folder
045:         * <li>GetFoldersAndFiles: Retrive the list of files and directory under the
046:         * current folder
047:         * <li>CreateFolder: Create a new directory under the current folder
048:         * <li>FileUpload: Send a new file to the server (must be sent with a POST)
049:         * </ul>
050:         * 
051:         * @author Simone Chiaretta (simo@users.sourceforge.net)
052:         */
053:
054:        public class ConnectorServlet extends HttpServlet {
055:
056:            private static String baseDir;
057:
058:            private static boolean debug = false;
059:
060:            /**
061:             * Initialize the servlet.<br>
062:             * Retrieve from the servlet configuration the "baseDir" which is the root
063:             * of the file repository:<br>
064:             * If not specified the value of "/UserFiles/" will be used.
065:             * 
066:             */
067:            public void init() throws ServletException {
068:                baseDir = getInitParameter("baseDir");
069:                debug = (new Boolean(getInitParameter("debug"))).booleanValue();
070:                if (baseDir == null)
071:                    baseDir = "/UserFiles/";
072:                String realBaseDir = getServletContext().getRealPath(baseDir);
073:                File baseFile = new File(realBaseDir);
074:                if (!baseFile.exists()) {
075:                    baseFile.mkdir();
076:                }
077:            }
078:
079:            /**
080:             * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br>
081:             * 
082:             * The servlet accepts commands sent in the following format:<br>
083:             * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br>
084:             * <br>
085:             * It execute the command and then return the results to the client in XML
086:             * format.
087:             * 
088:             */
089:            public void doGet(HttpServletRequest request,
090:                    HttpServletResponse response) throws ServletException,
091:                    IOException {
092:
093:                if (debug)
094:                    System.out.println("--- BEGIN DOGET ---");
095:
096:                response.setContentType("text/xml; charset=UTF-8");
097:                response.setHeader("Cache-Control", "no-cache");
098:                PrintWriter out = response.getWriter();
099:
100:                String commandStr = request.getParameter("Command");
101:                String typeStr = request.getParameter("Type");
102:                String currentFolderStr = request.getParameter("CurrentFolder");
103:
104:                String currentPath = baseDir + typeStr + currentFolderStr;
105:                String currentDirPath = getServletContext().getRealPath(
106:                        currentPath);
107:
108:                File currentDir = new File(currentDirPath);
109:                if (!currentDir.exists()) {
110:                    currentDir.mkdir();
111:                }
112:
113:                Document document = null;
114:                try {
115:                    DocumentBuilderFactory factory = DocumentBuilderFactory
116:                            .newInstance();
117:                    DocumentBuilder builder = factory.newDocumentBuilder();
118:                    document = builder.newDocument();
119:                } catch (ParserConfigurationException pce) {
120:                    pce.printStackTrace();
121:                }
122:
123:                Node root = CreateCommonXml(document, commandStr, typeStr,
124:                        currentFolderStr, request.getContextPath()
125:                                + currentPath);
126:
127:                if (debug)
128:                    System.out.println("Command = " + commandStr);
129:
130:                if (commandStr.equals("GetFolders")) {
131:                    getFolders(currentDir, root, document);
132:                } else if (commandStr.equals("GetFoldersAndFiles")) {
133:                    getFolders(currentDir, root, document);
134:                    getFiles(currentDir, root, document);
135:                } else if (commandStr.equals("CreateFolder")) {
136:                    String newFolderStr = request.getParameter("NewFolderName");
137:                    File newFolder = new File(currentDir, newFolderStr);
138:                    String retValue = "110";
139:
140:                    if (newFolder.exists()) {
141:                        retValue = "101";
142:                    } else {
143:                        try {
144:                            boolean dirCreated = newFolder.mkdir();
145:                            if (dirCreated)
146:                                retValue = "0";
147:                            else
148:                                retValue = "102";
149:                        } catch (SecurityException sex) {
150:                            retValue = "103";
151:                        }
152:
153:                    }
154:                    setCreateFolderResponse(retValue, root, document);
155:                }
156:
157:                document.getDocumentElement().normalize();
158:                try {
159:                    TransformerFactory tFactory = TransformerFactory
160:                            .newInstance();
161:                    Transformer transformer = tFactory.newTransformer();
162:
163:                    DOMSource source = new DOMSource(document);
164:
165:                    StreamResult result = new StreamResult(out);
166:                    transformer.transform(source, result);
167:
168:                    if (debug) {
169:                        StreamResult dbgResult = new StreamResult(System.out);
170:                        transformer.transform(source, dbgResult);
171:                        System.out.println("");
172:                        System.out.println("--- END DOGET ---");
173:                    }
174:
175:                } catch (Exception ex) {
176:                    ex.printStackTrace();
177:                }
178:
179:                out.flush();
180:                out.close();
181:            }
182:
183:            /**
184:             * Manage the Post requests (FileUpload).<br>
185:             * 
186:             * The servlet accepts commands sent in the following format:<br>
187:             * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br>
188:             * <br>
189:             * It store the file (renaming it in case a file with the same name exists)
190:             * and then return an HTML file with a javascript command in it.
191:             * 
192:             */
193:            public void doPost(HttpServletRequest request,
194:                    HttpServletResponse response) throws ServletException,
195:                    IOException {
196:
197:                if (debug)
198:                    System.out.println("--- BEGIN DOPOST ---");
199:
200:                response.setContentType("text/html; charset=UTF-8");
201:                response.setHeader("Cache-Control", "no-cache");
202:                PrintWriter out = response.getWriter();
203:
204:                String commandStr = request.getParameter("Command");
205:                String typeStr = request.getParameter("Type");
206:                String currentFolderStr = request.getParameter("CurrentFolder");
207:
208:                String currentPath = baseDir + typeStr + currentFolderStr;
209:                String currentDirPath = getServletContext().getRealPath(
210:                        currentPath);
211:
212:                if (debug)
213:                    System.out.println(currentDirPath);
214:
215:                String retVal = "0";
216:                String newName = "";
217:
218:                if (!commandStr.equals("FileUpload"))
219:                    retVal = "203";
220:                else {
221:                    DiskFileItemFactory factory = new DiskFileItemFactory();
222:                    ServletFileUpload upload = new ServletFileUpload(factory);
223:                    //DiskFileUpload upload = new DiskFileUpload();
224:                    try {
225:                        List items = upload.parseRequest(request);
226:
227:                        Map fields = new HashMap();
228:
229:                        Iterator iter = items.iterator();
230:                        while (iter.hasNext()) {
231:                            FileItem item = (FileItem) iter.next();
232:                            if (item.isFormField())
233:                                fields.put(item.getFieldName(), item
234:                                        .getString());
235:                            else
236:                                fields.put(item.getFieldName(), item);
237:                        }
238:                        FileItem uplFile = (FileItem) fields.get("NewFile");
239:                        String fileNameLong = uplFile.getName();
240:                        fileNameLong = fileNameLong.replace('\\', '/');
241:                        String[] pathParts = fileNameLong.split("/");
242:                        String fileName = pathParts[pathParts.length - 1];
243:
244:                        String nameWithoutExt = getNameWithoutExtension(fileName);
245:                        String ext = getExtension(fileName);
246:                        File pathToSave = new File(currentDirPath, fileName);
247:                        int counter = 1;
248:                        while (pathToSave.exists()) {
249:                            newName = nameWithoutExt + "(" + counter + ")"
250:                                    + "." + ext;
251:                            retVal = "201";
252:                            pathToSave = new File(currentDirPath, newName);
253:                            counter++;
254:                        }
255:                        uplFile.write(pathToSave);
256:                    } catch (Exception ex) {
257:                        retVal = "203";
258:                    }
259:
260:                }
261:
262:                out.println("<script type=\"text/javascript\">");
263:                out
264:                        .println("window.parent.frames['frmUpload'].OnUploadCompleted("
265:                                + retVal + ",'" + newName + "');");
266:                out.println("</script>");
267:                out.flush();
268:                out.close();
269:
270:                if (debug)
271:                    System.out.println("--- END DOPOST ---");
272:
273:            }
274:
275:            private void setCreateFolderResponse(String retValue, Node root,
276:                    Document doc) {
277:                Element myEl = doc.createElement("Error");
278:                myEl.setAttribute("number", retValue);
279:                root.appendChild(myEl);
280:            }
281:
282:            private void getFolders(File dir, Node root, Document doc) {
283:                Element folders = doc.createElement("Folders");
284:                root.appendChild(folders);
285:                File[] fileList = dir.listFiles();
286:                for (int i = 0; i < fileList.length; ++i) {
287:                    if (fileList[i].isDirectory()) {
288:                        Element myEl = doc.createElement("Folder");
289:                        myEl.setAttribute("name", fileList[i].getName());
290:                        folders.appendChild(myEl);
291:                    }
292:                }
293:            }
294:
295:            private void getFiles(File dir, Node root, Document doc) {
296:                Element files = doc.createElement("Files");
297:                root.appendChild(files);
298:                File[] fileList = dir.listFiles();
299:                for (int i = 0; i < fileList.length; ++i) {
300:                    if (fileList[i].isFile()) {
301:                        Element myEl = doc.createElement("File");
302:                        myEl.setAttribute("name", fileList[i].getName());
303:                        myEl.setAttribute("size", "" + fileList[i].length()
304:                                / 1024);
305:                        files.appendChild(myEl);
306:                    }
307:                }
308:            }
309:
310:            private Node CreateCommonXml(Document doc, String commandStr,
311:                    String typeStr, String currentPath, String currentUrl) {
312:
313:                Element root = doc.createElement("Connector");
314:                doc.appendChild(root);
315:                root.setAttribute("command", commandStr);
316:                root.setAttribute("resourceType", typeStr);
317:
318:                Element myEl = doc.createElement("CurrentFolder");
319:                myEl.setAttribute("path", currentPath);
320:                myEl.setAttribute("url", currentUrl);
321:                root.appendChild(myEl);
322:
323:                return root;
324:
325:            }
326:
327:            /*
328:             * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF
329:             * bug #991489
330:             */
331:            private static String getNameWithoutExtension(String fileName) {
332:                return fileName.substring(0, fileName.lastIndexOf("."));
333:            }
334:
335:            /*
336:             * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF
337:             * bug #991489
338:             */
339:            private String getExtension(String fileName) {
340:                return fileName.substring(fileName.lastIndexOf(".") + 1);
341:            }
342:
343:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.