/* * 测试getParameterMap */ @Test public void testGetParameterMap_正常情况() throws Exception { byte[] bytes = content.getBytes("US-ASCII"); HttpServletRequest request = new MockHttpServletRequest(bytes, CONTENT_TYPE); Map map = LazyParser.getParameterMap(request); // assertEquals("4",map.size()); //FIXME // 在form表单中的field重复的情况下,也应该能返回重复的表单数据 FileItem f = (FileItem) map.get("file"); assertEquals("This is the content of the file\n", new String(f.getBout().toByteArray())); assertEquals("text/whatever", f.getContentType()); assertEquals("foo.tab", f.getFileName()); f = (FileItem) map.get("field"); assertEquals("fieldValue", f.getValue()); f = (FileItem) map.get("multi"); assertEquals("value1", f.getValue()); LazyParser.release(); }
@RequestMapping("/source") public void source( Model model, @RequestParam("id") String jarid, @RequestParam("clz") String clazzName, @RequestParam(value = "type", required = false, defaultValue = "asmdump") String type) { model.addAttribute("clzName", clazzName); model.addAttribute("id", jarid); if (Database.get(jarid) == null) { return; } FileItem path = (FileItem) Database.get(jarid).getObj(); model.addAttribute("jarFile", path); try { JarFile jarFile = new JarFile(path.getFullName()); String code = ""; JarEntry entry = jarFile.getJarEntry(clazzName); InputStream inputStream = jarFile.getInputStream(entry); if (type.equals("asmdump")) { code = asmDump(inputStream); } else if (type.equals("decomp")) { code = jclazzDecomp(clazzName, inputStream); } model.addAttribute("code", code); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@RequestMapping("/view") public void view( Model model, @RequestParam("id") String jar, @RequestParam(value = "clz", required = false) String clazzName) { clazzName = clazzName != null ? clazzName.replace('.', '/') : null; model.addAttribute("clzName", clazzName); model.addAttribute("id", jar); if (Database.get(jar) == null) { return; } FileItem path = (FileItem) Database.get(jar).getObj(); try { ClassMap classMap = ClassMap.build(new JarFile(new File(path.getFullName()).getCanonicalPath())); classMap.rebuildConfig(new RenameConfig(), null); model.addAttribute("classMap", classMap); model.addAttribute("origName", path.getOrigName()); // to find which package should open if (clazzName != null) { model.addAttribute("openPkg", classMap.getShortPackage(clazzName)); } } catch (IOException e) { e.printStackTrace(); } }
private static FileItem prepareFileItemFromInputStream( PipelineContext pipelineContext, InputStream inputStream, int scope) { // Get FileItem final FileItem fileItem = prepareFileItem(pipelineContext, scope); // Write to file OutputStream os = null; try { os = fileItem.getOutputStream(); copyStream(inputStream, os); } catch (IOException e) { throw new OXFException(e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { throw new OXFException(e); } } } // Create file if it doesn't exist (necessary when the file size is 0) final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation(); try { storeLocation.createNewFile(); } catch (IOException e) { throw new OXFException(e); } return fileItem; }
/** * Tests if the given object is the same as the this object. Two Properties got from an Item * with the same ID are equal. * * @param obj an object to compare with this object. * @return <code>true</code> if the given object is the same as this object, <code>false</code> * if not */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof FileItem)) { return false; } final FileItem fi = (FileItem) obj; return fi.getHost() == getHost() && fi.file.equals(file); }
@Override public int compareTo(FileItem another) { if (another.isDir()) { return -1; } else { return this.getName().compareTo(another.getName()); } }
/* * 测试getFileItemsFromRequest */ @Test public void testGetFileItemFromRequest_正常情况() throws Exception { byte[] bytes = content.getBytes("US-ASCII"); HttpServletRequest request = new MockHttpServletRequest(bytes, CONTENT_TYPE); List<FileItem> fileItem = LazyParser.getFileItemsFromRequest(request); assertEquals(1, fileItem.size()); FileItem f = fileItem.get(0); assertEquals("This is the content of the file\n", new String(f.getBout().toByteArray())); assertEquals("text/whatever", f.getContentType()); assertEquals("foo.tab", f.getFileName()); LazyParser.release(); }
@RequestMapping(value = "download") public View download(@RequestParam("id") String jarid) { FileItem path = (FileItem) Database.get(jarid).getObj(); StreamView view = null; try { File file = new File(path.getFullName()); view = new StreamView("application/x-jar", new FileInputStream(file)); view.setBufferSize(4 * 1024); view.setContentDisposition("attachment; filename=\"" + path.getOrigName() + "\""); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return view; }
public static String getNextFile(String path, int sortType) { if (path == null) return null; String upperPath = getPathFromFullpath(path, "/"); String name = getNameFromFullpath(path); ArrayList<FileItem> fileList = getFilelist(upperPath, true); sortFilelist(fileList, sortType); boolean foundPath = false; for (FileItem item : fileList) { if (foundPath == true) return item.getFullPath(); else if (item.name.compareTo(name) == 0) foundPath = true; } return null; }
@RequestMapping(value = "search") public String search( Model model, @RequestParam("id") String jarid, @RequestParam("q") final String query) { model.addAttribute("id", jarid); model.addAttribute("query", query); if (Database.get(jarid) == null) { return null; } FileItem path = (FileItem) Database.get(jarid).getObj(); model.addAttribute("jarFile", path); try { ClassMap classMap = ClassMap.build(new JarFile(new File(path.getFullName()).getCanonicalPath())); classMap.rebuildConfig(new RenameConfig(), null); model.addAttribute("classMap", classMap); final Set<String> matches = new TreeSet<String>(); ClassWalker walker = new ClassWalker() { @Override public void walk(ClassInfo classInfo) { if (classInfo.getClassShortName().equals(query)) { matches.add(classInfo.getClassName()); } } }; classMap.walk(walker); if (matches.size() == 1) { model.addAttribute("clz", matches.iterator().next()); return "redirect:/jarviewer/view.htm"; } model.addAttribute("matches", matches); } catch (IOException e) { e.printStackTrace(); } return "/jarviewer/search"; }
public void selectPreviousItem(FileItem currentItem) { if (currentItem == null) { return; } int myIndex = -1; for (int i = 0; i < getFileCount(); i++) { FileItem fileItem = getFileItem(i); if (fileItem == currentItem) { myIndex = i; } } if (myIndex > 0 && myIndex < getFileCount()) { currentItem.setStyleName("fileLabel"); // $NON-NLS-1$ FileItem nextItem = getFileItem(myIndex - 1); nextItem.setStyleName("fileLabelSelected"); // $NON-NLS-1$ setSelectedFileItem(nextItem); nextItem.fireFileSelectionEvent(); } }
/** 测试getParameter的正常情况 */ @Test public void testGetParameter_正常情况_上传文件() throws Exception { byte[] bytes = content.getBytes("US-ASCII"); HttpServletRequest request = new MockHttpServletRequest(bytes, CONTENT_TYPE); // 文件域 Object o = LazyParser.getParameter(request, "file"); assertTrue(o instanceof FileItem); FileItem f = (FileItem) o; assertEquals("This is the content of the file\n", new String(f.getBout().toByteArray())); assertEquals("text/whatever", f.getContentType()); assertEquals("foo.tab", f.getFileName()); // 普通域 o = LazyParser.getParameter(request, "field"); assertTrue(o instanceof FileItem); f = (FileItem) o; assertEquals("fieldValue", f.getValue()); LazyParser.release(); }
public File doAttachment(HttpServletRequest request) throws ServletException, IOException { File file = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<?> items = upload.parseRequest(request); Iterator<?> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { parameters .put(item.getFieldName(), item.getString("UTF-8")); } else { File tempFile = new File(item.getName()); file = new File(sc.getRealPath("/") + savePath, tempFile .getName()); item.write(file); } } } catch (Exception e) { Logger logger = Logger.getLogger(SendAttachmentMailServlet.class); logger.error("邮件发送出了异常", e); } return file; }
private static void deleteFileItem(FileItem fileItem, int scope) { if (logger.isDebugEnabled() && fileItem instanceof DiskFileItem) { final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation(); if (storeLocation != null) { final String temporaryFileName = storeLocation.getAbsolutePath(); final String scopeString = (scope == REQUEST_SCOPE) ? "request" : (scope == SESSION_SCOPE) ? "session" : "application"; logger.debug("Deleting temporary " + scopeString + "-scoped file: " + temporaryFileName); } } fileItem.delete(); }
private RenameConfig executeRename(String jar, String renameConfig) { RenameConfig config = RenameConfig.loadFromString(renameConfig); FileItem path = (FileItem) Database.get(jar).getObj(); String oldjar = path.getFullName(); String newjar = jar + "_" + path.getVersion(); File file = new File(Database.getConfig().getUploadPath(), newjar + ".upload"); String filePath = null; try { filePath = file.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } Renamer.rename(config, oldjar, filePath); path.setFulleName(filePath); Database.save("changelog-" + jar, Database.Util.nextId(), renameConfig); Database.save("file", jar, path); return config; }
/** * Add listener to fileItem which is going to be automatically destroyed on session destruction * * @param pipelineContext PipelineContext * @param fileItem FileItem */ public static void deleteFileOnSessionTermination( PipelineContext pipelineContext, final FileItem fileItem) { // Try to delete the file on exit and on session termination final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT); final ExternalContext.Session session = externalContext.getSession(false); if (session != null) { session.addListener( new ExternalContext.Session.SessionListener() { public void sessionDestroyed() { deleteFileItem(fileItem, SESSION_SCOPE); } }); } else { logger.debug( "No existing session found so cannot register temporary file deletion upon session destruction: " + fileItem.getName()); } }
/** * Add listener to fileItem which is going to be automatically destroyed when the servlet is * destroyed * * @param pipelineContext PipelineContext * @param fileItem FileItem */ public static void deleteFileOnContextDestroyed( PipelineContext pipelineContext, final FileItem fileItem) { // Try to delete the file on exit and on session termination final ExternalContext externalContext = (ExternalContext) pipelineContext.getAttribute(PipelineContext.EXTERNAL_CONTEXT); ExternalContext.Application application = externalContext.getApplication(); if (application != null) { application.addListener( new ExternalContext.Application.ApplicationListener() { public void servletDestroyed() { deleteFileItem(fileItem, APPLICATION_SCOPE); } }); } else { logger.debug( "No application object found so cannot register temporary file deletion upon session destruction: " + fileItem.getName()); } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input type="text|radio|checkbox|etc", select, etc). String fieldname = item.getFieldName(); String fieldvalue = item.getString(); // ... (do your job here) } else { // Process form file field (input type="file"). String fieldname = item.getFieldName(); String filename = FilenameUtils.getName(item.getName()); InputStream filecontent = item.getInputStream(); // ... (do your job here) } } } catch (FileUploadException e) { throw new ServletException("Cannot parse multipart request.", e); } // ... }
public void deselect() { for (int i = 0; i < filesList.getRowCount(); i++) { FileItem item = (FileItem) filesList.getWidget(i, 0); item.setStyleName("fileLabel"); // $NON-NLS-1$ } }
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id_book = "", len = ""; // Imposto il content type della risposta e prendo l'output response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // La dimensione massima di ogni singolo file su system int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB // Dimensione massima della request int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB // Cartella temporanea File cartellaTemporanea = new File("C:\\tempo"); try { // Creo un factory per l'accesso al filesystem DiskFileItemFactory factory = new DiskFileItemFactory(); // Setto la dimensione massima di ogni file, opzionale factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte); // Setto la cartella temporanea, Opzionale factory.setRepository(cartellaTemporanea); // Istanzio la classe per l'upload ServletFileUpload upload = new ServletFileUpload(factory); // Setto la dimensione massima della request, opzionale upload.setSizeMax(dimensioneMassimaDellaRequestInByte); // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con // tutti i field sia di tipo file che gli altri List<FileItem> items = upload.parseRequest(request); /* * * Giro per tutti i campi inviati */ for (int i = 0; i < items.size(); i++) { FileItem item = items.get(i); // Controllo se si tratta di un campo di input normale if (item.isFormField()) { // Prendo solo il nome e il valore String name = item.getFieldName(); String value = item.getString(); if (name.equals("id_book")) { id_book = value; } if (name.equals("len")) { len = value; } } // Se si stratta invece di un file ho varie possibilità else { // Dopo aver ripreso tutti i dati disponibili String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); // scrivo direttamente su filesystem File uploadedFile = new File("/Users/Babol/Desktop/dVruhero/aMuseWebsite/web/userPhoto/" + fileName); // Solo se veramente ho inviato qualcosa if (item.getSize() > 0) { item.write(uploadedFile); DBconnection.EditCoverBook(fileName, Integer.parseInt(id_book)); } } } // out.println("</body>"); // out.println("</html>"); } catch (Exception ex) { System.out.println("Errore: " + ex.getMessage()); } finally { if (len.equals("ita")) response.sendRedirect("modify_book.jsp?id_book=" + id_book); else response.sendRedirect("modify_book_eng.jsp?id_book=" + id_book); } }
/** * 文件的上传服务 * * @param request * @return * @throws FileUploadException * @throws IOException */ public FileRepository uploadFile(HttpServletRequest request) throws FileUploadException, IOException { boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); FileRepository fileRepository = null; if (isMultipartContent) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext(); ) { FileItem item = iterator.next(); InputStream inputStream = item.getInputStream(); // 获得文件名 String fileName = item.getName(); String fileExtension = FileUtil.getFileExtension(fileName); // 获得文件的Extension类型 MimeTypeExtension mimeTypeExtension = mimeTypeExtensionService.findByMimeTypeExtensionName(fileExtension); fileRepository = new FileRepository(); FixEntityUtil.fixEntity(fileRepository); String fileRepoId = fileRepository.getId(); fileRepository.setMimeTypeExtensionName(fileExtension); if (mimeTypeExtension.getMimeType() != null) { fileRepository.setMimeTypeName(mimeTypeExtension.getMimeType().getMimeTypeName()); } fileRepository.setFileName(fileName); String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date()); String saveFilePath = Config.UPLOAD_FILE_PATH + "/" + datePath + "/"; File file = new File(saveFilePath); if (!file.exists()) { file.mkdirs(); } file = new File(saveFilePath + fileRepoId + ".xzsoft"); ByteArrayOutputStream out = new ByteArrayOutputStream(); int byteRead = 0; byte[] buffer = new byte[8192]; while ((byteRead = inputStream.read(buffer, 0, 8192)) != -1) { out.write(buffer, 0, byteRead); } inputStream.close(); // 将上传的文件变Base64加密过的字符串 String content = Base64.encode(out.toByteArray()); out.close(); // 将加密过后的数据存储到硬盘中 FileWriter fileWriter = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fileWriter); bw.write(content); bw.flush(); fileWriter.flush(); bw.close(); fileWriter.close(); } } else { throw new NotMultipartRequestException("上传的文件里面没有Multipart内容"); } return fileRepository; }
/** * Utility method to decode a multipart/fomr-data stream and return a Map of parameters of type * Object[], each of which can be a String or FileData. */ public static Map<String, Object[]> getParameterMapMultipart( PipelineContext pipelineContext, final ExternalContext.Request request, String headerEncoding) { final Map<String, Object[]> uploadParameterMap = new HashMap<String, Object[]>(); try { // Setup commons upload // Read properties // NOTE: We use properties scoped in the Request generator for historical reasons. Not too // good. int maxSize = RequestGenerator.getMaxSizeProperty(); int maxMemorySize = RequestGenerator.getMaxMemorySizeProperty(); final DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(maxMemorySize, SystemUtils.getTemporaryDirectory()); final ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory) { protected FileItem createItem(Map headers, boolean isFormField) throws FileUploadException { if (isFormField) { // Handle externalized values final String externalizeFormValuesPrefix = org.orbeon.oxf.properties.Properties.instance() .getPropertySet() .getString(ServletExternalContext.EXTERNALIZE_FORM_VALUES_PREFIX_PROPERTY); final String fieldName = getFieldName(headers); if (externalizeFormValuesPrefix != null && fieldName.startsWith(externalizeFormValuesPrefix)) { // In this case, we do as if the value content is an uploaded file so that it can // be externalized return super.createItem(headers, false); } else { // Just create the FileItem using the default way return super.createItem(headers, isFormField); } } else { // Just create the FileItem using the default way return super.createItem(headers, isFormField); } } }; upload.setHeaderEncoding(headerEncoding); upload.setSizeMax(maxSize); // Add a listener to destroy file items when the pipeline context is destroyed pipelineContext.addContextListener( new PipelineContext.ContextListenerAdapter() { public void contextDestroyed(boolean success) { for (final String name : uploadParameterMap.keySet()) { final Object values[] = uploadParameterMap.get(name); for (final Object currentValue : values) { if (currentValue instanceof FileItem) { final FileItem fileItem = (FileItem) currentValue; fileItem.delete(); } } } } }); // Wrap and implement just the required methods for the upload code final InputStream inputStream; try { inputStream = request.getInputStream(); } catch (IOException e) { throw new OXFException(e); } final RequestContext requestContext = new RequestContext() { public int getContentLength() { return request.getContentLength(); } public InputStream getInputStream() { // NOTE: The upload code does not actually check that it doesn't read more than the // content-length // sent by the client! Maybe here would be a good place to put an interceptor and make // sure we // don't read too much. return new InputStream() { public int read() throws IOException { return inputStream.read(); } }; } public String getContentType() { return request.getContentType(); } public String getCharacterEncoding() { return request.getCharacterEncoding(); } }; // Parse the request and add file information try { for (Object o : upload.parseRequest(requestContext)) { final FileItem fileItem = (FileItem) o; // Add value to existing values if any if (fileItem.isFormField()) { // Simple form field // Assume that form fields are in UTF-8. Can they have another encoding? If so, how is // it specified? StringUtils.addValueToObjectArrayMap( uploadParameterMap, fileItem.getFieldName(), fileItem.getString(STANDARD_PARAMETER_ENCODING)); } else { // File StringUtils.addValueToObjectArrayMap( uploadParameterMap, fileItem.getFieldName(), fileItem); } } } catch (FileUploadBase.SizeLimitExceededException e) { // Should we do something smart so we can use the Presentation // Server error page anyway? Right now, this is going to fail // miserably with an error. throw e; } catch (UnsupportedEncodingException e) { // Should not happen throw new OXFException(e); } finally { // Close the input stream; if we don't nobody does, and if this stream is // associated with a temporary file, that file may resist deletion if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new OXFException(e); } } } return uploadParameterMap; } catch (FileUploadException e) { throw new OXFException(e); } }
@SuppressWarnings("unchecked") public void populateFilesList( SolutionBrowserPerspective perspective, SolutionTree solutionTree, TreeItem item) { filesList.clear(); ArrayList<Element> files = (ArrayList<Element>) item.getUserObject(); // let's sort this list based on localized name Collections.sort( files, new Comparator<Element>() { public int compare(Element o1, Element o2) { String name1 = o1.getAttribute("localized-name"); // $NON-NLS-1$ String name2 = o2.getAttribute("localized-name"); // $NON-NLS-1$ return name1.compareTo(name2); } }); if (files != null) { int rowCounter = 0; for (int i = 0; i < files.size(); i++) { Element fileElement = files.get(i); if ("false".equals(fileElement.getAttribute("isDirectory"))) { // $NON-NLS-1$ //$NON-NLS-2$ String name = fileElement.getAttribute("name"); // $NON-NLS-1$ String solution = solutionTree.getSolution(); String path = solutionTree.getPath(); String lastModifiedDateStr = fileElement.getAttribute("lastModifiedDate"); // $NON-NLS-1$ String url = fileElement.getAttribute("url"); // $NON-NLS-1$ ContentTypePlugin plugin = PluginOptionsHelper.getContentTypePlugin(name); String icon = null; if (plugin != null) { icon = plugin.getFileIcon(); } String localizedName = fileElement.getAttribute("localized-name"); String description = fileElement.getAttribute("description"); String tooltip = localizedName; if (solutionTree.isUseDescriptionsForTooltip() && !StringUtils.isEmpty(description)) { tooltip = description; } final FileItem fileLabel = new FileItem( name, localizedName, tooltip, solution, path, //$NON-NLS-1$ lastModifiedDateStr, url, this, PluginOptionsHelper.getEnabledOptions(name), toolbar.getSupportsACLs(), icon); // BISERVER-2317: Request for more IDs for Mantle UI elements // set element id as the filename fileLabel.getElement().setId("file-" + name); // $NON-NLS-1$ fileLabel.addFileSelectionChangedListener(toolbar); fileLabel.setWidth("100%"); // $NON-NLS-1$ try { perspective.getDragController().makeDraggable(fileLabel); } catch (Exception e) { Throwable throwable = e; String text = "Uncaught exception: "; while (throwable != null) { StackTraceElement[] stackTraceElements = throwable.getStackTrace(); text += throwable.toString() + "\n"; for (int ii = 0; ii < stackTraceElements.length; ii++) { text += " at " + stackTraceElements[ii] + "\n"; } throwable = throwable.getCause(); if (throwable != null) { text += "Caused by: "; } } DialogBox dialogBox = new DialogBox(true); DOM.setStyleAttribute(dialogBox.getElement(), "backgroundColor", "#ABCDEF"); System.err.print(text); text = text.replaceAll(" ", " "); dialogBox.setHTML("<pre>" + text + "</pre>"); dialogBox.center(); } filesList.setWidget(rowCounter++, 0, fileLabel); if (selectedFileItem != null && selectedFileItem.getFullPath().equals(fileLabel.getFullPath())) { fileLabel.setStyleName("fileLabelSelected"); // $NON-NLS-1$ selectedFileItem = fileLabel; } else { fileLabel.setStyleName("fileLabel"); // $NON-NLS-1$ } } } } }
@RequestMapping("/graphdata") public View graphdata( @RequestParam("id") final String jar, @RequestParam(value = "clz", required = false) final String clz, @RequestParam(value = "type", required = false) final String type) { FileItem path = (FileItem) Database.get(jar).getObj(); try { final ClassMap classMap = ClassMap.build(new JarFile(new File(path.getFullName()).getCanonicalPath())); classMap.rebuildConfig(new RenameConfig(), null); return new View() { @Override public String getContentType() { return "application/json"; // return "text/plain"; } @Override public void render( Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { BufferedWriter writer = new BufferedWriter(response.getWriter()); Map<String, List<ClassInfo>> tree = classMap.getTree(); int count = 0; Set<String> allObj = new HashSet<String>(); writer.write("{\"src\":\""); ClassInfo clzInfo = classMap.getClassInfo(clz); if (clzInfo != null) { // partial dep-graph if ("mydeps".equals(type)) { // deps of clz for (String dep : clzInfo.getDependencies()) { if (classMap.contains(dep)) { writeDep(writer, clz, dep); } } } else if ("depsonme".equals(type)) { // who depends on me ? for (Map.Entry<String, List<ClassInfo>> e : tree.entrySet()) { for (ClassInfo info : e.getValue()) { if (info.getDependencies().contains(clz)) { writeDep(writer, info.getClassName(), clz); } } } } writer.write(clz + " {color:red,link:'/'}"); } else { // all data for (Map.Entry<String, List<ClassInfo>> e : tree.entrySet()) { writer.write(";" + e.getKey() + "\\n"); for (ClassInfo clazz : e.getValue()) { for (String dep : clazz.getDependencies()) { if (classMap.contains(dep)) { allObj.add(clazz.getClassName()); allObj.add(dep); writeDep(writer, clazz.getClassShortName(), Utils.getShortName(dep)); count++; } } } writer.write(";// end of package " + e.getKey() + "\\n"); } } writer.write("; totally " + count + " edges.\\n"); // TODO link doesn't work,why? // for (String clz : allObj) { // writer.write(Utils.getShortName(clz) + // " {link:'view.htm?id=" + jar + "&clz=" + clz + "'}\\n"); // } writer.write("\"}\n"); writer.flush(); Utils.close(writer); } private void writeDep(Writer writer, final String src, String dest) throws IOException { writer.write(src); writer.write(" -> "); writer.write(dest); writer.write("\\n"); } }; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
/** * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code> * multipart/form-data</code> stream. If files are stored on disk, the path is given by <code> * getRepository()</code>. * * @param req The servlet request to be parsed. * @return A list of <code>FileItem</code> instances parsed from the request, in the order that * they were transmitted. * @exception FileUploadException if there are problems reading/parsing the request or storing * files. */ public List /* FileItem */ parseRequest(HttpServletRequest req) throws FileUploadException { if (null == req) { throw new NullPointerException("req parameter"); } ArrayList items = new ArrayList(); String contentType = req.getHeader(CONTENT_TYPE); if ((null == contentType) || (!contentType.startsWith(MULTIPART))) { throw new InvalidContentTypeException( "the request doesn't contain a " + MULTIPART_FORM_DATA + " or " + MULTIPART_MIXED + " stream, content type header is " + contentType); } int requestSize = req.getContentLength(); if (requestSize == -1) { throw new UnknownSizeException("the request was rejected because it's size is unknown"); } if (sizeMax >= 0 && requestSize > sizeMax) { throw new SizeLimitExceededException( "the request was rejected because " + "it's size exceeds allowed range"); } try { int boundaryIndex = contentType.indexOf("boundary="); if (boundaryIndex < 0) { throw new FileUploadException( "the request was rejected because " + "no multipart boundary was found"); } byte[] boundary = contentType.substring(boundaryIndex + 9).getBytes(); InputStream input = req.getInputStream(); MultipartStream multi = new MultipartStream(input, boundary); multi.setHeaderEncoding(headerEncoding); boolean nextPart = multi.skipPreamble(); while (nextPart) { Map headers = parseHeaders(multi.readHeaders()); String fieldName = getFieldName(headers); if (fieldName != null) { String subContentType = getHeader(headers, CONTENT_TYPE); if (subContentType != null && subContentType.startsWith(MULTIPART_MIXED)) { // Multiple files. byte[] subBoundary = subContentType.substring(subContentType.indexOf("boundary=") + 9).getBytes(); multi.setBoundary(subBoundary); boolean nextSubPart = multi.skipPreamble(); while (nextSubPart) { headers = parseHeaders(multi.readHeaders()); if (getFileName(headers) != null) { FileItem item = createItem(headers, false); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } items.add(item); } else { // Ignore anything but files inside // multipart/mixed. multi.discardBodyData(); } nextSubPart = multi.readBoundary(); } multi.setBoundary(boundary); } else { if (getFileName(headers) != null) { // A single file. FileItem item = createItem(headers, false); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } items.add(item); } else { // A form field. FileItem item = createItem(headers, true); OutputStream os = item.getOutputStream(); try { multi.readBodyData(os); } finally { os.close(); } items.add(item); } } } else { // Skip this part. multi.discardBodyData(); } nextPart = multi.readBoundary(); } } catch (IOException e) { throw new FileUploadException( "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage()); } return items; }