Example usage for java.lang Thread setName

List of usage examples for java.lang Thread setName

Introduction

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

Prototype

public final synchronized void setName(String name) 

Source Link

Document

Changes the name of this thread to be equal to the argument name .

Usage

From source file:ECallCenter21.java

/**
 *
 *//*w  w w.  j av  a 2  s  .  co m*/
public void timedDashboardUpdate() {
    Thread timedDashboardUpdateThread = new Thread(allThreadsGroup, new Runnable() {
        @Override
        @SuppressWarnings({ "static-access", "empty-statement" })
        public void run() {
            // Calculate calls per second
            double callsPerSecondPrecise = 0;
            currentTimeDashboardCalendar = Calendar.getInstance();

            if ((campaignStat != null) && (lastTimeDashboardCampaignStat != null)) {
                if ((campaignStat.getCallingTT() > campaignStat.getRingingTT())) {
                    callsPerSecondPrecise = ((((double) campaignStat.getCallingTT()
                            - (double) lastTimeDashboardCampaignStat.getCallingTT())
                            / ((currentTimeDashboardCalendar.getTimeInMillis() / 1000)
                                    - (lastTimeDashboardCalendar.getTimeInMillis() / 1000))));
                } else {
                    callsPerSecondPrecise = ((((double) campaignStat.getRingingTT()
                            - (double) lastTimeDashboardCampaignStat.getRingingTT())
                            / ((currentTimeDashboardCalendar.getTimeInMillis() / 1000)
                                    - (lastTimeDashboardCalendar.getTimeInMillis() / 1000))));
                }
                double callsPerSecondRounded = (double) ((callsPerSecondPrecise * 100.0) / (double) 100.0);
                double callsPerMinutePrecise = (callsPerSecondRounded * 60);
                double callsPerMinuteRounded = (double) ((callsPerMinutePrecise * 100.0) / (double) 100.0);
                double callsPerHourRounded = (double) ((callsPerMinuteRounded * 60.0));
                if (((currentTimeDashboardCalendar.getTimeInMillis() / 1000)
                        - (lastTimeDashboardCalendar.getTimeInMillis() / 1000) > 0)) {
                    campaignTable.setValueAt(callsPerHourRounded + " per Hour", 9, 1);
                }
                try {
                    lastTimeDashboardCampaignStat = (CampaignStat) campaignStat.clone();
                } catch (CloneNotSupportedException ex) {
                    /* Nonsens in this case*/ }
                ;
                lastTimeDashboardCalendar = currentTimeDashboardCalendar.getInstance();
                if (!vergunning.vergunningOrderInProgress()) {
                    movePerformanceMeter((callsPerHourRounded / 100), smoothCheckBox.isSelected());
                }

                // Calculate the estimated number of seconds the campaign will take
                double durationCallsEpochTimePrecise = 0;
                if (((double) callsPerSecondPrecise != 0) && (order != null)) {
                    durationCallsEpochTimePrecise = Math
                            .round(order.getTargetTransactionQuantity() / (double) callsPerSecondPrecise);
                    //                        durationCallsEpochTime = (long)durationCallsEpochTimePrecise;
                    throughputFactor = (int) Math
                            .round(order.getMessageDuration() / (1 / callsPerSecondPrecise));
                    double hourlyTurnoverPrecise = (order.getMessageRate() * callsPerSecondPrecise * hour);
                    double hourlyTurnoverRounded = (double) (Math.round(hourlyTurnoverPrecise * 100.0) / 100.0);
                    turnoverStatsTable.setValueAt(hourlyTurnoverRounded, 0, 2); // Hourly Turnover
                }
            }
        }
    });
    timedDashboardUpdateThread.setName("timedDashboardUpdateThread");
    timedDashboardUpdateThread.setDaemon(runThreadsAsDaemons);
    timedDashboardUpdateThread.start();
}

From source file:ECallCenter21.java

private void muteAudio(final boolean muteParam) {
    Thread muteAudioThread = new Thread(allThreadsGroup, new Runnable() {
        @Override// w w w. java 2 s. c  o  m
        public void run() {
            int muteAudioCounter = 0;
            String[] status = new String[2];
            serviceLoopProgressBar.setEnabled(true);
            if (muteParam) {
                //                    myClickOnSoundTool.play();

                showStatus("Enable Mute Audio SoftPhone...", true,
                        true); /* true = logToApplic, true = logToFile */
                while (muteAudioCounter < outboundSoftPhonesAvailable) // Starts looping through the user-range
                {
                    SoftPhone thisSoftPhoneInstance = (SoftPhone) threadArray[muteAudioCounter]; // Get the reference to the SoftPhone object in the loop
                    status = thisSoftPhoneInstance.userInput(MUTEAUDIOBUTTON, "1", "", ""); // Send a registerButton response to this object's method userInput
                    if (status[0].equals("1")) {
                        showStatus("Mute Audio Error: " + status[1], true, true);
                        /* true = logToApplic, true = logToFile */ }
                    phoneStatsTable.setValueAt(muteAudioCounter + 1, 1, 1);
                    serviceLoopProgressBar.setValue(muteAudioCounter);
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException ex) {
                    }
                    muteAudioCounter++;
                }
                showStatus("Enable Mute Audio SoftPhone Completed", true,
                        true); /* true = logToApplic, true = logToFile */
                muteAudioToggleButton.setForeground(Color.blue);
                phoneStatsTable.setValueAt("-", 1, 1);
            } else {
                //                    myClickOffSoundTool.play();
                muteAudioCounter = 0;
                showStatus("Disable Mute Audio SoftPhone...", true,
                        true); /* true = logToApplic, true = logToFile */
                while (muteAudioCounter < outboundSoftPhonesAvailable) // Starts looping through the user-range
                {
                    SoftPhone thisSoftPhoneInstance = (SoftPhone) threadArray[muteAudioCounter]; // Get the reference to the SoftPhone object in the loop
                    status = thisSoftPhoneInstance.userInput(MUTEAUDIOBUTTON, "0", "", ""); // Send a registerButton response to this object's method userInput
                    if (status[0].equals("1")) {
                        showStatus("Mute Audio Error: " + status[1], true, true);
                        /* true = logToApplic, true = logToFile */ }
                    phoneStatsTable.setValueAt(muteAudioCounter + 1, 1, 1); // ProcessingInstance
                    serviceLoopProgressBar.setValue(muteAudioCounter);
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException ex) {
                    }
                    muteAudioCounter++;
                }
                showStatus("Disable Mute Audio SoftPhone Completed", true,
                        true); /* true = logToApplic, true = logToFile */
                muteAudioToggleButton.setForeground(Color.black);
                phoneStatsTable.setValueAt("-", 1, 1);
            }
            serviceLoopProgressBar.setValue(0);
            serviceLoopProgressBar.setEnabled(false);
            return;
        }
    });
    muteAudioThread.setName("muteAudioThread");
    muteAudioThread.setDaemon(runThreadsAsDaemons);
    muteAudioThread.start();
}

From source file:ECallCenter21.java

/**
 *
 * @param campaignIdParam//  www.j av  a  2 s .c  om
 */
public void runCampaign(int campaignIdParam) {
    callCenterStatus = LOADCAMPAIGN;
    runCampaignToggleButton.removeActionListener(runCampaignToggleButton.getActionListeners()[0]);
    final int campaignId = campaignIdParam;
    Thread outboundCallButtonActionPerformedThread7 = new Thread(allThreadsGroup, new Runnable() {
        @Override
        @SuppressWarnings({ "static-access", "static-access", "static-access", "static-access", "static-access",
                "static-access", "static-access" })
        public void run() {
            String[] status = new String[2];
            //              Prepare the Campaign Run loading the data objects
            campaignStopRequested = false;
            campaign = dbClient.loadCampaignFromOrderId(campaignId);

            order = dbClient.selectCustomerOrder(campaign.getOrderId());
            lastMessageDuration = order.getMessageDuration();

            // Load the Campaign Destinations
            destinationArray = dbClient.selectAllOpenCampaignDestinations(campaignId);

            // Get the saved campaignStat record
            int onAC = campaignStat.getOnAC();
            int idleAC = campaignStat.getIdleAC();
            campaignStat = dbClient.selectCampaignStat(campaignId);
            campaignStat.setOnAC(onAC);
            campaignStat.setIdleAC(idleAC);
            campaignStat.resetActiveCounts();
            try {
                lastTimeDashboardCampaignStat = (CampaignStat) campaignStat.clone();
            } catch (CloneNotSupportedException ex) {
                /* Nonsens in this case*/ } // Make sure there is no difference between this and lastCampaignStat (prevent dashboard going wild on first run)
            if (campaignStat.getConnectingTT() == 0) {
                campaign.setCalendarRegisteredStart(Calendar.getInstance(nlLocale));
                dbClient.updateCampaign(campaign);
            } // First run setting starttime

            soundFileToStream = order.getMessageFilename();
            toegangField.setText(usernameField.getText());
            //                durationCallsEpochTime = 0;
            outboundCallsInProgress = true;
            callCenterIsOutBound = true;
            campaignProgressBar.setEnabled(true);
            runCampaignToggleButton.setEnabled(true);
            stopCampaignButton.setEnabled(true);
            campaignProgressBar.setValue(0);

            callRatioChartData.setValue("Connecting", 0);
            callRatioChartData.setValue("Trying", 0);
            callRatioChartData.setValue("Busy", 0);
            callRatioChartData.setValue("Success", 0);
            graphInnerPanel.setVisible(true);
            chartPanel.setVisible(true);

            turnoverStatsTable.setValueAt(0, 0, 2);
            turnoverStatsTable.setValueAt(0, 1, 2);
            turnoverStatsTable.setValueAt(0, 2, 2);

            // Scheduled Start
            campaignLabel.setText("Campaign " + campaign.getId());
            if (campaign.getCalendarScheduledStart().getTimeInMillis() != 0) {
                campaignTable.setValueAt(String.format("%04d",
                        campaign.getCalendarScheduledStart().get(Calendar.YEAR)) + "-"
                        + String.format("%02d", campaign.getCalendarScheduledStart().get(Calendar.MONTH) + 1)
                        + "-"
                        + String.format("%02d", campaign.getCalendarScheduledStart().get(Calendar.DAY_OF_MONTH))
                        + " "
                        + String.format("%02d", campaign.getCalendarScheduledStart().get(Calendar.HOUR_OF_DAY))
                        + ":" + String.format("%02d", campaign.getCalendarScheduledStart().get(Calendar.MINUTE))
                        + ":"
                        + String.format("%02d", campaign.getCalendarScheduledStart().get(Calendar.SECOND)), 0,
                        1);
            }
            // Scheduled End
            if (campaign.getCalendarScheduledEnd().getTimeInMillis() != 0) {
                campaignTable.setValueAt(String.format("%04d",
                        campaign.getCalendarScheduledEnd().get(Calendar.YEAR)) + "-"
                        + String.format("%02d", campaign.getCalendarScheduledEnd().get(Calendar.MONTH) + 1)
                        + "-"
                        + String.format("%02d", campaign.getCalendarScheduledEnd().get(Calendar.DAY_OF_MONTH))
                        + " "
                        + String.format("%02d", campaign.getCalendarScheduledEnd().get(Calendar.HOUR_OF_DAY))
                        + ":" + String.format("%02d", campaign.getCalendarScheduledEnd().get(Calendar.MINUTE))
                        + ":" + String.format("%02d", campaign.getCalendarScheduledEnd().get(Calendar.SECOND)),
                        1, 1);
            }
            // Expect Start
            if (campaign.getCalendarExpectedStart().getTimeInMillis() != 0) {
                campaignTable.setValueAt(String.format("%04d",
                        campaign.getCalendarExpectedStart().get(Calendar.YEAR)) + "-"
                        + String.format("%02d", campaign.getCalendarExpectedStart().get(Calendar.MONTH) + 1)
                        + "-"
                        + String.format("%02d", campaign.getCalendarExpectedStart().get(Calendar.DAY_OF_MONTH))
                        + " "
                        + String.format("%02d", campaign.getCalendarExpectedStart().get(Calendar.HOUR_OF_DAY))
                        + ":" + String.format("%02d", campaign.getCalendarExpectedStart().get(Calendar.MINUTE))
                        + ":" + String.format("%02d", campaign.getCalendarExpectedStart().get(Calendar.SECOND)),
                        2, 1);
            }
            // Expect End
            if (campaign.getCalendarExpectedEnd().getTimeInMillis() != 0) {
                campaignTable.setValueAt(
                        String.format("%04d", campaign.getCalendarExpectedEnd().get(Calendar.YEAR)) + "-"
                                + String.format("%02d",
                                        campaign.getCalendarExpectedEnd().get(Calendar.MONTH) + 1)
                                + "-"
                                + String.format(
                                        "%02d", campaign.getCalendarExpectedEnd().get(Calendar.DAY_OF_MONTH))
                                + " "
                                + String.format("%02d",
                                        campaign.getCalendarExpectedEnd().get(Calendar.HOUR_OF_DAY))
                                + ":"
                                + String.format("%02d", campaign.getCalendarExpectedEnd().get(Calendar.MINUTE))
                                + ":"
                                + String.format("%02d", campaign.getCalendarExpectedEnd().get(Calendar.SECOND)),
                        3, 1);
            }
            // Registered Start
            if (campaign.getCalendarRegisteredStart().getTimeInMillis() != 0) {
                campaignTable
                        .setValueAt(
                                String.format("%04d", campaign.getCalendarRegisteredStart().get(Calendar.YEAR))
                                        + "-"
                                        + String.format("%02d",
                                                campaign.getCalendarRegisteredStart().get(Calendar.MONTH) + 1)
                                        + "-"
                                        + String.format("%02d",
                                                campaign.getCalendarRegisteredStart()
                                                        .get(Calendar.DAY_OF_MONTH))
                                        + " "
                                        + String.format("%02d",
                                                campaign.getCalendarRegisteredStart().get(Calendar.HOUR_OF_DAY))
                                        + ":"
                                        + String.format("%02d",
                                                campaign.getCalendarRegisteredStart().get(Calendar.MINUTE))
                                        + ":"
                                        + String.format("%02d",
                                                campaign.getCalendarRegisteredStart().get(Calendar.SECOND)),
                                4, 1);
            }
            // Registered End
            if (campaign.getCalendarRegisteredEnd().getTimeInMillis() != 0) {
                campaignTable.setValueAt(String.format("%04d",
                        campaign.getCalendarRegisteredEnd().get(Calendar.YEAR)) + "-"
                        + String.format("%02d", campaign.getCalendarRegisteredEnd().get(Calendar.MONTH) + 1)
                        + "-"
                        + String.format("%02d", campaign.getCalendarRegisteredEnd().get(Calendar.DAY_OF_MONTH))
                        + " "
                        + String.format("%02d", campaign.getCalendarRegisteredEnd().get(Calendar.HOUR_OF_DAY))
                        + ":" + String.format("%02d", campaign.getCalendarRegisteredEnd().get(Calendar.MINUTE))
                        + ":" + String.format("%02d", campaign.getCalendarRegisteredEnd().get(Calendar.SECOND)),
                        5, 1);
            }
            // The rest
            campaignTable.setValueAt("-", 6, 1); // Time Tot
            campaignTable.setValueAt("-", 7, 1); // Time Elap
            campaignTable.setValueAt("-", 8, 1); // Time End
            campaignTable.setValueAt("-", 9, 1); // Throughput Calls

            // Set the static proxy config

            status = new String[2];
            username = configurationCallCenter.getUsername();
            //                toegang         = prefixField.getText() + configurationCallCenter.getToegang() + suffixField.getText(); // User for Asterisk
            toegang = configurationCallCenter.getToegang();
            filename = "file:" + soundFileToStream;

            String text = destinationTextArea.getText();

            // ==============================================================================================================================

            // Sets the Order Object and after that displays the OrderMembers in the orderTable and turnover info
            orderLabel.setText("Order " + order.getOrderId());
            orderTable.setValueAt(order.getRecipientsCategory(), 0, 1);
            //                orderTable.setValueAt(order.getTimeWindowCategory(), 1, 1);
            orderTable.setValueAt(
                    order.getTimeWindow0() + " " + order.getTimeWindow1() + " " + order.getTimeWindow2(), 1, 1);
            orderTable.setValueAt(order.getTargetTransactionQuantity(), 2, 1);
            orderTable.setValueAt(order.getTargetTransactionQuantity(), 2, 1);
            orderTable.setValueAt(order.getMessageDuration() + " Sec", 3, 1);
            orderTable.setValueAt(order.getMessageRatePerSecond() + " / Sec", 4, 1);
            orderTable.setValueAt(order.getMessageRate(), 5, 1);
            orderTable.setValueAt(order.getSubTotal(), 6, 1);
            turnoverStatsTable
                    .setValueAt((float) (order.getTargetTransactionQuantity() * order.getMessageRate()), 2, 2); // Total Turnover

            // Make sure the outboundBurstRateSlider adapts to the message length in relation to the Call / Message Duration when message is longer than 10 seconds
            if (Math.round(order.getMessageDuration() * 100) < (eCallCenterGUI.callSpeedSlider.getMinimum())) // Soundfile results below minimum
            {
                eCallCenterGUI.callSpeedSlider.setMaximum(eCallCenterGUI.callSpeedSlider.getMinimum());
            } else {
                eCallCenterGUI.callSpeedSlider.setMaximum(order.getMessageDuration() * 50);
                eCallCenterGUI.callSpeedSlider
                        .setMajorTickSpacing(Math.round((eCallCenterGUI.callSpeedSlider.getMaximum()
                                - eCallCenterGUI.callSpeedSlider.getMinimum()) / 10));
                eCallCenterGUI.callSpeedSlider.setPaintLabels(true);
            }
            callSpeedInterval = Math.round(eCallCenterGUI.callSpeedSlider.getMaximum() / 2);
            callSpeedSlider.setValue(callSpeedInterval);

            //                campaignProgressBar.setMaximum(order.getTargetTransactionQuantity()-1);
            campaignProgressBar.setMaximum(dbClient.getNumberOfAllOpenCampaignDestinations(campaign.getId()));

            // This is where the Campaign Re-run loop start
            campaignRerunForLoop: for (int campaignReRunCounter = 1; campaignReRunCounter <= campaignReRunLimit; campaignReRunCounter++) {
                campaignReRunStage = campaignReRunCounter;
                destinationArray = dbClient.selectAllOpenCampaignDestinations(campaignId);

                try {
                    configurationSoftPhone = (Configuration) configurationCallCenter.clone();
                } // clone the config
                catch (CloneNotSupportedException ex) {
                    showStatus(ex.getMessage(), true, true);
                }

                configurationSoftPhone.setUsername(username);
                configurationSoftPhone.setToegang(toegang);

                // ==============================================================================================================================

                destinationsCounter = 0;
                runCampaignCounter = 0;

                // Call Queuer
                // This is where the Call Loop start
                campaignRunForLoop: for (Destination destinationElement : destinationArray) {
                    // TimeWindow Protector
                    if (callCenterIsNetManaged) {
                        //                            if (!TimeWindow.getCurrentTimeWindow().equals(order.getTimeWindowCategory()))

                        boolean legalTimeWindow = false;
                        for (int orderTimewindow : order.getTimewindowIndexArray()) {
                            if (timeTool.getCurrentTimeWindowIndex() == orderTimewindow) {
                                legalTimeWindow = true;
                            }
                        }

                        if (!legalTimeWindow) {
                            showStatus(
                                    "Self Destructing: " + Vergunning.PRODUCT + " running outside TimeWindow !",
                                    true, true);
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException ex) {
                            }
                            System.exit(0);
                        }
                    }

                    if (campaignStopRequested) {
                        runCampaignToggleButton.addActionListener(new java.awt.event.ActionListener() {
                            @Override
                            public void actionPerformed(java.awt.event.ActionEvent evt) {
                                runCampaignToggleButtonActionPerformed(evt);
                            }
                        });
                        runCampaignToggleButton.setSelected(false);
                        showStatus("Campaign " + campaign.getId() + " Stopped by user.", true, true);
                        runCampaignToggleButton.setText("");
                        runCampaignToggleButton.setForeground(Color.BLACK);
                        callCenterStatus = STOPPED;

                        campaignProgressBar.setValue(0);
                        campaignProgressBar.setEnabled(false);
                        outboundCallsInProgress = false;
                        phoneStatsTable.setValueAt("-", 1, 1); // ProcessingInstance

                        // Campaign is ready updating open campaignlist
                        String[] openCampaigns = dbClient.getOpenCampaigns();
                        if ((openCampaigns != null) && (openCampaigns.length > 0)) {
                            if (!callCenterIsNetManaged) {
                                campaignComboBox.setModel(new javax.swing.DefaultComboBoxModel(openCampaigns));
                                campaignComboBox.setEnabled(true);
                            }
                        } else {
                            campaignComboBox.setEnabled(false);
                            runCampaignToggleButton.setEnabled(false);
                            stopCampaignButton.setEnabled(false);
                        }
                        return;
                    }

                    destinationElement.resetTimestamps();
                    dbClient.updateDestination(destinationElement); // Makes sure progresstimestamps are reset  on e.g. second campaign round
                    if (runCampaignCounter == outboundSoftPhonesAvailable) {
                        runCampaignCounter = 0;
                    } // This actually makes the loop roundrobin connecting the end with the beginning

                    // Overheat Protector
                    while (
                    //                                (
                    //                                    (order.getTimeWindowCategory().equals(TimeWindow.getDAYTIME_DECRIPTION())) &&
                    //                                    (currentTimeCalendar.get(Calendar.HOUR_OF_DAY)  == TimeWindow.getDAYTIMEENDHOUR()) &&
                    //                                    (currentTimeCalendar.get(Calendar.MINUTE)       == TimeWindow.getDAYTIMEENDMINUTE())
                    //                                )                                                                                           ||
                    //                                (
                    //                                    (order.getTimeWindowCategory().equals(TimeWindow.getEVENING_DECRIPTION())) &&
                    //                                    (currentTimeCalendar.get(Calendar.HOUR_OF_DAY)  == TimeWindow.getEVENINGENDHOUR()) &&
                    //                                    (currentTimeCalendar.get(Calendar.MINUTE)       == TimeWindow.getEVENINGENDMINUTE())
                    //                                )                                                                                           ||

                    ((currentTimeCalendar.get(Calendar.HOUR_OF_DAY) == timeTool.getCurrentTimeWindow()
                            .getEndHour())
                            && (currentTimeCalendar.get(Calendar.MINUTE) == timeTool.getCurrentTimeWindow()
                                    .getEndMinute()))
                            ||

                            (vmUsage >= vmUsagePauseThreashold) || (memFree <= memFreeThreshold)
                            || (heapMemFree <= heapMemFreeThreshold)
                            || (campaignStat.getConnectingAC() >= connectingTallyLimit)
                            || (campaignStat.getCallingAC() >= callingTallyLimit)
                            || (campaignStat.getTalkingAC() >= establishedTallyLimit)
                            || (!runCampaignToggleButton.isSelected()) || (!powerToggleButton.isSelected())) {
                        callCenterStatus = PAUSING;
                        showStatus("Campaign: " + campaign.getId() + " Run: " + campaignReRunCounter + "-"
                                + campaignReRunLimit + " Pausing...", false, false);
                        runCampaignToggleButton.setText("? ?");
                        runCampaignToggleButton.setForeground(Color.ORANGE);
                        if (vmUsage >= vmUsagePauseThreashold) {
                            eCallCenterGUI.vmUsageThresholdLabel.setForeground(Color.RED);
                            eCallCenterGUI.vmUsagePauseValue.setForeground(Color.RED);
                            eCallCenterGUI.vmUsageThresholdSlider.setForeground(Color.RED);
                        } else {
                            eCallCenterGUI.vmUsageThresholdLabel.setForeground(Color.BLACK);
                            eCallCenterGUI.vmUsagePauseValue.setForeground(Color.BLACK);
                            eCallCenterGUI.vmUsageThresholdSlider.setForeground(Color.BLACK);
                        }
                        if (memFree <= memFreeThreshold) {
                            eCallCenterGUI.memFreeThresholdLabel.setForeground(Color.RED);
                            eCallCenterGUI.memFreeThresholdValue.setForeground(Color.RED);
                            eCallCenterGUI.memFreeThresholdSlider.setForeground(Color.RED);
                        } else {
                            eCallCenterGUI.memFreeThresholdLabel.setForeground(Color.BLACK);
                            eCallCenterGUI.memFreeThresholdValue.setForeground(Color.BLACK);
                            eCallCenterGUI.memFreeThresholdSlider.setForeground(Color.BLACK);
                        }
                        if (heapMemFree <= heapMemFreeThreshold) {
                            eCallCenterGUI.heapMemFreeThresholdLabel.setForeground(Color.RED);
                            eCallCenterGUI.heapMemFreeThresholdValue.setForeground(Color.RED);
                            eCallCenterGUI.heapMemFreeThresholdSlider.setForeground(Color.RED);
                        } else {
                            eCallCenterGUI.heapMemFreeThresholdLabel.setForeground(Color.BLACK);
                            eCallCenterGUI.heapMemFreeThresholdValue.setForeground(Color.BLACK);
                            eCallCenterGUI.heapMemFreeThresholdSlider.setForeground(Color.BLACK);
                        }
                        if (campaignStat.getConnectingAC() >= connectingTallyLimit) {
                            eCallCenterGUI.connectingTallyLimitLabel.setForeground(Color.RED);
                            eCallCenterGUI.connectingTallyLimitValue.setForeground(Color.RED);
                            eCallCenterGUI.connectingTallyLimitSlider.setForeground(Color.RED);
                        } else {
                            eCallCenterGUI.connectingTallyLimitLabel.setForeground(Color.BLACK);
                            eCallCenterGUI.connectingTallyLimitValue.setForeground(Color.BLACK);
                            eCallCenterGUI.connectingTallyLimitSlider.setForeground(Color.BLACK);
                        }
                        if (campaignStat.getCallingAC() >= callingTallyLimit) {
                            eCallCenterGUI.callingTallyLimitLabel.setForeground(Color.RED);
                            eCallCenterGUI.callingTallyLimitValue.setForeground(Color.RED);
                            eCallCenterGUI.callingTallyLimitSlider.setForeground(Color.RED);
                        } else {
                            eCallCenterGUI.callingTallyLimitLabel.setForeground(Color.BLACK);
                            eCallCenterGUI.callingTallyLimitValue.setForeground(Color.BLACK);
                            eCallCenterGUI.callingTallyLimitSlider.setForeground(Color.BLACK);
                        }
                        if (campaignStat.getTalkingAC() >= establishedTallyLimit) {
                            eCallCenterGUI.establishedTallyLimitLabel.setForeground(Color.RED);
                            eCallCenterGUI.establishedTallyLimitValue.setForeground(Color.RED);
                            eCallCenterGUI.establishedTallyLimitSlider.setForeground(Color.RED);
                        } else {
                            eCallCenterGUI.establishedTallyLimitLabel.setForeground(Color.BLACK);
                            eCallCenterGUI.establishedTallyLimitValue.setForeground(Color.BLACK);
                            eCallCenterGUI.establishedTallyLimitSlider.setForeground(Color.BLACK);
                        }
                        try {
                            Thread.sleep(outboundBurstDelay);
                        } catch (InterruptedException ex) {
                        }
                    }

                    if (destinationElement.getDestinationCount() > vergunning.getMaxCalls()) {
                        break;
                    }
                    //                        if ((order.getTargetTransactionQuantity() / 100) != 0) {campaignProgressPercentage = Math.round(destinationElement.getDestinationCount() / (order.getTargetTransactionQuantity() / 100));}
                    if ((order.getTargetTransactionQuantity() / 100) != 0) {
                        campaignProgressPercentage = Math
                                .round(destinationsCounter / (order.getTargetTransactionQuantity() / 100));
                    }
                    showStatus(
                            "Campaign: " + Integer.toString(campaign.getId()) + " Run: "
                                    + Integer.toString(campaignReRunCounter) + "-"
                                    + Integer.toString(campaignReRunLimit) + " " + icons.getTalkChar()
                                    + destinationElement.getDestination() + " ("
                                    + Integer.toString(campaignProgressPercentage) + "%) ["
                                    + Integer.toString(destinationElement.getDestinationCount()) + "-"
                                    + Integer.toString(order.getTargetTransactionQuantity()) + "]",
                            false, false);

                    //                    float cumTurnoverPrecise = destinationsCounter * order.getMessageRate();
                    float cumTurnoverPrecise = campaignStat.getCallingTT() * order.getMessageRate();
                    float cumTurnoverRounded = (float) (Math.round(cumTurnoverPrecise * 100.0) / 100.0);
                    turnoverStatsTable.setValueAt(cumTurnoverRounded, 1, 2); // Cummulative Turnover

                    //                        campaignProgressBar.setValue(destinationElement.getDestinationCount());
                    //                        campaignProgressBar.setValue(destinationsCounter);
                    campaignProgressBar.setValue(campaignStat.getCallingTT());
                    runCampaignToggleButton.setText("");
                    runCampaignToggleButton.setForeground(Color.GREEN);
                    callCenterStatus = RUNNING;
                    eCallCenterGUI.vmUsageThresholdLabel.setForeground(Color.BLACK);
                    eCallCenterGUI.vmUsagePauseValue.setForeground(Color.BLACK);
                    eCallCenterGUI.vmUsageThresholdSlider.setForeground(Color.BLACK);
                    eCallCenterGUI.memFreeThresholdLabel.setForeground(Color.BLACK);
                    eCallCenterGUI.memFreeThresholdValue.setForeground(Color.BLACK);
                    eCallCenterGUI.memFreeThresholdSlider.setForeground(Color.BLACK);
                    eCallCenterGUI.heapMemFreeThresholdLabel.setForeground(Color.BLACK);
                    eCallCenterGUI.heapMemFreeThresholdValue.setForeground(Color.BLACK);
                    eCallCenterGUI.heapMemFreeThresholdSlider.setForeground(Color.BLACK);
                    eCallCenterGUI.connectingTallyLimitLabel.setForeground(Color.BLACK);
                    eCallCenterGUI.connectingTallyLimitValue.setForeground(Color.BLACK);
                    eCallCenterGUI.connectingTallyLimitSlider.setForeground(Color.BLACK);
                    eCallCenterGUI.callingTallyLimitLabel.setForeground(Color.BLACK);
                    eCallCenterGUI.callingTallyLimitValue.setForeground(Color.BLACK);
                    eCallCenterGUI.callingTallyLimitSlider.setForeground(Color.BLACK);
                    eCallCenterGUI.establishedTallyLimitLabel.setForeground(Color.BLACK);
                    eCallCenterGUI.establishedTallyLimitValue.setForeground(Color.BLACK);
                    eCallCenterGUI.establishedTallyLimitSlider.setForeground(Color.BLACK);

                    //                        outboundSoftPhoneInstance = (SoftPhone) threadArray[runCampaignCounter];
                    // -- Make PhoneCall
                    if ((destinationElement.getDestination().length() != 0) && (destinationElement
                            .getDestination().length() <= vergunning.getDestinationDigits())) // If destination / phonenumber is larger than 0 bytes
                    {
                        try // If destination / phonenumber is larger than 0 bytes
                        {
                            final Destination callDestination = (Destination) destinationElement.clone();
                            Thread campaignCallThread = new Thread(allThreadsGroup, new Runnable() {

                                @Override
                                public void run() {
                                    SoftPhone thisSoftPhone = (SoftPhone) threadArray[runCampaignCounter]; // work from a copy softphone reference as the call loop carries on
                                    int callMode = 0;
                                    if (scanCheckBox.isSelected()) {
                                        callMode = SCANNING;
                                    } else {
                                        callMode = CALLING;
                                    }
                                    thisSoftPhone.setDestination(callDestination); // Load the phonenumber into the softphone instance before calling

                                    String[] status2 = new String[2];
                                    status2[0] = "0";
                                    status2[1] = "";
                                    status2 = thisSoftPhone.userInput(CALLBUTTON,
                                            callDestination.getDestination(), filename,
                                            Integer.toString(callMode));
                                    if (status2[0].equals("1")) {
                                        // Starting Instant SelfHealing Mechanism (I know it's not a mechanism, but it sounds so much better than automation)
                                        if (thisSoftPhone.getSipState() != thisSoftPhone.SIPSTATE_IDLE) {
                                            showStatus(icons.getIdleChar() + " " + thisSoftPhone.getInstanceId()
                                                    + " Unexpected Sipstatus: "
                                                    + thisSoftPhone.SIPSTATE_DESCRIPTION[thisSoftPhone
                                                            .getSipState()]
                                                    + "...", true, true);
                                            if (thisSoftPhone.getSipState() > thisSoftPhone.SIPSTATE_IDLE) {
                                                String[] status3 = new String[2];
                                                status3[0] = "";
                                                status3[1] = "";
                                                status3 = thisSoftPhone.stopListener();
                                                if (status3[0].equals("0")) {
                                                    showStatus(icons.getIdleChar() + " "
                                                            + thisSoftPhone.getInstanceId()
                                                            + " Listener Stopped Successfully to Sipstate: "
                                                            + thisSoftPhone.SIPSTATE_DESCRIPTION[thisSoftPhone
                                                                    .getSipState()],
                                                            true, true);
                                                } else {
                                                    showStatus(icons.getIdleChar() + " "
                                                            + thisSoftPhone.getInstanceId()
                                                            + " Listener Stopped Unsuccessfully to Sipstate: "
                                                            + thisSoftPhone.SIPSTATE_DESCRIPTION[thisSoftPhone
                                                                    .getSipState()],
                                                            true, true);
                                                }
                                            }
                                            if (thisSoftPhone.getSipState() < thisSoftPhone.SIPSTATE_IDLE) {
                                                String[] status4 = new String[2];
                                                status4[0] = "";
                                                status4[1] = "";
                                                status4 = thisSoftPhone.startListener(
                                                        thisSoftPhone.getConfiguration().getClientPort());
                                                if (status4[0].equals("0")) {
                                                    showStatus(icons.getIdleChar() + " "
                                                            + thisSoftPhone.getInstanceId()
                                                            + " Listener Started Successfully to Sipstate: "
                                                            + thisSoftPhone.SIPSTATE_DESCRIPTION[thisSoftPhone
                                                                    .getSipState()],
                                                            true, true);
                                                    thisSoftPhone.userInput(CALLBUTTON,
                                                            callDestination.getDestination(), filename,
                                                            Integer.toString(callMode));
                                                } else {
                                                    showStatus(icons.getIdleChar() + " "
                                                            + thisSoftPhone.getInstanceId()
                                                            + " Listener Started Unsuccessfully to Sipstate: "
                                                            + thisSoftPhone.SIPSTATE_DESCRIPTION[thisSoftPhone
                                                                    .getSipState()],
                                                            true, true);
                                                }
                                            }
                                        } else // The softphone is okay, so make the call
                                        {
                                            thisSoftPhone.userInput(CALLBUTTON,
                                                    callDestination.getDestination(), filename,
                                                    Integer.toString(callMode));
                                        }
                                    }
                                }
                            });
                            campaignCallThread.setName("campaignCallThread");
                            campaignCallThread.setDaemon(runThreadsAsDaemons);
                            campaignCallThread.start();
                        } catch (CloneNotSupportedException ex) {
                        }
                    }

                    // -- End of Valid Destinstion Call Routine

                    phoneStatsTable.setValueAt(runCampaignCounter + 1, 1, 1); // ProcessingInstance
                    try {
                        Thread.sleep(outboundBurstDelay);
                    } catch (InterruptedException ex) {
                    }
                    destinationsCounter++;
                    runCampaignCounter++;
                } // CampaignRun Loop

                // Wait until all phone become available again or 1 minute has passed
                callCenterStatus = RERUNBREAK;
                int reRunBreakCounter = 60;
                while ((campaignStat.getIdleAC() < outboundSoftPhonesAvailable) && (reRunBreakCounter > 0)
                        && (!campaignStopRequested)) {
                    showStatus(
                            "Campaign: " + campaign.getId() + " ReRun: " + campaignReRunCounter
                                    + " Break, Waiting Max: " + reRunBreakCounter + " seconds...",
                            false, false);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                    }
                    reRunBreakCounter--;
                }
            } // CampaignReRuns Loop

            runCampaignToggleButton.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    runCampaignToggleButtonActionPerformed(evt);
                }
            });
            runCampaignToggleButton.setSelected(false);
            showStatus("Campaign Completed...", true, true);
            runCampaignToggleButton.setText("");
            runCampaignToggleButton.setForeground(Color.BLACK);

            campaignProgressBar.setValue(0);
            campaignProgressBar.setEnabled(false);
            outboundCallsInProgress = false;
            phoneStatsTable.setValueAt("-", 1, 1); // ProcessingInstance

            // Writing Completion of campaign to database
            campaign.setCalendarRegisteredEnd(Calendar.getInstance(nlLocale));
            dbClient.updateCampaign(campaign);
            campaignTable.setValueAt(
                    String.format("%04d", campaign.getCalendarRegisteredEnd().get(Calendar.YEAR)) + "-"
                            + String.format("%02d", campaign.getCalendarRegisteredEnd().get(Calendar.MONTH) + 1)
                            + "-"
                            + String.format(
                                    "%02d", campaign.getCalendarRegisteredEnd().get(Calendar.DAY_OF_MONTH))
                            + " "
                            + String.format("%02d",
                                    campaign.getCalendarRegisteredEnd().get(Calendar.HOUR_OF_DAY))
                            + ":"
                            + String.format("%02d", campaign.getCalendarRegisteredEnd().get(Calendar.MINUTE))
                            + ":"
                            + String.format("%02d", campaign.getCalendarRegisteredEnd().get(Calendar.SECOND)),
                    5, 1);

            // Campaign is ready updating open campaignlist
            String[] openCampaigns = dbClient.getOpenCampaigns();
            if ((openCampaigns != null) && (openCampaigns.length > 0)) {
                campaignComboBox.setModel(new javax.swing.DefaultComboBoxModel(openCampaigns));
                campaignComboBox.setEnabled(true);
            } else {
                campaignComboBox.setEnabled(false);
                runCampaignToggleButton.setEnabled(false);
                stopCampaignButton.setEnabled(false);
            }

            if (autoPowerOff) {
                System.exit(0);
            }
            return;
        }
    });
    outboundCallButtonActionPerformedThread7.setName("outboundCallButtonActionPerformedThread7");
    outboundCallButtonActionPerformedThread7.setDaemon(runThreadsAsDaemons);
    outboundCallButtonActionPerformedThread7.start();
}

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.//ww  w.  j  a  va 2 s  .  co  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;
    }

}

From source file:ECallCenter21.java

/**
 *
 *//*from w  w w.j a  v a 2s .com*/
public void reRegister() {
    //   reRegistering = true;
    Thread reRegisterThread = new Thread(allThreadsGroup, new Runnable() {
        @Override
        @SuppressWarnings({ "static-access", "empty-statement" })
        public void run() {
            String[] status = new String[2];

            // Unregister before ReRegistering
            if ((registerToggleButton.isSelected() && (boundMode.equals("Inbound")))) {
                runCampaignCounter = 0;
                callCenterIsOutBound = false;

                showStatus("Sending Unregister requests to PBX...", true, true);
                registerToggleButton.setSelected(false);
                registerCounter = 0;
                while (registerCounter < outboundSoftPhonesAvailable) // Starts looping through the user-range
                {
                    SoftPhone thisSoftPhoneInstance = (SoftPhone) threadArray[registerCounter]; // Get the reference to the SoftPhone object in the loop
                    if (thisSoftPhoneInstance != null) {
                        status = thisSoftPhoneInstance.userInput(REGISTERBUTTON, "0", "", ""); // 1 ringResponseDelay, 2 BusyPercentage, 3 EndDelay
                        if (status[0].equals("1")) {
                            showStatus("UnRegistration Error: " + status[1], true, true);
                        }
                        try {
                            Thread.sleep(registrationBurstDelay);
                        } catch (InterruptedException ex) {
                        }
                    }
                    phoneStatsTable.setValueAt(registerCounter + 1, 1, 1); // ProcessingInstance
                    serviceLoopProgressBar.setValue(registerCounter);
                    registerCounter++;
                }
                serviceLoopProgressBar.setEnabled(false);
                serviceLoopProgressBar.setValue(0);
                // Do another round to recheck and redo the leftovers
                registerCounter = 0;
                int lastRegisteredActiveCount = 0;
                showStatus("Receiving delayed PBX Unregister responses...", true, true);
                while (lastRegisteredActiveCount != registeredActiveCount) // This codeblock waits until no more PBX registries are detected in time before doing another last (extra) register round
                {
                    lastRegisteredActiveCount = registeredActiveCount;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                    }
                }
                showStatus("Sending re-Unregister requests to PBX completed", true, true);
                registerToggleButton.setForeground(Color.BLACK);
                phoneStatsTable.setValueAt("-", 1, 1); // ProcessingInstance
            }

            registerToggleButton.setEnabled(true);
            registerToggleButton.setSelected(true);
            autoSpeedToggleButton.setSelected(false); // We dont need auto speed and system-load checking in inbound test mode
            moveVMUsageMeter(0, true);
            muteAudioToggleButton.setEnabled(false);
            humanResponseSimulatorToggleButton.setEnabled(false);

            // Extra initial re-registrations
            showStatus("Sending initial re-registration requests to PBX...", true, true);
            serviceLoopProgressBar.setValue(0);
            serviceLoopProgressBar.setEnabled(true);
            registerCounter = 0;
            registerToggleButton.setSelected(true);
            while (registerCounter < outboundSoftPhonesAvailable) // Starts looping through the user-range
            {
                SoftPhone thisSoftPhoneInstance = (SoftPhone) threadArray[registerCounter]; // Get the reference to the SoftPhone object in the loop
                if (thisSoftPhoneInstance != null) {
                    status = thisSoftPhoneInstance.userInput(REGISTERBUTTON, "1", "", ""); // 1 ringResponseDelay, 2 BusyPercentage, 3 EndDelay
                    if (status[0].equals("1")) {
                        showStatus("Re-Registration Error: " + status[1], true, true);
                    }
                    try {
                        Thread.sleep(registrationBurstDelay);
                    } catch (InterruptedException ex) {
                    }
                }
                phoneStatsTable.setValueAt(registerCounter + 1, 1, 1); // ProcessingInstance
                serviceLoopProgressBar.setValue(registerCounter);
                registerCounter++;
            }

            serviceLoopProgressBar.setEnabled(false);
            serviceLoopProgressBar.setValue(0);
            // Wait for delayed registerResponses from PBX
            int lastRegisteredActiveCount = 0;
            showStatus("Receiving initial delayed PBX re-registration responses...", true, true);
            while (lastRegisteredActiveCount != registeredActiveCount) // This codeblock waits until no more PBX registries are detected in time before doing another last (extra) register round
            {
                lastRegisteredActiveCount = registeredActiveCount;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
            }

            // Extra re-registrations
            serviceLoopProgressBar.setValue(0);
            serviceLoopProgressBar.setEnabled(true);
            registerCounter = 0;
            showStatus("Sending extra re-registration requests to PBX...", true, true);
            while ((registeredActiveCount < outboundSoftPhonesAvailable)
                    && (registerCounter < outboundSoftPhonesAvailable)) // Starts looping through the user-range
            {
                SoftPhone thisSoftPhoneInstance = (SoftPhone) threadArray[registerCounter]; // Get the reference to the SoftPhone object in the loop
                if (thisSoftPhoneInstance != null) {
                    if (thisSoftPhoneInstance
                            .getLoginState() == thisSoftPhoneInstance.LOGINSTATE_UNREGISTERED) {
                        status = thisSoftPhoneInstance.userInput(REGISTERBUTTON, "1", "", ""); // 1 ringResponseDelay, 2 BusyPercentage, 3 EndDelay
                        if (status[0].equals("1")) {
                            showStatus("Registration Error: " + status[1], true, true);
                        }
                        try {
                            Thread.sleep(Math.round(registrationBurstDelay / 4));
                        } catch (InterruptedException ex) {
                        }
                    }
                }
                phoneStatsTable.setValueAt(registerCounter + 1, 1, 1); // ProcessingInstance
                serviceLoopProgressBar.setValue(registerCounter);
                registerCounter++;
            }

            serviceLoopProgressBar.setEnabled(false);
            serviceLoopProgressBar.setValue(0);
            lastRegisteredActiveCount = 0;
            showStatus("Receiving extra PBX re-registration responses...", true, true);
            while (lastRegisteredActiveCount != registeredActiveCount) // This codeblock waits until no more PBX registries are detected in time before doing another last (extra) register round
            {
                lastRegisteredActiveCount = registeredActiveCount;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
            }

            // Extra final re-registrations
            serviceLoopProgressBar.setValue(0);
            serviceLoopProgressBar.setEnabled(true);
            registerCounter = 0;
            showStatus("Sending final re-registration requests to PBX...", true, true);
            while ((registeredActiveCount < outboundSoftPhonesAvailable)
                    && (registerCounter < outboundSoftPhonesAvailable)) // Starts looping through the user-range
            {
                SoftPhone thisSoftPhoneInstance = (SoftPhone) threadArray[registerCounter]; // Get the reference to the SoftPhone object in the loop
                if (thisSoftPhoneInstance != null) {
                    if (thisSoftPhoneInstance
                            .getLoginState() == thisSoftPhoneInstance.LOGINSTATE_UNREGISTERED) {
                        status = thisSoftPhoneInstance.userInput(REGISTERBUTTON, "1", "", ""); // 1 ringResponseDelay, 2 BusyPercentage, 3 EndDelay
                        if (status[0].equals("1")) {
                            showStatus("Registration Error: " + status[1], true, true);
                        }
                        try {
                            Thread.sleep(Math.round(registrationBurstDelay / 8));
                        } catch (InterruptedException ex) {
                        }
                    }
                }
                phoneStatsTable.setValueAt(registerCounter + 1, 1, 1); // ProcessingInstance
                serviceLoopProgressBar.setValue(registerCounter);
                registerCounter++;
            }

            serviceLoopProgressBar.setEnabled(false);
            serviceLoopProgressBar.setValue(0);
            lastRegisteredActiveCount = 0;
            showStatus("Receiving final PBX re-registration responses...", true, true);
            while (lastRegisteredActiveCount != registeredActiveCount) // This codeblock waits until no more PBX registries are detected in time before doing another last (extra) register round
            {
                lastRegisteredActiveCount = registeredActiveCount;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
            }

            if (callCenterIsNetManaged) {
                netManagerInboundServerToggleButton.setEnabled(callCenterIsNetManaged);
                netManagerInboundServerToggleButton.setSelected(callCenterIsNetManaged);
                enableInboundNetManagerServer(true);
            }

            serviceLoopProgressBar.setValue(0);
            serviceLoopProgressBar.setEnabled(false);
            registerToggleButton.setForeground(Color.BLUE);
            phoneStatsTable.setValueAt("-", 1, 1); // ProcessingInstance
            //      reRegistering = false;

            muteAudioToggleButton.setEnabled(true);
            humanResponseSimulatorToggleButton.setEnabled(true);
            setAutoSpeed(false);
            return;
        }
    });
    reRegisterThread.setName("reRegisterThread");
    reRegisterThread.setDaemon(runThreadsAsDaemons);
    reRegisterThread.start();
}

From source file:ECallCenter21.java

/**
 *
 * @param remoteDisplayData/*  w ww  . j a  va 2  s .c  o m*/
 */
@Override
synchronized public void phoneDisplay(final DisplayData remoteDisplayData) {
    if (enableDisplayCheckBox.isSelected()) {
        Thread displayThread14 = new Thread(allThreadsGroup, new Runnable() {
            @Override
            @SuppressWarnings({ "static-access" })
            public void run() {
                if (!localDisplayData.getSoftphoneInfoCell().equals(remoteDisplayData.getSoftphoneInfoCell())) {
                    localDisplayData.setSoftphoneInfoCell(remoteDisplayData.getSoftphoneInfoCell());
                    softphoneInfoLabel.setText(localDisplayData.getSoftphoneInfoCell());
                }
                if (!localDisplayData.getProxyInfoCell().equals(remoteDisplayData.getProxyInfoCell())) {
                    localDisplayData.setProxyInfoCell(remoteDisplayData.getProxyInfoCell());
                    proxyInfoLabel.setText(localDisplayData.getProxyInfoCell());
                }
                if (!localDisplayData.getPrimaryStatusCell().equals(remoteDisplayData.getPrimaryStatusCell())) {
                    localDisplayData.setPrimaryStatusCell(remoteDisplayData.getPrimaryStatusCell());
                    primaryStatusLabel.setText(localDisplayData.getPrimaryStatusCell());
                }
                if (!localDisplayData.getPrimaryStatusDetailsCell()
                        .equals(remoteDisplayData.getPrimaryStatusDetailsCell())) {
                    localDisplayData
                            .setPrimaryStatusDetailsCell(remoteDisplayData.getPrimaryStatusDetailsCell());
                    primaryStatusDetailsLabel.setText(localDisplayData.getPrimaryStatusDetailsCell());
                }
                if (!localDisplayData.getSecondaryStatusCell()
                        .equals(remoteDisplayData.getSecondaryStatusCell())) {
                    localDisplayData.setSecondaryStatusCell(remoteDisplayData.getSecondaryStatusCell());
                    secondaryStatusLabel.setText(localDisplayData.getSecondaryStatusCell());
                }
                if (!localDisplayData.getSecondaryStatusDetailsCell()
                        .equals(remoteDisplayData.getSecondaryStatusDetailsCell())) {
                    localDisplayData
                            .setSecondaryStatusDetailsCell(remoteDisplayData.getSecondaryStatusDetailsCell());
                    secondaryStatusDetailsLabel.setText(localDisplayData.getSecondaryStatusDetailsCell());
                }

                if (localDisplayData.getOnFlag() != remoteDisplayData.getOnFlag()) {
                    localDisplayData.setOnFlag(remoteDisplayData.getOnFlag());
                    if (localDisplayData.getOnFlag()) {
                        onPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.ONCOLOR));
                        onLabel.setForeground(localDisplayData.ONCOLOR);
                    } else {
                        onPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        onLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    }
                }
                if (localDisplayData.getIdleFlag() != remoteDisplayData.getIdleFlag()) {
                    localDisplayData.setIdleFlag(remoteDisplayData.getIdleFlag());
                    if (localDisplayData.getIdleFlag()) {
                        idlePanel.setBorder(BorderFactory.createLineBorder(localDisplayData.IDLECOLOR));
                        idleLabel.setForeground(localDisplayData.IDLECOLOR);
                    } else {
                        idlePanel.setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        idleLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    }
                }
                if (localDisplayData.getConnectFlag() != remoteDisplayData.getConnectFlag()) {
                    localDisplayData.setConnectFlag(remoteDisplayData.getConnectFlag());
                    if (localDisplayData.getConnectFlag()) {
                        connectingPanel
                                .setBorder(BorderFactory.createLineBorder(localDisplayData.CALLINGCOLOR));
                        connectingLabel.setForeground(localDisplayData.CONNECTCOLOR);
                    } else {
                        connectingPanel
                                .setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        connectingLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    }
                }
                if (localDisplayData.getCallingFlag() != remoteDisplayData.getCallingFlag()) {
                    localDisplayData.setCallingFlag(remoteDisplayData.getCallingFlag());
                    if (localDisplayData.getCallingFlag()) {
                        callingPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.CALLINGCOLOR));
                        callingLabel.setForeground(localDisplayData.CALLINGCOLOR);
                    } else {
                        callingPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        callingLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    }
                }
                if (localDisplayData.getRingingFlag() != remoteDisplayData.getRingingFlag()) {
                    localDisplayData.setRingingFlag(remoteDisplayData.getRingingFlag());
                    if (localDisplayData.getRingingFlag()) {
                        ringingPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.RINGINGCOLOR));
                        ringingLabel.setForeground(localDisplayData.RINGINGCOLOR);
                    } else {
                        ringingPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        ringingLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    }
                }
                if (localDisplayData.getAcceptFlag() != remoteDisplayData.getAcceptFlag()) {
                    localDisplayData.setAcceptFlag(remoteDisplayData.getAcceptFlag());
                    if (localDisplayData.getAcceptFlag()) {
                        acceptingPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.ACCEPTCOLOR));
                        acceptingLabel.setForeground(localDisplayData.ACCEPTCOLOR);
                    } else {
                        acceptingPanel
                                .setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        acceptingLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    }
                }
                if (localDisplayData.getTalkingFlag() != remoteDisplayData.getTalkingFlag()) {
                    localDisplayData.setTalkingFlag(remoteDisplayData.getTalkingFlag());
                    if (localDisplayData.getTalkingFlag()) {
                        talkingPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.TALKINGCOLOR));
                        talkingLabel.setForeground(localDisplayData.TALKINGCOLOR);
                    } else {
                        talkingPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        talkingLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    }
                }
                if (localDisplayData.getRegisteredFlag() != remoteDisplayData.getRegisteredFlag()) {
                    localDisplayData.setRegisteredFlag(remoteDisplayData.getRegisteredFlag());
                    if (localDisplayData.getRegisteredFlag()) {
                        registeredPanel
                                .setBorder(BorderFactory.createLineBorder(localDisplayData.REGISTEREDCOLOR));
                        registeredLabel.setForeground(localDisplayData.REGISTEREDCOLOR);
                        registerToggleButton.setSelected(true);
                        registerToggleButton.setForeground(Color.BLUE);
                    } else {
                        registeredPanel
                                .setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        registeredLabel.setForeground(localDisplayData.INACTIVECOLOR);
                        registerToggleButton.setSelected(false);
                        registerToggleButton.setForeground(Color.BLACK);
                    }
                }
                if (localDisplayData.getAnswerFlag() != remoteDisplayData.getAnswerFlag()) {
                    localDisplayData.setAnswerFlag(remoteDisplayData.getAnswerFlag());
                    if (localDisplayData.getAnswerFlag()) {
                        answerPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.ANSWERCOLOR));
                        answerLabel.setForeground(localDisplayData.ANSWERCOLOR);
                        cancelPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        cancelLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    } else {
                        answerPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        answerLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    }
                }
                if (localDisplayData.getCancelFlag() != remoteDisplayData.getCancelFlag()) {
                    localDisplayData.setCancelFlag(remoteDisplayData.getCancelFlag());
                    if (localDisplayData.getCancelFlag()) {
                        cancelPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.CANCELCOLOR));
                        cancelLabel.setForeground(localDisplayData.CANCELCOLOR);
                        answerPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        answerLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    } else {
                        cancelPanel.setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        cancelLabel.setForeground(localDisplayData.INACTIVECOLOR);
                    }
                }
                if (localDisplayData.getMuteFlag() != remoteDisplayData.getMuteFlag()) {
                    localDisplayData.setMuteFlag(remoteDisplayData.getMuteFlag());
                    if (localDisplayData.getMuteFlag()) {
                        mutePanel.setBorder(BorderFactory.createLineBorder(localDisplayData.MUTECOLOR));
                        muteLabel.setForeground(localDisplayData.MUTECOLOR);
                        muteAudioToggleButton.setSelected(true);
                        muteAudioToggleButton.setForeground(Color.BLUE);
                    } else {
                        mutePanel.setBorder(BorderFactory.createLineBorder(localDisplayData.INACTIVECOLOR));
                        muteLabel.setForeground(localDisplayData.INACTIVECOLOR);
                        muteAudioToggleButton.setSelected(false);
                        muteAudioToggleButton.setForeground(Color.BLACK);
                    }
                }
            }
        });
        displayThread14.setName("displayThread14");
        displayThread14.setDaemon(runThreadsAsDaemons);
        displayThread14.start();

    }
    return;
}

From source file:ECallCenter21.java

/**
 *
 *///from  w w w .j  a v a 2  s.  c om
public void timedSystemStatsUpdate() {
    Thread timedSystemStatsUpdateThread = new Thread(allThreadsGroup, new Runnable() {
        @Override
        @SuppressWarnings("static-access")
        public void run() {
            String[] status = new String[2];
            // Get CustomerOrder in case of any runtime changes like a changed soundfile
            if ((campaign != null) && (order != null) && (boundMode.equals("Outbound"))
                    && (callCenterStatus == RUNNING)) {
                order = dbClient.selectCustomerOrder(campaign.getOrderId());
                if (lastMessageDuration != order.getMessageDuration()) {
                    soundFileToStream = order.getMessageFilename();
                    filename = "file:" + soundFileToStream;
                    // Make sure the callSpeedSlider adapts to the message length in relation to the Call / Message Duration when message is longer than 10 seconds
                    if (Math.round(
                            order.getMessageDuration() * 100) < (eCallCenterGUI.callSpeedSlider.getMinimum())) // Soundfile results below minimum
                    {
                        eCallCenterGUI.callSpeedSlider.setMaximum(eCallCenterGUI.callSpeedSlider.getMinimum());
                    } else {
                        eCallCenterGUI.callSpeedSlider.setMaximum(order.getMessageDuration() * 50);
                        eCallCenterGUI.callSpeedSlider
                                .setMajorTickSpacing(Math.round((eCallCenterGUI.callSpeedSlider.getMaximum()
                                        - eCallCenterGUI.callSpeedSlider.getMinimum()) / 10));
                        eCallCenterGUI.callSpeedSlider.setPaintLabels(true);
                    }
                    callSpeedInterval = Math.round(eCallCenterGUI.callSpeedSlider.getMaximum() / 2);
                    callSpeedSlider.setValue(callSpeedInterval);
                    lastMessageDuration = order.getMessageDuration();
                }
            }

            memFree = sysMonitor.getPhysMem();
            systemStatsTable.setValueAt(Long.toString(memFree), 2, 1);

            heapMemMax = (Runtime.getRuntime().maxMemory() / (1024 * 1024));
            systemStatsTable.setValueAt(Long.toString(heapMemMax), 3, 1); // KB
            heapMemTot = (Runtime.getRuntime().totalMemory() / (1024 * 1024));
            systemStatsTable.setValueAt(Long.toString(heapMemTot), 4, 1); // KB
            heapMemFree = (Runtime.getRuntime().freeMemory() / (1024 * 1024));
            systemStatsTable.setValueAt(Long.toString(heapMemFree), 5, 1); // KB
            systemStatsTable.setValueAt(Thread.activeCount(), 1, 1);

            // Display time / performance facts
            currentTimeCalendar = Calendar.getInstance(nlLocale);
            difRegStartExpEndCalendar = Calendar.getInstance(nlLocale);
            difRegStartCurTimeCalendar = Calendar.getInstance(nlLocale);
            difCurTimeExpEndCalendar = Calendar.getInstance(nlLocale);

            if ((outboundCallsInProgress) && (campaignStat.getCallingTT() > 0)) {

                // Set & Display the ExpectedEnd timestamp in human readable format
                //                    campaign.setCalendarExpectedEnd(TimeWindow.getEstimatedEndCalendar(Calendar.getInstance(), order, throughputFactor, destination.getDestinationCount())); // The new way
                campaign.setCalendarExpectedEnd(timeTool.getEstimatedEndCalendar(Calendar.getInstance(), order,
                        throughputFactor, destination.getDestinationCount(), order.getTimewindowIndexArray())); // The new way
                dbClient.updateCampaign(campaign);

                difRegStartExpEndCalendar.setTimeInMillis(campaign.getCalendarExpectedEnd().getTimeInMillis()
                        - campaign.getCalendarRegisteredStart().getTimeInMillis());
                difRegStartCurTimeCalendar.setTimeInMillis(currentTimeCalendar.getTimeInMillis()
                        - campaign.getCalendarRegisteredStart().getTimeInMillis());
                difCurTimeExpEndCalendar.setTimeInMillis(campaign.getCalendarExpectedEnd().getTimeInMillis()
                        - currentTimeCalendar.getTimeInMillis());

                // Sets the End Expected Timestamp
                campaignTable.setValueAt(
                        String.format("%04d", campaign.getCalendarExpectedEnd().get(Calendar.YEAR)) + "-"
                                + String.format("%02d",
                                        campaign.getCalendarExpectedEnd().get(Calendar.MONTH) + 1)
                                + "-"
                                + String.format(
                                        "%02d", campaign.getCalendarExpectedEnd().get(Calendar.DAY_OF_MONTH))
                                + " "
                                + String.format("%02d",
                                        campaign.getCalendarExpectedEnd().get(Calendar.HOUR_OF_DAY))
                                + ":"
                                + String.format("%02d", campaign.getCalendarExpectedEnd().get(Calendar.MINUTE))
                                + ":"
                                + String.format("%02d", campaign.getCalendarExpectedEnd().get(Calendar.SECOND)),
                        3, 1);

                // Sets the Past / Elapsed Campaign Time
                campaignTable.setValueAt(
                        String.format("%04d", difRegStartExpEndCalendar.get(Calendar.YEAR) - 1970) + "-"
                                + String.format("%02d", difRegStartExpEndCalendar.get(Calendar.MONTH)) + "-"
                                + String.format("%02d",
                                        difRegStartExpEndCalendar.get(Calendar.DAY_OF_MONTH) - 1)
                                + " "
                                + String.format("%02d", difRegStartExpEndCalendar.get(Calendar.HOUR_OF_DAY) - 1)
                                + ":" + String.format("%02d", difRegStartExpEndCalendar.get(Calendar.MINUTE))
                                + ":" + String.format("%02d", difRegStartExpEndCalendar.get(Calendar.SECOND)),
                        6, 1);

                // Sets the Campaign Ending Countdown Time (ETA)
                campaignTable.setValueAt(String.format("%04d",
                        difRegStartCurTimeCalendar.get(Calendar.YEAR) - 1970) + "-"
                        + String.format("%02d", difRegStartCurTimeCalendar.get(Calendar.MONTH)) + "-"
                        + String.format("%02d", difRegStartCurTimeCalendar.get(Calendar.DAY_OF_MONTH) - 1) + " "
                        + String.format("%02d", difRegStartCurTimeCalendar.get(Calendar.HOUR_OF_DAY) - 1) + ":"
                        + String.format("%02d", difRegStartCurTimeCalendar.get(Calendar.MINUTE)) + ":"
                        + String.format("%02d", difRegStartCurTimeCalendar.get(Calendar.SECOND)), 7, 1);

                campaignTable.setValueAt(
                        String.format("%04d", difCurTimeExpEndCalendar.get(Calendar.YEAR) - 1970) + "-"
                                + String.format("%02d", difCurTimeExpEndCalendar.get(Calendar.MONTH)) + "-"
                                + String.format("%02d", difCurTimeExpEndCalendar.get(Calendar.DAY_OF_MONTH) - 1)
                                + " "
                                + String.format("%02d", difCurTimeExpEndCalendar.get(Calendar.HOUR_OF_DAY) - 1)
                                + ":" + String.format("%02d", difCurTimeExpEndCalendar.get(Calendar.MINUTE))
                                + ":" + String.format("%02d", difCurTimeExpEndCalendar.get(Calendar.SECOND)),
                        8, 1);

                dbClient.updateCampaign(campaign);
            }

            // Display PieGraph & Update CampaignStat
            if ((callCenterIsOutBound) && (callRatioChartData != null) && (callRatioChart != null)
                    && (dbClient != null)
                    && ((callCenterStatus == RUNNING) || (callCenterStatus == RERUNBREAK))) {
                callRatioChartData.setValue("Connecting",
                        (campaignStat.getConnectingTT() - campaignStat.getTryingTT()));
                callRatioChartData.setValue("Trying",
                        (campaignStat.getTryingTT() - campaignStat.getCallingTT()));
                callRatioChartData.setValue("Busy", campaignStat.getRemoteBusyTT());
                callRatioChartData.setValue("Success", campaignStat.getTalkingTT());
                callRatioChart.setTitle("Call Ratio");

                // Store the CampaignStats in database
                dbClient.updateCampaignStat(campaignStat);
            }

            // Only in correct TimeWindow
            //                if ( order != null)
            //                {
            //                    if ((callCenterIsNetManaged) && (callCenterIsOutBound) && (!TimeWindow.getCurrentTimeWindow().equals(order.getTimeWindowCategory())))
            //                    {
            //                        showStatus          (License.PRODUCT + " Shutdown: Running outside " + order.getTimeWindowCategory(), true, true);
            //                        try { Thread.sleep(5000); } catch (InterruptedException ex) { }
            //                        System.exit(0);
            //                    }
            //                }

            if (order != null) {
                boolean legalTimeWindow = false;
                for (int orderTimewindow : order.getTimewindowIndexArray()) {
                    if (orderTimewindow == timeTool.getCurrentTimeWindowIndex()) {
                        legalTimeWindow = true;
                    }
                }

                if (!legalTimeWindow) {
                    showStatus("Self Destructing: " + Vergunning.PRODUCT + " running outside TimeWindow !",
                            true, true);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                    }
                    System.exit(0);
                }
            }

            // Management Server Heartbeat (Manager heartbeat Lost)
            if (callCenterIsNetManaged) {
                //Exit if no management signal is received in time
                if (selfDestructCounter == 0) {
                    showStatus(Vergunning.PRODUCT + " Shutdown: Management Heartbeat Lost", true, true);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                    }
                    System.exit(0);
                }

                if (selfDestructCounter > 0) {
                    selfDestructCounter--;
                }
                if (selfDestructCounter < (selfDestructCounterLimit - 2)) // Warning and Restart
                {
                    if (!callCenterIsOutBound) {
                        if (!isRegistering) {
                            showStatus("Restarting Inbound Management Server", true, true);
                            enableInboundNetManagerServer(false);
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException ex) {
                            }
                            enableInboundNetManagerServer(true);
                        }
                    } else// if (getCallCenterStatus() == RUNNING)
                    {
                        showStatus("Restarting Outbound Management Server", true, true);
                        enableOutboundNetManagerServer(false);
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException ex) {
                        }
                        enableOutboundNetManagerServer(true);
                    }
                } else {
                    if (!callCenterIsOutBound) {
                        netManagerInboundServerToggleButton.setForeground(Color.BLACK);
                    } else {
                        netManagerOutboundServerToggleButton.setForeground(Color.BLACK);
                    }
                }
            }
        } // Run
    }); // Thread
    timedSystemStatsUpdateThread.setName("timedSystemStatsUpdateThread");
    timedSystemStatsUpdateThread.setDaemon(runThreadsAsDaemons);
    timedSystemStatsUpdateThread.start();
}