Search in sources :

Example 81 with Servlet

use of javax.servlet.Servlet in project sling by apache.

the class DefaultGetServletTest method testDisabledAlias.

@Test
public void testDisabledAlias() throws Exception {
    final DefaultGetServlet servlet = new DefaultGetServlet();
    final DefaultGetServlet.Config config = Mockito.mock(DefaultGetServlet.Config.class);
    Mockito.when(config.enable_html()).thenReturn(true);
    Mockito.when(config.enable_json()).thenReturn(true);
    Mockito.when(config.enable_xml()).thenReturn(false);
    Mockito.when(config.enable_txt()).thenReturn(false);
    Mockito.when(config.aliases()).thenReturn(new String[] { "xml:pdf" });
    servlet.activate(config);
    servlet.init();
    final Field field = DefaultGetServlet.class.getDeclaredField("rendererMap");
    field.setAccessible(true);
    @SuppressWarnings("unchecked") final Map<String, Servlet> map = (Map<String, Servlet>) field.get(servlet);
    assertEquals(4, map.size());
    assertNotNull(map.get("res"));
    assertNotNull(map.get("html"));
    assertNotNull(map.get("json"));
    assertNotNull(map.get("pdf"));
}
Also used : Field(java.lang.reflect.Field) Servlet(javax.servlet.Servlet) Map(java.util.Map) Test(org.junit.Test)

Example 82 with Servlet

use of javax.servlet.Servlet in project sling by apache.

the class AuthorizablePrivilegesInfoImpl method canAddUser.

/* (non-Javadoc)
     * @see org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canAddUser(javax.jcr.Session)
     */
public boolean canAddUser(Session jcrSession) {
    try {
        //if self-registration is enabled, then anyone can create a user
        if (bundleContext != null) {
            String filter = "(&(sling.servlet.resourceTypes=sling/users)(|(sling.servlet.methods=POST)(sling.servlet.selectors=create)))";
            Collection<ServiceReference<Servlet>> serviceReferences = bundleContext.getServiceReferences(Servlet.class, filter);
            if (serviceReferences != null) {
                String propName = "self.registration.enabled";
                for (ServiceReference<Servlet> serviceReference : serviceReferences) {
                    Object propValue = serviceReference.getProperty(propName);
                    if (propValue != null) {
                        boolean selfRegEnabled = Boolean.TRUE.equals(propValue);
                        if (selfRegEnabled) {
                            return true;
                        }
                        break;
                    }
                }
            }
        }
        UserManager userManager = AccessControlUtil.getUserManager(jcrSession);
        Authorizable currentUser = userManager.getAuthorizable(jcrSession.getUserID());
        if (currentUser != null) {
            if (((User) currentUser).isAdmin()) {
                //admin user has full control
                return true;
            }
        }
    } catch (RepositoryException e) {
        log.warn("Failed to determine if {} can add a new user", jcrSession.getUserID());
    } catch (InvalidSyntaxException e) {
        log.warn("Failed to determine if {} can add a new user", jcrSession.getUserID());
    }
    return false;
}
Also used : User(org.apache.jackrabbit.api.security.user.User) UserManager(org.apache.jackrabbit.api.security.user.UserManager) Servlet(javax.servlet.Servlet) Authorizable(org.apache.jackrabbit.api.security.user.Authorizable) RepositoryException(javax.jcr.RepositoryException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ServiceReference(org.osgi.framework.ServiceReference)

Example 83 with Servlet

use of javax.servlet.Servlet in project sling by apache.

the class SlingServlet method startSling.

/**
     * Installs the launcher jar from the given URL (if not <code>null</code>)
     * and launches Sling from that launcher.
     */
private void startSling(URL launcherJar) {
    synchronized (this) {
        if (sling != null) {
            log("Apache Sling already started, nothing to do");
            return;
        } else if (startingSling != null) {
            log("Apache Sling being started by Thread " + startingSling);
            return;
        }
        startingSling = Thread.currentThread();
    }
    if (launcherJar != null) {
        try {
            log("Checking launcher JAR in " + slingHome);
            loader.installLauncherJar(launcherJar);
        } catch (IOException ioe) {
            startupFailure("Failed installing " + launcherJar, ioe);
            return;
        }
    } else {
        log("No Launcher JAR to install");
    }
    Object object = null;
    try {
        object = loader.loadLauncher(SharedConstants.DEFAULT_SLING_SERVLET);
    } catch (IllegalArgumentException iae) {
        startupFailure("Cannot load Launcher Servlet " + SharedConstants.DEFAULT_SLING_SERVLET, iae);
        return;
    }
    if (object instanceof Servlet) {
        Servlet sling = (Servlet) object;
        if (sling instanceof Launcher) {
            Launcher slingLauncher = (Launcher) sling;
            slingLauncher.setNotifiable(this);
            slingLauncher.setCommandLine(properties);
            slingLauncher.setSlingHome(slingHome);
        }
        try {
            log("Starting launcher ...");
            sling.init(getServletConfig());
            this.sling = sling;
            this.startFailureCounter = 0;
            log("Startup completed");
        } catch (ServletException se) {
            startupFailure(null, se);
        }
    }
    // reset the starting flag
    synchronized (this) {
        startingSling = null;
    }
}
Also used : ServletException(javax.servlet.ServletException) Servlet(javax.servlet.Servlet) GenericServlet(javax.servlet.GenericServlet) Launcher(org.apache.sling.launchpad.base.shared.Launcher) IOException(java.io.IOException)

Example 84 with Servlet

use of javax.servlet.Servlet in project sling by apache.

the class ServletWrapper method compile.

/**
     * Compile the servlet java class. If the compiled class has
     * injected fields, don't create an instance of it.
     */
private void compile() throws Exception {
    logger.debug("Compiling {}", this.sourcePath);
    // clear exception
    this.compileException = null;
    try {
        final CompilerOptions opts = this.ioProvider.getForceCompileOptions();
        final CompilationUnit unit = new CompilationUnit(this.sourcePath, className, ioProvider);
        final CompilationResult result = this.ioProvider.getCompiler().compile(new org.apache.sling.commons.compiler.CompilationUnit[] { unit }, opts);
        final List<CompilerMessage> errors = result.getErrors();
        this.destroy();
        if (errors != null && errors.size() > 0) {
            throw CompilerException.create(errors, this.sourcePath);
        }
        final Servlet servlet = (Servlet) result.loadCompiledClass(this.className).newInstance();
        servlet.init(this.config);
        this.injectFields(servlet);
        this.theServlet = servlet;
    } catch (final Exception ex) {
        // store exception for futher access attempts
        this.compileException = ex;
        throw ex;
    }
}
Also used : CompilerMessage(org.apache.sling.commons.compiler.CompilerMessage) Servlet(javax.servlet.Servlet) CompilationResult(org.apache.sling.commons.compiler.CompilationResult) ServletException(javax.servlet.ServletException) UnavailableException(javax.servlet.UnavailableException)

Example 85 with Servlet

use of javax.servlet.Servlet in project sling by apache.

the class ServletWrapper method service.

/**
     * Call the servlet.
     * @param request The current request.
     * @param response The current response.
     * @throws Exception
     */
public void service(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            if (available > System.currentTimeMillis()) {
                response.setDateHeader("Retry-After", available);
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Servlet unavailable.");
                logger.error("Java servlet {} is unavailable.", this.sourcePath);
                return;
            }
            // Wait period has expired. Reset.
            available = 0;
        }
        final Servlet servlet = this.getServlet();
        // invoke the servlet
        if (servlet instanceof SingleThreadModel) {
            // of the page is determined right before servicing
            synchronized (this) {
                servlet.service(request, response);
            }
        } else {
            servlet.service(request, response);
        }
    } catch (final UnavailableException ex) {
        int unavailableSeconds = ex.getUnavailableSeconds();
        if (unavailableSeconds <= 0) {
            // Arbitrary default
            unavailableSeconds = 60;
        }
        available = System.currentTimeMillis() + (unavailableSeconds * 1000L);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage());
        logger.error("Java servlet {} is unavailable.", this.sourcePath);
    }
}
Also used : UnavailableException(javax.servlet.UnavailableException) Servlet(javax.servlet.Servlet) SingleThreadModel(javax.servlet.SingleThreadModel)

Aggregations

Servlet (javax.servlet.Servlet)86 Test (org.junit.Test)18 HttpServlet (javax.servlet.http.HttpServlet)16 ServletException (javax.servlet.ServletException)15 IOException (java.io.IOException)11 OptingServlet (org.apache.sling.api.servlets.OptingServlet)11 GenericServlet (javax.servlet.GenericServlet)10 DefaultErrorHandlerServlet (org.apache.sling.servlets.resolver.internal.defaults.DefaultErrorHandlerServlet)9 DefaultServlet (org.apache.sling.servlets.resolver.internal.defaults.DefaultServlet)9 ServletContext (javax.servlet.ServletContext)8 UnavailableException (javax.servlet.UnavailableException)8 Resource (org.apache.sling.api.resource.Resource)8 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)8 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)7 MockServletWebServerFactory (org.springframework.boot.web.servlet.server.MockServletWebServerFactory)7 ServletInfo (io.undertow.servlet.api.ServletInfo)6 ArrayList (java.util.ArrayList)5 Filter (javax.servlet.Filter)5 Context (org.apache.catalina.Context)5 SlingHttpServletResponse (org.apache.sling.api.SlingHttpServletResponse)5