Example usage for org.apache.commons.logging Log isDebugEnabled

List of usage examples for org.apache.commons.logging Log isDebugEnabled

Introduction

In this page you can find the example usage for org.apache.commons.logging Log isDebugEnabled.

Prototype

boolean isDebugEnabled();

Source Link

Document

Is debug logging currently enabled?

Usage

From source file:com.microsoft.tfs.client.common.framework.command.TeamExplorerLogCommandFinishedCallback.java

@Override
public void onCommandFinished(final ICommand command, IStatus status) {
    /*/*w w w.  j av  a  2 s . c o  m*/
     * Team Explorer ("private") logging. Map IStatus severity to commons
     * logging severity iff the severity is greater than the configured
     * tfsLogMinimumSeverity.
     */
    if (status.getSeverity() >= minimumSeverity) {
        /*
         * UncaughtCommandExceptionStatus is a TeamExplorerStatus, which
         * does a silly trick: it makes the exception it was given
         * accessible only through a non-standard method. This helps when
         * displaying the status to the user in a dialog, but prevents the
         * platform logger from logging stack traces, so fix it up here.
         *
         * The right long term fix is to ditch TeamExplorerStatus entirely.
         */
        if (status instanceof TeamExplorerStatus) {
            status = ((TeamExplorerStatus) status).toNormalStatus();
        }

        /*
         * Don't have a static Log for this class, because then the errors
         * show up as coming from this class, which is not correct. Instead,
         * get the logger for the class the errors originated from. Note
         * that this is not a particularly expensive operation - it looks up
         * the classname in a hashmap. This should be more than suitable for
         * a command finished error handler.
         */
        final Log log = LogFactory.getLog(CommandHelpers.unwrapCommand(command).getClass());

        if (status.getSeverity() == IStatus.ERROR && log.isErrorEnabled()) {
            log.error(CommandFinishedCallbackHelpers.getMessageForStatus(status), status.getException());
        } else if (status.getSeverity() == IStatus.WARNING && log.isWarnEnabled()) {
            log.error(CommandFinishedCallbackHelpers.getMessageForStatus(status), status.getException());
        } else if (status.getSeverity() == IStatus.INFO && log.isInfoEnabled()) {
            log.info(CommandFinishedCallbackHelpers.getMessageForStatus(status), status.getException());
        } else if (status.getSeverity() == IStatus.CANCEL && log.isInfoEnabled()) {
            log.info(CommandFinishedCallbackHelpers.getMessageForStatus(status), status.getException());
        } else if (status.getSeverity() != IStatus.OK && log.isDebugEnabled()) {
            log.debug(CommandFinishedCallbackHelpers.getMessageForStatus(status), status.getException());
        } else if (log.isTraceEnabled()) {
            log.trace(CommandFinishedCallbackHelpers.getMessageForStatus(status), status.getException());
        }
    }
}

From source file:hotbeans.support.AbstractHotBeanModuleRepository.java

/**
 * Destroys this AbstractHotBeanModuleRepository. Subclasses may override this method, but should call the super
 * class implementation.//from  w w w.  java  2  s .c  om
 */
public void destroy() throws Exception {
    Log logger = this.getLog();

    synchronized (this.lock) {
        String[] moduleNames = this.getHotBeanModuleNames();
        if (logger.isInfoEnabled())
            logger.info("Destroying " + this.getName() + " (" + ((moduleNames != null) ? moduleNames.length : 0)
                    + " modules).");
        HotBeanModuleType moduleType;
        HotBeanModule[] modules;
        for (int i = 0; i < moduleNames.length; i++) {
            if (logger.isDebugEnabled())
                logger.debug("Unloading revisions of module " + moduleNames[i] + ".");

            moduleType = this.getHotBeanModuleType(moduleNames[i]);
            if (moduleType != null) {
                modules = moduleType.getModules();
                for (int j = 0; j < modules.length; j++) {
                    if (logger.isDebugEnabled())
                        logger.debug("Checking" + modules[i] + ".");

                    if (modules[j].isActive() || modules[j].isInactive()) {
                        if (logger.isDebugEnabled())
                            logger.debug("Unloading " + modules[j] + ".");
                        modules[j].unload();
                    }
                    this.unregisterHotBeanModule(modules[j]);
                }
            }
        }
    }
}

From source file:de.ingrid.iplug.csw.dsc.cache.impl.AbstractUpdateStrategy.java

/**
 * Fetch all records that satisfy the given filter using the GetRecords and
 * return the ids and put them into the cache
 * @note This method guarantees to query the server without a constraint, if the
 * provided filter set is empty /*  w w  w  . jav  a  2s  .  c o  m*/
 * 
 * @param client The CSWClient to use
 * @param elementSetName The ElementSetName of the records to fetch
 * @param filterSet The filter set used to select the records
 * @param doCache Determines wether to cache the record or not
 * @return A list of ids of the fetched records
 * @throws Exception
 */
protected List<String> fetchRecords(CSWClient client, ElementSetName elementSetName, Set<Document> filterSet,
        boolean doCache) throws Exception {

    CSWFactory factory = client.getFactory();
    Log log = this.getLog();

    // if the filter set is empty, we add a null a least
    // this causes execution of the iteration below, but
    // but will not add a constraint definition to the request
    if (filterSet == null)
        filterSet = new HashSet<Document>();
    if (filterSet.size() == 0)
        filterSet.add(null);

    // variables for complete fetch process
    // int numTotal = 0;
    List<String> fetchedRecordIds = new CopyOnWriteArrayList<String>();

    // iterate over all filters
    int filterIndex = 1;
    for (Document filter : filterSet) {
        if (log.isDebugEnabled())
            log.debug("Processing filter " + filterIndex + ": "
                    + StringUtils.nodeToString(filter).replace("\n", "") + ".");

        // variables for current fetch process (current filter)
        int numRecordsTotal = 0;
        int numRecordsFetched = 0;
        List<String> currentFetchedRecordIds = new ArrayList<String>();

        // create the query
        CSWQuery query = factory.createQuery();
        query.setConstraint(filter);
        query.setResultType(ResultType.RESULTS);
        query.setElementSetName(elementSetName);
        query.setMaxRecords(this.recordsPerCall);
        query.setStartPosition(1);

        // do requests

        // do first request

        CSWSearchResult result = client.getRecords(query);
        numRecordsFetched += result.getNumberOfRecords();
        numRecordsTotal = result.getNumberOfRecordsTotal();
        if (log.isInfoEnabled())
            log.info(numRecordsTotal + " record(s) from filter " + filterIndex + ":");

        if (numRecordsTotal > 0) {

            if (log.isInfoEnabled()) {
                log.info("\nPARAMETERS OF FETCHING PROCESS:" + "\nrecords per chunk (request): "
                        + recordsPerCall + "\ngeneral pause between requesting next chunk (msec): "
                        + requestPause + "\nnum retries per chunk: " + cswConfig.numRetriesPerRequest
                        + "\npause between retries (msec): " + cswConfig.timeBetweenRetries
                        + "\nmax number of lost chunks: " + cswConfig.maxNumSkippedRequests);
            }

            // process
            currentFetchedRecordIds.addAll(processResult(result, doCache));

            int numSkippedRequests = 0;
            String logLostRecordChunks = "";
            int numLostRecords = 0;
            while (numRecordsFetched < numRecordsTotal) {
                if (cswConfig.maxNumSkippedRequests > -1) {
                    // fetching should end when a maximum number of failures (in a row) is reached.
                    if (numSkippedRequests > cswConfig.maxNumSkippedRequests) {
                        log.error("Problems fetching records. Total number of skipped requests reached ("
                                + cswConfig.maxNumSkippedRequests
                                + " requests without results). We end fetching process for this filter.");
                        statusProvider.addState(
                                "ERROR_FETCH", "Error during fetch, since more than "
                                        + cswConfig.maxNumSkippedRequests + " records have been skipped.",
                                Classification.ERROR);
                        break;
                    }
                }

                // generic pause between requests, set via spring
                Thread.sleep(this.requestPause);

                String logCurrRecordChunk = "";
                try {
                    // prepare next request
                    // Just for safety: get number of last fetched records from last result, if we have a result and records.
                    int numLastFetch = query.getMaxRecords();
                    if (result != null && (result.getNumberOfRecords() > 0)) {
                        numLastFetch = result.getNumberOfRecords();
                    }
                    numRecordsFetched += numLastFetch;
                    statusProvider.addState("FETCH",
                            "Fetching record " + (numRecordsFetched - numLastFetch + 1) + "-"
                                    + numRecordsFetched + " / " + numRecordsTotal + " from "
                                    + client.getFactory().getServiceUrl());

                    query.setStartPosition(query.getStartPosition() + numLastFetch);

                    // for logging below
                    logCurrRecordChunk = "" + query.getStartPosition() + " - "
                            + (query.getStartPosition() + query.getMaxRecords());

                    // do next request, if problems retry with increasing pause in between 
                    int numRetries = 0;
                    while (true) {
                        try {
                            result = null;
                            result = client.getRecords(query);
                            break;

                        } catch (Exception e) {
                            if (numRetries == cswConfig.numRetriesPerRequest) {
                                log.error("Retried " + numRetries + " times ! We skip records "
                                        + logCurrRecordChunk, e);
                                break;
                            }

                            numRetries++;
                            int timeBetweenRetry = numRetries * cswConfig.timeBetweenRetries;
                            log.error("Error fetching records " + logCurrRecordChunk + ". We retry "
                                    + numRetries + ". time after " + timeBetweenRetry + " msec !", e);
                            Thread.sleep(timeBetweenRetry);
                        }
                    }

                    // process
                    if (result == null || result.getNumberOfRecords() == 0) {
                        // no result from this query, we count the failures to check whether fetching process should be ended !
                        numSkippedRequests++;
                        numLostRecords += query.getMaxRecords();
                        logLostRecordChunks += logCurrRecordChunk + "\n";

                    } else {
                        currentFetchedRecordIds.addAll(processResult(result, doCache));
                    }
                } catch (Exception e) {
                    statusProvider.addState("ERROR_FETCH_PROCESS",
                            "Error during processing record: " + logCurrRecordChunk, Classification.ERROR);
                    log.error("Error processing records " + logCurrRecordChunk);
                    log.error(ExceptionUtils.getStackTrace(e));
                }
            }

            if (numLostRecords > 0) {
                statusProvider.addState("ERROR_FETCH_PROCESS",
                        "Error during fetching of record: " + logLostRecordChunks, Classification.ERROR);
                log.error("\nWe had failed GetRecords requests !!!" + "\nThe following " + numLostRecords
                        + " records were NOT fetched and are \"lost\":" + "\n" + logLostRecordChunks);
            }
        }

        // collect record ids
        fetchedRecordIds.addAll(currentFetchedRecordIds);
        // numTotal += currentFetchedRecordIds.size();
        filterIndex++;
    }
    return fetchedRecordIds;
}

From source file:jp.terasoluna.fw.batch.util.BatchUtil.java

/**
 * ???/*  w  ww . j a va 2 s  .  co  m*/
 * @param tranMap PlatformTransactionManager
 * @param statMap TransactionStatus
 * @param log Log
 * @return ???PlatformTransactionManager?????????true??
 */
public static boolean endTransactions(Map<?, ?> tranMap, Map<String, TransactionStatus> statMap, Log log) {
    boolean isNormal = true;

    Set<Entry<String, TransactionStatus>> statSet = statMap.entrySet();

    if (statSet == null || statSet.isEmpty()) {
        return isNormal;
    }

    Stack<Entry<String, TransactionStatus>> stack = new Stack<Entry<String, TransactionStatus>>();
    for (Entry<String, TransactionStatus> stat : statSet) {
        stack.push(stat);
    }

    while (!stack.isEmpty()) {
        // ???
        Entry<String, TransactionStatus> statEntry = stack.pop();
        String key = statEntry.getKey();
        TransactionStatus trnStat = statEntry.getValue();

        if (trnStat == null) {
            continue;
        }

        // ???
        Object ptmObj = tranMap.get(key);
        if (ptmObj == null || !(ptmObj instanceof PlatformTransactionManager)) {
            continue;
        }
        PlatformTransactionManager ptm = (PlatformTransactionManager) ptmObj;

        // ??????
        if (trnStat.isCompleted()) {
            continue;
        }

        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025041, trnStat);
        }

        // ?
        try {
            ptm.rollback(trnStat);
        } catch (TransactionException e) {
            if (log != null && log.isErrorEnabled()) {
                logError(log, LogId.EAL025045, e, key);
            }
            isNormal = false;
            // ????????
        }

        if (log != null && log.isDebugEnabled()) {
            logDebug(log, LogId.DAL025041, trnStat);
        }
    }
    return isNormal;
}

From source file:de.itsvs.cwtrpc.controller.AutowiredRemoteServiceGroupConfig.java

public void afterPropertiesSet() {
    final Log log;
    final ListableBeanFactory beanFactory;
    final String[] beanNames;
    final List<RemoteServiceConfig> serviceConfigs;

    log = LogFactory.getLog(AutowiredRemoteServiceGroupConfig.class);
    log.debug("Searching for remote services");

    beanFactory = getApplicationContext();
    beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, RemoteService.class, true,
            false);//from  www  .j ava2s .  co  m
    if (beanNames.length == 0) {
        return;
    }

    serviceConfigs = new ArrayList<RemoteServiceConfig>();
    for (String beanName : beanNames) {
        final Class<?> beanType;
        final Class<?> serviceInterface;

        beanType = beanFactory.getType(beanName);
        serviceInterface = getRemoteServiceInterface(beanType);
        if (serviceInterface != null) {
            if (serviceInterface.getAnnotation(RemoteServiceRelativePath.class) != null) {
                if (isAcceptedServiceInterface(serviceInterface)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Adding service '" + beanName + "'");
                    }
                    serviceConfigs.add(new RemoteServiceConfig(beanName));
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Ignoring service '" + beanName + "' since service does not specify "
                            + "remote service relative path");
                }
            }
        } else {
            if (log.isInfoEnabled()) {
                log.info("Ignoring service '" + beanName + "' since it implements multiple "
                        + "remote service interfaces");
            }
        }
    }

    setServiceConfigs(serviceConfigs);
}

From source file:com.moss.error_reporting.server.ErrorReportServer.java

public ErrorReportServer(ServerConfiguration config) {

    final Log log = LogFactory.getLog(this.getClass());

    try {//w w  w  .j  a  v  a  2s.co  m
        Server jetty = new Server();
        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setPort(config.bindPort());
        connector.setHost(config.bindAddress());
        jetty.addConnector(connector);

        boolean initialize = false;
        if (!config.storageDir().exists() || config.storageDir().listFiles().length == 0) {
            initialize = true;
        }

        log.info("Using storage dir: " + config.storageDir().getAbsolutePath());

        DataStore data = new DataStore(config.storageDir(), initialize);
        ReportingServiceImpl impl = new ReportingServiceImpl(data,
                new Notifier(config.smtpServer(), config.fromAddress(), config.emailReceipients()));

        final String path = "/Reporting";
        final SwitchingContentHandler handler = new SwitchingContentHandler(path);
        final boolean jaxwsEnabled = Boolean
                .parseBoolean(System.getProperty("shell.rpc.jaxws.enabled", "true"));

        if (jaxwsEnabled) {

            if (log.isDebugEnabled()) {
                log.debug(
                        "Constructing JAXWS http content handler RPC impl " + impl.getClass().getSimpleName());
            }

            try {
                ContentHandler jaxwsHandler = new JAXWSContentHandler(impl);
                handler.addHandler(jaxwsHandler);
            } catch (Exception ex) {
                throw new RuntimeException("Failed to create JAXWS service for " + impl.getClass().getName(),
                        ex);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Constructing Hessian http content handler for RPC impl "
                    + impl.getClass().getSimpleName());
        }

        ContentHandler hessianHandler = new HessianContentHandler(ReportingService.class, impl);
        handler.addHandler(hessianHandler);

        jetty.addHandler(handler);
        jetty.start();

        System.out.println("\n\nSERVER READY FOR ACTION\n\n");
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Unexpected Error.  Shutting Down.");
        System.exit(1);
    }
}

From source file:edu.vt.middleware.ldap.LdapTLSSocketFactory.java

/**
 * This returns a keystore as an <code>InputStream</code>. If the keystore
 * could not be loaded this method returns null.
 *
 * @param  filename  <code>String</code> to read
 * @param  pt  <code>PathType</code> how to read file
 *
 * @return  <code>InputStream</code> keystore
 *//*from  ww  w . j  a v a 2s  .  c om*/
private InputStream getInputStream(final String filename, final PathType pt) {
    final Log logger = LogFactory.getLog(LdapTLSSocketFactory.class);
    InputStream is = null;
    if (pt == PathType.CLASSPATH) {
        is = LdapTLSSocketFactory.class.getResourceAsStream(filename);
    } else if (pt == PathType.FILEPATH) {
        File file;
        try {
            file = new File(URI.create(filename));
        } catch (IllegalArgumentException e) {
            file = new File(filename);
        }
        try {
            is = new FileInputStream(file);
        } catch (IOException e) {
            if (logger.isWarnEnabled()) {
                logger.warn("Error loading keystore from " + filename, e);
            }
        }
    }
    if (is != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Successfully loaded " + filename + " from " + pt);
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to load " + filename + " from " + pt);
        }
    }
    return is;
}

From source file:helma.objectmodel.db.Transactor.java

/**
 * Commit the current transaction, persisting all changes to DB.
 *
 * @throws Exception ...// ww  w .j a  v a 2  s .  c  om
 */
public synchronized void commit() throws Exception {
    if (killed) {
        throw new DatabaseException("commit() called on killed transactor thread");
    } else if (!active) {
        return;
    }
    int inserted = 0;
    int updated = 0;
    int deleted = 0;

    ArrayList insertedNodes = null;
    ArrayList updatedNodes = null;
    ArrayList deletedNodes = null;
    ArrayList modifiedParentNodes = null;
    // if nodemanager has listeners collect dirty nodes
    boolean hasListeners = nmgr.hasNodeChangeListeners();

    if (hasListeners) {
        insertedNodes = new ArrayList();
        updatedNodes = new ArrayList();
        deletedNodes = new ArrayList();
        modifiedParentNodes = new ArrayList();
    }

    if (!dirtyNodes.isEmpty()) {
        Object[] dirty = dirtyNodes.values().toArray();

        // the set to collect DbMappings to be marked as changed
        HashSet dirtyDbMappings = new HashSet();
        Log eventLog = nmgr.app.getEventLog();

        for (int i = 0; i < dirty.length; i++) {
            Node node = (Node) dirty[i];

            // update nodes in db
            int nstate = node.getState();

            if (nstate == Node.NEW) {
                nmgr.insertNode(nmgr.db, txn, node);
                dirtyDbMappings.add(node.getDbMapping());
                node.setState(Node.CLEAN);

                // register node with nodemanager cache
                nmgr.registerNode(node);

                if (hasListeners) {
                    insertedNodes.add(node);
                }

                inserted++;
                if (eventLog.isDebugEnabled()) {
                    eventLog.debug("inserted node: " + node.getPrototype() + "/" + node.getID());
                }
            } else if (nstate == Node.MODIFIED) {
                // only mark DbMapping as dirty if updateNode returns true
                if (nmgr.updateNode(nmgr.db, txn, node)) {
                    dirtyDbMappings.add(node.getDbMapping());
                }
                node.setState(Node.CLEAN);

                // update node with nodemanager cache
                nmgr.registerNode(node);

                if (hasListeners) {
                    updatedNodes.add(node);
                }

                updated++;
                if (eventLog.isDebugEnabled()) {
                    eventLog.debug("updated node: " + node.getPrototype() + "/" + node.getID());
                }
            } else if (nstate == Node.DELETED) {
                nmgr.deleteNode(nmgr.db, txn, node);
                dirtyDbMappings.add(node.getDbMapping());

                // remove node from nodemanager cache
                nmgr.evictNode(node);

                if (hasListeners) {
                    deletedNodes.add(node);
                }

                deleted++;
                if (eventLog.isDebugEnabled()) {
                    eventLog.debug("removed node: " + node.getPrototype() + "/" + node.getID());
                }
            }

            node.clearWriteLock();
        }

        // set last data change times in db-mappings
        // long now = System.currentTimeMillis();
        for (Iterator i = dirtyDbMappings.iterator(); i.hasNext();) {
            DbMapping dbm = (DbMapping) i.next();
            if (dbm != null) {
                dbm.setLastDataChange();
            }
        }
    }

    long now = System.currentTimeMillis();

    if (!parentNodes.isEmpty()) {
        // set last subnode change times in parent nodes
        for (Iterator i = parentNodes.iterator(); i.hasNext();) {
            Node node = (Node) i.next();
            node.markSubnodesChanged();
            if (hasListeners) {
                modifiedParentNodes.add(node);
            }
        }
    }

    if (hasListeners) {
        nmgr.fireNodeChangeEvent(insertedNodes, updatedNodes, deletedNodes, modifiedParentNodes);
    }

    // clear the node collections
    recycle();

    if (active) {
        active = false;
        nmgr.db.commitTransaction(txn);
        txn = null;
    }

    StringBuffer msg = new StringBuffer(tname).append(" done in ").append(now - tstart).append(" millis");
    if (inserted + updated + deleted > 0) {
        msg.append(" [+").append(inserted).append(", ~").append(updated).append(", -").append(deleted)
                .append("]");
    }
    nmgr.app.logAccess(msg.toString());

    // unset transaction name
    tname = null;
}

From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java

/**
 * Initializes this FileSystemHotBeanModuleRepository.
 *///from   w w  w  .  ja v  a2s .c  o m
public void init() throws Exception {
    synchronized (super.getLock()) {
        if (!initialized) {
            Log logger = this.getLog();

            if (this.moduleRepositoryDirectory == null)
                this.moduleRepositoryDirectory = new File("hotModules");
            if (this.temporaryDirectory == null)
                this.temporaryDirectory = new File(this.moduleRepositoryDirectory, "temp");

            this.moduleRepositoryDirectory.mkdirs();
            this.temporaryDirectory.mkdirs();

            // Delete temporary directory on start up
            FileDeletor.delete(this.temporaryDirectory);

            if (logger.isDebugEnabled())
                logger.debug("Initializing FileSystemHotBeanModuleRepository - moduleRepositoryDirectory: "
                        + this.moduleRepositoryDirectory + ", temporaryDirectory: " + this.temporaryDirectory
                        + ".");

            RepositoryFileLock fileLock = null;
            try {
                fileLock = this.obtainRepositoryFileLock(false);
            } catch (Exception e) {
                logger.error("Error obtaining repository file lock on init!", e);
            } finally {
                this.releaseRepositoryFileLock(fileLock);
                fileLock = null;
            }

            super.init();

            initialized = true;
        }
    }
}

From source file:helma.framework.core.RequestEvaluator.java

/**
 *
 *///  w  ww.  j av  a  2 s .  c  o m
public void run() {
    // first, set a local variable to the current transactor thread so we know
    // when it's time to quit because another thread took over.
    Thread localThread = Thread.currentThread();

    // spans whole execution loop - close connections in finally clause
    try {

        // while this thread is serving requests
        while (localThread == thread) {

            // object reference to ressolve request path
            Object currentElement;

            // Get req and res into local variables to avoid memory caching problems
            // in unsynchronized method.
            RequestTrans req = getRequest();
            ResponseTrans res = getResponse();

            // request path object
            RequestPath requestPath = new RequestPath(app);

            String txname = req.getMethod() + ":" + req.getPath();
            Log eventLog = app.getEventLog();
            if (eventLog.isDebugEnabled()) {
                eventLog.debug(txname + " starting");
            }

            int tries = 0;
            boolean done = false;
            Throwable error = null;
            String functionName = function instanceof String ? (String) function : null;

            while (!done && localThread == thread) {
                // catch errors in path resolution and script execution
                try {

                    // initialize scripting engine
                    initScriptingEngine();
                    app.setCurrentRequestEvaluator(this);
                    // update scripting prototypes
                    scriptingEngine.enterContext();

                    // avoid going into transaction if called function doesn't exist.
                    // this only works for the (common) case that method is a plain
                    // method name, not an obj.method path
                    if (reqtype == INTERNAL) {
                        // if object is an instance of NodeHandle, get the node object itself.
                        if (thisObject instanceof NodeHandle) {
                            thisObject = ((NodeHandle) thisObject).getNode(app.nmgr.safe);
                            // If no valid node object return immediately
                            if (thisObject == null) {
                                done = true;
                                reqtype = NONE;
                                break;
                            }
                        }
                        // If function doesn't exist, return immediately
                        if (functionName != null
                                && !scriptingEngine.hasFunction(thisObject, functionName, true)) {
                            app.logEvent(missingFunctionMessage(thisObject, functionName));
                            done = true;
                            reqtype = NONE;
                            break;
                        }
                    } else if (function != null && functionName == null) {
                        // only internal requests may pass a function instead of a function name
                        throw new IllegalStateException("No function name in non-internal request ");
                    }

                    // Update transaction name in case we're processing an error
                    if (error != null) {
                        txname = "error:" + txname;
                    }

                    // begin transaction
                    transactor = Transactor.getInstance(app.nmgr);
                    transactor.begin(txname);

                    Object root = app.getDataRoot(scriptingEngine);
                    initGlobals(root, requestPath);

                    String action = null;

                    if (error != null) {
                        res.setError(error);
                    }

                    switch (reqtype) {
                    case HTTP:

                        // bring over the message from a redirect
                        session.recoverResponseMessages(res);

                        // catch redirect in path resolution or script execution
                        try {
                            // catch object not found in path resolution
                            try {
                                if (error != null) {
                                    // there was an error in the previous loop, call error handler
                                    currentElement = root;
                                    res.setStatus(500);

                                    // do not reset the requestPath so error handler can use the original one
                                    // get error handler action
                                    String errorAction = app.props.getProperty("error", "error");

                                    action = getAction(currentElement, errorAction, req);

                                    if (action == null) {
                                        throw new RuntimeException(error);
                                    }
                                } else if ((req.getPath() == null) || "".equals(req.getPath().trim())) {
                                    currentElement = root;
                                    requestPath.add(null, currentElement);

                                    action = getAction(currentElement, null, req);

                                    if (action == null) {
                                        throw new NotFoundException("Action not found");
                                    }
                                } else {
                                    // march down request path...
                                    StringTokenizer st = new StringTokenizer(req.getPath(), "/");
                                    int ntokens = st.countTokens();

                                    // limit path to < 50 tokens
                                    if (ntokens > 50) {
                                        throw new RuntimeException("Path too long");
                                    }

                                    String[] pathItems = new String[ntokens];

                                    for (int i = 0; i < ntokens; i++)
                                        pathItems[i] = st.nextToken();

                                    currentElement = root;
                                    requestPath.add(null, currentElement);

                                    for (int i = 0; i < ntokens; i++) {
                                        if (currentElement == null) {
                                            throw new NotFoundException("Object not found.");
                                        }

                                        if (pathItems[i].length() == 0) {
                                            continue;
                                        }

                                        // if we're at the last element of the path,
                                        // try to interpret it as action name.
                                        if (i == (ntokens - 1) && !req.getPath().endsWith("/")) {
                                            action = getAction(currentElement, pathItems[i], req);
                                        }

                                        if (action == null) {
                                            currentElement = getChildElement(currentElement, pathItems[i]);

                                            // add object to request path if suitable
                                            if (currentElement != null) {
                                                // add to requestPath array
                                                requestPath.add(pathItems[i], currentElement);
                                            }
                                        }
                                    }

                                    if (currentElement == null) {
                                        throw new NotFoundException("Object not found.");
                                    }

                                    if (action == null) {
                                        action = getAction(currentElement, null, req);
                                    }

                                    if (action == null) {
                                        throw new NotFoundException("Action not found");
                                    }
                                }
                            } catch (NotFoundException notfound) {
                                if (error != null) {

                                    // we already have an error and the error template wasn't found,
                                    // display it instead of notfound message
                                    throw new RuntimeException();
                                }

                                // The path could not be resolved. Check if there is a "not found" action
                                // specified in the property file.
                                res.setStatus(404);

                                String notFoundAction = app.props.getProperty("notfound", "notfound");

                                currentElement = root;
                                action = getAction(currentElement, notFoundAction, req);

                                if (action == null) {
                                    throw new NotFoundException(notfound.getMessage());
                                }
                            }

                            // register path objects with their prototype names in
                            // res.handlers
                            Map macroHandlers = res.getMacroHandlers();
                            int l = requestPath.size();
                            Prototype[] protos = new Prototype[l];

                            for (int i = 0; i < l; i++) {

                                Object obj = requestPath.get(i);

                                protos[i] = app.getPrototype(obj);

                                // immediately register objects with their direct prototype name
                                if (protos[i] != null) {
                                    macroHandlers.put(protos[i].getName(), obj);
                                    macroHandlers.put(protos[i].getLowerCaseName(), obj);
                                }
                            }

                            // in a second pass, we register path objects with their indirect
                            // (i.e. parent prototype) names, starting at the end and only
                            // if the name isn't occupied yet.
                            for (int i = l - 1; i >= 0; i--) {
                                if (protos[i] != null) {
                                    protos[i].registerParents(macroHandlers, requestPath.get(i));
                                }
                            }

                            /////////////////////////////////////////////////////////////////////////////
                            // end of path resolution section
                            /////////////////////////////////////////////////////////////////////////////
                            // beginning of execution section

                            // set the req.action property, cutting off the _action suffix
                            req.setAction(action);

                            // reset skin recursion detection counter
                            skinDepth = 0;

                            // try calling onRequest() function on object before
                            // calling the actual action
                            scriptingEngine.invoke(currentElement, "onRequest", EMPTY_ARGS,
                                    ScriptingEngine.ARGS_WRAP_DEFAULT, false);

                            // reset skin recursion detection counter
                            skinDepth = 0;

                            Object actionProcessor = req.getActionHandler() != null ? req.getActionHandler()
                                    : action;

                            // do the actual action invocation
                            if (req.isXmlRpc()) {
                                XmlRpcRequestProcessor xreqproc = new XmlRpcRequestProcessor();
                                XmlRpcServerRequest xreq = xreqproc
                                        .decodeRequest(req.getServletRequest().getInputStream());
                                Vector args = xreq.getParameters();
                                args.add(0, xreq.getMethodName());
                                result = scriptingEngine.invoke(currentElement, actionProcessor, args.toArray(),
                                        ScriptingEngine.ARGS_WRAP_XMLRPC, false);
                                res.writeXmlRpcResponse(result);
                                app.xmlrpcCount += 1;
                            } else {
                                scriptingEngine.invoke(currentElement, actionProcessor, EMPTY_ARGS,
                                        ScriptingEngine.ARGS_WRAP_DEFAULT, false);
                            }

                            // try calling onResponse() function on object before
                            // calling the actual action
                            scriptingEngine.invoke(currentElement, "onResponse", EMPTY_ARGS,
                                    ScriptingEngine.ARGS_WRAP_DEFAULT, false);

                        } catch (RedirectException redirect) {
                            // if there is a message set, save it on the user object for the next request
                            if (res.getRedirect() != null)
                                session.storeResponseMessages(res);
                        }

                        // check if request is still valid, or if the requesting thread has stopped waiting already
                        if (localThread != thread) {
                            return;
                        }
                        commitTransaction();
                        done = true;

                        break;

                    case XMLRPC:
                    case EXTERNAL:

                        try {
                            currentElement = root;

                            if (functionName.indexOf('.') > -1) {
                                StringTokenizer st = new StringTokenizer(functionName, ".");
                                int cnt = st.countTokens();

                                for (int i = 1; i < cnt; i++) {
                                    String next = st.nextToken();
                                    currentElement = getChildElement(currentElement, next);
                                }

                                if (currentElement == null) {
                                    throw new NotFoundException(
                                            "Method name \"" + function + "\" could not be resolved.");
                                }

                                functionName = st.nextToken();
                            }

                            if (reqtype == XMLRPC) {
                                // check XML-RPC access permissions
                                String proto = app.getPrototypeName(currentElement);
                                app.checkXmlRpcAccess(proto, functionName);
                            }

                            // reset skin recursion detection counter
                            skinDepth = 0;
                            if (!scriptingEngine.hasFunction(currentElement, functionName, false)) {
                                throw new NotFoundException(
                                        missingFunctionMessage(currentElement, functionName));
                            }
                            result = scriptingEngine.invoke(currentElement, functionName, args,
                                    ScriptingEngine.ARGS_WRAP_XMLRPC, false);
                            // check if request is still valid, or if the requesting thread has stopped waiting already
                            if (localThread != thread) {
                                return;
                            }
                            commitTransaction();
                        } catch (Exception x) {
                            // check if request is still valid, or if the requesting thread has stopped waiting already
                            if (localThread != thread) {
                                return;
                            }
                            abortTransaction();
                            app.logError(txname + " " + error, x);

                            // If the transactor thread has been killed by the invoker thread we don't have to
                            // bother for the error message, just quit.
                            if (localThread != thread) {
                                return;
                            }

                            this.exception = x;
                        }

                        done = true;
                        break;

                    case INTERNAL:

                        try {
                            // reset skin recursion detection counter
                            skinDepth = 0;

                            result = scriptingEngine.invoke(thisObject, function, args,
                                    ScriptingEngine.ARGS_WRAP_DEFAULT, true);
                            // check if request is still valid, or if the requesting thread has stopped waiting already
                            if (localThread != thread) {
                                return;
                            }
                            commitTransaction();
                        } catch (Exception x) {
                            // check if request is still valid, or if the requesting thread has stopped waiting already
                            if (localThread != thread) {
                                return;
                            }
                            abortTransaction();
                            app.logError(txname + " " + error, x);

                            // If the transactor thread has been killed by the invoker thread we don't have to
                            // bother for the error message, just quit.
                            if (localThread != thread) {
                                return;
                            }

                            this.exception = x;
                        }

                        done = true;
                        break;

                    } // switch (reqtype)
                } catch (AbortException x) {
                    // res.abort() just aborts the transaction and
                    // leaves the response untouched
                    // check if request is still valid, or if the requesting thread has stopped waiting already
                    if (localThread != thread) {
                        return;
                    }
                    abortTransaction();
                    done = true;
                } catch (ConcurrencyException x) {
                    res.reset();

                    if (++tries < 8) {
                        // try again after waiting some period
                        // check if request is still valid, or if the requesting thread has stopped waiting already
                        if (localThread != thread) {
                            return;
                        }
                        abortTransaction();

                        try {
                            // wait a bit longer with each try
                            int base = 800 * tries;
                            Thread.sleep((long) (base + (Math.random() * base * 2)));
                        } catch (InterruptedException interrupt) {
                            // we got interrrupted, create minimal error message 
                            res.reportError(interrupt);
                            done = true;
                            // and release resources and thread
                            thread = null;
                            transactor = null;
                        }
                    } else {
                        // check if request is still valid, or if the requesting thread has stopped waiting already
                        if (localThread != thread) {
                            return;
                        }
                        abortTransaction();

                        // error in error action. use traditional minimal error message
                        res.reportError("Application too busy, please try again later");
                        done = true;
                    }
                } catch (Throwable x) {
                    // check if request is still valid, or if the requesting thread has stopped waiting already
                    if (localThread != thread) {
                        return;
                    }
                    abortTransaction();

                    // If the transactor thread has been killed by the invoker thread we don't have to
                    // bother for the error message, just quit.
                    if (localThread != thread) {
                        return;
                    }

                    res.reset();

                    // check if we tried to process the error already,
                    // or if this is an XML-RPC request
                    if (error == null) {
                        if (!(x instanceof NotFoundException)) {
                            app.errorCount += 1;
                        }

                        // set done to false so that the error will be processed
                        done = false;
                        error = x;

                        app.logError(txname + " " + error, x);

                        if (req.isXmlRpc()) {
                            // if it's an XML-RPC exception immediately generate error response
                            if (!(x instanceof Exception)) {
                                // we need an exception to pass to XML-RPC responder
                                x = new Exception(x.toString(), x);
                            }
                            res.writeXmlRpcError((Exception) x);
                            done = true;
                        }
                    } else {
                        // error in error action. use traditional minimal error message
                        res.reportError(error);
                        done = true;
                    }
                } finally {
                    app.setCurrentRequestEvaluator(null);
                    // exit execution context
                    if (scriptingEngine != null) {
                        try {
                            scriptingEngine.exitContext();
                        } catch (Throwable t) {
                            // broken rhino, just get out of here
                        }
                    }
                }
            }

            notifyAndWait();

        }
    } finally {
        Transactor tx = Transactor.getInstance();
        if (tx != null)
            tx.closeConnections();
    }
}