List of usage examples for javax.servlet.http Part getInputStream
public InputStream getInputStream() throws IOException;
From source file:org.grible.servlets.app.imp.StorageImport.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)//from ww w .j a v a 2s. com */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { if (Security.anyServletEntryCheckFailed(request, response)) { return; } String className = Streams.asString(request.getPart("class").getInputStream()); Part filePart = request.getPart("file"); String fileName = ServletHelper.getFilename(filePart); String storageName = StringUtils.substringBefore(fileName, ".xls"); int categoryId = Integer.parseInt(request.getParameter("category")); String categoryPath = StringHelper .getFolderPathWithoutLastSeparator(request.getParameter("categorypath")); int productId = Integer.parseInt(request.getParameter("product")); InputStream filecontent = filePart.getInputStream(); ExcelFile excelFile = new ExcelFile(filecontent, ServletHelper.isXlsx(fileName)); Category category = null; if (ServletHelper.isJson()) { jDao = new JsonDao(); category = new Category(categoryPath, TableType.STORAGE, productId); } else { pDao = new PostgresDao(); category = new Category(categoryId); } if (DataManager.getInstance().getDao().isTableInProductExist(storageName, TableType.STORAGE, category)) { Table table = null; int currentKeysCount = 0; if (ServletHelper.isJson()) { table = jDao.getTable(storageName, TableType.STORAGE, category); currentKeysCount = table.getTableJson().getKeys().length; } else { table = pDao.getTable(storageName, categoryId); currentKeysCount = table.getKeys().length; } int importedKeysCount = excelFile.getKeys().length; if (currentKeysCount != importedKeysCount) { throw new Exception("Parameters number is different.<br>In the current storage: " + currentKeysCount + ". In the Excel file: " + importedKeysCount + "."); } request.getSession(true).setAttribute("importedTable", table); request.getSession(false).setAttribute("importedFile", excelFile); String destination = "/storages/?product=" + productId + "&id=" + table.getId(); response.sendRedirect(destination); } else { int storageId = 0; Key[] keys = excelFile.getKeys(); String[][] values = excelFile.getValues(); storageId = DataManager.getInstance().getDao().insertTable(storageName, TableType.STORAGE, category, null, className, keys, values); String message = ""; if (className.equals("")) { message = "'" + storageName + "' storage was successfully imported. WARNING: Class name is empty."; } else if (!className.endsWith("Info")) { message = "'" + storageName + "' storage was successfully imported. WARNING: Class name does not end with 'Info'."; } else { message = "'" + storageName + "' storage was successfully imported."; } String destination = ""; if (storageId > 0) { destination = "/storages/?product=" + productId + "&id=" + storageId; } else { destination = "/storages/?product=" + productId; } request.getSession(true).setAttribute("importResult", message); response.sendRedirect(destination); } } catch (Exception e) { int productId = Integer.parseInt(request.getParameter("product")); String destination = "/storages/?product=" + productId; String message = Lang.get("error") + ": " + e.getMessage(); e.printStackTrace(); request.getSession(true).setAttribute("importResult", message); response.sendRedirect(destination); } }
From source file:org.grible.servlets.app.imp.TableImport.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/*ww w .ja va 2s . c om*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { if (Security.anyServletEntryCheckFailed(request, response)) { return; } Part filePart = request.getPart("file"); String fileName = ServletHelper.getFilename(filePart); String tableName = StringUtils.substringBefore(fileName, ".xls"); int categoryId = Integer.parseInt(request.getParameter("category")); String categoryPath = StringHelper .getFolderPathWithoutLastSeparator(request.getParameter("categorypath")); int productId = Integer.parseInt(request.getParameter("product")); InputStream filecontent = filePart.getInputStream(); ExcelFile excelFile = new ExcelFile(filecontent, ServletHelper.isXlsx(fileName)); Category category = null; if (ServletHelper.isJson()) { jDao = new JsonDao(); category = new Category(categoryPath, TableType.TABLE, productId); } else { pDao = new PostgresDao(); category = new Category(categoryId); } if (DataManager.getInstance().getDao().isTableInProductExist(tableName, TableType.TABLE, category)) { Table table = null; int currentKeysCount = 0; if (ServletHelper.isJson()) { table = jDao.getTable(tableName, TableType.TABLE, category); currentKeysCount = table.getTableJson().getKeys().length; } else { table = pDao.getTable(tableName, categoryId); currentKeysCount = table.getKeys().length; } int importedKeysCount = excelFile.getKeys().length; if (currentKeysCount != importedKeysCount) { throw new Exception("Parameters number is different.<br>In the current table: " + currentKeysCount + ". In the Excel file: " + importedKeysCount + "."); } request.getSession(true).setAttribute("importedTable", table); request.getSession(false).setAttribute("importedFile", excelFile); String destination = "/tables/?product=" + productId + "&id=" + table.getId(); response.sendRedirect(destination); } else { Key[] keys = excelFile.getKeys(); String[][] values = excelFile.getValues(); int tableId = DataManager.getInstance().getDao().insertTable(tableName, TableType.TABLE, category, null, null, keys, values); if (excelFile.hasPreconditions()) { Key[] precondKeys = getKeys(excelFile.getPrecondition()); String[][] precondValues = getValues(excelFile.getPrecondition()); DataManager.getInstance().getDao().insertTable(null, TableType.PRECONDITION, category, tableId, null, precondKeys, precondValues); } if (excelFile.hasPostconditions()) { Key[] postcondKeys = getKeys(excelFile.getPostcondition()); String[][] postcondValues = getValues(excelFile.getPostcondition()); DataManager.getInstance().getDao().insertTable(null, TableType.POSTCONDITION, category, tableId, null, postcondKeys, postcondValues); } String message = "'" + tableName + "' table was successfully imported."; request.getSession(true).setAttribute("importResult", message); String destination = "/tables/?product=" + productId + "&id=" + tableId; response.sendRedirect(destination); } } catch (Exception e) { int productId = Integer.parseInt(request.getParameter("product")); String destination = "/tables/?product=" + productId; String message = Lang.get("error") + ": " + e.getMessage(); e.printStackTrace(); request.getSession(true).setAttribute("importResult", message); response.sendRedirect(destination); } }
From source file:Service.FichierServiceImpl.java
private boolean ajoutFichierInterne(Part p, String nom) throws IOException { String s = ""; if (!"".equals(p.getSubmittedFileName())) { s += "bonjour"; String separator = System.getProperty("file.separator"); File f = new File(servletContext.getRealPath("/WEB-INF/files") + separator); File fdef = new File(f.getParentFile().getParentFile().getParentFile().getParentFile().getAbsolutePath() + separator + "web" + separator + "files" + separator + nom); fdef.delete();//from w w w . j a v a2s . com fdef.createNewFile(); try { s += "[[[[" + fdef.getAbsolutePath() + "]]]"; InputStream in = p.getInputStream(); OutputStream out = new FileOutputStream(fdef); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } catch (Exception e) { return false; } return true; } return false; }
From source file:org.nuxeo.ecm.platform.ui.web.util.files.FileUtils.java
/** * Creates a Blob from a {@link Part}./* w ww. j av a2 s. co m*/ * <p> * Attempts to capture the underlying temporary file, if one exists. This needs to use reflection to avoid having * dependencies on the application server. * * @param part the servlet part * @return the blob * @since 7.2 */ public static Blob createBlob(Part part) throws IOException { Blob blob = null; try { // part : org.apache.catalina.core.ApplicationPart // part.fileItem : org.apache.tomcat.util.http.fileupload.disk.DiskFileItem // part.fileItem.isInMemory() : false if on disk // part.fileItem.getStoreLocation() : java.io.File Field fileItemField = part.getClass().getDeclaredField("fileItem"); fileItemField.setAccessible(true); Object fileItem = fileItemField.get(part); if (fileItem != null) { Method isInMemoryMethod = fileItem.getClass().getDeclaredMethod("isInMemory"); boolean inMemory = ((Boolean) isInMemoryMethod.invoke(fileItem)).booleanValue(); if (!inMemory) { Method getStoreLocationMethod = fileItem.getClass().getDeclaredMethod("getStoreLocation"); File file = (File) getStoreLocationMethod.invoke(fileItem); if (file != null) { // move the file to a temporary blob we own blob = Blobs.createBlobWithExtension(null); Files.move(file.toPath(), blob.getFile().toPath(), StandardCopyOption.REPLACE_EXISTING); } } } } catch (ReflectiveOperationException | SecurityException | IllegalArgumentException e) { // unknown Part implementation } if (blob == null) { // if we couldn't get to the file, use the InputStream blob = Blobs.createBlob(part.getInputStream()); } blob.setMimeType(part.getContentType()); blob.setFilename(retrieveFilename(part)); return blob; }
From source file:org.ohmage.request.Request.java
/** * Reads the HttpServletRequest for a key-value pair and returns the value * where the key is equal to the given key. * // w w w .j a va2 s .c o m * @param httpRequest A "multipart/form-data" request that contains the * parameter that has a key value 'key'. * * @param key The key for the value we are after in the 'httpRequest'. * * @return Returns null if there is no such key in the request or if, * after reading the object, it has a length of 0. Otherwise, it * returns the value associated with the key as a byte array. * * @throws ServletException Thrown if the 'httpRequest' is not a * "multipart/form-data" request. * * @throws IOException Thrown if there is an error reading the value from * the request's input stream. * * @throws IllegalStateException Thrown if the entire request is larger * than the maximum allowed size for a * request or if the value of the requested * key is larger than the maximum allowed * size for a single value. */ protected byte[] getMultipartValue(HttpServletRequest httpRequest, String key) throws ValidationException { try { Part part = httpRequest.getPart(key); if (part == null) { return null; } // Get the input stream. InputStream partInputStream = part.getInputStream(); // Wrap the input stream in a GZIP de-compressor if it is GZIP'd. String contentType = part.getContentType(); if ((contentType != null) && contentType.contains("gzip")) { LOGGER.info("Part was GZIP'd: " + key); partInputStream = new GZIPInputStream(partInputStream); } // Parse the data. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] chunk = new byte[4096]; int amountRead; while ((amountRead = partInputStream.read(chunk)) != -1) { outputStream.write(chunk, 0, amountRead); } if (outputStream.size() == 0) { return null; } else { return outputStream.toByteArray(); } } catch (ServletException e) { LOGGER.error("This is not a multipart/form-data POST.", e); setFailed(ErrorCode.SYSTEM_GENERAL_ERROR, "This is not a multipart/form-data POST which is what we expect for the current API call."); throw new ValidationException(e); } catch (IOException e) { LOGGER.info("There was a problem with the zipping of the data.", e); throw new ValidationException(ErrorCode.SERVER_INVALID_GZIP_DATA, "The zipped data was not valid zip data.", e); } }
From source file:org.ohmage.request.Request.java
/** * <p>/*from w w w .j a va2s.c om*/ * Retrieves a parameter from either parts or the servlet container's * deserialization. * </p> * * <p> * This supersedes {@link #getMultipartValue(HttpServletRequest, String)}. * </p> * * @param httpRequest * The HTTP request. * * @param key * The parameter key. * * @return The parameter if given otherwise null. * * @throws ValidationException * There was a problem reading from the request. */ protected byte[] getParameter(final HttpServletRequest httpRequest, final String key) throws ValidationException { // First, attempt to decode it as a multipart/form-data post. try { // Get the part. If it isn't a multipart/form-data post, an // exception will be thrown. If it is and such a part does not // exist, return null. Part part = httpRequest.getPart(key); if (part == null) { return null; } // If the part exists, attempt to retrieve it. InputStream partInputStream = part.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] chunk = new byte[4096]; int amountRead; while ((amountRead = partInputStream.read(chunk)) != -1) { outputStream.write(chunk, 0, amountRead); } // If the buffer is empty, return null. Otherwise, return the byte // array. if (outputStream.size() == 0) { return null; } else { return outputStream.toByteArray(); } } // This will be thrown if it isn't a multipart/form-post, at which // point we can attempt to use the servlet container's deserialization // of the parameters. catch (ServletException e) { // Get the parameter. String result = httpRequest.getParameter(key); // If it doesn't exist, return null. if (result == null) { return null; } // Otherwise, return its bytes. else { return result.getBytes(); } } // If we could not read a parameter, something more severe happened, // and we need to fail the request and throw an exception. catch (IOException e) { LOGGER.info("There was an error reading the message from the input " + "stream.", e); setFailed(); throw new ValidationException(e); } }
From source file:lc.kra.servlet.FileManagerServlet.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//*from w w w .j a v a2s.c o m*/ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Files files = null; File file = null, parent; String path = request.getParameter("path"), type = request.getContentType(), search = request.getParameter("search"), mode; if (path == null || !(file = new File(path)).exists()) files = new Roots(); else if (request.getParameter("zip") != null) { File zipFile = File.createTempFile(file.getName() + "-", ".zip"); if (file.isFile()) ZipUtil.addEntry(zipFile, file.getName(), file); else if (file.isDirectory()) ZipUtil.pack(file, zipFile); downloadFile(response, zipFile, permamentName(zipFile.getName()), "application/zip"); } else if (request.getParameter("delete") != null) { if (file.isFile()) file.delete(); else if (file.isDirectory()) { java.nio.file.Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { java.nio.file.Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { java.nio.file.Files.delete(dir); return FileVisitResult.CONTINUE; } }); } } else if ((mode = request.getParameter("mode")) != null) { boolean add = mode.startsWith("+"); if (mode.indexOf('r') > -1) file.setReadable(add); if (mode.indexOf('w') > -1) file.setWritable(add); if (mode.indexOf('x') > -1) file.setExecutable(add); } else if (file.isFile()) downloadFile(response, file); else if (file.isDirectory()) { if (search != null && !search.isEmpty()) files = new Search(file.toPath(), search); else if (type != null && type.startsWith("multipart/form-data")) { for (Part part : request.getParts()) { String name; if ((name = partFileName(part)) == null) //retrieves <input type="file" name="...">, no other (e.g. input) form fields continue; if (request.getParameter("unzip") == null) try (OutputStream output = new FileOutputStream(new File(file, name))) { copyStream(part.getInputStream(), output); } else ZipUtil.unpack(part.getInputStream(), file); } } else files = new Directory(file); } else throw new ServletException("Unknown type of file or folder."); if (files != null) { final PrintWriter writer = response.getWriter(); writer.println( "<!DOCTYPE html><html><head><style>*,input[type=\"file\"]::-webkit-file-upload-button{font-family:monospace}</style></head><body>"); writer.println("<p>Current directory: " + files + "</p><pre>"); if (!(files instanceof Roots)) { writer.print( "<form method=\"post\"><label for=\"search\">Search Files:</label> <input type=\"text\" name=\"search\" id=\"search\" value=\"" + (search != null ? search : "") + "\"> <button type=\"submit\">Search</button></form>"); writer.print( "<form method=\"post\" enctype=\"multipart/form-data\"><label for=\"upload\">Upload Files:</label> <button type=\"submit\">Upload</button> <button type=\"submit\" name=\"unzip\">Upload & Unzip</button> <input type=\"file\" name=\"upload[]\" id=\"upload\" multiple></form>"); writer.println(); } if (files instanceof Directory) { writer.println("+ <a href=\"?path=" + URLEncoder.encode(path, ENCODING) + "\">.</a>"); if ((parent = file.getParentFile()) != null) writer.println("+ <a href=\"?path=" + URLEncoder.encode(parent.getAbsolutePath(), ENCODING) + "\">..</a>"); else writer.println("+ <a href=\"?path=\">..</a>"); } for (File child : files.listFiles()) { writer.print(child.isDirectory() ? "+ " : " "); writer.print("<a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING) + "\" title=\"" + child.getAbsolutePath() + "\">" + child.getName() + "</a>"); if (child.isDirectory()) writer.print(" <a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING) + "&zip\" title=\"download\">⇩</a>"); if (search != null && !search.isEmpty()) writer.print(" <a href=\"?path=" + URLEncoder.encode(child.getParentFile().getAbsolutePath(), ENCODING) + "\" title=\"go to parent folder\">🗁</a>"); writer.println(); } writer.print("</pre></body></html>"); writer.flush(); } }
From source file:com.imagelake.uploads.Servlet_Upload.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Date d = new Date(); SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd"); String date = sm.format(d);/*from www.ja va 2 s .c o m*/ String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); UserDAOImp udi = new UserDAOImp(); // gets values of text fields PrintWriter out = response.getWriter(); String cat, imgtit, imgname, dominate, price, dimention, col1, col2, col3, col4, col5, col6, col7, col8, col9, size_string, uid; System.out.println("server name====" + request.getServerName()); uid = request.getParameter("uid"); imgname = request.getParameter("imgname"); imgtit = request.getParameter("tit"); cat = request.getParameter("cat"); dimention = request.getParameter("dimention"); dominate = request.getParameter("dominate"); col1 = request.getParameter("col-1"); col2 = request.getParameter("col-2"); col3 = request.getParameter("col-3"); col4 = request.getParameter("col-4"); col5 = request.getParameter("col-5"); col6 = request.getParameter("col-6"); col7 = request.getParameter("col-7"); col8 = request.getParameter("col-8"); col9 = request.getParameter("col-9"); size_string = request.getParameter("size"); long size = 0; System.out.println(cat + " " + imgname + " " + col1 + " " + col2 + " " + col3 + " " + col4 + " " + col5 + " " + col6 + " " + col7 + " " + col8 + " " + col9 + " //" + dominate + " " + size_string); System.out.println(request.getParameter("tit") + "bbbbb" + request.getParameter("cat")); InputStream inputStream = null; // input stream of the upload file System.out.println("woooooooooo" + imgtit.trim() + "hooooooooo"); if (imgtit.equals("") || imgtit.equals(null) || cat.equals("") || cat.equals(null) || cat.equals("0") || dimention.equals("") || dimention.equals(null) && dominate.equals("") || dominate.equals(null) && col1.equals("") || col1.equals(null) && col2.equals("") || col2.equals(null) && col3.equals("") || col3.equals(null) && col4.equals("") || col4.equals(null) && col5.equals("") && col5.equals(null) && col6.equals("") || col6.equals(null) && col7.equals("") || col7.equals(null) && col8.equals("") || col8.equals(null) && col9.equals("") || col9.equals(null)) { System.out.println("error"); out.write("error"); } else { // obtains the upload file part in this multipart request try { Part filePart = request.getPart("photo"); if (filePart != null) { // prints out some information for debugging System.out.println("NAME:" + filePart.getName()); System.out.println(filePart.getSize()); size = filePart.getSize(); System.out.println(filePart.getContentType()); // obtains input stream of the upload file inputStream = filePart.getInputStream(); System.out.println(inputStream); } } catch (Exception e) { e.printStackTrace(); } Connection conn = null; // connection to the database String message = null; // message will be sent back to client String fileName = null; try { // gets absolute path of the web application String applicationPath = request.getServletContext().getRealPath(""); // constructs path of the directory to save uploaded file String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR; // creates the save directory if it does not exists File fileSaveDir = new File(uploadFilePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdirs(); } System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath()); System.out.println("Upload File Directory2=" + fileSaveDir.getAbsolutePath() + "/" + imgname); //Get all the parts from request and write it to the file on server for (Part part : request.getParts()) { fileName = getFileName(part); if (!fileName.equals(null) || !fileName.equals("")) { try { part.write(uploadFilePath + File.separator + fileName); } catch (Exception e) { break; } } } //GlassFish File Upload System.out.println(inputStream); if (inputStream != null) { // int id=new ImagesDAOImp().checkImagesId(dominate, col1, col2, col3, col4, col5, col6, col7, col8, col9); // if(id==0){ boolean sliceImage = new CreateImages().sliceImages(col1, col2, col3, col4, col5, col6, col7, col8, col9, dominate, imgname, dimention, imgtit, cat, uid, date); if (sliceImage) { AdminNotification a = new AdminNotification(); a.setUser_id(Integer.parseInt(uid)); a.setDate(timeStamp); a.setShow(1); a.setType(1); String not = "New Image has uploaded by " + udi.getUn(Integer.parseInt(uid)); a.setNotification(not); int an = new AdminNotificationDAOImp().insertNotificaation(a); System.out.println("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPP " + an); boolean kl = new AdminHasNotificationDAOImp().insertNotification(udi.listAdminsIDs(), an, 1); if (kl) { out.write("ok"); } else { System.out.println("error in sliceimage"); out.write("error"); } } else { System.out.println("error in sliceimage"); out.write("error"); } // } /*else{ System.out.println("error in id"); out.write("error"); }*/ } // sends the statement to the database server } catch (Exception ex) { message = "ERROR: " + ex.getMessage(); ex.printStackTrace(); } finally { if (conn != null) { // closes the database connection try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } //out.write("ok"); //else code }
From source file:com.joseflavio.uxiamarelo.servlet.UxiAmareloServlet.java
@Override protected void doPost(HttpServletRequest requisicao, HttpServletResponse resposta) throws ServletException, IOException { String tipo = requisicao.getContentType(); if (tipo == null || tipo.isEmpty()) tipo = "text/plain"; String codificacao = requisicao.getCharacterEncoding(); if (codificacao == null || codificacao.isEmpty()) codificacao = "UTF-8"; resposta.setCharacterEncoding(codificacao); PrintWriter saida = resposta.getWriter(); try {/*from ww w . j a v a 2 s. com*/ JSON json; if (tipo.contains("json")) { json = new JSON(IOUtils.toString(requisicao.getInputStream(), codificacao)); } else { json = new JSON(); } Enumeration<String> parametros = requisicao.getParameterNames(); while (parametros.hasMoreElements()) { String chave = parametros.nextElement(); String valor = URLDecoder.decode(requisicao.getParameter(chave), codificacao); json.put(chave, valor); } if (tipo.contains("multipart")) { Collection<Part> arquivos = requisicao.getParts(); if (!arquivos.isEmpty()) { File diretorio = new File(uxiAmarelo.getDiretorio()); if (!diretorio.isAbsolute()) { diretorio = new File(requisicao.getServletContext().getRealPath("") + File.separator + uxiAmarelo.getDiretorio()); } if (!diretorio.exists()) diretorio.mkdirs(); String diretorioStr = diretorio.getAbsolutePath(); String url = uxiAmarelo.getDiretorioURL(); if (uxiAmarelo.isDiretorioURLRelativo()) { String url_esquema = requisicao.getScheme(); String url_servidor = requisicao.getServerName(); int url_porta = requisicao.getServerPort(); String url_contexto = requisicao.getContextPath(); url = url_esquema + "://" + url_servidor + ":" + url_porta + url_contexto + "/" + url; } if (url.charAt(url.length() - 1) == '/') { url = url.substring(0, url.length() - 1); } Map<String, List<JSON>> mapa_arquivos = new HashMap<>(); for (Part arquivo : arquivos) { String chave = arquivo.getName(); String nome_original = getNome(arquivo, codificacao); String nome = nome_original; if (nome == null || nome.isEmpty()) { try (InputStream is = arquivo.getInputStream()) { String valor = IOUtils.toString(is, codificacao); valor = URLDecoder.decode(valor, codificacao); json.put(chave, valor); continue; } } if (uxiAmarelo.getArquivoNome().equals("uuid")) { nome = UUID.randomUUID().toString(); } while (new File(diretorioStr + File.separator + nome).exists()) { nome = UUID.randomUUID().toString(); } arquivo.write(diretorioStr + File.separator + nome); List<JSON> lista = mapa_arquivos.get(chave); if (lista == null) { lista = new LinkedList<>(); mapa_arquivos.put(chave, lista); } lista.add((JSON) new JSON().put("nome", nome_original).put("endereco", url + "/" + nome)); } for (Entry<String, List<JSON>> entrada : mapa_arquivos.entrySet()) { List<JSON> lista = entrada.getValue(); if (lista.size() > 1) { json.put(entrada.getKey(), lista); } else { json.put(entrada.getKey(), lista.get(0)); } } } } String copaiba = (String) json.remove("copaiba"); if (StringUtil.tamanho(copaiba) == 0) { throw new IllegalArgumentException("copaiba = nome@classe@metodo"); } String[] copaibaParam = copaiba.split("@"); if (copaibaParam.length != 3) { throw new IllegalArgumentException("copaiba = nome@classe@metodo"); } String comando = (String) json.remove("uxicmd"); if (StringUtil.tamanho(comando) == 0) comando = null; if (uxiAmarelo.isCookieEnviar()) { Cookie[] cookies = requisicao.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { String nome = cookie.getName(); if (uxiAmarelo.cookieBloqueado(nome)) continue; if (!json.has(nome)) { try { json.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { json.put(nome, cookie.getValue()); } } } } } if (uxiAmarelo.isEncapsulamentoAutomatico()) { final String sepstr = uxiAmarelo.getEncapsulamentoSeparador(); final char sep0 = sepstr.charAt(0); for (String chave : new HashSet<>(json.keySet())) { if (chave.indexOf(sep0) == -1) continue; String[] caminho = chave.split(sepstr); if (caminho.length > 1) { Util.encapsular(caminho, json.remove(chave), json); } } } String resultado; if (comando == null) { try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaibaParam[0])) { resultado = cc.solicitar(copaibaParam[1], json.toString(), copaibaParam[2]); if (resultado == null) resultado = ""; } } else if (comando.equals("voltar")) { resultado = json.toString(); comando = null; } else { resultado = ""; } if (comando == null) { resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("application/json"); saida.write(resultado); } else if (comando.startsWith("redirecionar")) { resposta.sendRedirect(Util.obterStringDeJSON("redirecionar", comando, resultado)); } else if (comando.startsWith("base64")) { String url = comando.substring("base64.".length()); resposta.sendRedirect(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8"))); } else if (comando.startsWith("html_url")) { HttpURLConnection con = (HttpURLConnection) new URL( Util.obterStringDeJSON("html_url", comando, resultado)).openConnection(); con.setRequestProperty("User-Agent", "Uxi-amarelo"); if (con.getResponseCode() != HttpServletResponse.SC_OK) throw new IOException("HTTP = " + con.getResponseCode()); resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("text/html"); try (InputStream is = con.getInputStream()) { saida.write(IOUtils.toString(is)); } con.disconnect(); } else if (comando.startsWith("html")) { resposta.setStatus(HttpServletResponse.SC_OK); resposta.setContentType("text/html"); saida.write(Util.obterStringDeJSON("html", comando, resultado)); } else { throw new IllegalArgumentException(comando); } } catch (Exception e) { resposta.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resposta.setContentType("application/json"); saida.write(Util.gerarRespostaErro(e).toString()); } saida.flush(); }
From source file:eu.prestoprime.p4gui.ingest.UploadMasterFileServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = Tools.getSessionAttribute(request.getSession(), P4GUI.USER_BEAN_NAME, User.class); RoleManager.checkRequestedRole(USER_ROLE.producer, user.getCurrentP4Service().getRole(), response); // prepare dynamic variables Part masterQualityPart = request.getPart("masterFile"); String targetName = new SimpleDateFormat("yyyyMMdd-HHmm").format(new Date()) + ".mxf"; // prepare static variables String host = "p4.eurixgroup.com"; int port = 21; String username = "pprime"; String password = "pprime09"; FTPClient client = new FTPClient(); try {// w ww. j ava 2 s .co m client.connect(host, port); if (FTPReply.isPositiveCompletion(client.getReplyCode())) { if (client.login(username, password)) { client.setFileType(FTP.BINARY_FILE_TYPE); // TODO add behavior if file name is already present in // remote ftp folder // now OVERWRITES if (client.storeFile(targetName, masterQualityPart.getInputStream())) { logger.info("Stored file on remote FTP server " + host + ":" + port); request.setAttribute("masterfileName", targetName); } else { logger.error("Unable to store file on remote FTP server"); } } else { logger.error("Unable to login on remote FTP server"); } } else { logger.error("Unable to connect to remote FTP server"); } } catch (IOException e) { e.printStackTrace(); logger.fatal("General exception with FTPClient"); } Tools.servletInclude(this, request, response, "/body/ingest/masterfile/listfiles.jsp"); }