Ejemplo n.º 1
0
  @Test
  public void getSetAttributes() {
    ServletContext context = new ServletContext1(new MockWebContext());

    // name0 = value0
    context.setAttribute("name0", "value0");
    Enumeration<String> attributeNames = context.getAttributeNames();
    assertTrue(attributeNames.hasMoreElements());
    assertEquals("name0", attributeNames.nextElement());
    assertFalse(attributeNames.hasMoreElements());

    assertEquals("value0", context.getAttribute("name0"));
    assertNull(context.getAttribute("name1"));

    // name0 = value0, name1 = value1
    context.setAttribute("name1", "value1");
    attributeNames = context.getAttributeNames();
    assertTrue(attributeNames.hasMoreElements());
    String name = attributeNames.nextElement();
    assertTrue(name.equals("name0") || name.equals("name1"));
    assertTrue(attributeNames.hasMoreElements());
    name = attributeNames.nextElement();
    assertTrue(name.equals("name0") || name.equals("name1"));
    assertFalse(attributeNames.hasMoreElements());

    assertEquals("value0", context.getAttribute("name0"));
    assertEquals("value1", context.getAttribute("name1"));

    // name0 = edited, name1 = value1
    context.setAttribute("name0", "edited");
    attributeNames = context.getAttributeNames();
    assertTrue(attributeNames.hasMoreElements());
    name = attributeNames.nextElement();
    assertTrue(name.equals("name0") || name.equals("name1"));
    assertTrue(attributeNames.hasMoreElements());
    name = attributeNames.nextElement();
    assertTrue(name.equals("name0") || name.equals("name1"));
    assertFalse(attributeNames.hasMoreElements());

    assertEquals("edited", context.getAttribute("name0"));
    assertEquals("value1", context.getAttribute("name1"));

    // name0 = edited
    context.removeAttribute("name1");
    attributeNames = context.getAttributeNames();
    assertTrue(attributeNames.hasMoreElements());
    assertEquals("name0", attributeNames.nextElement());
    assertFalse(attributeNames.hasMoreElements());

    assertEquals("edited", context.getAttribute("name0"));
    assertNull(context.getAttribute("name1"));

    // empty
    context.setAttribute("name0", null);
    attributeNames = context.getAttributeNames();
    assertFalse(attributeNames.hasMoreElements());

    assertNull(context.getAttribute("name0"));
    assertNull(context.getAttribute("name1"));
  }
Ejemplo n.º 2
0
  public static void apply(final ServletContext context) {
    // Maybe configurable?
    context.removeAttribute("javax.faces.FACELETS_REFRESH_PERIOD");
    context.setAttribute("javax.faces.FACELETS_REFRESH_PERIOD", "1");

    context.removeAttribute("facelets.REFRESH_PERIOD");
    context.setAttribute("facelets.REFRESH_PERIOD", "1");

    context.removeAttribute("javax.faces.PROJECT_STAGE");
    context.setAttribute("javax.faces.PROJECT_STAGE", "Development");

    context.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD", "1");
    context.setInitParameter("javax.faces.PROJECT_STAGE", "Development");
    context.setInitParameter("facelets.REFRESH_PERIOD", "1");

    if (LOGGER.isLevelEnabled(Level.TRACE)) {
      Enumeration<String> names = context.getAttributeNames();
      if (names != null) {
        while (names.hasMoreElements()) {
          String k = names.nextElement();
          LOGGER.trace("CONTEXT ATTRIBUTE {} value: {}", k, context.getAttribute(k));
        }
      }

      names = context.getInitParameterNames();
      if (names != null) {
        while (names.hasMoreElements()) {
          String k = names.nextElement();
          LOGGER.trace("CONTEXT INIT PARAM {} value: {}", k, context.getInitParameter(k));
        }
      }
    }
  }
Ejemplo n.º 3
0
 public Collection values() {
   List list = new ArrayList();
   Enumeration keys = context.getAttributeNames();
   while (keys.hasMoreElements()) {
     list.add(context.getAttribute((String) keys.nextElement()));
   }
   return (list);
 }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   String title = "Shared Info";
   out.println(
       "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
           + "Transitional//EN\">"
           + "<HTML>\n"
           + "<HEAD><TITLE>"
           + title
           + "</TITLE></HEAD>\n"
           + "<BODY BGCOLOR=\"#FDF5E6\">\n"
           + "<H1 ALIGN=\"CENTER\">"
           + title
           + "</H1>\n"
           + "<UL>\n"
           + "  <LI>Session:");
   HttpSession session = request.getSession(true);
   Enumeration attributes = session.getAttributeNames();
   out.println(getAttributeList(attributes));
   out.println("  <LI>Current Servlet Context:");
   ServletContext application = getServletContext();
   attributes = application.getAttributeNames();
   out.println(getAttributeList(attributes));
   out.println("  <LI>Servlet Context of /shareTest1:");
   application = application.getContext("/shareTest1");
   if (application == null) {
     out.println("Context sharing disabled");
   } else {
     attributes = application.getAttributeNames();
     out.println(getAttributeList(attributes));
   }
   out.println("  <LI>Cookies:<UL>");
   Cookie[] cookies = request.getCookies();
   if ((cookies == null) || (cookies.length == 0)) {
     out.println("    <LI>No cookies found.");
   } else {
     Cookie cookie;
     for (int i = 0; i < cookies.length; i++) {
       cookie = cookies[i];
       out.println("    <LI>" + cookie.getName());
     }
   }
   out.println("    </UL>\n" + "</UL>\n" + "</BODY></HTML>");
 }
Ejemplo n.º 5
0
 public Set entrySet() {
   Set set = new HashSet();
   Enumeration keys = context.getAttributeNames();
   while (keys.hasMoreElements()) {
     set.add(context.getAttribute((String) keys.nextElement()));
   }
   return (set);
 }
Ejemplo n.º 6
0
 public int size() {
   int n = 0;
   Enumeration keys = context.getAttributeNames();
   while (keys.hasMoreElements()) {
     keys.nextElement();
     n++;
   }
   return (n);
 }
  @SuppressWarnings("unchecked")
  protected void peek() {
    ServletContext application = getActionServlet().getServletContext();
    HttpSession session = getSession();

    ApplicationContext wac =
        (ApplicationContext)
            application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    logger.debug(wac);

    ApplicationContext parent = wac.getParent();
    if (parent != null) logger.debug(parent.toString());

    for (String n : wac.getBeanDefinitionNames()) {
      logger.debug(n);
    }

    // notice the dot . in the key name!
    wac =
        (ApplicationContext)
            application.getAttribute("org.springframework.web.struts.ContextLoaderPlugIn.CONTEXT.");
    if (wac != null) {
      logger.debug("struts ContextLoaderPlugIn context");
      for (String n : wac.getBeanDefinitionNames()) {
        logger.debug(n);
      }
    } else {
      logger.debug("ContextLoaderPlugIn ac is null");
    }
    parent = wac.getParent();
    if (parent != null) {
      logger.debug("Parent = " + parent.toString());
    }

    logger.debug("Servlet context");
    for (Enumeration e = application.getAttributeNames(); e.hasMoreElements(); ) {
      String key = (String) e.nextElement();
      String s = String.format("%s=%s", key, application.getAttribute(key));
      logger.debug(s);
    }

    logger.debug("Session");
    for (Enumeration e = session.getAttributeNames(); e.hasMoreElements(); ) {
      String key = (String) e.nextElement();
      String s = String.format("%s=%s", key, session.getAttribute(key));
      logger.debug(s);
    }

    logger.debug("request attributes:");
    HttpServletRequest request = getRequest();
    for (Enumeration e = request.getAttributeNames(); e.hasMoreElements(); ) {
      String key = (String) e.nextElement();
      String s = String.format("%s=%s", key, request.getAttribute(key));
      logger.debug(s);
    }
  }
Ejemplo n.º 8
0
 public boolean containsValue(Object value) {
   if (value == null) {
     return (false);
   }
   Enumeration keys = context.getAttributeNames();
   while (keys.hasMoreElements()) {
     Object next = context.getAttribute((String) keys.nextElement());
     if (next == value) {
       return (true);
     }
   }
   return (false);
 }
Ejemplo n.º 9
0
  public GenericWebAppContext(
      ServletContext servletContext,
      HttpServletRequest request,
      HttpServletResponse response,
      SessionProvider sessionProvider,
      ManageableRepository repository) {

    initialize(servletContext, request, response);

    this.sessionProvider = sessionProvider;
    this.repository = repository;

    // log.info("WEb context ---------------");
    // initialize context with all props
    Enumeration en = servletContext.getInitParameterNames();
    while (en.hasMoreElements()) {
      String name = (String) en.nextElement();
      put(name, servletContext.getInitParameter(name));
      LOG.debug("ServletContext init param: " + name + "=" + servletContext.getInitParameter(name));
    }

    en = servletContext.getAttributeNames();
    while (en.hasMoreElements()) {
      String name = (String) en.nextElement();
      put(name, servletContext.getAttribute(name));
      LOG.debug("ServletContext: " + name + "=" + servletContext.getAttribute(name));
    }

    HttpSession session = request.getSession(false);
    if (session != null) {
      en = session.getAttributeNames();
      while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        put(name, session.getAttribute(name));
        LOG.debug("Session: " + name + "=" + session.getAttribute(name));
      }
    }

    en = request.getAttributeNames();
    while (en.hasMoreElements()) {
      String name = (String) en.nextElement();
      put(name, request.getAttribute(name));
    }

    en = request.getParameterNames();
    while (en.hasMoreElements()) {
      String name = (String) en.nextElement();
      put(name, request.getParameter(name));
      LOG.debug("Request: " + name + "=" + request.getParameter(name));
    }
  }
Ejemplo n.º 10
0
  /**
   * Returns a String with all application scope variables.
   *
   * @return A String with all application scope variables.
   */
  public String getApplicationScope() {
    Map info = new TreeMap();
    ServletContext context = pageContext.getServletContext();
    Enumeration names = context.getAttributeNames();

    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      Object value = context.getAttribute(name);

      info.put(name, toStringValue(value));
    }

    return toHTMLTable("application scope", info);
  }
  protected void logRequestInfo(HttpServletRequest request) {
    ServletContext servletContext = this.getServletContext();
    HttpSession session = request.getSession();

    Debug.logVerbose("--- Start Request Headers: ---", module);
    Enumeration<String> headerNames = UtilGenerics.cast(request.getHeaderNames());
    while (headerNames.hasMoreElements()) {
      String headerName = headerNames.nextElement();
      Debug.logVerbose(headerName + ":" + request.getHeader(headerName), module);
    }
    Debug.logVerbose("--- End Request Headers: ---", module);

    Debug.logVerbose("--- Start Request Parameters: ---", module);
    Enumeration<String> paramNames = UtilGenerics.cast(request.getParameterNames());
    while (paramNames.hasMoreElements()) {
      String paramName = paramNames.nextElement();
      Debug.logVerbose(paramName + ":" + request.getParameter(paramName), module);
    }
    Debug.logVerbose("--- End Request Parameters: ---", module);

    Debug.logVerbose("--- Start Request Attributes: ---", module);
    Enumeration<String> reqNames = UtilGenerics.cast(request.getAttributeNames());
    while (reqNames != null && reqNames.hasMoreElements()) {
      String attName = reqNames.nextElement();
      Debug.logVerbose(attName + ":" + request.getAttribute(attName), module);
    }
    Debug.logVerbose("--- End Request Attributes ---", module);

    Debug.logVerbose("--- Start Session Attributes: ---", module);
    Enumeration<String> sesNames = null;
    try {
      sesNames = UtilGenerics.cast(session.getAttributeNames());
    } catch (IllegalStateException e) {
      Debug.logVerbose("Cannot get session attributes : " + e.getMessage(), module);
    }
    while (sesNames != null && sesNames.hasMoreElements()) {
      String attName = sesNames.nextElement();
      Debug.logVerbose(attName + ":" + session.getAttribute(attName), module);
    }
    Debug.logVerbose("--- End Session Attributes ---", module);

    Enumeration<String> appNames = UtilGenerics.cast(servletContext.getAttributeNames());
    Debug.logVerbose("--- Start ServletContext Attributes: ---", module);
    while (appNames != null && appNames.hasMoreElements()) {
      String attName = appNames.nextElement();
      Debug.logVerbose(attName + ":" + servletContext.getAttribute(attName), module);
    }
    Debug.logVerbose("--- End ServletContext Attributes ---", module);
  }
Ejemplo n.º 12
0
  public static List getApplicationAttributes(Context context) {
    List attrs = new ArrayList();
    ServletContext servletCtx = context.getServletContext();
    for (Enumeration e = servletCtx.getAttributeNames(); e.hasMoreElements(); ) {
      String attrName = (String) e.nextElement();
      Object attrValue = servletCtx.getAttribute(attrName);

      Attribute attr = new Attribute();
      attr.setName(attrName);
      attr.setValue(attrValue);
      attr.setType(ClassUtils.getQualifiedName(attrValue.getClass()));
      attrs.add(attr);
    }
    return attrs;
  }
  /**
   * Register web-specific environment beans ("contextParameters", "contextAttributes") with the
   * given BeanFactory, as used by the WebApplicationContext.
   *
   * @param bf the BeanFactory to configure
   * @param sc the ServletContext that we're running within
   * @param config the ServletConfig of the containing Portlet
   */
  public static void registerEnvironmentBeans(
      ConfigurableListableBeanFactory bf, ServletContext sc, ServletConfig config) {

    if (sc != null && !bf.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)) {
      bf.registerSingleton(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME, sc);
    }

    if (config != null
        && !bf.containsBean(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME)) {
      bf.registerSingleton(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME, config);
    }

    if (!bf.containsBean(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME)) {
      Map<String, String> parameterMap = new HashMap<String, String>();
      if (sc != null) {
        Enumeration<?> paramNameEnum = sc.getInitParameterNames();
        while (paramNameEnum.hasMoreElements()) {
          String paramName = (String) paramNameEnum.nextElement();
          parameterMap.put(paramName, sc.getInitParameter(paramName));
        }
      }
      if (config != null) {
        Enumeration<?> paramNameEnum = config.getInitParameterNames();
        while (paramNameEnum.hasMoreElements()) {
          String paramName = (String) paramNameEnum.nextElement();
          parameterMap.put(paramName, config.getInitParameter(paramName));
        }
      }
      bf.registerSingleton(
          WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME,
          Collections.unmodifiableMap(parameterMap));
    }

    if (!bf.containsBean(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME)) {
      Map<String, Object> attributeMap = new HashMap<String, Object>();
      if (sc != null) {
        Enumeration<?> attrNameEnum = sc.getAttributeNames();
        while (attrNameEnum.hasMoreElements()) {
          String attrName = (String) attrNameEnum.nextElement();
          attributeMap.put(attrName, sc.getAttribute(attrName));
        }
      }
      bf.registerSingleton(
          WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME,
          Collections.unmodifiableMap(attributeMap));
    }
  }
 @Test
 public void onDifferentPortInServletContainer() throws Exception {
   this.applicationContext.register(
       RootConfig.class,
       EndpointConfig.class,
       DifferentPortConfig.class,
       BaseConfiguration.class,
       EndpointWebMvcAutoConfiguration.class,
       ErrorMvcAutoConfiguration.class);
   ServletContext servletContext = mock(ServletContext.class);
   given(servletContext.getInitParameterNames()).willReturn(new Vector<String>().elements());
   given(servletContext.getAttributeNames()).willReturn(new Vector<String>().elements());
   this.applicationContext.setServletContext(servletContext);
   this.applicationContext.refresh();
   assertContent("/controller", ports.get().management, null);
   assertContent("/endpoint", ports.get().management, null);
   this.applicationContext.close();
   assertAllClosed();
 }
Ejemplo n.º 15
0
  private Enumeration<String> doGetAttributeNamesInScope(int scope) {
    switch (scope) {
      case PAGE_SCOPE:
        return Collections.enumeration(attributes.keySet());

      case REQUEST_SCOPE:
        return request.getAttributeNames();

      case SESSION_SCOPE:
        if (session == null) {
          throw new IllegalStateException(Localizer.getMessage("jsp.error.page.noSession"));
        }
        return session.getAttributeNames();

      case APPLICATION_SCOPE:
        return context.getAttributeNames();

      default:
        throw new IllegalArgumentException("Invalid scope");
    }
  }
Ejemplo n.º 16
0
  public static void showServletInfo(HttpServlet servlet, PrintStream out) {
    out.println("Servlet Info");
    out.println(" getServletName(): " + servlet.getServletName());
    out.println(" getRootPath(): " + getRootPath());
    out.println(" Init Parameters:");
    Enumeration params = servlet.getInitParameterNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      out.println("  " + name + ": " + servlet.getInitParameter(name));
    }
    out.println();

    ServletContext context = servlet.getServletContext();
    out.println("Context Info");

    try {
      out.println(" context.getResource('/'): " + context.getResource("/"));
    } catch (java.net.MalformedURLException e) {
    } // cant happen
    out.println(" context.getServerInfo(): " + context.getServerInfo());
    out.println("  name: " + getServerInfoName(context.getServerInfo()));
    out.println("  version: " + getServerInfoVersion(context.getServerInfo()));

    out.println(" context.getInitParameterNames():");
    params = context.getInitParameterNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      out.println("  " + name + ": " + context.getInitParameter(name));
    }

    out.println(" context.getAttributeNames():");
    params = context.getAttributeNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      out.println("  context.getAttribute(\"" + name + "\"): " + context.getAttribute(name));
    }

    out.println();
  }
Ejemplo n.º 17
0
 @Override
 public Enumeration<String> getAttributeNames() {
   return proxy.getAttributeNames();
 }
Ejemplo n.º 18
0
 @Test
 public void emptyAttributes() {
   ServletContext context = new ServletContext1(new MockWebContext());
   Enumeration<String> attributeNames = context.getAttributeNames();
   assertFalse(attributeNames.hasMoreElements());
 }
  /**
   * This method is designed to be invoked from a {@link javax.servlet.http.HttpSessionListener}
   * like {@link BridgeSessionListener} when a session timeout/expiration occurs. The logic in this
   * method is a little awkward because we have to try and remove BridgeRequestScope instances from
   * {@link Map} instances in the {@link ServletContext} rather than the {@link PortletContext}
   * because we only have access to the Servlet-API when sessions expire.
   */
  public void removeBridgeRequestScopesBySession(HttpSession httpSession) {

    // For each ServletContext attribute name:
    String httpSessionId = httpSession.getId();
    ServletContext servletContext = httpSession.getServletContext();

    Enumeration<String> attributeNames = servletContext.getAttributeNames();

    if (attributeNames != null) {

      while (attributeNames.hasMoreElements()) {
        String attributeName = attributeNames.nextElement();

        // Get the value associated with the current attribute name.
        Object attributeValue = servletContext.getAttribute(attributeName);

        // If the value is a type of java.util.Map then it is possible that it contains
        // BridgeRequestScope
        // instances.
        if ((attributeValue != null) && (attributeValue instanceof Map)) {

          // Prepare to iterate over the map entries.
          Map<?, ?> map = (Map<?, ?>) attributeValue;

          Set<?> entrySet = null;

          try {
            entrySet = map.entrySet();
          } catch (Exception e) {
            // ignore -- some maps like Mojarra's Flash scope will throw a NullPointerException
          }

          if (entrySet != null) {

            // Iterate over the map entries, and build up a list of BridgeRequestScope keys that are
            // to be
            // removed. Doing it this way prevents ConcurrentModificationExceptions from being
            // thrown.
            List<Object> keysToRemove = new ArrayList<Object>();

            for (Object mapEntryAsObject : entrySet) {
              Map.Entry<?, ?> mapEntry = (Map.Entry<?, ?>) mapEntryAsObject;
              Object key = mapEntry.getKey();
              Object value = mapEntry.getValue();

              if ((value != null) && (value instanceof BridgeRequestScope)) {
                BridgeRequestScope bridgeRequestScope = (BridgeRequestScope) value;
                String bridgeRequestScopeSessionId =
                    bridgeRequestScope.getId().split("[:][:][:]")[1];

                if (httpSessionId.equals(bridgeRequestScopeSessionId)) {
                  keysToRemove.add(key);
                }
              }
            }

            // For each BridgeRequestScope key that is to be removed:
            for (Object bridgeRequestScopeId : keysToRemove) {

              // Remove it from the map.
              Object bridgeRequestScope = map.remove(bridgeRequestScopeId);
              logger.debug(
                  "Removed bridgeRequestScopeId=[{0}] bridgeRequestScope=[{1}] from cache due to session timeout",
                  bridgeRequestScopeId, bridgeRequestScope);
            }
          }
        }
      }
    }
  }
Ejemplo n.º 20
0
 public Enumeration getAttributeNames() {
   return delegate.getAttributeNames();
 }
Ejemplo n.º 21
0
 public List<String> getAttributeNames() {
   return InternalUtils.toList(servletContext.getAttributeNames());
 }