Example usage for java.lang InterruptedException InterruptedException

List of usage examples for java.lang InterruptedException InterruptedException

Introduction

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

Prototype

public InterruptedException() 

Source Link

Document

Constructs an InterruptedException with no detail message.

Usage

From source file:org.hyperic.lather.server.LatherServlet.java

private void doServiceCall(HttpServletRequest req, HttpServletResponse resp, String methName, LatherValue args,
        LatherXCoder xCoder, LatherContext ctx) throws IOException {

    final LatherDispatcher latherDispatcher = Bootstrap.getBean(LatherDispatcher.class);
    final ServiceCaller caller = new ServiceCaller(resp, xCoder, ctx, methName, args, latherDispatcher);
    final Thread currentThread = Thread.currentThread();
    final String threadName = currentThread.getName();

    try {//from ww  w. j  a  va  2s. c  o m
        currentThread.setName(methName + "-" + ids.getAndIncrement());
        LatherThreadMonitor.get().register(caller);
        caller.run();
        if (currentThread.isInterrupted()) {
            throw new InterruptedException();
        }
    } catch (InterruptedException exc) {
        log.warn("Interrupted while trying to execute lather method=" + methName + " from ip="
                + ctx.getCallerIP());
    } finally {
        caller.markFinished();
        currentThread.setName(threadName);
    }
}

From source file:uk.ac.kcl.texthunter.core.MLModelMaker.java

public FeatureMap executeXVal() {
    setBusy(true);//from  w  w  w . j  a v a  2s  .  com
    //before threads are started set countdown to one for cleanup routine
    cdl = new CountDownLatch(1);
    //load docs
    ArrayList<Corpus> corpusSetup;
    try {
        if (Thread.currentThread().isInterrupted()) {
            throw new InterruptedException();
        }

        try {
            File file = new File(resultsFile);
            File xvalResultsFile = new File(
                    file.getAbsoluteFile() + File.separator + "crossValidationResults.tsv");
            if (resumeXValidation) {
                ArrayList<Parameter> prevResults = parseCmdLineParamFile(xvalResultsFile);
                this.folds = prevResults.get(0).getFolds();
                if (prevResults.get(0).getType().equals("clean")) {
                    paramsList = Parameter.generateParamList(false, folds);
                } else {
                    paramsList = Parameter.generateParamList(true, folds);
                }
                for (Parameter toDoParam : paramsList) {
                    for (Parameter savedParam : prevResults) {
                        if (toDoParam.getID() == savedParam.getID()) {
                            toDoParam.setF1(savedParam.getF1());
                            toDoParam.setPrecision(savedParam.getPrecision());
                            toDoParam.setRecall(savedParam.getRecall());
                        }
                    }
                }
            } else {
                paramsList = Parameter.generateParamList(roughValidation, folds);
            }

            if (Thread.currentThread().isInterrupted()) {
                throw new InterruptedException();
            }
            if (folds > trainingDocs.size()) {
                System.out.println("Insufficient documents available (" + trainingDocs.size() + ") for " + folds
                        + " folds.");
            } else {
                File xvalCorpusDir = new File(resultsFile + File.separator + "xvalCorpus");
                File finCorpusDir = new File(resultsFile + File.separator + "outerCorpus");

                File tempAppFolder = new File(resultsFile + File.separator + "temp");
                if (!tempAppFolder.exists()) {
                    tempAppFolder.mkdir();
                }
                if (!resumeXValidation) {
                    for (int i = 0; i <= 5; i++) {
                        try {
                            Thread.sleep(500);
                            FileUtils.deleteDirectory(xvalCorpusDir);
                            FileUtils.deleteDirectory(finCorpusDir);
                            break;
                        } catch (IOException ex) {
                            System.out.println("Attempting deletion " + i);
                        }
                    }
                    corpusSetup = setUpCorpora(trainingDocs, true);
                    this.fincorpus = corpusSetup.get(0);
                    this.opcorpus = corpusSetup.get(1);
                    // if file doesnt exists, then create it
                    if (file.mkdir()) {
                        System.out.println("Directory Created");
                    } else {
                        System.out.println("Directory is not created");
                    }
                    //save corpora in case of interruption
                    if (finCorpusDir.mkdir()) {
                        System.out.println("outerCorpus dir Created");
                    } else {
                        System.out.println("outerCorpus dir  is not created");
                    }

                    if (Thread.currentThread().isInterrupted()) {
                        throw new InterruptedException();
                    }
                    for (gate.Document doc : fincorpus) {
                        try {
                            gate.corpora.DocumentStaxUtils.writeDocument(doc,
                                    new File(finCorpusDir.getAbsolutePath() + File.separator + doc.getName()));
                        } catch (XMLStreamException | IOException ex) {
                            Logger.getLogger(AnnotationEditor.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                    if (xvalCorpusDir.mkdir()) {
                        System.out.println("xvalCorpus dir Created");
                    } else {
                        System.out.println("xvalCorpus dir  is not created");
                    }
                    for (gate.Document doc : opcorpus) {
                        try {
                            gate.corpora.DocumentStaxUtils.writeDocument(doc,
                                    new File(xvalCorpusDir.getAbsolutePath() + File.separator + doc.getName()));
                        } catch (XMLStreamException | IOException ex) {
                            Logger.getLogger(AnnotationEditor.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                } else {
                    fincorpus = Factory.newCorpus("OuterCorpus");
                    opcorpus = Factory.newCorpus("OptimisationCorpus");
                    this.fincorpus.populate((finCorpusDir.toURI().toURL()), null, "UTF-8", false);
                    this.opcorpus.populate(xvalCorpusDir.toURI().toURL(), null, "UTF-8", false);
                }
                if (getProgressThroughParamList() == paramsList.size()) {
                    return null;
                }

                //write header
                FileWriter fw = new FileWriter((xvalResultsFile), resumeXValidation);
                try (BufferedWriter bw = new BufferedWriter(fw)) {
                    String content = "type\tID\tc\tt\td\ttau\tnegex\trmStops\tmissing\tspurious\tcorrect\tP\tR\tF1\tfolds";
                    if (!resumeXValidation) {
                        bw.write(content);
                        bw.newLine();
                    }
                }
                int processorCount = threadCount;
                //                int processorCount = 1;
                int paramsPerCore = paramsList.size() / processorCount;
                int[][] paramIDAL = new int[processorCount][2];

                int runningCount = 0;
                for (int i = 0; i <= processorCount - 1; i++) {

                    if (i == 0) {
                        paramIDAL[i][0] = 0;
                        paramIDAL[i][1] = paramsPerCore;
                    } else if (i == processorCount - 1) {
                        paramIDAL[i][0] = runningCount;
                        paramIDAL[i][1] = paramsList.size();
                    } else {
                        paramIDAL[i][0] = runningCount;
                        paramIDAL[i][1] = runningCount + paramsPerCore;
                    }
                    runningCount = runningCount + paramsPerCore + 1;
                }
                for (int i = 0; i <= processorCount - 1; i++) {
                    XValidate xval = new XValidate(opcorpus, paramIDAL[i]);
                    synchronized (loadLock) {
                        xval.loadThreadApps();
                    }
                    alXValidate.add(xval);
                }
                System.out.println("X val ready to go with " + alXValidate.size() + " threads!");
                this.xvalARit = alXValidate.iterator();
                if (Thread.currentThread().isInterrupted()) {
                    throw new InterruptedException();
                }
                for (int i = 0; i <= processorCount - 1; i++) {
                    newThread nt = new newThread(xvalARit.next());
                    Thread t = new Thread(nt);
                    t.start();
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                    }
                }
                //once threads are started, set CDL to number of threads and 
                cdl = new CountDownLatch(processorCount + 1);
                if (Thread.currentThread().isInterrupted()) {
                    throw new InterruptedException();
                }

            }
        } catch (IOException | ResourceInstantiationException ex) {
            Logger.getLogger(MLModelMaker.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (InterruptedException ex) {
    }
    //count down by one as MLmodelmaker has run its main routine
    cdl.countDown();
    return null;
}

From source file:org.talend.designer.runprocess.java.AbstractJavaProcessor.java

protected String buildExportZip(ProcessItem processItem, IProgressMonitor progressMonitor)
        throws ProcessorException {
    Map<ExportChoice, Object> exportChoiceMap = JobScriptsManagerFactory.getDefaultExportChoiceMap();
    exportChoiceMap.put(ExportChoice.needLauncher, false);
    exportChoiceMap.put(ExportChoice.needJobItem, false);
    // exportChoiceMap.put(ExportChoice.needJobScript, true); //?? for old build? no need
    if (CommonsPlugin.isDebugMode()) {
        exportChoiceMap.put(ExportChoice.needSourceCode, true);
    } else {/*from  w ww .j  a v  a2  s. co m*/
        exportChoiceMap.put(ExportChoice.needSourceCode, false);
    }
    exportChoiceMap.put(ExportChoice.binaries, true);
    exportChoiceMap.put(ExportChoice.includeLibs, true);

    if (progressMonitor.isCanceled()) {
        throw new ProcessorException(new InterruptedException());
    }
    final String archiveFilePath = Path
            .fromOSString(CorePlugin.getDefault().getPreferenceStore()
                    .getString(ITalendCorePrefConstants.FILE_PATH_TEMP))
            .append(getFilePathPrefix() + '_' + process.getName() + FileExtensions.ZIP_FILE_SUFFIX).toString();

    try {
        exportChoiceMap.put(ExportChoice.needContext, true);
        String contextName = processItem.getProcess().getDefaultContext();
        exportChoiceMap.put(ExportChoice.contextName, contextName);

        buildJob(archiveFilePath, processItem, processItem.getProperty().getVersion(), contextName,
                exportChoiceMap, JobExportType.POJO, progressMonitor);
    } catch (Exception e) {
        throw new ProcessorException(e);
    } finally {
        ProcessorUtilities.resetExportConfig();
    }
    return archiveFilePath;
}

From source file:de.sub.goobi.export.dms.AutomaticDmsExportWithoutHibernate.java

/**
 * Download image.//from  ww w  . j  a v  a2s .co  m
 *
 * @param myProcess
 *            process object
 * @param userHome
 *            safe file
 * @param atsPpnBand
 *            String
 * @param ordnerEndung
 *            String
 */
public void imageDownload(ProcessObject myProcess, SafeFile userHome, String atsPpnBand,
        final String ordnerEndung) throws IOException, InterruptedException, SwapException, DAOException {
    /*
     * den Ausgangspfad ermitteln
     */
    SafeFile tifOrdner = new SafeFile(this.fi.getImagesTifDirectory(true));

    /*
     * jetzt die Ausgangsordner in die Zielordner kopieren
     */
    if (tifOrdner.exists() && tifOrdner.list().length > 0) {
        SafeFile zielTif = new SafeFile(userHome + File.separator + atsPpnBand + ordnerEndung);

        /* bei Agora-Import einfach den Ordner anlegen */
        if (this.project.isUseDmsImport()) {
            if (!zielTif.exists()) {
                zielTif.mkdir();
            }
        } else {
            /*
             * wenn kein Agora-Import, dann den Ordner mit
             * Benutzerberechtigung neu anlegen
             */
            User myUser = (User) Helper.getManagedBeanValue("#{LoginForm.myBenutzer}");
            try {
                FilesystemHelper.createDirectoryForUser(zielTif.getAbsolutePath(), myUser.getLogin());
            } catch (Exception e) {
                if (task != null) {
                    task.setException(e);
                }
                Helper.setFehlerMeldung("Export canceled, error", "could not create destination directory");
                myLogger.error("could not create destination directory", e);
            }
        }

        /* jetzt den eigentlichen Kopiervorgang */

        SafeFile[] dateien = tifOrdner.listFiles(Helper.dataFilter);
        for (int i = 0; i < dateien.length; i++) {
            if (task != null) {
                task.setWorkDetail(dateien[i].getName());
            }
            if (dateien[i].isFile()) {
                SafeFile meinZiel = new SafeFile(zielTif + File.separator + dateien[i].getName());
                dateien[i].copyFile(meinZiel, false);
            }
            if (task != null) {
                task.setProgress((int) ((i + 1) * 98d / dateien.length + 1));
                if (task.isInterrupted()) {
                    throw new InterruptedException();
                }
            }
        }
        if (task != null) {
            task.setWorkDetail(null);
        }
    }
}

From source file:org.eclipse.jubula.client.ui.editors.TestResultViewer.java

/**
 * Generates a Test Result tree and returns the root node of the generated 
 * tree./*w ww. j  ava  2 s  .co  m*/
 * 
 * @param summaryId The database ID of the summary for which to generate the
 *                  tree.
 * @param parentProjectId The database ID of the Project associated with 
 *                        the test run.
 * @return the root node of the generated Test Result tree.
 * 
 * @throws InterruptedException if the operation was cancelled by the user.
 */
private TestResultNode generateTestResult(Long summaryId, Long parentProjectId) throws InterruptedException {

    IProgressService progressService = (IProgressService) getSite().getService(IProgressService.class);

    GenerateTestResultTreeOperation operation = new GenerateTestResultTreeOperation(summaryId, parentProjectId,
            m_cacheResults ? GeneralStorage.getInstance().getMasterSession() : m_session);

    try {
        progressService.busyCursorWhile(operation);
    } catch (InvocationTargetException e) {
        LOG.error(Messages.ErrorFetchingTestResultInformation + StringConstants.DOT, e);
    } catch (OperationCanceledException oce) {
        throw new InterruptedException();
    }

    return operation.getRootNode();
}

From source file:org.apache.hama.bsp.BSPMaster.java

BSPMaster(HamaConfiguration conf, String identifier) throws IOException, InterruptedException {
    this.conf = conf;
    this.masterIdentifier = identifier;

    // Create the scheduler and init scheduler services
    Class<? extends TaskScheduler> schedulerClass = conf.getClass("bsp.master.taskscheduler",
            SimpleTaskScheduler.class, TaskScheduler.class);
    this.taskScheduler = ReflectionUtils.newInstance(schedulerClass, conf);

    InetSocketAddress inetSocketAddress = getAddress(conf);
    // inetSocketAddress is null if we are in local mode, then we should start
    // nothing./*from   w  w  w. ja  v  a 2 s. com*/
    if (inetSocketAddress != null) {
        host = inetSocketAddress.getHostName();
        port = inetSocketAddress.getPort();
        LOG.info("RPC BSPMaster: host " + host + " port " + port);

        startTime = System.currentTimeMillis();
        this.masterServer = RPC.getServer(this, host, port, conf);

        infoPort = conf.getInt("bsp.http.infoserver.port", 40013);

        infoServer = new HttpServer("bspmaster", host, infoPort, true, conf);
        infoServer.setAttribute("bsp.master", this);

        // starting webserver
        infoServer.start();

        if (conf.getBoolean("bsp.monitor.fd.enabled", false)) {
            this.supervisor.set(FDProvider.createSupervisor(
                    conf.getClass("bsp.monitor.fd.supervisor.class", UDPSupervisor.class, Supervisor.class),
                    conf));
        }

        while (!Thread.currentThread().isInterrupted()) {
            try {
                if (fs == null) {
                    fs = FileSystem.get(conf);
                }
            } catch (IOException e) {
                LOG.error("Can't get connection to Hadoop Namenode!", e);
            }
            try {
                // clean up the system dir, which will only work if hdfs is out of
                // safe mode
                if (systemDir == null) {
                    systemDir = new Path(getSystemDir());
                }

                LOG.info("Cleaning up the system directory");
                LOG.info(systemDir);
                fs.delete(systemDir, true);
                if (FileSystem.mkdirs(fs, systemDir, new FsPermission(SYSTEM_DIR_PERMISSION))) {
                    break;
                }
                LOG.error("Mkdirs failed to create " + systemDir);
                LOG.info(SUBDIR);

            } catch (AccessControlException ace) {
                LOG.warn("Failed to operate on bsp.system.dir (" + systemDir + ") because of permissions.");
                LOG.warn(
                        "Manually delete the bsp.system.dir (" + systemDir + ") and then start the BSPMaster.");
                LOG.warn("Bailing out ... ");
                throw ace;
            } catch (IOException ie) {
                LOG.info("problem cleaning system directory: " + systemDir, ie);
            }
            Thread.sleep(FS_ACCESS_RETRY_PERIOD);
        }

        if (Thread.currentThread().isInterrupted()) {
            throw new InterruptedException();
        }

        deleteLocalFiles(SUBDIR);
    } else {
        System.out.println(localModeMessage);
        LOG.info(localModeMessage);
    }
}

From source file:org.graphwalker.ModelBasedTesting.java

public String[] getNextStep() throws InterruptedException {
    if (threadSuspended) {
        logger.debug("Execution is now suspended: " + getGraph().getLabelKey());
        synchronized (lock) {
            while (threadSuspended) {
                wait();//  ww  w . java2 s.c om
            }
        }
        logger.debug("Executions is now resumed: " + getGraph().getLabelKey());
    }

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }
    if (this.machine == null) {
        getMachine();
    }

    getStatisticsManager();
    Util.AbortIf(getGenerator() == null, "No generator has been defined!");

    PathGenerator backupGenerator = null;
    if (runRandomGeneratorOnce) {
        backupGenerator = getGenerator();
        try {
            setGenerator(Keywords.GENERATOR_RANDOM);
        } catch (GeneratorException e) {
            logger.error(e.getMessage());
            throw new RuntimeException("ERROR: " + e.getMessage(), e);
        }
    }

    try {
        return getGenerator().getNext();
    } catch (RuntimeException e) {
        logger.fatal(e.toString());
        throw new RuntimeException("ERROR: " + e.getMessage(), e);
    } finally {
        if (runRandomGeneratorOnce) {
            runRandomGeneratorOnce = false;
            setGenerator(backupGenerator);
        }
    }
}

From source file:org.ut.biolab.medsavant.client.view.genetics.variantinfo.GeneManiaSubInspector.java

protected void updateRelatedGenesPanel(Set<Gene> g) {
    genes = g;//from w  ww  .j av  a  2 s. co m
    kvpPanel.removeAll();
    kvpPanel.invalidate();
    kvpPanel.updateUI();
    kvp = new KeyValuePairPanel(5);
    kvp.setKeysVisible(false);
    kvpPanel.add(kvp);
    progressBar.setVisible(true);
    progressMessage.setVisible(true);
    progressBar.setIndeterminate(true);
    progressMessage.setText("Querying GeneMANIA for related genes");

    final Object lock = new Object();

    Runnable r = new Runnable() {
        @Override
        public void run() {
            boolean setMsgOff = true;
            boolean buildGraph = true;
            if (!Thread.interrupted()) {
                try {
                    List<String> geneNames = new ArrayList();
                    for (Gene gene : genes) {
                        geneNames.add(gene.getName());
                    }
                    List<String> notInGenemania = new ArrayList<String>(geneNames);
                    notInGenemania.removeAll(GenemaniaInfoRetriever.getValidGenes(geneNames));
                    geneNames = GenemaniaInfoRetriever.getValidGenes(geneNames);
                    genemania.setGenes(geneNames);

                    if (notInGenemania.size() > 0) {
                        String message = "<html><center>Following gene(s) not found in GeneMANIA: ";
                        for (String invalidGene : notInGenemania) {
                            message += "<br>" + invalidGene;
                        }
                        message += "</center></html>";
                        progressMessage.setText(message);
                        setMsgOff = false;
                        buildGraph = false;
                    }
                    GeneSetFetcher geneSetFetcher = GeneSetFetcher.getInstance();
                    if (genemania.getGenes().size() > 0) {
                        int i = 1;
                        String zero = Integer.toString(0);
                        Font HEADER_FONT = new Font("Arial", Font.BOLD, 10);
                        kvp.addKey(zero);
                        JLabel geneHeader = new JLabel("Gene".toUpperCase());
                        geneHeader.setFont(HEADER_FONT);
                        kvp.setValue(zero, geneHeader);
                        JLabel varFreqHeader = new JLabel("<html>VARIATION<br>FREQUENCY<br>(var/kb)</html>");
                        varFreqHeader.setFont(HEADER_FONT);
                        kvp.setAdditionalColumn(zero, 0, varFreqHeader);
                        JLabel genemaniaHeader = new JLabel("<html>GENEMANIA<br>SCORE</html>");
                        genemaniaHeader.setFont(HEADER_FONT);

                        if (Thread.interrupted()) {
                            throw new InterruptedException();
                        }

                        if (rankByVarFreq) {
                            Iterator<org.ut.biolab.medsavant.shared.model.Gene> itr = geneSetFetcher
                                    .getGenesByNumVariants(genemania.getRelatedGeneNamesByScore()).iterator();

                            //skip the first one (it's the name of selected gene already displayed)
                            itr.next();

                            while (itr.hasNext()) {
                                addGeneToKeyValuePanel(itr.next(), i++);
                            }

                            currSizeOfArray = i - 1;
                        } else {
                            Iterator<String> itr = genemania.getRelatedGeneNamesByScore().iterator();

                            //skip the first one (it's the name of selected gene already displayed)
                            itr.next();

                            List<String> tmp = new LinkedList<String>();
                            while (itr.hasNext()) {
                                tmp.add(itr.next());
                            }

                            System.out.println("start populating table" + System.currentTimeMillis());

                            /*while (itr.hasNext()) {
                                    
                             //getNormalizedVariantCount(gene)
                             addGeneToKeyValuePanel(GeneSetFetcher.getInstance().getGene(itr.next()), i++);
                             }*/

                            for (String foo : tmp) {
                                addGeneToKeyValuePanel(GeneSetFetcher.getInstance().getGene(foo), i++);
                            }
                            System.out.println("done thread" + System.currentTimeMillis());

                            currSizeOfArray = i - 1;
                        }
                    }

                } catch (InterruptedException e) {
                    LOG.error(e);
                    buildGraph = false;
                } catch (NoRelatedGenesInfoException e) {
                    LOG.error(e);
                    progressMessage.setText(e.getMessage());
                    setMsgOff = false;
                    buildGraph = false;
                } catch (Exception ex) {
                    LOG.error(ex);
                    buildGraph = false;
                    ClientMiscUtils.reportError("Error retrieving data from GeneMANIA: %s", ex);
                } catch (Error e) {
                    LOG.error(e);
                } finally {
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(0);
                    progressBar.setVisible(false);

                    if (setMsgOff) {
                        progressMessage.setVisible(false);
                    }
                }

            }

            synchronized (lock) {
                lock.notify();
            }
        }
    };
    if (genemaniaAlgorithmThread == null) {
        genemaniaAlgorithmThread = new Thread(r);
    } else {
        genemaniaAlgorithmThread.interrupt();
        genemaniaAlgorithmThread = new Thread(r);

    }

    final Runnable geneDescriptionFetcher = new Runnable() {
        @Override
        public void run() {
            for (int j = 1; j <= currSizeOfArray; j++) {
                try {
                    String geneName = kvp.getValue(Integer.toString(j));
                    Gene gene = GeneSetFetcher.getInstance().getGene(geneName);
                    String d = gene.getDescription();
                    kvp.setToolTipForValue(Integer.toString(j), d);
                } catch (Exception e) {
                    //do nothing (don't set tool tip to anything)
                }
            }
        }
    };
    //}

    genemaniaAlgorithmThread.start();

    Runnable r2 = new Runnable() {
        @Override
        public void run() {
            try {
                synchronized (lock) {
                    lock.wait();
                    Thread toolTipGenerator = new Thread(geneDescriptionFetcher);
                    Thread varFreqCalculator = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 1; i <= currSizeOfArray; i++) {
                                try {
                                    String geneName = kvp.getValue(Integer.toString(i));
                                    Gene gene = GeneSetFetcher.getInstance().getGene(geneName);
                                    kvp.setAdditionalColumn(Integer.toString(i), 0, new JLabel(Double.toString(
                                            GeneSetFetcher.getInstance().getNormalizedVariantCount(gene))));
                                    kvp.invalidate();
                                    kvp.updateUI();
                                } catch (Exception ex) {
                                    //don't put in any variation frequency
                                }
                            }
                        }
                    });
                    toolTipGenerator.start();
                    varFreqCalculator.start();
                }
            } catch (Exception e) {
            }
        }
    };

    Thread t2 = new Thread(r2);
    t2.start();
}

From source file:jenkins.branch.OrganizationFolder.java

/**
 * {@inheritDoc}// w w  w .  j  a va2  s.  c  o m
 */
@Override
protected void computeChildren(final ChildObserver<MultiBranchProject<?, ?>> observer,
        final TaskListener listener) throws IOException, InterruptedException {
    // capture the current digests to prevent unnecessary rescan if re-saving after scan
    try {
        navDigest = Util.getDigestOf(Items.XSTREAM2.toXML(navigators));
    } catch (XStreamException e) {
        navDigest = null;
    }
    try {
        facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(projectFactories));
    } catch (XStreamException e) {
        facDigest = null;
    }
    long start = System.currentTimeMillis();
    listener.getLogger().format("[%tc] Starting organization scan...%n", start);
    try {
        listener.getLogger().format("[%tc] Updating actions...%n", System.currentTimeMillis());
        Map<SCMNavigator, List<Action>> navigatorActions = new HashMap<>();
        for (SCMNavigator navigator : navigators) {
            List<Action> actions;
            try {
                actions = navigator.fetchActions(this, null, listener);
            } catch (IOException e) {
                MultiBranchProject.printStackTrace(e,
                        listener.error("[%tc] Could not refresh actions for navigator %s",
                                System.currentTimeMillis(), navigator));
                // preserve previous actions if we have some transient error fetching now (e.g. API rate limit)
                actions = Util.fixNull(state.getActions().get(navigator));
            }
            navigatorActions.put(navigator, actions);
        }
        // update any persistent actions for the SCMNavigator
        if (!navigatorActions.equals(state.getActions())) {
            boolean saveProject = false;
            for (List<Action> actions : navigatorActions.values()) {
                for (Action a : actions) {
                    // undo any hacks that attached the contributed actions without attribution
                    saveProject = removeActions(a.getClass()) || saveProject;
                }
            }
            BulkChange bc = new BulkChange(state);
            try {
                state.setActions(navigatorActions);
                try {
                    bc.commit();
                } catch (IOException | RuntimeException e) {
                    MultiBranchProject.printStackTrace(e, listener
                            .error("[%tc] Could not persist folder level actions", System.currentTimeMillis()));
                    throw e;
                }
                if (saveProject) {
                    try {
                        save();
                    } catch (IOException | RuntimeException e) {
                        MultiBranchProject.printStackTrace(e,
                                listener.error("[%tc] Could not persist folder level configuration changes",
                                        System.currentTimeMillis()));
                        throw e;
                    }
                }
            } finally {
                bc.abort();
            }
        }
        for (SCMNavigator navigator : navigators) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
            listener.getLogger().format("[%tc] Consulting %s%n", System.currentTimeMillis(),
                    navigator.getDescriptor().getDisplayName());
            try {
                navigator.visitSources(
                        new SCMSourceObserverImpl(listener, observer, navigator, (SCMSourceEvent<?>) null));
            } catch (IOException | InterruptedException | RuntimeException e) {
                MultiBranchProject.printStackTrace(e,
                        listener.error("[%tc] Could not fetch sources from navigator %s",
                                System.currentTimeMillis(), navigator));
                throw e;
            }
        }
    } finally {
        long end = System.currentTimeMillis();
        listener.getLogger().format("[%tc] Finished organization scan. Scan took %s%n", end,
                Util.getTimeSpanString(end - start));

    }
}

From source file:com.appunite.websocket.WebSocket.java

/**
 * Send a message to socket//from www .j a  v a  2 s  . co m
 * 
 * (thread safe)
 * 
 * @param opcode
 *            - type of message (0x00-0x0f) <a
 *            href="http://tools.ietf.org/html/rfc6455#section-11.8">rfc6455
 *            opcode</a>
 * @param mask
 *            - message mask key (4 byte length) or Optional.absent() if
 *            message should not be masked
 * @param buffer
 *            buffer that will be sent to user. This buffer will be changed
 *            if mask will be set
 * @throws IOException
 *             - when write error occur
 * @throws InterruptedException
 *             - when socket was interrupted
 * @throws NotConnectedException
 *             - when socket was not connected
 */
private void sendMessage(int opcode, Optional<byte[]> mask, byte[] buffer)
        throws IOException, InterruptedException, NotConnectedException {
    checkNotNull(buffer, "buffer should not be null");
    checkNotNull(mask, "mask should not be null");
    synchronized (mLockObj) {
        if (!State.CONNECTED.equals(mState)) {
            throw new NotConnectedException();
        }
        mWriting += 1;
    }
    try {
        synchronized (mWriteLock) {
            sendHeader(true, opcode, mask, buffer.length);
            if (mask.isPresent()) {
                maskBuffer(buffer, mask.get());
            }
            mOutputStream.writeBytes(buffer);
            mOutputStream.flush();

        }
    } catch (IOException e) {
        synchronized (mLockObj) {
            if (State.DISCONNECTING.equals(mState)) {
                throw new InterruptedException();
            } else {
                throw e;
            }
        }
    } finally {
        synchronized (mLockObj) {
            mWriting -= 1;
            mLockObj.notifyAll();
        }
    }
}