Search in sources :

Example 81 with ServletContext

use of javax.servlet.ServletContext in project spring-framework by spring-projects.

the class ViewResolverTests method testXmlViewResolver.

@Test
public void testXmlViewResolver() throws Exception {
    StaticWebApplicationContext wac = new StaticWebApplicationContext();
    wac.registerSingleton("testBean", TestBean.class);
    wac.setServletContext(new MockServletContext());
    wac.refresh();
    TestBean testBean = (TestBean) wac.getBean("testBean");
    XmlViewResolver vr = new XmlViewResolver();
    vr.setLocation(new ClassPathResource("org/springframework/web/servlet/view/views.xml"));
    vr.setApplicationContext(wac);
    View view1 = vr.resolveViewName("example1", Locale.getDefault());
    assertTrue("Correct view class", TestView.class.equals(view1.getClass()));
    assertTrue("Correct URL", "/example1.jsp".equals(((InternalResourceView) view1).getUrl()));
    View view2 = vr.resolveViewName("example2", Locale.getDefault());
    assertTrue("Correct view class", JstlView.class.equals(view2.getClass()));
    assertTrue("Correct URL", "/example2new.jsp".equals(((InternalResourceView) view2).getUrl()));
    ServletContext sc = new MockServletContext();
    Map model = new HashMap();
    TestBean tb = new TestBean();
    model.put("tb", tb);
    HttpServletRequest request = new MockHttpServletRequest(sc);
    HttpServletResponse response = new MockHttpServletResponse();
    request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
    request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, new FixedThemeResolver());
    view1.render(model, request, response);
    assertTrue("Correct tb attribute", tb.equals(request.getAttribute("tb")));
    assertTrue("Correct test1 attribute", "testvalue1".equals(request.getAttribute("test1")));
    assertTrue("Correct test2 attribute", testBean.equals(request.getAttribute("test2")));
    request = new MockHttpServletRequest(sc);
    response = new MockHttpServletResponse();
    request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
    request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, new FixedThemeResolver());
    view2.render(model, request, response);
    assertTrue("Correct tb attribute", tb.equals(request.getAttribute("tb")));
    assertTrue("Correct test1 attribute", "testvalue1".equals(request.getAttribute("test1")));
    assertTrue("Correct test2 attribute", "testvalue2".equals(request.getAttribute("test2")));
}
Also used : HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) View(org.springframework.web.servlet.View) AcceptHeaderLocaleResolver(org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver) MockServletContext(org.springframework.mock.web.test.MockServletContext) ClassPathResource(org.springframework.core.io.ClassPathResource) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) TestBean(org.springframework.tests.sample.beans.TestBean) FixedThemeResolver(org.springframework.web.servlet.theme.FixedThemeResolver) MockServletContext(org.springframework.mock.web.test.MockServletContext) ServletContext(javax.servlet.ServletContext) HashMap(java.util.HashMap) Map(java.util.Map) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) Test(org.junit.Test)

Example 82 with ServletContext

use of javax.servlet.ServletContext in project hadoop by apache.

the class FsckServlet method doGet.

/** Handle fsck request */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    @SuppressWarnings("unchecked") final Map<String, String[]> pmap = request.getParameterMap();
    final PrintWriter out = response.getWriter();
    final InetAddress remoteAddress = InetAddress.getByName(request.getRemoteAddr());
    final ServletContext context = getServletContext();
    final Configuration conf = NameNodeHttpServer.getConfFromContext(context);
    final UserGroupInformation ugi = getUGI(request, conf);
    try {
        ugi.doAs(new PrivilegedExceptionAction<Object>() {

            @Override
            public Object run() throws Exception {
                NameNode nn = NameNodeHttpServer.getNameNodeFromContext(context);
                final FSNamesystem namesystem = nn.getNamesystem();
                final BlockManager bm = namesystem.getBlockManager();
                final int totalDatanodes = namesystem.getNumberOfDatanodes(DatanodeReportType.LIVE);
                new NamenodeFsck(conf, nn, bm.getDatanodeManager().getNetworkTopology(), pmap, out, totalDatanodes, remoteAddress).fsck();
                return null;
            }
        });
    } catch (InterruptedException e) {
        response.sendError(400, e.getMessage());
    }
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) IOException(java.io.IOException) BlockManager(org.apache.hadoop.hdfs.server.blockmanagement.BlockManager) ServletContext(javax.servlet.ServletContext) InetAddress(java.net.InetAddress) PrintWriter(java.io.PrintWriter) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 83 with ServletContext

use of javax.servlet.ServletContext in project hadoop by apache.

the class ImageServlet method doPut.

@Override
protected void doPut(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    try {
        ServletContext context = getServletContext();
        final FSImage nnImage = NameNodeHttpServer.getFsImageFromContext(context);
        final Configuration conf = (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF);
        final PutImageParams parsedParams = new PutImageParams(request, response, conf);
        final NameNodeMetrics metrics = NameNode.getNameNodeMetrics();
        validateRequest(context, conf, request, response, nnImage, parsedParams.getStorageInfoString());
        UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                // if its not the active NN, then we need to notify the caller it was was the wrong
                // target (regardless of the fact that we got the image)
                HAServiceProtocol.HAServiceState state = NameNodeHttpServer.getNameNodeStateFromContext(getServletContext());
                if (state != HAServiceProtocol.HAServiceState.ACTIVE) {
                    // we need a different response type here so the client can differentiate this
                    // from the failure to upload due to (1) security, or (2) other checkpoints already
                    // present
                    response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, "Nameode " + request.getLocalAddr() + " is currently not in a state which can " + "accept uploads of new fsimages. State: " + state);
                    return null;
                }
                final long txid = parsedParams.getTxId();
                String remoteAddr = request.getRemoteAddr();
                ImageUploadRequest imageRequest = new ImageUploadRequest(txid, remoteAddr);
                final NameNodeFile nnf = parsedParams.getNameNodeFile();
                // if the node is attempting to upload an older transaction, we ignore it
                SortedSet<ImageUploadRequest> larger = currentlyDownloadingCheckpoints.tailSet(imageRequest);
                if (larger.size() > 0) {
                    response.sendError(HttpServletResponse.SC_CONFLICT, "Another checkpointer is already in the process of uploading a" + " checkpoint made up to transaction ID " + larger.last());
                    return null;
                }
                //make sure no one else has started uploading one
                if (!currentlyDownloadingCheckpoints.add(imageRequest)) {
                    response.sendError(HttpServletResponse.SC_CONFLICT, "Either current namenode is checkpointing or another" + " checkpointer is already in the process of " + "uploading a checkpoint made at transaction ID " + txid);
                    return null;
                }
                try {
                    if (nnImage.getStorage().findImageFile(nnf, txid) != null) {
                        response.sendError(HttpServletResponse.SC_CONFLICT, "Either current namenode has checkpointed or " + "another checkpointer already uploaded an " + "checkpoint for txid " + txid);
                        return null;
                    }
                    InputStream stream = request.getInputStream();
                    try {
                        long start = monotonicNow();
                        MD5Hash downloadImageDigest = TransferFsImage.handleUploadImageRequest(request, txid, nnImage.getStorage(), stream, parsedParams.getFileSize(), getThrottler(conf));
                        nnImage.saveDigestAndRenameCheckpointImage(nnf, txid, downloadImageDigest);
                        // Metrics non-null only when used inside name node
                        if (metrics != null) {
                            long elapsed = monotonicNow() - start;
                            metrics.addPutImage(elapsed);
                        }
                        // Now that we have a new checkpoint, we might be able to
                        // remove some old ones.
                        nnImage.purgeOldStorage(nnf);
                    } finally {
                        // remove the request once we've processed it, or it threw an error, so we
                        // aren't using it either
                        currentlyDownloadingCheckpoints.remove(imageRequest);
                        stream.close();
                    }
                } finally {
                    nnImage.removeFromCheckpointing(txid);
                }
                return null;
            }
        });
    } catch (Throwable t) {
        String errMsg = "PutImage failed. " + StringUtils.stringifyException(t);
        response.sendError(HttpServletResponse.SC_GONE, errMsg);
        throw new IOException(errMsg);
    }
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) ServletException(javax.servlet.ServletException) NameNodeFile(org.apache.hadoop.hdfs.server.namenode.NNStorage.NameNodeFile) ServletContext(javax.servlet.ServletContext) MD5Hash(org.apache.hadoop.io.MD5Hash) NameNodeMetrics(org.apache.hadoop.hdfs.server.namenode.metrics.NameNodeMetrics)

Example 84 with ServletContext

use of javax.servlet.ServletContext in project hadoop by apache.

the class TestAuthenticationFilter method getMockedServletContextWithStringSigner.

private static SignerSecretProvider getMockedServletContextWithStringSigner(FilterConfig config) throws Exception {
    Properties secretProviderProps = new Properties();
    secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET, "secret");
    SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider();
    secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
    ServletContext context = Mockito.mock(ServletContext.class);
    Mockito.when(context.getAttribute(AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)).thenReturn(secretProvider);
    Mockito.when(config.getServletContext()).thenReturn(context);
    return secretProvider;
}
Also used : SignerSecretProvider(org.apache.hadoop.security.authentication.util.SignerSecretProvider) ServletContext(javax.servlet.ServletContext) Properties(java.util.Properties)

Example 85 with ServletContext

use of javax.servlet.ServletContext in project hadoop by apache.

the class TestZKSignerSecretProvider method getDummyServletContext.

private ServletContext getDummyServletContext() {
    ServletContext servletContext = mock(ServletContext.class);
    when(servletContext.getAttribute(ZKSignerSecretProvider.ZOOKEEPER_SIGNER_SECRET_PROVIDER_CURATOR_CLIENT_ATTRIBUTE)).thenReturn(null);
    return servletContext;
}
Also used : ServletContext(javax.servlet.ServletContext)

Aggregations

ServletContext (javax.servlet.ServletContext)1059 Test (org.junit.Test)231 HttpServletRequest (javax.servlet.http.HttpServletRequest)171 IOException (java.io.IOException)138 HttpServletResponse (javax.servlet.http.HttpServletResponse)127 ServletException (javax.servlet.ServletException)95 File (java.io.File)75 ServletConfig (javax.servlet.ServletConfig)68 FilterConfig (javax.servlet.FilterConfig)65 HashMap (java.util.HashMap)63 Enumeration (java.util.Enumeration)52 InputStream (java.io.InputStream)51 ArrayList (java.util.ArrayList)49 URL (java.net.URL)47 HttpSession (javax.servlet.http.HttpSession)43 Map (java.util.Map)38 PrintWriter (java.io.PrintWriter)32 List (java.util.List)32 RequestDispatcher (javax.servlet.RequestDispatcher)30 WebApplicationContext (org.springframework.web.context.WebApplicationContext)28