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:org.pentaho.di.job.entries.job.JobEntryJob.java

public Result execute(Result result, int nr) throws KettleException {
    result.setEntryNr(nr);// www  .j a  va 2 s  . com

    LogChannelFileWriter logChannelFileWriter = null;

    LogLevel jobLogLevel = parentJob.getLogLevel();
    if (setLogfile) {
        String realLogFilename = environmentSubstitute(getLogFilename());
        // We need to check here the log filename
        // if we do not have one, we must fail
        if (Const.isEmpty(realLogFilename)) {
            logError(BaseMessages.getString(PKG, "JobJob.Exception.LogFilenameMissing"));
            result.setNrErrors(1);
            result.setResult(false);
            return result;
        }

        // create parent folder?
        if (!createParentFolder(realLogFilename)) {
            result.setNrErrors(1);
            result.setResult(false);
            return result;
        }
        try {
            logChannelFileWriter = new LogChannelFileWriter(this.getLogChannelId(),
                    KettleVFS.getFileObject(realLogFilename), setAppendLogfile);
            logChannelFileWriter.startLogging();
        } catch (KettleException e) {
            logError("Unable to open file appender for file [" + getLogFilename() + "] : " + e.toString());
            logError(Const.getStackTracker(e));
            result.setNrErrors(1);
            result.setResult(false);
            return result;
        }
        jobLogLevel = logFileLevel;
    }

    // Figure out the remote slave server...
    //
    SlaveServer remoteSlaveServer = null;
    if (!Const.isEmpty(remoteSlaveServerName)) {
        String realRemoteSlaveServerName = environmentSubstitute(remoteSlaveServerName);
        remoteSlaveServer = parentJob.getJobMeta().findSlaveServer(realRemoteSlaveServerName);
        if (remoteSlaveServer == null) {
            throw new KettleException(BaseMessages.getString(PKG,
                    "JobJob.Exception.UnableToFindRemoteSlaveServer", realRemoteSlaveServerName));
        }
    }
    try {
        // First load the job, outside of the loop...
        if (parentJob.getJobMeta() != null) {
            // reset the internal variables again.
            // Maybe we should split up the variables even more like in UNIX shells.
            // The internal variables need to be reset to be able use them properly
            // in 2 sequential sub jobs.
            parentJob.getJobMeta().setInternalKettleVariables();
        }

        // Explain what we are loading...
        //
        switch (specificationMethod) {
        case REPOSITORY_BY_NAME:
            if (log.isDetailed()) {
                logDetailed("Loading job from repository : [" + directory + " : "
                        + environmentSubstitute(jobname) + "]");
            }
            break;
        case FILENAME:
            if (log.isDetailed()) {
                logDetailed("Loading job from XML file : [" + environmentSubstitute(filename) + "]");
            }
            break;
        case REPOSITORY_BY_REFERENCE:
            if (log.isDetailed()) {
                logDetailed("Loading job from repository by reference : [" + jobObjectId + "]");
            }
            break;
        default:
            break;
        }

        JobMeta jobMeta = getJobMeta(rep, this);

        // Verify that we loaded something, complain if we did not...
        //
        if (jobMeta == null) {
            throw new KettleException(
                    "Unable to load the job: please specify the name and repository directory OR a filename");
        }

        verifyRecursiveExecution(parentJob, jobMeta);

        int iteration = 0;
        String[] args1 = arguments;
        // no arguments? Check the parent jobs arguments
        if (args1 == null || args1.length == 0) {
            args1 = parentJob.getArguments();
        }

        copyVariablesFrom(parentJob);
        setParentVariableSpace(parentJob);

        //
        // For the moment only do variable translation at the start of a job, not
        // for every input row (if that would be switched on)
        //
        String[] args = null;
        if (args1 != null) {
            args = new String[args1.length];
            for (int idx = 0; idx < args1.length; idx++) {
                args[idx] = environmentSubstitute(args1[idx]);
            }
        }

        RowMetaAndData resultRow = null;
        boolean first = true;
        List<RowMetaAndData> rows = new ArrayList<RowMetaAndData>(result.getRows());

        while ((first && !execPerRow)
                || (execPerRow && rows != null && iteration < rows.size() && result.getNrErrors() == 0)) {
            first = false;

            // Clear the result rows of the result
            // Otherwise we double the amount of rows every iteration in the simple cases.
            //
            if (execPerRow) {
                result.getRows().clear();
            }

            if (rows != null && execPerRow) {
                resultRow = rows.get(iteration);
            } else {
                resultRow = null;
            }

            NamedParams namedParam = new NamedParamsDefault();

            // First (optionally) copy all the parameter values from the parent job
            //
            if (paramsFromPrevious) {
                String[] parentParameters = parentJob.listParameters();
                for (int idx = 0; idx < parentParameters.length; idx++) {
                    String par = parentParameters[idx];
                    String def = parentJob.getParameterDefault(par);
                    String val = parentJob.getParameterValue(par);
                    String des = parentJob.getParameterDescription(par);

                    namedParam.addParameterDefinition(par, def, des);
                    namedParam.setParameterValue(par, val);
                }
            }

            // Now add those parameter values specified by the user in the job entry
            //
            if (parameters != null) {
                for (int idx = 0; idx < parameters.length; idx++) {
                    if (!Const.isEmpty(parameters[idx])) {

                        // If it's not yet present in the parent job, add it...
                        //
                        if (Const.indexOfString(parameters[idx], namedParam.listParameters()) < 0) {
                            // We have a parameter
                            try {
                                namedParam.addParameterDefinition(parameters[idx], "", "Job entry runtime");
                            } catch (DuplicateParamException e) {
                                // Should never happen
                                //
                                logError("Duplicate parameter definition for " + parameters[idx]);
                            }
                        }

                        if (Const.isEmpty(Const.trim(parameterFieldNames[idx]))) {
                            namedParam.setParameterValue(parameters[idx],
                                    Const.NVL(environmentSubstitute(parameterValues[idx]), ""));
                        } else {
                            // something filled in, in the field column...
                            //
                            String value = "";
                            if (resultRow != null) {
                                value = resultRow.getString(parameterFieldNames[idx], "");
                            }
                            namedParam.setParameterValue(parameters[idx], value);
                        }
                    }
                }
            }

            Result oneResult = new Result();

            List<RowMetaAndData> sourceRows = null;

            if (execPerRow) {
                // Execute for each input row

                if (argFromPrevious) {
                    // Copy the input row to the (command line) arguments

                    args = null;
                    if (resultRow != null) {
                        args = new String[resultRow.size()];
                        for (int i = 0; i < resultRow.size(); i++) {
                            args[i] = resultRow.getString(i, null);
                        }
                    }
                } else {
                    // Just pass a single row
                    List<RowMetaAndData> newList = new ArrayList<RowMetaAndData>();
                    newList.add(resultRow);
                    sourceRows = newList;
                }

                if (paramsFromPrevious) { // Copy the input the parameters

                    if (parameters != null) {
                        for (int idx = 0; idx < parameters.length; idx++) {
                            if (!Const.isEmpty(parameters[idx])) {
                                // We have a parameter
                                if (Const.isEmpty(Const.trim(parameterFieldNames[idx]))) {
                                    namedParam.setParameterValue(parameters[idx],
                                            Const.NVL(environmentSubstitute(parameterValues[idx]), ""));
                                } else {
                                    String fieldValue = "";

                                    if (resultRow != null) {
                                        fieldValue = resultRow.getString(parameterFieldNames[idx], "");
                                    }
                                    // Get the value from the input stream
                                    namedParam.setParameterValue(parameters[idx], Const.NVL(fieldValue, ""));
                                }
                            }
                        }
                    }
                }
            } else {
                if (argFromPrevious) {
                    // Only put the first Row on the arguments
                    args = null;
                    if (resultRow != null) {
                        args = new String[resultRow.size()];
                        for (int i = 0; i < resultRow.size(); i++) {
                            args[i] = resultRow.getString(i, null);
                        }
                    }
                } else {
                    // Keep it as it was...
                    sourceRows = result.getRows();
                }

                if (paramsFromPrevious) { // Copy the input the parameters

                    if (parameters != null) {
                        for (int idx = 0; idx < parameters.length; idx++) {
                            if (!Const.isEmpty(parameters[idx])) {
                                // We have a parameter
                                if (Const.isEmpty(Const.trim(parameterFieldNames[idx]))) {
                                    namedParam.setParameterValue(parameters[idx],
                                            Const.NVL(environmentSubstitute(parameterValues[idx]), ""));
                                } else {
                                    String fieldValue = "";

                                    if (resultRow != null) {
                                        fieldValue = resultRow.getString(parameterFieldNames[idx], "");
                                    }
                                    // Get the value from the input stream
                                    namedParam.setParameterValue(parameters[idx], Const.NVL(fieldValue, ""));
                                }
                            }
                        }
                    }
                }
            }

            if (remoteSlaveServer == null) {
                // Local execution...
                //

                // Create a new job
                //
                job = new Job(rep, jobMeta, this);
                job.setForcingSeparateLogging(forcingSeparateLogging);
                job.setParentJob(parentJob);
                job.setLogLevel(jobLogLevel);
                job.shareVariablesWith(this);
                job.setInternalKettleVariables(this);
                job.copyParametersFrom(jobMeta);
                job.setInteractive(parentJob.isInteractive());
                if (job.isInteractive()) {
                    job.getJobEntryListeners().addAll(parentJob.getJobEntryListeners());
                }

                // Pass the socket repository all around.
                //
                job.setSocketRepository(parentJob.getSocketRepository());

                // Set the parameters calculated above on this instance.
                //
                job.clearParameters();
                String[] parameterNames = job.listParameters();
                for (int idx = 0; idx < parameterNames.length; idx++) {
                    // Grab the parameter value set in the job entry
                    //
                    String thisValue = namedParam.getParameterValue(parameterNames[idx]);
                    if (!Const.isEmpty(thisValue)) {
                        // Set the value as specified by the user in the job entry
                        //
                        job.setParameterValue(parameterNames[idx], thisValue);
                    } else {
                        // See if the parameter had a value set in the parent job...
                        // This value should pass down to the sub-job if that's what we
                        // opted to do.
                        //
                        if (isPassingAllParameters()) {
                            String parentValue = parentJob.getParameterValue(parameterNames[idx]);
                            if (!Const.isEmpty(parentValue)) {
                                job.setParameterValue(parameterNames[idx], parentValue);
                            }
                        }
                    }
                }
                job.activateParameters();

                // Set the source rows we calculated above...
                //
                job.setSourceRows(sourceRows);

                // Don't forget the logging...
                job.beginProcessing();

                // Link the job with the sub-job
                parentJob.getJobTracker().addJobTracker(job.getJobTracker());

                // Link both ways!
                job.getJobTracker().setParentJobTracker(parentJob.getJobTracker());

                if (parentJob.getJobMeta().isBatchIdPassed()) {
                    job.setPassedBatchId(parentJob.getBatchId());
                }

                job.setArguments(args);

                // Inform the parent job we started something here...
                //
                for (DelegationListener delegationListener : parentJob.getDelegationListeners()) {
                    // TODO: copy some settings in the job execution configuration, not strictly needed
                    // but the execution configuration information is useful in case of a job re-start
                    //
                    delegationListener.jobDelegationStarted(job, new JobExecutionConfiguration());
                }

                JobEntryJobRunner runner = new JobEntryJobRunner(job, result, nr, log);
                Thread jobRunnerThread = new Thread(runner);
                // PDI-6518
                // added UUID to thread name, otherwise threads do share names if jobs entries are executed in parallel in a
                // parent job
                // if that happens, contained transformations start closing each other's connections
                jobRunnerThread.setName(Const.NVL(job.getJobMeta().getName(), job.getJobMeta().getFilename())
                        + " UUID: " + UUID.randomUUID().toString());
                jobRunnerThread.start();

                // Keep running until we're done.
                //
                while (!runner.isFinished() && !parentJob.isStopped()) {
                    try {
                        Thread.sleep(0, 1);
                    } catch (InterruptedException e) {
                        // Ignore
                    }
                }

                // if the parent-job was stopped, stop the sub-job too...
                if (parentJob.isStopped()) {
                    job.stopAll();
                    runner.waitUntilFinished(); // Wait until finished!
                }

                oneResult = runner.getResult();

            } else {

                // Make sure we can parameterize the slave server connection
                //
                remoteSlaveServer.shareVariablesWith(this);

                // Remote execution...
                //
                JobExecutionConfiguration jobExecutionConfiguration = new JobExecutionConfiguration();
                jobExecutionConfiguration.setPreviousResult(result.lightClone()); // lightClone() because rows are
                                                                                  // overwritten in next line.
                jobExecutionConfiguration.getPreviousResult().setRows(sourceRows);
                jobExecutionConfiguration.setArgumentStrings(args);
                jobExecutionConfiguration.setVariables(this);
                jobExecutionConfiguration.setRemoteServer(remoteSlaveServer);
                jobExecutionConfiguration.setRepository(rep);
                jobExecutionConfiguration.setLogLevel(jobLogLevel);
                jobExecutionConfiguration.setPassingExport(passingExport);
                jobExecutionConfiguration.setExpandingRemoteJob(expandingRemoteJob);
                for (String param : namedParam.listParameters()) {
                    String defValue = namedParam.getParameterDefault(param);
                    String value = namedParam.getParameterValue(param);
                    jobExecutionConfiguration.getParams().put(param, Const.NVL(value, defValue));
                }

                // Send the XML over to the slave server
                // Also start the job over there...
                //
                String carteObjectId = null;
                try {
                    carteObjectId = Job.sendToSlaveServer(jobMeta, jobExecutionConfiguration, rep, metaStore);
                } catch (KettleException e) {
                    // Perhaps the job exists on the remote server, carte is down, etc.
                    // This is an abort situation, stop the parent job...
                    // We want this in case we are running in parallel. The other job
                    // entries can stop running now.
                    //
                    parentJob.stopAll();

                    // Pass the exception along
                    //
                    throw e;
                }

                // Now start the monitoring...
                //
                SlaveServerJobStatus jobStatus = null;
                while (!parentJob.isStopped() && waitingToFinish) {
                    try {
                        jobStatus = remoteSlaveServer.getJobStatus(jobMeta.getName(), carteObjectId, 0);
                        if (jobStatus.getResult() != null) {
                            // The job is finished, get the result...
                            //
                            oneResult = jobStatus.getResult();
                            break;
                        }
                    } catch (Exception e1) {
                        logError("Unable to contact slave server [" + remoteSlaveServer
                                + "] to verify the status of job [" + jobMeta.getName() + "]", e1);
                        oneResult.setNrErrors(1L);
                        break; // Stop looking too, chances are too low the server will
                               // come back on-line
                    }

                    // sleep for 1 second
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // Ignore
                    }
                }

                if (!waitingToFinish) {
                    // Since the job was posted successfully, the result is true...
                    //
                    oneResult = new Result();
                    oneResult.setResult(true);
                }

                if (parentJob.isStopped()) {
                    try {
                        // See if we have a status and if we need to stop the remote
                        // execution here...
                        //
                        if (jobStatus == null || jobStatus.isRunning()) {
                            // Try a remote abort ...
                            //
                            remoteSlaveServer.stopJob(jobMeta.getName(), carteObjectId);
                        }
                    } catch (Exception e1) {
                        logError("Unable to contact slave server [" + remoteSlaveServer + "] to stop job ["
                                + jobMeta.getName() + "]", e1);
                        oneResult.setNrErrors(1L);
                        break; // Stop looking too, chances are too low the server will
                               // come back on-line
                    }
                }

            }

            if (iteration == 0) {
                result.clear();
            }

            result.add(oneResult);

            // if one of them fails (in the loop), increase the number of errors
            //
            if (oneResult.getResult() == false) {
                result.setNrErrors(result.getNrErrors() + 1);
            }

            iteration++;
        }

    } catch (KettleException ke) {
        logError("Error running job entry 'job' : ", ke);

        result.setResult(false);
        result.setNrErrors(1L);
    }

    if (setLogfile) {
        if (logChannelFileWriter != null) {
            logChannelFileWriter.stopLogging();

            ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, logChannelFileWriter.getLogFile(),
                    parentJob.getJobname(), getName());
            result.getResultFiles().put(resultFile.getFile().toString(), resultFile);

            // See if anything went wrong during file writing...
            //
            if (logChannelFileWriter.getException() != null) {
                logError("Unable to open log file [" + getLogFilename() + "] : ");
                logError(Const.getStackTracker(logChannelFileWriter.getException()));
                result.setNrErrors(1);
                result.setResult(false);
                return result;
            }
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:org.apache.jackrabbit.core.RepositoryImpl.java

/**
 * private constructor//ww w  . j a  v  a 2s  . c o  m
 *
 * @param repConfig
 */
protected RepositoryImpl(RepositoryConfig repConfig) throws RepositoryException {

    log.info("Starting repository...");

    boolean succeeded = false;
    try {
        this.repConfig = repConfig;

        // Acquire a lock on the repository home
        repLock = new RepositoryLock(repConfig.getHomeDir());
        repLock.acquire();

        // setup file systems
        repStore = repConfig.getFileSystem();
        String fsRootPath = "/meta";
        try {
            if (!repStore.exists(fsRootPath) || !repStore.isFolder(fsRootPath)) {
                repStore.createFolder(fsRootPath);
            }
        } catch (FileSystemException fse) {
            String msg = "failed to create folder for repository meta data";
            log.error(msg, fse);
            throw new RepositoryException(msg, fse);
        }
        metaDataStore = new BasedFileSystem(repStore, fsRootPath);

        // init root node uuid
        rootNodeId = loadRootNodeId(metaDataStore);

        // load repository properties
        repProps = loadRepProps();
        nodesCount = Long.parseLong(repProps.getProperty(STATS_NODE_COUNT_PROPERTY, "0"));
        propsCount = Long.parseLong(repProps.getProperty(STATS_PROP_COUNT_PROPERTY, "0"));

        // create registries
        nsReg = createNamespaceRegistry(new BasedFileSystem(repStore, "/namespaces"));
        ntReg = createNodeTypeRegistry(nsReg, new BasedFileSystem(repStore, "/nodetypes"));

        dataStore = repConfig.getDataStore();
        if (dataStore != null) {
            assert InternalValue.USE_DATA_STORE;
        }

        // init workspace configs
        Iterator iter = repConfig.getWorkspaceConfigs().iterator();
        while (iter.hasNext()) {
            WorkspaceConfig config = (WorkspaceConfig) iter.next();
            WorkspaceInfo info = createWorkspaceInfo(config);
            wspInfos.put(config.getName(), info);
        }

        // initialize optional clustering
        // put here before setting up any other external event source that a cluster node
        // will be interested in
        if (repConfig.getClusterConfig() != null) {
            clusterNode = createClusterNode();
            nsReg.setEventChannel(clusterNode);
            ntReg.setEventChannel(clusterNode);

            createWorkspaceEventChannel = clusterNode;
            clusterNode.setListener(this);
        }

        // init version manager
        vMgr = createVersionManager(repConfig.getVersioningConfig(), delegatingDispatcher);
        if (clusterNode != null) {
            vMgr.setEventChannel(clusterNode.createUpdateChannel(null));
        }

        // init virtual node type manager
        virtNTMgr = new VirtualNodeTypeStateManager(getNodeTypeRegistry(), delegatingDispatcher,
                NODETYPES_NODE_ID, SYSTEM_ROOT_NODE_ID);

        // initialize startup workspaces
        initStartupWorkspaces();

        // initialize system search manager
        getSystemSearchManager(repConfig.getDefaultWorkspaceName());

        // after the workspace is initialized we pass a system session to
        // the virtual node type manager

        // todo FIXME the *global* virtual node type manager is using a session that is bound to a single specific workspace...
        virtNTMgr.setSession(getSystemSession(repConfig.getDefaultWorkspaceName()));

        // now start cluster node as last step
        if (clusterNode != null) {
            try {
                clusterNode.start();
            } catch (ClusterException e) {
                String msg = "Unable to start clustered node, forcing shutdown...";
                log.error(msg, e);
                shutdown();
                throw new RepositoryException(msg, e);
            }
        }

        // amount of time in seconds before an idle workspace is automatically
        // shut down
        int maxIdleTime = repConfig.getWorkspaceMaxIdleTime();
        if (maxIdleTime != 0) {
            // start workspace janitor thread
            Thread wspJanitor = new Thread(new WorkspaceJanitor(maxIdleTime * 1000));
            wspJanitor.setName("WorkspaceJanitor");
            wspJanitor.setPriority(Thread.MIN_PRIORITY);
            wspJanitor.setDaemon(true);
            wspJanitor.start();
        }

        succeeded = true;
        log.info("Repository started");
    } catch (RepositoryException e) {
        log.error("failed to start Repository: " + e.getMessage(), e);
        throw e;
    } finally {
        if (!succeeded) {
            // repository startup failed, clean up...
            shutdown();
        }
    }
}

From source file:org.zaproxy.zap.GuiBootstrap.java

/**
 * Initialises the {@code Model}, {@code View} and {@code Control}.
 *
 * @param firstTime {@code true} if it's the first time ZAP is being started, {@code false} otherwise
 *//*from w w  w . j a  v a  2s. c o  m*/
private void init(final boolean firstTime) {
    try {
        initModel();
    } catch (Exception e) {
        if (e instanceof FileNotFoundException) {
            JOptionPane.showMessageDialog(null, Constant.messages.getString("start.db.error"),
                    Constant.messages.getString("start.title.error"), JOptionPane.ERROR_MESSAGE);
        }
        logger.fatal(e.getMessage(), e);
    }

    OptionsParam options = Model.getSingleton().getOptionsParam();
    OptionsParamView viewParam = options.getViewParam();

    FontUtils.setDefaultFont(viewParam.getFontName(), viewParam.getFontSize());

    View.setDisplayOption(viewParam.getDisplayOption());

    setupLocale(options);

    View.getSingleton().showSplashScreen();

    promptForProxyDetailsIfNeeded(options);

    Thread bootstrap = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                initControlAndPostViewInit();

            } catch (Throwable e) {
                if (!Constant.isDevBuild()) {
                    ErrorInfo errorInfo = new ErrorInfo(
                            Constant.messages.getString("start.gui.dialog.fatal.error.title"),
                            Constant.messages.getString("start.gui.dialog.fatal.error.message"), null, null, e,
                            null, null);
                    JXErrorPane errorPane = new JXErrorPane();
                    errorPane.setErrorInfo(errorInfo);
                    JXErrorPane.showDialog(View.getSingleton().getSplashScreen(), errorPane);
                }
                View.getSingleton().hideSplashScreen();

                logger.fatal("Failed to initialise GUI: ", e);
                return;
            }

            warnAddOnsAndExtensionsNoLongerRunnable();

            if (firstTime) {
                // Disabled for now - we have too many popups occuring when you
                // first start up
                // be nice to have a clean start up wizard...
                // ExtensionHelp.showHelp();

            } else {
                // Dont auto check for updates the first time, no chance of any
                // proxy having been set
                final ExtensionAutoUpdate eau = (ExtensionAutoUpdate) Control.getSingleton()
                        .getExtensionLoader().getExtension("ExtensionAutoUpdate");
                if (eau != null) {
                    eau.alertIfNewVersions();
                }
            }

        }
    });
    bootstrap.setName("ZAP-BootstrapGUI");
    bootstrap.setDaemon(false);
    bootstrap.start();
}

From source file:de.dmarcini.submatix.pclogger.gui.MainCommGUI.java

/**
 * Starte einen virtuellen Portfinder Project: SubmatixBTForPC Package: de.dmarcini.submatix.pclogger.gui
 * /*  w ww  . j a  v a 2  s .  c o m*/
 * @author Dirk Marciniak (dirk_marciniak@arcor.de) Stand: 21.08.2013
 * @param _model
 */
private void startVirtualPortFinder(DefaultComboBoxModel<String> _model) {
    VirtualSerialPortsFinder vPortFinder = new VirtualSerialPortsFinder(this, _model);
    Thread th = new Thread(vPortFinder);
    th.setName("virtual_port_finder");
    th.start();
}

From source file:com.mirth.connect.donkey.server.channel.Channel.java

/**
 * Start the channel and all of the channel's connectors.
 *///from   ww  w  .j  a  va 2  s.  co m
public synchronized void start(Set<Integer> connectorsToStart) throws StartException {
    if (currentState == DeployedState.DEPLOYING || currentState == DeployedState.STOPPED) {
        List<Integer> startedMetaDataIds = new ArrayList<Integer>();

        try {
            ThreadUtils.checkInterruptedStatus();

            updateCurrentState(DeployedState.STARTING);

            /*
             * We can't guarantee the state of the process lock when the channel was stopped or
             * halted, so we just reset it.
             */
            processLock.reset();
            removeContentLock = new ReentrantLock(true);
            dispatchThreads.clear();
            shuttingDown = false;
            stopSourceQueue = false;

            // Remove any items in the queue's buffer because they may be outdated and refresh the queue size.
            sourceQueue.invalidate(true, true);

            channelExecutor = Executors.newCachedThreadPool();

            // start the destination connectors but not the destination queues
            for (DestinationChainProvider chainProvider : destinationChainProviders) {
                for (Integer metaDataId : chainProvider.getMetaDataIds()) {
                    DestinationConnector destinationConnector = chainProvider.getDestinationConnectors()
                            .get(metaDataId);

                    if (destinationConnector.getCurrentState() == DeployedState.STOPPED
                            && (connectorsToStart == null || connectorsToStart.contains(metaDataId))) {
                        startedMetaDataIds.add(metaDataId);
                        destinationConnector.start();
                    }
                }
            }

            ThreadUtils.checkInterruptedStatus();
            try {
                processUnfinishedMessages();
            } catch (InterruptedException e) {
                logger.error("Startup recovery interrupted for channel " + name + " (" + channelId + ")", e);
                throw e;
            } catch (Exception e) {
                Throwable cause;
                if (e instanceof ExecutionException) {
                    cause = e.getCause();
                } else {
                    cause = e;
                }

                logger.error("Startup recovery failed for channel " + name + " (" + channelId + "): "
                        + cause.getMessage(), cause);
            }

            ThreadUtils.checkInterruptedStatus();

            // start the destination queues
            for (Integer metaDataId : startedMetaDataIds) {
                getDestinationConnector(metaDataId).startQueue();
            }

            // Remove any items in the queue's buffer because they may be outdated and refresh the queue size.
            sourceQueue.invalidate(true, true);

            // start up the worker thread that will process queued messages
            if (!sourceConnector.isRespondAfterProcessing()) {
                int processingThreads = ((SourceConnectorPropertiesInterface) sourceConnector
                        .getConnectorProperties()).getSourceConnectorProperties().getProcessingThreads();
                queueThreads.clear();
                for (int i = 1; i <= processingThreads; i++) {
                    Thread queueThread = new Thread(Channel.this);
                    queueThread.setName("Source Queue Thread " + i + " on " + name + " (" + channelId + ")");
                    queueThread.start();
                    queueThreads.put(queueThread.getId(), queueThread);
                }
            }

            if (connectorsToStart == null || connectorsToStart.contains(0)) {
                ThreadUtils.checkInterruptedStatus();
                // start up the source connector
                if (sourceConnector.getCurrentState() == DeployedState.STOPPED) {
                    startedMetaDataIds.add(0);
                    sourceConnector.start();
                }

                updateCurrentState(DeployedState.STARTED);
            } else {
                updateCurrentState(DeployedState.PAUSED);
            }
        } catch (Throwable t) {
            if (t instanceof InterruptedException) {
                throw new StartException("Start channel task for " + name + " (" + channelId
                        + ") terminated by halt notification.", t);
            }
            // If an exception occurred, then attempt to rollback by stopping all the connectors that were started
            try {
                updateCurrentState(DeployedState.STOPPING);
                stop(startedMetaDataIds);
                updateCurrentState(DeployedState.STOPPED);
            } catch (Throwable t2) {
                if (t2 instanceof InterruptedException) {
                    throw new StartException("Start channel task for " + name + " (" + channelId
                            + ") terminated by halt notification.", t);
                }

                updateCurrentState(DeployedState.STOPPED);
            }

            throw new StartException("Failed to start channel " + name + " (" + channelId + ").", t);
        }
    } else {
        logger.warn(
                "Failed to start channel " + name + " (" + channelId + "): The channel is already running.");
    }
}

From source file:org.jvnet.hudson.test.JenkinsRule.java

/**
 * Prepares a webapp hosting environment to get {@link javax.servlet.ServletContext} implementation
 * that we need for testing./*  w  w  w  .  j a v a2s. c  o m*/
 */
protected ServletContext createWebServer() throws Exception {
    server = new Server();

    WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath);
    context.setClassLoader(getClass().getClassLoader());
    context.setConfigurations(new Configuration[] { new WebXmlConfiguration(), new NoListenerConfiguration() });
    server.setHandler(context);
    context.setMimeTypes(MIME_TYPES);

    SocketConnector connector = new SocketConnector();
    connector.setHeaderBufferSize(12 * 1024); // use a bigger buffer as Stapler traces can get pretty large on deeply nested URL
    if (System.getProperty("port") != null)
        connector.setPort(Integer.parseInt(System.getProperty("port")));

    server.setThreadPool(new ThreadPoolImpl(new ThreadPoolExecutor(10, 10, 10L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r);
                    t.setName("Jetty Thread Pool");
                    return t;
                }
            })));
    server.addConnector(connector);
    server.addUserRealm(configureUserRealm());
    server.start();

    localPort = connector.getLocalPort();
    LOGGER.log(Level.INFO, "Running on {0}", getURL());

    return context.getServletContext();
}

From source file:com.cloudbees.hudson.plugins.folder.AbstractFolder.java

/**
 * {@inheritDoc}//from  w w  w. java2 s. c  o m
 */
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
    super.onLoad(parent, name);
    init();
    final Thread t = Thread.currentThread();
    String n = t.getName();
    try {
        if (items == null) {
            // When Jenkins is getting reloaded, we want children being loaded to be able to find existing items that they will be overriding.
            // This is necessary for them to correctly keep the running builds, for example.
            // ItemGroupMixIn.loadChildren handles the rest of this logic.
            Item current = parent.getItem(name);
            if (current != null && current.getClass() == getClass()) {
                this.items = ((AbstractFolder) current).items;
            }
        }

        final ChildNameGenerator<AbstractFolder<I>, I> childNameGenerator = childNameGenerator();
        items = loadChildren(this, getJobsDir(), new Function1<String, I>() {
            @Override
            public String call(I item) {
                String fullName = item.getFullName();
                t.setName("Loading job " + fullName);
                float percentage = 100.0f * jobEncountered.incrementAndGet() / Math.max(1, jobTotal.get());
                long now = System.currentTimeMillis();
                if (loadingTick == 0) {
                    loadingTick = now;
                } else if (now - loadingTick > TICK_INTERVAL) {
                    LOGGER.log(Level.INFO, String.format("Loading job %s (%.1f%%)", fullName, percentage));
                    loadingTick = now;
                }
                if (childNameGenerator == null) {
                    return item.getName();
                } else {
                    String name = childNameGenerator.itemNameFromItem(AbstractFolder.this, item);
                    if (name == null) {
                        return childNameGenerator.itemNameFromLegacy(AbstractFolder.this, item.getName());
                    }
                    return name;
                }
            }
        });
    } finally {
        t.setName(n);
    }
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

private boolean initCheckpointServer() {
    this.executor = Executors.newScheduledThreadPool(THREAD_POOL_SIZE, new ThreadFactory() {
        @Override/*from w ww.  j a  va  2  s  .c o m*/
        public Thread newThread(Runnable r) {
            Thread thread = Executors.defaultThreadFactory().newThread(r);
            thread.setName(SQLReconfiguratorDB.class.getSimpleName() + myID);
            return thread;
        }
    });

    try {
        InetAddress addr = null;
        try {
            this.serverSock = new ServerSocket();
            // first try the configured address, else fall back to wildcard
            this.serverSock
                    .bind(new InetSocketAddress(addr = this.consistentNodeConfig.getBindAddress(myID), 0));
        } catch (IOException ioe) {
            log.info(this + " unable to open large checkpoint server socket on " + addr
                    + "; trying wildcard address instead");
            this.serverSock = new ServerSocket(0);
        }
        checkpointServerFuture = executor.submit(new CheckpointServer());
        return true;
    } catch (IOException e) {
        log.severe(this + " unable to open server socket for large checkpoint transfers");
        e.printStackTrace();
    }
    return false;
}

From source file:org.dasein.cloud.cloudsigma.compute.vm.ServerSupport.java

private void change(@Nonnull VirtualMachine vm, @Nonnull String body) throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + ServerSupport.class.getName() + ".change(" + vm + "," + body + ")");
    }// ww  w  . j  a v a  2 s  .com
    try {
        boolean restart = false;
        if (!VmState.STOPPED.equals(vm.getCurrentState())) {
            restart = true;
        }
        VirtualMachine workingVm = vm;

        if (restart) {
            if (logger.isInfoEnabled()) {
                logger.info("Virtual machine " + vm.getProviderVirtualMachineId()
                        + " needs to be stopped prior to change");
            }
            stop(vm.getProviderVirtualMachineId(), false);
            if (logger.isInfoEnabled()) {
                logger.info("Waiting for " + vm.getProviderVirtualMachineId() + " to fully stop");
            }
            workingVm = waitForState(workingVm, CalendarWrapper.MINUTE * 10L, VmState.STOPPED);
            if (workingVm == null) {
                logger.info("Virtual machine " + vm.getProviderVirtualMachineId()
                        + " disappared while waiting for stop");
                throw new CloudException("Virtual machine " + vm.getProviderVirtualMachineId()
                        + " disappeared before attachment could happen");
            }
            if (logger.isInfoEnabled()) {
                logger.info("Done waiting for " + vm.getProviderVirtualMachineId() + ": "
                        + workingVm.getCurrentState());
            }
        }
        CloudSigmaMethod method = new CloudSigmaMethod(provider);

        if (logger.isInfoEnabled()) {
            logger.info("PUTing changes to " + vm.getProviderVirtualMachineId());
        }

        if (method.putString(toServerURL(vm.getProviderVirtualMachineId(), ""), body) == null) {
            throw new CloudException("Unable to locate servers endpoint in CloudSigma");
        }
        if (logger.isInfoEnabled()) {
            logger.info("Change to " + vm.getProviderVirtualMachineId() + " succeeded");
        }
        if (restart) {
            if (logger.isInfoEnabled()) {
                logger.info("Restarting " + vm.getProviderVirtualMachineId());
            }
            final String id = vm.getProviderVirtualMachineId();

            Thread t = new Thread() {
                public void run() {
                    try {
                        try {
                            ServerSupport.this.start(id);
                            try {
                                Thread.sleep(2000L);
                            } catch (InterruptedException ignore) {
                            }
                        } catch (Exception e) {
                            logger.warn("Failed to start VM post-change: " + e.getMessage());
                        }
                    } finally {
                        provider.release();
                    }
                }
            };

            provider.hold();
            t.setName("Restart CloudSigma VM " + id);
            t.setDaemon(true);
            t.start();
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + ServerSupport.class.getName() + ".change()");
        }
    }
}

From source file:org.jvnet.hudson.test.JenkinsRule.java

public Statement apply(final Statement base, final Description description) {
    if (description.getAnnotation(WithoutJenkins.class) != null) {
        // request has been made to not create the instance for this test method
        return base;
    }//  w ww. j  ava2s  .  co  m
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            testDescription = description;
            Thread t = Thread.currentThread();
            String o = t.getName();
            t.setName("Executing " + testDescription.getDisplayName());
            before();
            try {
                System.out.println("=== Starting " + testDescription.getDisplayName());
                // so that test code has all the access to the system
                ACL.impersonate(ACL.SYSTEM);
                try {
                    base.evaluate();
                } catch (Throwable th) {
                    // allow the late attachment of a debugger in case of a failure. Useful
                    // for diagnosing a rare failure
                    try {
                        throw new BreakException();
                    } catch (BreakException e) {
                    }

                    RandomlyFails rf = testDescription.getAnnotation(RandomlyFails.class);
                    if (rf != null) {
                        System.err.println("Note: known to randomly fail: " + rf.value());
                    }

                    throw th;
                }
            } finally {
                after();
                testDescription = null;
                t.setName(o);
            }
        }
    };
}