Example usage for java.util.concurrent.atomic AtomicBoolean get

List of usage examples for java.util.concurrent.atomic AtomicBoolean get

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean get.

Prototype

public final boolean get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:info.archinnov.achilles.it.TestCRUDSimpleEntity.java

@Test
public void should_delete_with_not_equal_condition() throws Exception {
    //Given/*  ww w .java 2  s .co m*/
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    final Date date = buildDateKey();
    scriptExecutor.executeScriptTemplate("SimpleEntity/insert_single_row.cql",
            ImmutableMap.of("id", id, "table", "simple"));

    final AtomicBoolean success = new AtomicBoolean(false);
    final LWTResultListener lwtResultListener = new LWTResultListener() {

        @Override
        public void onSuccess() {
            success.getAndSet(true);
        }

        @Override
        public void onError(LWTResult lwtResult) {

        }
    };
    //When
    manager.dsl().delete().allColumns_FromBaseTable().where().id_Eq(id).date_Eq(date)
            .ifConsistencyList_NotEq(Arrays.asList(ALL)).withLwtResultListener(lwtResultListener).execute();

    //Then
    final Row row = session.execute("SELECT * FROM simple WHERE id = " + id).one();
    assertThat(row).isNull();
    assertThat(success.get()).isTrue();
}

From source file:io.openvidu.server.recording.service.RecordingManager.java

private void checkRecordingPaths(String openviduRecordingPath, String openviduRecordingCustomLayout)
        throws OpenViduException {
    log.info("Initializing recording paths");

    Path recordingPath = null;// w  w  w .j a v a  2s  .  c  om
    try {
        recordingPath = Files.createDirectories(Paths.get(openviduRecordingPath));
    } catch (IOException e) {
        String errorMessage = "The recording path \"" + openviduRecordingPath
                + "\" is not valid. Reason: OpenVidu Server cannot find path \"" + openviduRecordingPath
                + "\" and doesn't have permissions to create it";
        log.error(errorMessage);
        throw new OpenViduException(Code.RECORDING_PATH_NOT_VALID, errorMessage);
    }

    // Check OpenVidu Server write permissions in recording path
    if (!Files.isWritable(recordingPath)) {
        String errorMessage = "The recording path \"" + openviduRecordingPath
                + "\" is not valid. Reason: OpenVidu Server needs write permissions. Try running command \"sudo chmod 777 "
                + openviduRecordingPath + "\"";
        log.error(errorMessage);
        throw new OpenViduException(Code.RECORDING_PATH_NOT_VALID, errorMessage);
    } else {
        log.info("OpenVidu Server has write permissions on recording path: {}", openviduRecordingPath);
    }

    final String testFolderPath = openviduRecordingPath + "/TEST_RECORDING_PATH_" + System.currentTimeMillis();
    final String testFilePath = testFolderPath + "/TEST_RECORDING_PATH.webm";

    // Check Kurento Media Server write permissions in recording path
    KurentoClientSessionInfo kcSessionInfo = new OpenViduKurentoClientSessionInfo("TEST_RECORDING_PATH",
            "TEST_RECORDING_PATH");
    MediaPipeline pipeline = this.kcProvider.getKurentoClient(kcSessionInfo).createMediaPipeline();
    RecorderEndpoint recorder = new RecorderEndpoint.Builder(pipeline, "file://" + testFilePath).build();

    final AtomicBoolean kurentoRecorderError = new AtomicBoolean(false);

    recorder.addErrorListener(new EventListener<ErrorEvent>() {
        @Override
        public void onEvent(ErrorEvent event) {
            if (event.getErrorCode() == 6) {
                // KMS write permissions error
                kurentoRecorderError.compareAndSet(false, true);
            }
        }
    });

    recorder.record();

    try {
        // Give the error event some time to trigger if necessary
        Thread.sleep(500);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }

    if (kurentoRecorderError.get()) {
        String errorMessage = "The recording path \"" + openviduRecordingPath
                + "\" is not valid. Reason: Kurento Media Server needs write permissions. Try running command \"sudo chmod 777 "
                + openviduRecordingPath + "\"";
        log.error(errorMessage);
        throw new OpenViduException(Code.RECORDING_PATH_NOT_VALID, errorMessage);
    }

    recorder.stop();
    recorder.release();
    pipeline.release();

    log.info("Kurento Media Server has write permissions on recording path: {}", openviduRecordingPath);

    try {
        new CustomFileManager().deleteFolder(testFolderPath);
        log.info("OpenVidu Server has write permissions over files created by Kurento Media Server");
    } catch (IOException e) {
        String errorMessage = "The recording path \"" + openviduRecordingPath
                + "\" is not valid. Reason: OpenVidu Server does not have write permissions over files created by Kurento Media Server. "
                + "Try running Kurento Media Server as user \"" + System.getProperty("user.name")
                + "\" or run OpenVidu Server as superuser";
        log.error(errorMessage);
        log.error(
                "Be aware that a folder \"{}\" was created and should be manually deleted (\"sudo rm -rf {}\")",
                testFolderPath, testFolderPath);
        throw new OpenViduException(Code.RECORDING_PATH_NOT_VALID, errorMessage);
    }

    if (openviduConfig.openviduRecordingCustomLayoutChanged(openviduRecordingCustomLayout)) {
        // Property openvidu.recording.custom-layout changed
        File dir = new File(openviduRecordingCustomLayout);
        if (dir.exists()) {
            if (!dir.isDirectory()) {
                String errorMessage = "The custom layouts path \"" + openviduRecordingCustomLayout
                        + "\" is not valid. Reason: path already exists but it is not a directory";
                log.error(errorMessage);
                throw new OpenViduException(Code.RECORDING_FILE_EMPTY_ERROR, errorMessage);
            } else {
                if (dir.listFiles() == null) {
                    String errorMessage = "The custom layouts path \"" + openviduRecordingCustomLayout
                            + "\" is not valid. Reason: OpenVidu Server needs read permissions. Try running command \"sudo chmod 755 "
                            + openviduRecordingCustomLayout + "\"";
                    log.error(errorMessage);
                    throw new OpenViduException(Code.RECORDING_FILE_EMPTY_ERROR, errorMessage);
                } else {
                    log.info("OpenVidu Server has read permissions on custom layout path: {}",
                            openviduRecordingCustomLayout);
                    log.info("Custom layouts path successfully initialized at {}",
                            openviduRecordingCustomLayout);
                }
            }
        } else {
            try {
                Files.createDirectories(dir.toPath());
                log.warn(
                        "OpenVidu custom layouts path (system property 'openvidu.recording.custom-layout') has been created, being folder {}. "
                                + "It is an empty folder, so no custom layout is currently present",
                        dir.getAbsolutePath());
            } catch (IOException e) {
                String errorMessage = "The custom layouts path \"" + openviduRecordingCustomLayout
                        + "\" is not valid. Reason: OpenVidu Server cannot find path \""
                        + openviduRecordingCustomLayout + "\" and doesn't have permissions to create it";
                log.error(errorMessage);
                throw new OpenViduException(Code.RECORDING_FILE_EMPTY_ERROR, errorMessage);
            }
        }
    }

    log.info("Recording path successfully initialized at {}", openviduRecordingPath);
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldCallFail() throws Exception {
    final AtomicBoolean timeoutCalled = new AtomicBoolean(false);
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build()
            .afterFailure((b, e) -> failureCalled.set(true)).afterSuccess((b) -> successCalled.set(true))
            .afterTimeout((b) -> timeoutCalled.set(true)).create();
    try {//from www .j a  v a2s.  c  om
        gremlinExecutor.eval("10/0").get();
        fail();
    } catch (Exception ignored) {
    }

    // need to wait long enough for the callback to register
    Thread.sleep(500);

    assertFalse(timeoutCalled.get());
    assertFalse(successCalled.get());
    assertTrue(failureCalled.get());
    gremlinExecutor.close();
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.localworkspace.LocalWorkspaceScanner.java

private void scanPartTwo() {
    // The items in this set may be folders or files. They have local
    // version rows, but no local item on disk. We will mark the local
    // version row as MissingOnDisk. The row will persist until the
    // reconcile before the next Get. If it is still MissingOnDisk then, we
    // will remove the row and reconcile that delete to the server so that
    // the item will come back.
    for (final WorkspaceLocalItem lvEntry : markForRemoval) {
        // If the item is in the exclusion list for this scanner, do not
        // process the item.
        if (skippedItems.contains(lvEntry.getLocalItem())) {
            continue;
        }/*w  ww .  ja v a 2  s .c  om*/

        final LocalPendingChange pcEntry = pc.getByLocalVersion(lvEntry);

        // Pending adds do not have their local version row removed marked
        // as MissingFromDisk.
        if (null == pcEntry || !pcEntry.isAdd()) {
            if (!lvEntry.isMissingOnDisk()) {
                lv.removeByServerItem(lvEntry.getServerItem(), lvEntry.isCommitted(), false);
                lvEntry.setMissingOnDisk(true);
                lv.add(lvEntry);
            }

            final String targetServerItem = pc.getTargetServerItemForLocalVersion(lvEntry);

            if (lvEntry.isCommitted() && null == pcEntry
                    && null != pc.getByTargetServerItem(targetServerItem)) {
                // if we don't have a pending change against the item, but
                // have a pending change against the target i.e. add, branch
                // or rename we don't want mark this as a candidate as there
                // is no way to actually pend the delete without moving the
                // item out of the way, we will let check-in take care of it
                // with a namespace conflict
                continue;
            }

            final LocalPendingChange newChange = new LocalPendingChange(lvEntry, targetServerItem,
                    ChangeType.DELETE);
            newChange.setCandidate(true);
            addCandidateChange(newChange);
        }
    }

    // The items in this set may be folders or files. They have local
    // version rows, and were previously marked as MissingOnDisk. However,
    // their local item has reappeared. We will remove the MissingOnDisk
    // bit.
    for (final WorkspaceLocalItem lvEntry : reappearedOnDisk) {
        // If the item is in the exclusion list for this scanner, do not
        // process the item.
        if (skippedItems.contains(lvEntry.getLocalItem())) {
            continue;
        }

        lv.removeByServerItem(lvEntry.getServerItem(), lvEntry.isCommitted(), false);
        lvEntry.setMissingOnDisk(false);
        lv.add(lvEntry);
    }

    // The items in this set are all files. They were identified as having
    // identical content as the workspace version, but a different
    // timestamp. We will update the local version table to contain the new
    // timestamp. Additionally, if the item has a pending edit, we will
    // selective-undo the edit.

    for (final KeyValuePair<String, Long> undoOp : toUndo) {
        final String localItem = undoOp.getKey();
        final long onDiskModifiedTime = undoOp.getValue();

        if (skippedItems.contains(localItem)) {
            continue;
        }

        final WorkspaceLocalItem lvEntry = lv.getByLocalItem(localItem);

        // Bring the last-modified time on the item forward to match the
        // latest scan.
        if (lvEntry.getLastModifiedTime() != onDiskModifiedTime) {
            lvEntry.setLastModifiedTime(onDiskModifiedTime);
            lv.setDirty(true);
        }

        final LocalPendingChange pcEntry = pc.getByLocalVersion(lvEntry);

        // If the item has a pending edit, undo the pending edit, because
        // the content is identical to the workspace version. The only
        // uncommitted server items which can have their pending change
        // undone are those with changetype "branch, edit".
        if (null != pcEntry && pcEntry.isEdit() && !pcEntry.isAdd()
                && (!pcEntry.isEncoding() || pcEntry.getEncoding() == lvEntry.getEncoding())) {
            final AtomicReference<Failure[]> outFailures = new AtomicReference<Failure[]>();
            final AtomicBoolean outOnlineOperationRequired = new AtomicBoolean();
            final List<LocalPendingChange> pcEntries = new ArrayList<LocalPendingChange>(1);
            pcEntries.add(pcEntry);

            // The GetOperations returned are not processed.
            final GetOperation[] getOps = LocalDataAccessLayer.undoPendingChanges(
                    LocalWorkspaceTransaction.getCurrent().getWorkspace(), wp, lv, pc, pcEntries,
                    ChangeType.EDIT, outFailures, outOnlineOperationRequired);

            // No renames or locks are being undone,
            Check.isTrue(!outOnlineOperationRequired.get() && (1 == getOps.length),
                    "!outOnlineOperationRequired.get() && (1 == getOps.length)"); //$NON-NLS-1$

            // Since we've modified the pending changes table in a silent
            // way, we want to set the flag on the transaction we're a part
            // of that indicates the PendingChangesChanged event should be
            // raised for this workspace, once the transaction completes.
            LocalWorkspaceTransaction.getCurrent().setRaisePendingChangesChanged(true);
        }
    }
}

From source file:com.barchart.netty.server.http.TestHttpServer.java

@Test
public void testShutdown() throws Exception {

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    final AtomicBoolean pass = new AtomicBoolean(false);

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

        @Override//from  w ww .ja v  a  2  s .co m
        public void run() {

            try {
                Thread.sleep(1000);
                server.shutdown();
            } catch (final InterruptedException e1) {
                e1.printStackTrace();
            }

            try {
                client.execute(new HttpGet("http://localhost:" + port + "/basic"));
            } catch (final HttpHostConnectException hhce) {
                pass.set(true);
            } catch (final Exception e) {
                e.printStackTrace();
            }

        }

    });

    t.start();

    final HttpGet get = new HttpGet("http://localhost:" + port + "/client-disconnect");
    final HttpResponse response = client.execute(get);
    EntityUtils.consume(response.getEntity());
    assertEquals(200, response.getStatusLine().getStatusCode());

    t.join();

    assertTrue(pass.get());

}

From source file:netbeanstypescript.TSDeclarationFinder.java

@Override
public OffsetRange getReferenceSpan(final Document doc, final int caretOffset) {
    final OffsetRange[] tokenRange = new OffsetRange[1];
    doc.render(new Runnable() {
        @Override/*from   w  ww  . j a v a2  s.co  m*/
        public void run() {
            TokenSequence<?> ts = TokenHierarchy.get(doc).tokenSequence(JsTokenId.javascriptLanguage());
            int offsetWithinToken = ts.move(caretOffset);
            if (ts.moveNext()) {
                Token<?> tok = ts.token();
                if (possibleRefs.contains(tok.id().primaryCategory())) {
                    int start = caretOffset - offsetWithinToken;
                    tokenRange[0] = new OffsetRange(start, start + tok.length());
                    return;
                }
            }
            // If we're right between two tokens, check the previous
            if (offsetWithinToken == 0 && ts.movePrevious()) {
                Token<?> tok = ts.token();
                if (possibleRefs.contains(tok.id().primaryCategory())) {
                    tokenRange[0] = new OffsetRange(caretOffset - tok.length(), caretOffset);
                }
            }
        }
    });
    if (tokenRange[0] == null) {
        return OffsetRange.NONE;
    }

    // Now query the language service to see if this is actually a reference
    final AtomicBoolean isReference = new AtomicBoolean();
    class ReferenceSpanTask extends UserTask implements Runnable {
        @Override
        public void run() {
            try {
                ParserManager.parse(Collections.singleton(Source.create(doc)), this);
            } catch (ParseException e) {
                TSService.log.log(Level.WARNING, null, e);
            }
        }

        @Override
        public void run(ResultIterator ri) throws ParseException {
            // Calling ResultIterator#getParserResult() ensures latest snapshot pushed to server
            Object defs = TSService.call("getDefsAtPosition",
                    ri.getParserResult().getSnapshot().getSource().getFileObject(), caretOffset);
            isReference.set(defs != null);
        }
    }
    // Don't block the UI thread for too long in case server is busy
    RequestProcessor.Task task = RP.post(new ReferenceSpanTask());
    try {
        task.waitFinished(1000);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        task.cancel();
    }
    return isReference.get() ? tokenRange[0] : OffsetRange.NONE;
}

From source file:org.apache.blur.shell.QueryCommand.java

private void doItInternal(Blur.Iface client, String[] args, PrintWriter out)
        throws FinishedException, BlurException, TException {
    CommandLine commandLine = QueryCommandHelper.parse(args, out, name() + " " + usage());
    if (commandLine == null) {
        return;//from  ww  w  .  j a  va2 s.  c  om
    }
    BlurQuery blurQuery = QueryCommandHelper.getBlurQuery(commandLine);
    if (Main.debug) {
        out.println(blurQuery);
    }
    _width = 100;
    if (commandLine.hasOption(QueryCommandHelper.WIDTH)) {
        _width = Integer.parseInt(commandLine.getOptionValue(QueryCommandHelper.WIDTH));
    }
    String tablename = args[1];
    long s = System.nanoTime();
    BlurResults blurResults = client.query(tablename, blurQuery);
    long e = System.nanoTime();
    long timeInNanos = e - s;
    if (blurResults.getTotalResults() == 0) {
        out.println("No results found in [" + timeInNanos / 1000000.0 + " ms].");
        return;
    }

    ConsoleReader reader = getConsoleReader();
    if (reader == null) {
        String description = blurResults.getTotalResults() + " results found in [" + timeInNanos / 1000000.0
                + " ms].  " + getFetchMetaData(blurResults);
        out.println(description);
        List<BlurResult> results = blurResults.getResults();
        for (BlurResult result : results) {
            print(out, result);
        }
        return;
    }

    String prompt = reader.getPrompt();
    reader.setPrompt("");
    final TableDisplay tableDisplay = new TableDisplay(reader);
    tableDisplay.setDescription(white(blurResults.getTotalResults() + " results found in ["
            + timeInNanos / 1000000.0 + " ms].  " + getFetchMetaData(blurResults)));
    tableDisplay.setSeperator(" ");
    try {

        final AtomicBoolean viewing = new AtomicBoolean(true);

        tableDisplay.addKeyHook(new Runnable() {
            @Override
            public void run() {
                synchronized (viewing) {
                    viewing.set(false);
                    viewing.notify();
                    tableDisplay.setStopReadingInput(true);
                }
            }
        }, 'q');

        RenderType type = getRenderRype(blurResults);
        switch (type) {
        case ROW_MULTI_FAMILY:
            renderRowMultiFamily(tableDisplay, blurResults);
            break;
        case ROW_SINGLE_FAMILY:
            renderRowSingleFamily(tableDisplay, blurResults);
            break;
        default:
            break;
        }

        while (viewing.get()) {
            synchronized (viewing) {
                try {
                    viewing.wait();
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    } finally {
        try {
            tableDisplay.close();
        } catch (IOException ex) {
            if (Main.debug) {
                ex.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            if (Main.debug) {
                ex.printStackTrace();
            }
        }
        try {
            reader.setPrompt("");
            reader.clearScreen();
        } catch (IOException ex) {
            if (Main.debug) {
                ex.printStackTrace();
            }
        }
        out.write("\u001B[0m");
        out.flush();
        reader.setPrompt(prompt);
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.css.CSSStyleSheet.java

private static boolean selectsPseudoClass(final BrowserVersion browserVersion,
        final AttributeCondition condition, final DomElement element) {
    if (browserVersion.hasFeature(QUERYSELECTORALL_NOT_IN_QUIRKS)) {
        final Object sobj = element.getPage().getScriptableObject();
        if (sobj instanceof HTMLDocument && ((HTMLDocument) sobj).getDocumentMode() < 8) {
            return false;
        }/*from www.  j  a  v a2  s.  co m*/
    }

    final String value = condition.getValue();
    if ("root".equals(value)) {
        return element == element.getPage().getDocumentElement();
    } else if ("enabled".equals(value)) {
        return element instanceof DisabledElement && !((DisabledElement) element).isDisabled();
    }
    if ("disabled".equals(value)) {
        return element instanceof DisabledElement && ((DisabledElement) element).isDisabled();
    }
    if ("focus".equals(value)) {
        final HtmlPage htmlPage = element.getHtmlPageOrNull();
        if (htmlPage != null) {
            final DomElement focus = htmlPage.getFocusedElement();
            return element == focus;
        }
    } else if ("checked".equals(value)) {
        return (element instanceof HtmlCheckBoxInput && ((HtmlCheckBoxInput) element).isChecked())
                || (element instanceof HtmlRadioButtonInput && ((HtmlRadioButtonInput) element).isChecked()
                        || (element instanceof HtmlOption && ((HtmlOption) element).isSelected()));
    } else if ("first-child".equals(value)) {
        for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement) {
                return false;
            }
        }
        return true;
    } else if ("last-child".equals(value)) {
        for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement) {
                return false;
            }
        }
        return true;
    } else if ("first-of-type".equals(value)) {
        final String type = element.getNodeName();
        for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                return false;
            }
        }
        return true;
    } else if ("last-of-type".equals(value)) {
        final String type = element.getNodeName();
        for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                return false;
            }
        }
        return true;
    } else if (value.startsWith("nth-child(")) {
        final String nth = value.substring(value.indexOf('(') + 1, value.length() - 1);
        int index = 0;
        for (DomNode n = element; n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement) {
                index++;
            }
        }
        return getNth(nth, index);
    } else if (value.startsWith("nth-last-child(")) {
        final String nth = value.substring(value.indexOf('(') + 1, value.length() - 1);
        int index = 0;
        for (DomNode n = element; n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement) {
                index++;
            }
        }
        return getNth(nth, index);
    } else if (value.startsWith("nth-of-type(")) {
        final String type = element.getNodeName();
        final String nth = value.substring(value.indexOf('(') + 1, value.length() - 1);
        int index = 0;
        for (DomNode n = element; n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                index++;
            }
        }
        return getNth(nth, index);
    } else if (value.startsWith("nth-last-of-type(")) {
        final String type = element.getNodeName();
        final String nth = value.substring(value.indexOf('(') + 1, value.length() - 1);
        int index = 0;
        for (DomNode n = element; n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                index++;
            }
        }
        return getNth(nth, index);
    } else if ("only-child".equals(value)) {
        for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement) {
                return false;
            }
        }
        for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement) {
                return false;
            }
        }
        return true;
    } else if ("only-of-type".equals(value)) {
        final String type = element.getNodeName();
        for (DomNode n = element.getPreviousSibling(); n != null; n = n.getPreviousSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                return false;
            }
        }
        for (DomNode n = element.getNextSibling(); n != null; n = n.getNextSibling()) {
            if (n instanceof DomElement && n.getNodeName().equals(type)) {
                return false;
            }
        }
        return true;
    } else if ("empty".equals(value)) {
        return isEmpty(element);
    } else if ("target".equals(value)) {
        final String ref = element.getPage().getUrl().getRef();
        return StringUtils.isNotBlank(ref) && ref.equals(element.getId());
    } else if (value.startsWith("not(")) {
        final String selectors = value.substring(value.indexOf('(') + 1, value.length() - 1);
        final AtomicBoolean errorOccured = new AtomicBoolean(false);
        final ErrorHandler errorHandler = new ErrorHandler() {
            @Override
            public void warning(final CSSParseException exception) throws CSSException {
                // ignore
            }

            @Override
            public void fatalError(final CSSParseException exception) throws CSSException {
                errorOccured.set(true);
            }

            @Override
            public void error(final CSSParseException exception) throws CSSException {
                errorOccured.set(true);
            }
        };
        final CSSOMParser parser = new CSSOMParser(new SACParserCSS3());
        parser.setErrorHandler(errorHandler);
        try {
            final SelectorList selectorList = parser
                    .parseSelectors(new InputSource(new StringReader(selectors)));
            if (errorOccured.get() || selectorList == null || selectorList.getLength() != 1) {
                throw new CSSException("Invalid selectors: " + selectors);
            }

            validateSelectors(selectorList, 9, element);

            return !CSSStyleSheet.selects(browserVersion, selectorList.item(0), element);
        } catch (final IOException e) {
            throw new CSSException("Error parsing CSS selectors from '" + selectors + "': " + e.getMessage());
        }
    }
    return false;
}

From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java

private void doUploadMessage(final RoutingContext ctx, final String tenant, final String deviceId,
        final Buffer payload, final String contentType, final Future<MessageSender> senderTracker,
        final String endpointName) {

    if (!isPayloadOfIndicatedType(payload, contentType)) {
        HttpUtils.badRequest(ctx,//w ww  .  ja v a2  s  . c  o  m
                String.format("Content-Type %s does not match with the payload", contentType));
    } else {
        final Integer qosHeader = getQoSLevel(ctx.request().getHeader(Constants.HEADER_QOS_LEVEL));
        if (contentType == null) {
            HttpUtils.badRequest(ctx, String.format("%s header is missing", HttpHeaders.CONTENT_TYPE));
        } else if (qosHeader != null && qosHeader == HEADER_QOS_INVALID) {
            HttpUtils.badRequest(ctx, "Bad QoS Header Value");
        } else {

            final Device authenticatedDevice = getAuthenticatedDevice(ctx);
            final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId,
                    authenticatedDevice);
            final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant);

            // AtomicBoolean to control if the downstream message was sent successfully
            final AtomicBoolean downstreamMessageSent = new AtomicBoolean(false);
            // AtomicReference to a Handler to be called to close an open command receiver link.
            final AtomicReference<Handler<Void>> closeLinkAndTimerHandlerRef = new AtomicReference<>();

            // Handler to be called with a received command. If the timer expired, null is provided as command.
            final Handler<Message> commandReceivedHandler = commandMessage -> {
                // reset the closeHandler reference, since it is not valid anymore at this time.
                closeLinkAndTimerHandlerRef.set(null);
                if (downstreamMessageSent.get()) {
                    // finish the request, since the response is now complete (command was added)
                    if (!ctx.response().closed()) {
                        ctx.response().end();
                    }
                }
            };

            CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> {

                if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) {
                    final MessageSender sender = senderTracker.result();
                    final Message downstreamMessage = newMessage(
                            ResourceIdentifier.from(endpointName, tenant, deviceId),
                            sender.isRegistrationAssertionRequired(), ctx.request().uri(), contentType, payload,
                            tokenTracker.result(), HttpUtils.getTimeTilDisconnect(ctx));
                    customizeDownstreamMessage(downstreamMessage, ctx);

                    // first open the command receiver link (if needed)
                    return openCommandReceiverLink(ctx, tenant, deviceId, commandReceivedHandler)
                            .compose(closeLinkAndTimerHandler -> {
                                closeLinkAndTimerHandlerRef.set(closeLinkAndTimerHandler);

                                if (qosHeader == null) {
                                    return sender.send(downstreamMessage);
                                } else {
                                    return sender.sendAndWaitForOutcome(downstreamMessage);
                                }
                            });
                } else {
                    // this adapter is not enabled for the tenant
                    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
                }
            }).compose(delivery -> {
                LOG.trace(
                        "successfully processed message for device [tenantId: {}, deviceId: {}, endpoint: {}]",
                        tenant, deviceId, endpointName);
                metrics.incrementProcessedHttpMessages(endpointName, tenant);
                ctx.response().setStatusCode(HttpURLConnection.HTTP_ACCEPTED);
                downstreamMessageSent.set(true);

                // if no command timer was created, the request now can be responded
                if (closeLinkAndTimerHandlerRef.get() == null) {
                    ctx.response().end();
                }

                return Future.succeededFuture();

            }).recover(t -> {

                LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]",
                        tenant, deviceId, endpointName, t);

                cancelResponseTimer(closeLinkAndTimerHandlerRef);

                if (ClientErrorException.class.isInstance(t)) {
                    final ClientErrorException e = (ClientErrorException) t;
                    ctx.fail(e.getErrorCode());
                } else {
                    metrics.incrementUndeliverableHttpMessages(endpointName, tenant);
                    HttpUtils.serviceUnavailable(ctx, 2);
                }
                return Future.failedFuture(t);
            });
        }
    }
}

From source file:com.netflix.curator.TestSessionFailRetryLoop.java

@Test
public void testRetryStatic() throws Exception {
    Timing timing = new Timing();
    final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(),
            timing.session(), timing.connection(), null, new RetryOneTime(1));
    SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
    retryLoop.start();/*  w w w. j  a  v a2  s.  co m*/
    try {
        client.start();
        final AtomicBoolean secondWasDone = new AtomicBoolean(false);
        final AtomicBoolean firstTime = new AtomicBoolean(true);
        SessionFailRetryLoop.callWithRetry(client, SessionFailRetryLoop.Mode.RETRY, new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        if (firstTime.compareAndSet(true, false)) {
                            Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                            KillSession.kill(client.getZooKeeper(), server.getConnectString());
                            client.getZooKeeper();
                            client.blockUntilConnectedOrTimedOut();
                        }

                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        return null;
                    }
                });

                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        Assert.assertFalse(firstTime.get());
                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        secondWasDone.set(true);
                        return null;
                    }
                });
                return null;
            }
        });

        Assert.assertTrue(secondWasDone.get());
    } finally {
        retryLoop.close();
        IOUtils.closeQuietly(client);
    }
}