Java Code Examples for javax.servlet.ServletContext#getAttribute()

The following examples show how to use javax.servlet.ServletContext#getAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FrameServletHandler.java    From urule with Apache License 2.0 6 votes vote down vote up
public void importProject(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	DiskFileItemFactory factory = new DiskFileItemFactory();
	ServletContext servletContext = req.getSession().getServletContext();
	File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	factory.setRepository(repository);
	ServletFileUpload upload = new ServletFileUpload(factory);
	InputStream inputStream=null;
	boolean overwriteProject=true;
	List<FileItem> items = upload.parseRequest(req);
	if(items.size()==0){
		throw new ServletException("Upload file is invalid.");
	}
	for(FileItem item:items){
		String name=item.getFieldName();
		if(name.equals("overwriteProject")){
			String overwriteProjectStr=new String(item.get());
			overwriteProject=Boolean.valueOf(overwriteProjectStr);
		}else if(name.equals("file")){
			inputStream=item.getInputStream();
		}
	}
	repositoryService.importXml(inputStream,overwriteProject);
	IOUtils.closeQuietly(inputStream);
	resp.sendRedirect(req.getContextPath()+"/urule/frame");
}
 
Example 2
Source File: FileChecksumServlets.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response
    ) throws ServletException, IOException {
  final PrintWriter out = response.getWriter();
  final String path = ServletUtil.getDecodedPath(request, "/getFileChecksum");
  final XMLOutputter xml = new XMLOutputter(out, "UTF-8");
  xml.declaration();

  final ServletContext context = getServletContext();
  final DataNode datanode = (DataNode) context.getAttribute("datanode");
  final Configuration conf = 
    new HdfsConfiguration(datanode.getConf());
  
  try {
    final DFSClient dfs = DatanodeJspHelper.getDFSClient(request, 
        datanode, conf, getUGI(request, conf));
    final MD5MD5CRC32FileChecksum checksum = dfs.getFileChecksum(path, Long.MAX_VALUE);
    MD5MD5CRC32FileChecksum.write(xml, checksum);
  } catch(IOException ioe) {
    writeXml(ioe, path, xml);
  } catch (InterruptedException e) {
    writeXml(e, path, xml);
  }
  xml.endDocument();
}
 
Example 3
Source File: DefaultCarbonAuthenticator.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param request
 * @return
 * @throws AxisFault
 */
private AuthenticationAdminClient getAuthenticationAdminCient(HttpServletRequest request)
        throws AxisFault {
    HttpSession session = request.getSession();
    ServletContext servletContext = session.getServletContext();
    String backendServerURL = request.getParameter("backendURL");
    if (backendServerURL == null) {
        backendServerURL = CarbonUIUtil.getServerURL(servletContext, request.getSession());
    }
    session.setAttribute(CarbonConstants.SERVER_URL, backendServerURL);

    ConfigurationContext configContext = (ConfigurationContext) servletContext
            .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);

    String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_AUTH_TOKEN);

    return new AuthenticationAdminClient(configContext, backendServerURL, cookie, session, true);
}
 
Example 4
Source File: HttpServer.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the user has privileges to access to instrumentation servlets.
 * <p/>
 * If <code>hadoop.security.instrumentation.requires.admin</code> is set to FALSE
 * (default value) it always returns TRUE.
 * <p/>
 * If <code>hadoop.security.instrumentation.requires.admin</code> is set to TRUE
 * it will check that if the current user is in the admin ACLS. If the user is
 * in the admin ACLs it returns TRUE, otherwise it returns FALSE.
 *
 * @param servletContext the servlet context.
 * @param request the servlet request.
 * @param response the servlet response.
 * @return TRUE/FALSE based on the logic decribed above.
 */
public static boolean isInstrumentationAccessAllowed(
  ServletContext servletContext, HttpServletRequest request,
  HttpServletResponse response) throws IOException {
  Configuration conf =
    (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);

  boolean access = true;
  boolean adminAccess = conf.getBoolean(
    CommonConfigurationKeys.HADOOP_SECURITY_INSTRUMENTATION_REQUIRES_ADMIN,
    false);
  if (adminAccess) {
    access = hasAdministratorAccess(servletContext, request, response);
  }
  return access;
}
 
Example 5
Source File: HttpServer2.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the user has privileges to access to instrumentation servlets.
 * <p/>
 * If <code>hadoop.security.instrumentation.requires.admin</code> is set to FALSE
 * (default value) it always returns TRUE.
 * <p/>
 * If <code>hadoop.security.instrumentation.requires.admin</code> is set to TRUE
 * it will check that if the current user is in the admin ACLS. If the user is
 * in the admin ACLs it returns TRUE, otherwise it returns FALSE.
 *
 * @param servletContext the servlet context.
 * @param request the servlet request.
 * @param response the servlet response.
 * @return TRUE/FALSE based on the logic decribed above.
 */
public static boolean isInstrumentationAccessAllowed(
  ServletContext servletContext, HttpServletRequest request,
  HttpServletResponse response) throws IOException {
  Configuration conf =
    (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);

  boolean access = true;
  boolean adminAccess = conf.getBoolean(
    CommonConfigurationKeys.HADOOP_SECURITY_INSTRUMENTATION_REQUIRES_ADMIN,
    false);
  if (adminAccess) {
    access = hasAdministratorAccess(servletContext, request, response);
  }
  return access;
}
 
Example 6
Source File: AsyncStockServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void onComplete(AsyncEvent event) throws IOException {
    if (clients.remove(event.getAsyncContext()) && clientcount.decrementAndGet()==0) {
        ServletContext sc = event.getAsyncContext().getRequest().getServletContext();
        Stockticker ticker = (Stockticker) sc.getAttribute(
                AsyncStockContextListener.STOCK_TICKER_KEY);
        ticker.removeTickListener(this);
    }
}
 
Example 7
Source File: OAuthUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static synchronized OAuthDataProvider getOAuthDataProvider(
        ServletContext servletContext) {
    OAuthDataProvider dataProvider = (OAuthDataProvider) servletContext
            .getAttribute(OAuthConstants.OAUTH_DATA_PROVIDER_INSTANCE_KEY);

    if (dataProvider == null) {
        String dataProviderClassName = servletContext
                .getInitParameter(OAuthConstants.OAUTH_DATA_PROVIDER_CLASS);

        if (StringUtils.isEmpty(dataProviderClassName)) {
            throw new RuntimeException(
                    "There should be provided [ " + OAuthConstants.OAUTH_DATA_PROVIDER_CLASS
                            + " ] context init param in web.xml");
        }

        try {
            dataProvider = (OAuthDataProvider) OAuthUtils
                    .instantiateClass(dataProviderClassName);

            servletContext
                    .setAttribute(OAuthConstants.OAUTH_DATA_PROVIDER_INSTANCE_KEY, dataProvider);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Cannot instantiate OAuth Data Provider class: " + dataProviderClassName, e);
        }
    }

    return dataProvider;
}
 
Example 8
Source File: ServletUtils.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
public static Object findTool(String key, String toolboxKey,
                              ServletContext application)
{
    Toolbox toolbox = (Toolbox)application.getAttribute(toolboxKey);
    if (toolbox != null)
    {
        return toolbox.get(key);
    }
    return null;
}
 
Example 9
Source File: PluginManagerResource.java    From sylph with Apache License 2.0 5 votes vote down vote up
public PluginManagerResource(
        @Context ServletContext servletContext,
        @Context UriInfo uriInfo)
{
    this.servletContext = servletContext;
    this.uriInfo = uriInfo;
    this.sylphContext = (SylphContext) servletContext.getAttribute("sylphContext");
}
 
Example 10
Source File: InterfaceX_EngineSideServer.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void init() throws ServletException {
    ServletContext context = getServletContext();

    try {
        // get reference to engine
        _engine = (EngineGateway) context.getAttribute("engine");
        if (_engine == null) {

            // turn on persistence if required
            String persistOn = context.getInitParameter("EnablePersistence");
            boolean persist = "true".equalsIgnoreCase(persistOn);
            _engine = new EngineGatewayImpl(persist);
            context.setAttribute("engine", _engine);
        }
        // add interface X monitoring if required
        String listenerURI = context.getInitParameter("InterfaceXListener");
        if (listenerURI != null) {
            for (String uri : listenerURI.split(";")) {
                _engine.addInterfaceXListener(uri);
            }    
        }

    }
    catch (YPersistenceException e) {
        logger.fatal("Failure to initialise runtime (persistence failure)", e);
        throw new UnavailableException("Persistence failure");
    }
}
 
Example 11
Source File: SetSessionPathListener.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
  try {
    final ServletContext servletContext = sce.getServletContext();
    Injector injector = (Injector) servletContext.getAttribute(Injector.class.getName());
    final String agentEndpoint =
        injector.getInstance(Key.get(String.class, Names.named("wsagent.endpoint")));
    servletContext.getSessionCookieConfig().setPath(new URL(agentEndpoint).getPath());
  } catch (MalformedURLException e) {
    LOG.warn("Unable to set correct session path due to malformed agent URL.", e);
  }
}
 
Example 12
Source File: NameNodeHttpServer.java    From big-c with Apache License 2.0 4 votes vote down vote up
static FSImage getFsImageFromContext(ServletContext context) {
  return (FSImage)context.getAttribute(FSIMAGE_ATTRIBUTE_KEY);
}
 
Example 13
Source File: MacroTreeRenderer.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public void renderImage(Appendable writer, Map<String, Object> context, ModelTree.ModelNode.Image image) throws IOException {
    if (image == null) {
        return;
    }
    HttpServletResponse response = (HttpServletResponse) context.get("response");
    HttpServletRequest request = (HttpServletRequest) context.get("request");

    String urlMode = image.getUrlMode();
    String src = image.getSrc(context);
    String id = image.getId(context);
    String style = image.getStyle(context);
    String wid = image.getWidth(context);
    String hgt = image.getHeight(context);
    String border = image.getBorder(context);
    String alt = ""; //TODO add alt to tree images image.getAlt(context);

    Boolean fullPath = null; // SCIPIO: changed from boolean to Boolean
    Boolean secure = null; // SCIPIO: changed from boolean to Boolean
    Boolean encode = false; // SCIPIO: changed from boolean to Boolean
    String urlString = "";

    if (urlMode != null && "intra-app".equalsIgnoreCase(urlMode)) {
        if (request != null && response != null) {
            ServletContext ctx = request.getServletContext(); // SCIPIO: get context using servlet API 3.0
            RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
            urlString = rh.makeLink(request, response, src, fullPath, secure, encode);
        } else {
            urlString = src;
        }
    } else  if (urlMode != null && "content".equalsIgnoreCase(urlMode)) {
        if (request != null && response != null) {
            StringBuilder newURL = new StringBuilder();
            ContentUrlTag.appendContentPrefix(request, newURL);
            newURL.append(src);
            urlString = newURL.toString();
        }
    } else {
        urlString = src;
    }
    StringWriter sr = new StringWriter();
    sr.append("<@renderImage ");
    sr.append("src=");
    sr.append(ftlFmt.makeStringLiteral(src));
    sr.append(" id=");
    sr.append(ftlFmt.makeStringLiteral(id));
    sr.append(" style=");
    sr.append(ftlFmt.makeStringLiteral(style));
    sr.append(" wid=");
    sr.append(ftlFmt.makeStringLiteral(wid));
    sr.append(" hgt=");
    sr.append(ftlFmt.makeStringLiteral(hgt));
    sr.append(" border=");
    sr.append(ftlFmt.makeStringLiteral(border));
    sr.append(" alt=");
    sr.append(ftlFmt.makeStringLiteral(alt));
    sr.append(" urlString=");
    sr.append(ftlFmt.makeStringLiteral(urlString));
    sr.append(" />");
    executeMacro(writer, sr.toString());
}
 
Example 14
Source File: ZKSignerSecretProvider.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Override
public void init(Properties config, ServletContext servletContext,
        long tokenValidity) throws Exception {
  Object curatorClientObj = servletContext.getAttribute(
          ZOOKEEPER_SIGNER_SECRET_PROVIDER_CURATOR_CLIENT_ATTRIBUTE);
  if (curatorClientObj != null
          && curatorClientObj instanceof CuratorFramework) {
    client = (CuratorFramework) curatorClientObj;
  } else {
    client = createCuratorClient(config);
    servletContext.setAttribute(
        ZOOKEEPER_SIGNER_SECRET_PROVIDER_CURATOR_CLIENT_ATTRIBUTE, client);
  }
  this.tokenValidity = tokenValidity;
  shouldDisconnect = Boolean.parseBoolean(
          config.getProperty(DISCONNECT_FROM_ZOOKEEPER_ON_SHUTDOWN, "true"));
  path = config.getProperty(ZOOKEEPER_PATH);
  if (path == null) {
    throw new IllegalArgumentException(ZOOKEEPER_PATH
            + " must be specified");
  }
  try {
    nextRolloverDate = System.currentTimeMillis() + tokenValidity;
    // everyone tries to do this, only one will succeed and only when the
    // znode doesn't already exist.  Everyone else will synchronize on the
    // data from the znode
    client.create().creatingParentsIfNeeded()
            .forPath(path, generateZKData(generateRandomSecret(),
            generateRandomSecret(), null));
    zkVersion = 0;
    LOG.info("Creating secret znode");
  } catch (KeeperException.NodeExistsException nee) {
    LOG.info("The secret znode already exists, retrieving data");
  }
  // Synchronize on the data from the znode
  // passing true tells it to parse out all the data for initing
  pullFromZK(true);
  long initialDelay = nextRolloverDate - System.currentTimeMillis();
  // If it's in the past, try to find the next interval that we should
  // be using
  if (initialDelay < 1l) {
    int i = 1;
    while (initialDelay < 1l) {
      initialDelay = nextRolloverDate + tokenValidity * i
              - System.currentTimeMillis();
      i++;
    }
  }
  super.startScheduler(initialDelay, tokenValidity);
}
 
Example 15
Source File: ContextHelper.java    From greenmail with Apache License 2.0 4 votes vote down vote up
public static Managers getManagers(ServletContext ctx) {
    return (Managers) ctx.getAttribute(ATTRIBUTE_NAME_MANAGERS);
}
 
Example 16
Source File: LastaPrepareFilter.java    From lastaflute with Apache License 2.0 4 votes vote down vote up
protected MessageResources getMessageResources(ServletContext context) {
    return (MessageResources) context.getAttribute(LastaWebKey.MESSAGE_RESOURCES_KEY);
}
 
Example 17
Source File: ContextLoader.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Initialize Spring's web application context for the given servlet context,
 * using the application context provided at construction time, or creating a new one
 * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
 * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
 * @param servletContext current servlet context
 * @return the new WebApplicationContext
 * @see #ContextLoader(WebApplicationContext)
 * @see #CONTEXT_CLASS_PARAM
 * @see #CONFIG_LOCATION_PARAM
 */
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
	if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
		throw new IllegalStateException(
				"Cannot initialize context because there is already a root application context present - " +
				"check whether you have multiple ContextLoader* definitions in your web.xml!");
	}

	Log logger = LogFactory.getLog(ContextLoader.class);
	servletContext.log("Initializing Spring root WebApplicationContext");
	if (logger.isInfoEnabled()) {
		logger.info("Root WebApplicationContext: initialization started");
	}
	long startTime = System.currentTimeMillis();

	try {
		// Store context in local instance variable, to guarantee that
		// it is available on ServletContext shutdown.
		if (this.context == null) {
			this.context = createWebApplicationContext(servletContext);
		}
		if (this.context instanceof ConfigurableWebApplicationContext) {
			ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
			if (!cwac.isActive()) {
				// The context has not yet been refreshed -> provide services such as
				// setting the parent context, setting the application context id, etc
				if (cwac.getParent() == null) {
					// The context instance was injected without an explicit parent ->
					// determine parent for root web application context, if any.
					ApplicationContext parent = loadParentContext(servletContext);
					cwac.setParent(parent);
				}
				configureAndRefreshWebApplicationContext(cwac, servletContext);
			}
		}
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

		ClassLoader ccl = Thread.currentThread().getContextClassLoader();
		if (ccl == ContextLoader.class.getClassLoader()) {
			currentContext = this.context;
		}
		else if (ccl != null) {
			currentContextPerThread.put(ccl, this.context);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
					WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
		}
		if (logger.isInfoEnabled()) {
			long elapsedTime = System.currentTimeMillis() - startTime;
			logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
		}

		return this.context;
	}
	catch (RuntimeException ex) {
		logger.error("Context initialization failed", ex);
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
		throw ex;
	}
	catch (Error err) {
		logger.error("Context initialization failed", err);
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
		throw err;
	}
}
 
Example 18
Source File: HttpServer.java    From hbase with Apache License 2.0 3 votes vote down vote up
/**
 * Does the user sending the HttpServletRequest has the administrator ACLs? If
 * it isn't the case, response will be modified to send an error to the user.
 *
 * @param servletContext the {@link ServletContext} to use
 * @param request the {@link HttpServletRequest} to check
 * @param response used to send the error response if user does not have admin access.
 * @return true if admin-authorized, false otherwise
 * @throws IOException if an unauthenticated or unauthorized user tries to access the page
 */
public static boolean hasAdministratorAccess(
    ServletContext servletContext, HttpServletRequest request,
    HttpServletResponse response) throws IOException {
  Configuration conf =
      (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
  AccessControlList acl = (AccessControlList) servletContext.getAttribute(ADMINS_ACL);

  return hasAdministratorAccess(conf, acl, request, response);
}
 
Example 19
Source File: HttpServer2.java    From knox with Apache License 2.0 3 votes vote down vote up
/**
 * Get the admin ACLs from the given ServletContext and check if the given
 * user is in the ACL.
 *
 * @param servletContext the context containing the admin ACL.
 * @param remoteUser the remote user to check for.
 * @return true if the user is present in the ACL, false if no ACL is set or
 *         the user is not present
 */
public static boolean userHasAdministratorAccess(ServletContext servletContext,
                                                 String remoteUser) {
  AccessControlList adminsAcl = (AccessControlList) servletContext
                                                        .getAttribute(ADMINS_ACL);
  UserGroupInformation remoteUserUGI =
      UserGroupInformation.createRemoteUser(remoteUser);
  return adminsAcl != null && adminsAcl.isUserAllowed(remoteUserUGI);
}
 
Example 20
Source File: RequestHandler.java    From scipio-erp with Apache License 2.0 2 votes vote down vote up
/**
 * SCIPIO: Returns the servlet mapping for the controller.
 * NOTE: Unlike ofbiz's _CONTROL_PATH_ request attribute, this is accessible to early filters,
 * because it's determined during servlet initialization.
 * Added 2017-11-14.
 */
public static String getControlServletMapping(ServletContext servletContext) {
    return (String) servletContext.getAttribute("_CONTROL_MAPPING_");
}