Example usage for org.apache.wicket.request IRequestCycle getRequest

List of usage examples for org.apache.wicket.request IRequestCycle getRequest

Introduction

In this page you can find the example usage for org.apache.wicket.request IRequestCycle getRequest.

Prototype

Request getRequest();

Source Link

Usage

From source file:com.madalla.wicket.request.SwitchProtocolRequestHandler.java

License:Apache License

/**
 * {@inheritDoc}/*from  ww  w .j a  v a 2 s .  c  om*/
 */
public void respond(IRequestCycle requestCycle) {
    WebRequest webRequest = (WebRequest) requestCycle.getRequest();
    HttpServletRequest request = (HttpServletRequest) webRequest.getContainerRequest();

    Integer port = null;
    if (protocol == Protocol.HTTP) {
        if (httpsConfig.getHttpPort() != 80) {
            port = httpsConfig.getHttpPort();
        }
    } else if (protocol == Protocol.HTTPS) {
        if (httpsConfig.getHttpsPort() != 443) {
            port = httpsConfig.getHttpsPort();
        }
    }

    final String url = getUrl(protocol.toString().toLowerCase(), port, request);

    WebResponse response = (WebResponse) requestCycle.getResponse();

    response.sendRedirect(url);
}

From source file:com.madalla.wicket.request.SwitchProtocolRequestHandler.java

License:Apache License

/**
 * Returns a target that can be used to redirect to the specified protocol. If no change is
 * required {@code null} will be returned.
 * //ww  w  . j a v a2  s  .c  o  m
 * @param protocol
 *            required protocol
 * @param httpsConfig
 *            the https configuration
 * @return request handler or {@code null}
 */
public static IRequestHandler requireProtocol(Protocol protocol, final HttpsConfig httpsConfig) {
    IRequestCycle requestCycle = RequestCycle.get();
    WebRequest webRequest = (WebRequest) requestCycle.getRequest();
    HttpServletRequest request = (HttpServletRequest) webRequest.getContainerRequest();
    if (protocol == null || protocol == Protocol.PRESERVE_CURRENT
            || request.getScheme().equals(protocol.toString().toLowerCase())) {
        return null;
    } else {
        return new SwitchProtocolRequestHandler(protocol, httpsConfig);
    }
}

From source file:fiftyfive.wicket.resource.MergedResourceRequestHandler.java

License:Apache License

public void respond(IRequestCycle requestCycle) {
    WebRequest origRequest = (WebRequest) requestCycle.getRequest();

    // Explicitly set the last modified header of the response based on the last modified
    // time of the aggregate. Do this on the original response because our wrapped response
    // ignores the last modified headers contributed by each individual resource.
    WebResponse origResponse = (WebResponse) requestCycle.getResponse();
    if (this.lastModified != null) {
        origResponse.setLastModifiedTime(this.lastModified);
    }//  w  w  w  .j  a  va  2s . co  m

    try {
        // Make a special response object that merges the contributions of each resource,
        // but maintains a single set of headers.
        MergedResponse merged = new MergedResponse(origResponse);
        requestCycle.setResponse(merged);

        // Make a special request object that tweaks the If-Modified-Since header to ensure
        // we don't end up in a situation where some resources respond 200 and others 304.
        // Yes, calling RequestCycle#setRequest() is frowned upon so this is a bit of a hack.
        ((RequestCycle) requestCycle).setRequest(new MergedRequest(origRequest));

        for (ResourceReference ref : this.resources) {
            ResourceRequestHandler handler = new ResourceRequestHandler(ref.getResource(), this.pageParameters);
            handler.respond(requestCycle);

            // If first resource sent 304 Not Modified that means all will.
            // We can therefore skip the rest.
            if (304 == merged.status) {
                break;
            }
        }
    } finally {
        // Restore the original request once we're done. We don't need to restore the
        // original response because Wicket takes care of that automatically.
        ((RequestCycle) requestCycle).setRequest(origRequest);
    }
}

From source file:gr.abiss.calipso.wicket.AttachmentLinkPanel.java

License:Open Source License

public AttachmentLinkPanel(String id, final Attachment attachment, boolean addHeadScript) {
    super(id);/*from  w w w . j av  a 2s. c  o  m*/
    if (addHeadScript) {
        renderSighslideDirScript();
    }
    WebMarkupContainer attachmentContainer = new WebMarkupContainer("attachmentContainer");
    add(attachmentContainer);
    if (attachment == null) {
        attachmentContainer.setVisible(false);
        return;
    }
    final String fileName = getResponse().encodeURL(attachment.getFileName()).toString();
    String downloadLabel = null;
    WebMarkupContainer imageAttachmentContainer = new WebMarkupContainer("imageAttachment");
    attachmentContainer.add(imageAttachmentContainer);
    // if attachment is image, preview it
    if (fileName.endsWith(".png") || fileName.endsWith(".gif") || fileName.endsWith(".bmp")
            || fileName.endsWith(".jpeg") || fileName.endsWith(".jpg")) {
        BufferedImage icon = null;
        // read image
        try {
            File imageFileThumb = new File(getCalipso().getCalipsoHome() + File.separator
                    + attachment.getBasePath() + File.separator + "thumb_" + attachment.getFileName());
            if (imageFileThumb.exists()) {
                icon = ImageIO.read(imageFileThumb);
            }
        } catch (IOException e) {
            throw new RuntimeException("Unable to read thumb image", e);
        }
        // render html
        if (icon != null) {
            BufferedDynamicImageResource iconResource = new BufferedDynamicImageResource();
            iconResource.setImage(icon);
            Image image = new Image("imageThumb", iconResource);
            Link imageAttachmentLink = new Link("attachment") {
                // adapted from wicket.markup.html.link.DownloadLink
                // with the difference that the File is instantiated only
                // after onClick
                public void onClick() {
                    getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {

                        public void respond(IRequestCycle requestCycle) {
                            WebResponse r = (WebResponse) requestCycle.getResponse();
                            r.setAttachmentHeader(fileName);
                            try {
                                File previewfile = new File(getCalipso().getCalipsoHome() + File.separator
                                        + attachment.getBasePath() + File.separator + "small_"
                                        + attachment.getFileName());
                                logger.info("Looking for previewfile path: " + previewfile.getAbsolutePath());
                                InputStream is = new FileInputStream(previewfile);
                                try {
                                    Streams.copy(is, r.getOutputStream());
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                } finally {
                                    try {
                                        is.close();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            } catch (FileNotFoundException e) {
                                throw new RuntimeException(e);
                            }
                        }

                        public void detach(IRequestCycle requestCycle) {
                            // TODO Auto-generated method stub

                        }
                    });
                }
            };
            imageAttachmentLink.add(image);
            imageAttachmentContainer.add(imageAttachmentLink);
            downloadLabel = attachment.isSimple() ? attachment.getOriginalFileName()
                    : localize("item_view_form.download");
        } else {
            imageAttachmentContainer.setVisible(false);
        }
    } else {
        imageAttachmentContainer.setVisible(false);
    }
    // attachment link
    Link link = new Link("attachment") {
        // adapted from wicket.markup.html.link.DownloadLink
        // with the difference that the File is instantiated only after
        // onClick
        public void onClick() {
            getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {

                public void respond(IRequestCycle requestCycle) {
                    WebResponse r = (WebResponse) requestCycle.getResponse();
                    try {
                        String ua = ((WebRequest) requestCycle.getRequest()).getHeader("User-Agent");
                        boolean isMSIE = (ua != null && ua.indexOf("MSIE") != -1);
                        logger.debug("Client browser is IE - " + isMSIE);
                        if (isMSIE) {
                            r.setAttachmentHeader(
                                    URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20"));
                        } else {
                            // This works in FireFox - NEW W3C STANDART
                            // See
                            // http://greenbytes.de/tech/webdav/draft-reschke-rfc2231-in-http-latest.html#RFC2231
                            r.setHeader("Content-Disposition",
                                    "attachment; filename*=UTF-8''" + URLEncoder.encode(
                                            attachment.isSimple() ? attachment.getOriginalFileName() : fileName,
                                            "UTF-8").replaceAll("\\+", "%20"));
                        }
                        r.setContentType(MimeTable.getDefaultTable().getContentTypeFor(fileName));
                    } catch (UnsupportedEncodingException e1) {
                        logger.error("Error encoding", e1);
                        r.setAttachmentHeader(fileName);
                    }
                    try {
                        File file = AttachmentUtils.getSavedAttachmentFile(attachment,
                                getCalipso().getCalipsoHome());
                        InputStream is = new FileInputStream(file);
                        try {
                            Streams.copy(is, r.getOutputStream());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        } finally {
                            try {
                                is.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }

                public void detach(IRequestCycle requestCycle) {
                    // TODO Auto-generated method stub

                }
            });
        }
    };
    if (downloadLabel == null) {
        downloadLabel = fileName;
    }
    link.add(new Label("fileName", downloadLabel));
    attachmentContainer.add(link);
}

From source file:gr.abiss.calipso.wicket.fileUpload.AttachmentDownLoadableLinkPanel.java

License:Open Source License

public AttachmentDownLoadableLinkPanel(String id, final Attachment attachment) {
    super(id);//www. j av  a2 s  . c om
    renderSighslideDirScript();

    final String filaName = attachment.getFileName();
    String downloadLabel = null;

    // attachment link
    Link link = new Link("attachmentLink") {

        public void onClick() {

            getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {

                public void respond(IRequestCycle requestCycle) {
                    WebResponse r = (WebResponse) requestCycle.getResponse();
                    try {
                        String ua = ((WebRequest) requestCycle.getRequest()).getHeader("User-Agent");
                        boolean isMSIE = (ua != null && ua.indexOf("MSIE") != -1);
                        logger.debug("Client browser is IE - " + isMSIE);
                        if (isMSIE) {
                            r.setAttachmentHeader(URLEncoder.encode(attachment.getFileName(), "UTF-8")
                                    .replaceAll("\\+", "%20"));
                        } else {

                            // This works in FireFox - NEW W3C STANDART
                            // See
                            // http://greenbytes.de/tech/webdav/draft-reschke-rfc2231-in-http-latest.html#RFC2231
                            r.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder
                                    .encode(attachment.getFileName(), "UTF-8").replaceAll("\\+", "%20"));
                        }
                        r.setContentType(
                                MimeTable.getDefaultTable().getContentTypeFor(attachment.getFileName()));
                    } catch (UnsupportedEncodingException e1) {
                        logger.error("Some mess in Encoding");
                        r.setAttachmentHeader(attachment.getFileName());
                    }
                    try {
                        File file = AttachmentUtils.getSavedAttachmentFile(attachment,
                                getCalipso().getCalipsoHome());
                        InputStream is = new FileInputStream(file);
                        try {
                            Streams.copy(is, r.getOutputStream());
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        } finally {
                            try {
                                is.close();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }

                public void detach(IRequestCycle requestCycle) {
                    // TODO Auto-generated method stub

                }
            });

            // }
            // }

        }
    };
    downloadLabel = attachment.getFileName();
    add(link);
    link.add(new Label("fileName", downloadLabel));
}

From source file:name.martingeisse.wicket.util.json.AbstractJsonRequestHandler.java

License:Open Source License

@Override
public void respond(IRequestCycle requestCycle) {
    WebRequest request = (WebRequest) requestCycle.getRequest();
    WebResponse response = (WebResponse) requestCycle.getResponse();

    JavascriptAssembler assembler = new JavascriptAssembler();
    generateJson(assembler, request);/* w ww.j a v a 2 s.c  o m*/

    response.setHeader("Cache-Control", "no-cache, must-revalidate");
    response.setHeader("Pragma", "no-cache");
    response.setContentType(getContentType());
    ((HttpServletResponse) response.getContainerResponse()).setCharacterEncoding("utf-8");
    response.write(assembler.getAssembledCode());
}

From source file:org.artifactory.webapp.wicket.page.logs.SystemLogsViewPanel.java

License:Open Source License

/**
 * Add a link to enable the download of the system log file
 *//*from  w  w  w  .ja  v a2s .co  m*/
private void addSystemLogsLink() {
    // This is very ugly and should be removed when we upgrade wicket, see RTFACT-5470 for explanation
    downloadLink = new DownloadLink("systemLogsLink", systemLogFile) {
        @Override
        public void onClick() {
            final File file = getModelObject();
            IResourceStream resourceStream = new FileResourceStream(new org.apache.wicket.util.file.File(file));
            ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(resourceStream) {
                @Override
                public void respond(IRequestCycle requestCycle) {
                    IResource.Attributes attributes = new IResource.Attributes(requestCycle.getRequest(),
                            requestCycle.getResponse());

                    ResourceStreamResource resource = new ResourceStreamResource(this.getResourceStream()) {
                        @Override
                        protected void configureCache(ResourceResponse data, Attributes attributes) {
                            Response response = attributes.getResponse();
                            ((WebResponse) response).disableCaching();
                        }
                    };
                    resource.setFileName(file.getName());
                    resource.setContentDisposition(ContentDisposition.ATTACHMENT);
                    resource.respond(attributes);
                }
            };
            getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
        }
    };

    add(downloadLink);
    downloadLink.add(linkLabel);
    downloadLink.setOutputMarkupId(true);
    linkLabel.setOutputMarkupId(true);
}

From source file:org.brixcms.plugin.site.resource.ResourceNodeHandler.java

License:Apache License

@Override
public void respond(IRequestCycle requestCycle) {
    boolean save = (this.save != null) ? this.save
            : Strings.isTrue(RequestCycle.get().getRequest().getRequestParameters()
                    .getParameterValue(SAVE_PARAMETER).toString());

    BrixFileNode node = (BrixFileNode) this.node.getObject();

    if (!SitePlugin.get().canViewNode(node, Action.Context.PRESENTATION)) {
        throw Brix.get().getForbiddenException();
    }/*from ww  w. ja v a2s .  c  o m*/

    WebResponse response = (WebResponse) RequestCycle.get().getResponse();

    response.setContentType(node.getMimeType());

    Date lastModified = node.getLastModified();
    response.setLastModifiedTime(Time.valueOf(lastModified));

    try {
        final HttpServletRequest r = (HttpServletRequest) requestCycle.getRequest().getContainerRequest();
        String since = r.getHeader("If-Modified-Since");
        if (!save && since != null) {
            Date d = new Date(r.getDateHeader("If-Modified-Since"));

            // the weird toString comparison is to prevent comparing
            // milliseconds
            if (d.after(lastModified) || d.toString().equals(lastModified.toString())) {
                response.setContentLength(node.getContentLength());
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                return;
            }
        }
        String fileName = node.getName();
        long length = node.getContentLength();
        HttpServletResponse httpServletResponse = (HttpServletResponse) response.getContainerResponse();
        InputStream stream = node.getDataAsStream();

        new Streamer(length, stream, fileName, save, r, httpServletResponse).stream();
    } catch (Exception e) {
        log.error("Error writing resource data to content", e);
    }
}

From source file:org.jabylon.rest.ui.wicket.xliff.XliffDownloadForm.java

License:Open Source License

/**
 * Called by WICKET on form submit. Triggers subsequent processing, i.e. the conversion/download
 * of XLIFF files.//  www  .j a  v a  2 s  .  c o  m
 * <p>
 * 1. Retrieve form result as {@link XliffLanguageTupleSelectionPanel} objects.<br>
 * 2. Convert to Map holding Language tuples.<br>
 * 3. Call XLIFF conversion/export processing.<br>
 */
@Override
protected void onSubmit() {
    List<XliffLanguageTupleSelectionPanel> result = getSelection();
    final Map<Language, Language> resultAsMap = processSelection(result);

    getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {

        @Override
        public void respond(IRequestCycle requestCycle) {
            XliffDownloadResource downloadResource = new XliffDownloadResource(resultAsMap, projectVersion,
                    filter);
            downloadResource
                    .respond(new IResource.Attributes(requestCycle.getRequest(), requestCycle.getResponse()));
        }

        @Override
        public void detach(IRequestCycle requestCycle) {
            // nothing to do.
        }
    });
}

From source file:org.wicketstuff.poi.excel.TableComponentAsXlsHandler.java

License:Apache License

public void respond(IRequestCycle requestCycle) {
    try {/*from  w ww  . jav a2 s . c  o m*/
        TableParser parser = new TableParser(newSheet(), cellExporter);
        if (tableComponent instanceof IPageable) {
            IPageable pageable = (IPageable) tableComponent;
            for (int i = 0; i < pageable.getPageCount(); i++) {
                pageable.setCurrentPage(i);
                parser.parse(tableComponent);
            }
        } else {
            parser.parse(tableComponent);
        }
        XlsStream xlsStream = new XlsStream(parser.getSheet().getWorkbook());
        ResourceStreamResource resource = new ResourceStreamResource(xlsStream);
        resource.setFileName(filename);
        resource.setContentDisposition(ContentDisposition.ATTACHMENT);
        IResource.Attributes a = new IResource.Attributes(requestCycle.getRequest(),
                requestCycle.getResponse());
        resource.respond(a);
    } catch (Exception e) {
        throw new RuntimeException("Error while generating a xls file to table component", e);
    }
}