Example usage for org.apache.wicket.request.http WebResponse getOutputStream

List of usage examples for org.apache.wicket.request.http WebResponse getOutputStream

Introduction

In this page you can find the example usage for org.apache.wicket.request.http WebResponse getOutputStream.

Prototype

public OutputStream getOutputStream() 

Source Link

Document

Returns an OutputStream suitable for writing binary data in the response.

Usage

From source file:com.gitblit.wicket.pages.ExportTicketPage.java

License:Apache License

public ExportTicketPage(final PageParameters params) {
    super(params);

    if (params.get("r").isEmpty()) {
        error(getString("gb.repositoryNotSpecified"));
        redirectToInterceptPage(new RepositoriesPage());
    }//from w w w . j  a  va2s. c  om

    getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {

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

            final String repositoryName = WicketUtils.getRepositoryName(params);
            RepositoryModel repository = app().repositories().getRepositoryModel(repositoryName);
            String objectId = WicketUtils.getObject(params).toLowerCase();
            if (objectId.endsWith(".json")) {
                objectId = objectId.substring(0, objectId.length() - ".json".length());
            }
            long id = Long.parseLong(objectId);
            TicketModel ticket = app().tickets().getTicket(repository, id);

            String content = TicketSerializer.serialize(ticket);
            contentType = "application/json; charset=UTF-8";
            response.setContentType(contentType);
            try {
                response.getOutputStream().write(content.getBytes("UTF-8"));
            } catch (Exception e) {
                logger.error("Failed to write text response", e);
            }
        }

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

        }
    });
}

From source file:com.gitblit.wicket.pages.RawPage.java

License:Apache License

public RawPage(final PageParameters params) {
    super(params);

    if (params.get("r").isEmpty()) {
        error(getString("gb.repositoryNotSpecified"));
        redirectToInterceptPage(new RepositoriesPage());
    }//from  ww w  .  jav  a2 s . c o  m

    getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {

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

            final String repositoryName = WicketUtils.getRepositoryName(params);
            final String objectId = WicketUtils.getObject(params);
            final String blobPath = WicketUtils.getPath(params);

            String[] encodings = getEncodings();
            GitBlitWebSession session = GitBlitWebSession.get();
            UserModel user = session.getUser();

            RepositoryModel model = app().repositories().getRepositoryModel(user, repositoryName);
            if (model == null) {
                // user does not have permission
                error(getString("gb.canNotLoadRepository") + " " + repositoryName);
                redirectToInterceptPage(new RepositoriesPage());
                return;
            }

            Repository r = app().repositories().getRepository(repositoryName);
            if (r == null) {
                error(getString("gb.canNotLoadRepository") + " " + repositoryName);
                redirectToInterceptPage(new RepositoriesPage());
                return;
            }

            if (StringUtils.isEmpty(blobPath)) {
                // objectid referenced raw view
                byte[] binary = JGitUtils.getByteContent(r, objectId);
                if (binary == null) {
                    final String objectNotFound = MessageFormat
                            .format("Raw page failed to find object {0} in {1}", objectId, repositoryName);
                    logger.error(objectNotFound);
                    throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_NOT_FOUND, objectNotFound);
                }
                contentType = "application/octet-stream";
                response.setContentType(contentType);
                response.setContentLength(binary.length);
                try {
                    response.getOutputStream().write(binary);
                } catch (Exception e) {
                    logger.error("Failed to write binary response", e);
                }
            } else {
                // standard raw blob view
                RevCommit commit = JGitUtils.getCommit(r, objectId);
                if (commit == null) {
                    final String commitNotFound = MessageFormat
                            .format("Raw page failed to find commit {0} in {1}", objectId, repositoryName);
                    logger.error(commitNotFound);
                    throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_NOT_FOUND, commitNotFound);
                }

                String filename = blobPath;
                if (blobPath.indexOf('/') > -1) {
                    filename = blobPath.substring(blobPath.lastIndexOf('/') + 1);
                }

                String extension = null;
                if (blobPath.lastIndexOf('.') > -1) {
                    extension = blobPath.substring(blobPath.lastIndexOf('.') + 1);
                }

                // Map the extensions to types
                Map<String, Integer> map = new HashMap<String, Integer>();
                for (String ext : app().settings().getStrings(Keys.web.imageExtensions)) {
                    map.put(ext.toLowerCase(), 2);
                }
                for (String ext : app().settings().getStrings(Keys.web.binaryExtensions)) {
                    map.put(ext.toLowerCase(), 3);
                }

                final String blobNotFound = MessageFormat.format(
                        "Raw page failed to find blob {0} in {1} @ {2}", blobPath, repositoryName, objectId);

                if (extension != null) {
                    int type = 0;
                    if (map.containsKey(extension)) {
                        type = map.get(extension);
                    }
                    switch (type) {
                    case 2:
                        // image blobs
                        byte[] image = JGitUtils.getByteContent(r, commit.getTree(), blobPath, true);
                        if (image == null) {
                            logger.error(blobNotFound);
                            throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_NOT_FOUND,
                                    blobNotFound);
                        }
                        contentType = "image/" + extension.toLowerCase();
                        response.setContentType(contentType);
                        response.setContentLength(image.length);
                        try {
                            response.getOutputStream().write(image);
                        } catch (IOException e) {
                            logger.error("Failed to write image response", e);
                        }
                        break;
                    case 3:
                        // binary blobs (download)
                        byte[] binary = JGitUtils.getByteContent(r, commit.getTree(), blobPath, true);
                        if (binary == null) {
                            logger.error(blobNotFound);
                            throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_NOT_FOUND,
                                    blobNotFound);
                        }
                        contentType = "application/octet-stream";
                        response.setContentLength(binary.length);
                        response.setContentType(contentType);

                        try {
                            String userAgent = GitBlitRequestUtils.getServletRequest().getHeader("User-Agent");

                            if (userAgent != null && userAgent.indexOf("MSIE 5.5") > -1) {
                                response.setHeader("Content-Disposition",
                                        "filename=\"" + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
                            } else if (userAgent != null && userAgent.indexOf("MSIE") > -1) {
                                response.setHeader("Content-Disposition", "attachment; filename=\""
                                        + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
                            } else {
                                response.setHeader("Content-Disposition", "attachment; filename=\""
                                        + new String(filename.getBytes(Constants.ENCODING), "latin1") + "\"");
                            }
                        } catch (UnsupportedEncodingException e) {
                            response.setHeader("Content-Disposition",
                                    "attachment; filename=\"" + filename + "\"");
                        }

                        try {
                            response.getOutputStream().write(binary);
                        } catch (IOException e) {
                            logger.error("Failed to write binary response", e);
                        }
                        break;
                    default:
                        // plain text
                        String content = JGitUtils.getStringContent(r, commit.getTree(), blobPath, encodings);
                        if (content == null) {
                            logger.error(blobNotFound);
                            throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_NOT_FOUND,
                                    blobNotFound);
                        }
                        contentType = "text/plain; charset=UTF-8";
                        response.setContentType(contentType);
                        try {
                            response.getOutputStream().write(content.getBytes("UTF-8"));
                        } catch (Exception e) {
                            logger.error("Failed to write text response", e);
                        }
                    }

                } else {
                    // plain text
                    String content = JGitUtils.getStringContent(r, commit.getTree(), blobPath, encodings);
                    if (content == null) {
                        logger.error(blobNotFound);
                        throw new AbortWithHttpErrorCodeException(HttpServletResponse.SC_NOT_FOUND,
                                blobNotFound);
                    }
                    contentType = "text/plain; charset=UTF-8";
                    response.setContentType(contentType);
                    try {
                        response.getOutputStream().write(content.getBytes("UTF-8"));
                    } catch (Exception e) {
                        logger.error("Failed to write text response", e);
                    }
                }
            }
            r.close();
        }

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

        }

    });

}

From source file:com.mylab.wicket.jpa.ui.pages.select2.AbstractSelect2Choice.java

License:Apache License

@Override
public void onResourceRequested() {

    // this is the callback that retrieves matching choices used to populate
    // the dropdown

    Request request = getRequestCycle().getRequest();
    IRequestParameters params = request.getRequestParameters();

    // retrieve choices matching the search term

    String term = params.getParameterValue("q").toOptionalString();

    int page = params.getParameterValue("page").toInt(1);
    // select2 uses 1-based paging, but in wicket world we are used to
    // 0-based/*from   ww w  .  ja  v a  2 s .  c  o m*/
    page -= 1;

    Response<T> response = new Response<>();
    getProvider().query(term, page, response);

    // jsonize and write out the choices to the response

    WebResponse webResponse = (WebResponse) getRequestCycle().getResponse();
    webResponse.setContentType("application/json");

    OutputStreamWriter out = new OutputStreamWriter(webResponse.getOutputStream(), getRequest().getCharset());
    JSONWriter json = new JSONWriter(out);

    try {
        json.object();
        json.key("items").array();
        for (T item : response) {
            json.object();
            getProvider().toJson(item, json);
            json.endObject();
        }
        json.endArray();
        json.key("more").value(response.getHasMore()).endObject();
    } catch (JSONException e) {
        throw new RuntimeException("Could not write Json response", e);
    }

    try {
        out.flush();
    } catch (IOException e) {
        throw new RuntimeException("Could not write Json to servlet response", e);
    }
}

From source file:com.vaynberg.wicket.select2.AbstractSelect2Choice.java

License:Apache License

@Override
public void onResourceRequested() {

    // this is the callback that retrieves matching choices used to populate the dropdown

    Request request = getRequestCycle().getRequest();
    IRequestParameters params = request.getRequestParameters();

    // retrieve choices matching the search term

    String term = params.getParameterValue("term").toOptionalString();

    int page = params.getParameterValue("page").toInt(1);
    // select2 uses 1-based paging, but in wicket world we are used to
    // 0-based/* www. j  av  a2 s. c o m*/
    page -= 1;

    Response<T> response = new Response<T>();
    provider.query(term, page, response);

    // jsonize and write out the choices to the response

    WebResponse webResponse = (WebResponse) getRequestCycle().getResponse();
    webResponse.setContentType("application/json");

    OutputStreamWriter out = new OutputStreamWriter(webResponse.getOutputStream(), getRequest().getCharset());
    JSONWriter json = new JSONWriter(out);

    try {
        json.object();
        json.key("results").array();
        for (T item : response) {
            json.object();
            provider.toJson(item, json);
            json.endObject();
        }
        json.endArray();
        json.key("more").value(response.getHasMore()).endObject();
    } catch (JSONException e) {
        throw new RuntimeException("Could not write Json response", e);
    }

    try {
        out.flush();
    } catch (IOException e) {
        throw new RuntimeException("Could not write Json to servlet response", e);
    }
}

From source file:eu.schulteweb.wicket.datatables.markup.html.repeater.data.table.DataTable.java

License:Apache License

@Override
public void onResourceRequested() {
    DataRequest request = new DataRequest(RequestCycle.get().getRequest());

    WebResponse webResponse = (WebResponse) getRequestCycle().getResponse();
    webResponse.setContentType("application/json");

    dataProvider.getJSONResponse(request, webResponse.getOutputStream());
}

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  ww w . ja v  a 2 s.  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);//from   www. j a v a 2s.  co  m
    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:gr.abiss.calipso.wicket.ItemList.java

License:Open Source License

private void addExcelExport() {
    add(new Link("export") {
        public void onClick() {
            // temporarily switch off paging of results
            itemSearch.setPageSize(-1);// w  w  w. jav  a2  s  .  c  o m
            final ExcelUtils eu = new ExcelUtils(getCalipso().findItems(itemSearch), itemSearch, this);
            // restore page size
            itemSearch.setPageSize(pageSize);
            getRequestCycle().scheduleRequestHandlerAfterCurrent(new IRequestHandler() {
                public void respond(IRequestCycle requestCycle) {
                    WebResponse r = (WebResponse) requestCycle.getResponse();
                    r.setAttachmentHeader("calipso-export-" + DateUtils.formatForFileName() + ".xls");
                    try {
                        eu.exportToExcel().write(r.getOutputStream());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                public void detach(IRequestCycle requestCycle) {
                }
            });
        }
    });
}

From source file:org.dcm4chee.wizard.panel.BasicConfigurationPanel.java

License:LGPL

private Link<Object> getExportLink() {
    return new Link<Object>("export") {
        private static final long serialVersionUID = 1L;

        @Override/*from   w w w  .  j a  v  a 2 s  .  co  m*/
        public void onClick() {

            RequestCycle.get().replaceAllRequestHandlers(new IRequestHandler() {

                @Override
                public void detach(IRequestCycle requestCycle) {
                }

                @Override
                public void respond(IRequestCycle requestCycle) {

                    OutputStream out = null;
                    try {
                        WebResponse response = (WebResponse) getRequestCycle().getResponse();
                        response.setContentType("application/zip");
                        response.setAttachmentHeader("configuration.zip");
                        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
                        out = zos;
                        ZipEntry entry = new ZipEntry("configuration.xml");
                        zos.putNextEntry(entry);
                        DicomConfiguration dicomConfiguration = ((WizardApplication) getApplication())
                                .getDicomConfigurationManager().getDicomConfiguration();
                        ((PreferencesDicomConfiguration) dicomConfiguration).getDicomConfigurationRoot()
                                .exportSubtree(zos);
                        zos.flush();
                        zos.closeEntry();
                    } catch (ZipException ze) {
                        log.warn("Problem creating zip file: " + ze);
                    } catch (ClientAbortException cae) {
                        log.warn("Client aborted zip file download: " + cae);
                    } catch (Exception e) {
                        log.error("An error occurred while attempting to stream zip file for download: ", e);
                    } finally {
                        try {
                            if (out != null)
                                out.close();
                        } catch (Exception ignore) {
                        }
                    }
                }
            });
        }
    };
}

From source file:org.opensingular.form.wicket.mapper.attachment.DownloadSupportedBehavior.java

License:Apache License

private void writeResponse(String url) throws IOException {
    JSONObject jsonFile = new JSONObject();
    jsonFile.put("url", url);
    WebResponse response = (WebResponse) RequestCycle.get().getResponse();
    response.setContentType("application/json");
    response.setHeader("Cache-Control", "no-store, no-cache");
    response.getOutputStream().write(jsonFile.toString().getBytes(StandardCharsets.UTF_8));
    response.flush();/*from www .j  ava  2  s .com*/
}