Example usage for org.apache.commons.fileupload FileItem getString

List of usage examples for org.apache.commons.fileupload FileItem getString

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getString.

Prototype

String getString();

Source Link

Document

Returns the contents of the file item as a String, using the default character encoding.

Usage

From source file:eg.nileu.cis.nilestore.webapp.servlets.UploadServletRequest.java

/**
 * Init_ajax upload.//from   ww  w. j av a 2 s.c o m
 * 
 * @throws Exception
 *             the exception
 */
@SuppressWarnings("unchecked")
private void init_ajaxUpload() throws Exception {

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    List<FileItem> items = uploadHandler.parseRequest(request);
    for (FileItem item : items) {
        if (!item.isFormField()) {
            File f = File.createTempFile("upfile", ".tmp");
            f.deleteOnExit();
            item.write(f);
            fileName = item.getName();
            if (fileName.contains(File.separator)) {
                fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
            }
            filePath = f.getAbsolutePath();
            isFileFound = true;
            // Here we handle only one file at once
            break;
        } else {
            if (item.getFieldName().equals(DEST_FIELD_NAME)) {
                dest = Integer.valueOf(item.getString());
            }
        }
    }
    String t = getParameter("t");
    if (t != null) {
        returnType = t;
    }
}

From source file:com.aliasi.demo.framework.DemoServlet.java

void generateOutput(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    InputStream in = null;/*from w  w w .  j a  v a2  s  .  c  o m*/
    OutputStream out = null;

    try {
        response.setContentType(mDemo.responseType());
        out = response.getOutputStream();

        @SuppressWarnings("unchecked") // bad inherited API from commons
        Properties properties = mapToProperties((Map<String, String[]>) request.getParameterMap());

        String reqContentType = request.getContentType();

        if (reqContentType == null || reqContentType.startsWith("text/plain")) {

            properties.setProperty("inputType", "text/plain");
            String reqCharset = request.getCharacterEncoding();
            if (reqCharset != null)
                properties.setProperty("inputCharset", reqCharset);
            in = request.getInputStream();

        } else if (reqContentType.startsWith("application/x-www-form-urlencoded")) {

            String codedText = request.getParameter("inputText");
            byte[] bytes = codedText.getBytes("ISO-8859-1");
            in = new ByteArrayInputStream(bytes);

        } else if (ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload uploader = new ServletFileUpload(factory);
            @SuppressWarnings("unchecked") // bad commons API
            List<FileItem> items = (List<FileItem>) uploader.parseRequest(request);
            Iterator<FileItem> it = items.iterator();
            while (it.hasNext()) {
                log("found item");
                FileItem item = it.next();
                if (item.isFormField()) {
                    String key = item.getFieldName();
                    String val = item.getString();
                    properties.setProperty(key, val);
                } else {
                    byte[] bytes = item.get();
                    in = new ByteArrayInputStream(bytes);
                }
            }

        } else {
            System.out.println("unexpected content type");
            String msg = "Unexpected request content" + reqContentType;
            throw new ServletException(msg);
        }
        mDemo.process(in, out, properties);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    } finally {
        Streams.closeQuietly(in);
        Streams.closeQuietly(out);
    }
}

From source file:gov.nist.appvet.tool.sigverifier.Service.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get received HTTP parameters and file upload
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = null;//from w w w.j  av  a2 s. c om
    FileItem fileItem = null;

    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    // Get received items
    Iterator iter = items.iterator();
    FileItem item = null;

    while (iter.hasNext()) {
        item = (FileItem) iter.next();
        if (item.isFormField()) {
            // Get HTML form parameters
            String incomingParameter = item.getFieldName();
            String incomingValue = item.getString();
            if (incomingParameter.equals("appid")) {
                appId = incomingValue;
            }
            /** CHANGE (START): Get other tools-specific form parameters **/
            /** CHANGE (END): Get other tools-specific form parameters **/
        } else {
            // item should now hold the received file
            if (item != null) {
                fileItem = item;
                log.debug("Received file: " + fileItem.getName());
            }
        }
    }

    if (appId == null) {
        // All tool services require an AppVet app ID
        HttpUtil.sendHttp400(response, "No app ID specified");
        return;
    }

    if (fileItem != null) {
        // Get app file
        fileName = FileUtil.getFileName(fileItem.getName());
        if (!fileName.endsWith(".apk")) {
            HttpUtil.sendHttp400(response, "Invalid app file: " + fileItem.getName());
            return;
        }
        // Create app directory
        appDirPath = Properties.TEMP_DIR + "/" + appId;
        File appDir = new File(appDirPath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        // Create report path
        reportFilePath = Properties.TEMP_DIR + "/" + appId + "/" + reportName + "."
                + Properties.reportFormat.toLowerCase();

        appFilePath = Properties.TEMP_DIR + "/" + appId + "/" + fileName;
        log.debug("App file path: " + appFilePath);
        if (!FileUtil.saveFileUpload(fileItem, appFilePath)) {
            HttpUtil.sendHttp500(response, "Could not save uploaded file");
            return;
        }
    } else {
        HttpUtil.sendHttp400(response, "No app was received.");
        return;
    }

    // Use if reading command from ToolProperties.xml. Otherwise,
    // comment-out if using custom command (called by customExecute())
    command = getCommand();

    // If asynchronous, send acknowledgement back to AppVet now
    if (Properties.protocol.equals(Protocol.ASYNCHRONOUS.name())) {
        HttpUtil.sendHttp202(response, "Received app " + appId + " for processing.");
    }
    /*
     * CHANGE: Select either execute() to execute a native OS command or
     * customExecute() to execute your own custom code. Make sure that the
     * unused method call is commented-out.
     */
    reportBuffer = new StringBuffer();
    boolean succeeded = execute(command, reportBuffer);

    // Delay for demo purposes
    try {
        Thread.sleep(Properties.delay);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // boolean succeeded = customExecute(reportBuffer);
    if (!succeeded) {
        log.error("Error detected: " + reportBuffer.toString());
        String errorReport = ReportUtil.getHtmlReport(response, fileName, ToolStatus.ERROR,
                reportBuffer.toString(), "Description: \tApp is signed.\n\n",
                "Description: \tApp is unsigned or incorrectly signed.\n\n", null,
                "Description: \tError or exception processing app.\n\n");
        // Send report to AppVet
        if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) {
            // Send back ASCII in HTTP Response
            ReportUtil.sendInHttpResponse(response, errorReport, ToolStatus.ERROR);
        } else if (Properties.protocol.equals(Protocol.ASYNCHRONOUS.name())) {
            // Send report file in new HTTP Request to AppVet
            if (FileUtil.saveReport(errorReport, reportFilePath)) {
                ReportUtil.sendInNewHttpRequest(appId, reportFilePath, ToolStatus.ERROR);
            }
        }
        return;
    }

    // Analyze report and generate tool status
    log.debug("Analyzing report for " + appFilePath);
    ToolStatus reportStatus = analyzeReport(reportBuffer.toString());
    log.debug("Result: " + reportStatus.name());
    String reportContent = null;

    // Get report
    if (Properties.reportFormat.equals(ReportFormat.HTML.name())) {
        reportContent = ReportUtil.getHtmlReport(response, fileName, reportStatus, reportBuffer.toString(),
                "Description: \tApp is signed (Note: some warnings may exist. See below for details).\n\n",
                "Description: \tApp is unsigned or incorrectly signed.\n\n",
                "Description: \tApp is unsigned or incorrectly signed.\n\n",
                "Description: \tError or exception processing app.\n\n");
    } else if (Properties.reportFormat.equals(ReportFormat.TXT.name())) {
        reportContent = getTxtReport();
    } else if (Properties.reportFormat.equals(ReportFormat.PDF.name())) {
        reportContent = getPdfReport();
    } else if (Properties.reportFormat.equals(ReportFormat.JSON.name())) {
        reportContent = getJsonReport();
    }

    // If report is null or empty, stop processing
    if (reportContent == null || reportContent.isEmpty()) {
        log.error("Tool report is null or empty");
        return;
    }

    // Send report to AppVet
    if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) {
        // Send back ASCII in HTTP Response
        ReportUtil.sendInHttpResponse(response, reportContent, reportStatus);
    } else if (Properties.protocol.equals(Protocol.ASYNCHRONOUS.name())) {
        // Send report file in new HTTP Request to AppVet
        if (FileUtil.saveReport(reportContent, reportFilePath)) {
            ReportUtil.sendInNewHttpRequest(appId, reportFilePath, reportStatus);
        }
    }

    // Clean up
    if (!Properties.keepApps) {
        if (FileUtil.deleteDirectory(new File(appDirPath))) {
            log.debug("Deleted " + appFilePath);
        } else {
            log.warn("Could not delete " + appFilePath);
        }
    }

    reportBuffer = null;

    // Clean up
    System.gc();
}

From source file:net.hillsdon.reviki.web.pages.impl.DefaultPageImpl.java

public View attach(final PageReference page, final ConsumedPath path, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new InvalidInputException("multipart request expected.");
    }//from  w  w  w . j  ava2 s  . c o m
    List<FileItem> items = getFileItems(request);
    try {
        if (items.size() > 4) {
            throw new InvalidInputException("One file at a time.");
        }
        String attachmentName = null;
        Long baseRevision = null;
        String attachmentMessage = null;
        FileItem file = null;
        for (FileItem item : items) {
            if (PARAM_ATTACHMENT_NAME.equals(item.getFieldName())) {
                attachmentName = item.getString().trim();
            }
            if (PARAM_BASE_REVISION.equals(item.getFieldName())) {
                baseRevision = RequestParameterReaders.getLong(item.getString().trim(), PARAM_BASE_REVISION);
            }
            if (PARAM_ATTACHMENT_MESSAGE.equals(item.getFieldName())) {
                attachmentMessage = item.getString().trim();
                if (attachmentMessage.length() == 0) {
                    attachmentMessage = null;
                }
            }
            if (!item.isFormField()) {
                file = item;
            }
        }
        if (baseRevision == null) {
            baseRevision = VersionedPageInfo.UNCOMMITTED;
        }

        if (file == null || file.getSize() == 0) {
            request.setAttribute("flash", ERROR_NO_FILE);
            return attachments(page, path, request, response);
        } else {
            InputStream in = file.getInputStream();
            try {
                // get the page from store - needed to get content of the special
                // pages which were not saved yet
                PageInfo pageInfo = _store.get(page, -1);
                // IE sends the full file path.
                storeAttachment(pageInfo, attachmentName, baseRevision, attachmentMessage,
                        FilenameUtils.getName(file.getName()), in);
                _store.expire(pageInfo);
                return new RedirectToPageView(_wikiUrls, page, "/attachments/");
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } finally {
        for (FileItem item : items) {
            item.delete();
        }
    }
}

From source file:fsi_admin.JAwsS3Conn.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ERROR = null, codErr = null;

    try {//from   w  w  w  . j  a  v  a  2 s . co  m
        Properties parametros = new Properties();
        Vector archivos = new Vector();
        DiskFileUpload fu = new DiskFileUpload();
        List items = fu.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField())
                parametros.put(item.getFieldName(), item.getString());
            else
                archivos.addElement(item);
        }

        if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null
                || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null
                || parametros.getProperty("ACTION") == null) {
            System.out.println("No recibi parametros de conexin antes del archivo");
            ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD,ACTION) antes del archivo";
            codErr = "3";
            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
        }

        //Hasta aqui se han enviado todos los parametros ninguno nulo
        if (ERROR == null) {
            StringBuffer msj = new StringBuffer(), S3BUKT = new StringBuffer(), S3USR = new StringBuffer(),
                    S3PASS = new StringBuffer();
            MutableBoolean COBRAR = new MutableBoolean(false);
            MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0);
            // Primero obtiene info del S3
            if (!obtenInfoAWSS3(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"),
                    parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), S3BUKT, S3USR, S3PASS,
                    msj, COSTO, SALDO, COBRAR)) {
                System.out.println("El usuario y contrasea de servicio estan mal");
                ERROR = msj.toString();
                codErr = "2";
                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                        parametros.getProperty("PASSWORD"), request, ERROR, 2);

            } else {
                AWSCredentials credentials = new BasicAWSCredentials(S3USR.toString(), S3PASS.toString());
                AmazonS3 s3 = new AmazonS3Client(credentials);
                Region usWest2 = Region.getRegion(Regions.US_WEST_2);
                s3.setRegion(usWest2);
                //System.out.println("AwsConn:" + parametros.getProperty("NOMBRE") + ":parametros.getProperty(NOMBRE)");
                String nombre = parametros.getProperty("SERVER") + parametros.getProperty("DATABASE")
                        + parametros.getProperty("ID_MODULO") + parametros.getProperty("OBJIDS")
                        + parametros.getProperty("IDSEP") + parametros.getProperty("NOMBRE");
                //System.out.println("AwsConn_Nombre:" + nombre + ":nombre");

                if (parametros.getProperty("ACTION").equals("SUBIR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));
                    Double TAMBITES = new Double(Double.parseDouble(parametros.getProperty("TAMBITES")));

                    if (COBRAR.booleanValue() && SALDO
                            .doubleValue() < (COSTO.doubleValue() * (((TOTBITES + TAMBITES) / 1024) / 1024))) {
                        System.out
                                .println("El servicio S3 de subida tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de subida tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!subirArchivo(msj, s3, S3BUKT.toString(), nombre, archivos)) {
                            System.out.println("No se permiti subir el archivo al s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else {
                            ingresarRegistroExitoso(parametros.getProperty("SERVER"),
                                    parametros.getProperty("DATABASE"), parametros.getProperty("ID_MODULO"),
                                    parametros.getProperty("OBJIDS"), parametros.getProperty("IDSEP"),
                                    parametros.getProperty("NOMBRE"), parametros.getProperty("TAMBITES"));
                        }
                    }

                } else if (parametros.getProperty("ACTION").equals("ELIMINAR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));

                    if (COBRAR.booleanValue()
                            && SALDO.doubleValue() < (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))) {
                        System.out
                                .println("El servicio S3 de borrado tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de borrado tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!eliminarArchivo(msj, s3, S3BUKT.toString(), nombre)) {
                            System.out.println("No se permiti eliminar el archivo del s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else {
                            eliminarRegistroExitoso(parametros.getProperty("SERVER"),
                                    parametros.getProperty("DATABASE"), parametros.getProperty("ID_MODULO"),
                                    parametros.getProperty("OBJIDS"), parametros.getProperty("IDSEP"),
                                    parametros.getProperty("NOMBRE"));
                        }
                    }
                } else if (parametros.getProperty("ACTION").equals("DESCARGAR")) {
                    Double TOTBITES = new Double(Double.parseDouble(parametros.getProperty("TOTBITES")));
                    //System.out.println("COBRAR: " + COBRAR.booleanValue() + " SALDO: " + SALDO.doubleValue() + " COSTO: " + COSTO.doubleValue() + " TOTBITES: " + TOTBITES + " TOTMB: " + ((TOTBITES / 1024) / 1024) + " RES: " + (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024)));
                    if (COBRAR.booleanValue()
                            && SALDO.doubleValue() < (COSTO.doubleValue() * ((TOTBITES / 1024) / 1024))) {
                        System.out.println(
                                "El servicio S3 de descarga tiene un costo que no alcanza en el saldo");
                        ERROR = "El servicio S3 de descarga tiene un costo que no alcanza en el saldo";
                        codErr = "2";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 2);
                    } else {
                        if (!descargarArchivo(response, msj, s3, S3BUKT.toString(), nombre,
                                parametros.getProperty("NOMBRE"))) {
                            System.out.println("No se permiti descargar el archivo del s3");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
                        } else
                            return;
                    }
                }

                if (ERROR == null) {
                    //Devuelve la respuesta al cliente
                    Element S3 = new Element("S3");
                    S3.setAttribute("Archivo", nombre);
                    S3.setAttribute("MsjError", "");
                    Document Reporte = new Document(S3);

                    Format format = Format.getPrettyFormat();
                    format.setEncoding("utf-8");
                    format.setTextMode(TextMode.NORMALIZE);
                    XMLOutputter xmlOutputter = new XMLOutputter(format);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    xmlOutputter.output(Reporte, out);

                    byte[] data = out.toByteArray();
                    ByteArrayInputStream istream = new ByteArrayInputStream(data);

                    String destino = "Archivo.xml";
                    JBajarArchivo fd = new JBajarArchivo();
                    fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml",
                            data.length, destino);

                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        ERROR = "ERROR DE EXCEPCION EN SERVIDOR AWS S3: " + e.getMessage();
    }

    //Genera el archivo XML de error para ser devuelto al Servidor
    if (ERROR != null) {
        Element SIGN_ERROR = new Element("SIGN_ERROR");
        SIGN_ERROR.setAttribute("CodError", codErr);
        SIGN_ERROR.setAttribute("MsjError", ERROR);
        Document Reporte = new Document(SIGN_ERROR);

        Format format = Format.getPrettyFormat();
        format.setEncoding("utf-8");
        format.setTextMode(TextMode.NORMALIZE);
        XMLOutputter xmlOutputter = new XMLOutputter(format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        xmlOutputter.output(Reporte, out);

        byte[] data = out.toByteArray();
        ByteArrayInputStream istream = new ByteArrayInputStream(data);

        String destino = "SIGN_ERROR.xml";
        JBajarArchivo fd = new JBajarArchivo();
        fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length,
                destino);

    }

}

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Sets up the given {@link EntityEnclosingMethod} to send the same multipart
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
 *                               configuring to send a multipart request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the mutlipart data to be sent via the {@link EntityEnclosingMethod}
 *//*w  w  w. ja  v a2 s. com*/
private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod,
        HttpServletRequest httpServletRequest) throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), entityEnclosingMethod.getParams());
        entityEnclosingMethod.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:agent_update.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w.j a v  a 2 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, FileUploadException {
    response.setContentType("text/html;charset=UTF-8");

    HttpSession hs = request.getSession();
    PrintWriter out = response.getWriter();

    try {

        if (hs.getAttribute("user") != null) {
            Login ln = (Login) hs.getAttribute("user");
            System.out.println(ln.getUId());

            String fn = "";
            String lastn = "";
            String un = "";
            String state = "";
            String city = "";
            String area = "";
            String e = "";
            String ad1 = "";
            String ad2 = "";
            String num = "";
            String p = "";
            String des = "";
            String cmp = "";
            String work = "";
            String agentphoto = "";
            String agentname = "";
            int id = 0;

            // creates FileItem instances which keep their content in a temporary file on disk
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            //get the list of all fields from request
            List<FileItem> fields = upload.parseRequest(request);
            // iterates the object of list
            Iterator<FileItem> it = fields.iterator();
            //getting objects one by one
            while (it.hasNext()) {
                //assigning coming object if list to object of FileItem
                FileItem fileItem = it.next();
                //check whether field is form field or not
                boolean isFormField = fileItem.isFormField();

                if (isFormField) {
                    //get the filed name 
                    String fieldName = fileItem.getFieldName();

                    if (fieldName.equals("fname")) {
                        fn = fileItem.getString();
                    } else if (fieldName.equals("id")) {
                        id = Integer.parseInt(fileItem.getString());
                    } else if (fieldName.equals("lname")) {
                        lastn = fileItem.getString();
                    } else if (fieldName.equals("uname")) {
                        un = fileItem.getString();
                    } else if (fieldName.equals("state")) {
                        state = fileItem.getString();
                    } else if (fieldName.equals("city")) {
                        city = fileItem.getString();
                    } else if (fieldName.equals("area")) {
                        area = fileItem.getString();
                    } else if (fieldName.equals("email")) {
                        e = fileItem.getString();
                    } else if (fieldName.equals("address1")) {
                        ad1 = fileItem.getString();
                    } else if (fieldName.equals("address2")) {
                        ad2 = fileItem.getString();
                    } else if (fieldName.equals("number")) {
                        num = fileItem.getString();

                    } else if (fieldName.equals("pwd")) {
                        p = fileItem.getString();
                    }

                    else if (fieldName.equals("descrip")) {
                        des = fileItem.getString();
                    } else if (fieldName.equals("compname")) {
                        cmp = fileItem.getString();
                    } else if (fieldName.equals("workx")) {
                        work = fileItem.getString();
                    }

                } else {

                    agentphoto = new File(fileItem.getName()).getName();

                    System.out.println(agentphoto);
                    try {

                        // FOR UBUNTU add GETRESOURCE  and GETPATH

                        String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/profilepic/";
                        //                    String filePath=  this.getServletContext().getResource("/images/profilepic").getPath()+"//";
                        System.out.println("====" + fp);
                        fileItem.write(new File(fp + agentphoto));
                    } catch (Exception ex) {
                        out.println(ex.toString());
                    }

                }

            }
            SessionFactory sf = NewHibernateUtil.getSessionFactory();
            Session ss = sf.openSession();
            Transaction tr = ss.beginTransaction();
            //            
            //           String state="";
            //            Criteria cr = ss.createCriteria(StateMaster.class);
            //            cr.add(Restrictions.eq("sId", Integer.parseInt(stateid)));
            //            ArrayList<StateMaster> ar = (ArrayList<StateMaster>)cr.list();
            //            System.out.println("----------"+ar.size());
            //            if(ar.isEmpty()){
            //                
            //            }else{
            //                state = ar.get(0).getSName();
            //                System.out.println("-------"+ar.get(0));
            //            }
            //            
            //            String city="";
            //            Criteria cr2 = ss.createCriteria(CityMaster.class);
            //            cr2.add(Restrictions.eq("cityId", Integer.parseInt(cityid)));
            //            ArrayList<CityMaster> ar2 = (ArrayList<CityMaster>)cr2.list();
            //            System.out.println("----------"+ar2.size());
            //            if(ar2.isEmpty()){
            //                
            //            }else{
            //                city = ar2.get(0).getCityName();
            //                System.out.println("-------"+city);
            //            }
            //            
            //            String area="";
            //            Criteria cr3 = ss.createCriteria(AreaMaster.class);
            //            cr3.add(Restrictions.eq("areaId", Integer.parseInt(areaid)));
            //            ArrayList<AreaMaster> ar3 = (ArrayList<AreaMaster>)cr3.list();
            //            System.out.println("----------"+ar3.size());
            //            if(ar3.isEmpty()){
            //                
            //            }else{
            //                area = ar3.get(0).getAreaName();
            //                System.out.println("-------"+area);
            //            }
            //            

            //       Criteria crr=ss.createCriteria(AgentDetail.class);
            //       crr.add(Restrictions.eq("uId", ln.getUId()));
            //       ArrayList<AgentDetail> arr=(ArrayList<AgentDetail>)crr.list();
            //       if(arr.isEmpty())
            //       {
            //           out.print("array empty");
            //       }
            //       else
            //       {
            //           AgentDetail agd=arr.get(0);
            AgentDetail agd2 = (AgentDetail) ss.get(AgentDetail.class, id);
            AgentDetail agd = new AgentDetail();

            agd.setUId(agd2.getUId());
            agd.setAId(agd2.getAId());
            agd.setACompanyname(cmp);
            agd.setADescription(des);
            agd.setAEmail(e);
            agd.setAFname(fn);
            agd.setAImg(agentphoto);
            agd.setALname(lastn);
            agd.setANo(num);
            agd.setAWorkx(work);
            agd.setACity(city);
            agd.setAArea(area);
            agd.setAState(state);
            agd.setAAddress1(ad1);
            agd.setAAddress2(ad2);
            agd.setAStatus(null);
            agd.setARating(null);
            agd.setAStatus("Accepted");
            // agd.getUId().setPwd(p);
            // agd.getUId().setUName(un);

            ss.evict(agd2);
            ss.update(agd);
            tr.commit();
            //       }

            RequestDispatcher rd = request.getRequestDispatcher("agentprofile.jsp");
            rd.forward(request, response);

        }
    }

    catch (HibernateException e) {
        out.println(e.getMessage());
    }
}

From source file:fsi_admin.JSmtpConn.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ERROR = null, codErr = null;

    try {/*www.  j ava2 s . c o  m*/
        Properties parametros = new Properties();
        Vector archivos = new Vector();
        DiskFileUpload fu = new DiskFileUpload();
        List items = fu.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField())
                parametros.put(item.getFieldName(), item.getString());
            else
                archivos.addElement(item);
        }

        if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null
                || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null
                || parametros.getProperty("BODY") == null || parametros.getProperty("MIMETYPE") == null
                || parametros.getProperty("SUBJECT") == null || parametros.getProperty("EMAIL") == null
                || parametros.getProperty("SOURCEMAIL") == null) {
            System.out.println("No recibi parametros de conexin antes del correo a enviar");
            ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD) antes del correo a enviar";
            codErr = "3";
            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
        }

        //Hasta aqui se han enviado todos los parametros ninguno nulo
        if (ERROR == null) {
            StringBuffer msj = new StringBuffer(), SMTPHOST = new StringBuffer(), SMTPPORT = new StringBuffer(),
                    SMTPUSR = new StringBuffer(), SMTPPASS = new StringBuffer();
            MutableBoolean COBRAR = new MutableBoolean(false);
            MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0);
            // Primero obtiene info del SMTP
            if (!obtenInfoSMTP(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"),
                    parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), SMTPHOST, SMTPPORT,
                    SMTPUSR, SMTPPASS, msj, COSTO, SALDO, COBRAR)) {
                System.out.println("El usuario y contrasea de servicio estan mal");
                ERROR = msj.toString();
                codErr = "2";
                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                        parametros.getProperty("PASSWORD"), request, ERROR, 2);

            } else {
                if (COBRAR.booleanValue() && SALDO.doubleValue() < COSTO.doubleValue()) {
                    System.out.println("El servicio tiene un costo que no alcanza en el saldo");
                    ERROR = "El servicio SMTP tiene un costo que no alcanza en el saldo";
                    codErr = "2";
                    ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                            parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                            parametros.getProperty("PASSWORD"), request, ERROR, 2);

                } else {
                    Properties props;

                    props = System.getProperties();
                    props.put("mail.transport.protocol", "smtp");
                    props.put("mail.smtp.port", Integer.parseInt(SMTPPORT.toString()));

                    // Set properties indicating that we want to use STARTTLS to encrypt the connection.
                    // The SMTP session will begin on an unencrypted connection, and then the client
                    // will issue a STARTTLS command to upgrade to an encrypted connection.
                    props.put("mail.smtp.auth", "true");
                    props.put("mail.smtp.starttls.enable", "true");
                    props.put("mail.smtp.starttls.required", "true");

                    // Create a Session object to represent a mail session with the specified properties. 
                    Session session = Session.getDefaultInstance(props);
                    MimeMessage mmsg = new MimeMessage(session);
                    BodyPart messagebodypart = new MimeBodyPart();
                    MimeMultipart multipart = new MimeMultipart();

                    if (!prepareMsg(parametros.getProperty("SOURCEMAIL"), parametros.getProperty("EMAIL"),
                            parametros.getProperty("SUBJECT"), parametros.getProperty("MIMETYPE"),
                            parametros.getProperty("BODY"), msj, props, session, mmsg, messagebodypart,
                            multipart)) {
                        System.out.println("No se permiti preparar el mensaje");
                        ERROR = msj.toString();
                        codErr = "3";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 3);

                    } else {
                        if (!adjuntarArchivo(msj, messagebodypart, multipart, archivos)) {
                            System.out.println("No se permiti adjuntar archivos al mensaje");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);

                        } else {
                            if (!sendMsg(SMTPHOST.toString(), SMTPUSR.toString(), SMTPPASS.toString(), msj,
                                    session, mmsg, multipart)) {
                                System.out.println("No se permiti enviar el mensaje");
                                ERROR = msj.toString();
                                codErr = "3";
                                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                        parametros.getProperty("PASSWORD"), request, ERROR, 3);
                            } else {
                                ingresarRegistroExitoso(parametros.getProperty("SERVER"),
                                        parametros.getProperty("DATABASE"), parametros.getProperty("SUBJECT"),
                                        COSTO, SALDO, COBRAR);

                                //Devuelve la respuesta al cliente
                                Element Correo = new Element("Correo");
                                Correo.setAttribute("Subject", parametros.getProperty("SUBJECT"));
                                Correo.setAttribute("MsjError", "");
                                Document Reporte = new Document(Correo);

                                Format format = Format.getPrettyFormat();
                                format.setEncoding("utf-8");
                                format.setTextMode(TextMode.NORMALIZE);
                                XMLOutputter xmlOutputter = new XMLOutputter(format);
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                xmlOutputter.output(Reporte, out);

                                byte[] data = out.toByteArray();
                                ByteArrayInputStream istream = new ByteArrayInputStream(data);

                                String destino = "Correo.xml";
                                JBajarArchivo fd = new JBajarArchivo();
                                fd.doDownload(response, getServletConfig().getServletContext(), istream,
                                        "text/xml", data.length, destino);

                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        ERROR = "ERROR DE EXCEPCION EN SERVIDOR PAC: " + e.getMessage();
    }

    //Genera el archivo XML de error para ser devuelto al Servidor
    if (ERROR != null) {
        Element SIGN_ERROR = new Element("SIGN_ERROR");
        SIGN_ERROR.setAttribute("CodError", codErr);
        SIGN_ERROR.setAttribute("MsjError", ERROR);
        Document Reporte = new Document(SIGN_ERROR);

        Format format = Format.getPrettyFormat();
        format.setEncoding("utf-8");
        format.setTextMode(TextMode.NORMALIZE);
        XMLOutputter xmlOutputter = new XMLOutputter(format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        xmlOutputter.output(Reporte, out);

        byte[] data = out.toByteArray();
        ByteArrayInputStream istream = new ByteArrayInputStream(data);

        String destino = "SIGN_ERROR.xml";
        JBajarArchivo fd = new JBajarArchivo();
        fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length,
                destino);

    }
}

From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Handle multipart form.//  w  w  w . j  a  va2s . co  m
 * 
 * @param request the request
 * @param requestContext the request context
 * 
 * @throws Exception the exception
 */
private void handleMultipartForm(HttpServletRequest request, RequestContextIFace requestContext)
        throws Exception {
    SourceBean serviceRequest = requestContext.getServiceRequest();

    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List fileItems = upload.parseRequest(request);
    Iterator iter = fileItems.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();
            serviceRequest.setAttribute(name, value);
        } else {
            processFileField(item, requestContext);
        }
    }
}

From source file:com.afis.jx.ckfinder.connector.handlers.command.FileUploadCommand.java

/**
 *
 * @param request http request/*w  w  w .  j a  v  a2s.c om*/
 * @return true if uploaded correctly
 */
@SuppressWarnings("unchecked")
private boolean fileUpload(final HttpServletRequest request) {
    try {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

        List<FileItem> items = uploadHandler.parseRequest(request);
        Collections.sort(items, new Comparator<FileItem>() {
            //This comparator moves tokenParamName to first position on the list.
            @Override
            public int compare(FileItem a, FileItem b) {
                if (a.getFieldName().equals(tokenParamName)) {
                    return (-1);
                }
                if (b.getFieldName().equals(tokenParamName)) {
                    return (1);
                }
                return 0;
            }
        });

        for (int i = 0, j = items.size(); i < j; i++) {
            FileItem item = items.get(i);
            if (configuration.isEnableCsrfProtection() && (!items.get(0).getFieldName().equals(tokenParamName)
                    || (item.getFieldName().equals(tokenParamName)
                            && !checkCsrfToken(request, item.getString())))) {
                throw new ConnectorException(Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST,
                        "CSRF Attempt");
            } else if (items.get(0).getFieldName().equals(tokenParamName) && items.size() == 1) {
                //No file was provided. Only the CSRF token
                throw new ConnectorException(Constants.Errors.CKFINDER_CONNECTOR_ERROR_CUSTOM_ERROR,
                        "No file provided in the request.");
            } else if (!item.isFormField()) {
                String path = configuration.getTypes().get(this.type).getPath() + this.currentFolder;
                this.fileName = getFileItemName(item);

                try {
                    if (validateUploadItem(item, path)) {
                        return saveTemporaryFile(path, item);
                    }
                } finally {
                    item.delete();
                }
            }
        }
        return false;
    } catch (InvalidContentTypeException e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT;
        return false;
    } catch (IOFileUploadException e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
        return false;
    } catch (SizeLimitExceededException e) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
        return false;
    } catch (FileSizeLimitExceededException e) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
        return false;
    } catch (ConnectorException e) {
        this.errorCode = e.getErrorCode();
        if (this.errorCode == Constants.Errors.CKFINDER_CONNECTOR_ERROR_CUSTOM_ERROR) {
            this.customErrorMsg = e.getErrorMsg();
        }
        return false;
    } catch (Exception e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
        return false;
    }

}