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.wso2.carbon.appfactory.eventing.EventNotifier.java

/**
 * Notifying the received events to the related Event Dispatcher
 * @param event//from w w  w .  j  av  a2 s .  c o  m
 * @throws AppFactoryEventException
 */
public void notify(final Event event) throws AppFactoryEventException {
    final int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    final String userName = inferUserName(event);
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            Event.EventDispatchType[] eventDispatchTypes = event.getEventDispatchTypes();
            if (eventDispatchTypes == null) {
                log.error("Event dispatch type is not defined in received event.");
                return;
            }

            for (Event.EventDispatchType eventDispatchType : eventDispatchTypes) {
                if (eventDispatchType != Event.EventDispatchType.SOCIAL_ACTIVITY) {
                    EventDispatcher eventDispatcher = dispatcherMap.get(eventDispatchType);
                    if (eventDispatcher != null) {
                        try {
                            eventDispatcher.dispatchEvent(event);
                        } catch (AppFactoryEventException e) {
                            //todo: retry logic
                            log.error("Failed to dispatch event with error:" + e.getMessage(), e);
                        }
                    } else {
                        log.error("Failed to find event dispatcher for dispatch type:" + eventDispatchType);
                    }
                }
            }
            try {
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext
                        .getThreadLocalCarbonContext();
                privilegedCarbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
                for (Event.EventDispatchType eventDispatchType : eventDispatchTypes) {
                    if (eventDispatchType == Event.EventDispatchType.SOCIAL_ACTIVITY) {
                        EventDispatcher eventDispatcher = dispatcherMap.get(eventDispatchType);
                        try {
                            eventDispatcher.dispatchEvent(event);
                        } catch (AppFactoryEventException e) {
                            log.error("Failed to dispatch event with error:" + e.getMessage(), e);
                        }
                    }
                }
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }
        }
    });
    thread.setName(APPFACTORY_EVENT_NOTIFIER_THREAD);
    thread.start();
}

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

/**
 * Protected constructor./*w  ww .  ja va  2  s  .  co m*/
 *
 * @param repConfig the repository configuration.
 * @throws RepositoryException if there is already another repository
 *                             instance running on the given configuration
 *                             or another error occurs.
 */
protected RepositoryImpl(RepositoryConfig repConfig) throws RepositoryException {
    // Acquire a lock on the repository home
    repLock = repConfig.getRepositoryLockMechanism();
    repLock.init(repConfig.getHomeDir());
    repLock.acquire();

    long t0 = System.currentTimeMillis();
    log.info("Starting repository...");

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

        context.setFileSystem(repConfig.getFileSystem());

        // Load root node identifier
        context.setRootNodeId(loadRootNodeId());

        // initialize repository descriptors
        initRepositoryDescriptors();

        // create registries
        context.setNamespaceRegistry(createNamespaceRegistry());
        context.setNodeTypeRegistry(createNodeTypeRegistry());
        context.setPrivilegeRegistry(
                new PrivilegeRegistry(context.getNamespaceRegistry(), context.getFileSystem()));

        // Create item state cache manager
        context.setItemStateCacheFactory(new ManagedMLRUItemStateCacheFactory(cacheMgr));

        DataStore dataStore = repConfig.getDataStore();
        if (dataStore != null) {
            context.setDataStore(dataStore);
        }

        nodeIdFactory = new NodeIdFactory(repConfig.getHomeDir());
        nodeIdFactory.open();
        context.setNodeIdFactory(nodeIdFactory);

        context.setWorkspaceManager(new WorkspaceManager(this));

        // init workspace configs
        for (WorkspaceConfig config : repConfig.getWorkspaceConfigs()) {
            WorkspaceInfo info = createWorkspaceInfo(config);
            wspInfos.put(config.getName(), info);
        }

        // initialize optional clustering before setting up any other
        // external event source that a cluster node will be interested in
        ClusterNode clusterNode = null;
        if (repConfig.getClusterConfig() != null) {
            clusterNode = createClusterNode();
            context.setClusterNode(clusterNode);
            context.getNamespaceRegistry().setEventChannel(clusterNode);
            context.getNodeTypeRegistry().setEventChannel(clusterNode);
            context.getPrivilegeRegistry().setEventChannel(clusterNode);

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

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

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

        // initialize startup workspaces
        initStartupWorkspaces();

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

        // Initialise the security manager;
        initSecurityManager();

        // 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) {
            setDescriptor(JACKRABBIT_CLUSTER_ID, repConfig.getClusterConfig().getId());
            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 (" + (System.currentTimeMillis() - t0) + "ms)");
    } catch (RepositoryException e) {
        log.error("failed to start Repository: " + e.getMessage(), e);
        throw e;
    } finally {
        if (!succeeded) {
            try {
                // repository startup failed, clean up...
                shutdown();
            } catch (Throwable t) {
                // ensure this exception does not overlay the original
                // startup exception and only log it
                log.error("In addition to startup fail, another unexpected problem "
                        + "occurred while shutting down the repository again.", t);
                // Clear the repository lock if it was left in place
                repLock.release();
            }
        }
    }
}

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

@Override
public @Nonnull VirtualMachine clone(final @Nonnull String vmId, @Nonnull String intoDcId, @Nonnull String name,
        @Nonnull String description, boolean powerOn, @Nullable String... firewallIds)
        throws InternalException, CloudException {
    logger.debug("Name: " + name + ", description: " + description);

    VirtualMachine vm = getVirtualMachine(vmId);

    if (vm == null || VmState.TERMINATED.equals(vm.getCurrentState())) {
        throw new CloudException("No such virtual machine to clone: " + vmId);
    }//w w w. j a  v a 2s  .com
    long timeout = System.currentTimeMillis() + (CalendarWrapper.MINUTE * 20L);

    if (!VmState.STOPPED.equals(vm.getCurrentState())) {
        throw new CloudException("Server must be stopped before making clone");
    }
    /*   stop(vmId);
    while (timeout > System.currentTimeMillis()) {
        if (vm == null || VmState.TERMINATED.equals(vm.getCurrentState())) {
            throw new CloudException("Virtual machine terminated during stop for cloning");
        }
        if (VmState.STOPPED.equals(vm.getCurrentState())) {
            break;
        }
        try {
            Thread.sleep(30000L);
        } catch (InterruptedException ignore) {
        }
        try {
            vm = getVirtualMachine(vmId);
        } catch (Exception ignore) {
        }
    }
    }  */
    try {
        //dmayne 20130222: api 2.0 uses empty body for server clone

        CloudSigmaMethod method = new CloudSigmaMethod(provider);
        vm = null; // make sure we are looking at the vm in the response

        //dmayne 20130218: use JSON Parsing
        JSONObject object = new JSONObject(method.postString(toServerURL(vmId, "action/?do=clone"), ""));
        if (object != null) {
            vm = toVirtualMachine((JSONObject) object);
        }
        if (vm == null) {
            throw new CloudException("No virtual machine was provided in the response");
        }
        if (powerOn) {
            vm = waitForState(vm, CalendarWrapper.MINUTE * 15L, VmState.STOPPED, VmState.RUNNING);
            if (vm == null) {
                throw new CloudException("New VM disappeared");
            }
            if (!VmState.RUNNING.equals(vm.getCurrentState())) {
                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-create: " + e.getMessage());
                            }
                        } finally {
                            provider.release();
                        }
                    }
                };

                provider.hold();
                t.setName("Start CloudSigma VM " + id);
                t.setDaemon(true);
                t.start();
            }
        }
        return vm;
    } catch (JSONException e) {
        throw new InternalException(e);
    } finally {
        provider.hold();
        Thread t = new Thread() {
            public void run() {
                try {
                    try {
                        ServerSupport.this.start(vmId);
                        try {
                            Thread.sleep(2000L);
                        } catch (InterruptedException ignore) {
                        }
                    } catch (Throwable ignore) {
                    }
                } finally {
                    provider.release();
                }
            }
        };

        t.setName("CloudSigma Clone Restarted " + vmId);
        t.setDaemon(true);
        t.start();
    }
}

From source file:processing.app.Base.java

public Base(String[] args) throws Exception {
    Thread deleteFilesOnShutdownThread = new Thread(DeleteFilesOnShutdown.INSTANCE);
    deleteFilesOnShutdownThread.setName("DeleteFilesOnShutdown");
    Runtime.getRuntime().addShutdownHook(deleteFilesOnShutdownThread);

    BaseNoGui.initLogger();//w  ww . j av a 2s.  co  m

    initLogger();

    BaseNoGui.initPlatform();

    BaseNoGui.getPlatform().init();

    BaseNoGui.initPortableFolder();

    // Look for a possible "--preferences-file" parameter and load preferences
    BaseNoGui.initParameters(args);

    CommandlineParser parser = new CommandlineParser(args);
    parser.parseArgumentsPhase1();
    commandLine = !parser.isGuiMode();

    BaseNoGui.checkInstallationFolder();

    // If no path is set, get the default sketchbook folder for this platform
    if (BaseNoGui.getSketchbookPath() == null) {
        File defaultFolder = getDefaultSketchbookFolderOrPromptForIt();
        if (BaseNoGui.getPortableFolder() != null)
            PreferencesData.set("sketchbook.path", BaseNoGui.getPortableSketchbookFolder());
        else
            PreferencesData.set("sketchbook.path", defaultFolder.getAbsolutePath());
        if (!defaultFolder.exists()) {
            defaultFolder.mkdirs();
        }
    }

    SplashScreenHelper splash;
    if (parser.isGuiMode()) {
        // Setup all notification widgets
        splash = new SplashScreenHelper(SplashScreen.getSplashScreen());
        BaseNoGui.notifier = new GUIUserNotifier(this);

        // Setup the theme coloring fun
        Theme.init();
        System.setProperty("swing.aatext", PreferencesData.get("editor.antialias", "true"));

        // Set the look and feel before opening the window
        try {
            BaseNoGui.getPlatform().setLookAndFeel();
        } catch (Exception e) {
            // ignore
        }

        // Use native popups so they don't look so crappy on osx
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    } else {
        splash = new SplashScreenHelper(null);
    }

    splash.splashText(tr("Loading configuration..."));

    BaseNoGui.initVersion();

    // Don't put anything above this line that might make GUI,
    // because the platform has to be inited properly first.

    // Create a location for untitled sketches
    untitledFolder = FileUtils.createTempFolder("untitled" + new Random().nextInt(Integer.MAX_VALUE), ".tmp");
    DeleteFilesOnShutdown.add(untitledFolder);

    splash.splashText(tr("Initializing packages..."));
    BaseNoGui.initPackages();

    splash.splashText(tr("Preparing boards..."));

    if (!isCommandLine()) {
        rebuildBoardsMenu();
        rebuildProgrammerMenu();
    } else {
        TargetBoard lastSelectedBoard = BaseNoGui.getTargetBoard();
        if (lastSelectedBoard != null)
            BaseNoGui.selectBoard(lastSelectedBoard);
    }

    // Setup board-dependent variables.
    onBoardOrPortChange();

    pdeKeywords = new PdeKeywords();
    pdeKeywords.reload();

    contributionInstaller = new ContributionInstaller(BaseNoGui.getPlatform(),
            new GPGDetachedSignatureVerifier());
    libraryInstaller = new LibraryInstaller(BaseNoGui.getPlatform());

    parser.parseArgumentsPhase2();

    // Save the preferences. For GUI mode, this happens in the quit
    // handler, but for other modes we should also make sure to save
    // them.
    if (parser.isForceSavePrefs()) {
        PreferencesData.save();
    }

    if (parser.isInstallBoard()) {
        ContributionsIndexer indexer = new ContributionsIndexer(BaseNoGui.getSettingsFolder(),
                BaseNoGui.getHardwareFolder(), BaseNoGui.getPlatform(), new GPGDetachedSignatureVerifier());
        ProgressListener progressListener = new ConsoleProgressListener();

        List<String> downloadedPackageIndexFiles = contributionInstaller.updateIndex(progressListener);
        contributionInstaller.deleteUnknownFiles(downloadedPackageIndexFiles);
        indexer.parseIndex();
        indexer.syncWithFilesystem();

        String[] boardToInstallParts = parser.getBoardToInstall().split(":");

        ContributedPlatform selected = null;
        if (boardToInstallParts.length == 3) {
            selected = indexer.getIndex().findPlatform(boardToInstallParts[0], boardToInstallParts[1],
                    VersionHelper.valueOf(boardToInstallParts[2]).toString());
        } else if (boardToInstallParts.length == 2) {
            List<ContributedPlatform> platformsByName = indexer.getIndex().findPlatforms(boardToInstallParts[0],
                    boardToInstallParts[1]);
            Collections.sort(platformsByName, new DownloadableContributionVersionComparator());
            if (!platformsByName.isEmpty()) {
                selected = platformsByName.get(platformsByName.size() - 1);
            }
        }
        if (selected == null) {
            System.out.println(tr("Selected board is not available"));
            System.exit(1);
        }

        ContributedPlatform installed = indexer.getInstalled(boardToInstallParts[0], boardToInstallParts[1]);

        if (!selected.isBuiltIn()) {
            contributionInstaller.install(selected, progressListener);
        }

        if (installed != null && !installed.isBuiltIn()) {
            contributionInstaller.remove(installed);
        }

        System.exit(0);

    } else if (parser.isInstallLibrary()) {
        BaseNoGui.onBoardOrPortChange();

        ProgressListener progressListener = new ConsoleProgressListener();
        libraryInstaller.updateIndex(progressListener);

        LibrariesIndexer indexer = new LibrariesIndexer(BaseNoGui.getSettingsFolder());
        indexer.parseIndex();
        indexer.setLibrariesFolders(BaseNoGui.getLibrariesFolders());
        indexer.rescanLibraries();

        for (String library : parser.getLibraryToInstall().split(",")) {
            String[] libraryToInstallParts = library.split(":");

            ContributedLibrary selected = null;
            if (libraryToInstallParts.length == 2) {
                selected = indexer.getIndex().find(libraryToInstallParts[0],
                        VersionHelper.valueOf(libraryToInstallParts[1]).toString());
            } else if (libraryToInstallParts.length == 1) {
                List<ContributedLibrary> librariesByName = indexer.getIndex().find(libraryToInstallParts[0]);
                Collections.sort(librariesByName, new DownloadableContributionVersionComparator());
                if (!librariesByName.isEmpty()) {
                    selected = librariesByName.get(librariesByName.size() - 1);
                }
            }
            if (selected == null) {
                System.out.println(tr("Selected library is not available"));
                System.exit(1);
            }

            Optional<ContributedLibrary> mayInstalled = indexer.getIndex()
                    .getInstalled(libraryToInstallParts[0]);
            if (mayInstalled.isPresent() && selected.isIDEBuiltIn()) {
                System.out.println(tr(I18n.format(
                        "Library {0} is available as built-in in the IDE.\nRemoving the other version {1} installed in the sketchbook...",
                        library, mayInstalled.get().getParsedVersion())));
                libraryInstaller.remove(mayInstalled.get(), progressListener);
            } else {
                libraryInstaller.install(selected, mayInstalled, progressListener);
            }
        }

        System.exit(0);

    } else if (parser.isVerifyOrUploadMode()) {
        // Set verbosity for command line build
        PreferencesData.setBoolean("build.verbose", parser.isDoVerboseBuild());
        PreferencesData.setBoolean("upload.verbose", parser.isDoVerboseUpload());

        // Set preserve-temp flag
        PreferencesData.setBoolean("runtime.preserve.temp.files", parser.isPreserveTempFiles());

        // Make sure these verbosity preferences are only for the current session
        PreferencesData.setDoSave(false);

        Sketch sketch = null;
        String outputFile = null;

        try {
            // Build
            splash.splashText(tr("Verifying..."));

            File sketchFile = BaseNoGui.absoluteFile(parser.getFilenames().get(0));
            sketch = new Sketch(sketchFile);

            outputFile = new Compiler(sketch).build(progress -> {
            }, false);
        } catch (Exception e) {
            // Error during build
            e.printStackTrace();
            System.exit(1);
        }

        if (parser.isUploadMode()) {
            // Upload
            splash.splashText(tr("Uploading..."));

            try {
                List<String> warnings = new ArrayList<>();
                UploaderUtils uploader = new UploaderUtils();
                boolean res = uploader.upload(sketch, null, outputFile, parser.isDoUseProgrammer(),
                        parser.isNoUploadPort(), warnings);
                for (String warning : warnings) {
                    System.out.println(tr("Warning") + ": " + warning);
                }
                if (!res) {
                    throw new Exception();
                }
            } catch (Exception e) {
                // Error during upload
                System.out.flush();
                System.err.flush();
                System.err.println(tr("An error occurred while uploading the sketch"));
                System.exit(1);
            }
        }

        // No errors exit gracefully
        System.exit(0);
    } else if (parser.isGuiMode()) {
        splash.splashText(tr("Starting..."));

        for (String path : parser.getFilenames()) {
            // Correctly resolve relative paths
            File file = absoluteFile(path);

            // Fix a problem with systems that use a non-ASCII languages. Paths are
            // being passed in with 8.3 syntax, which makes the sketch loader code
            // unhappy, since the sketch folder naming doesn't match up correctly.
            // http://dev.processing.org/bugs/show_bug.cgi?id=1089
            if (OSUtils.isWindows()) {
                try {
                    file = file.getCanonicalFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (!parser.isForceSavePrefs())
                PreferencesData.setDoSave(true);
            if (handleOpen(file, retrieveSketchLocation(".default"), false) == null) {
                String mess = I18n.format(tr("Failed to open sketch: \"{0}\""), path);
                // Open failure is fatal in upload/verify mode
                if (parser.isVerifyOrUploadMode())
                    showError(null, mess, 2);
                else
                    showWarning(null, mess, null);
            }
        }

        installKeyboardInputMap();

        // Check if there were previously opened sketches to be restored
        restoreSketches();

        // Create a new empty window (will be replaced with any files to be opened)
        if (editors.isEmpty()) {
            handleNew();
        }

        new Thread(new BuiltInCoreIsNewerCheck(this)).start();

        // Check for boards which need an additional core
        new Thread(new NewBoardListener(this)).start();

        // Check for updates
        if (PreferencesData.getBoolean("update.check")) {
            new UpdateCheck(this);

            contributionsSelfCheck = new ContributionsSelfCheck(this,
                    new UpdatableBoardsLibsFakeURLsHandler(this), contributionInstaller, libraryInstaller);
            new Timer(false).schedule(contributionsSelfCheck,
                    Constants.BOARDS_LIBS_UPDATABLE_CHECK_START_PERIOD);
        }

    } else if (parser.isNoOpMode()) {
        // Do nothing (intended for only changing preferences)
        System.exit(0);
    } else if (parser.isGetPrefMode()) {
        BaseNoGui.dumpPrefs(parser);
    } else if (parser.isVersionMode()) {
        System.out.println("Arduino: " + BaseNoGui.VERSION_NAME_LONG);
        System.exit(0);
    }
}

From source file:com.twinsoft.convertigo.eclipse.editors.connector.HtmlConnectorDesignComposite.java

private void showCurrentScreenClass() {
    Thread th = new Thread(new Runnable() {
        public void run() {
            final Document currentWebDom = getWebViewer().getDom();

            if (currentWebDom == null) {
                ConvertigoPlugin.errorMessageBox("Mozilla retrieved Dom is null!");
                return;
            }//  ww w  . ja v  a  2s.c  o  m

            //Engine.logBeans.debug3("(HtmlConnectorDesignComposite) showCurrentScreenClass dom:\n"+ XMLUtils.prettyPrintDOM(currentWebDom), null);
            ScreenClass htmlScreenClass = null;
            synchronized (htmlConnector) {
                Document currentDom = htmlConnector.getCurrentXmlDocument();
                htmlConnector.setCurrentXmlDocument(currentWebDom);
                try {
                    htmlScreenClass = htmlConnector.getCurrentScreenClass();
                } catch (EngineException e) {
                    ConvertigoPlugin.logInfo("Engine exception occurs: " + e.getMessage());
                }
                htmlConnector.setCurrentXmlDocument(currentDom);
            }
            fireObjectSelected(new CompositeEvent(htmlScreenClass));
        }
    });
    th.setName("Document completed Update");
    th.start();
}

From source file:JNLPAppletLauncher.java

public void start() {
    if (DEBUG) {//from  w w w.  j a v  a2  s  .c  om
        System.err.println("Applet.start");
    }

    if (isInitOk) {
        if (firstStart) { // first time
            firstStart = false;

            Thread startupThread = new Thread() {
                public void run() {
                    initAndStartApplet();
                }
            };
            startupThread.setName("AppletLauncher-Startup");
            startupThread.setPriority(Thread.NORM_PRIORITY - 1);
            startupThread.start();
        } else if (appletStarted) {
            checkNoDDrawAndUpdateDeploymentProperties();

            // We have to start again the applet (start can be called multiple times,
            // e.g once per tabbed browsing
            subApplet.start();
        }
    }

}

From source file:org.structr.schema.SchemaService.java

private static void updateIndexConfiguration(final Map<String, Map<String, PropertyKey>> removedClasses) {

    final Thread indexUpdater = new Thread(new Runnable() {

        @Override//  w  ww.j  a  va  2s.  co m
        public void run() {

            // critical section, only one thread should update the index at a time
            if (updating.compareAndSet(false, true)) {

                try {

                    final DatabaseService graphDb = StructrApp.getInstance().getDatabaseService();

                    final Map<String, Map<String, Boolean>> schemaIndexConfig = new HashMap();
                    final Map<String, Map<String, Boolean>> removedClassesConfig = new HashMap();

                    for (final Entry<String, Map<String, PropertyKey>> entry : StructrApp.getConfiguration()
                            .getTypeAndPropertyMapping().entrySet()) {

                        final Class type = getType(entry.getKey());
                        if (type != null) {

                            final String typeName = type.getSimpleName();

                            final Boolean alreadySeenType = schemaIndexConfig.containsKey(typeName);
                            final Map<String, Boolean> typeConfig = (alreadySeenType
                                    ? schemaIndexConfig.get(typeName)
                                    : new HashMap());

                            if (!alreadySeenType) {
                                schemaIndexConfig.put(typeName, typeConfig);
                            }

                            for (final PropertyKey key : entry.getValue().values()) {

                                boolean createIndex = key.isIndexed() || key.isIndexedWhenEmpty();

                                createIndex &= !NonIndexed.class.isAssignableFrom(type);
                                createIndex &= NodeInterface.class.equals(type) || !GraphObject.id.equals(key);

                                typeConfig.put(key.dbName(), createIndex);
                            }
                        }
                    }

                    for (final Entry<String, Map<String, PropertyKey>> entry : removedClasses.entrySet()) {

                        final String typeName = StringUtils.substringAfterLast(entry.getKey(), ".");

                        final Map<String, Boolean> typeConfig = new HashMap();
                        removedClassesConfig.put(typeName, typeConfig);

                        for (final PropertyKey key : entry.getValue().values()) {

                            final boolean wasIndexed = key.isIndexed() || key.isIndexedWhenEmpty();
                            final boolean wasIdIndex = GraphObject.id.equals(key);
                            final boolean dropIndex = wasIndexed && !wasIdIndex;

                            typeConfig.put(key.dbName(), dropIndex);
                        }
                    }

                    graphDb.updateIndexConfiguration(schemaIndexConfig, removedClassesConfig);

                } finally {

                    updating.set(false);
                }
            }
        }
    });

    indexUpdater.setName("indexUpdater");
    indexUpdater.setDaemon(true);
    indexUpdater.start();
}

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

protected DispatchResult dispatchRawMessage(RawMessage rawMessage, boolean batch) throws ChannelException {
    // Allow messages to continue processing while the channel is stopping if they are part of an existing batch
    if ((currentState == DeployedState.STOPPING && !batch) || currentState == DeployedState.STOPPED) {
        throw new ChannelException(true);
    }//from  w  w  w .j  a v  a 2  s . com

    Thread currentThread = Thread.currentThread();
    String originalThreadName = currentThread.getName();
    boolean lockAcquired = false;
    Long persistedMessageId = null;

    try {
        synchronized (dispatchThreads) {
            if (!shuttingDown) {
                dispatchThreads.add(currentThread);
            } else {
                throw new ChannelException(true);
            }
        }

        if (StringUtils.contains(originalThreadName, channelId)) {
            currentThread.setName("Channel Dispatch Thread < " + originalThreadName);
        } else {
            currentThread.setName(
                    "Channel Dispatch Thread on " + name + " (" + channelId + ") < " + originalThreadName);
        }

        DonkeyDao dao = null;
        Message processedMessage = null;
        Response response = null;
        String responseErrorMessage = null;
        DispatchResult dispatchResult = null;

        try {
            obtainProcessLock();
            lockAcquired = true;

            /*
             * TRANSACTION: Create Raw Message - create a source connector message from the raw
             * message and set the status as RECEIVED - store attachments
             */
            dao = daoFactory.getDao();
            ConnectorMessage sourceMessage = createAndStoreSourceMessage(dao, rawMessage);
            ThreadUtils.checkInterruptedStatus();

            if (sourceConnector.isRespondAfterProcessing()) {
                dao.commit(storageSettings.isRawDurable());
                persistedMessageId = sourceMessage.getMessageId();
                dao.close();

                markDeletedQueuedMessages(rawMessage, persistedMessageId);

                processedMessage = process(sourceMessage, false);
            } else {
                // Block other threads from adding to the source queue until both the current commit and queue addition finishes
                synchronized (sourceQueue) {
                    dao.commit(storageSettings.isRawDurable());
                    persistedMessageId = sourceMessage.getMessageId();
                    dao.close();
                    queue(sourceMessage);
                }

                markDeletedQueuedMessages(rawMessage, persistedMessageId);
            }

            if (responseSelector.canRespond()) {
                try {
                    response = responseSelector.getResponse(sourceMessage, processedMessage);
                } catch (Exception e) {
                    responseErrorMessage = ExceptionUtils.getStackTrace(e);
                }
            }
        } catch (RuntimeException e) {
            // TODO determine behavior if this occurs.
            throw new ChannelException(true, e);
        } finally {
            if (lockAcquired && (!sourceConnector.isRespondAfterProcessing() || persistedMessageId == null
                    || Thread.currentThread().isInterrupted())) {
                // Release the process lock if an exception was thrown before a message was persisted
                // or if the thread was interrupted because no additional processing will be done.
                releaseProcessLock();
                lockAcquired = false;
            }

            if (dao != null && !dao.isClosed()) {
                dao.close();
            }

            // Create the DispatchResult at the very end because lockAcquired might have changed
            if (persistedMessageId != null) {
                dispatchResult = new DispatchResult(persistedMessageId, processedMessage, response,
                        sourceConnector.isRespondAfterProcessing(), lockAcquired);

                if (StringUtils.isNotBlank(responseErrorMessage)) {
                    dispatchResult.setResponseError(responseErrorMessage);
                }
            }
        }

        return dispatchResult;
    } catch (InterruptedException e) {
        // This exception should only ever be thrown during a halt.
        // It is impossible to know whether or not the message was persisted because the task will continue to run
        // even though we are no longer waiting for it. Furthermore it is possible the message was actually sent.

        // The best we can do is cancel the task and throw a channel exception. 
        // If the message was not queued on the source connector, recovery should take care of it.
        // If the message was queued, the source of the message will be notified that the message was not persisted to be safe.
        // This could lead to a potential duplicate message being received/sent, but it is one of the consequences of using halt.

        throw new ChannelException(true, e);
    } catch (Throwable t) {
        Throwable cause = t.getCause();
        ChannelException channelException = null;

        if (cause instanceof InterruptedException) {
            channelException = new ChannelException(true, cause);
        } else if (cause instanceof ChannelException) {
            logger.error("Runtime error in channel " + name + " (" + channelId + ").", cause);
            channelException = (ChannelException) cause;
        } else {
            logger.error("Error processing message in channel " + name + " (" + channelId + ").", t);
            channelException = new ChannelException(false, t);
        }

        if (persistedMessageId == null) {
            throw channelException;
        }

        return new DispatchResult(persistedMessageId, null, null, false, lockAcquired, channelException);
    } finally {
        synchronized (dispatchThreads) {
            dispatchThreads.remove(currentThread);
        }
        currentThread.setName(originalThreadName);
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.ImageFrame.java

protected void generateThumbnailsInBackground(final List<WorkbenchRowImage> rowImages) {
    Collections.sort(rowImages);//from  w ww  . ja  v a 2s .  c o m

    Thread thumbGenTask = new Thread() {
        @Override
        @SuppressWarnings("synthetic-access")
        public void run() {
            // This is just a weird workaround.
            // For some reason, using the List directly resulted in a ConcurrentModificationException everytime
            // this method was called from addImages().
            // It doesn't look like it should throw an exception at all.
            WorkbenchRowImage[] imgs = new WorkbenchRowImage[rowImages.size()];
            rowImages.toArray(imgs);
            for (WorkbenchRowImage rowImage : imgs) {
                final WorkbenchRowImage ri = rowImage;
                try {
                    final ImageIcon thumb = generateThumbnail(rowImage);

                    // cache it so we don't have to do this again and again
                    rowImage.setThumbnail(thumb);

                    // update the UI
                    Runnable updateTrayUI = new Runnable() {
                        public void run() {
                            log.info("Thumbnail generation complete.  Updating the UI.  " + ri);
                            if (row == ri.getWorkbenchRow()) {
                                tray.getModel().set(ri.getImageOrder(), thumb);
                                tray.repaint();
                            }
                        }
                    };
                    SwingUtilities.invokeLater(updateTrayUI);
                } catch (IOException e) {
                    UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ImageFrame.class, e);
                    log.warn("Failed to generate a thumbnail for " + rowImage.getCardImageFullPath(), e);
                }
            }
        }
    };

    thumbGenTask.setName("GenThumbs");
    thumbGenTask.setDaemon(true);
    thumbGenTask.setPriority(Thread.MIN_PRIORITY);
    thumbGenTask.start();
}

From source file:org.n52.ifgicopter.spf.SPFEngine.java

/**
 * Starts the engine. In a cycle//from   w ww.  j a  v a2  s  .c o m
 */
public void start() {
    this.statusListeners = SPFRegistry.getInstance().getStatusChangeListeners();
    this.outputMessageListeners = SPFRegistry.getInstance().getOutputMessageListeners();

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {

            List<Map<String, Object>> data = null;

            while (SPFEngine.this.running) {
                /*
                 * infinite loop over all IInputPlugin instances
                 */
                for (IInputPlugin iip : SPFEngine.this.inputPlugins.keySet()) {

                    /*
                     * check if we have new data at the plugin
                     */
                    if (iip.hasNewData()) {
                        /*
                         * pull new data of the plugin
                         */
                        data = iip.getNewData();

                        for (Map<String, Object> map : data) {
                            SPFEngine.this.inputPlugins.get(iip).addNewData(map);
                        }
                    } else {
                        /*
                         * was there an error last time?
                         */
                        int stat = iip.getStatus();
                        Integer oldStat = SPFEngine.this.inputPluginStatus.put(iip, Integer.valueOf(stat));
                        if (oldStat != null && oldStat.intValue() != stat) {
                            /*
                             * this is a status change
                             */
                            for (IStatusChangeListener iscl : SPFEngine.this.statusListeners) {
                                iscl.statusChanged(stat, iip);
                            }

                        }

                        /*
                         * if its not running do not get data
                         */
                        if (stat == IModule.STATUS_NOT_RUNNING) {
                            /*
                             * plugin is not running, skip.
                             */
                            continue;
                        }
                    }

                    /*
                     * the thread is taking 100% of a dualcore system
                     * fix: let it sleep for 50 ms. should do the job.
                     */
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        SPFEngine.this.log.warn(e.getMessage(), e);
                    }
                }
            }
        }
    });
    t.setName("SPFEngine-main-thread");
    t.start();
}