Example usage for java.lang ClassNotFoundException getCause

List of usage examples for java.lang ClassNotFoundException getCause

Introduction

In this page you can find the example usage for java.lang ClassNotFoundException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:it.cnr.icar.eric.client.xml.registry.LifeCycleManagerImpl.java

/**
 * Creates instances of information model interfaces (factory method). To
 * create an Organization, use this method as follows:
 * /*w ww.j ava 2  s.  c  om*/
 * <pre>
 * Organization org = (Organization) lifeCycleMgr.createObject(LifeCycleManager.ORGANIZATION);
 * </pre>
 * <p>
 * <DL>
 * <DT><B>Capability Level: 0 </B>
 * </DL>
 * 
 * @param interfaceName
 *            the unqualified name of an interface in the
 *            javax.xml.registry.infomodel package
 * 
 * @return an Object that can then be cast to an instance of the interface
 * 
 * @throws JAXRException
 *             if the JAXR provider encounters an internal error
 * 
 * @throws InvalidRequestException
 *             if the interface is not an interface in the
 *             javax.xml.registry.infomodel package
 * 
 * @throws UnsupportedCapabilityException
 *             if the client attempts to create an instance of an infomodel
 *             interface that is not supported by the capability level of
 *             the JAXR provider
 */
public Object createObject(String className)
        throws JAXRException, InvalidRequestException, UnsupportedCapabilityException {
    Object obj = null;

    try {
        // Try to find extended constructor by nickname
        Constructor<?> cons = imFactory.getConstructor1Arg(className);
        if (cons != null) {
            // use extended constructor
            Object[] args = { this };
            obj = cons.newInstance(args);

            // set extended type
            String typeId = imFactory.getTypeName(className);
            BusinessQueryManagerImpl bqm = (BusinessQueryManagerImpl) regService.getBusinessQueryManager();
            Concept typeConcept = (Concept) bqm.getRegistryObject(typeId, LifeCycleManager.CONCEPT);
            if (obj instanceof Association) {
                ((Association) obj).setAssociationType(typeConcept);
            } else if (obj instanceof ExtrinsicObject) {
                ((ExtrinsicObjectImpl) obj).setObjectType(typeConcept);
            }
        } else {
            // proceed the default way: infomodel class
            className = "it.cnr.icar.eric.client.xml.registry.infomodel."
                    + BindingUtility.mapEbXMLNameToJAXRName(className) + "Impl";

            Class<?> cls = this.getClass().getClassLoader().loadClass(className);
            Class<?> lcmCls = this.getClass().getClassLoader()
                    .loadClass("it.cnr.icar.eric.client.xml.registry.LifeCycleManagerImpl");
            @SuppressWarnings("rawtypes")
            Class[] parmTypes = { lcmCls };
            cons = cls.getDeclaredConstructor(parmTypes);

            Object[] args = { this };
            obj = cons.newInstance(args);
        }

    } catch (ClassNotFoundException e) {
        throw new InvalidRequestException(JAXRResourceBundle.getInstance()
                .getString("message.error.invalid.classname", new Object[] { className }));
    } catch (NoSuchMethodException e) {
        throw new JAXRException(e);
    } catch (InvocationTargetException e) {
        throw new JAXRException(e.getCause());
    } catch (IllegalAccessException e) {
        throw new JAXRException(e);
    } catch (InstantiationException e) {
        throw new JAXRException(e);
    } catch (ExceptionInInitializerError e) {
        throw new JAXRException(e);
    } catch (SecurityException e) {
        throw new JAXRException(e);
    }

    return obj;
}

From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java

/**
 * This is public so that it can be unit tested easily without HTTP.
 *///  w  ww . j  a v a2  s  .c  o m
public String processCall(String payload) throws SerializationException {

    // Let subclasses see the serialized request.
    //
    onBeforeRequestDeserialized(payload);

    // Create a stream to deserialize the request.
    //
    ServerSerializationStreamReader streamReader = new ServerSerializationStreamReader(serializableTypeOracle);
    streamReader.prepareToRead(payload);

    // Read the service interface
    //
    String serviceIntfName = streamReader.readString();

    // TODO(mmendez): need to check the signature
    // Verify that this very servlet implements the specified interface
    // name.
    //
    if (!isImplementedRemoteServiceInterface(serviceIntfName)) {
        // Bad payload, possible hack attempt.
        //
        throw new SecurityException("Blocked attempt to access interface '" + serviceIntfName
                + "', which is either not implemented by this servlet or which doesn't extend RemoteService; this is either misconfiguration or a hack attempt");
    }

    // Actually get the service interface, so that we can query its methods.
    //
    Class serviceIntf;
    try {
        serviceIntf = getClassFromName(serviceIntfName);
    } catch (ClassNotFoundException e) {
        throw new SerializationException("Unknown service interface class '" + serviceIntfName + "'", e);
    }

    // Read the method name.
    //
    String methodName = streamReader.readString();

    // Read the number and names of the parameter classes from the stream.
    // We have to do this so that we can find the correct overload of the
    // method.
    //
    int paramCount = streamReader.readInt();
    Class[] paramTypes = new Class[paramCount];
    for (int i = 0; i < paramTypes.length; i++) {
        String paramClassName = streamReader.readString();
        try {
            paramTypes[i] = getClassFromName(paramClassName);
        } catch (ClassNotFoundException e) {
            throw new SerializationException("Unknown parameter " + i + " type '" + paramClassName + "'", e);
        }
    }

    // For security, make sure the method is found in the service interface
    // and not just one that happens to be defined on this class.
    //
    Method serviceIntfMethod = findInterfaceMethod(serviceIntf, methodName, paramTypes, true);

    // If it wasn't found, don't continue.
    //
    if (serviceIntfMethod == null) {
        // Bad payload, possible hack attempt.
        //
        throw new SecurityException("Method '" + methodName + "' (or a particular overload) on interface '"
                + serviceIntfName + "' was not found, this is either misconfiguration or a hack attempt");
    }

    // Deserialize the parameters.
    //
    Object[] args = new Object[paramCount];
    for (int i = 0; i < args.length; i++) {
        args[i] = streamReader.deserializeValue(paramTypes[i]);
    }

    // Make the call via reflection.
    //
    String responsePayload = GENERIC_FAILURE_MSG;
    ServerSerializationStreamWriter streamWriter = new ServerSerializationStreamWriter(serializableTypeOracle);
    Throwable caught = null;
    try {
        Class returnType = serviceIntfMethod.getReturnType();
        /**
         * The method is not invoked from <code>this</code> but from <code>this.proxy</code>;
         * <code>this</code> is the exporter, <code>this.proxy</code> is the actual service
         * implementation
         * @author rlogman@gmail.com
         */
        Object returnVal = serviceIntfMethod.invoke(this.proxy, args);
        responsePayload = createResponse(streamWriter, returnType, returnVal, false);
    } catch (IllegalArgumentException e) {
        caught = e;
    } catch (IllegalAccessException e) {
        caught = e;
    } catch (InvocationTargetException e) {
        // Try to serialize the caught exception if the client is expecting
        // it,
        // otherwise log the exception server-side.
        caught = e;
        Throwable cause = e.getCause();
        if (cause != null) {
            // Update the caught exception to the underlying cause
            caught = cause;
            // Serialize the exception back to the client if it's a declared
            // exception
            if (isExpectedException(serviceIntfMethod, cause)) {
                Class thrownClass = cause.getClass();
                responsePayload = createResponse(streamWriter, thrownClass, cause, true);
                // Don't log the exception on the server
                caught = null;
            }
        }
    }

    if (caught != null) {
        responsePayload = GENERIC_FAILURE_MSG;
        // servletContext may be null (for example, when unit testing)
        /**
         * Our logger will not be servlet context's log (we don't have
         * direct access to it at this point)
         * @author rlogman@gmail.com
         */
        if (logger != null) {
            // Log the exception server side
            logger.error("Exception while dispatching incoming RPC call", caught);
        }
    }

    // Let subclasses see the serialized response.
    //
    onAfterResponseSerialized(responsePayload);

    return responsePayload;
}

From source file:it.cnr.icar.eric.client.ui.common.ReferenceAssociation.java

public void setReferenceAttributeOnSourceObject() throws JAXRException {
    String referenceAttribute = this.getReferenceAttribute();

    //Now use Refelection API to add target to src
    try {// w ww.  j av a 2  s .c  o  m
        Class<? extends RegistryObject> srcClass = src.getClass();
        Class<?> targetClass = target.getClass();
        Class<?> registryObjectClass = null;

        String targetInterfaceName = targetClass.getName();
        targetInterfaceName = targetInterfaceName.substring(targetInterfaceName.lastIndexOf(".") + 1);

        if (targetInterfaceName.endsWith("Impl")) {
            //Remove Impl suffix for JAXR provider Impl classes
            targetInterfaceName = targetInterfaceName.substring(0, targetInterfaceName.length() - 4);
        }

        targetInterfaceName = "javax.xml.registry.infomodel." + targetInterfaceName;

        ClassLoader classLoader = srcClass.getClassLoader();

        try {
            targetClass = classLoader.loadClass(targetInterfaceName);
            registryObjectClass = classLoader.loadClass("javax.xml.registry.infomodel.RegistryObject");
        } catch (ClassNotFoundException e) {
            throw new JAXRException("No JAXR interface found by name " + targetInterfaceName);
        }

        @SuppressWarnings("static-access")
        String suffix = UIUtility.getInstance().initCapString(referenceAttribute);
        Method method = null;
        Class<?>[] paramTypes = new Class[1];

        //See if there is a simple attribute of this name using type of targetObject
        try {
            paramTypes[0] = targetClass;
            method = srcClass.getMethod("set" + suffix, paramTypes);

            Object[] params = new Object[1];
            params[0] = target;
            method.invoke(src, params);
            isCollectionRef = false;

            return;
        } catch (NoSuchMethodException | IllegalAccessException e) {
            method = null;
        }

        //See if there is a simple attribute of this name using base type RegistryObject
        try {
            paramTypes[0] = registryObjectClass;
            method = srcClass.getMethod("set" + suffix, paramTypes);

            Object[] params = new Object[1];
            params[0] = target;
            method.invoke(src, params);
            isCollectionRef = false;

            return;
        } catch (NoSuchMethodException | IllegalAccessException e) {
            method = null;
        }

        //See if there is a addCXXX method for suffix of XXX ending in "s" for plural
        if (suffix.endsWith("s")) {
            suffix = suffix.substring(0, suffix.length() - 1);
        }

        try {
            paramTypes[0] = targetClass;
            method = srcClass.getMethod("add" + suffix, paramTypes);

            Object[] params = new Object[1];
            params[0] = target;
            method.invoke(src, params);
            isCollectionRef = true;

            return;
        } catch (NoSuchMethodException | IllegalAccessException e) {
            method = null;
        }

        //See if there is a addCXXX method for suffix of XXX ending in "es" for plural
        if (suffix.endsWith("e")) {
            suffix = suffix.substring(0, suffix.length() - 1);
        }

        try {
            paramTypes[0] = targetClass;
            method = srcClass.getMethod("add" + suffix, paramTypes);

            Object[] params = new Object[1];
            params[0] = target;
            method.invoke(src, params);
            isCollectionRef = true;

            return;
        } catch (NoSuchMethodException | IllegalAccessException e) {
            method = null;
        }

        //Special case while adding child organization to an organization
        if (src instanceof Organization && target instanceof Organization) {
            try {
                paramTypes[0] = targetClass;
                method = srcClass.getMethod("addChildOrganization", paramTypes);

                Object[] params = new Object[1];
                params[0] = target;
                method.invoke(src, params);
                isCollectionRef = true;

                return;
            } catch (NoSuchMethodException | IllegalAccessException e) {
                method = null;
            }
        }
        throw new JAXRException("No method found for reference attribute " + referenceAttribute
                + " for src object of type " + srcClass.getName());
    } catch (IllegalArgumentException e) {
        throw new JAXRException(e);
    } catch (InvocationTargetException e) {
        throw new JAXRException(e.getCause());
    } catch (ExceptionInInitializerError e) {
        throw new JAXRException(e);
    }
}

From source file:com.zenesis.qx.remote.RequestHandler.java

/**
 * Handles a server method call from the client; expects a serverId, methodName, and an optional
 * array of parameters/* w  w  w .  ja  v  a2  s .  c  o m*/
 * @param jp
 * @throws ServletException
 * @throws IOException
 */
protected void cmdCallServerMethod(JsonParser jp) throws ServletException, IOException {
    // Get the basics
    Object obj = getFieldValue(jp, "serverId", Object.class);
    Class serverClass = null;
    Proxied serverObject = null;
    if (obj instanceof Integer) {
        int serverId = (Integer) obj;
        serverObject = getProxied(serverId);
        serverClass = serverObject.getClass();
    } else if (obj != null) {
        try {
            serverClass = Class.forName(obj.toString());
        } catch (ClassNotFoundException e) {
            log.error("Cannot find server class " + obj + ": " + e.getMessage());
        }
    }
    String methodName = getFieldValue(jp, "methodName", String.class);
    int asyncId = getFieldValue(jp, "asyncId", Integer.class);

    // Onto what should be parameters
    jp.nextToken();

    // Find the method by hand - we have already guaranteed that there will not be conflicting
    //   method names (ie no overridden methods) but Java needs a list of parameter types
    //   so we do it ourselves.
    boolean found = false;

    // Check for property accessors; if serverObject is null then it's static method call and
    //   properties are not supported
    if (serverObject != null && methodName.length() > 3
            && (methodName.startsWith("get") || methodName.startsWith("set"))) {
        String name = methodName.substring(3, 4).toLowerCase();
        if (methodName.length() > 4)
            name += methodName.substring(4);
        for (ProxyType type = ProxyTypeManager.INSTANCE.getProxyType(serverClass); type != null; type = type
                .getSuperType()) {
            ProxyProperty property = type.getProperties().get(name);
            if (property != null) {
                Object result = null;
                if (methodName.startsWith("get")) {
                    readParameters(jp, null);
                    result = property.getValue(serverObject);
                } else {
                    Object[] values = readParameters(jp,
                            new Class[] { property.getPropertyClass().getJavaType() });
                    property.setValue(serverObject, values[0]);
                }
                if (property.isOnDemand())
                    tracker.setClientHasValue(serverObject, property);
                tracker.getQueue().queueCommand(CommandId.CommandType.FUNCTION_RETURN, serverObject, null,
                        new FunctionReturn(asyncId, result));
                found = true;
                break;
            }
        }
    }

    if (!found) {
        for (ProxyType type = ProxyTypeManager.INSTANCE.getProxyType(serverClass); type != null
                && !found; type = type.getSuperType()) {
            ProxyMethod[] methods = type.getMethods();
            for (int i = 0; i < methods.length; i++)
                if (methods[i].getName().equals(methodName)) {
                    Method method = methods[i].getMethod();

                    // Call the method
                    Object[] values = null;
                    try {
                        values = readParameters(jp, method.getParameterTypes());
                        Object result = method.invoke(serverObject, values);
                        tracker.getQueue().queueCommand(CommandId.CommandType.FUNCTION_RETURN, serverObject,
                                null, new FunctionReturn(asyncId, result));
                    } catch (InvocationTargetException e) {
                        Throwable t = e.getCause();
                        log.error("Exception while invoking " + method + "(" + Helpers.toString(values)
                                + ") on " + serverObject + ": " + t.getMessage(), t);
                        throw new ProxyException(serverObject, "Exception while invoking " + method + " on "
                                + serverObject + ": " + t.getMessage(), t);
                    } catch (RuntimeException e) {
                        log.error("Exception while invoking " + method + "(" + Helpers.toString(values)
                                + ") on " + serverObject + ": " + e.getMessage(), e);
                        throw new ProxyException(serverObject, "Exception while invoking " + method + " on "
                                + serverObject + ": " + e.getMessage(), e);
                    } catch (IllegalAccessException e) {
                        throw new ServletException("Exception while running " + method + "("
                                + Helpers.toString(values) + "): " + e.getMessage(), e);
                    }
                    found = true;
                    break;
                }
        }
    }

    if (!found)
        throw new ServletException("Cannot find method called " + methodName + " in "
                + (serverObject != null ? serverObject : serverClass));

    jp.nextToken();
}

From source file:org.infoglue.deliver.applications.actions.ViewPageAction.java

/**
 * This method the renderer for the component editor. 
 *///  ww  w .j a  v  a2  s .  c  om

public String doRenderDecoratedPage() throws Exception {
    if (CmsPropertyHandler.getOperatingMode().equals("3"))
        return doExecute();

    while (CmsPropertyHandler.getActuallyBlockOnBlockRequests()
            && RequestAnalyser.getRequestAnalyser().getBlockRequests()) {
        //logger.info("Queing up requests as cache eviction are taking place..");
        Thread.sleep(10);
    }

    if (logger.isInfoEnabled()) {
        logger.info("************************************************");
        logger.info("* ViewPageAction was called....                *");
        logger.info("************************************************");
    }

    HttpServletRequest request = getRequest();

    if (!CmsPropertyHandler.getOperatingMode().equals("3"))
        tk = new ThreadMonitor(new Long(CmsPropertyHandler.getDeliverRequestTimeout()).longValue(), request,
                "Page view took to long!", true);
    else {
        if (!CmsPropertyHandler.getKillLiveRequestWhichTimedout())
            tk = new ThreadMonitor(new Long(CmsPropertyHandler.getLiveDeliverRequestTimeout()).longValue(),
                    request, "Page view seems to take to long!", false);
        else
            tk = new ThreadMonitor(new Long(CmsPropertyHandler.getLiveDeliverRequestTimeout()).longValue(),
                    request, "Page view took to long!", true);
    }

    RequestAnalyser.getRequestAnalyser().incNumberOfCurrentRequests(tk);

    long start = System.currentTimeMillis();
    long elapsedTime = 0;

    DatabaseWrapper dbWrapper = new DatabaseWrapper(CastorDatabaseService.getDatabase());
    //Database db = CastorDatabaseService.getDatabase();

    beginTransaction(dbWrapper.getDatabase());

    try {
        validateAndModifyInputParameters(dbWrapper.getDatabase());

        this.nodeDeliveryController = NodeDeliveryController.getNodeDeliveryController(this.siteNodeId,
                this.languageId, this.contentId);
        this.integrationDeliveryController = IntegrationDeliveryController
                .getIntegrationDeliveryController(this.siteNodeId, this.languageId, this.contentId);

        boolean isUserRedirected = false;
        Integer protectedSiteNodeVersionId = this.nodeDeliveryController
                .getProtectedSiteNodeVersionId(dbWrapper.getDatabase(), siteNodeId);
        logger.info("protectedSiteNodeVersionId:" + protectedSiteNodeVersionId);

        boolean protectDeliver = true;

        if (logger.isInfoEnabled())
            logger.info("RemoteAddress:" + getRequest().getRemoteAddr());

        //if(getRequest().getRemoteAddr().equals("127.0.0.1") || getRequest().getRemoteAddr().equals("192.168.0.1"))
        //   protectDeliver = false;

        if (protectedSiteNodeVersionId != null || protectDeliver)
            isUserRedirected = handleExtranetLogic(dbWrapper.getDatabase(), this.repositoryId,
                    protectedSiteNodeVersionId, protectDeliver, true);
        /*
        else
        {
           String forceIdentityCheck = RepositoryDeliveryController.getRepositoryDeliveryController().getExtraPropertyValue(this.repositoryId, "forceIdentityCheck");
           if(CmsPropertyHandler.getForceIdentityCheck().equalsIgnoreCase("true") || (forceIdentityCheck != null && forceIdentityCheck.equalsIgnoreCase("true")))
              isUserRedirected = handleExtranetLogic(dbWrapper.getDatabase(), true);
        }
        */

        String pageKey = this.nodeDeliveryController.getPageCacheKey(dbWrapper.getDatabase(),
                this.getHttpSession(), this.getRequest(), this.siteNodeId, this.languageId, this.contentId,
                browserBean.getUseragent(), this.getRequest().getQueryString(),
                "_" + this.showSimple + "_pagecomponentDecorated");

        templateController = getTemplateController(dbWrapper, getSiteNodeId(), getLanguageId(), getContentId(),
                getRequest(), (InfoGluePrincipal) this.principal, true);

        InfoGluePrincipal principal = templateController.getPrincipal();
        String cmsUserName = (String) templateController.getHttpServletRequest().getSession()
                .getAttribute("cmsUserName");
        if (cmsUserName != null && !CmsPropertyHandler.getAnonymousUser().equalsIgnoreCase(cmsUserName))
            principal = templateController.getPrincipal(cmsUserName);

        //As this is the decorated view we need to cache personalized results due to access rights etc.
        if (principal != null && pageKey.indexOf(principal.getName()) == -1)
            pageKey = pageKey + "_" + principal.getName();

        if (logger.isInfoEnabled())
            logger.info("A pageKey:" + pageKey);

        if (logger.isInfoEnabled())
            logger.info("handled extranet users");

        // ----
        // -- portlet
        // ----

        // -- check if the portal is active
        String portalEnabled = CmsPropertyHandler.getEnablePortal();
        boolean portalActive = ((portalEnabled != null) && portalEnabled.equals("true"));

        if (portalActive && !isRecacheCall) {
            logger.info("---> Checking for portlet action");
            PortalService service = new PortalService();
            //TODO: catch PortalException?
            boolean actionExecuted = service.service(getRequest(), getResponse());

            // -- if an action was executed return NONE as a redirect is issued
            if (actionExecuted) {
                logger.info("---> PortletAction was executed, returning NONE as a redirect has been issued");
                isUserRedirected = true;
                return NONE;
            }
        }

        if (logger.isInfoEnabled())
            logger.info("handled portal action");

        if (!isUserRedirected) {
            logger.info("this.templateController.getPrincipal():" + templateController.getPrincipal());

            DeliveryContext deliveryContext = DeliveryContext.getDeliveryContext(true);
            deliveryContext.setRepositoryName(this.repositoryName);
            deliveryContext.setSiteNodeId(this.siteNodeId);
            deliveryContext.setLanguageId(this.languageId);
            deliveryContext.setContentId(this.contentId);
            deliveryContext.setShowSimple(this.showSimple);
            deliveryContext.setPageKey(pageKey);
            //deliveryContext.setSession(this.getSession());
            //deliveryContext.setInfoGlueAbstractAction(this);
            deliveryContext.setHttpServletRequest(this.getRequest());
            deliveryContext.setHttpServletResponse(this.getResponse());
            deliveryContext.setUseFullUrl(Boolean.parseBoolean(CmsPropertyHandler.getUseDNSNameInURI()));

            //deliveryContext.setDisablePageCache(true);

            SiteNode siteNode = nodeDeliveryController.getSiteNode(dbWrapper.getDatabase(), this.siteNodeId);
            if (siteNode == null)
                throw new SystemException("There was no page with this id.");

            if (siteNode.getSiteNodeTypeDefinition() == null)
                throw new SystemException("There was no SiteNodeTypeDefinition defined for the site node "
                        + siteNode.getName() + "[" + siteNode.getId() + "].");

            String invokerClassName = siteNode.getSiteNodeTypeDefinition().getInvokerClassName();

            if (invokerClassName == null || invokerClassName.equals("")) {
                throw new SystemException("There was no page invoker class assigned to this page type.");
            } else {
                try {
                    PageInvoker pageInvoker = (PageInvoker) Class.forName(invokerClassName).newInstance();
                    pageInvoker = pageInvoker.getDecoratedPageInvoker(templateController);
                    pageInvoker.setParameters(dbWrapper, this.getRequest(), this.getResponse(),
                            templateController, deliveryContext);
                    pageInvoker.deliverPage();
                } catch (ClassNotFoundException e) {
                    throw new SystemException(
                            "An error was thrown when trying to use the page invoker class assigned to this page type:"
                                    + e.getMessage(),
                            e);
                } finally {
                    deliveryContext.clear();
                    deliveryContext = null;
                }
            }
        }

        //StatisticsService.getStatisticsService().registerRequest(getRequest(), getResponse(), pagePath, elapsedTime);
    } catch (PageNotFoundException e) {
        String extraInformation = "Original URL: " + getOriginalFullURL() + "\n";
        extraInformation += "Referer: " + getRequest().getHeader("Referer") + "\n";
        extraInformation += "UserAgent: " + getRequest().getHeader("User-Agent") + "\n";
        extraInformation += "User IP: " + getRequest().getRemoteAddr();

        logger.warn("A user requested a non existing page:" + e.getMessage() + "\n" + extraInformation);
        rollbackTransaction(dbWrapper.getDatabase());

        getResponse().setContentType("text/html; charset=UTF-8");
        getRequest().setAttribute("responseCode", "404");
        getRequest().setAttribute("error", e);
        getRequest().setAttribute("errorUrl", getErrorUrl());
        getRequest().getRequestDispatcher("/ErrorPage.action").forward(getRequest(), getResponse());
    } catch (NoBaseTemplateFoundException e) {
        String extraInformation = "Original URL: " + getOriginalFullURL() + "\n";
        extraInformation += "Referer: " + getRequest().getHeader("Referer") + "\n";
        extraInformation += "UserAgent: " + getRequest().getHeader("User-Agent") + "\n";
        extraInformation += "User IP: " + getRequest().getRemoteAddr();

        logger.error(
                "A user requested a page which had no base template (probably of the old HTMLPageInvoker type - should be changed):"
                        + e.getMessage() + "\n" + extraInformation);
        rollbackTransaction(dbWrapper.getDatabase());

        getResponse().setContentType("text/html; charset=UTF-8");
        getRequest().setAttribute("responseCode", "500");
        getRequest().setAttribute("error", e);
        getRequest().setAttribute("errorUrl", getErrorUrl());
        getRequest().getRequestDispatcher("/ErrorPage.action").forward(getRequest(), getResponse());
    } catch (Exception e) {
        String extraInformation = "Original URL: " + getOriginalFullURL() + "\n";
        extraInformation += "Referer: " + getRequest().getHeader("Referer") + "\n";
        extraInformation += "UserAgent: " + getRequest().getHeader("User-Agent") + "\n";
        extraInformation += "User IP: " + getRequest().getRemoteAddr();

        if (e instanceof java.net.SocketException
                || e.getCause() != null && e.getCause() instanceof java.net.SocketException)
            logger.warn("An error occurred so we should not complete the transaction:" + e.getMessage() + "\n"
                    + extraInformation);
        else
            logger.error("An error occurred so we should not complete the transaction:" + e.getMessage() + "\n"
                    + extraInformation, e);

        rollbackTransaction(dbWrapper.getDatabase());

        throw new SystemException(e.getMessage());
    } finally {
        try {
            closeTransaction(dbWrapper.getDatabase());
        } catch (Exception e) {
            logger.error("Problem closing connection:" + e.getMessage(), e);
        }

        try {
            if (templateController != null) {
                templateController.clear();
                templateController = null;
            }
        } catch (Exception e) {
            logger.error("Problem clearing:" + e.getMessage(), e);

        }

        elapsedTime = Math.abs(System.currentTimeMillis() - start);

        RequestAnalyser.getRequestAnalyser().decNumberOfCurrentRequests(elapsedTime);

        if (!memoryWarningSent) {
            float memoryLeft = ((float) Runtime.getRuntime().maxMemory()
                    - (float) Runtime.getRuntime().totalMemory()) / 1024f / 1024f;
            float percentLeft = (memoryLeft / ((float) Runtime.getRuntime().maxMemory() / 1024f / 1024f))
                    * 100f;
            float percentLeft2 = ((float) Runtime.getRuntime().freeMemory()
                    / (float) Runtime.getRuntime().totalMemory()) * 100f;

            //System.out.println("memoryLeft:" + memoryLeft);
            //System.out.println("maxMemory:" + (Runtime.getRuntime().maxMemory() / 1024f / 1024f));
            //System.out.println("totalMemory:" + (Runtime.getRuntime().totalMemory() / 1024f / 1024f));
            //System.out.println("freeMemory:" + (Runtime.getRuntime().freeMemory() / 1024f / 1024f));
            //System.out.println("percentLeft:" + percentLeft);
            //System.out.println("percentLeft2:" + percentLeft2);
            if (percentLeft < 15 && percentLeft2 < 15) {
                memoryWarningSent = true;
                String subject = "Memory is getting low on " + CmsPropertyHandler.getServerName();
                String mailBody = "The java maximum heap size is almost used up - only " + (int) memoryLeft
                        + "MB (" + (int) percentLeft
                        + "%) left. Increase the max heap size if possible or trim the cache sizes if they are very large.";
                String warningEmailReceiver = CmsPropertyHandler.getWarningEmailReceiver();
                if (warningEmailReceiver != null && !warningEmailReceiver.equals("")
                        && warningEmailReceiver.indexOf("@warningEmailReceiver@") == -1) {
                    try {
                        logger.warn("Sending warning mail:" + (int) percentLeft + ":" + (int) memoryLeft + ":"
                                + Runtime.getRuntime().maxMemory() / 1024f / 1024f);
                        MailServiceFactory.getService().sendEmail("text/html", warningEmailReceiver,
                                warningEmailReceiver, null, null, null, null, subject, mailBody, "utf-8");
                    } catch (Exception e) {
                        logger.error("Could not send mail:" + e.getMessage(), e);
                    }
                }
            }
        }

        String originalFullUrl = getOriginalFullURL();
        if (elapsedTime > 20000) {
            logger.warn("The page delivery took " + elapsedTime + "ms for request " + originalFullUrl);
            logger.warn("The memory consumption was "
                    + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + "("
                    + Runtime.getRuntime().totalMemory() + "/" + Runtime.getRuntime().maxMemory() + ") bytes");
        } else {
            logger.info("The page delivery took " + elapsedTime + "ms");
            logger.info("The memory consumption was "
                    + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + "("
                    + Runtime.getRuntime().totalMemory() + "/" + Runtime.getRuntime().maxMemory() + ") bytes");
        }

        if (tk != null && !tk.getIsDoneRunning())
            tk.done();
        else
            logger.warn("Done had allready been run... skipping");
    }

    return NONE;
}