List of usage examples for javax.servlet.http Part getName
public String getName();
From source file:com.thoughtworks.go.apiv1.configrepooperations.ConfigRepoOperationsControllerV1.java
String preflight(Request req, Response res) throws IOException { ConfigRepoConfig repo = repoFromRequest(req); ConfigRepoPlugin plugin = pluginFromRequest(req); PartialConfigLoadContext context = configContext(repo); final PreflightResult result = new PreflightResult(); try {/*w w w . j a va 2s . co m*/ Collection<Part> uploads = req.raw().getParts(); Map<String, String> contents = new LinkedHashMap<>(); for (Part ul : uploads) { if (!"files[]".equals(ul.getName())) { continue; } StringWriter w = new StringWriter(); IOUtils.copy(ul.getInputStream(), w, StandardCharsets.UTF_8); contents.put(ul.getSubmittedFileName(), w.toString()); } if (contents.isEmpty()) { result.update(Collections.singletonList( "No file content provided; check to make sure you POST the form data as `files[]=`"), false); } else { PartialConfig partialConfig = plugin.parseContent(contents, context); partialConfig.setOrigins(adHocConfigOrigin(repo)); CruiseConfig config = partialConfigService.merge(partialConfig, context.configMaterial().getFingerprint(), gcs.clonedConfigForEdit()); gcs.validateCruiseConfig(config); result.update(Collections.emptyList(), true); } } catch (RecordNotFoundException e) { throw e; } catch (InvalidPartialConfigException e) { result.update(Collections.singletonList(e.getErrors()), false); } catch (GoConfigInvalidException e) { result.update(e.getAllErrors(), false); } catch (Exception e) { throw HaltApiResponses.haltBecauseOfReason(e.getMessage()); } return writerForTopLevelObject(req, res, w -> PreflightResultRepresenter.toJSON(w, result)); }
From source file:AddPost.java
/** * metodo usato per gestire il caso di upload di file multipli da * parte del'utente su un singolo post, siccome la libreria * utilizzata non gestiva questo particolare caso. * @throws IOException//from w w w. ja v a 2s . co m * @throws ServletException * @throws SQLException */ private void getFiles() throws IOException, ServletException, SQLException { Collection<Part> p = mReq.getParts(); for (Part part : p) { if (part.getName().equals("post")) { // } else { if (part.getSize() > 1024 * 1024 * 10) { error++; } else { String path = mReq.getServletContext().getRealPath("/"); String name = part.getSubmittedFileName(); int i; if (isInGroupFiles(name)) { for (i = 1; isInGroupFiles("(" + i + ")" + name); i++) ; name = "(" + i + ")" + name; } //Hotfixies for absoluth paths //IE if (name.contains("\\")) { name = name.substring(name.lastIndexOf("\\")); } //somthing else, never encountered if (name.contains("/")) { name = name.substring(name.lastIndexOf("/")); } dbm.newFile(dbm.getIdFromUser(user), groupid, name); File outputFile = new File(path + "/files/" + groupid + "/" + name); if (!outputFile.exists()) { outputFile.createNewFile(); } if (!outputFile.isDirectory()) { InputStream finput = new BufferedInputStream(part.getInputStream()); OutputStream foutput = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buffer = new byte[1024 * 500]; int bytes_letti = 0; while ((bytes_letti = finput.read(buffer)) > 0) { foutput.write(buffer, 0, bytes_letti); } finput.close(); foutput.close(); } } } } }
From source file:uk.ac.ncl.ssip.webserver.StartDBServlet.java
private void processFiles() throws IOException { String path = new File(".").getCanonicalPath() + "/target/webapp/uploads/"; System.out.println(path);/* ww w . j a v a 2s.c o m*/ OutputStream out = null; InputStream filecontent = null; try { for (Part filePart : fileParts) { if (filePart.getName().contains("url")) { String[] urlSplit = request.getParameter(filePart.getName()).split("/"); if (urlSplit.length > 1) { System.out.println("URL detected: " + filePart.getName() + "\nFile name: " + urlSplit[urlSplit.length - 1]); FileUtils.copyURLToFile(new URL(request.getParameter(filePart.getName())), new File("./target/webapp/uploads/" + urlSplit[urlSplit.length - 1])); System.out.println("New file " + urlSplit[urlSplit.length - 1] + " created in uploads."); } } if (filePart.getName().contains("file")) { fileNum++; if (!getFileName(filePart).equals("")) { if (!(new File(path).list().toString().contains(getFileName(filePart)))) { out = new FileOutputStream(new File(path + File.separator + getFileName(filePart))); filecontent = filePart.getInputStream(); int read = 0; final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } //APPEND TO LOG FILE NOT CONSOLE System.out.println("New file " + getFileName(filePart) + " created at " + path); LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", new Object[] { getFileName(filePart), path }); } else { System.out.println("File already exists in uploads: " + getFileName(filePart)); } } } } } catch (FileNotFoundException fne) { System.out.println("You either did not specify a file to upload or are " + "trying to upload a file to a protected or nonexistent " + "location."); System.out.println("<br/> ERROR: " + fne.getMessage()); LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", new Object[] { fne.getMessage() }); } finally { if (out != null) { out.close(); } if (filecontent != null) { filecontent.close(); } } }
From source file:servlets.NewRestaurant.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from ww w . j av a 2 s . c om*/ * @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 { //Controlliamo che i parametri siano specificati e corretti e se si procediamo. if (request.getParameter("nome") != null && request.getParameter("descrizione") != null && request.getParameter("cap") != null && request.getParameter("citta") != null && request.getParameter("stato") != null) { try { //Procediamo a salvare le informazioni RestaurantBean rest = new RestaurantBean(); rest.setName(request.getParameter("nome")); rest.setDescription(request.getParameter("descrizione")); rest.setWeb_site_url(request.getParameter("URL_sito")); rest.setTelephone(request.getParameter("telefono")); rest.setMail(request.getParameter("email")); rest.setAddress(request.getParameter("indirizzo")); rest.setCap(request.getParameter("cap").isEmpty() ? 0 : parseInt(request.getParameter("cap"))); rest.setCity(request.getParameter("citta")); rest.setId_country(Integer.valueOf(request.getParameter("stato"))); rest.setId_price_range(Integer.valueOf(request.getParameter("pricerange"))); rest.setGlobal_value(0); rest.setN_visits(0); String[] checkedCuisineIds = request.getParameterValues("cuisine"); String[] checkedOpeningHoursIds = request.getParameterValues("openinghour"); //Dobbiamo ottenere latitudine e longitudine GeoCoder geo = new GeoCoder(); GeocodeResponse geoResp = geo.getLocation(rest.getAddress(), rest.getCity(), String.valueOf(rest.getCap())); try { rest.setLatitude(geoResp.getResults().get(0).getGeometry().getLocation().getLat()); rest.setLongitude(geoResp.getResults().get(0).getGeometry().getLocation().getLng()); } //valori non validi catch (Exception e) { RequestDispatcher rd = request.getRequestDispatcher("/general_error_page.jsp"); rd.forward(request, response); } //Cerchiamo l'id dell'utente che sta creando il ristorante HttpSession session = request.getSession(false); UserBean userLogged = (UserBean) session.getAttribute("user"); rest.setId_creator(userLogged.getId()); rest.setId_owner(userLogged.getId()); //Abbiamo salvato tutto nel bean, ora dobbiamo inviare il bean al DAO e salvare le modifiche al database RestaurantDAO restDAO = new RestaurantDAO(); int restID = restDAO.addRestaurant(rest); //Ora dobbiamo salvare le relazioni per cuisineType e openinghour restDAO.addRestCuisine(restID, checkedCuisineIds); restDAO.addRestOpeningHours(restID, checkedOpeningHoursIds); //Tutto andato a buon fine, possiamo dunque salvare le foto in locale e apportare modifiche nel database //Ottengo la COllection di tutte le Parts Collection<Part> fileParts = request.getParts(); //Ora devo filtrarla, in modo da avere solo quelle riguardanti le foto CollectionUtils.filter(fileParts, new org.apache.commons.collections4.Predicate<Part>() { @Override public boolean evaluate(Part o) { return o.getName().equals("foto"); } }); int i = 0; //Per ogni foto salvo in db e locale. for (Part part : fileParts) { PhotoBean foto = new PhotoBean(); foto.setName(String.valueOf(restID) + "-" + i + ".jpg"); foto.setDescription("Foto ristorante"); foto.setId_restaurant(restID); foto.setId_user(userLogged.getId()); // (2) create a java timestamp object that represents the current time (i.e., a "current timestamp") Calendar calendar = Calendar.getInstance(); foto.setDate(new java.sql.Timestamp(calendar.getTime().getTime())); //Inseriamo la foto nel db PhotoDAO photoDao = new PhotoDAO(); photoDao.addPhoto(foto); //Salviamo la foto in locale // gets absolute path of the web application String appPath = request.getServletContext().getRealPath(""); // constructs path of the directory to save uploaded file String savePath = appPath + File.separator + SAVE_DIR; // creates the save directory if it does not exists File fileSaveDir = new File(savePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } // Part part = request.getPart("foto"); String fileName = String.valueOf(restID) + "-" + i + ".jpg"; // refines the fileName in case it is an absolute path fileName = new File(fileName).getName(); part.write(savePath + File.separator + fileName); Logger.getLogger(NewRestaurant.class.getName()).log(Level.SEVERE, savePath + File.separator + fileName); //Incremento contatore numero foto i++; } //Fine salvataggio foto //Dobbiamo aggiornare l'utente se non era gi ristoratore, ora che ha messo un ristorante! if (userLogged.getType() == 0) { UserDAO userDAO = new UserDAO(); int affectedRows = userDAO.upgradeUser(userLogged.getId()); if (affectedRows == 0) { throw new SQLException("Errore aggiornamento utente, no rows affected."); } else { userLogged.setType(1); session.setAttribute("user", userLogged); } } request.setAttribute("formValid", "The restaurant " + rest.getName() + " has been create "); RequestDispatcher rd = request.getRequestDispatcher("/createdRestaurant.jsp"); rd.forward(request, response); } catch (SQLException ex) { Logger.getLogger(NewRestaurant.class.getName()).log(Level.SEVERE, null, ex); } } //Errore, non tutti i parametri necessari sono stati specificati. else { RequestDispatcher rd = request.getRequestDispatcher("/general_error_page.jsp"); rd.forward(request, response); } }
From source file:controller.servlet.Upload.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w .j a va 2 s . co m*/ * @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 { // Subida de los ficheros al sistema. UploadedFile uF; UploadedFileDaoImpl uFD = new UploadedFileDaoImpl(); int numberOfCsvFiles = 0; int numberOfNotCsvFiles = 0; for (Part part : request.getParts()) { if (part.getName().equals("file")) { try (InputStream is = request.getPart(part.getName()).getInputStream()) { int i = is.available(); byte[] b = new byte[i]; if (b.length == 0) { break; } is.read(b); String fileName = obtenerNombreFichero(part); String extension = FilenameUtils.getExtension(fileName); String path = this.getServletContext().getRealPath(""); String ruta = path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName; File directorio = new File(path + File.separator + Path.UPLOADEDFILES_FOLDER); if (!directorio.exists()) { directorio.mkdirs(); } // Se sube el fichero en caso de ser zip o csv. if (extension.equals(Path.CSV_EXTENSION) || extension.equals(Path.ZIP_EXTENSION)) { try (FileOutputStream os = new FileOutputStream(ruta)) { os.write(b); } if (extension.equals(Path.CSV_EXTENSION)) { numberOfCsvFiles++; } } else { numberOfNotCsvFiles++; } // Extraccin de los ficheros incluidos en el zip. if (extension.equals(Path.ZIP_EXTENSION)) { ZipInputStream zis = new ZipInputStream( new FileInputStream(directorio + File.separator + fileName)); ZipEntry eachFile; while (null != (eachFile = zis.getNextEntry())) { File newFile = new File(directorio + File.separator + eachFile.getName()); // Se guardan los csv. if (FilenameUtils.getExtension(directorio + File.separator + eachFile.getName()) .equals(Path.CSV_EXTENSION)) { numberOfCsvFiles++; try (FileOutputStream fos = new FileOutputStream(newFile)) { int len; byte[] buffer = new byte[1024]; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } zis.closeEntry(); // Insertar en BD uF = new UploadedFile(0, eachFile.getName(), new java.sql.Date(new Date().getTime()), false, null); uFD.createFile(uF); } else { numberOfNotCsvFiles++; } } File fileToDelete = new File( path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName); fileToDelete.delete(); } else { // Insertar en BD uF = new UploadedFile(0, fileName, new java.sql.Date(new Date().getTime()), false, null); uFD.createFile(uF); } } } } // Asignacin de valores. HttpSession session = request.getSession(true); session.setAttribute("numberOfCsvFiles", numberOfCsvFiles); session.setAttribute("numberOfNotCsvFiles", numberOfNotCsvFiles); if (numberOfCsvFiles == 0 && numberOfNotCsvFiles == 0) { session.setAttribute("error", true); } else { session.setAttribute("error", false); } processRequest(request, response); }
From source file:org.apache.sling.servlets.post.impl.operations.StreamedUploadOperation.java
/** * Get the upload file name from the part. * @param part//from w ww .ja va 2 s. co m * @return */ private String getUploadName(Part part) { // only return non null if the submitted file name is non null. // the Sling API states that if the field name is '*' then the submitting file name is used, // otherwise the field name is used. String name = part.getName(); String fileName = part.getSubmittedFileName(); if ("*".equals(name)) { name = fileName; } // strip of possible path (some browsers include the entire path) name = name.substring(name.lastIndexOf('/') + 1); name = name.substring(name.lastIndexOf('\\') + 1); return Text.escapeIllegalJcrChars(name); }
From source file:beans.DecryptFileBean.java
public void validateFile(FacesContext ctx, UIComponent comp, Object value) { if (getUser() != null) { Part file = (Part) value; if (file != null) { status = ""; if (file.getSize() > 1024) { status += "- File too big.\n"; }/*ww w. j ava 2 s .c o m*/ if (!"text/plain".equals(file.getContentType())) { status += "- " + file.getContentType() + " content was found in " + file.getName() + ". Expected text/plain. Please select a text file."; } } } else { status = "You are not logged in."; } }
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 w w w .ja va2s . 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 www . j a v a 2 s.c om 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:org.ohmage.request.survey.SurveyUploadRequest.java
/** * Creates a new survey upload request.//ww w . ja v a2 s.c om * * @param httpRequest The HttpServletRequest with the parameters for this * request. * * @throws InvalidRequestException Thrown if the parameters cannot be * parsed. * * @throws IOException There was an error reading from the request. */ public SurveyUploadRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException { super(httpRequest, false, TokenLocation.PARAMETER, null); LOGGER.info("Creating a survey upload request."); String tCampaignUrn = null; DateTime tCampaignCreationTimestamp = null; List<JSONObject> tJsonData = null; Map<UUID, Image> tImageContentsMap = null; Map<String, Video> tVideoContentsMap = null; Map<String, Audio> tAudioContentsMap = null; if (!isFailed()) { try { Map<String, String[]> parameters = getParameters(); // Validate the campaign URN String[] t = parameters.get(InputKeys.CAMPAIGN_URN); if (t == null || t.length != 1) { throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "campaign_urn is missing or there is more than one."); } else { tCampaignUrn = CampaignValidators.validateCampaignId(t[0]); if (tCampaignUrn == null) { throw new ValidationException(ErrorCode.CAMPAIGN_INVALID_ID, "The campaign ID is invalid."); } } // Validate the campaign creation timestamp t = parameters.get(InputKeys.CAMPAIGN_CREATION_TIMESTAMP); if (t == null || t.length != 1) { throw new ValidationException(ErrorCode.SERVER_INVALID_TIMESTAMP, "campaign_creation_timestamp is missing or there is more than one"); } else { // Make sure it's a valid timestamp. try { tCampaignCreationTimestamp = DateTimeUtils.getDateTimeFromString(t[0]); } catch (IllegalArgumentException e) { throw new ValidationException(ErrorCode.SERVER_INVALID_DATE, e.getMessage(), e); } } byte[] surveyDataBytes = getParameter(httpRequest, InputKeys.SURVEYS); if (surveyDataBytes == null) { throw new ValidationException(ErrorCode.SURVEY_INVALID_RESPONSES, "No value found for 'surveys' parameter or multiple surveys parameters were found."); } else { LOGGER.debug(new String(surveyDataBytes)); try { tJsonData = CampaignValidators.validateUploadedJson(new String(surveyDataBytes, "UTF-8")); } catch (IllegalArgumentException e) { throw new ValidationException(ErrorCode.SURVEY_INVALID_RESPONSES, "The survey responses could not be URL decoded.", e); } } tImageContentsMap = new HashMap<UUID, Image>(); t = getParameterValues(InputKeys.IMAGES); if (t.length > 1) { throw new ValidationException(ErrorCode.SURVEY_INVALID_IMAGES_VALUE, "Multiple images parameters were given: " + InputKeys.IMAGES); } else if (t.length == 1) { LOGGER.debug("Validating the BASE64-encoded images."); Map<UUID, Image> images = SurveyResponseValidators.validateImages(t[0]); if (images != null) { tImageContentsMap.putAll(images); } } // Retrieve and validate images and videos. List<UUID> imageIds = new ArrayList<UUID>(); tVideoContentsMap = new HashMap<String, Video>(); tAudioContentsMap = new HashMap<String, Audio>(); Collection<Part> parts = null; try { // FIXME - push to base class especially because of the ServletException that gets thrown parts = httpRequest.getParts(); for (Part p : parts) { UUID id; String name = p.getName(); try { id = UUID.fromString(name); } catch (IllegalArgumentException e) { LOGGER.info("Ignoring part: " + name); continue; } String contentType = p.getContentType(); if (contentType.startsWith("image")) { imageIds.add(id); } else if (contentType.startsWith("video/")) { tVideoContentsMap.put(name, new Video(UUID.fromString(name), contentType.split("/")[1], getMultipartValue(httpRequest, name))); } else if (contentType.startsWith("audio/")) { try { tAudioContentsMap.put(name, new Audio(UUID.fromString(name), contentType.split("/")[1], getMultipartValue(httpRequest, name))); } catch (DomainException e) { throw new ValidationException(ErrorCode.SYSTEM_GENERAL_ERROR, "Could not create the Audio object.", e); } } } } catch (ServletException e) { LOGGER.info("This is not a multipart/form-post."); } catch (IOException e) { LOGGER.error("cannot parse parts", e); throw new ValidationException(e); } catch (DomainException e) { LOGGER.info("A Media object could not be built.", e); throw new ValidationException(e); } Set<UUID> stringSet = new HashSet<UUID>(imageIds); if (stringSet.size() != imageIds.size()) { throw new ValidationException(ErrorCode.IMAGE_INVALID_DATA, "a duplicate image key was detected in the multi-part upload"); } for (UUID imageId : imageIds) { Image image = ImageValidators.validateImageContents(imageId, getMultipartValue(httpRequest, imageId.toString())); if (image == null) { throw new ValidationException(ErrorCode.IMAGE_INVALID_DATA, "The image data is missing: " + imageId); } tImageContentsMap.put(imageId, image); if (LOGGER.isDebugEnabled()) { LOGGER.debug("succesfully created a BufferedImage for key " + imageId); } } } catch (ValidationException e) { e.failRequest(this); e.logException(LOGGER, true); } } this.campaignUrn = tCampaignUrn; this.campaignCreationTimestamp = tCampaignCreationTimestamp; this.jsonData = tJsonData; this.imageContentsMap = tImageContentsMap; this.videoContentsMap = tVideoContentsMap; this.audioContentsMap = tAudioContentsMap; this.owner = null; surveyResponseIds = null; }