Search in sources :

Example 1 with AbstractResource

use of org.apache.wicket.request.resource.AbstractResource in project wicket by apache.

the class WicketFilterTest method options.

@Test
public void options() throws IOException, ServletException, ParseException {
    try {
        application = new MockApplication();
        WicketFilter filter = new WicketFilter();
        filter.init(new FilterTestingConfig());
        ThreadContext.setApplication(application);
        final String failure = "Should never get here when an OPTIONS request is issued";
        IResource resource = new AbstractResource() {

            @Override
            protected ResourceResponse newResourceResponse(Attributes attributes) {
                fail(failure);
                return null;
            }
        };
        application.getSharedResources().add("foo.txt", resource);
        // check OPTIONS request is processed correctly
        MockHttpServletRequest request = new MockHttpServletRequest(application, null, null);
        request.setURL(request.getContextPath() + request.getServletPath() + "/wicket/resource/" + Application.class.getName() + "/foo.txt");
        // test that we do not care about case
        request.setMethod("OPtioNS");
        MockHttpServletResponse response = new MockHttpServletResponse(request);
        filter.doFilter(request, response, new FilterChain() {

            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
            }
        });
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        assertEquals("0", response.getHeader("Content-Length"));
        assertFalse(Strings.isEmpty(response.getHeader("Allow")));
        assertTrue(response.getHeader("Allow").toUpperCase().contains("GET"));
        assertTrue(response.getHeader("Allow").toUpperCase().contains("POST"));
        // try with a GET request to make sure we fail correctly
        request = new MockHttpServletRequest(application, null, null);
        request.setURL(request.getContextPath() + request.getServletPath() + "/wicket/resource/" + Application.class.getName() + "/foo.txt");
        response = new MockHttpServletResponse(request);
        try {
            filter.doFilter(request, response, new FilterChain() {

                @Override
                public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
                }
            });
        } catch (AssertionError e) {
            assertTrue(failure.equals(e.getMessage()));
        }
    } finally {
        ThreadContext.detach();
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) MockHttpServletRequest(org.apache.wicket.protocol.http.mock.MockHttpServletRequest) MockHttpServletResponse(org.apache.wicket.protocol.http.mock.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) MockApplication(org.apache.wicket.mock.MockApplication) MockHttpServletRequest(org.apache.wicket.protocol.http.mock.MockHttpServletRequest) FilterChain(javax.servlet.FilterChain) AbstractResource(org.apache.wicket.request.resource.AbstractResource) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) MockApplication(org.apache.wicket.mock.MockApplication) Application(org.apache.wicket.Application) IResource(org.apache.wicket.request.resource.IResource) MockHttpServletResponse(org.apache.wicket.protocol.http.mock.MockHttpServletResponse) Test(org.junit.Test)

Example 2 with AbstractResource

use of org.apache.wicket.request.resource.AbstractResource in project syncope by apache.

the class SyncopeEnduserApplication method init.

@Override
protected void init() {
    super.init();
    // read enduser.properties
    Properties props = PropertyUtils.read(getClass(), ENDUSER_PROPERTIES, "enduser.directory").getLeft();
    domain = props.getProperty("domain", SyncopeConstants.MASTER_DOMAIN);
    adminUser = props.getProperty("adminUser");
    Args.notNull(adminUser, "<adminUser>");
    anonymousUser = props.getProperty("anonymousUser");
    Args.notNull(anonymousUser, "<anonymousUser>");
    anonymousKey = props.getProperty("anonymousKey");
    Args.notNull(anonymousKey, "<anonymousKey>");
    captchaEnabled = Boolean.parseBoolean(props.getProperty("captcha"));
    Args.notNull(captchaEnabled, "<captcha>");
    xsrfEnabled = Boolean.parseBoolean(props.getProperty("xsrf"));
    Args.notNull(xsrfEnabled, "<xsrf>");
    String scheme = props.getProperty("scheme");
    Args.notNull(scheme, "<scheme>");
    String host = props.getProperty("host");
    Args.notNull(host, "<host>");
    String port = props.getProperty("port");
    Args.notNull(port, "<port>");
    String rootPath = props.getProperty("rootPath");
    Args.notNull(rootPath, "<rootPath>");
    String useGZIPCompression = props.getProperty("useGZIPCompression");
    Args.notNull(useGZIPCompression, "<useGZIPCompression>");
    maxUploadFileSizeMB = props.getProperty("maxUploadFileSizeMB") == null ? null : Integer.valueOf(props.getProperty("maxUploadFileSizeMB"));
    clientFactory = new SyncopeClientFactoryBean().setAddress(scheme + "://" + host + ":" + port + "/" + rootPath).setContentType(SyncopeClientFactoryBean.ContentType.JSON).setUseCompression(BooleanUtils.toBoolean(useGZIPCompression));
    // read customForm.json
    try (InputStream is = getClass().getResourceAsStream("/" + CUSTOM_FORM_FILE)) {
        customForm = MAPPER.readValue(is, new TypeReference<HashMap<String, CustomAttributesInfo>>() {
        });
        File enduserDir = new File(props.getProperty("enduser.directory"));
        boolean existsEnduserDir = enduserDir.exists() && enduserDir.canRead() && enduserDir.isDirectory();
        if (existsEnduserDir) {
            File customFormFile = FileUtils.getFile(enduserDir, CUSTOM_FORM_FILE);
            if (customFormFile.exists() && customFormFile.canRead() && customFormFile.isFile()) {
                customForm = MAPPER.readValue(FileUtils.openInputStream(customFormFile), new TypeReference<HashMap<String, CustomAttributesInfo>>() {
                });
            }
        }
        FileAlterationObserver observer = existsEnduserDir ? new FileAlterationObserver(enduserDir, pathname -> StringUtils.contains(pathname.getPath(), CUSTOM_FORM_FILE)) : new FileAlterationObserver(getClass().getResource("/" + CUSTOM_FORM_FILE).getFile(), pathname -> StringUtils.contains(pathname.getPath(), CUSTOM_FORM_FILE));
        FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
        FileAlterationListener listener = new FileAlterationListenerAdaptor() {

            @Override
            public void onFileChange(final File file) {
                try {
                    LOG.trace("{} has changed. Reloading form customization configuration.", CUSTOM_FORM_FILE);
                    customForm = MAPPER.readValue(FileUtils.openInputStream(file), new TypeReference<HashMap<String, CustomAttributesInfo>>() {
                    });
                } catch (IOException e) {
                    e.printStackTrace(System.err);
                }
            }

            @Override
            public void onFileCreate(final File file) {
                try {
                    LOG.trace("{} has been created. Loading form customization configuration.", CUSTOM_FORM_FILE);
                    customForm = MAPPER.readValue(FileUtils.openInputStream(file), new TypeReference<HashMap<String, CustomAttributesInfo>>() {
                    });
                } catch (IOException e) {
                    e.printStackTrace(System.err);
                }
            }

            @Override
            public void onFileDelete(final File file) {
                LOG.trace("{} has been deleted. Resetting form customization configuration.", CUSTOM_FORM_FILE);
                customForm = null;
            }
        };
        observer.addListener(listener);
        monitor.addObserver(observer);
        monitor.start();
    } catch (Exception e) {
        throw new WicketRuntimeException("Could not read " + CUSTOM_FORM_FILE, e);
    }
    // mount resources
    ClassPathScanImplementationLookup classPathScanImplementationLookup = (ClassPathScanImplementationLookup) getServletContext().getAttribute(EnduserInitializer.CLASSPATH_LOOKUP);
    for (final Class<? extends AbstractResource> resource : classPathScanImplementationLookup.getResources()) {
        Resource annotation = resource.getAnnotation(Resource.class);
        if (annotation == null) {
            LOG.debug("No @Resource annotation found on {}, ignoring", resource.getName());
        } else {
            try {
                final AbstractResource instance = resource.newInstance();
                mountResource(annotation.path(), new ResourceReference(annotation.key()) {

                    private static final long serialVersionUID = -128426276529456602L;

                    @Override
                    public IResource getResource() {
                        return instance;
                    }
                });
            } catch (Exception e) {
                LOG.error("Could not instantiate {}", resource.getName(), e);
            }
        }
    }
    // mount captcha resource only if captcha is enabled
    if (captchaEnabled) {
        mountResource("/api/captcha", new ResourceReference("captcha") {

            private static final long serialVersionUID = -128426276529456602L;

            @Override
            public IResource getResource() {
                return new CaptchaResource();
            }
        });
    }
}
Also used : Page(org.apache.wicket.Page) FileAlterationObserver(org.apache.commons.io.monitor.FileAlterationObserver) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ClassPathScanImplementationLookup(org.apache.syncope.client.enduser.init.ClassPathScanImplementationLookup) SyncopeClientFactoryBean(org.apache.syncope.client.lib.SyncopeClientFactoryBean) StringUtils(org.apache.commons.lang3.StringUtils) FileAlterationListenerAdaptor(org.apache.commons.io.monitor.FileAlterationListenerAdaptor) IResource(org.apache.wicket.request.resource.IResource) Map(java.util.Map) HomePage(org.apache.syncope.client.enduser.pages.HomePage) Response(org.apache.wicket.request.Response) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Request(org.apache.wicket.request.Request) ResourceReference(org.apache.wicket.request.resource.ResourceReference) SyncopeConstants(org.apache.syncope.common.lib.SyncopeConstants) Properties(java.util.Properties) Logger(org.slf4j.Logger) FileAlterationListener(org.apache.commons.io.monitor.FileAlterationListener) FileAlterationMonitor(org.apache.commons.io.monitor.FileAlterationMonitor) WicketRuntimeException(org.apache.wicket.WicketRuntimeException) Args(org.apache.wicket.util.lang.Args) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) AbstractResource(org.apache.wicket.request.resource.AbstractResource) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) File(java.io.File) Serializable(java.io.Serializable) PropertyUtils(org.apache.syncope.common.lib.PropertyUtils) WebApplication(org.apache.wicket.protocol.http.WebApplication) CaptchaResource(org.apache.syncope.client.enduser.resources.CaptchaResource) Session(org.apache.wicket.Session) CustomAttributesInfo(org.apache.syncope.client.enduser.model.CustomAttributesInfo) Resource(org.apache.syncope.client.enduser.annotations.Resource) EnduserInitializer(org.apache.syncope.client.enduser.init.EnduserInitializer) InputStream(java.io.InputStream) FileAlterationMonitor(org.apache.commons.io.monitor.FileAlterationMonitor) AbstractResource(org.apache.wicket.request.resource.AbstractResource) CaptchaResource(org.apache.syncope.client.enduser.resources.CaptchaResource) Properties(java.util.Properties) FileAlterationObserver(org.apache.commons.io.monitor.FileAlterationObserver) ClassPathScanImplementationLookup(org.apache.syncope.client.enduser.init.ClassPathScanImplementationLookup) SyncopeClientFactoryBean(org.apache.syncope.client.lib.SyncopeClientFactoryBean) FileAlterationListener(org.apache.commons.io.monitor.FileAlterationListener) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ResourceReference(org.apache.wicket.request.resource.ResourceReference) CustomAttributesInfo(org.apache.syncope.client.enduser.model.CustomAttributesInfo) InputStream(java.io.InputStream) WicketRuntimeException(org.apache.wicket.WicketRuntimeException) IResource(org.apache.wicket.request.resource.IResource) AbstractResource(org.apache.wicket.request.resource.AbstractResource) CaptchaResource(org.apache.syncope.client.enduser.resources.CaptchaResource) Resource(org.apache.syncope.client.enduser.annotations.Resource) IOException(java.io.IOException) WicketRuntimeException(org.apache.wicket.WicketRuntimeException) IOException(java.io.IOException) FileAlterationListenerAdaptor(org.apache.commons.io.monitor.FileAlterationListenerAdaptor) File(java.io.File) IResource(org.apache.wicket.request.resource.IResource)

Example 3 with AbstractResource

use of org.apache.wicket.request.resource.AbstractResource in project syncope by apache.

the class ClassPathScanImplementationLookup method load.

@SuppressWarnings("unchecked")
public void load() {
    resources = new ArrayList<>();
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AssignableTypeFilter(AbstractResource.class));
    for (BeanDefinition bd : scanner.findCandidateComponents(getBasePackage())) {
        try {
            Class<?> clazz = ClassUtils.resolveClassName(bd.getBeanClassName(), ClassUtils.getDefaultClassLoader());
            boolean isAbsractClazz = Modifier.isAbstract(clazz.getModifiers());
            if (!isAbsractClazz) {
                if (AbstractResource.class.isAssignableFrom(clazz)) {
                    if (clazz.isAnnotationPresent(Resource.class)) {
                        resources.add((Class<? extends AbstractResource>) clazz);
                    } else {
                        LOG.error("Could not find annotation {} in {}, ignoring", Resource.class.getName(), clazz.getName());
                    }
                }
            }
        } catch (Throwable t) {
            LOG.warn("Could not inspect class {}", bd.getBeanClassName(), t);
        }
    }
    resources = Collections.unmodifiableList(resources);
}
Also used : ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) AbstractResource(org.apache.wicket.request.resource.AbstractResource) Resource(org.apache.syncope.client.enduser.annotations.Resource) AbstractResource(org.apache.wicket.request.resource.AbstractResource) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) AssignableTypeFilter(org.springframework.core.type.filter.AssignableTypeFilter)

Example 4 with AbstractResource

use of org.apache.wicket.request.resource.AbstractResource in project wicket by apache.

the class MapperDemoResourceReference method getResource.

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

        private static final long serialVersionUID = 1L;

        @Override
        protected ResourceResponse newResourceResponse(Attributes attributes) {
            ResourceResponse resourceResponse = new ResourceResponse();
            PageParameters parameters = attributes.getParameters();
            StringValue sheetParam = parameters.get("sheet");
            StringValue formatParam = parameters.get("format");
            final String responseText = String.format("You just printed sheet '%s' in format '%s'.\n\n\nPress browser's back button to go to the examples.", sheetParam, formatParam);
            resourceResponse.setContentType("text/plain");
            resourceResponse.setContentLength(responseText.length());
            resourceResponse.setWriteCallback(new WriteCallback() {

                @Override
                public void writeData(Attributes attributes) {
                    attributes.getResponse().write(responseText);
                }
            });
            return resourceResponse;
        }
    };
}
Also used : AbstractResource(org.apache.wicket.request.resource.AbstractResource) PageParameters(org.apache.wicket.request.mapper.parameter.PageParameters) StringValue(org.apache.wicket.util.string.StringValue)

Example 5 with AbstractResource

use of org.apache.wicket.request.resource.AbstractResource in project midpoint by Evolveum.

the class UserMenuPanel method initLayout.

private void initLayout() {
    WebMarkupContainer iconBox = new WebMarkupContainer(ID_ICON_BOX);
    add(iconBox);
    IModel<AbstractResource> jpegPhotoModel = loadJpegPhotoModel();
    NonCachingImage img = new NonCachingImage(ID_PHOTO, jpegPhotoModel);
    iconBox.add(img);
    Label usernameLink = new Label(ID_USERNAME_LINK, (IModel<String>) this::getShortUserName);
    add(usernameLink);
    WebMarkupContainer panelIconBox = new WebMarkupContainer(ID_PANEL_ICON_BOX);
    add(panelIconBox);
    NonCachingImage panelImg = new NonCachingImage(ID_PANEL_PHOTO, jpegPhotoModel);
    panelIconBox.add(panelImg);
    Label username = new Label(ID_USERNAME, (IModel<String>) this::getShortUserName);
    username.setRenderBodyOnly(true);
    add(username);
    Label focusType = new Label(ID_FOCUS_TYPE, getPageBase().createStringResource("PageTemplate." + getFocusType()));
    add(focusType);
    MidpointForm<?> form = new MidpointForm<>(ID_LOGOUT_FORM);
    form.add(AttributeModifier.replace("action", (IModel<String>) () -> SecurityUtils.getPathForLogoutWithContextPath(getRequest().getContextPath(), getAuthenticatedModule().getPrefix())));
    add(form);
    WebMarkupContainer csrfField = SecurityUtils.createHiddenInputForCsrf(ID_CSRF_FIELD);
    form.add(csrfField);
}
Also used : IModel(org.apache.wicket.model.IModel) NonCachingImage(org.apache.wicket.markup.html.image.NonCachingImage) Label(org.apache.wicket.markup.html.basic.Label) MidpointForm(com.evolveum.midpoint.web.component.form.MidpointForm) AbstractResource(org.apache.wicket.request.resource.AbstractResource) WebMarkupContainer(org.apache.wicket.markup.html.WebMarkupContainer)

Aggregations

AbstractResource (org.apache.wicket.request.resource.AbstractResource)5 IOException (java.io.IOException)2 Resource (org.apache.syncope.client.enduser.annotations.Resource)2 IResource (org.apache.wicket.request.resource.IResource)2 MidpointForm (com.evolveum.midpoint.web.component.form.MidpointForm)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 File (java.io.File)1 InputStream (java.io.InputStream)1 Serializable (java.io.Serializable)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Properties (java.util.Properties)1 FilterChain (javax.servlet.FilterChain)1 ServletException (javax.servlet.ServletException)1 ServletRequest (javax.servlet.ServletRequest)1 ServletResponse (javax.servlet.ServletResponse)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 FileUtils (org.apache.commons.io.FileUtils)1