Example usage for javax.servlet ServletContext log

List of usage examples for javax.servlet ServletContext log

Introduction

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

Prototype

public void log(String message, Throwable throwable);

Source Link

Document

Writes an explanatory message and a stack trace for a given Throwable exception to the servlet log file.

Usage

From source file:org.owasp.webgoat.application.WebGoatServletListener.java

private void setApplicationVariables(ServletContext context) {
    Application app = Application.getInstance();
    try {/*w  ww.j ava  2s. com*/
        InputStream inputStream = context.getResourceAsStream("/META-INF/MANIFEST.MF");
        Manifest manifest = new Manifest(inputStream);
        Attributes attr = manifest.getMainAttributes();
        String name = attr.getValue("Specification-Title");
        String version = attr.getValue("Specification-Version");
        String build = attr.getValue("Implementation-Version");
        app.setName(name);
        app.setVersion(version);
        app.setBuild(build);
    } catch (IOException ioe) {
        context.log("Error setting application variables", ioe);
    }
}

From source file:org.mule.config.builders.MuleXmlBuilderContextListener.java

public void initialize(ServletContext context) {
    String config = context.getInitParameter(INIT_PARAMETER_MULE_CONFIG);
    if (config == null) {
        config = getDefaultConfigResource();
        if (logger.isDebugEnabled()) {
            logger.debug("No Mule config file(s) specified, using default: " + config);
        }/*from w w w  .  j a va 2  s  .co m*/
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Mule config file(s): " + config);
        }
    }

    try {
        muleContext = createMuleContext(config, context);
        context.setAttribute(MuleProperties.MULE_CONTEXT_PROPERTY, muleContext);
        muleContext.start();
    } catch (MuleException ex) {
        context.log(ex.getMessage(), ex);
        // Logging is not configured OOTB for Tomcat, so we'd better make a
        // start-up failure plain to see.
        ex.printStackTrace();
    } catch (Error error) {
        // WSAD doesn't always report the java.lang.Error, log it
        context.log(error.getMessage(), error);
        // Logging is not configured OOTB for Tomcat, so we'd better make a
        // start-up failure plain to see.
        error.printStackTrace();
        throw error;
    }
}

From source file:org.tobarsegais.webapp.ServletContextListenerImpl.java

public void contextInitialized(ServletContextEvent sce) {
    ServletContext application = sce.getServletContext();
    Map<String, String> bundles = new HashMap<String, String>();
    Map<String, Toc> contents = new LinkedHashMap<String, Toc>();
    List<IndexEntry> keywords = new ArrayList<IndexEntry>();
    Directory index = new RAMDirectory();
    Analyzer analyzer = new StandardAnalyzer(LUCENE_VERSON);
    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(LUCENE_VERSON, analyzer);
    IndexWriter indexWriter;/*  ww  w  .j  av a2 s .c o m*/
    try {
        indexWriter = new IndexWriter(index, indexWriterConfig);
    } catch (IOException e) {
        application.log("Cannot create search index. Search will be unavailable.", e);
        indexWriter = null;
    }
    for (String path : (Set<String>) application.getResourcePaths(BUNDLE_PATH)) {
        if (path.endsWith(".jar")) {
            String key = path.substring("/WEB-INF/bundles/".length(), path.lastIndexOf(".jar"));
            application.log("Parsing " + path);
            URLConnection connection = null;
            try {
                URL url = new URL("jar:" + application.getResource(path) + "!/");
                connection = url.openConnection();
                if (!(connection instanceof JarURLConnection)) {
                    application.log(path + " is not a jar file, ignoring");
                    continue;
                }
                JarURLConnection jarConnection = (JarURLConnection) connection;
                JarFile jarFile = jarConnection.getJarFile();
                Manifest manifest = jarFile.getManifest();
                if (manifest != null) {
                    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
                    if (symbolicName != null) {
                        int i = symbolicName.indexOf(';');
                        if (i != -1) {
                            symbolicName = symbolicName.substring(0, i);
                        }
                        bundles.put(symbolicName, key);
                        key = symbolicName;
                    }
                }

                JarEntry pluginEntry = jarFile.getJarEntry("plugin.xml");
                if (pluginEntry == null) {
                    application.log(path + " does not contain a plugin.xml file, ignoring");
                    continue;
                }
                Plugin plugin = Plugin.read(jarFile.getInputStream(pluginEntry));

                Extension tocExtension = plugin.getExtension("org.eclipse.help.toc");
                if (tocExtension == null || tocExtension.getFile("toc") == null) {
                    application.log(path + " does not contain a 'org.eclipse.help.toc' extension, ignoring");
                    continue;
                }
                JarEntry tocEntry = jarFile.getJarEntry(tocExtension.getFile("toc"));
                if (tocEntry == null) {
                    application.log(path + " is missing the referenced toc: " + tocExtension.getFile("toc")
                            + ", ignoring");
                    continue;
                }
                Toc toc;
                try {
                    toc = Toc.read(jarFile.getInputStream(tocEntry));
                } catch (IllegalStateException e) {
                    application.log("Could not parse " + path + " due to " + e.getMessage(), e);
                    continue;
                }
                contents.put(key, toc);

                Extension indexExtension = plugin.getExtension("org.eclipse.help.index");
                if (indexExtension != null && indexExtension.getFile("index") != null) {
                    JarEntry indexEntry = jarFile.getJarEntry(indexExtension.getFile("index"));
                    if (indexEntry != null) {
                        try {
                            keywords.addAll(Index.read(key, jarFile.getInputStream(indexEntry)).getChildren());
                        } catch (IllegalStateException e) {
                            application.log("Could not parse " + path + " due to " + e.getMessage(), e);
                        }
                    } else {
                        application.log(
                                path + " is missing the referenced index: " + indexExtension.getFile("index"));
                    }

                }
                application.log(path + " successfully parsed and added as " + key);
                if (indexWriter != null) {
                    application.log("Indexing content of " + path);
                    Set<String> files = new HashSet<String>();
                    Stack<Iterator<? extends TocEntry>> stack = new Stack<Iterator<? extends TocEntry>>();
                    stack.push(Collections.singleton(toc).iterator());
                    while (!stack.empty()) {
                        Iterator<? extends TocEntry> cur = stack.pop();
                        if (cur.hasNext()) {
                            TocEntry entry = cur.next();
                            stack.push(cur);
                            if (!entry.getChildren().isEmpty()) {
                                stack.push(entry.getChildren().iterator());
                            }
                            String file = entry.getHref();
                            if (file == null) {
                                continue;
                            }
                            int hashIndex = file.indexOf('#');
                            if (hashIndex != -1) {
                                file = file.substring(0, hashIndex);
                            }
                            if (files.contains(file)) {
                                // already indexed
                                // todo work out whether to just pull the section
                                continue;
                            }
                            Document document = new Document();
                            document.add(new Field("title", entry.getLabel(), Field.Store.YES,
                                    Field.Index.ANALYZED));
                            document.add(new Field("href", key + "/" + entry.getHref(), Field.Store.YES,
                                    Field.Index.NO));
                            JarEntry docEntry = jarFile.getJarEntry(file);
                            if (docEntry == null) {
                                // ignore missing file
                                continue;
                            }
                            InputStream inputStream = null;
                            try {
                                inputStream = jarFile.getInputStream(docEntry);
                                org.jsoup.nodes.Document docDoc = Jsoup.parse(IOUtils.toString(inputStream));
                                document.add(new Field("contents", docDoc.body().text(), Field.Store.NO,
                                        Field.Index.ANALYZED));
                                indexWriter.addDocument(document);
                            } finally {
                                IOUtils.closeQuietly(inputStream);
                            }
                        }
                    }
                }
            } catch (XMLStreamException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } catch (MalformedURLException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } catch (IOException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } finally {
                if (connection instanceof HttpURLConnection) {
                    // should never be the case, but we should try to be sure
                    ((HttpURLConnection) connection).disconnect();
                }
            }
        }
    }
    if (indexWriter != null) {
        try {
            indexWriter.close();
        } catch (IOException e) {
            application.log("Cannot create search index. Search will be unavailable.", e);
        }
        application.setAttribute("index", index);
    }

    application.setAttribute("toc", Collections.unmodifiableMap(contents));
    application.setAttribute("keywords", new Index(keywords));
    application.setAttribute("bundles", Collections.unmodifiableMap(bundles));
    application.setAttribute("analyzer", analyzer);
    application.setAttribute("contentsQueryParser", new QueryParser(LUCENE_VERSON, "contents", analyzer));
}

From source file:org.rapla.server.jsonrpc.JsonServlet.java

public void service(final HttpServletRequest req, final HttpServletResponse resp, ServletContext servletContext)
        throws IOException {
    try {//ww  w.  j a v a  2s  .c o  m
        final CallType call = createActiveCall(req, resp);
        call.xsrf = xsrf;

        call.noCache();
        //      if (!acceptJSON(call)) {
        //        textError(call, SC_BAD_REQUEST, "Must Accept " + JsonConstants.JSON_TYPE);
        //        return;
        //      }

        perThreadCall.set(call);
        doService(call);

        if (call.internalFailure != null) {
            // Hide internal errors from the client.
            //
            final String msg = "Error in " + call.method.getName();
            servletContext.log(msg, call.internalFailure);
            call.onFailure(new Exception("Internal Server Error"));
        }

        final String out = formatResult(call);
        RPCServletUtils.writeResponse(servletContext, call.httpResponse, out, call.callback == null
                && out.length() > 256 && RPCServletUtils.acceptsGzipEncoding(call.httpRequest));
    } finally {
        perThreadCall.set(null);
    }
}

From source file:org.mule.config.builders.DeployableMuleXmlContextListener.java

public void initialize(ServletContext context) {
    String config = context.getInitParameter(MuleXmlBuilderContextListener.INIT_PARAMETER_MULE_CONFIG);
    if (config == null) {
        config = MuleServer.DEFAULT_CONFIGURATION;
        if (logger.isDebugEnabled()) {
            logger.debug("No Mule config file(s) specified, using default: " + config);
        }/* w w w  .  j a  v a  2  s .  com*/
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Mule config file(s): " + config);
        }
    }

    if (muleContext == null) {
        throw new RuntimeException("MuleContext is not available");
    }

    try {
        configurationBuilder = new WebappMuleXmlConfigurationBuilder(context, config);
        configurationBuilder.setUseDefaultConfigResource(false);

        // Support Spring-first configuration in webapps
        final ApplicationContext parentContext = (ApplicationContext) context
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        if (parentContext != null) {
            configurationBuilder.setParentContext(parentContext);
        }
        configurationBuilder.configure(muleContext);
    } catch (MuleException ex) {
        context.log(ex.getMessage(), ex);
        // Logging is not configured OOTB for Tomcat, so we'd better make a
        // start-up failure plain to see.
        ex.printStackTrace();
    } catch (Error error) {
        // WSAD doesn't always report the java.lang.Error, log it
        context.log(error.getMessage(), error);
        // Logging is not configured OOTB for Tomcat, so we'd better make a
        // start-up failure plain to see.
        error.printStackTrace();
        throw error;
    }
}

From source file:com.sun.faces.config.ConfigureListener.java

/**
 * <p>Verify that all of the application-defined objects that have been
 * configured can be successfully instantiated.</p>
 *
 * @param context <code>ServletContext</code> instance for this application
 * @param fcb     <code>FacesConfigBean</code> containing the
 *                configuration information
 * @throws FacesException if an application-defined object cannot
 *                        be instantiated
 *///w w  w . j ava2 s .  c  o m
private void verifyObjects(ServletContext context, FacesConfigBean fcb) throws FacesException {

    if (log.isDebugEnabled()) {
        log.debug("Verifying application objects");
    }

    ApplicationFactory af = (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
    Application app = af.getApplication();
    RenderKitFactory rkf = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
    boolean success = true;

    // Check components
    ComponentBean comp[] = fcb.getComponents();
    for (int i = 0, len = comp.length; i < len; i++) {
        try {
            app.createComponent(comp[i].getComponentType());
        } catch (Exception e) {
            context.log(comp[i].getComponentClass(), e);
            success = false;
        }
    }

    // Check converters
    ConverterBean conv1[] = fcb.getConvertersByClass();
    Class clazz;
    for (int i = 0, len = conv1.length; i < len; i++) {
        try {
            clazz = Util.loadClass(conv1[i].getConverterForClass(), this);
            app.createConverter(clazz);
        } catch (Exception e) {
            context.log(conv1[i].getConverterForClass(), e);
            clazz = null;
            success = false;
        }
        try {
            app.createConverter(clazz);
        } catch (Exception e) {
            context.log(conv1[i].getConverterClass(), e);
            success = false;
        }
    }
    ConverterBean conv2[] = fcb.getConvertersById();
    for (int i = 0, len = conv2.length; i < len; i++) {
        try {
            app.createConverter(conv2[i].getConverterId());
        } catch (Exception e) {
            context.log(conv2[i].getConverterClass());
            success = false;
        }
    }

    // Check renderers
    RenderKitBean rkb[] = fcb.getRenderKits();
    RenderKit rk;
    for (int i = 0, len = rkb.length; i < len; i++) {
        try {
            rk = rkf.getRenderKit(null, rkb[i].getRenderKitId());
            RendererBean rb[] = rkb[i].getRenderers();
            for (int j = 0, len2 = rb.length; j < len2; j++) {
                try {
                    rk.getRenderer(rb[j].getComponentFamily(), rb[j].getRendererType());
                } catch (Exception e) {
                    context.log(rb[j].getRendererClass(), e);
                    success = false;
                }
            }
        } catch (Exception e) {
            context.log(rkb[i].getRenderKitId());
            success = false;
        }
    }

    // Check validators
    ValidatorBean val[] = fcb.getValidators();
    for (int i = 0, len = val.length; i < len; i++) {
        try {
            app.createValidator(val[i].getValidatorId());
        } catch (Exception e) {
            context.log(val[i].getValidatorClass(), e);
            success = false;
        }
    }

    // Throw an exception on any failures
    if (!success) {
        String message;
        try {
            message = Util.getExceptionMessageString(Util.OBJECT_CREATION_ERROR_ID, new Object[] {});
        } catch (Exception ee) {
            message = "One or more configured application objects "
                    + "cannot be created.  See your web application logs " + "for details.";
        }
        if (log.isErrorEnabled()) {
            log.error(message);
        }
        throw new FacesException(message);
    } else {
        if (log.isInfoEnabled()) {
            log.info("Application object verification completed successfully");
        }
    }

}

From source file:org.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.java

public void doFilter(ServletRequest rq, ServletResponse rs, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) rq;
    HttpServletResponse response = (HttpServletResponse) rs;
    ServletContext servletContext = filterConfig.getServletContext();

    SiteMeshWebAppContext webAppContext = new SiteMeshWebAppContext(request, response, servletContext);
    ContentProcessor contentProcessor = initContentProcessor(webAppContext);
    DecoratorSelector decoratorSelector = initDecoratorSelector(webAppContext);

    if (filterAlreadyAppliedForRequest(request)) {
        // Prior to Servlet 2.4 spec, it was unspecified whether the filter should be called again upon an include().
        chain.doFilter(request, response);
        return;/*from   ww w . j  av  a 2 s  . co m*/
    }

    if (!contentProcessor.handles(webAppContext)) {
        // Optimization: If the content doesn't need to be processed, bypass SiteMesh.
        chain.doFilter(request, response);
        return;
    }

    if (containerTweaks.shouldAutoCreateSession()) {
        request.getSession(true);
    }

    try {

        Content content = obtainContent(contentProcessor, webAppContext, request, response, chain);

        if (content == null) {
            return;
        }

        detectContentTypeFromPage(content, response);
        Decorator decorator = decoratorSelector.selectDecorator(content, webAppContext);
        persistenceInterceptor.reconnect();
        decorator.render(content, webAppContext);

    } catch (IllegalStateException e) {
        // Some containers (such as WebLogic) throw an IllegalStateException when an error page is served.
        // It may be ok to ignore this. However, for safety it is propegated if possible.
        if (!containerTweaks.shouldIgnoreIllegalStateExceptionOnErrorPage()) {
            throw e;
        }
    } catch (RuntimeException e) {
        if (containerTweaks.shouldLogUnhandledExceptions()) {
            // Some containers (such as Tomcat 4) swallow RuntimeExceptions in filters.
            servletContext.log("Unhandled exception occurred whilst decorating page", e);
        }
        throw e;
    } catch (ServletException e) {
        request.setAttribute(ALREADY_APPLIED_KEY, null);
        throw e;
    } finally {
        if (persistenceInterceptor.isOpen()) {
            persistenceInterceptor.destroy();
        }
    }

}

From source file:com.aoindustries.website.signup.SignupCustomizeManagementActionHelper.java

public static void setRequestAttributes(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response, SignupSelectPackageForm signupSelectPackageForm,
        SignupCustomizeServerForm signupCustomizeServerForm,
        SignupCustomizeManagementForm signupCustomizeManagementForm) throws IOException, SQLException {
    AOServConnector rootConn = SiteSettings.getInstance(servletContext).getRootAOServConnector();
    PackageDefinition packageDefinition = rootConn.getPackageDefinitions()
            .get(signupSelectPackageForm.getPackageDefinition());
    if (packageDefinition == null)
        throw new SQLException(
                "Unable to find PackageDefinition: " + signupSelectPackageForm.getPackageDefinition());
    List<PackageDefinitionLimit> limits = packageDefinition.getLimits();

    // Get the total harddrive space in gigabytes
    int totalHardwareDiskSpace = SignupCustomizeServerActionHelper.getTotalHardwareDiskSpace(rootConn,
            signupCustomizeServerForm);//from   ww  w  . j a v  a2 s . c o m

    // Find all the options
    List<Option> backupOnsiteOptions = new ArrayList<Option>();
    List<Option> backupOffsiteOptions = new ArrayList<Option>();
    List<Option> distributionScanOptions = new ArrayList<Option>();
    List<Option> failoverOptions = new ArrayList<Option>();
    for (PackageDefinitionLimit limit : limits) {
        Resource resource = limit.getResource();
        String resourceName = resource.getName();
        if (resourceName.startsWith("backup_onsite_")) {
            int limitPower = limit.getHardLimit();
            if (limitPower == PackageDefinitionLimit.UNLIMITED || limitPower > 0) {
                // This is per gigabyte of physical space
                BigDecimal additionalRate = limit.getAdditionalRate();
                if (additionalRate == null)
                    additionalRate = BigDecimal.valueOf(0, 2);
                backupOnsiteOptions.add(new Option(limit.getPkey(), resource.toString(),
                        additionalRate.multiply(BigDecimal.valueOf(totalHardwareDiskSpace))));
            }
        } else if (resourceName.startsWith("backup_offsite_")) {
            int limitPower = limit.getHardLimit();
            if (limitPower == PackageDefinitionLimit.UNLIMITED || limitPower > 0) {
                // This is per gigabyte of physical space
                BigDecimal additionalRate = limit.getAdditionalRate();
                if (additionalRate == null)
                    additionalRate = BigDecimal.valueOf(0, 2);
                backupOffsiteOptions.add(new Option(limit.getPkey(), resource.toString(),
                        additionalRate.multiply(BigDecimal.valueOf(totalHardwareDiskSpace))));
            }
        }
    }
    // Distribution scan option
    {
        Resource resource = rootConn.getResources().get(Resource.DISTRIBUTION_SCAN);
        if (resource == null) {
            servletContext.log(null,
                    new SQLException("Unable to find Resource: " + Resource.DISTRIBUTION_SCAN));
        } else {
            PackageDefinitionLimit limit = packageDefinition.getLimit(resource);
            if (limit != null) {
                int hard = limit.getHardLimit();
                if (hard == PackageDefinitionLimit.UNLIMITED || hard > 0) {
                    BigDecimal additionalRate = limit.getAdditionalRate();
                    if (additionalRate == null)
                        additionalRate = BigDecimal.valueOf(0, 2);
                    distributionScanOptions
                            .add(new Option(limit.getPkey(), resource.toString(), additionalRate));
                }
            }
        }
    }
    // Failover option
    {
        Resource resource = rootConn.getResources().get(Resource.FAILOVER);
        if (resource == null) {
            servletContext.log(null, new SQLException("Unable to find Resource: " + Resource.FAILOVER));
        } else {
            PackageDefinitionLimit limit = packageDefinition.getLimit(resource);
            if (limit != null) {
                int hard = limit.getHardLimit();
                if (hard == PackageDefinitionLimit.UNLIMITED || hard > 0) {
                    // This is per gigabyte of physical space
                    BigDecimal additionalRate = limit.getAdditionalRate();
                    if (additionalRate == null)
                        additionalRate = BigDecimal.valueOf(0, 2);
                    additionalRate = additionalRate.multiply(BigDecimal.valueOf(totalHardwareDiskSpace));
                    failoverOptions.add(new Option(limit.getPkey(), resource.toString(), additionalRate));

                    // Only once the failover option is available will the MySQL replication option be available
                    Resource mrResource = rootConn.getResources().get(Resource.MYSQL_REPLICATION);
                    if (mrResource == null) {
                        servletContext.log(null,
                                new SQLException("Unable to find Resource: " + Resource.MYSQL_REPLICATION));
                    } else {
                        PackageDefinitionLimit mrLimit = packageDefinition.getLimit(mrResource);
                        if (mrLimit != null) {
                            int mrHard = mrLimit.getHardLimit();
                            if (mrHard == PackageDefinitionLimit.UNLIMITED || mrHard > 0) {
                                BigDecimal mrAdditionalRate = mrLimit.getAdditionalRate();
                                if (mrAdditionalRate == null)
                                    mrAdditionalRate = BigDecimal.valueOf(0, 2);
                                failoverOptions.add(new Option(mrLimit.getPkey(), mrResource.toString(),
                                        additionalRate.add(mrAdditionalRate)));
                            }
                        }
                    }
                }
            }
        }
    }

    if (!backupOnsiteOptions.isEmpty())
        backupOnsiteOptions.add(0, new Option(-1, "No On-Site Backup", BigDecimal.valueOf(0, 2)));
    if (!backupOffsiteOptions.isEmpty())
        backupOffsiteOptions.add(0, new Option(-1, "No Off-Site Backup", BigDecimal.valueOf(0, 2)));
    if (!distributionScanOptions.isEmpty())
        distributionScanOptions.add(0, new Option(-1, "No daily scans", BigDecimal.valueOf(0, 2)));
    if (!failoverOptions.isEmpty())
        failoverOptions.add(0, new Option(-1, "No Fail-Over Mirror", BigDecimal.valueOf(0, 2)));

    // Sort by price
    Collections.sort(backupOnsiteOptions, new Option.PriceComparator());
    Collections.sort(backupOffsiteOptions, new Option.PriceComparator());
    Collections.sort(distributionScanOptions, new Option.PriceComparator());
    Collections.sort(failoverOptions, new Option.PriceComparator());

    // Clear any customization settings that are not part of the current package definition (this happens when they
    // select a different package type)
    if (signupCustomizeManagementForm.getBackupOnsiteOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeManagementForm.getBackupOnsiteOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeManagementForm.setBackupOnsiteOption(-1);
    }
    if (signupCustomizeManagementForm.getBackupOffsiteOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeManagementForm.getBackupOffsiteOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeManagementForm.setBackupOffsiteOption(-1);
    }
    if (signupCustomizeManagementForm.getDistributionScanOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeManagementForm.getDistributionScanOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeManagementForm.setDistributionScanOption(-1);
    }
    if (signupCustomizeManagementForm.getFailoverOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeManagementForm.getFailoverOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeManagementForm.setFailoverOption(-1);
    }

    // Store to request
    request.setAttribute("packageDefinition", packageDefinition);
    request.setAttribute("hardwareRate", SignupCustomizeServerActionHelper.getHardwareMonthlyRate(rootConn,
            signupCustomizeServerForm, packageDefinition));
    request.setAttribute("backupOnsiteOptions", backupOnsiteOptions);
    request.setAttribute("backupOffsiteOptions", backupOffsiteOptions);
    request.setAttribute("distributionScanOptions", distributionScanOptions);
    request.setAttribute("failoverOptions", failoverOptions);
}

From source file:org.jahia.portlets.PortletServlet.java

protected boolean attemptRegistration(ServletContext context, ClassLoader paClassLoader) {
    if (PlutoServices.getServices() != null) {
        contextService = PlutoServices.getServices().getPortletContextService();
        File[] fragments = null;//from w w w  .  j  a va2s .c  o m
        String fragmentsPath = getServletContext().getRealPath("/WEB-INF/fragments");
        if (StringUtils.isNotEmpty(fragmentsPath)) {
            try {
                fragments = new File(fragmentsPath).listFiles();
            } catch (Exception e) {
                logger.warn(
                        "Unable to list contentr of the /WEB-INF/fragments directory for internal portlets.",
                        e);
            }
        }

        for (int i = 0; fragments != null && i < fragments.length; i++) {
            try {
                File fragment = fragments[i];
                log("Processing fragment " + fragment);
                ServletConfig config = new ServletConfigWrapper(getServletConfig(), fragment.getName());
                String applicationName = contextService.register(config);
                portletContext = contextService.getPortletContext(applicationName);
                List<? extends PortletDefinition> portlets = contextService.getPortletContext(applicationName)
                        .getPortletApplicationDefinition().getPortlets();
                for (Iterator iterator = portlets.iterator(); iterator.hasNext();) {
                    PortletDefinition portletDD = (PortletDefinition) iterator.next();
                    portletConfigs.put(
                            Jahia.getContextPath() + "/" + fragment.getName() + "."
                                    + portletDD.getPortletName(),
                            contextService.getPortletConfig(applicationName, portletDD.getPortletName()));
                }
            } catch (Exception ex) {
                log("Error while registering portlet", ex);
            }
        }
        started = true;

        for (Map.Entry<String, DriverPortletConfig> entry : portletConfigs.entrySet()) {
            DriverPortletConfig portletConfig = entry.getValue();
            PortletDefinition portletDD = portletConfig.getPortletDefinition();

            //          Create and initialize the portlet wrapped in the servlet.
            try {
                Class<?> clazz = paClassLoader.loadClass((portletDD.getPortletClass()));
                Portlet portlet = (Portlet) clazz.newInstance();

                String rootPath = portletConfig.getInitParameter("rootPath");
                String realPath = portletConfig.getPortletContext().getRealPath(rootPath + "/definitions.cnd");
                if (new File(realPath).exists()) {
                    try {
                        NodeTypeRegistry.getInstance().addDefinitionsFile(new File(realPath),
                                portletConfig.getPortletName());
                        JCRStoreService.getInstance().deployDefinitions(portletConfig.getPortletName(), null,
                                -1);
                    } catch (ParseException | IOException e) {
                        logger.error(e.getMessage(), e);
                    }
                }

                portlet.init(portletConfig);
                portlets.put(entry.getKey(), portlet);

                initializeEventPortlet();
                initializeResourceServingPortlet();
                //return true;
            } catch (Exception ex) {
                context.log(ex.getMessage(), ex);
                // take out of service
                //return true;
            }
        }
        return true;
    }
    return false;
}