Example usage for javax.servlet.http HttpServletResponse setDateHeader

List of usage examples for javax.servlet.http HttpServletResponse setDateHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setDateHeader.

Prototype

public void setDateHeader(String name, long date);

Source Link

Document

Sets a response header with the given name and date-value.

Usage

From source file:com.starit.diamond.server.controller.ConfigController.java

/**
 * ???// ww w  .  ja va 2 s .  co m
 * 
 * @param request
 * @param dataId
 * @param clientGroup
 *            ?
 * @return
 */
@RequestMapping(method = RequestMethod.GET)
public String getConfig(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(Constants.DATAID) String dataId,
        @RequestParam(value = Constants.GROUP, required = false) String group) {
    response.setHeader("Content-Type", "text/plain;charset=UTF-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";

    }

    if (group == null) {
        group = Constants.DEFAULT_GROUP;
    }

    String md5 = this.configService.getContentMD5(dataId, group);
    if (md5 != null) {
        response.setHeader(Constants.CONTENT_MD5, md5);

        // Md5304
        String requestMd5 = request.getHeader(Constants.CONTENT_MD5);
        if (md5.equals(requestMd5)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return "304";
        }
    } else {
        // 404.jsp, 404??, ???404.jsp
        return "404";
    }
    // 304???double-check??
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    String path = configService.getConfigInfoPath(dataId, address, group);
    // ?
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "forward:" + path;
}

From source file:com.priocept.jcr.server.UploadServlet.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    try {//from  w  ww . j  a v a2s.c  om
        if (log.isDebugEnabled())
            log.debug(request.getParameterMap());
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                args.put("contentType", item.getContentType());
                String fileName = item.getName();
                int slash = fileName.lastIndexOf("/");
                if (slash < 0)
                    slash = fileName.lastIndexOf("\\");
                if (slash > 0)
                    fileName = fileName.substring(slash + 1);
                args.put("fileName", fileName);

                if (log.isDebugEnabled())
                    log.debug(args);

                InputStream in = null;
                try {
                    in = item.openStream();
                    writeToFile(request.getSession().getId() + "/" + fileName, in, true,
                            request.getSession().getServletContext().getRealPath("/"));
                } catch (Exception e) {
                    //                  e.printStackTrace();
                    log.error("Fail to upload " + fileName);

                    response.setContentType("text/html");
                    response.setHeader("Pragma", "No-cache");
                    response.setDateHeader("Expires", 0);
                    response.setHeader("Cache-Control", "no-cache");
                    PrintWriter out = response.getWriter();
                    out.println("<html>");
                    out.println("<body>");
                    out.println("<script type=\"text/javascript\">");
                    out.println("if (parent.uploadFailed) parent.uploadFailed('"
                            + e.getLocalizedMessage().replaceAll("\'|\"", "") + "');");
                    out.println("</script>");
                    out.println("</body>");
                    out.println("</html>");
                    out.flush();
                    return;
                } finally {
                    if (in != null)
                        try {
                            in.close();
                        } catch (Exception e) {
                        }
                }

            }
        }
        response.setContentType("text/html");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<script type=\"text/javascript\">");
        out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');");
        out.println("</script>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:org.apache.karaf.cave.server.maven.MavenProxyServletTest.java

private void testDownload(Handler serverHandler) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));

    Server server = new Server(0);
    server.setHandler(serverHandler);/*from   w w  w.  j  ava  2  s  . co  m*/
    server.start();

    try {
        int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/maven2@id=central", "http",
                "localhost", localPort, "fuse", "fuse", null);
        CaveMavenServlet servlet = new CaveMavenServlet(resolver, 5, null, null, null);

        AsyncContext context = EasyMock.createMock(AsyncContext.class);

        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo())
                .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();

        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {
            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }

            @Override
            public boolean isReady() {
                // TODO Auto-generated method stub
                return true;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {
                // TODO Auto-generated method stub

            }
        }).anyTimes();
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();

        final CountDownLatch latch = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
            @Override
            public Object answer() throws Throwable {
                latch.countDown();
                return null;
            }
        });

        EasyMock.makeThreadSafe(context, true);
        EasyMock.replay(request, response, context);

        servlet.init();
        servlet.doGet(request, response);

        latch.await();

        Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray());

        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.AgentDispatchGameAction.java

/**
 * This method verifies the pack entered by the user
 * /*from  ww w.  j a  v  a 2 s  .  com*/
 * @return String
 * @throws Exception
 */
public String verifyPack() throws Exception {

    boolean isValid = false;
    int gameId = getGameId();
    boolean isBlank = false;
    boolean isDuplicate = false;

    HttpSession session = getRequest().getSession();
    List<PackBean> packList = (List<PackBean>) session.getAttribute("AGT_PACK_LIST");

    String packNbr = getPackNbrToVerify();

    System.out.println("============== " + getPackNbrToVerify() + "===" + gameNbr);
    if (packNbr.indexOf(gameNbr + "") != -1 && packNbr.indexOf("-") == -1) {
        String str = packNbr.substring(("" + gameNbr).length(), packNbr.length());
        packNbr = gameNbr + "-" + str;
        System.out.println("str == " + packNbr);

    } else {
        System.out.println("=======================else");
    }

    // ********* remove this hard-coded value***********
    UserInfoBean userInfoBean = (UserInfoBean) session.getAttribute("USER_INFO");
    int agtOrgId = userInfoBean.getUserOrgId();
    // int agtOrgId = 2;
    // ****************************************************

    // try {

    // check if the entered pack is valid
    if (packNbr != null && !packNbr.trim().equals("")) {
        AgentDispatchGameHelper helper = new AgentDispatchGameHelper();
        isValid = helper.verifyPack(gameId, agtOrgId, packNbr, gameNbr);
    } else {
        isValid = true;
    }

    // when the user changes the packNbr to blanks
    if (packNbr != null && packNbr.trim().equals("")) {
        System.out.println("--For Blank--------");
        isBlank = true;
        PackBean blankBean = packList.get(packCountId - 1);
        blankBean.setPackNumber("");
        blankBean.setValid(true);
        blankBean.setStatus(null);

    }

    /*
     * } catch (LMSException le) { return APPLICATION_ERROR; }
     */

    /*
     * try { PrintWriter out = getResponse().getWriter(); if (isValid) {
     * out.write("valid"); } } catch (IOException e) { // TODO
     * Auto-generated catch block e.printStackTrace(); }
     */

    if (!isBlank) {

        System.out.println("--Agent If Not Blank--------");
        if (packList != null) {
            copyPackValues(packList);

            // for duplicate check

            int dupCount = 0;

            int packCountId = getPackCountId();
            System.out.println("Agent PackCountId:::::::::::" + packCountId);

            for (PackBean bean : packList) {
                if (packNbr.equals(bean.getPackNumber())) {
                    dupCount++;
                }

                if (dupCount > 1) {
                    isDuplicate = true;
                    PackBean dupBean = packList.get(packCountId - 1);
                    dupBean.setValid(false);
                    dupBean.setStatus("Duplicate Pack");
                    break;
                }
            }

            if (dupCount <= 1) {
                PackBean dupBean = packList.get(packCountId - 1);
                dupBean.setValid(true);
                dupBean.setStatus(null);
            }

            if (!isDuplicate) {
                for (PackBean bean : packList) {
                    System.out.println(isValid + "==" + bean.getPackNumber() + "==="
                            + packNbr.equals(bean.getPackNumber()));
                    if (packNbr.equals(bean.getPackNumber())) {
                        if (!isValid) {
                            bean.setValid(false);
                            bean.setStatus("Wrong Pack Number");
                            break;
                        } else {
                            bean.setValid(true);
                            bean.setStatus(null);
                            break;
                        }
                    }
                }
            }

        }
    }

    setPackList(packList);

    // change the value of no of books to dispatch
    changeDispatchBooks();

    System.out.println("---------Trying to prevent caching------");
    HttpServletResponse response = getResponse();
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0
    response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    response.setDateHeader("Expires", 0); // prevents caching at the proxy
    // server
    response.setHeader("Cache-Control", "private"); // HTTP 1.1
    response.setHeader("Cache-Control", "no-store"); // HTTP 1.1
    response.setHeader("Cache-Control", "max-stale=0"); // HTTP 1.1

    return SUCCESS;
}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.AgentDispatchGameAction.java

/**
 * This method verifies the book entered by the user
 * //from   w  ww  .  j  a  v a  2s.c o  m
 * @return String
 * @throws Exception
 */
public String verifyBook() throws Exception {

    boolean isValid = false;
    int gameId = getGameId();
    boolean isBlank = false;
    boolean isDuplicate = false;

    HttpSession session = getRequest().getSession();
    List<BookBean> bookList = (List<BookBean>) session.getAttribute("AGT_BOOK_LIST");

    String bookNbr = getBookNbrToVerify();

    System.out.println("Bokkkkkkkk To verify::::::::::::::::::::::::::::::::" + bookNbr);

    // ********* remove this hard-coded value***********
    UserInfoBean userInfoBean = (UserInfoBean) session.getAttribute("USER_INFO");
    int agtOrgId = userInfoBean.getUserOrgId();
    // int agtOrgId = 2;
    // ****************************************************

    // try {

    // verify if the entered book is valid

    if (bookNbr != null && !bookNbr.trim().equals("")) {
        // System.out.println("Inside eee BookNbr:::::::" +
        // getBookNbrToVerify());

        System.out.println(":::::::::" + bookNbr.indexOf("-"));

        if (bookNbr.indexOf("-") == -1) {
            OrderedGameBean orderedGameBean = (OrderedGameBean) session.getAttribute("AGT_ORDERED_GAME");

            bookNbr = bookNbr.substring(0, orderedGameBean.getGameNbrDigits()) + "-"
                    + bookNbr.substring(orderedGameBean.getGameNbrDigits());

            System.out.println("New book nbr:::" + bookNbr);

        }

        AgentDispatchGameHelper helper = new AgentDispatchGameHelper();
        Connection conn = DBConnect.getConnection();
        try {
            isValid = helper.verifyBook(gameId, agtOrgId, bookNbr, conn, gameNbr);
        } finally {
            conn.close();
        }
    } else {
        isValid = true;
    }

    // when the user changes the bookNbr to blanks
    if (bookNbr != null && bookNbr.trim().equals("")) {
        System.out.println("--For Blank--------");
        isBlank = true;
        BookBean blankBean = bookList.get(bookCountId - 1);
        blankBean.setBookNumber("");
        blankBean.setValid(true);
        blankBean.setStatus(null);

    }

    /*
     * } catch (LMSException le) { return APPLICATION_ERROR; }
     */

    if (!isBlank) {

        System.out.println("--Agent Book If Not Blank--------");
        if (bookList != null) {
            copyBookValues(bookList);

            // for duplicate check

            int dupCount = 0;

            int bookCountId = getBookCountId();
            System.out.println("Agent BookCountId:::::::::::" + bookCountId);

            for (BookBean bean : bookList) {
                if (bookNbr.equals(bean.getBookNumber())) {
                    dupCount++;
                }

                if (dupCount > 1) {
                    isDuplicate = true;
                    BookBean dupBean = bookList.get(bookCountId - 1);
                    dupBean.setValid(false);
                    dupBean.setStatus("Duplicate Book");
                    break;
                }
            }

            if (dupCount <= 1) {
                BookBean dupBean = bookList.get(bookCountId - 1);
                dupBean.setValid(true);
                dupBean.setStatus(null);
            }

            if (!isDuplicate) {
                for (BookBean bean : bookList) {
                    if (bookNbr.equals(bean.getBookNumber())) {
                        if (!isValid) {
                            bean.setValid(false);
                            bean.setStatus("Wrong Book Number");
                            break;
                        } else {
                            bean.setValid(true);
                            bean.setStatus(null);
                            break;
                        }
                    }
                }
            }

        }
    }

    setBookList(bookList);

    // change the value of no of books to dispatch
    changeDispatchBooks();

    System.out.println("---------Agent Book Trying to prevent caching------");
    HttpServletResponse response = getResponse();
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0
    response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    response.setDateHeader("Expires", 0); // prevents caching at the proxy
    // server
    response.setHeader("Cache-Control", "private"); // HTTP 1.1
    response.setHeader("Cache-Control", "no-store"); // HTTP 1.1
    response.setHeader("Cache-Control", "max-stale=0"); // HTTP 1.1

    return SUCCESS;

}

From source file:com.skilrock.lms.web.scratchService.inventoryMgmt.common.AgentDispatchGameAction.java

public String verifyBookSeries() throws Exception {
    // update by arun
    Connection conn = DBConnect.getConnection();
    try {/*from   w ww.j  a  va  2  s. co m*/
        boolean isValid = false;
        boolean isSeriesValid = true;
        int gameId = getGameId();
        HttpSession session = getRequest().getSession();
        UserInfoBean userInfoBean = (UserInfoBean) session.getAttribute("USER_INFO");
        int agtOrgId = userInfoBean.getUserOrgId();
        List<BookBean> bookList = new ArrayList();
        List<BookBean> bookSeriesList = new ArrayList();
        List bookSeriesAll = new ArrayList();
        session.setAttribute("BOOK_SERIES_ALL", bookSeriesAll);
        session.setAttribute("AGT_BOOK_LIST", bookList);
        session.setAttribute("BOOK_SERIES_LIST", bookSeriesList);
        StringTokenizer bookNbrFrmTok = new StringTokenizer(((String[]) bookNbrFromArr)[0], ",");
        StringTokenizer bookNbrToTok = new StringTokenizer(((String[]) bookNbrToArr)[0], ",");
        bookNbrFrmStr = new String[bookNbrFrmTok.countTokens()];
        bookNbrToStr = new String[bookNbrToTok.countTokens()];
        int frmTok = 0;
        while (bookNbrFrmTok.hasMoreTokens()) {
            bookNbrFrmStr[frmTok] = bookNbrFrmTok.nextToken();
            bookNbrToStr[frmTok] = bookNbrToTok.nextToken();
            frmTok = frmTok + 1;
        }
        System.out.println("---Series length" + bookNbrFrmStr);

        if (bookNbrFrmStr != null) {
            for (int seriesNo = 0; seriesNo < bookNbrFrmStr.length; seriesNo++) {
                if (bookNbrFrmStr[seriesNo] != "") {

                    String bookNbrFrom = bookNbrFrmStr[seriesNo];
                    String bookNbrTo = bookNbrToStr[seriesNo];

                    int bookNbrFrmInt = Integer.parseInt(bookNbrFrom.replaceAll("-", ""));
                    int bookNbrToInt = Integer.parseInt(bookNbrTo.replaceAll("-", ""));
                    int noOfbooks = bookNbrToInt - bookNbrFrmInt;
                    BookSeriesBean bookSeBean = new BookSeriesBean();
                    bookSeBean.setBookNbrFrom(bookNbrFrom);
                    bookSeBean.setBookNbrTo(bookNbrTo);
                    bookSeBean.setStatus("");
                    bookSeBean.setValid(isValid);

                    for (int i = 0; i < noOfbooks + 1; i++) {
                        String bookNbr = String.valueOf(bookNbrFrmInt);

                        if (bookNbr != null && !bookNbr.trim().equals("")) {
                            // add hyphens if necessary

                            System.out.println(":::::::::" + bookNbr.indexOf("-"));

                            if (bookNbr.indexOf("-") == -1) {
                                OrderedGameBean orderedGameBean = (OrderedGameBean) session
                                        .getAttribute("AGT_ORDERED_GAME");

                                bookNbr = bookNbr.substring(0, orderedGameBean.getGameNbrDigits()) + "-"
                                        + bookNbr.substring(orderedGameBean.getGameNbrDigits());

                                System.out.println("New book nbr:::" + bookNbr);

                            }

                            System.out.println("---------------vvvvvvvvvvvvv----------" + bookNbr);
                            AgentDispatchGameHelper helper = new AgentDispatchGameHelper();
                            isValid = helper.verifyBook(gameId, agtOrgId, bookNbr, conn, gameNbr);

                            if (isValid) {
                                BookBean bookBean = new BookBean();
                                bookBean.setValid(true);
                                bookBean.setBookNumber(bookNbr);
                                for (BookBean bean : bookSeriesList) {
                                    if (bookNbr.equals(bean.getBookNumber())) {
                                        isSeriesValid = false;
                                        bookSeBean.setStatus("Series Contains Tickets of Another Series");
                                        break;// New series contains
                                        // ticket of old series
                                    }
                                }
                                if (isSeriesValid) {
                                    bookSeriesList.add(bookBean);
                                }

                            } else {
                                isSeriesValid = false;
                                bookSeBean.setStatus("Series Not Valid");
                                break;// Series not valid
                            }
                        }
                        System.out.println("inside for of verifyBookSeries");

                        bookNbrFrmInt++;

                    }

                    if (isSeriesValid) {
                        bookSeBean.setValid(true);
                        session.setAttribute("BOOK_SERIES_LIST", bookSeriesList);
                    }
                    bookSeriesAll.add(bookSeBean);
                    session.setAttribute("BOOK_SERIES_ALL", bookSeriesAll);
                    // changeDispatchBooks();
                    // System.out.println("@@@@@@@@@@@@@################$$$$$$$$$$$$$%%%%%%%%%%%%%%%%");
                }
            }
        }
        verifyIndividualBooks(bookList);

        for (int i = 0; i < bookSeriesList.size(); i++) {
            for (int j = 0; j < bookList.size(); j++) {
                // System.out.println(bookSeriesList.size()+"-Gaura
                // Test--"+bookList.size());
                if (((BookBean) bookList.get(j)).getBookNumber()
                        .equals(((BookBean) bookSeriesList.get(i)).getBookNumber())) {
                    BookBean bean = (BookBean) bookList.get(j);
                    bean.setValid(false);
                    bean.setStatus("Book Number already in Book Series");
                }
            }
        }
        setBookList(bookList);
        session.setAttribute("AGT_BOOK_LIST", bookList);
        changeDispatchBooks();
        System.out.println("---------Trying to prevent caching------" + bookList);
        HttpServletResponse response = getResponse();
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0
        response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
        response.setDateHeader("Expires", 0); // prevents caching at the
        // proxy server
        response.setHeader("Cache-Control", "private"); // HTTP 1.1
        response.setHeader("Cache-Control", "no-store"); // HTTP 1.1
        response.setHeader("Cache-Control", "max-stale=0"); // HTTP 1.1

        return SUCCESS;
    } finally {
        conn.close();
    }

}

From source file:com.qwazr.webapps.example.DocumentationServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String path = request.getPathInfo().substring(remotePrefix.length());

    File file = new File(documentationPath, path);
    if (!file.exists()) {
        response.sendError(404, "File not found: " + file);
        return;// w w w.j  av a2s  .  c  o  m
    }
    if (file.isDirectory()) {
        if (!path.endsWith("/")) {
            response.sendRedirect(request.getPathInfo() + '/');
            return;
        }
        for (String indexFileName : indexFileNames) {
            File readMefile = new File(file, indexFileName);
            if (readMefile.exists()) {
                file = readMefile;
                break;
            }
        }
    }

    Pair<String, String[]> paths = getRemoteLink(path);
    request.setAttribute("original_link", paths.getLeft());
    request.setAttribute("breadcrumb_parts", paths.getRight());

    if (!file.exists()) {
        response.sendError(404, "File not found: " + file);
        return;
    }

    request.setAttribute("currentfile", file);
    final String extension = FilenameUtils.getExtension(file.getName());
    final List<File> fileList = getBuildList(file.getParentFile());
    if ("md".equals(extension)) {
        request.setAttribute("markdown", markdownTool.toHtml(file));
        request.setAttribute("filelist", fileList);
    } else if ("adoc".equals(extension)) {
        request.setAttribute("adoc", asciiDoctorTool.convertFile(file));
        request.setAttribute("filelist", fileList);
    } else if (file.isFile()) {
        String type = mimeTypeMap.getContentType(file);
        if (type != null)
            response.setContentType(type);
        response.setContentLengthLong(file.length());
        response.setDateHeader("Last-Modified", file.lastModified());
        response.setHeader("Cache-Control", "max-age=86400");
        response.setDateHeader("Expires", System.currentTimeMillis() + 86400 * 1000);
        InputStream inputStream = new FileInputStream(file);
        try {
            IOUtils.copy(inputStream, response.getOutputStream());
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        return;
    } else if (file.isDirectory()) {
        request.setAttribute("filelist", getBuildList(file));
    } else {
        response.sendRedirect(paths.getLeft());
    }
    try {
        freemarkerTool.template(templatePath, request, response);
    } catch (TemplateException e) {
        throw new ServletException(e);
    }
}

From source file:com.starit.diamond.server.controller.ConfigController.java

/**
 * ???//from w  w w.  j a  v a  2s.  c  om
 * 
 * @param request
 * @param dataId
 * @param clientGroup
 *            ?
 * @return
 */
@RequestMapping(method = RequestMethod.POST)
public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(Constants.PROBE_MODIFY_REQUEST) String probeModify) {
    String version = request.getHeader(Constants.CLIENT_VERSION_HEADER);
    if (version == null) {
        version = "3.0.0";
    }
    response.setHeader("Content-Type", "text/html;charset=UTF-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";

    }

    final List<ConfigKey> configKeyList = getConfigKeyList(probeModify);

    StringBuilder resultBuilder = new StringBuilder();
    StringBuilder newResultBuilder = new StringBuilder();
    int index = 0;
    for (ConfigKey key : configKeyList) {
        String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup());
        if (md5 != null) {
            if (!md5.equals(key.getMd5())) {
                resultBuilder.append(key.getDataId()).append(":").append(key.getGroup()).append(";");
                newResultBuilder.append(key.getDataId()).append(Constants.WORD_SEPARATOR).append(key.getGroup())
                        .append(Constants.LINE_SEPARATOR);
                index++;
            }
        } else {
            if (key.getMd5() != null) {
                resultBuilder.append(key.getDataId()).append(":").append(key.getGroup()).append(";");
                newResultBuilder.append(key.getDataId()).append(Constants.WORD_SEPARATOR).append(key.getGroup())
                        .append(Constants.LINE_SEPARATOR);
                index++;
            }
        }

    }

    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");

    int versionNum = 0;
    if (index > 0) {
        versionNum = Protocol.getVersionNumber(version);
    } else {
        versionNum = -1;
    }
    String returnHeader = newResultBuilder.toString();
    try {
        returnHeader = URLEncoder.encode(newResultBuilder.toString(), "UTF-8");
    } catch (Exception e) {
    }
    if (versionNum >= 204) {
        request.setAttribute("content", returnHeader);
    } else if (versionNum >= 0) {
        response.addHeader(Constants.PROBE_MODIFY_RESPONSE_NEW, returnHeader);
        response.addHeader(Constants.PROBE_MODIFY_RESPONSE, resultBuilder.toString());// ?1.0
    } else {
        request.setAttribute("content", "");
        response.addHeader(Constants.PROBE_MODIFY_RESPONSE_NEW, "");
        response.addHeader(Constants.PROBE_MODIFY_RESPONSE, "");
    }
    return "200";
}

From source file:com.octo.captcha.module.struts.image.RenderImageCaptchaAction.java

public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

    ImageCaptchaService service = (ImageCaptchaService) CaptchaServicePlugin.getInstance().getService();
    String captchaID = CaptchaModuleConfigHelper.getId(httpServletRequest);
    //(String) theRequest.getParameter(captchaIDParameterName);

    // call the ManageableImageCaptchaService methods
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {/*from w w w.j  av a 2 s .co  m*/
        BufferedImage challenge = service.getImageChallengeForID(captchaID, httpServletRequest.getLocale());
        // the output stream to render the captcha image as jpeg into

        // a jpeg encoder
        JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
        jpegEncoder.encode(challenge);
    } catch (IllegalArgumentException e) {
        // log a security warning and return a 404...
        if (log.isWarnEnabled()) {
            log.warn("There was a try from " + httpServletRequest.getRemoteAddr()
                    + " to render an URL without ID" + " or with a too long one");
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            log.error("should never pass here!");
            return actionMapping.findForward("error");
        }
    } catch (CaptchaServiceException e) {
        // log and return a 404 instead of an image...
        log.warn("Error trying to generate a captcha and " + "render its challenge as JPEG", e);
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        // log.error("should never pass here!");
        return actionMapping.findForward("error");
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);
    httpServletResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
    // log.error("should never pass here!");
    return null;
}

From source file:ru.org.linux.user.UserEventController.java

@RequestMapping(value = "/show-replies.jsp", method = RequestMethod.GET)
public ModelAndView showReplies(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "nick", required = false) String nick,
        @RequestParam(value = "offset", defaultValue = "0") int offset,
        @ModelAttribute("notifications") Action action) throws Exception {
    Template tmpl = Template.getTemplate(request);
    boolean feedRequested = request.getParameterMap().containsKey("output");

    if (nick == null) {
        if (tmpl.isSessionAuthorized()) {
            return new ModelAndView(new RedirectView("/notifications"));
        }//from   w ww.j  av  a2  s. c o m
        throw new AccessViolationException("not authorized");
    } else {
        User.checkNick(nick);
        if (!tmpl.isSessionAuthorized() && !feedRequested) {
            throw new AccessViolationException("not authorized");
        }
        if (tmpl.isSessionAuthorized() && nick.equals(tmpl.getCurrentUser().getNick()) && !feedRequested) {
            return new ModelAndView(new RedirectView("/notifications"));
        }
        if (!feedRequested && !tmpl.isModeratorSession()) {
            throw new AccessViolationException(
                    "? ?  ?");
        }
    }

    Map<String, Object> params = new HashMap<>();
    params.put("nick", nick);

    if (offset < 0) {
        offset = 0;
    }

    boolean firstPage = offset == 0;
    int topics = tmpl.getProf().getTopics();
    if (feedRequested) {
        topics = 50;
    }

    if (topics > 200) {
        topics = 200;
    }

    params.put("firstPage", firstPage);
    params.put("topics", topics);
    params.put("offset", offset);

    /* define timestamps for caching */
    long time = System.currentTimeMillis();
    int delay = firstPage ? 90 : 60 * 60;
    response.setDateHeader("Expires", time + 1000 * delay);

    User user = userDao.getUser(nick);

    boolean showPrivate = tmpl.isModeratorSession();

    User currentUser = tmpl.getCurrentUser();
    params.put("currentUser", currentUser);

    if (currentUser != null && currentUser.getId() == user.getId()) {
        showPrivate = true;
        params.put("unreadCount", user.getUnreadEvents());
        response.addHeader("Cache-Control", "no-cache");
    }

    List<UserEvent> list = userEventService.getRepliesForUser(user, showPrivate, topics, offset,
            UserEventFilterEnum.ALL);
    List<PreparedUserEvent> prepared = userEventService.prepare(list, feedRequested, request.isSecure());

    params.put("isMyNotifications", false);
    params.put("topicsList", prepared);
    params.put("hasMore", list.size() == topics);

    ModelAndView result = new ModelAndView("show-replies", params);

    if (feedRequested) {
        result.addObject("feed-type", "rss");
        if ("atom".equals(request.getParameter("output"))) {
            result.addObject("feed-type", "atom");
        }
        result.setView(feedView);
    }
    return result;
}