Example usage for org.apache.wicket.request.resource AbstractResource AbstractResource

List of usage examples for org.apache.wicket.request.resource AbstractResource AbstractResource

Introduction

In this page you can find the example usage for org.apache.wicket.request.resource AbstractResource AbstractResource.

Prototype

public AbstractResource() 

Source Link

Document

Construct.

Usage

From source file:org.apache.openmeetings.web.util.RecordingResourceReference.java

License:Apache License

@Override
public IResource getResource() {
    return new AbstractResource() {
        private static final long serialVersionUID = 1L;
        private final static String ACCEPT_RANGES_HEADER = "Accept-Ranges";
        private final static String RANGE_HEADER = "Range";
        private final static String CONTENT_RANGE_HEADER = "Content-Range";
        private final static String RANGES_BYTES = "bytes";
        private File file;
        private boolean isRange = false;
        private long start = 0;
        private long end = 0;

        private long getChunkLength() {
            return isRange ? end - start + 1 : (file == null ? -1 : file.length());
        }//from  w w w  .j a v a 2  s.  com

        private IResourceStream getResourceStream() {
            return file == null ? null : new FileResourceStream(file) {
                private static final long serialVersionUID = 2546785247219805747L;
                private transient BoundedInputStream bi;

                @Override
                public InputStream getInputStream() throws ResourceStreamNotFoundException {
                    if (bi == null) {
                        //bi = new BoundedInputStream(super.getInputStream(), end + 1);
                        bi = new BoundedInputStream(super.getInputStream(),
                                isRange ? end + 1 : (file == null ? -1 : file.length()));
                        try {
                            bi.skip(start);
                        } catch (IOException e) {
                            throw new ResourceStreamNotFoundException(e);
                        }
                    }
                    return bi;
                }

                @Override
                public Bytes length() {
                    return Bytes.bytes(getChunkLength());
                }

                @Override
                public void close() throws IOException {
                    if (bi != null) {
                        bi.close(); //also will close original stream
                        bi = null;
                    }
                }

                @Override
                public String getContentType() {
                    return RecordingResourceReference.this.getContentType();
                }
            };
        }

        @Override
        protected void setResponseHeaders(ResourceResponse data, Attributes attributes) {
            Response response = attributes.getResponse();
            if (response instanceof WebResponse) {
                WebResponse webResponse = (WebResponse) response;
                webResponse.setStatus(
                        isRange ? HttpServletResponse.SC_PARTIAL_CONTENT : HttpServletResponse.SC_OK);
            }
            super.setResponseHeaders(data, attributes);
        }

        @Override
        protected ResourceResponse newResourceResponse(Attributes attributes) {
            ResourceResponse rr = new ResourceResponse();
            FlvRecording r = getRecording(attributes);
            if (r != null) {
                isRange = false;
                file = getFile(r);
                rr.setFileName(getFileName(r));
                rr.setContentType(RecordingResourceReference.this.getContentType());
                rr.setContentDisposition(ContentDisposition.INLINE);
                rr.setLastModified(Time.millis(file.lastModified()));
                rr.getHeaders().addHeader(ACCEPT_RANGES_HEADER, RANGES_BYTES);
                String range = ((HttpServletRequest) attributes.getRequest().getContainerRequest())
                        .getHeader(RANGE_HEADER);
                if (range != null && range.startsWith(RANGES_BYTES)) {
                    String[] bounds = range.substring(RANGES_BYTES.length() + 1).split("-");
                    if (bounds != null && bounds.length > 0) {
                        long length = file.length();
                        isRange = true;
                        start = Long.parseLong(bounds[0]);
                        end = bounds.length > 1 ? Long.parseLong(bounds[1]) : length - 1;
                        //Content-Range: bytes 229376-232468/232469
                        rr.getHeaders().addHeader(CONTENT_RANGE_HEADER,
                                String.format("%s %d-%d/%d", RANGES_BYTES, start, end, length));
                    }
                }
                rr.setContentLength(getChunkLength());
                rr.setWriteCallback(new WriteCallback() {
                    @Override
                    public void writeData(Attributes attributes) throws IOException {
                        IResourceStream rStream = getResourceStream();
                        try {
                            writeStream(attributes, rStream.getInputStream());
                        } catch (ResourceStreamNotFoundException e1) {
                        } catch (ResponseIOException e) {
                            // in case of range operations we expecting such exceptions
                            if (!isRange) {
                                log.error("Error while playing the stream", e);
                            }
                        } finally {
                            rStream.close();
                        }
                    }
                });
            } else {
                rr.setError(HttpServletResponse.SC_NOT_FOUND);
            }
            return rr;
        }
    };
}

From source file:org.geoserver.wms.web.data.StyleAdminPanel.java

License:Open Source License

public void initUI(CompoundPropertyModel<StyleInfo> styleModel) {

    StyleInfo style = getStylePage().getStyleInfo();

    IModel<String> nameBinding = styleModel.bind("name");

    add(nameTextField = new TextField<String>("name", nameBinding));
    nameTextField.setRequired(true);/*from  w  ww .j  a va  2s .com*/

    IModel<WorkspaceInfo> wsBinding = styleModel.bind("workspace");
    wsChoice = new DropDownChoice<WorkspaceInfo>("workspace", wsBinding, new WorkspacesModel(),
            new WorkspaceChoiceRenderer());
    wsChoice.setNullValid(true);
    if (!stylePage.isAuthenticatedAsAdmin()) {
        wsChoice.setNullValid(false);
        wsChoice.setRequired(true);
    }

    add(wsChoice);

    //always disable the workspace toggle if not admin
    if (!stylePage.isAuthenticatedAsAdmin()) {
        wsChoice.setEnabled(false);
    }

    IModel<String> formatBinding = styleModel.bind("format");
    formatChoice = new DropDownChoice<String>("format", formatBinding, new StyleFormatsModel(),
            new ChoiceRenderer<String>() {

                private static final long serialVersionUID = 2064887235303504013L;

                @Override
                public String getIdValue(String object, int index) {
                    return object;
                }

                @Override
                public Object getDisplayValue(String object) {
                    return Styles.handler(object).getName();
                }
            });
    formatChoice.add(new AjaxFormComponentUpdatingBehavior("change") {

        private static final long serialVersionUID = -8372146231225388561L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            target.appendJavaScript(String.format(
                    "if (document.gsEditors) { document.gsEditors.editor.setOption('mode', '%s'); }",
                    stylePage.styleHandler().getCodeMirrorEditMode()));
        }
    });
    add(formatChoice);

    formatReadOnlyMessage = new WebMarkupContainer("formatReadOnly", new Model<String>());
    formatReadOnlyMessage.setVisible(false);
    add(formatReadOnlyMessage);
    // add the Legend fields        
    legendPanel = new ExternalGraphicPanel("legendPanel", styleModel, stylePage.styleForm);
    legendPanel.setOutputMarkupId(true);
    add(legendPanel);
    if (style.getId() != null) {
        try {
            stylePage.setRawStyle(stylePage.readFile(style));
        } catch (IOException e) {
            // ouch, the style file is gone! Register a generic error message
            Session.get().error(new ParamResourceModel("styleNotFound", this, style.getFilename()).getString());
        }
    }

    // style generation functionality
    templates = new DropDownChoice<StyleType>("templates", new Model<StyleType>(), new StyleTypeModel(),
            new StyleTypeChoiceRenderer());
    templates.setOutputMarkupId(true);
    templates.add(new AjaxFormComponentUpdatingBehavior("change") {

        private static final long serialVersionUID = -6649152103570059645L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            templates.validate();
            generateLink.setEnabled(templates.getConvertedInput() != null);
            target.add(generateLink);
        }
    });
    add(templates);
    generateLink = generateLink();
    generateLink.setEnabled(false);
    add(generateLink);

    // style copy functionality
    styles = new DropDownChoice<StyleInfo>("existingStyles", new Model<StyleInfo>(), new StylesModel(),
            new StyleChoiceRenderer());
    styles.setOutputMarkupId(true);
    styles.add(new AjaxFormComponentUpdatingBehavior("change") {

        private static final long serialVersionUID = 8098121930876372129L;

        @Override
        protected void onUpdate(AjaxRequestTarget target) {
            styles.validate();
            copyLink.setEnabled(styles.getConvertedInput() != null);
            target.add(copyLink);
        }
    });
    add(styles);
    copyLink = copyLink();
    copyLink.setEnabled(false);
    add(copyLink);

    uploadLink = uploadLink();
    //uploadLink.setEnabled(false);
    add(uploadLink);

    fileUploadField = new FileUploadField("filename");
    //Explicitly set model so this doesn't use the form model
    fileUploadField.setDefaultModel(new Model<String>(""));
    add(fileUploadField);

    add(previewLink());

    legendContainer = new WebMarkupContainer("legendContainer");
    legendContainer.setOutputMarkupId(true);
    add(legendContainer);
    this.legendImg = new Image("legendImg", new AbstractResource() {

        private static final long serialVersionUID = -6932528694575832606L;

        @Override
        protected ResourceResponse newResourceResponse(Attributes attributes) {
            ResourceResponse rr = new ResourceResponse();
            rr.setContentType("image/png");
            rr.setWriteCallback(new WriteCallback() {
                @Override
                public void writeData(Attributes attributes) throws IOException {
                    ImageIO.write(legendImage, "PNG", attributes.getResponse().getOutputStream());
                }
            });
            return rr;
        }
    });
    legendContainer.add(this.legendImg);
    this.legendImg.setVisible(false);
    this.legendImg.setOutputMarkupId(true);
}

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

License:Apache License

/**
 * Registra um recurso compartilhado do wicket para permitir o download
 * sem bloquear a fila de ajax do wicket.
 * O recurso compartilhado  removido to logo o download  executado
 * Esse procedimento visa garantir que somente quem tem acesso  pgina pode fazer
 * download dos arquivos.//from www  . j a  v  a 2 s  . co  m
 *
 * @param filename
 * @return
 */
private String getDownloadURL(String id, String filename) {
    String url = DOWNLOAD_PATH + "/" + id + "/" + new Date().getTime();
    SharedResourceReference ref = new SharedResourceReference(String.valueOf(id));
    AbstractResource resource = new AbstractResource() {
        @Override
        protected ResourceResponse newResourceResponse(Attributes attributes) {
            IAttachmentRef fileRef = findAttachmentRef(id);
            if (fileRef == null) {
                return new ResourceResponse().setStatusCode(HttpServletResponse.SC_NOT_FOUND);
            }
            ResourceResponse resourceResponse = new ResourceResponse();
            if (fileRef.getSize() > 0) {
                resourceResponse.setContentLength(fileRef.getSize());
            }
            resourceResponse.setFileName(filename);
            try {
                resourceResponse.setContentDisposition(contentDisposition);
                resourceResponse.setContentType(fileRef.getContentType());
                resourceResponse.setWriteCallback(new WriteCallback() {
                    @Override
                    public void writeData(Attributes attributes) throws IOException {
                        try (InputStream inputStream = fileRef.getContentAsInputStream()) {
                            IOUtils.copy(inputStream, attributes.getResponse().getOutputStream());
                            /*Desregistrando recurso compartilhado*/
                            WebApplication.get().unmount(url);
                            WebApplication.get().getSharedResources().remove(ref.getKey());
                        } catch (Exception e) {
                            getLogger().error("Erro ao recuperar arquivo.", e);
                            ((WebResponse) attributes.getResponse())
                                    .setStatus(HttpServletResponse.SC_NOT_FOUND);
                            resourceResponse.setStatusCode(HttpServletResponse.SC_NOT_FOUND);
                        }
                    }
                });
            } catch (Exception e) {
                getLogger().error("Erro ao recuperar arquivo.", e);
                resourceResponse.setStatusCode(HttpServletResponse.SC_NOT_FOUND);
            }
            return resourceResponse;
        }
    };
    /*registrando recurso compartilhado*/
    WebApplication.get().getSharedResources().add(String.valueOf(id), resource);
    WebApplication.get().mountResource(url, ref);
    String path = WebApplication.get().getServletContext().getContextPath() + "/"
            + WebApplication.get().getWicketFilter().getFilterPath() + url;
    path = path.replaceAll("\\*", "").replaceAll("//", "/");
    return path;
}

From source file:org.wicketstuff.html5.media.webvtt.VttResourceReference.java

License:Apache License

@Override
public IResource getResource() {
    return new AbstractResource() {

        private static final long serialVersionUID = 1L;

        @Override/*w ww .ja v  a 2 s .com*/
        protected ResourceResponse newResourceResponse(Attributes attributes) {
            ResourceResponse resourceResponse = new ResourceResponse();
            resourceResponse.setContentType("text/vtt");
            resourceResponse.setTextEncoding("UTF-8");
            resourceResponse.setWriteCallback(new WriteCallback() {
                @Override
                public void writeData(Attributes attributes) throws IOException {
                    OutputStream outputStream = attributes.getResponse().getOutputStream();
                    Streams.copy(new ByteArrayInputStream(getWebVtt().create().getBytes()), outputStream);
                }
            });
            return resourceResponse;
        }
    };
}