List of usage examples for javax.servlet.http HttpServletRequest getPart
public Part getPart(String name) throws IOException, ServletException;
From source file:pe.edu.upeu.application.web.controller.CVacaciones.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*w w w .java2 s . c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Map<String, Object> mp = new HashMap<String, Object>(); InterfaceDgpDAO dgp = new DgpDAO(); ContratoDAO cD = new ContratoDAO(); VacacionDAO vC = new VacacionDAO(); InterfaceVacacionesDAO vaca = new VacacionDAO(); DocumentoDAO d = new DocumentoDAO(); Detalle_VacacionDAO Dvac = new Detalle_VacacionDAO(); HttpSession sesion = request.getSession(true); String iddir = (String) sesion.getAttribute("IDDIR"); String iddep = (String) sesion.getAttribute("DEPARTAMENTO_ID"); String user = (String) sesion.getAttribute("IDUSER"); String contentType = request.getContentType(); System.out.println("contentType = " + contentType); boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Check that we have a file upload request System.out.println("isMultipart = " + isMultipart); if (isMultipart) { String opc = request.getParameter("opc");// Retrieves all text inputs if (opc.equals("asign")) { Part filePart = request.getPart("docadj"); // Retrieves <input type="file" name="file"> response.setContentType("application/json;charset=UTF-8"); String idcon = (String) sesion.getAttribute("id_con_vac"); System.out.println(opc); String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix. System.out.println(fileName); String renombre_archivo = null; Calendar fecha = new GregorianCalendar(); int hora = fecha.get(Calendar.HOUR_OF_DAY); int min = fecha.get(Calendar.MINUTE); int sec = fecha.get(Calendar.SECOND); renombre_archivo = String.valueOf(hora) + String.valueOf(min) + String.valueOf(sec) + "_" + idcon + "_" + fileName.toUpperCase(); System.out.println(renombre_archivo); // String ubicacionArchivo = ""; // ubicacionArchivo = FactoryConnectionDB.url + "Archivo/"; // // ubicacion = getServletContext().getRealPath(".").substring(0, getServletContext().getRealPath(".").length() - 11) + "web\\Vista\\Usuario\\Fotos"; // DiskFileItemFactory f = new DiskFileItemFactory(); // f.setSizeThreshold(1024); // f.setRepository(new File(ubicacionArchivo)); // ServletFileUpload upload = new ServletFileUpload(f); String Descripcion = request.getParameter("dest"); String Estado = request.getParameter("est"); System.out.println(Descripcion); System.out.println(Estado); String iddaj = d.INSERT_DOCUMENTO_ADJUNTO(null, iddep, "1", user, null, null, null, null, Descripcion, null, Estado, idcon).trim(); System.out.println(iddaj); d.INSERT_ARCHIVO_DOCUMENTO(null, iddaj, renombre_archivo, fileName, null); String idvac = vC.insert_vacation(iddaj, idcon); // System.out.println("idvac: "+idvac); // System.out.println("iddaj: "+iddaj); // System.out.println("idcon: "+idcon); if (idcon != null) { System.out.println("aaaa:" + idvac); mp.put("info", idvac); } else { mp.put("info", "-1"); } Gson gson = new Gson(); out.println(gson.toJson(mp)); out.flush(); out.close(); } } else { String opc = request.getParameter("opc"); if (opc.equals("rolrequest")) { response.setContentType("application/json;charset=UTF-8"); String idrol = (String) sesion.getAttribute("IDROL"); System.out.println(idrol); mp.put("idrol", idrol); Gson gson = new Gson(); out.println(gson.toJson(mp)); out.flush(); out.close(); } if (opc.equals("Listar")) { response.sendRedirect("Vista/Vacaciones/Lista_Empleados.jsp"); } if (opc.equals("listartadm")) { response.sendRedirect("Vista/Vacaciones/List_Trab_Adm.jsp"); } if (opc.equals("listaraut")) { response.sendRedirect("Vista/Vacaciones/List_Trab_Adm.jsp"); } if (opc.equals("listTA")) { response.setContentType("application/json;charset=UTF-8"); System.out.println("llega"); mp.put("aptos", vC.trabajadoresapt()); Gson gson = new Gson(); out.println(gson.toJson(mp)); out.flush(); out.close(); } if (opc.equals("listadm")) { response.setContentType("application/json;charset=UTF-8"); String idep = (String) sesion.getAttribute("DEPARTAMENTO_ID"); mp.put("adm", vC.trabajadoresadm(idep)); Gson gson = new Gson(); out.println(gson.toJson(mp)); out.flush(); out.close(); } if (opc.equals("listToAut")) { response.setContentType("application/json;charset=UTF-8"); String idep = (String) sesion.getAttribute("DEPARTAMENTO_ID"); mp.put("adm", vC.ListToAut(idep)); Gson gson = new Gson(); out.println(gson.toJson(mp)); out.flush(); out.close(); } if (opc.equals("AutorizAN")) { response.setContentType("application/json;charset=UTF-8"); String[] id_au = request.getParameterValues("AutorizAN"); List<String> list = new ArrayList<String>(); for (int i = 0; i < id_au.length; i++) { list.add(id_au[i]); } boolean a = vC.admitirV(list); if (a) { response.sendRedirect("Vista/Vacaciones/Lista_Empleados.jsp"); //ok } else { //error } //System.out.println(a); /*sesion.setAttribute("lista", list); response.sendRedirect("Vista/Contrato/Formato_Plantilla/Impresion_Masiva.jsp");*/ } if (opc.equals("sendcon")) { String idcon = request.getParameter("idcon"); System.out.println(idcon); sesion.setAttribute("id_con_vac", idcon); response.sendRedirect("Vista/Vacaciones/prog_vacaciones.jsp"); } if (opc.equals("get_info_trab")) { response.setContentType("application/json;charset=UTF-8"); System.out.println("hola que hace"); System.out.println("ola k ase"); String idcon = (String) sesion.getAttribute("id_con_vac"); System.out.println(idcon); if (idcon != null) { mp.put("info", vC.get_info_trab(idcon)); } else { mp.put("info", "-1"); } Gson gson = new Gson(); out.println(gson.toJson(mp)); out.flush(); out.close(); } if (opc.equals("Procesar")) { String iddgp = ""; String idpro = ""; try { iddgp = CCriptografiar.Desencriptar(request.getParameter("dgp")); idpro = CCriptografiar.Desencriptar(request.getParameter("proceso")); } catch (Exception ex) { System.out.println("Error: " + ex); } if (iddgp.equals("") && idpro.equals("")) { vaca.PROCESAR_VACACIONES(idpro, iddgp); } response.sendRedirect("Vista/Vacaciones/Proceso_Vacacion.jsp"); mp.put("rpta", true); } if (opc.equals("listEsVacaciones")) { mp.put("list", dgp.LIST_DGP_PROCESO(iddep, "", true)); } // if (opc.equals("asign")) { // response.setContentType("application/json;charset=UTF-8"); // String idcon = (String) sesion.getAttribute("id_con_vac"); // String idvac = "DOC-0002"; // if (idcon != null) { // mp.put("info", idvac); // } else { // mp.put("info", "-1"); // } // Gson gson = new Gson(); // // out.println(gson.toJson(mp)); // out.flush(); // // out.close(); // } if (opc.equals("asigndv")) { String idDetvac = null; String fedesde = request.getParameter("from"); String fehasta = request.getParameter("to"); //String idvacacion = "1"; String idvacacion = request.getParameter("idvac"); // System.out.println(idvacacion); System.out.println(fedesde + " " + fehasta + " " + idvacacion); Detalle_VacacionDAO MoDet_Vac = new Detalle_VacacionDAO(); Detalle_Vacacion Detv = new Detalle_Vacacion(); Detv.setIddetalle(null); Detv.setFe_inicio(fedesde); Detv.setFe_fin(fehasta); Detv.setIdvacacion(idvacacion); // // Dvac.insert(MoDet_Vac); MoDet_Vac.insert(Detv); // sesion.setAttribute("List_Usuario_var", usu.List_Usuario_var()); response.setContentType("application/json;charset=UTF-8"); Gson gson = new Gson(); out.println(gson.toJson(mp)); out.flush(); out.close(); } } try { } finally { out.close(); } }
From source file:de.teamgrit.grit.webserver.ConnectionHandler.java
/** * Action to create a new connection.//from w ww . j av a 2s . c om * * @param request * the {@link HttpServletRequest} passed to the handle() method * @return the added {@link Connection} on success, null otherwise * @throws BadRequestException * if something goes wrong due to a bad request * @throws InternalActionErrorException * if something else goes wrong (e.g. could not write to file) */ private String create(HttpServletRequest request) throws BadRequestException, InternalActionErrorException { String errorPrefix = "Error in connection/create:\n"; /* Get all needed parameters from the request. */ String connectionName; ConnectionType connectionType; String location; String username; String password; String sshUsername; List<String> structure; try { connectionName = parseName(request.getParameter("connectionName"), "connection name"); connectionType = parseConnectionType(request.getParameter("connectionType")); location = parseLocation(request.getParameter("location")); username = parseName(request.getParameter("username"), "username"); password = request.getParameter("password"); if (connectionType == ConnectionType.ILIAS) { sshUsername = parseName(request.getParameter("sshUsername"), "sshUsername"); } else { sshUsername = ""; } if (connectionType == ConnectionType.SVN) { structure = parseStructure(request.getParameter("structure")); } else { structure = null; } } catch (BadRequestException e) { throw new BadRequestException(errorPrefix + e.getMessage()); } /* If this is an ILIAS connection, we need the SSH key-file */ Part sshKey = null; String keyFileName = ""; if (connectionType == ConnectionType.ILIAS) { try { sshKey = request.getPart("sshKeyFile"); } catch (ServletException e) { throw new BadRequestException(errorPrefix + "No multipart request."); } catch (IOException e) { throw new InternalActionErrorException(errorPrefix + "Could not read the submitted keyfile."); } keyFileName = sshKey.getSubmittedFileName(); if ((keyFileName == null) || ("".equals(keyFileName))) { throw new BadRequestException("No key-file submitted!"); } } /* Create the connection. */ Connection connection = null; try { connection = m_controller.addConnection(connectionName, connectionType, location, username, password, sshUsername, keyFileName, structure); } catch (ConfigurationException e) { throw new InternalActionErrorException(errorPrefix + "Could not create connection."); } catch (InvalidStructureException e) { throw new InternalActionErrorException(errorPrefix + "The submitted structure is invalid."); } /* Write the key-file if this is an ILIAS connection. */ if (connectionType == ConnectionType.ILIAS) { Path outputDirectory = connection.getSshKeyFileLocation().getParent(); writeSubmittedFile(sshKey, outputDirectory); } return GSON.toJson(connection); }
From source file:de.teamgrit.grit.webserver.ConnectionHandler.java
/** * Action to update a connection.//from w w w. j a v a 2s . c o m * * @param connectionId * the ID of the connection * @param request * the {@link HttpServletRequest} passed to the handle() method * @return the added {@link Connection} on success, null otherwise * @throws BadRequestException * if something goes wrong due to a bad request * @throws InternalActionErrorException * if something else goes wrong (e.g. could not write to file) */ private String update(String connectionId, HttpServletRequest request) throws BadRequestException, InternalActionErrorException { String errorPrefix = "Error in connection/create:\n"; /* Get all needed parameters from the request. */ String connectionName; ConnectionType connectionType; String location; String username; String password; String sshUsername; List<String> structure; try { connectionName = parseName(request.getParameter("connectionName"), "connection name"); connectionType = parseConnectionType(request.getParameter("connectionType")); location = parseLocation(request.getParameter("location")); username = parseName(request.getParameter("username"), "username"); password = request.getParameter("password"); if (connectionType == ConnectionType.ILIAS) { sshUsername = parseName(request.getParameter("sshUsername"), "sshUsername"); } else { sshUsername = ""; } if (connectionType == ConnectionType.SVN) { structure = parseStructure(request.getParameter("structure")); } else { structure = null; } } catch (BadRequestException e) { throw new BadRequestException(errorPrefix + e.getMessage()); } /* If this is an ILIAS connection, we need the SSH key-file */ Part sshKey = null; String keyFileName = ""; if (connectionType == ConnectionType.ILIAS) { try { sshKey = request.getPart("sshKeyFile"); } catch (ServletException e) { throw new BadRequestException(errorPrefix + "No multipart request."); } catch (IOException e) { throw new InternalActionErrorException(errorPrefix + "Could not read the submitted keyfile."); } keyFileName = sshKey.getSubmittedFileName(); if ((keyFileName == null) || ("".equals(keyFileName))) { throw new BadRequestException("No key-file submitted!"); } } int connectionIdInt = Integer.parseInt(connectionId); /* Update the connection. */ Connection connection = null; try { connection = m_controller.updateConnection(connectionIdInt, connectionName, connectionType, location, username, password, sshUsername, keyFileName, structure); } catch (ConfigurationException e) { throw new InternalActionErrorException(errorPrefix + "Could not create connection."); } catch (InvalidStructureException e) { throw new InternalActionErrorException(errorPrefix + "The submitted structure is invalid."); } /* Write the key-file if this is an ILIAS connection. */ if (connectionType == ConnectionType.ILIAS) { Path outputDirectory = connection.getSshKeyFileLocation().getParent(); writeSubmittedFile(sshKey, outputDirectory); } return GSON.toJson(connection); }
From source file:cheladocs.controlo.DocumentoServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/pdf; application/msword; application/excel"); String comando = request.getParameter("comando"); if (comando == null) { comando = "principal"; }/*from www . j a v a2s .com*/ DocumentoDAO documentoDAO; Documento documento = new Documento(); if (comando == null || !comando.equalsIgnoreCase("principal")) { try { idDocumento = request.getParameter("numero_protocolo"); if (idDocumento != null) { documento.setNumeroProtocolo(Integer.parseInt(idDocumento)); } } catch (NumberFormatException ex) { System.err.println("Erro ao converter dado: " + ex.getMessage()); } } try { documentoDAO = new DocumentoDAO(); if (comando.equalsIgnoreCase("guardar")) { documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente"))); documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada"))); documento.setOrigem(request.getParameter("origem_documento")); documento.setDescricaoAssunto(request.getParameter("descricao_assunto")); documento.getNaturezaAssunto() .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto"))); documento.getTipoExpediente() .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente"))); Part ficheiro = request.getPart("ficheiro"); if (ficheiro != null) { byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream()); documento.setConteudoDocumento(ficheiroDados); documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName()); doUpload(ficheiro, request); } documentoDAO.save(documento); response.sendRedirect("paginas/gerir_documento.jsp"); } else if (comando.equalsIgnoreCase("editar")) { documento.setNumeroProtocolo(Integer.parseInt(request.getParameter("requerente"))); documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente"))); documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada"))); documento.setOrigem(request.getParameter("origem_documento")); documento.setDescricaoAssunto(request.getParameter("descricao_assunto")); documento.getNaturezaAssunto() .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto"))); documento.getTipoExpediente() .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente"))); Part ficheiro = request.getPart("ficheiro"); if (ficheiro != null) { byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream()); documento.setConteudoDocumento(ficheiroDados); documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName()); doUpload(ficheiro, request); } documentoDAO.update(documento); response.sendRedirect("paginas/gerir_documento.jsp"); } else if (comando.equalsIgnoreCase("eliminar")) { documentoDAO.delete(documento); response.sendRedirect("paginas/gerir_documento.jsp"); } else if (comando.equalsIgnoreCase("prepara_editar")) { documento = documentoDAO.findById(documento.getNumeroProtocolo()); request.setAttribute("documento", documento); RequestDispatcher rd = request.getRequestDispatcher("paginas/documento_editar.jsp"); rd.forward(request, response); } else if (comando.equalsIgnoreCase("listar")) { response.sendRedirect("paginas/gerir_documento.jsp"); } else if (comando.equalsIgnoreCase("imprimir_todos") || comando.equalsIgnoreCase("imprimir_by_id")) { ReporteUtil reporte = new ReporteUtil(); File caminhoRelatorio = null; HashMap hashMap = new HashMap(); if (comando.equalsIgnoreCase("imprimir_todos")) { caminhoRelatorio = new File(getServletConfig().getServletContext() .getRealPath("/WEB-INF/relatorios/DocumentoListar.jasper")); reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response); } else { hashMap.put("codigo_documento", Integer.parseInt(idDocumento)); caminhoRelatorio = new File(getServletConfig().getServletContext() .getRealPath("/WEB-INF/relatorios/Ficha_Documento.jasper")); reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response); } } } catch (IOException ex) { ex.printStackTrace(); } }
From source file:com.playright.servlet.DataController.java
private static CoverageData getCoverageDateFromRequest(HttpServletRequest request) throws ServletException { CoverageData cd = new CoverageData(); try {/* w w w . j av a 2 s . co m*/ if (!"".equalsIgnoreCase(request.getParameter("id")) && request.getParameter("id") != null) { cd.setId(Integer.parseInt(request.getParameter("id"))); } SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); java.util.Date ud = sdf.parse(request.getParameter("newsDate")); cd.setNewsDate(new java.sql.Date(ud.getTime())); cd.setNewspaper(request.getParameter("newspaper")); cd.setHeadline(request.getParameter("headline")); cd.setLanguage(request.getParameter("language")); cd.setEdition(request.getParameter("edition")); cd.setSupplement(request.getParameter("supplement")); cd.setSource(request.getParameter("source")); if (!"".equalsIgnoreCase(request.getParameter("pageNo")) && request.getParameter("pageNo") != null) { cd.setPageNo(Integer.parseInt(request.getParameter("pageNo"))); } if (!"".equalsIgnoreCase(request.getParameter("height")) && request.getParameter("height") != null) { cd.setHeight(Integer.parseInt(request.getParameter("height"))); } if (!"".equalsIgnoreCase(request.getParameter("width")) && request.getParameter("width") != null) { cd.setWidth(Integer.parseInt(request.getParameter("width"))); } if (!"".equalsIgnoreCase(request.getParameter("totalArticleSize")) && request.getParameter("totalArticleSize") != null) { cd.setTotalArticleSize(Integer.parseInt(request.getParameter("totalArticleSize"))); } if (!"".equalsIgnoreCase(request.getParameter("circulationFigure")) && request.getParameter("circulationFigure") != null) { cd.setCirculationFigure(Integer.parseInt(request.getParameter("circulationFigure"))); } if (!"".equalsIgnoreCase(request.getParameter("journalistFactor")) && request.getParameter("journalistFactor") != null) { cd.setJournalistFactor(Integer.parseInt(request.getParameter("journalistFactor"))); } if (!"".equalsIgnoreCase(request.getParameter("quantitativeAve")) && request.getParameter("quantitativeAve") != null) { cd.setQuantitativeAve(new BigDecimal(request.getParameter("quantitativeAve"))); } if (!"".equalsIgnoreCase(request.getParameter("imageExists")) && request.getParameter("imageExists") != null) { cd.setImageExists(request.getParameter("imageExists")); } Blob b = null; String fileName = ""; String contentType = ""; try { Part filePart = request.getPart("image"); InputStream fileContent = filePart.getInputStream(); byte[] bytes = IOUtils.toByteArray(fileContent); b = new SerialBlob(bytes); fileName = filePart.getSubmittedFileName(); contentType = filePart.getContentType(); } catch (IOException ex) { Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex); } if (b != null && b.length() != 0) { cd.setImageBlob(b); cd.setImageFileName(fileName); cd.setImageType(contentType); } } catch (ParseException ex) { Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex); } return cd; }
From source file:com.izv.controlador.ControladorAndroid.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* ww w . jav a 2 s . c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); boolean forward = false; String target, op, action, view; ControlDB bd; target = request.getParameter("target"); op = request.getParameter("op"); action = request.getParameter("action"); if (target.equals("inmobiliaria") && op.equals("insert") && action.equals("op")) { response.setContentType("text/html;charset=UTF-8"); format = new SimpleDateFormat(); format.applyPattern("yyyy-dd-MM"); Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); format.format(date); Inmueble inmueble = new Inmueble(); inmueble.setLocalidad(request.getParameter("localidad")); inmueble.setDireccion(request.getParameter("direccion")); inmueble.setTipo(request.getParameter("tipo")); inmueble.setUsuario(request.getParameter("usuario")); inmueble.setPrecio(request.getParameter("precio")); inmueble.setFechaalta(date); ModeloInmueble.insert(inmueble); Inmueble inm = ModeloInmueble.get(inmueble.getId() + ""); try (PrintWriter out = response.getWriter()) { out.println(inm.getId() + ""); } } else { if (target.equals("inmobiliaria") && op.equals("imagen") && action.equals("op")) { forward = false; boolean error = false; String id = request.getParameter("id"); response.setContentType("text/html;charset=UTF-8"); Calendar calendario = new GregorianCalendar(); Date date = calendario.getTime(); SimpleDateFormat formatoFecha = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSSSS"); String fecha = formatoFecha.format(date); String titulo = "inmueble_" + id + "_" + fecha; Part archivoPost = request.getPart("archivo"); String carpeta = getServletContext().getRealPath("/") + "fotos/"; InputStream input = archivoPost.getInputStream(); try { OutputStream out = new FileOutputStream(carpeta + titulo + ".jpg"); byte[] b = new byte[2048]; int length; while ((length = input.read(b)) != -1) { out.write(b, 0, length); } } catch (Exception e) { error = true; } finally { input.close(); } Fotos fot = new Fotos(); fot.setIdinmueble(Integer.valueOf(id)); fot.setNombre(titulo + ".jpg"); ModeloFoto.insert(fot); try (PrintWriter out = response.getWriter()) { if (error) { out.println("error"); } else { out.println("foto subida"); // respuesta json chapucera } } } else { if (target.equals("bar")) { try { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); response.setContentType("application/json"); /* int r = bd.ejecutarDelete("delete from pedidos where idPedido=52"); System.out.println(r); */ // String fechaHora = getFecha(); // String consulta = "insert into pedidos values(0, '" + fechaHora + "', 0, 0, null, 'admin ', 6, 1)"; // bd.ejecutarInsert(consulta); ResultSet r = bd.ejecutarSelect("Select * from pedidos"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = r.getMetaData(); int columns = rsMetaData.getColumnCount(); try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } System.out.println(objetoJSON + "\n"); // System.out.println(r.getString(1) + " " + r.getString(2) + " " + r.getString(3) // + " " + r.getString(4)); array.put(objetoJSON); } } catch (SQLException ex) { Logger.getLogger(ControladorAndroid.class.getName()).log(Level.SEVERE, null, ex); } PrintWriter out = response.getWriter(); out.print(array); out.flush(); // obj.put("nombre", "Angel"); // obj.put("password", "1234"); // System.out.println("JSON " + obj.toString()); // System.out.println(obj.getString("nombre") + " " + obj.getString("password")); } catch (JSONException ex) { Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(ControladorAndroid.class.getName()).log(Level.SEVERE, null, ex); } } } } }
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);//ww w. ja v a 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:org.eclipse.equinox.http.servlet.tests.ServletTest.java
public void test_Servlet16() throws Exception { Servlet servlet = new HttpServlet() { private static final long serialVersionUID = 1L; @Override//from ww w . ja v a 2 s . c o m protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Part part = req.getPart("file"); Assert.assertNotNull(part); String submittedFileName = part.getSubmittedFileName(); String contentType = part.getContentType(); long size = part.getSize(); PrintWriter writer = resp.getWriter(); writer.write(submittedFileName); writer.write("|"); writer.write(contentType); writer.write("|" + size); } }; Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16"); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*"); props.put("equinox.http.multipartSupported", Boolean.TRUE); registrations.add(getBundleContext().registerService(Servlet.class, servlet, props)); Map<String, List<Object>> map = new HashMap<String, List<Object>>(); map.put("file", Arrays.<Object>asList(getClass().getResource("resource1.txt"))); Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map); Assert.assertEquals("200", result.get("responseCode").get(0)); Assert.assertEquals("resource1.txt|text/plain|1", result.get("responseBody").get(0)); }
From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java
public void test_Servlet17() throws Exception { Servlet servlet = new HttpServlet() { private static final long serialVersionUID = 1L; @Override//from ww w . java2 s .c o m protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Part part = req.getPart("file"); Assert.assertNotNull(part); String submittedFileName = getSubmittedFileName(part); String contentType = part.getContentType(); long size = part.getSize(); PrintWriter writer = resp.getWriter(); writer.write(submittedFileName); writer.write("|"); writer.write(contentType); writer.write("|" + size); } }; Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16"); props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*"); props.put("equinox.http.multipartSupported", Boolean.TRUE); registrations.add(getBundleContext().registerService(Servlet.class, servlet, props)); Map<String, List<Object>> map = new HashMap<String, List<Object>>(); map.put("file", Arrays.<Object>asList(getClass().getResource("blue.png"))); Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map); Assert.assertEquals("200", result.get("responseCode").get(0)); Assert.assertEquals("blue.png|image/png|292", result.get("responseBody").get(0)); }
From source file:org.helm.rest.AjaxTool.java
Response OnCmd(String cmd, Map<String, String> items, HttpServletRequest request) throws Exception { JSONObject ret = new JSONObject(); switch (cmd) { case "helm.toolkit.monomer.json": { ArrayList<JSONObject> ret2 = getToolkitMonomers(); ret.put("list", ret2); }//w w w .j a v a 2 s . c o m break; case "helm.toolkit.monomer.downloadjson": { ArrayList<JSONObject> ret2 = getToolkitMonomers(); String s = "org.helm.webeditor.Monomers.loadDB(" + ret2.toString() + ");"; return Response.status(Response.Status.OK).entity(s).build(); } case "helm.monomer.del": LoadRules(); ret = monomers.DelRecord(items.get("id")); if (ret != null) { try { monomers.Save(); } catch (Exception e) { throw e; } } break; case "helm.monomer.load": LoadMonomers(); ret = monomers.LoadRow(items.get("id")); break; case "helm.monomer.save": { LoadMonomers(); String[] keys = monomers.getKeys(); String[] row = new String[keys.length]; for (int i = 0; i < keys.length; ++i) { row[i] = items.get(keys[i]); } ret = monomers.SaveRecord(row); if (ret != null) { try { monomers.Save(); } catch (Exception e) { throw e; } } } break; case "helm.monomer.suggest": break; case "helm.monomer.list": { LoadMonomers(); int page = ToInt(items.get("page")); int countperpage = ToInt(items.get("countperpage")); String polymertype = items.get("polymertype"); String monomertype = items.get("monomertype"); String symbol = items.get("symbol"); ret = monomers.List(page, countperpage, "polymertype", polymertype, "monomertype", monomertype, "symbol", symbol); } break; case "helm.monomer.all": { LoadMonomers(); ret.put("monomers", monomers.AsJSON()); } break; case "helm.monomer.json": { LoadMonomers(); ArrayList<JSONObject> ret2 = monomers.AsJSON(); ret.put("list", ret2); } break; case "helm.monomer.downloadjson": { LoadMonomers(); ArrayList<JSONObject> ret2 = monomers.AsJSON(); String s = "org.helm.webeditor.Monomers.loadDB(" + ret2.toString() + ");"; return Response.status(Response.Status.OK).entity(s).build(); } case "helm.monomer.filelocation": { ret = new JSONObject(); ret.put("momomers", DEFAULT_HELM_DIR + System.getProperty("file.separator") + DEFAULT_MONOMERS_FILE_NAME); } break; case "helm.rule.del": LoadRules(); ret = rules.DelRecord(items.get("id")); if (ret != null) { try { rules.Save(); } catch (Exception e) { throw e; } } break; case "helm.rule.load": LoadRules(); ret = rules.LoadRow(items.get("id")); break; case "helm.rule.save": { LoadRules(); String[] keys = rules.getKeys(); String[] row = new String[keys.length]; for (int i = 0; i < keys.length; ++i) { row[i] = items.get(keys[i]); } ret = rules.SaveRecord(row); if (ret != null) { try { rules.Save(); } catch (Exception e) { throw e; } } } break; case "helm.rule.list": { LoadRules(); int page = ToInt(items.get("page")); int countperpage = ToInt(items.get("countperpage")); String category = items.get("category"); ret = rules.List(page, countperpage, "category", category, null, null, null, null); } break; case "helm.rule.all": { LoadRules(); ret.put("rules", rules.AsJSON()); } break; case "helm.rule.downloadjson": case "helm.rules.downloadjson": { LoadRules(); ArrayList<JSONObject> ret2 = rules.AsJSON(); String s = "org.helm.webeditor.RuleSet.loadDB(" + ret2.toString() + ");"; return Response.status(Response.Status.OK).entity(s).build(); } case "openjsd": { ret = new JSONObject(); Part part = request.getPart("file"); String filename = getFileName(part); String contents = getValue(part); ret.put("filename", filename); ret.put("base64", Database.EncodeBase64(contents)); String s = "<html><head></head><body><textarea>" + wrapAjaxResult(ret) + "</textarea></body></html>"; return Response.status(Response.Status.OK).entity(s).type("text/html").build(); } case "savefile": { String filename = items.get("filename"); String contents = items.get("contents"); return Response.ok(contents, "application/unknown") .header("content-disposition", "attachment;filename=" + filename).build(); } case "helm.properties": ret = CalculateProperties(items.get("helm")); break; case "cleanup": ret = Cleanup(items.get("input"), items.get("inputformat")); break; default: return Response.status(Response.Status.OK).entity(wrapAjaxError("Unknown cmd: " + cmd)).build(); } return Response.status(Response.Status.OK).entity(wrapAjaxResult(ret)).build(); }