Example usage for javax.servlet.http HttpServletRequest getServletContext

List of usage examples for javax.servlet.http HttpServletRequest getServletContext

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Gets the servlet context to which this ServletRequest was last dispatched.

Usage

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Registration18_WhiteboardServletByNameOnly() throws Exception {
    String expected = "a";
    final String servletName = "hello_servlet";
    Servlet namedServlet = new BaseServlet(expected);
    Servlet targetServlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override/*from  w ww.ja  va2  s .  co m*/
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            request.getServletContext().getNamedDispatcher(servletName).forward(request, response);
        }

    };

    Hashtable<String, String> props = new Hashtable<String, String>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, servletName);
    registrations.add(getBundleContext().registerService(Servlet.class, namedServlet, props));

    props = new Hashtable<String, String>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/s");
    registrations.add(getBundleContext().registerService(Servlet.class, targetServlet, props));

    String actual = requestAdvisor.request("s");
    Assert.assertEquals(expected, actual);
}

From source file:sos.Sos.java

/**allows to query a specific observation using an identifier returned by the service as response to an InsertObservation operation. 
 * //w  ww. j  av a 2s . c om
 * @param request Http Servlet Request
 * @param response Http Servlet Response
 * @param out PrintWriter for Http Servlet Response
 * @param snannySostServerConfig the sos server configuration
 * @throws SnannySostServerException 
 */
private void getObservationById(HttpServletRequest request, HttpServletResponse response, PrintWriter out,
        SnannySostServerConfig snannySostServerConfig) throws SnannySostServerException {
    String uuid = getSosObservationUuid(request);
    SOSFORMAT sosresponseformat = getResponseFormatParameter(request);
    if (snannySostServerConfig.isCouchbase()) {
        try {
            JsonDocument jsonDocument = CouchbaseManager.getObservationBucket().get(uuid);

            if (jsonDocument == null) {
                throw new SnannySostServerException(SnannySostServerMessages.ERROR_NO_UUID_RECORD_1of2 + uuid
                        + SnannySostServerMessages.ERROR_NO_UUID_RECORD_2of2, Status.NOT_FOUND);
            }
            response.setContentType(SosFormat.getContentType(sosresponseformat));
            switch (sosresponseformat) {
            case JSON:
                if (snannySostServerConfig.isJsonObject()) {
                    out.append(new JsonTranscoder().jsonObjectToString(
                            jsonDocument.content().getObject(SnannySostServerConfig.FilejsonField)));
                } else {
                    out.append(new JsonArrayTranscoder().jsonArrayToString(
                            jsonDocument.content().getArray(SnannySostServerConfig.FilejsonField)));
                }
                break;

            case XML:
                if (snannySostServerConfig.isJsonObject()) {
                    JSONObject jSONObject = new JSONObject(
                            StringEscapeUtils.unescapeXml(new JsonTranscoder().jsonObjectToString(
                                    jsonDocument.content().getObject(SnannySostServerConfig.FilejsonField))));
                    out.append(JSONML.toString(jSONObject));
                } else {
                    JSONArray jsonArray = new JSONArray(
                            StringEscapeUtils.unescapeXml(new JsonArrayTranscoder().jsonArrayToString(
                                    jsonDocument.content().getArray(SnannySostServerConfig.FilejsonField))));
                    out.append(JSONML.toString(jsonArray));
                }
                break;
            }

        } catch (Exception ex) {
            throw new SnannySostServerException(
                    SnannySostServerMessages.ERROR_COUCHBASE_ERROR + ex.getMessage(),
                    Status.SERVICE_UNAVAILABLE);
        }
    } else {
        File uuidFile = SnannySostServerConfig.singleton(request.getServletContext()).getOemFile(uuid);
        try {
            byte[] encoded = Files.readAllBytes(Paths.get(uuidFile.toURI()));
            String uuidFileContent = new String(encoded, snannySostServerConfig.getCharset());
            response.setContentType(SosFormat.getContentType(sosresponseformat));
            switch (sosresponseformat) {
            case JSON:
                if (snannySostServerConfig.isJsonObject()) {
                    JSONObject jsonObject = JSONML.toJSONObject(uuidFileContent);
                    out.append(jsonObject.toString());
                } else {
                    JSONArray jsonArray = JSONML.toJSONArray(uuidFileContent);
                    out.append(jsonArray.toString());
                }

                break;

            case XML:
                out.append(uuidFileContent);
                break;
            }
        } catch (Exception ex) {
            throw new SnannySostServerException(SnannySostServerMessages.ERROR_describeSensor,
                    Status.SERVICE_UNAVAILABLE);
        }
    }
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_ServletContextHelper12() throws Exception {
    String expected1 = "a,b,1";

    BundleContext bundleContext = getBundleContext();
    Bundle bundle = bundleContext.getBundle();

    ServletContextHelper servletContextHelper = new ServletContextHelper(bundle) {
    };/*from  w  ww. j  a  va 2 s  .c o m*/
    Servlet s1 = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            StringBuilder builder = new StringBuilder();
            builder.append(request.getServletContext().getInitParameter("a")).append(',');
            builder.append(request.getServletContext().getInitParameter("b")).append(',');
            builder.append(request.getServletContext().getInitParameter("c"));
            response.getWriter().print(builder.toString());
        }
    };

    Collection<ServiceRegistration<?>> registrations = new ArrayList<ServiceRegistration<?>>();
    try {
        Dictionary<String, Object> contextProps = new Hashtable<String, Object>();
        contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME, "a");
        contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH, "/a");
        contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_INIT_PARAM_PREFIX + "a", "a");
        contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_INIT_PARAM_PREFIX + "b", "b");
        contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_INIT_PARAM_PREFIX + "c",
                new Integer(1));
        registrations.add(
                bundleContext.registerService(ServletContextHelper.class, servletContextHelper, contextProps));

        Dictionary<String, String> servletProps1 = new Hashtable<String, String>();
        servletProps1.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S1");
        servletProps1.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/s");
        servletProps1.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT,
                "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=a)");
        registrations.add(bundleContext.registerService(Servlet.class, s1, servletProps1));

        String actual = requestAdvisor.request("a/s");

        Assert.assertEquals(expected1, actual);
    } finally {
        for (ServiceRegistration<?> registration : registrations) {
            registration.unregister();
        }
    }
}

From source file:net.community.chest.gitcloud.facade.frontend.git.GitController.java

private void serveRequest(RequestMethod method, HttpServletRequest req, HttpServletResponse rsp)
        throws IOException, ServletException {
    if (logger.isDebugEnabled()) {
        logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]");
    }/*from w w  w.j a v  a2  s. c om*/

    if ((loopRetryTimeout > 0L) && (!loopDetected)) {
        long now = System.currentTimeMillis(), diff = now - initTimestamp;
        if ((diff > 0L) && (diff < loopRetryTimeout)) {
            try {
                MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(new ObjectName(
                        "net.community.chest.gitcloud.facade.backend.git:name=BackendRepositoryResolver"));
                if (mbeanInfo != null) {
                    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " detected loop: " + mbeanInfo.getClassName() + "["
                            + mbeanInfo.getDescription() + "]");
                    loopDetected = true;
                }
            } catch (JMException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "]" + " failed " + e.getClass().getSimpleName()
                            + " to detect loop: " + e.getMessage());
                }
            }
        }
    }

    ResolvedRepositoryData repoData = resolveTargetRepository(method, req);
    if (repoData == null) {
        throw ExtendedLogUtils.thrownLogging(logger, Level.WARNING,
                "serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "]",
                new NoSuchElementException("Failed to resolve repository"));
    }

    String username = authenticate(req);
    // TODO check if the user is allowed to access the repository via the resolve operation (push/pull) if at all (e.g., private repo)
    logger.info("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString() + "] user="
            + username);

    /*
     * NOTE: this feature requires enabling cross-context forwarding.
     * In Tomcat, the 'crossContext' attribute in 'Context' element of
     * 'TOMCAT_HOME\conf\context.xml' must be set to true, to enable cross-context 
     */
    if (loopDetected) {
        // TODO see if can find a more efficient way than splitting and re-constructing
        URI uri = repoData.getRepoLocation();
        ServletContext curContext = req.getServletContext();
        String urlPath = uri.getPath(), urlQuery = uri.getQuery();
        String[] comps = StringUtils.split(urlPath, '/');
        String appName = comps[0];
        ServletContext loopContext = Validate.notNull(curContext.getContext("/" + appName),
                "No cross-context for %s", appName);
        // build the relative path in the re-directed context
        StringBuilder sb = new StringBuilder(
                urlPath.length() + 1 + (StringUtils.isEmpty(urlQuery) ? 0 : urlQuery.length()));
        for (int index = 1; index < comps.length; index++) {
            sb.append('/').append(comps[index]);
        }
        if (!StringUtils.isEmpty(urlQuery)) {
            sb.append('?').append(urlQuery);
        }

        String redirectPath = sb.toString();
        RequestDispatcher dispatcher = Validate.notNull(loopContext.getRequestDispatcher(redirectPath),
                "No dispatcher for %s", redirectPath);
        dispatcher.forward(req, rsp);
        if (logger.isDebugEnabled()) {
            logger.debug("serveRequest(" + method + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                    + "]" + " forwarded to " + loopContext.getContextPath() + "/" + redirectPath);
        }
    } else {
        executeRemoteRequest(method, repoData.getRepoLocation(), req, rsp);
    }
}

From source file:de.appsolve.padelcampus.admin.controller.general.AdminGeneralDesignController.java

@RequestMapping(method = POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ModelAndView postIndex(HttpServletRequest request,
        @RequestParam("backgroundImage") MultipartFile backgroundImage,
        @RequestParam(value = "backgroundImageRepeat", required = false, defaultValue = "false") Boolean backgroundImageRepeat,
        @RequestParam(value = "backgroundSizeCover", required = false, defaultValue = "false") Boolean backgroundSizeCover,
        @RequestParam(value = "loaderOpacity", required = false, defaultValue = "false") Boolean loaderOpacity,
        @RequestParam("companyLogo") MultipartFile companyLogo,
        @RequestParam("touchIcon") MultipartFile touchIcon) throws Exception {
    List<CssAttribute> atts = htmlResourceUtil.getCssAttributes();
    for (CssAttribute att : atts) {
        switch (att.getName()) {
        case "backgroundImage":
            if (!backgroundImage.isEmpty()) {
                StringBuilder sb = new StringBuilder("url(data:");
                sb.append(backgroundImage.getContentType());
                sb.append(";base64,");
                sb.append(Base64.encodeBase64String(backgroundImage.getBytes()));
                sb.append(")");
                att.setCssValue(sb.toString());
            }//from   w  ww  . ja va2s. c om
            break;
        case "backgroundRepeat":
            if (backgroundImageRepeat) {
                att.setCssValue("repeat");
            } else {
                att.setCssValue("no-repeat");
            }
            break;
        case "backgroundSize":
            if (backgroundSizeCover) {
                att.setCssValue("cover");
            } else {
                att.setCssValue("inherit");
            }
            break;
        case "loaderOpacity":
            if (loaderOpacity) {
                att.setCssValue("@loaderOpacity: 1");
            } else {
                att.setCssValue("@loaderOpacity: 0");
            }
            break;
        default:
            att.setCssValue(request.getParameter(att.getName() + ""));
        }
        cssAttributeDAO.saveOrUpdate(att);
    }
    Customer customer = (Customer) sessionUtil.getCustomer(request);
    if (!companyLogo.isEmpty()) {

        //delete old picture from FS if it exists. will be removed from DB automatically due to orphanRemoval=true
        deleteImage(customer.getCompanyLogo());
        customer.setCompanyLogo(null);
        customerDAO.saveOrUpdate(customer);

        Image newImage = imageUtil.saveImage(companyLogo.getContentType(), companyLogo.getBytes(),
                ImageCategory.companyIcon);
        customer.setCompanyLogo(newImage);
        customer = customerDAO.saveOrUpdate(customer);
        sessionUtil.setCustomer(request, customer);
    }
    if (!touchIcon.isEmpty()) {
        //delete old picture from FS
        deleteImage(customer.getTouchIcon());
        customer.setTouchIcon(null);
        customerDAO.saveOrUpdate(customer);

        Image image = imageUtil.saveImage(touchIcon.getContentType(), touchIcon.getBytes(),
                Constants.TOUCH_ICON_WIDTH, Constants.TOUCH_ICON_HEIGHT, ImageCategory.touchIcon);
        customer.setTouchIcon(image);
        customer = customerDAO.saveOrUpdate(customer);
        sessionUtil.setCustomer(request, customer);
    }

    htmlResourceUtil.updateCss(request.getServletContext(), customer);
    return getIndexView(atts);
}

From source file:controller.StudentController.java

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addorchange(HttpServletRequest request) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    // int mssv = Integer.parseInt(request.getParameter("mssv"));
    // String tensv = request.getParameter("tensv");
    // String ngaysinh = request.getParameter("ngaysinh");
    // String ngaydi = request.getParameter("ngaydi");
    // String que = request.getParameter("que");
    // String lop = request.getParameter("lop");
    // String khoa = request.getParameter("khoa");
    // int sdt = Integer.parseInt(request.getParameter("sdt"));
    // int maphong = Integer.parseInt(request.getParameter("roomnum"));
    // int makhu = Integer.parseInt(request.getParameter("roomregion"));

    int mssv = 0;
    String tensv = null;//from  w  w  w .j  av  a  2  s.co  m
    String ngaysinh = null;
    String ngaydi = null;
    String que = null;
    String lop = null;
    String khoa = null;
    int sdt = 0;
    int maphong = 0;
    int makhu = 0;
    FileItem f = null;
    String fName = null;
    try {
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.getFieldName().equals("mssv")) {
                mssv = Integer.parseInt(item.getString());
            }

            if (item.getFieldName().equals("tensv")) {
                tensv = item.getString();
            }
            if (item.getFieldName().equals("ngaysinh")) {
                ngaysinh = item.getString();
            }
            if (item.getFieldName().equals("ngaydi")) {
                ngaydi = item.getString();
            }
            if (item.getFieldName().equals("que")) {
                que = item.getString();
            }
            if (item.getFieldName().equals("lop")) {
                lop = item.getString();
            }
            if (item.getFieldName().equals("khoa")) {
                khoa = item.getString();
            }
            if (item.getFieldName().equals("sdt")) {
                sdt = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("roomnum")) {
                maphong = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("roomregion")) {
                makhu = Integer.parseInt(item.getString());
            }

            if (!item.isFormField()) {
                f = item;
                fName = new File(item.getName()).getName();

            }
        }

    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    RoomRegion region = new RoomRegion(makhu, "");
    Room room = new Room(maphong, region, 0, 0, null, null);
    if (room.checkRoom()) {
        Student student = new Student(mssv, tensv, ngaysinh, que, lop, khoa, room, sdt, ngaydi, fName);
        request.setAttribute("roomnum", new Room().roomList());
        request.setAttribute("roomregion", new RoomRegion().regionList());
        try {
            if (student.add() >= 3) {
                String path = request.getServletContext().getRealPath("/");
                String UPLOAD_DIRECTORY = path + "/static/uploads";
                File dir = new File(UPLOAD_DIRECTORY);
                dir.mkdirs();
                File file = new File(dir.getAbsolutePath() + System.getProperty("file.separator") + fName);

                f.write(file);
                System.out.println(file.getPath());
                request.setAttribute("message", "Thm thnh cng!");
            } else {
                request.setAttribute("message", "Khng thm c, Sinh vin ny  tn ti!");
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        request.setAttribute("message", "Phng ny hin  y!");
    }
    request.setAttribute("id", "add");
    return SVManager(request);
}

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);//  w w w . jav a2 s. co 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:servlets.NewRestaurant.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  w  w. j a v  a  2  s.  c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //Controlliamo che i parametri siano specificati e corretti e se si procediamo.
    if (request.getParameter("nome") != null && request.getParameter("descrizione") != null
            && request.getParameter("cap") != null && request.getParameter("citta") != null
            && request.getParameter("stato") != null) {

        try {
            //Procediamo a salvare le informazioni
            RestaurantBean rest = new RestaurantBean();

            rest.setName(request.getParameter("nome"));
            rest.setDescription(request.getParameter("descrizione"));
            rest.setWeb_site_url(request.getParameter("URL_sito"));
            rest.setTelephone(request.getParameter("telefono"));
            rest.setMail(request.getParameter("email"));
            rest.setAddress(request.getParameter("indirizzo"));
            rest.setCap(request.getParameter("cap").isEmpty() ? 0 : parseInt(request.getParameter("cap")));
            rest.setCity(request.getParameter("citta"));
            rest.setId_country(Integer.valueOf(request.getParameter("stato")));
            rest.setId_price_range(Integer.valueOf(request.getParameter("pricerange")));
            rest.setGlobal_value(0);
            rest.setN_visits(0);
            String[] checkedCuisineIds = request.getParameterValues("cuisine");
            String[] checkedOpeningHoursIds = request.getParameterValues("openinghour");

            //Dobbiamo ottenere latitudine e longitudine
            GeoCoder geo = new GeoCoder();
            GeocodeResponse geoResp = geo.getLocation(rest.getAddress(), rest.getCity(),
                    String.valueOf(rest.getCap()));
            try {
                rest.setLatitude(geoResp.getResults().get(0).getGeometry().getLocation().getLat());
                rest.setLongitude(geoResp.getResults().get(0).getGeometry().getLocation().getLng());
            }
            //valori non validi
            catch (Exception e) {
                RequestDispatcher rd = request.getRequestDispatcher("/general_error_page.jsp");
                rd.forward(request, response);
            }
            //Cerchiamo l'id dell'utente che sta creando il ristorante
            HttpSession session = request.getSession(false);
            UserBean userLogged = (UserBean) session.getAttribute("user");
            rest.setId_creator(userLogged.getId());
            rest.setId_owner(userLogged.getId());

            //Abbiamo salvato tutto nel bean, ora dobbiamo inviare il bean al DAO e salvare le modifiche al database
            RestaurantDAO restDAO = new RestaurantDAO();
            int restID = restDAO.addRestaurant(rest);

            //Ora dobbiamo salvare le relazioni per cuisineType e openinghour 
            restDAO.addRestCuisine(restID, checkedCuisineIds);
            restDAO.addRestOpeningHours(restID, checkedOpeningHoursIds);

            //Tutto  andato a buon fine, possiamo dunque salvare le foto in locale e apportare modifiche nel database
            //Ottengo la COllection di tutte le Parts
            Collection<Part> fileParts = request.getParts();
            //Ora devo filtrarla, in modo da avere solo quelle riguardanti le foto
            CollectionUtils.filter(fileParts, new org.apache.commons.collections4.Predicate<Part>() {
                @Override
                public boolean evaluate(Part o) {
                    return o.getName().equals("foto");
                }
            });
            int i = 0;
            //Per ogni foto salvo in db e locale.
            for (Part part : fileParts) {
                PhotoBean foto = new PhotoBean();
                foto.setName(String.valueOf(restID) + "-" + i + ".jpg");
                foto.setDescription("Foto ristorante");
                foto.setId_restaurant(restID);
                foto.setId_user(userLogged.getId());

                // (2) create a java timestamp object that represents the current time (i.e., a "current timestamp")
                Calendar calendar = Calendar.getInstance();
                foto.setDate(new java.sql.Timestamp(calendar.getTime().getTime()));

                //Inseriamo la foto nel db
                PhotoDAO photoDao = new PhotoDAO();
                photoDao.addPhoto(foto);

                //Salviamo la foto in locale
                // gets absolute path of the web application
                String appPath = request.getServletContext().getRealPath("");
                // constructs path of the directory to save uploaded file
                String savePath = appPath + File.separator + SAVE_DIR;

                // creates the save directory if it does not exists
                File fileSaveDir = new File(savePath);
                if (!fileSaveDir.exists()) {
                    fileSaveDir.mkdir();
                }

                // Part part = request.getPart("foto");
                String fileName = String.valueOf(restID) + "-" + i + ".jpg";
                // refines the fileName in case it is an absolute path
                fileName = new File(fileName).getName();
                part.write(savePath + File.separator + fileName);
                Logger.getLogger(NewRestaurant.class.getName()).log(Level.SEVERE,
                        savePath + File.separator + fileName);

                //Incremento contatore numero foto
                i++;
            }
            //Fine salvataggio foto
            //Dobbiamo aggiornare l'utente se non era gi ristoratore, ora che ha messo un ristorante!
            if (userLogged.getType() == 0) {
                UserDAO userDAO = new UserDAO();
                int affectedRows = userDAO.upgradeUser(userLogged.getId());
                if (affectedRows == 0) {
                    throw new SQLException("Errore aggiornamento utente, no rows affected.");
                } else {
                    userLogged.setType(1);
                    session.setAttribute("user", userLogged);
                }
            }

            request.setAttribute("formValid", "The restaurant " + rest.getName() + " has been create ");
            RequestDispatcher rd = request.getRequestDispatcher("/createdRestaurant.jsp");
            rd.forward(request, response);

        } catch (SQLException ex) {
            Logger.getLogger(NewRestaurant.class.getName()).log(Level.SEVERE, null, ex);
        }

    } //Errore, non tutti i parametri necessari sono stati specificati.
    else {
        RequestDispatcher rd = request.getRequestDispatcher("/general_error_page.jsp");
        rd.forward(request, response);
    }

}

From source file:com.rr.wabshs.ui.calendar.calendarController.java

/**
 * The '/ical-events' GET request will create the iCal .ics file to be uploaded to a calendar
 * @param session//from w ww .ja  v  a  2s.com
 * @param response
 * @return 
 */
@RequestMapping(value = "/ical-events", method = RequestMethod.GET)
public ModelAndView getEventsForIcal(HttpServletRequest request, HttpSession session,
        HttpServletResponse response) throws Exception {

    /* List Calender Events */
    List<calendarEvents> calendarEvents = calendarManager.getPublicCalendarEvents(programId);

    if (calendarEvents != null && calendarEvents.size() > 0) {

        fileSystem dir = new fileSystem();
        dir.setDir(registryName, "");

        String fileName = "ical-nyopce-events.ics";

        File newFile = new File(dir.getDir() + fileName);

        /* Create the empty file in the correct location */
        try {

            if (newFile.exists()) {
                newFile.delete();
                newFile.createNewFile();
            } else {
                newFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        /* Read in the file */
        FileInputStream fileInput = null;
        File file = new File(dir.getDir() + fileName);
        fileInput = new FileInputStream(file);

        FileWriter fw = null;

        try {
            fw = new FileWriter(file, true);
        } catch (IOException ex) {
            Logger.getLogger(exportManager.class.getName()).log(Level.SEVERE, null, ex);
        }

        SimpleDateFormat iCaldateFormat = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat iCalTimeFormat = new SimpleDateFormat("hh:mm a");
        SimpleDateFormat iCalTimeFormatToTime = new SimpleDateFormat("HHmmss");

        StringBuilder iCalRow = new StringBuilder();
        iCalRow.append("BEGIN:VCALENDAR");
        iCalRow.append("\r\n");
        iCalRow.append("VERSION:2.0");
        iCalRow.append("\r\n");
        iCalRow.append("PRODID:-//NYOPCE - ECPv4.0.4//NONSGML v1.0//EN");
        iCalRow.append("\r\n");
        iCalRow.append("CALSCALE:GREGORIAN");
        iCalRow.append("\r\n");
        iCalRow.append("METHOD:PUBLISH");
        iCalRow.append("\r\n");
        iCalRow.append("X-WR-CALNAME:NYOPCE");
        iCalRow.append("\r\n");
        iCalRow.append("X-ORIGINAL-URL:http://nyopce.wpengine.com");
        iCalRow.append("\r\n");
        iCalRow.append("X-WR-CALDESC:Events for NYOPCE");
        iCalRow.append("\r\n");

        for (calendarEvents event : calendarEvents) {

            Date startTime = iCalTimeFormat
                    .parse(event.getEventStartTime().replace("am", " AM").replace("pm", " PM"));
            Date endTime = iCalTimeFormat
                    .parse(event.getEventEndTime().replace("am", " AM").replace("pm", " PM"));

            iCalRow.append("BEGIN:VEVENT");
            iCalRow.append("\r\n");
            iCalRow.append("DTSTART:").append(iCaldateFormat.format(event.getEventStartDate())).append("T")
                    .append(iCalTimeFormatToTime.format(startTime));
            iCalRow.append("\r\n");
            iCalRow.append("DTEND:").append(iCaldateFormat.format(event.getEventEndDate())).append("T")
                    .append(iCalTimeFormatToTime.format(endTime));
            iCalRow.append("\r\n");
            iCalRow.append("DTSTAMP:").append("20160107T132605");
            iCalRow.append("\r\n");
            iCalRow.append("CREATED:").append(iCaldateFormat.format(event.getDateCreated()));
            iCalRow.append("\r\n");
            iCalRow.append("LAST-MODIFIED:").append(iCaldateFormat.format(event.getDateCreated()));
            iCalRow.append("\r\n");
            iCalRow.append("UID:").append("");
            iCalRow.append("\r\n");
            iCalRow.append("SUMMARY:").append(event.getEventTitle().replace("&", "and"));
            iCalRow.append("\r\n");
            iCalRow.append("DESCRIPTION:").append(event.getEventNotes());
            iCalRow.append("\r\n");
            iCalRow.append("URL:").append("");
            iCalRow.append("\r\n");
            iCalRow.append("LOCATION:").append(event.getEventLocation());
            iCalRow.append("\r\n");
            iCalRow.append("GEO:").append("");
            iCalRow.append("\r\n");
            iCalRow.append("X-APPLE-STRUCTURED-LOCATION;VALUE=URI;X-ADDRESS=").append("");
            iCalRow.append("\r\n");
            iCalRow.append("CATEGORIES:").append(event.getCategoryName());
            iCalRow.append("\r\n");
            iCalRow.append("END:VEVENT");
            iCalRow.append("\r\n");
        }

        iCalRow.append("END:VCALENDAR");

        fw.write(iCalRow.toString());

        fw.close();

        ServletContext context = request.getServletContext();
        String mimeType = context.getMimeType(dir.getDir() + fileName);

        File f = new File(dir.getDir() + fileName);

        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        response.setContentType(mimeType);

        OutputStream outputStream = null;
        InputStream in = null;

        in = new FileInputStream(dir.getDir() + fileName);
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = 0;

        response.setContentLength((int) f.length());
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");

        outputStream = response.getOutputStream();
        while (0 < (bytesRead = in.read(buffer))) {
            outputStream.write(buffer, 0, bytesRead);
        }

        in.close();
        outputStream.close();
    }

    return null;
}

From source file:Commands.AddShoesCommand.java

@Override
public String executeCommand(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String forwardToJsp = "";
    HttpSession session = request.getSession(true);
    ShoesDao sd = new ShoesDao();
    boolean check = true;
    ArrayList<String> addList = new ArrayList<>();
    ArrayList<Shoes> list = new ArrayList<>();
    HashMap<Integer, LinkedList<String>> status = new HashMap<>();
    HashMap<Integer, LinkedList<Integer>> color = new HashMap<>();
    LinkedList<String> s = null;
    LinkedList<Integer> c = null;
    if (session.getAttribute("userLogin") != null && ((User) session.getAttribute("userLogin")).is_Admin()) {
        if (request.getParameter("number") != null) {
            int num = Integer.parseInt(request.getParameter("number"));
            for (int n = 1; n < num; n++) {
                s = new LinkedList<>();
                c = new LinkedList<>();
                boolean check1 = true;
                if (request.getParameter("name-" + n) != null && request.getParameter("brand-" + n) != null
                        && request.getParameter("sport-" + n) != null) {
                    if (request.getParameter("name-" + n).isEmpty()) {
                        session.setAttribute("errorMsg", "The name cannot be empty");
                        return forwardToJsp = "AddShoes.jsp";
                    }//  w  ww.  java2  s .c o m
                    String name = (String) request.getParameter("name-" + n).substring(0, 1).toUpperCase()
                            + request.getParameter("name-" + n).substring(1).toLowerCase();
                    int brand = Integer.parseInt(request.getParameter("brand-" + n));
                    int sport = Integer.parseInt(request.getParameter("sport-" + n));
                    if (request.getParameter("price-" + n).isEmpty()) {
                        s.add("price cannot be empty");
                    }
                    double price = Double.parseDouble(request.getParameter("price-" + n));
                    if (price < 1 || price > 200) {
                        s.add("price range is between 1 to 200");
                    }
                    if (!sd.findShoes(name).isEmpty()) {
                        s.add("The name is repeated");
                    }

                    boolean repeat = false;
                    for (int i = 1; i < 4; i++) {
                        if (request.getParameter("color" + i + "-" + n) != null) {
                            int id = Integer.parseInt(request.getParameter("color" + i + "-" + n));
                            if (c.contains(id)) {
                                repeat = true;
                            }
                            c.add(id);
                        }
                    }
                    if (repeat) {
                        s.add("The color is repeated");
                    }

                    //                        String[] files1 = request.getParameterValues("file1-" + n);
                    //                        String[] files2 = request.getParameterValues("file2-" + n);
                    //                        String[] files3 = request.getParameterValues("file3-" + n);
                    //                        long a=Arrays.stream(files1).filter((String st) -> !st.isEmpty()).count();
                    //                        long b=Arrays.stream(files1).filter((String st) -> !st.isEmpty()).count();
                    //                        long d=Arrays.stream(files1).filter((String st) -> !st.isEmpty()).count();
                    //                        if(a==0 || b==0 || d==0){
                    //                            s.add("Images is not uploaded");
                    //                        }
                    //                        p.add(files1);
                    //                        p.add(files2);
                    //                        p.add(files3);
                    if (!s.isEmpty()) {
                        status.put(n, s);
                    }
                    color.put(n, c);
                    list.add(new Shoes(n, brand, 0, sport, name, price, ""));
                } else {
                    check = false;
                    break;
                }
            }
            ColorDao cd = new ColorDao();

            response.setContentType("text/html");
            session.setAttribute("list", list);
            session.setAttribute("status", status);
            session.setAttribute("allcolor", color);
            if (status.isEmpty() && check) {
                for (int i = 0; i < list.size(); i++) {
                    c = color.get(i + 1);
                    Iterator<Integer> iter = c.iterator();
                    int count = 1;

                    while (iter.hasNext()) {
                        String name = list.get(i).getName();
                        int colorId = iter.next();
                        String colorName = cd.findColorById(colorId).getColor_Name();
                        String pic = name + "-" + colorName + "-";
                        sd.addShoes(list.get(i).getBrandID(), colorId, list.get(i).getTypeID(), name,
                                list.get(i).getPrice(), pic);
                        String colo = request.getParameter("cr" + count + "-" + (i + 1));
                        String[] col = colo.split(",");
                        String UPLOAD_DIRECTORY = request.getServletContext().getRealPath("") + File.separator
                                + "img" + File.separator;
                        int count1 = 1;
                        for (String str : col) {
                            File file = new File(UPLOAD_DIRECTORY + str.substring(4));
                            File f = new File(UPLOAD_DIRECTORY + pic + count1 + ".jpg");
                            try {
                                boolean check1 = file.renameTo(f);
                                if (check1 == false) {
                                    session.setAttribute("errorMsg",
                                            str.substring(4) + " " + UPLOAD_DIRECTORY + pic);
                                    return "AddShoes.jsp";
                                }
                            } catch (SecurityException | NullPointerException se) {
                                session.setAttribute("errorMsg", Arrays.toString(se.getStackTrace()));
                                return "AddShoes.jsp";

                            }
                            count1++;
                        }
                        count++;

                    }
                }
                session.setAttribute("errorMsg", "Shoes is successful added");
                //                    session.removeAttribute("list");
                //                    session.removeAttribute("allcolor");
                //                    session.removeAttribute("status");

            } else {
                session.setAttribute("errorMsg", "Please fill the form with correct information");
                forwardToJsp = "AddShoes.jsp";
            }

        } else {
            session.setAttribute("errorMsg", "Fail to save changes, please refresh the page and try again");
            forwardToJsp = "shoes.jsp";
        }
    } else {
        session.setAttribute("errorMsg", "You are not allowed to access this page");
        forwardToJsp = "index.jsp";
    }
    return forwardToJsp;
}