Example usage for javax.servlet ServletContext getInitParameter

List of usage examples for javax.servlet ServletContext getInitParameter

Introduction

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

Prototype

public String getInitParameter(String name);

Source Link

Document

Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.

Usage

From source file:org.wso2.carbon.apimgt.webapp.publisher.lifecycle.listener.APIPublisherLifecycleListener.java

@Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
    if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())
            && WebappPublisherConfig.getInstance().isPublished()) {
        StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
        ServletContext servletContext = context.getServletContext();
        String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
        boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);

        String profile = System.getProperty(PROPERTY_PROFILE);
        if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase())
                && isManagedApi) {
            try {
                AnnotationProcessor annotationProcessor = new AnnotationProcessor(context);
                Set<String> annotatedSwaggerAPIClasses = annotationProcessor
                        .scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName());
                List<APIResourceConfiguration> apiDefinitions = annotationProcessor
                        .extractAPIInfo(servletContext, annotatedSwaggerAPIClasses);
                for (APIResourceConfiguration apiDefinition : apiDefinitions) {
                    APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition);
                    APIPublisherUtil.setResourceAuthTypes(servletContext, apiConfig);
                    try {
                        int tenantId = APIPublisherDataHolder.getInstance().getTenantManager()
                                .getTenantId(apiConfig.getTenantDomain());

                        boolean isTenantActive = APIPublisherDataHolder.getInstance().getTenantManager()
                                .isTenantActive(tenantId);
                        if (isTenantActive) {
                            boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted();
                            if (isServerStarted) {
                                APIPublisherService apiPublisherService = APIPublisherDataHolder.getInstance()
                                        .getApiPublisherService();
                                if (apiPublisherService == null) {
                                    throw new IllegalStateException(
                                            "API Publisher service is not initialized properly");
                                }// w w w . j a va 2 s  . c  o  m
                                apiPublisherService.publishAPI(apiConfig);
                            } else {
                                if (log.isDebugEnabled()) {
                                    log.debug("Server has not started yet. Hence adding API '"
                                            + apiConfig.getName() + "' to the queue");
                                }
                                APIPublisherDataHolder.getInstance().getUnpublishedApis().push(apiConfig);
                            }
                        } else {
                            log.error("No tenant [" + apiConfig.getTenantDomain() + "] "
                                    + "found when publishing the Web app");
                        }
                    } catch (Throwable e) {
                        log.error("Error occurred while publishing API '" + apiConfig.getName()
                                + "' with the context '" + apiConfig.getContext() + "' and version '"
                                + apiConfig.getVersion() + "'", e);
                    }
                }
            } catch (IOException e) {
                log.error("Error encountered while discovering annotated classes", e);
            } catch (ClassNotFoundException e) {
                log.error("Error while scanning class for annotations", e);
            } catch (UserStoreException e) {
                log.error("Error while retrieving tenant admin user for the tenant domain"
                        + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(), e);
            } catch (Throwable e) {
                // This is done to stop tomcat failure if a webapp failed to publish apis.
                log.error("Failed to Publish api from " + servletContext.getContextPath(), e);
            }
        }
    }
}

From source file:com.github.persapiens.jsfboot.mojarra.MojarraServletContextInitializerIT.java

public void testOnStartup() throws ServletException {
    MojarraServletContextInitializer mojarraServletContextInitializer = new MojarraServletContextInitializer(
            this.mojarraProperties);

    ServletContext servletContext = new MojarraMockServletContext();

    mojarraServletContextInitializer.onStartup(servletContext);

    assertThat(servletContext.getInitParameter(MojarraServletContextConfigurer.PREFFIX + ".clientStateTimeout"))
            .isEqualTo("10");
}

From source file:com.sa.osgi.jetty.UploadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//www . j  av  a2  s  .com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        String ss = servletContext.getInitParameter("javax.servlet.context.tempdir");
        File repository = new File("/tmp");//(File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);
        System.out.println("context var: " + ss);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            // Parse the request
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();

                if (item.isFormField()) {
                    //                    processFormField(item);
                } else {
                    processUploadedFile(item);
                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    response.sendRedirect("/welcome");

    //        RequestDispatcher dis = request.getRequestDispatcher("/welcome");
    //        dis.forward(request, response);

}

From source file:com.github.persapiens.jsfboot.myfaces.MyfacesServletContextInitializerIT.java

public void testOnStartup() throws ServletException {
    MyfacesServletContextInitializer myfacesServletContextInitializer = new MyfacesServletContextInitializer(
            this.myfacesProperties);

    ServletContext servletContext = new MyfacesMockServletContext();

    myfacesServletContextInitializer.onStartup(servletContext);

    assertThat(servletContext
            .getInitParameter(MyfacesServletContextConfigurer.PREFFIX + "STRICT_JSF_2_CC_EL_RESOLVER"))
                    .isEqualTo("myElResolver");
}

From source file:org.archive.wayback.webapp.RequestMapper.java

/**
 * @param configPath//www  .jav a 2  s. c  o  m
 * @param servletContext
 * @throws ConfigurationException 
 */
@SuppressWarnings("unchecked")
public RequestMapper(ServletContext servletContext) throws ConfigurationException {

    String configPath = servletContext.getInitParameter(CONFIG_PATH);
    if (configPath == null) {
        throw new ConfigurationException("Missing " + CONFIG_PATH + " parameter");
    }
    String resolvedPath = servletContext.getRealPath(configPath);
    Resource resource = new FileSystemResource(resolvedPath);
    factory = new XmlBeanFactory(resource);
    Map map = factory.getBeansOfType(PropertyPlaceholderConfigurer.class);
    if (map != null) {
        Collection<PropertyPlaceholderConfigurer> macros = map.values();
        for (PropertyPlaceholderConfigurer macro : macros) {
            macro.postProcessBeanFactory(factory);
        }
    }
    factory.preInstantiateSingletons();
}

From source file:org.wso2.carbon.device.mgt.core.config.permission.lifecycle.WebAppDeploymentLifecycleListener.java

@Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
    if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
        StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
        ServletContext servletContext = context.getServletContext();
        String contextPath = context.getServletContext().getContextPath();
        String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
        boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);

        if (isManagedApi) {
            try {
                AnnotationProcessor annotationProcessor = new AnnotationProcessor(context);
                Set<String> annotatedAPIClasses = annotationProcessor
                        .scanStandardContext(io.swagger.annotations.SwaggerDefinition.class.getName());
                List<Permission> permissions = annotationProcessor.extractPermissions(annotatedAPIClasses);
                PermissionManagerService permissionManagerService = PermissionManagerServiceImpl.getInstance();
                if (permissions != null) {
                    for (Permission permission : permissions) {
                        permissionManagerService.addPermission(permission);
                    }//from  w  ww . j a v  a  2s .com
                }
            } catch (PermissionManagementException e) {
                log.error("Exception occurred while adding the permissions from webapp : "
                        + servletContext.getContextPath(), e);
            } catch (IOException e) {
                log.error("Cannot find API annotation Class in the webapp '" + contextPath + "' class path", e);
            }
        }

    }
}

From source file:org.joinfaces.mojarra.MojarraServletContextInitializerIT.java

@Test
public void testOnStartup() throws ServletException {
    MojarraServletContextInitializer mojarraServletContextInitializer = new MojarraServletContextInitializer(
            this.mojarraProperties);

    ServletContext servletContext = new MojarraMockServletContext();

    mojarraServletContextInitializer.onStartup(servletContext);

    assertThat(servletContext.getInitParameter(MojarraServletContextConfigurer.PREFFIX + ".clientStateTimeout"))
            .isEqualTo("10");
}

From source file:org.joinfaces.myfaces.MyfacesServletContextInitializerIT.java

@Test
public void testOnStartup() throws ServletException {
    MyfacesServletContextInitializer myfacesServletContextInitializer = new MyfacesServletContextInitializer(
            this.myfacesProperties);

    ServletContext servletContext = new MyfacesMockServletContext();

    myfacesServletContextInitializer.onStartup(servletContext);

    assertThat(servletContext
            .getInitParameter(MyfacesServletContextConfigurer.PREFFIX + "STRICT_JSF_2_CC_EL_RESOLVER"))
                    .isEqualTo("myElResolver");
}

From source file:org.jwatch.listener.settings.SettingsLoaderListener.java

public void contextInitialized(ServletContextEvent event) {
    try {//from   w ww  . j  a va 2s. c o  m
        log.info("Starting Settings Load...");
        long start = Calendar.getInstance().getTimeInMillis();

        ServletContext sc = event.getServletContext();
        if (sc != null) {
            String sMaxEvents = sc.getInitParameter("maxevents");
            int maxEvents = NumberUtils.toInt(sMaxEvents, EventService.DEFAULT_MAX_EVENT_LIST_SIZE);
            sc.setAttribute("maxevents", maxEvents); // expose to other servlets
            EventService.setMaxEventListSize(maxEvents);

            String sMaxShowEvents = sc.getInitParameter("maxshowevents");
            int maxShowEvents = NumberUtils.toInt(sMaxShowEvents,
                    EventService.DEFAULT_MAX_SHOW_EVENT_LIST_SIZE);
            sc.setAttribute("maxshowevents", maxShowEvents); // expose to other servlets
            EventService.setMaxShowEventListSize(maxShowEvents);
        }

        // load config file and instances
        QuartzInstanceService.initQuartzInstanceMap();

        SettingsUtil.loadProperties();

        // connect/start DB
        connectionUtil = new ConnectionUtil(SettingsUtil.getDBFilePath());
        StringBuffer jwatchLog = new StringBuffer();
        jwatchLog.append("CREATE TEXT TABLE IF NOT EXISTS JWATCHLOG (").append("id INTEGER IDENTITY,")
                .append("CALENDARNAME VARCHAR(256),").append("JOBGROUP VARCHAR(256),")
                .append("JOBNAME VARCHAR(256),").append("SCHEDULERNAME VARCHAR(256),")
                .append("TRIGGERGROUP VARCHAR(256),").append("TRIGGERNAME VARCHAR(256),")
                .append("FIRETIME DATE,").append("NEXTFIRETIME  DATE,").append("PREVIOUSFIRETIME  DATE,")
                .append("SCHEDULEDFIRETIME  DATE,").append("RECOVERING BOOLEAN,").append("JOBRUNTIME BIGINT, ")
                .append("REFIRECOUNT INTEGER, ").append("SCHEDULERID VARCHAR(256),")
                .append("QUARTZINSTANCEID VARCHAR(256)").append(")");
        connectionUtil.update(jwatchLog.toString());

        long end = Calendar.getInstance().getTimeInMillis();
        log.info("Settings startup completed in: " + (end - start) + " ms");
    } catch (Throwable t) {
        log.error("Failed to initialize Settings.", t);
    }
}

From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java

protected String getAppPropertiesConfig(ServletContext sc) {
    return sc.getInitParameter(APP_PROPS_CONFIG_PARAM);
}