Example usage for java.lang Thread getAllStackTraces

List of usage examples for java.lang Thread getAllStackTraces

Introduction

In this page you can find the example usage for java.lang Thread getAllStackTraces.

Prototype

public static Map<Thread, StackTraceElement[]> getAllStackTraces() 

Source Link

Document

Returns a map of stack traces for all live threads.

Usage

From source file:org.opennms.core.test.db.TemporaryDatabasePostgreSQL.java

public static void dumpThreads() {
    Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
    int daemons = 0;
    for (Thread t : threads.keySet()) {
        if (t.isDaemon()) {
            daemons++;//from w  w w  . ja  v  a 2s  .c om
        }
    }
    System.err.println("Thread dump of " + threads.size() + " threads (" + daemons + " daemons):");
    Map<Thread, StackTraceElement[]> sortedThreads = new TreeMap<Thread, StackTraceElement[]>(
            new Comparator<Thread>() {
                @Override
                public int compare(final Thread t1, final Thread t2) {
                    return Long.valueOf(t1.getId()).compareTo(Long.valueOf(t2.getId()));
                }
            });
    sortedThreads.putAll(threads);

    for (Entry<Thread, StackTraceElement[]> entry : sortedThreads.entrySet()) {
        Thread thread = entry.getKey();
        System.err.println("Thread " + thread.getId() + (thread.isDaemon() ? " (daemon)" : "") + ": " + thread
                + " (state: " + thread.getState() + ")");
        for (StackTraceElement e : entry.getValue()) {
            System.err.println("\t" + e);
        }
    }
    System.err.println("Thread dump completed.");
}

From source file:bear.core.BearMain.java

public static StringBuilder threadDump() {
    Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();

    StringBuilder sb = new StringBuilder();

    for (Map.Entry<Thread, StackTraceElement[]> e : map.entrySet()) {
        Thread thread = e.getKey();

        StackTraceElement[] elements = e.getValue();
        StackTraceElement el = elements == null || elements.length == 0 ? null : elements[0];

        sb.append(thread.getName());//from w w w.j a va2s  .  c  om
        if (el != null) {
            sb.append("\tat ").append(el).append("\n");
        }
    }

    sb.append("\n\n");

    Exception e = new Exception();

    for (Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
        Thread thread = entry.getKey();
        StackTraceElement[] stack = entry.getValue();
        sb.append(thread.getName()).append(", id=").append(thread.getId()).append("\n");
        e.setStackTrace(stack);
        sb.append(Throwables.getStackTraceAsString(e));
        sb.append("\n");
    }

    return sb;
}

From source file:hudson.Functions.java

public static Map<Thread, StackTraceElement[]> dumpAllThreads() {
    return Thread.getAllStackTraces();
}

From source file:password.pwm.http.servlet.ConfigManagerServlet.java

private void outputZipDebugFile(final PwmRequest pwmRequest, final ZipOutputStream zipOutput,
        final String pathPrefix) throws IOException, PwmUnrecoverableException {
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final PwmSession pwmSession = pwmRequest.getPwmSession();

    { // kick off health check so that it might be faster later..
        Thread healthThread = new Thread() {
            public void run() {
                pwmApplication.getHealthMonitor().getHealthRecords();
            }//  w  ww . ja  va 2s  .c om
        };
        healthThread
                .setName(Helper.makeThreadName(pwmApplication, ConfigManagerServlet.class) + "-HealthCheck");
        healthThread.setDaemon(true);
        healthThread.start();
    }
    final StoredConfiguration storedConfiguration = readCurrentConfiguration(pwmRequest);
    storedConfiguration.resetAllPasswordValues(
            "value removed from " + PwmConstants.PWM_APP_NAME + "-Support configuration export");
    {
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + PwmConstants.DEFAULT_CONFIG_FILE_FILENAME));
        storedConfiguration.resetAllPasswordValues(
                "value removed from " + PwmConstants.PWM_APP_NAME + "-Support configuration export");

        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        storedConfiguration.toXml(outputStream);
        zipOutput.write(outputStream.toByteArray());
        zipOutput.closeEntry();
        zipOutput.flush();
    }
    {
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "configuration-debug.txt"));
        zipOutput.write(storedConfiguration.toString(true).getBytes(PwmConstants.DEFAULT_CHARSET));
        zipOutput.closeEntry();
        zipOutput.flush();
    }
    {
        final String aboutJson = JsonUtil.serialize(AdminServlet.makeInfoBean(pwmApplication),
                JsonUtil.Flag.PrettyPrint);
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "about.json"));
        zipOutput.write(aboutJson.getBytes(PwmConstants.DEFAULT_CHARSET));
        zipOutput.closeEntry();
        zipOutput.flush();
    }
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pwmApplication.getAuditManager().outputVaultToCsv(baos, pwmRequest.getLocale(), true);
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "audit.csv"));
        zipOutput.write(baos.toByteArray());
        zipOutput.closeEntry();
        zipOutput.flush();
    }
    {
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "info.json"));
        final LinkedHashMap<String, Object> outputMap = new LinkedHashMap<>();

        { // services info
            final LinkedHashMap<String, Object> servicesMap = new LinkedHashMap<>();
            for (final PwmService service : pwmApplication.getPwmServices()) {
                final LinkedHashMap<String, Object> serviceOutput = new LinkedHashMap<>();
                serviceOutput.put("name", service.getClass().getSimpleName());
                serviceOutput.put("status", service.status());
                serviceOutput.put("health", service.healthCheck());
                serviceOutput.put("serviceInfo", service.serviceInfo());
                servicesMap.put(service.getClass().getSimpleName(), serviceOutput);
            }
            outputMap.put("services", servicesMap);
        }

        // java threads
        outputMap.put("threads", Thread.getAllStackTraces());

        final String recordJson = JsonUtil.serializeMap(outputMap, JsonUtil.Flag.PrettyPrint);
        zipOutput.write(recordJson.getBytes(PwmConstants.DEFAULT_CHARSET));
        zipOutput.closeEntry();
        zipOutput.flush();
    }
    if (pwmApplication.getApplicationPath() != null) {
        try {
            zipOutput.putNextEntry(new ZipEntry(pathPrefix + "fileMd5sums.json"));
            final Map<String, String> fileChecksums = BuildChecksumMaker
                    .readDirectorySums(pwmApplication.getApplicationPath());
            final String json = JsonUtil.serializeMap(fileChecksums, JsonUtil.Flag.PrettyPrint);
            zipOutput.write(json.getBytes(PwmConstants.DEFAULT_CHARSET));
            zipOutput.closeEntry();
            zipOutput.flush();
        } catch (Exception e) {
            LOGGER.error(pwmSession,
                    "unable to generate fileMd5sums during zip debug building: " + e.getMessage());
        }
    }
    {
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "debug.log"));
        final int maxCount = 100 * 1000;
        final int maxSeconds = 30 * 1000;
        final LocalDBLogger.SearchParameters searchParameters = new LocalDBLogger.SearchParameters(
                PwmLogLevel.TRACE, maxCount, null, null, maxSeconds, null);
        final LocalDBLogger.SearchResults searchResults = pwmApplication.getLocalDBLogger()
                .readStoredEvents(searchParameters);
        int counter = 0;
        while (searchResults.hasNext()) {
            final PwmLogEvent event = searchResults.next();
            zipOutput.write(event.toLogString().getBytes(PwmConstants.DEFAULT_CHARSET));
            zipOutput.write("\n".getBytes(PwmConstants.DEFAULT_CHARSET));
            counter++;
            if (counter % 100 == 0) {
                zipOutput.flush();
            }
        }
        zipOutput.closeEntry();
    }
    {
        zipOutput.putNextEntry(new ZipEntry(pathPrefix + "health.json"));
        final Set<HealthRecord> records = pwmApplication.getHealthMonitor().getHealthRecords();
        final String recordJson = JsonUtil.serializeCollection(records, JsonUtil.Flag.PrettyPrint);
        zipOutput.write(recordJson.getBytes(PwmConstants.DEFAULT_CHARSET));
        zipOutput.closeEntry();
        zipOutput.flush();
    }
}

From source file:org.apache.hadoop.hive.metastore.MetaStoreUtils.java

private static String getAllThreadStacksAsString() {
    Map<Thread, StackTraceElement[]> threadStacks = Thread.getAllStackTraces();
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<Thread, StackTraceElement[]> entry : threadStacks.entrySet()) {
        Thread t = entry.getKey();
        sb.append(System.lineSeparator());
        sb.append("Name: ").append(t.getName()).append(" State: ").append(t.getState());
        addStackString(entry.getValue(), sb);
    }// ww w.  j av  a2s  .  c  o  m
    return sb.toString();
}

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextDestroyed(ServletContextEvent event) {

    _logger.info("Shutting down...");

    // interrupt the page monitor if we have one
    if (_monitor != null)
        _monitor.interrupt();/*from   w w  w . ja v  a 2  s.c o m*/

    // get the servletContext
    ServletContext servletContext = event.getServletContext();

    // get all of the applications
    Applications applications = (Applications) servletContext.getAttribute("applications");
    // if we got some
    if (applications != null) {
        // loop the application ids
        for (String id : applications.getIds()) {
            // get the application
            Versions versions = applications.getVersions(id);
            // loop the versions of each app
            for (String version : versions.keySet()) {
                // get the application
                Application application = applications.get(id, version);
                // have it close any sensitive resources 
                application.close(servletContext);
            }
        }
    }

    // sleep for 2 seconds to allow any database connection cleanup to complete
    try {
        Thread.sleep(2000);
    } catch (Exception ex) {
    }

    // This manually deregisters JDBC drivers, which prevents Tomcat from complaining about memory leaks from this class
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            DriverManager.deregisterDriver(driver);
            _logger.info(String.format("Deregistering jdbc driver: %s", driver));
        } catch (SQLException e) {
            _logger.error(String.format("Error deregistering driver %s", driver), e);
        }
    }

    // Thanks to http://stackoverflow.com/questions/11872316/tomcat-guice-jdbc-memory-leak
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (Thread t : threadArray) {
        if (t.getName().contains("Abandoned connection cleanup thread")) {
            synchronized (t) {
                try {
                    _logger.info("Forcing stop of Abandoned connection cleanup thread");
                    t.stop(); //don't complain, it works
                } catch (Exception ex) {
                    _logger.info("Error forcing stop of Abandoned connection cleanup thread", ex);
                }
            }
        }
    }

    // sleep for 1 second to allow any database connection cleanup to complete
    try {
        Thread.sleep(1000);
    } catch (Exception ex) {
    }

    // last log
    _logger.info("Logger shutdown");
    // shutdown logger
    if (_logger != null)
        LogManager.shutdown();

}

From source file:pcgen.gui2.facade.CharacterFacadeImpl.java

/**
 * @see pcgen.facade.core.CharacterFacade#export(ExportHandler, BufferedWriter)
 *///from   w w w.j  av  a 2 s.  co  m
@Override
public void export(ExportHandler theHandler, BufferedWriter buf) throws ExportException {
    final int maxRetries = 3;
    for (int i = 0; i < maxRetries; i++) {
        try {
            Logging.log(Logging.DEBUG, "Starting export at serial " + theCharacter.getSerial() + " to "
                    + theHandler.getTemplateFile());
            PlayerCharacter exportPc = getExportCharacter();
            theHandler.write(exportPc, buf);
            Logging.log(Logging.DEBUG, "Finished export at serial " + theCharacter.getSerial() + " to "
                    + theHandler.getTemplateFile());
            return;
        } catch (ConcurrentModificationException e) {
            Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
            for (Entry<Thread, StackTraceElement[]> threadEntry : allStackTraces.entrySet()) {
                if (threadEntry.getValue().length > 1) {
                    StringBuilder sb = new StringBuilder("Thread: " + threadEntry.getKey() + "\n");
                    for (StackTraceElement elem : threadEntry.getValue()) {
                        sb.append("  ");
                        sb.append(elem.toString());
                        sb.append("\n");
                    }
                    Logging.log(Logging.INFO, sb.toString());
                }
            }
            Logging.log(Logging.WARNING, "Retrying export after ConcurrentModificationException", e);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                Logging.errorPrint("Interrupted sleep - probably closing.");
                return;

            }
        }
    }
    Logging.errorPrint(
            "Unable to export using " + theHandler.getTemplateFile() + " due to concurrent modifications.");
}

From source file:org.sakaiproject.site.tool.SiteAction.java

/**
 * /* Actions for vm templates under the "chef_site" root. This method is
 * called by doContinue. Each template has a hidden field with the value of
 * template-index that becomes the value of index for the switch statement
 * here. Some cases not implemented./*from  w  ww. j  a v a 2 s. c  o  m*/
 */
private void actionForTemplate(String direction, int index, ParameterParser params, final SessionState state,
        RunData data) {
    // Continue - make any permanent changes, Back - keep any data entered
    // on the form
    boolean forward = "continue".equals(direction) ? true : false;

    SiteInfo siteInfo = new SiteInfo();
    // SAK-16600 change to new template for tool editing
    if (index == 3) {
        index = 4;
    }

    switch (index) {
    case 0:
        /*
         * actionForTemplate chef_site-list.vm
         * 
         */
        break;
    case 1:
        /*
         * actionForTemplate chef_site-type.vm
         * 
         */
        break;
    case 4:
        /*
         * actionForTemplate chef_site-editFeatures.vm
         * actionForTemplate chef_site-editToolGroupFeatures.vm
         * 
         */
        if (forward) {
            // editing existing site or creating a new one?
            Site site = getStateSite(state);
            getFeatures(params, state, site == null ? "18" : "15");
        }
        break;

    case 8:
        /*
         * actionForTemplate chef_site-siteDeleteConfirm.vm
         * 
         */
        break;
    case 10:
        /*
         * actionForTemplate chef_site-newSiteConfirm.vm
         * 
         */
        if (!forward) {
        }
        break;
    case 12:
        /*
         * actionForTemplate chef_site_siteInfo-list.vm
         * 
         */
        break;
    case 13:
        /*
         * actionForTemplate chef_site_siteInfo-editInfo.vm
         * 
         */
        if (forward) {
            if (getStateSite(state) == null) {
                // alerts after clicking Continue but not Back
                if (!forward) {
                    // removing previously selected template site
                    state.removeAttribute(STATE_TEMPLATE_SITE);
                }

                updateSiteAttributes(state);
            }

            updateSiteInfo(params, state);
        }
        break;
    case 14:
        /*
         * actionForTemplate chef_site_siteInfo-editInfoConfirm.vm
         * 
         */
        break;
    case 15:
        /*
         * actionForTemplate chef_site_siteInfo-addRemoveFeatureConfirm.vm
         * 
         */
        break;
    case 18:
        /*
         * actionForTemplate chef_siteInfo-editAccess.vm
         * 
         */
        if (!forward) {
        }
        break;
    case 24:
        /*
         * actionForTemplate
         * chef_site-siteInfo-editAccess-globalAccess-confirm.vm
         * 
         */
        break;
    case 26:
        /*
         * actionForTemplate chef_site-modifyENW.vm
         * 
         */
        updateSelectedToolList(state, params, true);
        break;
    case 27:
        /*
         * actionForTemplate chef_site-importSites.vm
         * 
         * This is called after the tools have been selected on the import page (merge) and the finish button is clicked
         * and is also called in the new site workflow when importing from an existing site
         */
        if (forward) {
            Site existingSite = getStateSite(state);
            if (existingSite != null) {
                // revising a existing site's tool
                if (select_import_tools(params, state)) {
                    String threadName = "SiteImportThread" + existingSite.getId();
                    boolean found = false;
                    //check all running threads for our named thread
                    //this isn't cluster safe, but this check it more targeted towards
                    //a single user re-importing multiple times during a slow import (which would be on the same server)
                    for (Thread t : Thread.getAllStackTraces().keySet()) {
                        if (threadName.equals(t.getName())) {
                            found = true;
                            break;
                        }
                    }
                    if (found) {
                        //an existing thread is running for this site import, throw warning
                        addAlert(state, rb.getString("java.import.existing"));
                    } else {

                        // list of tools that were selected for import
                        final Hashtable importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL);

                        //list of existing tools in the destination site
                        final List existingTools = originalToolIds(
                                (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST),
                                state);

                        final String userEmail = UserDirectoryService.getCurrentUser().getEmail();
                        final Session session = SessionManager.getCurrentSession();
                        final ToolSession toolSession = SessionManager.getCurrentToolSession();
                        final String siteId = existingSite.getId();
                        Thread siteImportThread = new Thread() {
                            public void run() {
                                Site existingSite;
                                try {
                                    existingSite = SiteService.getSite(siteId);
                                    SessionManager.setCurrentSession(session);
                                    SessionManager.setCurrentToolSession(toolSession);
                                    EventTrackingService.post(
                                            EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_START,
                                                    existingSite.getReference(), false));
                                    importToolIntoSite(existingTools, importTools, existingSite);
                                    if (ServerConfigurationService.getBoolean(SAK_PROP_IMPORT_NOTIFICATION,
                                            true)) {
                                        userNotificationProvider.notifySiteImportCompleted(userEmail,
                                                existingSite.getId(), existingSite.getTitle());
                                    }
                                    EventTrackingService.post(
                                            EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_END,
                                                    existingSite.getReference(), false));
                                } catch (IdUnusedException e) {
                                    M_log.error(e.getMessage(), e);
                                }
                            }
                        };
                        siteImportThread.setName(threadName);
                        siteImportThread.start();
                        state.setAttribute(IMPORT_QUEUED, rb.get("importQueued"));
                        state.removeAttribute(STATE_IMPORT_SITE_TOOL);
                        state.removeAttribute(STATE_IMPORT_SITES);
                    }
                } else {
                    // show alert and remain in current page
                    addAlert(state, rb.getString("java.toimporttool"));
                }
            } else {
                // new site
                select_import_tools(params, state);
            }
        } else {
            // read form input about import tools
            select_import_tools(params, state);
        }
        break;
    case 60:
        /*
         * actionForTemplate chef_site-importSitesMigrate.vm
         * 
         * This is called after the tools have been selected on the import page (replace) and the finish button is clicked
         *
         */
        if (forward) {
            Site existingSite = getStateSite(state);
            if (existingSite != null) {
                // revising a existing site's tool
                if (select_import_tools(params, state)) {
                    String threadName = "SiteImportThread" + existingSite.getId();
                    boolean found = false;
                    //check all running threads for our named thread
                    //this isn't cluster safe, but this check it more targeted towards
                    //a single user re-importing multiple times during a slow import (which would be on the same server)
                    for (Thread t : Thread.getAllStackTraces().keySet()) {
                        if (threadName.equals(t.getName())) {
                            found = true;
                            break;
                        }
                    }
                    if (found) {
                        //an existing thread is running for this site import, throw warning
                        addAlert(state, rb.getString("java.import.existing"));
                    } else {

                        // list of tools that were selected for import
                        final Hashtable importTools = (Hashtable) state.getAttribute(STATE_IMPORT_SITE_TOOL);

                        //list of existing tools in the destination site
                        final List existingTools = originalToolIds(
                                (List<String>) state.getAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST),
                                state);

                        final String userEmail = UserDirectoryService.getCurrentUser().getEmail();
                        final Session session = SessionManager.getCurrentSession();
                        final ToolSession toolSession = SessionManager.getCurrentToolSession();
                        final String siteId = existingSite.getId();
                        Thread siteImportThread = new Thread() {
                            public void run() {
                                Site existingSite;
                                try {
                                    existingSite = SiteService.getSite(siteId);
                                    SessionManager.setCurrentSession(session);
                                    SessionManager.setCurrentToolSession(toolSession);
                                    EventTrackingService.post(
                                            EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_START,
                                                    existingSite.getReference(), false));
                                    // Remove all old contents before importing contents from new site
                                    importToolIntoSiteMigrate(existingTools, importTools, existingSite);
                                    if (ServerConfigurationService.getBoolean(SAK_PROP_IMPORT_NOTIFICATION,
                                            true)) {
                                        userNotificationProvider.notifySiteImportCompleted(userEmail,
                                                existingSite.getId(), existingSite.getTitle());
                                    }
                                    EventTrackingService.post(
                                            EventTrackingService.newEvent(SiteService.EVENT_SITE_IMPORT_END,
                                                    existingSite.getReference(), false));
                                } catch (IdUnusedException e) {
                                    M_log.error(e.getMessage(), e);
                                }
                            }
                        };
                        siteImportThread.setName(threadName);
                        siteImportThread.start();
                        state.setAttribute(IMPORT_QUEUED, rb.get("importQueued"));
                        state.removeAttribute(STATE_IMPORT_SITE_TOOL);
                        state.removeAttribute(STATE_IMPORT_SITES);
                    }
                } else {
                    // show alert and remain in current page
                    addAlert(state, rb.getString("java.toimporttool"));
                }
            } else {
                // new site
                select_import_tools(params, state);
            }
        } else {
            // read form input about import tools
            select_import_tools(params, state);
        }
        break;
    case 28:
        /*
         * actionForTemplate chef_siteinfo-import.vm
         * 
         * This is called after the sites to import from have been selected on the import page and the next button is clicked
         * 
         */
        if (forward) {
            if (params.getStrings("importSites") == null) {
                addAlert(state, rb.getString("java.toimport") + " ");
                state.removeAttribute(STATE_IMPORT_SITES);
            } else {
                List importSites = new ArrayList(Arrays.asList(params.getStrings("importSites")));
                Hashtable sites = new Hashtable();
                for (index = 0; index < importSites.size(); index++) {
                    try {
                        Site s = SiteService.getSite((String) importSites.get(index));
                        sites.put(s, new Vector());
                    } catch (IdUnusedException e) {
                    }
                }
                state.setAttribute(STATE_IMPORT_SITES, sites);
            }
        }
        break;
    case 58:
        /*
         * actionForTemplate chef_siteinfo-importSelection.vm
         * 
         */
        break;
    case 59:
        /*
         * actionForTemplate chef_siteinfo-import.vm
         * 
         */
        if (forward) {
            if (params.getStrings("importSites") == null) {
                addAlert(state, rb.getString("java.toimport") + " ");
                state.removeAttribute(STATE_IMPORT_SITES);
            } else {
                List importSites = new ArrayList(Arrays.asList(params.getStrings("importSites")));
                Hashtable sites = new Hashtable();
                for (index = 0; index < importSites.size(); index++) {
                    try {
                        Site s = SiteService.getSite((String) importSites.get(index));
                        sites.put(s, new Vector());
                    } catch (IdUnusedException e) {
                    }
                }
                state.setAttribute(STATE_IMPORT_SITES, sites);
            }

        }
        break;
    case 29:
        /*
         * actionForTemplate chef_siteinfo-duplicate.vm
         * 
         */
        if (forward) {
            if (state.getAttribute(SITE_DUPLICATED) == null) {
                if (StringUtils.trimToNull(params.getString("title")) == null) {
                    addAlert(state, rb.getString("java.dupli") + " ");
                } else {
                    String title = params.getString("title");
                    state.setAttribute(SITE_DUPLICATED_NAME, title);

                    String newSiteId = IdManager.createUuid();
                    try {
                        String oldSiteId = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);

                        // Retrieve the source site reference to be used in the EventTrackingService
                        // notification of the start/end of a site duplication.
                        String sourceSiteRef = null;
                        try {
                            Site sourceSite = SiteService.getSite(oldSiteId);
                            sourceSiteRef = sourceSite.getReference();

                        } catch (IdUnusedException e) {
                            M_log.warn(
                                    this + ".actionForTemplate; case29: invalid source siteId: " + oldSiteId);
                            return;
                        }

                        // SAK-20797
                        long oldSiteQuota = this.getSiteSpecificQuota(oldSiteId);

                        Site site = SiteService.addSite(newSiteId, getStateSite(state));

                        // An event for starting the "duplicate site" action
                        EventTrackingService
                                .post(EventTrackingService.newEvent(SiteService.EVENT_SITE_DUPLICATE_START,
                                        sourceSiteRef, site.getId(), false, NotificationService.NOTI_OPTIONAL));

                        // get the new site icon url
                        if (site.getIconUrl() != null) {
                            site.setIconUrl(transferSiteResource(oldSiteId, newSiteId, site.getIconUrl()));
                        }

                        // set title
                        site.setTitle(title);

                        // SAK-20797 alter quota if required
                        boolean duplicateQuota = params.getString("dupequota") != null
                                ? params.getBoolean("dupequota")
                                : false;
                        if (duplicateQuota == true) {

                            if (oldSiteQuota > 0) {
                                M_log.info("Saving quota");
                                try {
                                    String collId = m_contentHostingService.getSiteCollection(site.getId());

                                    ContentCollectionEdit col = m_contentHostingService.editCollection(collId);

                                    ResourcePropertiesEdit resourceProperties = col.getPropertiesEdit();
                                    resourceProperties.addProperty(
                                            ResourceProperties.PROP_COLLECTION_BODY_QUOTA,
                                            new Long(oldSiteQuota).toString());
                                    m_contentHostingService.commitCollection(col);

                                } catch (Exception ignore) {
                                    M_log.warn("saveQuota: unable to duplicate site-specific quota for site : "
                                            + site.getId() + " : " + ignore);
                                }
                            }
                        }

                        try {
                            SiteService.save(site);

                            // import tool content
                            importToolContent(oldSiteId, site, false);

                            String siteType = site.getType();
                            if (SiteTypeUtil.isCourseSite(siteType)) {
                                // for course site, need to
                                // read in the input for
                                // term information
                                String termId = StringUtils.trimToNull(params.getString("selectTerm"));
                                if (termId != null) {
                                    AcademicSession term = cms.getAcademicSession(termId);
                                    if (term != null) {
                                        ResourcePropertiesEdit rp = site.getPropertiesEdit();
                                        rp.addProperty(Site.PROP_SITE_TERM, term.getTitle());
                                        rp.addProperty(Site.PROP_SITE_TERM_EID, term.getEid());
                                    } else {
                                        M_log.warn("termId=" + termId + " not found");
                                    }
                                }
                            }

                            // save again
                            SiteService.save(site);

                            String realm = SiteService.siteReference(site.getId());
                            try {
                                AuthzGroup realmEdit = authzGroupService.getAuthzGroup(realm);
                                if (SiteTypeUtil.isCourseSite(siteType)) {
                                    // also remove the provider id attribute if any
                                    realmEdit.setProviderGroupId(null);
                                }

                                // add current user as the maintainer
                                realmEdit.addMember(UserDirectoryService.getCurrentUser().getId(),
                                        site.getMaintainRole(), true, false);

                                authzGroupService.save(realmEdit);
                            } catch (GroupNotDefinedException e) {
                                M_log.error(this
                                        + ".actionForTemplate chef_siteinfo-duplicate: IdUnusedException, not found, or not an AuthzGroup object "
                                        + realm, e);
                                addAlert(state, rb.getString("java.realm"));
                            } catch (AuthzPermissionException e) {
                                addAlert(state, this + rb.getString("java.notaccess"));
                                M_log.error(this + ".actionForTemplate chef_siteinfo-duplicate: "
                                        + rb.getString("java.notaccess"), e);
                            }

                        } catch (IdUnusedException e) {
                            M_log.warn(this
                                    + " actionForTemplate chef_siteinfo-duplicate:: IdUnusedException when saving "
                                    + newSiteId);
                        } catch (PermissionException e) {
                            M_log.warn(this
                                    + " actionForTemplate chef_siteinfo-duplicate:: PermissionException when saving "
                                    + newSiteId);
                        }

                        // TODO: hard coding this frame id
                        // is fragile, portal dependent, and
                        // needs to be fixed -ggolden
                        // schedulePeerFrameRefresh("sitenav");
                        scheduleTopRefresh();

                        // send site notification
                        sendSiteNotification(state, site, null);

                        state.setAttribute(SITE_DUPLICATED, Boolean.TRUE);

                        // An event for ending the "duplicate site" action
                        EventTrackingService
                                .post(EventTrackingService.newEvent(SiteService.EVENT_SITE_DUPLICATE_END,
                                        sourceSiteRef, site.getId(), false, NotificationService.NOTI_OPTIONAL));

                    } catch (IdInvalidException e) {
                        addAlert(state, rb.getString("java.siteinval"));
                        M_log.error(this + ".actionForTemplate chef_siteinfo-duplicate: "
                                + rb.getString("java.siteinval") + " site id = " + newSiteId, e);
                    } catch (IdUsedException e) {
                        addAlert(state, rb.getString("java.sitebeenused"));
                        M_log.error(this + ".actionForTemplate chef_siteinfo-duplicate: "
                                + rb.getString("java.sitebeenused") + " site id = " + newSiteId, e);
                    } catch (PermissionException e) {
                        addAlert(state, rb.getString("java.allowcreate"));
                        M_log.error(this + ".actionForTemplate chef_siteinfo-duplicate: "
                                + rb.getString("java.allowcreate") + " site id = " + newSiteId, e);
                    }
                }
            }

            if (state.getAttribute(STATE_MESSAGE) == null) {
                // site duplication confirmed
                state.removeAttribute(SITE_DUPLICATED);
                state.removeAttribute(SITE_DUPLICATED_NAME);

                // return to the list view
                state.setAttribute(STATE_TEMPLATE_INDEX, "12");
            }
        }
        break;
    case 33:
        break;
    case 36:
        /*
         * actionForTemplate chef_site-newSiteCourse.vm
         */
        if (forward) {
            List providerChosenList = new Vector();
            List providerDescriptionChosenList = new Vector();

            if (params.getStrings("providerCourseAdd") == null) {
                state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
                state.removeAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN);
                if (params.getString("manualAdds") == null) {
                    addAlert(state, rb.getString("java.manual") + " ");
                }
            }
            if (state.getAttribute(STATE_MESSAGE) == null) {
                // The list of courses selected from provider listing
                if (params.getStrings("providerCourseAdd") != null) {
                    providerChosenList = new ArrayList(Arrays.asList(params.getStrings("providerCourseAdd"))); // list of
                    // description choices
                    if (params.getStrings("providerCourseAddDescription") != null) {
                        providerDescriptionChosenList = new ArrayList(
                                Arrays.asList(params.getStrings("providerCourseAddDescription"))); // list of
                        state.setAttribute(STATE_ADD_CLASS_PROVIDER_DESCRIPTION_CHOSEN,
                                providerDescriptionChosenList);
                    }
                    // course
                    // ids
                    String userId = (String) state.getAttribute(STATE_INSTRUCTOR_SELECTED);
                    String currentUserId = (String) state.getAttribute(STATE_CM_CURRENT_USERID);

                    if (userId == null || (userId != null && userId.equals(currentUserId))) {
                        state.setAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN, providerChosenList);
                        state.removeAttribute(STATE_CM_AUTHORIZER_SECTIONS);
                        state.removeAttribute(FORM_ADDITIONAL);
                        state.removeAttribute(STATE_CM_AUTHORIZER_LIST);
                    } else {
                        // STATE_CM_AUTHORIZER_SECTIONS are SectionObject,
                        // so need to prepare it
                        // also in this page, u can pick either section from
                        // current user OR
                        // sections from another users but not both. -
                        // daisy's note 1 for now
                        // till we are ready to add more complexity
                        List sectionObjectList = prepareSectionObject(providerChosenList, userId);
                        state.setAttribute(STATE_CM_AUTHORIZER_SECTIONS, sectionObjectList);
                        state.removeAttribute(STATE_ADD_CLASS_PROVIDER_CHOSEN);
                        // set special instruction & we will keep
                        // STATE_CM_AUTHORIZER_LIST
                        String additional = StringUtils.trimToEmpty(params.getString("additional"));
                        state.setAttribute(FORM_ADDITIONAL, additional);
                    }
                }
                collectNewSiteInfo(state, params, providerChosenList);

                String find_course = params.getString("find_course");
                if (state.getAttribute(STATE_TEMPLATE_SITE) != null
                        && (find_course == null || !"true".equals(find_course))) {
                    // creating based on template
                    doFinish(data);
                }
            }
        }
        break;
    case 38:
        break;
    case 39:
        break;
    case 42:
        /*
         * actionForTemplate chef_site-type-confirm.vm
         * 
         */
        break;
    case 43:
        /*
         * actionForTemplate chef_site-editClass.vm
         * 
         */
        if (forward) {
            if (params.getStrings("providerClassDeletes") == null
                    && params.getStrings("manualClassDeletes") == null
                    && params.getStrings("cmRequestedClassDeletes") == null && !"back".equals(direction)) {
                addAlert(state, rb.getString("java.classes"));
            }

            if (params.getStrings("providerClassDeletes") != null) {
                // build the deletions list
                List providerCourseList = (List) state.getAttribute(SITE_PROVIDER_COURSE_LIST);
                List providerCourseDeleteList = new ArrayList(
                        Arrays.asList(params.getStrings("providerClassDeletes")));
                for (ListIterator i = providerCourseDeleteList.listIterator(); i.hasNext();) {
                    providerCourseList.remove((String) i.next());
                }

                //Track provider deletes, seems like the only place to do it. If a confirmation is ever added somewhere, don't do this.
                trackRosterChanges(org.sakaiproject.site.api.SiteService.EVENT_SITE_ROSTER_REMOVE,
                        providerCourseDeleteList);
                state.setAttribute(SITE_PROVIDER_COURSE_LIST, providerCourseList);
            }
            if (params.getStrings("manualClassDeletes") != null) {
                // build the deletions list
                List manualCourseList = (List) state.getAttribute(SITE_MANUAL_COURSE_LIST);
                List manualCourseDeleteList = new ArrayList(
                        Arrays.asList(params.getStrings("manualClassDeletes")));
                for (ListIterator i = manualCourseDeleteList.listIterator(); i.hasNext();) {
                    manualCourseList.remove((String) i.next());
                }
                state.setAttribute(SITE_MANUAL_COURSE_LIST, manualCourseList);
            }

            if (params.getStrings("cmRequestedClassDeletes") != null) {
                // build the deletions list
                List<SectionObject> cmRequestedCourseList = (List) state
                        .getAttribute(STATE_CM_REQUESTED_SECTIONS);
                List<String> cmRequestedCourseDeleteList = new ArrayList(
                        Arrays.asList(params.getStrings("cmRequestedClassDeletes")));
                for (ListIterator i = cmRequestedCourseDeleteList.listIterator(); i.hasNext();) {
                    String sectionId = (String) i.next();
                    try {
                        SectionObject so = new SectionObject(cms.getSection(sectionId));
                        SectionObject soFound = null;
                        for (Iterator j = cmRequestedCourseList.iterator(); soFound == null && j.hasNext();) {
                            SectionObject k = (SectionObject) j.next();
                            if (k.eid.equals(sectionId)) {
                                soFound = k;
                            }
                        }
                        if (soFound != null)
                            cmRequestedCourseList.remove(soFound);
                    } catch (IdNotFoundException e) {
                        M_log.warn("actionForTemplate 43 editClass: Cannot find section " + sectionId);
                    }
                }
                state.setAttribute(STATE_CM_REQUESTED_SECTIONS, cmRequestedCourseList);
            }

            updateCourseClasses(state, new Vector(), new Vector());
        }
        break;
    case 44:
        if (forward) {
            AcademicSession a = (AcademicSession) state.getAttribute(STATE_TERM_SELECTED);
            Site site = getStateSite(state);
            ResourcePropertiesEdit pEdit = site.getPropertiesEdit();

            // update the course site property and realm based on the selection
            updateCourseSiteSections(state, site.getId(), pEdit, a);
            try {
                SiteService.save(site);
            } catch (Exception e) {
                M_log.error(this + ".actionForTemplate chef_siteinfo-addCourseConfirm: " + e.getMessage()
                        + site.getId(), e);
            }

            removeAddClassContext(state);
        }

        break;
    case 54:
        if (forward) {

            // store answers to site setup questions
            if (getAnswersToSetupQuestions(params, state)) {
                state.setAttribute(STATE_TEMPLATE_INDEX,
                        state.getAttribute(STATE_SITE_SETUP_QUESTION_NEXT_TEMPLATE));
            }
        }
        break;
    case 61:
        // import users
        if (forward) {
            if (params.getStrings("importSites") == null) {
                addAlert(state, rb.getString("java.toimport") + " ");
            } else {
                importSitesUsers(params, state);
            }
        }
        break;
    }

}