Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:com.runwaysdk.controller.ServletDispatcher.java

/**
 * @param req//  ww w. j a  va2 s  .c  om
 * @param annotation
 * @return
 * @throws FileUploadException
 */
@SuppressWarnings("unchecked")
private Map<String, Parameter> getParameters(HttpServletRequest req, ActionParameters annotation) {
    String mojaxObject = req.getParameter(MOJAX_OBJECT);

    if (mojaxObject != null) {
        try {
            return this.getParameterMap(new MojaxObjectParser(annotation, mojaxObject).getMap());
        } catch (JSONException e) {
            throw new ClientException(e);
        }
    } else {
        if (ServletFileUpload.isMultipartContent(req)) {
            Map<String, Parameter> parameters = new HashMap<String, Parameter>();

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

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

            try {
                List<FileItem> items = upload.parseRequest(req);

                for (FileItem item : items) {
                    String fieldName = item.getFieldName();

                    if (item.isFormField()) {
                        String fieldValue = item.getString();

                        if (!parameters.containsKey(fieldName)) {
                            parameters.put(fieldName, new BasicParameter());
                        }

                        ((BasicParameter) parameters.get(fieldName)).add(fieldValue);
                    } else if (!item.isFormField() && item.getSize() > 0) {
                        parameters.put(fieldName, new MultipartFileParameter(item));
                    }
                }

                return parameters;
            } catch (FileUploadException e) {
                // Change the exception type
                throw new RuntimeException(e);
            }
        } else {
            return this.getParameterMap(req.getParameterMap());
        }
    }
}

From source file:azkaban.webapp.servlet.LoginAbstractAzkabanServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Session session = getSessionFromRequest(req);

    logRequest(req, session);/* w w  w. ja  va  2s.c  o  m*/

    // Handle Multipart differently from other post messages
    if (ServletFileUpload.isMultipartContent(req)) {
        Map<String, Object> params = multipartParser.parseMultipart(req);
        if (session == null) {
            // See if the session id is properly set.
            if (params.containsKey("session.id")) {
                String sessionId = (String) params.get("session.id");
                String ip = req.getRemoteAddr();

                session = getSessionFromSessionId(sessionId, ip);
                if (session != null) {
                    handleMultiformPost(req, resp, params, session);
                    return;
                }
            }

            // if there's no valid session, see if it's a one time session.
            if (!params.containsKey("username") || !params.containsKey("password")) {
                writeResponse(resp, "Login error. Need username and password");
                return;
            }

            String username = (String) params.get("username");
            String password = (String) params.get("password");
            String ip = req.getRemoteAddr();

            try {
                session = createSession(username, password, ip);
            } catch (UserManagerException e) {
                writeResponse(resp, "Login error: " + e.getMessage());
                return;
            }
        }

        handleMultiformPost(req, resp, params, session);
    } else if (hasParam(req, "action") && getParam(req, "action").equals("login")) {
        HashMap<String, Object> obj = new HashMap<String, Object>();
        handleAjaxLoginAction(req, resp, obj);
        this.writeJSON(resp, obj);
    } else if (session == null) {
        if (hasParam(req, "username") && hasParam(req, "password")) {
            // If it's a post command with curl, we create a temporary session
            try {
                session = createSession(req);
            } catch (UserManagerException e) {
                writeResponse(resp, "Login error: " + e.getMessage());
            }

            handlePost(req, resp, session);
        } else {
            // There are no valid sessions and temporary logins, no we either pass
            // back a message or redirect.
            if (isAjaxCall(req)) {
                String response = createJsonResponse("error", "Invalid Session. Need to re-login", "login",
                        null);
                writeResponse(resp, response);
            } else {
                handleLogin(req, resp, "Enter username and password");
            }
        }
    } else {
        handlePost(req, resp, session);
    }
}

From source file:com.ekitap.controller.AdminUrunController.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w w .j a  v  a  2s .co 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");
    response.setCharacterEncoding("ISO-8859-9");
    String adminPath = request.getServletPath();
    String url = null;
    String adi = request.getParameter("adi");
    ArrayList<KategoriBean> liste = null;
    ArrayList<YazarBean> yazarListe = null;
    ArrayList<YayinEviBean> yayinEviListe = null;
    ArrayList<UrunlerBean> urunListe = null;
    ArrayList<UrunlerBean> urunGuncelListe = null;
    ArrayList<UrunResimBean> liste_resim = null;
    ArrayList liste_fiyat = null;
    ArrayList<OzellikBean> liste_ozellik;
    ArrayList<UrunOzellikBean> liste_urun_ozellik;
    ArrayList<StokBean> liste_stok;
    int sayfa = 1;
    int sayfaSayisi = (int) UrunlerDAO.sayfaSayisi(UrunlerDAO.getUrunAdet(), sayfaBasinaUrun);
    if (adminPath.equals("/urungoster")) {
        System.out.println(request.getParameter("id"));
        try {
            sayfa = Integer.parseInt(request.getParameter("id"));
            if (sayfa <= 0 || sayfa > sayfaSayisi) {
                sayfa = 1;
            }
        } catch (Exception e) {
            sayfa = 1;
        }

        int baslangicSayisi = (sayfa - 1) * sayfaBasinaUrun;
        urunListe = UrunlerDAO.getUrunListele(baslangicSayisi, sayfaBasinaUrun);
        if (urunListe != null) {
            request.setAttribute("urunliste", urunListe);
            request.setAttribute("sayfasayisi", sayfaSayisi);
        }

        url = "/WEB-INF/view/adminpanel" + adminPath + ".jsp";
        request.getRequestDispatcher(url).forward(request, response);
    } else if (adminPath.equals("/urunekle")) {
        if (adi == null || adi.trim().isEmpty()) {
            liste = KategoriDAO.getKategoriListele();
            yazarListe = YazarDAO.getYazarListele();
            yayinEviListe = YayinEviDAO.getYayinEviListele();
            if (liste != null) {
                request.setAttribute("katliste", liste);
            }
            if (yazarListe != null) {
                request.setAttribute("yazarliste", yazarListe);
            }
            if (yayinEviListe != null) {
                request.setAttribute("yayinliste", yayinEviListe);
            }

            url = "/WEB-INF/view/adminpanel" + adminPath + ".jsp";
            request.getRequestDispatcher(url).forward(request, response);
        }
        // rn ekle
        else {
            int urunid;
            try {
                //   System.out.println(request.getParameter("urunID"));
                urunid = Integer.parseInt(request.getParameter("urunID"));
                // System.out.println(urunid);
            } catch (Exception e) {
                urunid = 0;
            }

            //                int yayin = Integer.parseInt(request.getParameter("yayin"));
            //                int yazar = Integer.parseInt(request.getParameter("yazar"));
            int katidd = Integer.parseInt(request.getParameter("katidd"));
            UrunlerBean urunler = new UrunlerBean(0, request.getParameter("adi"), 0, 0, katidd,
                    request.getParameter("aciklama"));
            int urunID = UrunlerDAO.setUrunEkle(urunler, urunid);

            adminPath = "/urunguncelle";
            response.sendRedirect("/urunguncelle?urunID=" + urunID);
            //                url = "/WEB-INF/view/adminpanel" + adminPath + ".jsp";
            //            request.getRequestDispatcher(url).forward(request, response);
        }

    } else if (adminPath.equals("/urunguncelle")) {
        liste = KategoriDAO.getKategoriListele();
        yazarListe = YazarDAO.getYazarListele();
        yayinEviListe = YayinEviDAO.getYayinEviListele();
        String urunid = request.getParameter("urunID");
        liste_resim = UrunlerDAO.getResimListele(Integer.parseInt(urunid));
        liste_fiyat = UrunlerDAO.getUrunFiyat(Integer.parseInt(urunid));
        liste_ozellik = UrunlerDAO.getOzellik();
        liste_urun_ozellik = UrunlerDAO.getUrunOzellik(Integer.parseInt(urunid));
        liste_stok = UrunlerDAO.getUrunStok(Integer.parseInt(urunid));
        if (urunid == null || urunid.trim().isEmpty()) {
            return;
        }
        urunGuncelListe = UrunlerDAO.getUrunGuncelBilgi(urunid);
        if (liste != null) {
            request.setAttribute("katliste", liste);
        }
        if (yazarListe != null) {
            request.setAttribute("yazarliste", yazarListe);
        }
        if (yayinEviListe != null) {
            request.setAttribute("yayinliste", yayinEviListe);
        }
        if (urunGuncelListe != null) {
            request.setAttribute("guncelurun", urunGuncelListe);
        }
        if (liste_resim != null) {
            request.setAttribute("resimliste", liste_resim);
        }
        if (liste_fiyat != null) {
            request.setAttribute("fiyatliste", liste_fiyat);
        }
        if (liste_ozellik != null) {
            request.setAttribute("ozellikliste", liste_ozellik);
        }
        if (liste_urun_ozellik != null) {
            request.setAttribute("urunozellikliste", liste_urun_ozellik);
        }
        if (liste_stok != null) {
            request.setAttribute("stokliste", liste_stok);
        }
        url = "/WEB-INF/view/adminpanel" + adminPath + ".jsp";
        request.getRequestDispatcher(url).forward(request, response);
    } else if (adminPath.equals("/yazarekle")) {
        System.out.println(request.getParameter("yazaradi"));
        //burdan cek
        YazarBean yazar = new YazarBean(0, request.getParameter("yazarad"), request.getParameter("yazarsoyad"),
                request.getParameter("yazarmail"));
        //  System.out.println(request.getParameter("yazarad")+request.getParameter("yazarsoyad")+request.getParameter("yazarmail"));
        YazarDAO.setYazarEkle(yazar);
    } else if (adminPath.equals("/yayineviekle")) {
        YayinEviBean yayinEvi = new YayinEviBean(0, request.getParameter("yayinad"),
                request.getParameter("yayinadres"), request.getParameter("yayinmail"));
        YayinEviDAO.setYayinEviEkle(yayinEvi);

    } else if (adminPath.equals("/resimekle")) {
        int urunID = Integer.parseInt(request.getParameter("urunID"));

        System.out.println(urunID);
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String name = null;
        // process only if it is multipart content
        if (isMultipart) {
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                // Parse the request
                List<FileItem> multiparts = upload.parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        liste_resim = UrunlerDAO.resimKaydet(urunID, name);
        request.setAttribute("resimliste", liste_resim);
        url = "/WEB-INF/view/adminpanel" + adminPath + ".jsp";
        request.getRequestDispatcher(url).forward(request, response);
    } else if (adminPath.equals("/fiyatekle")) {
        float vergiOnce = Float.parseFloat(request.getParameter("vergionce"));
        float vergiSonra = Float.parseFloat(request.getParameter("vergisonra"));
        int urunID = Integer.parseInt(request.getParameter("urunID"));

        UrunlerDAO.setUrunFiyat(urunID, vergiOnce, vergiSonra);
    } else if (adminPath.equals("/ozellikekle")) {
        String urunid = request.getParameter("urunID");
        if (urunid == null || urunid.trim().isEmpty()) {
            return;
        }
        int i = 1;
        ArrayList<UrunOzellikBean> a = new ArrayList();
        UrunOzellikBean urunOzellik;
        while (request.getParameter("field" + Integer.toString(i)) != null) {
            urunOzellik = new UrunOzellikBean(Integer.parseInt(urunid),
                    Integer.parseInt(request.getParameter("ofield" + Integer.toString(i))),
                    request.getParameter("field" + Integer.toString(i)));
            a.add(urunOzellik);

            i++;
        }
        UrunlerDAO.setUrunOzellik(a);
        //            for (UrunOzellikBean object : a) {
        //                System.out.println(object.getDeger()+object.getOzellikID());
        //            }

    } else if (adminPath.equals("/stokekle")) {
        String urunid = request.getParameter("urunID");
        if (urunid == null || urunid.trim().isEmpty()) {
            return;
        }
        try {
            int stok = Integer.parseInt(request.getParameter("stok"));

            UrunlerDAO.setUrunStok(new StokBean(0, Integer.parseInt(urunid), stok));
        } catch (Exception e) {
        }
    }
}

From source file:com.ephesoft.gxt.admin.server.ImportTableUploadServlet.java

/**
 * This API is used to process attach file.
 * //from   ww  w  . jav  a 2s .  c  o  m
 * @param req {@link HttpServletRequest}.
 * @param resp {@link HttpServletResponse}.
 * @param bSService {@link BatchSchemaService}.
 * @return
 */
private void attachFile(final HttpServletRequest req, final HttpServletResponse resp,
        final BatchSchemaService bSService) throws IOException {

    final PrintWriter printWriter = resp.getWriter();
    String tempFile = null;

    if (ServletFileUpload.isMultipartContent(req)) {
        final String testTableDirPath = EphesoftStringUtil.concatenate(bSService.getBaseFolderLocation(),
                File.separator, req.getParameter("batchClassIdentifier"), File.separator,
                bSService.getTestTableFolderName());
        final ServletFileUpload upload = getUploadedFile(testTableDirPath);

        tempFile = processUploadedFile(upload, req, printWriter, testTableDirPath);
        printWriter.write(tempFile);

    } else {
        log.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }

    printWriter.flush();
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.filterConfiguration.FilterConfigurationImportHandler.java

/**
 * Upload the properties file to FilterConfigurations/import folder
 * //w  w w . jav a 2s.  co  m
 * @param request
 */
private File uploadFile(HttpServletRequest request) {
    File f = null;
    try {
        String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight"
                + File.separator + "FilterConfigurations" + File.separator + "import";
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = (FileItem) items.get(i);
                if (!item.isFormField()) {
                    String filePath = item.getName();
                    if (filePath.contains(":")) {
                        filePath = filePath.substring(filePath.indexOf(":") + 1);
                    }
                    String originalFilePath = filePath.replace("\\", File.separator).replace("/",
                            File.separator);
                    String fileName = tmpDir + File.separator + originalFilePath;
                    f = new File(fileName);
                    f.getParentFile().mkdirs();
                    item.write(f);
                }
            }
        }
        return f;
    } catch (Exception e) {
        logger.error("File upload failed.", e);
        return null;
    }
}

From source file:com.ephesoft.gxt.admin.server.UploadClassifyExtractFile.java

/**
 * This API is used to process attach file.
 * //  ww w.j  av  a2  s. co m
 * @param req {@link HttpServletRequest}.
 * @param resp {@link HttpServletResponse}.
 * @param bSService {@link BatchSchemaService}.
 * @return
 */
private void attachFile(final HttpServletRequest req, final HttpServletResponse resp,
        final BatchSchemaService bSService) throws IOException {
    final String batchClassIdentifier = req.getParameter(DocumentTypeConstants.BATCH_CLASS_ID_REQ_PARAMETER);

    final PrintWriter printWriter = resp.getWriter();
    String tempFile = null;

    if (ServletFileUpload.isMultipartContent(req)) {
        String testTableDirPath = null;
        if (req.getParameter(DocumentTypeConstants.IS_TEST_CLASSIFICATIONFILE).equalsIgnoreCase("true")) {
            testTableDirPath = EphesoftStringUtil.concatenate(bSService.getBaseFolderLocation(), File.separator,
                    batchClassIdentifier, File.separator, "test-classification");
        } else {
            testTableDirPath = EphesoftStringUtil.concatenate(bSService.getBaseFolderLocation(), File.separator,
                    batchClassIdentifier, File.separator, "test-extraction");
        }
        final ServletFileUpload upload = getUploadedFile(testTableDirPath);

        tempFile = processUploadedFile(upload, req, printWriter, testTableDirPath);
        printWriter.write(tempFile);

    } else {
        log.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }

    printWriter.flush();
}

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

/**
 * Performs an HTTP PUT request// w  w  w.  j a va  2s .  c om
 *
 * @param httpServletRequest  The {@link javax.servlet.http.HttpServletRequest} object passed
 *                            in by the servlet engine representing the
 *                            client request to be proxied
 * @param httpServletResponse The {@link javax.servlet.http.HttpServletResponse} object by which
 *                            we can send a proxied response to the client
 */
@Override
public void doPut(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    ProxyDetails proxyDetails = createProxyDetails(httpServletRequest, httpServletResponse);
    if (!proxyDetails.isValid()) {
        noMappingFound(httpServletRequest, httpServletResponse);
    } else {
        PutMethod putMethodProxyRequest = new PutMethod(proxyDetails.getStringProxyURL());
        setProxyRequestHeaders(proxyDetails, httpServletRequest, putMethodProxyRequest);
        if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
            handleMultipartPost(putMethodProxyRequest, httpServletRequest);
        } else {
            handleEntity(putMethodProxyRequest, httpServletRequest);
        }
        executeProxyRequest(proxyDetails, putMethodProxyRequest, httpServletRequest, httpServletResponse);
    }
}

From source file:it.geosdi.era.server.servlet.HTTPProxy.java

/**
 * Performs an HTTP POST request/* ww w .  ja va 2s.c om*/
 * @param httpServletRequest The {@link HttpServletRequest} object passed
 *                            in by the servlet engine representing the
 *                            client request to be proxied
 * @param httpServletResponse The {@link HttpServletResponse} object by which
 *                             we can send a proxied response to the client 
 */
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    URL url = null;
    String user = null, password = null, method = "GET", post = null;
    int timeout = 0;

    Set entrySet = httpServletRequest.getParameterMap().entrySet();
    Map headers = new HashMap();
    for (Object anEntrySet : entrySet) {
        Map.Entry header = (Map.Entry) anEntrySet;
        String key = (String) header.getKey();
        String value = ((String[]) header.getValue())[0];
        if ("user".equals(key)) {
            user = value;
        } else if ("password".equals(key)) {
            password = value;
        } else if ("timeout".equals(key)) {
            timeout = Integer.parseInt(value);
        } else if ("method".equals(key)) {
            method = value;
        } else if ("post".equals(key)) {
            post = value;
        } else if ("url".equals(key)) {
            url = new URL(value);
        } else {
            headers.put(key, value);
        }
    }

    if (url != null) {
        //           String digest=null;
        //            if (user != null && password!=null) {
        //                digest = "Basic " + new String(Base64.encodeBase64((user+":"+password).getBytes()));
        //            }

        // Create a standard POST request
        PostMethod postMethodProxyRequest = new PostMethod(
                /*this.getProxyURL(httpServletRequest)*/ url.toExternalForm());
        // Forward the request headers
        setProxyRequestHeaders(url, httpServletRequest, postMethodProxyRequest);
        // Check if this is a mulitpart (file upload) POST
        if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
            this.handleMultipartPost(postMethodProxyRequest, httpServletRequest);
        } else {
            this.handleStandardPost(postMethodProxyRequest, httpServletRequest);
        }
        // Execute the proxy request
        this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse, user,
                password);
    }
}

From source file:com.occamlab.te.web.TestServlet.java

public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {//from   w ww . ja va  2 s.c o m
        FileItemFactory ffactory;
        ServletFileUpload upload;
        List /* FileItem */ items = null;
        HashMap<String, String> params = new HashMap<String, String>();
        boolean multipart = ServletFileUpload.isMultipartContent(request);
        if (multipart) {
            ffactory = new DiskFileItemFactory();
            upload = new ServletFileUpload(ffactory);
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                }
            }
        } else {
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                params.put(name, request.getParameter(name));
            }
        }
        HttpSession session = request.getSession();
        ServletOutputStream out = response.getOutputStream();
        String operation = params.get("te-operation");
        if (operation.equals("Test")) {
            TestSession s = new TestSession();
            String user = request.getRemoteUser();
            File logdir = new File(conf.getUsersDir(), user);
            String mode = params.get("mode");
            RuntimeOptions opts = new RuntimeOptions();
            opts.setWorkDir(conf.getWorkDir());
            opts.setLogDir(logdir);
            if (mode.equals("retest")) {
                opts.setMode(Test.RETEST_MODE);
                String sessionid = params.get("session");
                String test = params.get("test");
                if (sessionid == null) {
                    int i = test.indexOf("/");
                    sessionid = i > 0 ? test.substring(0, i) : test;
                }
                opts.setSessionId(sessionid);
                if (test == null) {
                    opts.addTestPath(sessionid);
                } else {
                    opts.addTestPath(test);
                }
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        String profileId = entry.getValue();
                        int i = profileId.indexOf("}");
                        opts.addTestPath(sessionid + "/" + profileId.substring(i + 1));
                    }
                }
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else if (mode.equals("resume")) {
                opts.setMode(Test.RESUME_MODE);
                String sessionid = params.get("session");
                opts.setSessionId(sessionid);
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else {
                opts.setMode(Test.TEST_MODE);
                String sessionid = LogUtils.generateSessionId(logdir);
                s.setSessionId(sessionid);
                String sources = params.get("sources");
                s.setSourcesName(sources);
                SuiteEntry suite = conf.getSuites().get(sources);
                s.setSuiteName(suite.getId());
                //                    String suite = params.get("suite");
                //                    s.setSuiteName(suite);
                String description = params.get("description");
                s.setDescription(description);
                opts.setSessionId(sessionid);
                opts.setSourcesName(sources);
                opts.setSuiteName(suite.getId());
                ArrayList<String> profiles = new ArrayList<String>();
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        profiles.add(entry.getValue());
                        opts.addProfile(entry.getValue());
                    }
                }
                s.setProfiles(profiles);
                s.save(logdir);
            }
            String webdir = conf.getWebDirs().get(s.getSourcesName());
            //                String requestURI = request.getRequestURI();
            //                String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1);
            //                URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null);
            URI contextURI = new URI(request.getScheme(), null, request.getServerName(),
                    request.getServerPort(), request.getRequestURI(), null, null);
            opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString());
            //                URI baseURI = new URL(contextURI.toURL(), webdir).toURI();
            //                String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/";
            //                opts.setBaseURI(base);
            //System.out.println(opts.getSourcesName());
            TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts);
            //System.out.println(indexes.get(opts.getSourcesName()).toString());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            core.setOut(ps);
            core.setWeb(true);
            Thread thread = new Thread(core);
            session.setAttribute("testsession", core);
            thread.start();
            response.setContentType("text/xml");
            out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>");
        } else if (operation.equals("Stop")) {
            response.setContentType("text/xml");
            TECore core = (TECore) session.getAttribute("testsession");
            if (core != null) {
                core.stopThread();
                session.removeAttribute("testsession");
                out.println("<stopped/>");
            } else {
                out.println("<message>Could not retrieve core object</message>");
            }
        } else if (operation.equals("GetStatus")) {
            TECore core = (TECore) session.getAttribute("testsession");
            response.setContentType("text/xml");
            out.print("<status");
            if (core.getFormHtml() != null) {
                out.print(" form=\"true\"");
            }
            if (core.isThreadComplete()) {
                out.print(" complete=\"true\"");
                session.removeAttribute("testsession");
            }
            out.println(">");
            out.print("<![CDATA[");
            //                out.print(core.getOutput());
            out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' '));
            out.println("]]>");
            out.println("</status>");
        } else if (operation.equals("GetForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            String html = core.getFormHtml();
            core.setFormHtml(null);
            response.setContentType("text/html");
            out.print(html);
        } else if (operation.equals("SubmitForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            Document doc = DB.newDocument();
            Element root = doc.createElement("values");
            doc.appendChild(root);
            for (String key : params.keySet()) {
                if (!key.startsWith("te-")) {
                    Element valueElement = doc.createElement("value");
                    valueElement.setAttribute("key", key);
                    valueElement.appendChild(doc.createTextNode(params.get(key)));
                    root.appendChild(valueElement);
                }
            }
            if (multipart) {
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (!item.isFormField() && !item.getName().equals("")) {
                        File uploadedFile = new File(core.getLogDir(),
                                StringUtils.getFilenameFromString(item.getName()));
                        item.write(uploadedFile);
                        Element valueElement = doc.createElement("value");
                        String key = item.getFieldName();
                        valueElement.setAttribute("key", key);
                        if (core.getFormParsers().containsKey(key)) {
                            Element parser = core.getFormParsers().get(key);
                            URL url = uploadedFile.toURI().toURL();
                            Element resp = core.parse(url.openConnection(), parser, doc);
                            Element content = DomUtils.getElementByTagName(resp, "content");
                            if (content != null) {
                                Element child = DomUtils.getChildElement(content);
                                if (child != null) {
                                    valueElement.appendChild(child);
                                }
                            }
                        } else {
                            Element fileEntry = doc.createElementNS(CTL_NS, "file-entry");
                            fileEntry.setAttribute("full-path",
                                    uploadedFile.getAbsolutePath().replace('\\', '/'));
                            fileEntry.setAttribute("media-type", item.getContentType());
                            fileEntry.setAttribute("size", String.valueOf(item.getSize()));
                            valueElement.appendChild(fileEntry);
                        }
                        root.appendChild(valueElement);
                    }
                }
            }
            core.setFormResults(doc);
            response.setContentType("text/html");
            out.println("<html>");
            out.println("<head><title>Form Submitted</title></head>");
            out.print("<body onload=\"window.parent.update()\"></body>");
            out.println("</html>");
        }
    } catch (Throwable t) {
        throw new ServletException(t);
    }
}

From source file:com.ephesoft.gxt.admin.server.ImportDocumentTypeUploadServlet.java

/**
 * This API is used to process attach file.
 * /*from www.  ja va 2s  .  c o m*/
 * @param req {@link HttpServletRequest}.
 * @param resp {@link HttpServletResponse}.
 * @param bSService {@link BatchSchemaService}.
 * @return
 */
private void attachFile(final HttpServletRequest req, final HttpServletResponse resp,
        final BatchSchemaService bSService) throws IOException {

    final PrintWriter printWriter = resp.getWriter();
    String tempZipFile = null;

    if (ServletFileUpload.isMultipartContent(req)) {
        final String serDirPath = bSService.getBatchExportFolderLocation();
        final ServletFileUpload upload = getUploadedFile(serDirPath);

        tempZipFile = processUploadedFile(upload, req, printWriter, serDirPath);
        printWriter.write(tempZipFile);

    } else {
        log.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }

    printWriter.flush();
}