Example usage for javax.servlet ServletContext getAttribute

List of usage examples for javax.servlet ServletContext getAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletContext getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the servlet container attribute with the given name, or null if there is no attribute by that name.

Usage

From source file:com.google.zxing.web.DecodeServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    Logger logger = Logger.getLogger("com.google.zxing");
    ServletContext context = servletConfig.getServletContext();
    logger.addHandler(new ServletContextLogHandler(context));
    File repository = (File) context.getAttribute("javax.servlet.context.tempdir");
    FileCleaningTracker fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(context);
    diskFileItemFactory = new DiskFileItemFactory(1 << 16, repository);
    diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker);

    URL blockURL = context.getClassLoader().getResource("/private/uri-block-substrings.txt");
    if (blockURL == null) {
        blockedURLSubstrings = Collections.emptyList();
    } else {/*w w w  .j  a  v  a 2s . c  o  m*/
        try {
            blockedURLSubstrings = Resources.readLines(blockURL, StandardCharsets.UTF_8);
        } catch (IOException ioe) {
            throw new ServletException(ioe);
        }
        log.info("Blocking URIs containing: " + blockedURLSubstrings);
    }
}

From source file:org.glom.web.server.OnlineGlomServlet.java

protected UserStore getUserStore() {
    //See if there is already a shared userstore
    final ServletConfig config = this.getServletConfig();
    if (config == null) {
        Log.error("getServletConfig() return null");
        return null;
    }//from   w w w  . ja va 2  s . c o  m

    final ServletContext context = config.getServletContext();
    if (context == null) {
        Log.error("getServletContext() return null");
        return null;
    }

    //Use the existing shared document set, if any:
    final Object object = context.getAttribute(USER_STORE);
    if ((object != null) && !(object instanceof UserStore)) {
        Log.error("The configuredDocumentSet attribute is not of the expected type.");
        return null;
    }

    UserStore userStore = (UserStore) object;
    if (userStore != null) {
        return userStore;
    }

    //Create the shared userstore
    //TODO: Possible race condition between checking and creating+setting:
    userStore = new UserStore();

    //Store it in the Servlet Context,
    //so it is available to all servlets:
    context.setAttribute(USER_STORE, userStore);

    return userStore;
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentUninstaller.java

@Override
public boolean uninstallComponent(Component component) throws ApsSystemException {
    ServletContext servletContext = ((ConfigurableWebApplicationContext) _applicationContext)
            .getServletContext();/*from  w  w  w  .  j  av a  2 s. c om*/
    ClassLoader cl = (ClassLoader) servletContext.getAttribute("componentInstallerClassLoader");
    List<ClassPathXmlApplicationContext> ctxList = (List<ClassPathXmlApplicationContext>) servletContext
            .getAttribute("pluginsContextsList");
    ClassPathXmlApplicationContext appCtx = null;
    if (ctxList != null) {
        for (ClassPathXmlApplicationContext ctx : ctxList) {
            if (component.getCode().equals(ctx.getDisplayName())) {
                appCtx = ctx;
            }
        }
    }
    String appRootPath = servletContext.getRealPath("/");
    String backupDirPath = appRootPath + "componentinstaller" + File.separator + component.getArtifactId()
            + "-backup";
    Map<File, File> resourcesMap = new HashMap<File, File>();
    try {
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            if (cl != null) {
                Thread.currentThread().setContextClassLoader(cl);
            }
            if (null == component || null == component.getUninstallerInfo()) {
                return false;
            }
            this.getDatabaseManager().createBackup();//backup database
            SystemInstallationReport report = super.extractReport();
            ComponentUninstallerInfo ui = component.getUninstallerInfo();
            //remove records from db
            String[] dataSourceNames = this.extractBeanNames(DataSource.class);
            for (int j = 0; j < dataSourceNames.length; j++) {
                String dataSourceName = dataSourceNames[j];
                Resource resource = (null != ui) ? ui.getSqlResources(dataSourceName) : null;
                String script = (null != resource) ? this.readFile(resource) : null;
                if (null != script && script.trim().length() > 0) {
                    DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName);
                    String[] queries = QueryExtractor.extractDeleteQueries(script);
                    TableDataUtils.executeQueries(dataSource, queries, true);
                }
            }
            this.executePostProcesses(ui.getPostProcesses());

            //drop tables
            Map<String, List<String>> tableMapping = component.getTableMapping();
            if (tableMapping != null) {
                for (int j = 0; j < dataSourceNames.length; j++) {
                    String dataSourceName = dataSourceNames[j];
                    List<String> tableClasses = tableMapping.get(dataSourceName);
                    if (null != tableClasses && tableClasses.size() > 0) {
                        List<String> newList = new ArrayList<String>();
                        newList.addAll(tableClasses);
                        Collections.reverse(newList);
                        DataSource dataSource = (DataSource) this.getBeanFactory().getBean(dataSourceName);
                        IDatabaseManager.DatabaseType type = this.getDatabaseManager()
                                .getDatabaseType(dataSource);
                        TableFactory tableFactory = new TableFactory(dataSourceName, dataSource, type);
                        tableFactory.dropTables(newList);
                    }
                }
            }

            //move resources (jar, files and folders) on temp folder  
            List<String> resourcesPaths = ui.getResourcesPaths();
            if (resourcesPaths != null) {
                for (String resourcePath : resourcesPaths) {
                    try {
                        String fullResourcePath = servletContext.getRealPath(resourcePath);
                        File resFile = new File(fullResourcePath);
                        String relResPath = FilenameUtils.getPath(resFile.getAbsolutePath());
                        File newResFile = new File(
                                backupDirPath + File.separator + relResPath + resFile.getName());
                        if (resFile.isDirectory()) {
                            FileUtils.copyDirectory(resFile, newResFile);
                            resourcesMap.put(resFile, newResFile);
                            FileUtils.deleteDirectory(resFile);
                        } else {
                            FileUtils.copyFile(resFile, newResFile);
                            resourcesMap.put(resFile, newResFile);
                            FileUtils.forceDelete(resFile);
                        }
                    } catch (Exception e) {
                    }
                }
            }

            //upgrade report
            ComponentInstallationReport cir = report.getComponentReport(component.getCode(), true);
            cir.getDataSourceReport().upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED);
            cir.getDataReport().upgradeDatabaseStatus(SystemInstallationReport.Status.UNINSTALLED);
            this.saveReport(report);

            //remove plugin's xmlapplicationcontext if present
            if (appCtx != null) {
                appCtx.close();
                ctxList.remove(appCtx);
            }
            InitializerManager initializerManager = (InitializerManager) _applicationContext
                    .getBean("InitializerManager");
            initializerManager.reloadCurrentReport();
            ComponentManager componentManager = (ComponentManager) _applicationContext
                    .getBean("ComponentManager");
            componentManager.refresh();
        } catch (Exception e) {
            _logger.error("Unexpected error in component uninstallation process", e);
            throw new ApsSystemException("Unexpected error in component uninstallation process.", e);
        } finally {
            Thread.currentThread().setContextClassLoader(currentClassLoader);
            ApsWebApplicationUtils.executeSystemRefresh(servletContext);
        }
    } catch (Throwable t) {
        //restore files on temp folder
        try {
            for (Object object : resourcesMap.entrySet()) {
                File resFile = ((Map.Entry<File, File>) object).getKey();
                File newResFile = ((Map.Entry<File, File>) object).getValue();
                if (newResFile.isDirectory()) {
                    FileUtils.copyDirectoryToDirectory(newResFile, resFile.getParentFile());
                } else {
                    FileUtils.copyFile(newResFile, resFile.getParentFile());
                }
            }
        } catch (Exception e) {
        }
        _logger.error("Unexpected error in component uninstallation process", t);
        throw new ApsSystemException("Unexpected error in component uninstallation process.", t);
    } finally {
        //clean temp folder
    }
    return true;
}

From source file:org.apache.struts2.spring.StrutsSpringObjectFactory.java

/**
 * Constructs the spring object factory//from   ww  w  .  j av a  2  s . c  o  m
 * @param autoWire The type of autowiring to use
 * @param alwaysAutoWire Whether to always respect the autowiring or not
 * @param useClassCacheStr Whether to use the class cache or not
 * @param servletContext The servlet context
 * @since 2.1.3
 */
@Inject
public StrutsSpringObjectFactory(
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE, required = false) String autoWire,
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_AUTOWIRE_ALWAYS_RESPECT, required = false) String alwaysAutoWire,
        @Inject(value = StrutsConstants.STRUTS_OBJECTFACTORY_SPRING_USE_CLASS_CACHE, required = false) String useClassCacheStr,
        @Inject ServletContext servletContext, @Inject(StrutsConstants.STRUTS_DEVMODE) String devMode,
        @Inject Container container) {

    super();
    boolean useClassCache = "true".equals(useClassCacheStr);
    if (LOG.isInfoEnabled()) {
        LOG.info("Initializing Struts-Spring integration...");
    }

    Object rootWebApplicationContext = servletContext
            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

    if (rootWebApplicationContext instanceof RuntimeException) {
        RuntimeException runtimeException = (RuntimeException) rootWebApplicationContext;
        LOG.fatal(runtimeException.getMessage());
        return;
    }

    ApplicationContext appContext = (ApplicationContext) rootWebApplicationContext;
    if (appContext == null) {
        // uh oh! looks like the lifecycle listener wasn't installed. Let's inform the user
        String message = "********** FATAL ERROR STARTING UP STRUTS-SPRING INTEGRATION **********\n"
                + "Looks like the Spring listener was not configured for your web app! \n"
                + "Nothing will work until WebApplicationContextUtils returns a valid ApplicationContext.\n"
                + "You might need to add the following to web.xml: \n" + "    <listener>\n"
                + "        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>\n"
                + "    </listener>";
        LOG.fatal(message);
        return;
    }

    String watchList = container.getInstance(String.class, "struts.class.reloading.watchList");
    String acceptClasses = container.getInstance(String.class, "struts.class.reloading.acceptClasses");
    String reloadConfig = container.getInstance(String.class, "struts.class.reloading.reloadConfig");

    if ("true".equals(devMode) && StringUtils.isNotBlank(watchList)
            && appContext instanceof ClassReloadingXMLWebApplicationContext) {
        //prevent class caching
        useClassCache = false;

        ClassReloadingXMLWebApplicationContext reloadingContext = (ClassReloadingXMLWebApplicationContext) appContext;
        reloadingContext.setupReloading(watchList.split(","), acceptClasses, servletContext,
                "true".equals(reloadConfig));
        if (LOG.isInfoEnabled()) {
            LOG.info("Class reloading is enabled. Make sure this is not used on a production environment!",
                    watchList);
        }

        setClassLoader(reloadingContext.getReloadingClassLoader());

        //we need to reload the context, so our isntance of the factory is picked up
        reloadingContext.refresh();
    }

    this.setApplicationContext(appContext);

    int type = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME; // default
    if ("name".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
    } else if ("type".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
    } else if ("auto".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;
    } else if ("constructor".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
    } else if ("no".equals(autoWire)) {
        type = AutowireCapableBeanFactory.AUTOWIRE_NO;
    }
    this.setAutowireStrategy(type);

    this.setUseClassCache(useClassCache);

    this.setAlwaysRespectAutowireStrategy("true".equalsIgnoreCase(alwaysAutoWire));

    if (LOG.isInfoEnabled()) {
        LOG.info("... initialized Struts-Spring integration successfully");
    }
}

From source file:org.glom.web.server.OnlineGlomServlet.java

protected ConfiguredDocumentSet getConfiguredDocumentSet() {
    //See if there is already a shared documentSet:
    final ServletConfig config = this.getServletConfig();
    if (config == null) {
        Log.error("getServletConfig() return null");
        return null;
    }//from   www .j  av a  2 s  .  c om

    final ServletContext context = config.getServletContext();
    if (context == null) {
        Log.error("getServletContext() return null");
        return null;
    }

    //Use the existing shared document set, if any:
    final Object object = context.getAttribute(CONFIGURED_DOCUMENT_SET);
    if ((object != null) && !(object instanceof ConfiguredDocumentSet)) {
        Log.error("The configuredDocumentSet attribute is not of the expected type.");
        return null;
    }

    ConfiguredDocumentSet configuredDocumentSet = (ConfiguredDocumentSet) object;
    if (configuredDocumentSet != null) {
        return configuredDocumentSet;
    }

    //Create the shared document set:
    //TODO: Possible race condition between checking and creating+setting:
    configuredDocumentSet = new ConfiguredDocumentSet();
    try {
        configuredDocumentSet.readConfiguration();
    } catch (ServletException e) {
        Log.error("Configuration error", e);
        return null;
    }

    //Store it in the Servlet Context,
    //so it is available to all servlets:
    context.setAttribute(CONFIGURED_DOCUMENT_SET, configuredDocumentSet);

    return configuredDocumentSet;
}

From source file:com.rapid.forms.RapidFormAdapter.java

protected Map<String, String> getUserFormPageVariableValues(RapidRequest rapidRequest, String formId) {
    // get the servlet context
    ServletContext servletContext = rapidRequest.getRapidServlet().getServletContext();
    // get the map of form values
    Map<String, HashMap<String, String>> userFormPageVariableValues = (Map<String, HashMap<String, String>>) servletContext
            .getAttribute(USER_FORM_PAGE_VARIABLE_VALUES);
    // if there aren't any yet
    if (userFormPageVariableValues == null) {
        // make some
        userFormPageVariableValues = new HashMap<String, HashMap<String, String>>();
        // store them
        servletContext.setAttribute(USER_FORM_PAGE_VARIABLE_VALUES, userFormPageVariableValues);
    }/*  w  w  w  . j a  va2s .co  m*/
    // get the map of values
    HashMap<String, String> formPageVariableValues = userFormPageVariableValues.get(formId);
    // if it's null
    if (formPageVariableValues == null) {
        // make some
        formPageVariableValues = new HashMap<String, String>();
        // store them
        userFormPageVariableValues.put(formId, formPageVariableValues);
    }
    // return
    return formPageVariableValues;
}

From source file:be.fedict.eid.idp.protocol.openid.AbstractOpenIDProtocolService.java

private ServerManager getServerManager(HttpServletRequest request) {

    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    ServerManager serverManager = (ServerManager) servletContext.getAttribute(getServiceManagerAttribute());
    if (null != serverManager) {
        return serverManager;
    }/*from  w  w w.j  a  va2  s .co  m*/
    LOG.debug("creating an OpenID server manager");
    serverManager = new ServerManager();
    /*
     * Important that the shared association store and the private
     * association store are different. See also:
     * http://code.google.com/p/openid4java/source/detail?r=738
     */
    serverManager.setSharedAssociations(new InMemoryServerAssociationStore());
    serverManager.setPrivateAssociations(new InMemoryServerAssociationStore());
    String location = "https://" + request.getServerName();
    if (request.getServerPort() != 443) {
        location += ":" + request.getServerPort();
    }
    location += "/eid-idp";
    String opEndpointUrl = location + "/protocol/" + getPath();
    LOG.debug("OP endpoint URL: " + opEndpointUrl);
    serverManager.setOPEndpointUrl(opEndpointUrl);
    servletContext.setAttribute(getServiceManagerAttribute(), serverManager);
    return serverManager;
}

From source file:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * init is called one time when the Servlet is loaded. This is the place where one-time
 * initialization is done. Specifically, we load the properties file for this application, and
 * create the AbstractCatalog object for subsequent use.
 * //from   w w w . j  a va  2  s  .  c  o  m
 * @param config servlet configuration information
 * @exception ServletException there was a problem with initialization
 */
@Override
public void init(final ServletConfig config) throws ServletException {
    super.init(config);

    getBuildVersion();

    try {
        // Trecho para inicializar o layer lexml para provimento
        // dos registros
        try {
            LexMLOAI.helper.inicializar();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
        // fim inicializacao do LexmL
        HashMap attributes = null;
        ServletContext context = getServletContext();
        Properties properties = (Properties) context.getAttribute(PROPERTIES_SERVLET_CONTEXT_ATTRIBUTE);
        if (properties == null) {
            final String PROPERTIES_INIT_PARAMETER = "properties";
            log.debug("OAIHandler.init(..): No '" + PROPERTIES_SERVLET_CONTEXT_ATTRIBUTE
                    + "' servlet context attribute. Trying to use init parameter '" + PROPERTIES_INIT_PARAMETER
                    + "'");

            InputStream in = getClass().getResourceAsStream("/oaicat.properties");
            if (in != null) {
                properties = new Properties();
                properties.load(in);
                attributes = getAttributes(properties);
            } else {
                log.error("Arquivo oaicat.properties nao encontrado.");
            }
        } else {
            log.debug("Load context properties");
            attributes = getAttributes(properties);
        }

        log.debug("Store global properties");
        attributesMap.put("global", attributes);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw new ServletException(e.getMessage());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        throw new ServletException(e.getMessage());
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        throw new ServletException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new ServletException(e.getMessage());
    } catch (Throwable e) {
        e.printStackTrace();
        throw new ServletException(e.getMessage());
    } finally {
        JPAUtil.closeEntityManager();
    }
}

From source file:com.hphoto.server.ApiServlet.java

public void init(ServletConfig config) throws ServletException {
    if (server != null) {
        return;//from   w w w  . j a  v a  2 s . c  o m
    }
    try {
        ServletContext context = config.getServletContext();
        this.server = (TableServer) context.getAttribute("hphoto.tableServer");
        this.conf = (Configuration) context.getAttribute("hphoto.conf");
    } catch (Exception e) {
        throw new ServletException(e);
    }
}