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

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

Introduction

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

Prototype

public final V get() 

Source Link

Document

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

Usage

From source file:no.barentswatch.fiskinfo.BaseActivity.java

/**
 * This functions creates a dialog which allows the user to export different
 * map layers.// w  ww  . j a va2s  . com
 * 
 * @param ActivityContext
 *            The context of the current activity.
 * @return True if the export succeeded, false otherwise.
 */
public boolean exportMapLayerToUser(Context activityContext) {
    LayoutInflater layoutInflater = getLayoutInflater();
    View view = layoutInflater.inflate(R.layout.dialog_export_metadata, (null));

    Button downloadButton = (Button) view.findViewById(R.id.metadataDownloadButton);
    Button cancelButton = (Button) view.findViewById(R.id.cancel_button);

    final AlertDialog builder = new AlertDialog.Builder(activityContext).create();
    builder.setTitle(R.string.map_export_metadata_title);
    builder.setView(view);
    final AtomicReference<String> selectedHeader = new AtomicReference<String>();
    final AtomicReference<String> selectedFormat = new AtomicReference<String>();
    final ExpandableListView expListView = (ExpandableListView) view
            .findViewById(R.id.exportMetadataMapServices);
    final List<String> listDataHeader = new ArrayList<String>();
    final HashMap<String, List<String>> listDataChild = new HashMap<String, List<String>>();
    final Map<String, String> nameToApiNameResolver = new HashMap<String, String>();

    JSONArray availableSubscriptions = getSharedCacheOfAvailableSubscriptions();
    if (availableSubscriptions == null) {
        availableSubscriptions = authenticatedGetRequestToBarentswatchAPIService(
                getString(R.string.my_page_geo_data_service));
        setSharedCacheOfAvailableSubscriptions(availableSubscriptions);
    }

    for (int i = 0; i < availableSubscriptions.length(); i++) {
        try {
            JSONObject currentSub = availableSubscriptions.getJSONObject(i);
            nameToApiNameResolver.put(currentSub.getString("Name"), currentSub.getString("ApiName"));
            listDataHeader.add(currentSub.getString("Name"));
            List<String> availableDownloadFormatsOfCurrentLayer = new ArrayList<String>();
            JSONArray availableFormats = currentSub.getJSONArray("Formats");
            for (int j = 0; j < availableFormats.length(); j++) {
                availableDownloadFormatsOfCurrentLayer.add(availableFormats.getString(j));
            }
            listDataChild.put(listDataHeader.get(i), availableDownloadFormatsOfCurrentLayer);

            System.out
                    .println("item: " + currentSub.getString("Name") + ", " + currentSub.getString("ApiName"));
        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("ExportMapLAyerToUser", "Invalid JSON returned from API CALL");
            return false;
        }
    }
    final ExpandableListAdapter listAdapter = new ExpandableListAdapter(activityContext, listDataHeader,
            listDataChild);
    expListView.setAdapter(listAdapter);

    // Listview on child click listener
    expListView.setOnChildClickListener(new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition,
                long id) {
            selectedHeader.set(nameToApiNameResolver.get(listDataHeader.get(groupPosition)));
            selectedHeader.set(listDataHeader.get(groupPosition));
            selectedFormat.set(listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition));

            LinearLayout currentlySelected = (LinearLayout) parent.findViewWithTag("currentlySelectedRow");
            if (currentlySelected != null) {
                currentlySelected.getChildAt(0).setBackgroundColor(Color.WHITE);
                currentlySelected.setTag(null);
            }

            ((LinearLayout) v).getChildAt(0).setBackgroundColor(Color.rgb(214, 214, 214));
            v.setTag("currentlySelectedRow");

            return true;
        }
    });

    downloadButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            new DownloadMapLayerFromBarentswatchApiInBackground()
                    .execute(nameToApiNameResolver.get(selectedHeader.get()), selectedFormat.get());
            builder.dismiss();
        }
    });

    cancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            builder.dismiss();
        }
    });

    builder.setCanceledOnTouchOutside(false);
    builder.show();

    return true;
}

From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java

private String launchProcess(final Settings settings, final PortGroup portGroup) {
    final AtomicBoolean ready = new AtomicBoolean();
    final AtomicReference<String> logPrefix = new AtomicReference<String>("");
    new Thread(new Runnable() {
        @Override/*from w w w.  ja  v a  2 s  . co  m*/
        public void run() {
            List<String> myArgs = new ArrayList<String>();
            myArgs.add(settings.javaBinary() == null ? JAVA_BIN : settings.javaBinary());
            myArgs.addAll(inheritedArgs);
            if (!settings.customClasspath()) {
                myArgs.addAll(classpathArgs.get());
            }
            if (settings.javaExportModules()) {
                myArgs.add("-XaddExports:javafx.web/com.sun.webkit.network=ALL-UNNAMED");
                myArgs.add("-XaddExports:javafx.web/com.sun.webkit.network.about=ALL-UNNAMED");
                myArgs.add("-XaddExports:javafx.web/com.sun.webkit.network.data=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.http=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.https=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.file=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.ftp=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.jar=ALL-UNNAMED");
                myArgs.add("-XaddExports:java.base/sun.net.www.protocol.mailto=ALL-UNNAMED");
                myArgs.add("-XaddExports:javafx.graphics/com.sun.glass.ui=ALL-UNNAMED");
                myArgs.add("-XaddExports:javafx.web/com.sun.javafx.webkit=ALL-UNNAMED");
                myArgs.add("-XaddExports:javafx.web/com.sun.webkit=ALL-UNNAMED");
            }
            myArgs.add("-Djava.io.tmpdir=" + tmpDir.getAbsolutePath());
            myArgs.add("-Djava.rmi.server.hostname=" + settings.host());
            myArgs.addAll(settings.javaOptions());
            myArgs.add(JBrowserDriverServer.class.getName());
            myArgs.add(Long.toString(portGroup.child));
            myArgs.add(Long.toString(portGroup.parent));
            myArgs.add(Long.toString(portGroup.parentAlt));
            try {
                new ProcessExecutor().addListener(new ProcessListener() {
                    @Override
                    public void afterStart(Process proc, ProcessExecutor executor) {
                        process.set(proc);
                    }
                }).redirectOutput(new LogOutputStream() {
                    boolean done = false;

                    @Override
                    protected void processLine(String line) {
                        if (line != null && !line.isEmpty()) {
                            if (!done) {
                                synchronized (ready) {
                                    if (line.startsWith("ready on ports ")) {
                                        String[] parts = line.substring("ready on ports ".length()).split("/");
                                        actualPortGroup.set(new PortGroup(Integer.parseInt(parts[0]),
                                                Integer.parseInt(parts[1]), Integer.parseInt(parts[2])));
                                        logPrefix.set(new StringBuilder().append("[Instance ")
                                                .append(sessionIdCounter.incrementAndGet()).append("][Port ")
                                                .append(actualPortGroup.get().child).append("]").toString());
                                        ready.set(true);
                                        ready.notifyAll();
                                        done = true;
                                    } else {
                                        log(settings.logger(), logPrefix.get(), line);
                                    }
                                }
                            } else {
                                log(settings.logger(), logPrefix.get(), line);
                            }
                        }
                    }
                }).redirectError(new LogOutputStream() {
                    @Override
                    protected void processLine(String line) {
                        log(settings.logger(), logPrefix.get(), line);
                    }
                }).destroyOnExit().command(myArgs).execute();
            } catch (Throwable t) {
                Util.handleException(t);
            }
            synchronized (ready) {
                ready.set(true);
                ready.notifyAll();
            }
        }
    }).start();
    synchronized (ready) {
        while (!ready.get()) {
            try {
                ready.wait();
                break;
            } catch (InterruptedException e) {
            }
        }
    }
    return logPrefix.get();
}

From source file:de.sainth.recipe.backend.db.repositories.RecipeRepository.java

public Recipe save(Recipe recipe) {
    AtomicReference<Recipe> bu = new AtomicReference<>();
    create.transaction(configuration -> {
        Long id = null;//from   w ww .  j av  a 2 s  . c o  m
        if (recipe.getId() != null) {
            id = using(configuration).select(RECIPES.ID).from(RECIPES).where(RECIPES.ID.eq(recipe.getId()))
                    .forUpdate().fetchOneInto(Long.class);
        }
        RecipesRecord recipeRecord;
        List<DirectionsRecord> directionsRecords = new ArrayList<>();
        List<IngredientsRecord> ingredientsRecords = new ArrayList<>();
        if (recipe.getId() == null || id == null) {
            recipeRecord = using(configuration)
                    .insertInto(RECIPES, RECIPES.NAME, RECIPES.COMMENT, RECIPES.DIFFICULTY, RECIPES.PORTIONS,
                            RECIPES.AUTHOR, RECIPES.PUBLIC_VISIBLE)
                    .values(recipe.getName(), recipe.getComment(), recipe.getDifficulty(), recipe.getPortions(),
                            recipe.getAuthor().getId(), recipe.isPublicVisible())
                    .returning().fetchOne();
            for (Ingredient ingredient : recipe.getIngredients()) {
                ingredientsRecords.add(using(configuration)
                        .insertInto(INGREDIENTS, INGREDIENTS.AMOUNT, INGREDIENTS.CATEGORY, INGREDIENTS.FOOD,
                                INGREDIENTS.RECIPE)
                        .values(ingredient.getAmount(), ingredient.getCategory(), ingredient.getFood().getId(),
                                recipeRecord.getId())
                        .returning().fetchOne());
            }
            for (Direction direction : recipe.getDirections()) {
                directionsRecords.add(using(configuration)
                        .insertInto(DIRECTIONS, DIRECTIONS.POSITION, DIRECTIONS.DESCRIPTION,
                                DIRECTIONS.DURATION, DIRECTIONS.RECIPE)
                        .values(direction.getPosition(), direction.getDescription(), direction.getDuration(),
                                recipeRecord.getId())
                        .returning().fetchOne());
            }
        } else {
            recipeRecord = using(configuration).update(RECIPES).set(RECIPES.NAME, recipe.getName())
                    .set(RECIPES.COMMENT, recipe.getComment()).set(RECIPES.DIFFICULTY, recipe.getDifficulty())
                    .set(RECIPES.PORTIONS, recipe.getPortions()).set(RECIPES.AUTHOR, recipe.getAuthor().getId())
                    .set(RECIPES.PUBLIC_VISIBLE, recipe.isPublicVisible()).where(RECIPES.ID.eq(id)).returning()
                    .fetchOne();
            using(configuration).delete(INGREDIENTS).where(INGREDIENTS.RECIPE.eq(id));
            for (Ingredient ingredient : recipe.getIngredients()) {
                ingredientsRecords.add(using(configuration)
                        .insertInto(INGREDIENTS, INGREDIENTS.AMOUNT, INGREDIENTS.CATEGORY, INGREDIENTS.FOOD,
                                INGREDIENTS.RECIPE)
                        .values(ingredient.getAmount(), ingredient.getCategory(), ingredient.getFood().getId(),
                                recipeRecord.getId())
                        .returning().fetchOne());
            }
            using(configuration).delete(DIRECTIONS).where(DIRECTIONS.RECIPE.eq(id));
            for (Direction direction : recipe.getDirections()) {
                directionsRecords.add(using(configuration)
                        .insertInto(DIRECTIONS, DIRECTIONS.POSITION, DIRECTIONS.DESCRIPTION,
                                DIRECTIONS.DURATION, DIRECTIONS.RECIPE)
                        .values(direction.getPosition(), direction.getDescription(), direction.getDuration(),
                                recipeRecord.getId())
                        .returning().fetchOne());
            }
        }
        String username = using(configuration).select(USERS.NAME).from(USERS)
                .where(USERS.ID.eq(recipeRecord.getAuthor())).fetchOneInto(String.class);

        List<Ingredient> ingredients = ingredientsRecords.stream().map(
                i -> new Ingredient(i.getAmount(), i.getCategory(), selectFood(configuration, i.getFood())))
                .collect(Collectors.toList());
        List<Direction> directions = directionsRecords.stream()
                .map(d -> new Direction(d.getId(), d.getPosition(), d.getDescription(), d.getDuration()))
                .collect(Collectors.toList());
        bu.set(new Recipe(recipeRecord.getId(), recipeRecord.getName(), recipeRecord.getComment(),
                recipeRecord.getDifficulty(), recipeRecord.getPortions(), recipeRecord.getPublicVisible(),
                new User(recipeRecord.getAuthor(), username), ingredients, directions));
    });

    return bu.get();
}

From source file:org.apache.brooklyn.location.jclouds.JcloudsLocation.java

protected LoginCredentials waitForWinRmAvailable(final ComputeService computeService, final NodeMetadata node,
        Optional<HostAndPort> hostAndPortOverride, List<LoginCredentials> credentialsToTry, ConfigBag setup) {
    String waitForWinrmAvailable = setup.get(WAIT_FOR_WINRM_AVAILABLE);
    checkArgument(!"false".equalsIgnoreCase(waitForWinrmAvailable),
            "waitForWinRmAvailable called despite waitForWinRmAvailable=%s", waitForWinrmAvailable);
    Duration timeout = null;// www  . ja va2  s  .com
    try {
        timeout = Duration.parse(waitForWinrmAvailable);
    } catch (Exception e) {
        // TODO will this just be a NumberFormatException? If so, catch that specificially
        // normal if 'true'; just fall back to default
        Exceptions.propagateIfFatal(e);
    }
    if (timeout == null) {
        timeout = Duration.parse(WAIT_FOR_WINRM_AVAILABLE.getDefaultValue());
    }

    Set<String> users = Sets.newLinkedHashSet();
    for (LoginCredentials creds : credentialsToTry) {
        users.add(creds.getUser());
    }
    String user = (users.size() == 1) ? Iterables.getOnlyElement(users)
            : "{" + Joiner.on(",").join(users) + "}";
    String vmIp = hostAndPortOverride.isPresent() ? hostAndPortOverride.get().getHostText()
            : getFirstReachableAddress(node, setup);
    if (vmIp == null)
        LOG.warn("Unable to extract IP for " + node + " (" + setup.getDescription()
                + "): subsequent connection attempt will likely fail");
    int vmPort = hostAndPortOverride.isPresent() ? hostAndPortOverride.get().getPortOrDefault(5985) : 5985;

    String connectionDetails = user + "@" + vmIp + ":" + vmPort;
    final HostAndPort hostAndPort = hostAndPortOverride.isPresent() ? hostAndPortOverride.get()
            : HostAndPort.fromParts(vmIp, vmPort);
    final AtomicReference<LoginCredentials> credsSuccessful = new AtomicReference<LoginCredentials>();

    // Don't use config that relates to the final user credentials (those have nothing to do
    // with the initial credentials of the VM returned by the cloud provider).
    // The createTemporaryWinRmMachineLocation deals with removing that.
    ConfigBag winrmProps = ConfigBag.newInstanceCopying(setup);

    final Map<WinRmMachineLocation, LoginCredentials> machinesToTry = Maps.newLinkedHashMap();
    for (LoginCredentials creds : credentialsToTry) {
        machinesToTry.put(createTemporaryWinRmMachineLocation(hostAndPort, creds, winrmProps), creds);
    }
    try {
        Callable<Boolean> checker = new Callable<Boolean>() {
            public Boolean call() {
                for (Map.Entry<WinRmMachineLocation, LoginCredentials> entry : machinesToTry.entrySet()) {
                    WinRmMachineLocation machine = entry.getKey();
                    WinRmToolResponse response = machine.executeCommand(
                            ImmutableMap.of(WinRmTool.PROP_EXEC_TRIES.getName(), 1),
                            ImmutableList.of("echo testing"));
                    boolean success = (response.getStatusCode() == 0);
                    if (success) {
                        credsSuccessful.set(entry.getValue());
                        return true;
                    }
                }
                return false;
            }
        };

        waitForReachable(checker, connectionDetails, credentialsToTry, setup, timeout);
    } finally {
        for (WinRmMachineLocation machine : machinesToTry.keySet()) {
            getManagementContext().getLocationManager().unmanage(machine);
        }
    }

    return credsSuccessful.get();
}

From source file:com.networknt.client.oauth.OauthHelper.java

/**
 * Get a signed JWT token from token service to ensure that nobody can modify the payload when the token
 * is passed from service to service. Unlike the access JWT token, this token is ensure the data integrity
 * with signature./* www.  ja va2 s . c  o m*/
 *
 * @param signRequest SignRequest that is constructed from the client.yml sign section
 * @param envTag environment tag that is used for service lookup if serviceId is used.
 * @return Result that contains TokenResponse or error status when failed.
 */
public static Result<TokenResponse> getSignResult(SignRequest signRequest, String envTag) {
    final AtomicReference<Result<TokenResponse>> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        if (signRequest.getServerUrl() != null) {
            connection = client.connect(new URI(signRequest.getServerUrl()), Http2Client.WORKER,
                    Http2Client.SSL, Http2Client.BUFFER_POOL,
                    signRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                            : OptionMap.EMPTY)
                    .get();
        } else if (signRequest.getServiceId() != null) {
            Cluster cluster = SingletonServiceFactory.getBean(Cluster.class);
            String url = cluster.serviceToUrl("https", signRequest.getServiceId(), envTag, null);
            connection = client
                    .connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL,
                            signRequest.enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
                                    : OptionMap.EMPTY)
                    .get();
        } else {
            // both server_url and serviceId are empty in the config.
            logger.error("Error: both server_url and serviceId are not configured in client.yml for "
                    + signRequest.getClass());
            throw new ClientException("both server_url and serviceId are not configured in client.yml for "
                    + signRequest.getClass());
        }
    } catch (Exception e) {
        logger.error("cannot establish connection:", e);
        return Failure.of(new Status(ESTABLISH_CONNECTION_ERROR,
                signRequest.getServerUrl() != null ? signRequest.getServerUrl() : signRequest.getServiceId()));
    }

    try {
        Map<String, Object> map = new HashMap<>();
        map.put("expires", signRequest.getExpires());
        map.put("payload", signRequest.getPayload());
        String requestBody = Config.getInstance().getMapper().writeValueAsString(map);
        connection.getIoThread().execute(() -> {
            final ClientRequest request = new ClientRequest().setMethod(Methods.POST)
                    .setPath(signRequest.getUri());
            request.getRequestHeaders().put(Headers.HOST, "localhost");
            request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
            request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded");
            request.getRequestHeaders().put(Headers.AUTHORIZATION,
                    getBasicAuthHeader(signRequest.getClientId(), signRequest.getClientSecret()));
            connection.sendRequest(request, new ClientCallback<ClientExchange>() {
                @Override
                public void completed(ClientExchange result) {
                    new StringWriteChannelListener(requestBody).setup(result.getRequestChannel());
                    result.setResponseListener(new ClientCallback<ClientExchange>() {
                        @Override
                        public void completed(ClientExchange result) {
                            new StringReadChannelListener(Http2Client.BUFFER_POOL) {

                                @Override
                                protected void stringDone(String string) {

                                    logger.debug("getToken response = " + string);
                                    reference.set(handleResponse(getContentTypeFromExchange(result), string));
                                    latch.countDown();
                                }

                                @Override
                                protected void error(IOException e) {
                                    logger.error("IOException:", e);
                                    reference.set(Failure.of(new Status(FAIL_TO_SEND_REQUEST)));
                                    latch.countDown();
                                }
                            }.setup(result.getResponseChannel());
                        }

                        @Override
                        public void failed(IOException e) {
                            logger.error("IOException:", e);
                            reference.set(Failure.of(new Status(FAIL_TO_SEND_REQUEST)));
                            latch.countDown();
                        }
                    });
                }

                @Override
                public void failed(IOException e) {
                    logger.error("IOException:", e);
                    reference.set(Failure.of(new Status(FAIL_TO_SEND_REQUEST)));
                    latch.countDown();
                }
            });
        });

        latch.await(signRequest.getTimeout(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        return Failure.of(new Status(FAIL_TO_SEND_REQUEST));
    } finally {
        IoUtils.safeClose(connection);
    }

    //if reference.get() is null at this point, mostly likely couldn't get token within latch.await() timeout.
    return reference.get() == null ? Failure.of(new Status(GET_TOKEN_TIMEOUT)) : reference.get();
}

From source file:org.elasticsearch.client.sniff.SnifferTests.java

/**
 * Test behaviour when a bunch of onFailure sniffing rounds are triggered in parallel. Each run will always
 * schedule a subsequent afterFailure round. Also, for each onFailure round that starts, the net scheduled round
 * (either afterFailure or ordinary) gets cancelled.
 *///from  ww  w . j  a  v  a2 s  .c  o  m
public void testSniffOnFailure() throws Exception {
    RestClient restClient = mock(RestClient.class);
    CountingHostsSniffer hostsSniffer = new CountingHostsSniffer();
    final AtomicBoolean initializing = new AtomicBoolean(true);
    final long sniffInterval = randomLongBetween(1, Long.MAX_VALUE);
    final long sniffAfterFailureDelay = randomLongBetween(1, Long.MAX_VALUE);
    int minNumOnFailureRounds = randomIntBetween(5, 10);
    final CountDownLatch initializingLatch = new CountDownLatch(1);
    final Set<Sniffer.ScheduledTask> ordinaryRoundsTasks = new CopyOnWriteArraySet<>();
    final AtomicReference<Future<?>> initializingFuture = new AtomicReference<>();
    final Set<Sniffer.ScheduledTask> onFailureTasks = new CopyOnWriteArraySet<>();
    final Set<Sniffer.ScheduledTask> afterFailureTasks = new CopyOnWriteArraySet<>();
    final AtomicBoolean onFailureCompleted = new AtomicBoolean(false);
    final CountDownLatch completionLatch = new CountDownLatch(1);
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    try {
        Scheduler scheduler = new Scheduler() {
            @Override
            public Future<?> schedule(final Sniffer.Task task, long delayMillis) {
                if (initializing.compareAndSet(true, false)) {
                    assertEquals(0L, delayMillis);
                    Future<?> future = executor.submit(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                task.run();
                            } finally {
                                //we need to make sure that the sniffer is initialized, so the sniffOnFailure
                                //call does what it needs to do. Otherwise nothing happens until initialized.
                                initializingLatch.countDown();
                            }
                        }
                    });
                    assertTrue(initializingFuture.compareAndSet(null, future));
                    return future;
                }
                if (delayMillis == 0L) {
                    Future<?> future = executor.submit(task);
                    onFailureTasks.add(new Sniffer.ScheduledTask(task, future));
                    return future;
                }
                if (delayMillis == sniffAfterFailureDelay) {
                    Future<?> future = scheduleOrSubmit(task);
                    afterFailureTasks.add(new Sniffer.ScheduledTask(task, future));
                    return future;
                }

                assertEquals(sniffInterval, delayMillis);
                assertEquals(sniffInterval, task.nextTaskDelay);

                if (onFailureCompleted.get() && onFailureTasks.size() == afterFailureTasks.size()) {
                    completionLatch.countDown();
                    return mock(Future.class);
                }

                Future<?> future = scheduleOrSubmit(task);
                ordinaryRoundsTasks.add(new Sniffer.ScheduledTask(task, future));
                return future;
            }

            private Future<?> scheduleOrSubmit(Sniffer.Task task) {
                if (randomBoolean()) {
                    return executor.schedule(task, randomLongBetween(0L, 200L), TimeUnit.MILLISECONDS);
                } else {
                    return executor.submit(task);
                }
            }

            @Override
            public void shutdown() {
            }
        };
        final Sniffer sniffer = new Sniffer(restClient, hostsSniffer, scheduler, sniffInterval,
                sniffAfterFailureDelay);
        assertTrue("timeout waiting for sniffer to get initialized",
                initializingLatch.await(1000, TimeUnit.MILLISECONDS));

        ExecutorService onFailureExecutor = Executors.newFixedThreadPool(randomIntBetween(5, 20));
        Set<Future<?>> onFailureFutures = new CopyOnWriteArraySet<>();
        try {
            //with tasks executing quickly one after each other, it is very likely that the onFailure round gets skipped
            //as another round is already running. We retry till enough runs get through as that's what we want to test.
            while (onFailureTasks.size() < minNumOnFailureRounds) {
                onFailureFutures.add(onFailureExecutor.submit(new Runnable() {
                    @Override
                    public void run() {
                        sniffer.sniffOnFailure();
                    }
                }));
            }
            assertThat(onFailureFutures.size(), greaterThanOrEqualTo(minNumOnFailureRounds));
            for (Future<?> onFailureFuture : onFailureFutures) {
                assertNull(onFailureFuture.get());
            }
            onFailureCompleted.set(true);
        } finally {
            onFailureExecutor.shutdown();
            onFailureExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS);
        }

        assertFalse(initializingFuture.get().isCancelled());
        assertTrue(initializingFuture.get().isDone());
        assertNull(initializingFuture.get().get());

        assertTrue("timeout waiting for sniffing rounds to be completed",
                completionLatch.await(1000, TimeUnit.MILLISECONDS));
        assertThat(onFailureTasks.size(), greaterThanOrEqualTo(minNumOnFailureRounds));
        assertEquals(onFailureTasks.size(), afterFailureTasks.size());

        for (Sniffer.ScheduledTask onFailureTask : onFailureTasks) {
            assertFalse(onFailureTask.future.isCancelled());
            assertTrue(onFailureTask.future.isDone());
            assertNull(onFailureTask.future.get());
            assertTrue(onFailureTask.task.hasStarted());
            assertFalse(onFailureTask.task.isSkipped());
        }

        int cancelledTasks = 0;
        int completedTasks = onFailureTasks.size() + 1;
        for (Sniffer.ScheduledTask afterFailureTask : afterFailureTasks) {
            if (assertTaskCancelledOrCompleted(afterFailureTask)) {
                completedTasks++;
            } else {
                cancelledTasks++;
            }
        }

        assertThat(ordinaryRoundsTasks.size(), greaterThan(0));
        for (Sniffer.ScheduledTask task : ordinaryRoundsTasks) {
            if (assertTaskCancelledOrCompleted(task)) {
                completedTasks++;
            } else {
                cancelledTasks++;
            }
        }
        assertEquals(onFailureTasks.size(), cancelledTasks);

        assertEquals(completedTasks, hostsSniffer.runs.get());
        int setHostsRuns = hostsSniffer.runs.get() - hostsSniffer.failures.get() - hostsSniffer.emptyList.get();
        verify(restClient, times(setHostsRuns)).setHosts(Matchers.<HttpHost>anyVararg());
        verifyNoMoreInteractions(restClient);
    } finally {
        executor.shutdown();
        executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
    }
}

From source file:org.apache.brooklyn.location.jclouds.JcloudsLocation.java

protected LoginCredentials waitForSshable(final ComputeService computeService, final NodeMetadata node,
        Optional<HostAndPort> hostAndPortOverride, List<LoginCredentials> credentialsToTry, ConfigBag setup) {
    String waitForSshable = setup.get(WAIT_FOR_SSHABLE);
    checkArgument(!"false".equalsIgnoreCase(waitForSshable),
            "waitForReachable called despite waitForSshable=%s for %s", waitForSshable, node);
    checkArgument(credentialsToTry.size() > 0, "waitForReachable called without credentials for %s", node);

    Duration timeout = null;// www. j  a  va2 s  .  c o m
    try {
        timeout = Duration.parse(waitForSshable);
    } catch (Exception e) {
        // normal if 'true'; just fall back to default
    }
    if (timeout == null) {
        timeout = Duration.parse(WAIT_FOR_SSHABLE.getDefaultValue());
    }

    Set<String> users = Sets.newLinkedHashSet();
    for (LoginCredentials creds : credentialsToTry) {
        users.add(creds.getUser());
    }
    String user = (users.size() == 1) ? Iterables.getOnlyElement(users)
            : "{" + Joiner.on(",").join(users) + "}";
    String vmIp = hostAndPortOverride.isPresent() ? hostAndPortOverride.get().getHostText()
            : getFirstReachableAddress(node, setup);
    if (vmIp == null)
        LOG.warn("Unable to extract IP for " + node + " (" + setup.getDescription()
                + "): subsequent connection attempt will likely fail");
    int vmPort = hostAndPortOverride.isPresent() ? hostAndPortOverride.get().getPortOrDefault(22) : 22;

    String connectionDetails = user + "@" + vmIp + ":" + vmPort;
    final HostAndPort hostAndPort = hostAndPortOverride.isPresent() ? hostAndPortOverride.get()
            : HostAndPort.fromParts(vmIp, vmPort);
    final AtomicReference<LoginCredentials> credsSuccessful = new AtomicReference<LoginCredentials>();

    // Don't use config that relates to the final user credentials (those have nothing to do 
    // with the initial credentials of the VM returned by the cloud provider).
    ConfigBag sshProps = ConfigBag.newInstanceCopying(setup);
    sshProps.remove("password");
    sshProps.remove("privateKeyData");
    sshProps.remove("privateKeyFile");
    sshProps.remove("privateKeyPassphrase");

    final Map<SshMachineLocation, LoginCredentials> machinesToTry = Maps.newLinkedHashMap();
    for (LoginCredentials creds : credentialsToTry) {
        machinesToTry.put(createTemporarySshMachineLocation(hostAndPort, creds, sshProps), creds);
    }
    try {
        Callable<Boolean> checker = new Callable<Boolean>() {
            public Boolean call() {
                for (Map.Entry<SshMachineLocation, LoginCredentials> entry : machinesToTry.entrySet()) {
                    SshMachineLocation machine = entry.getKey();
                    int exitstatus = machine
                            .execScript(
                                    ImmutableMap.of(SshTool.PROP_SSH_TRIES_TIMEOUT.getName(),
                                            Duration.THIRTY_SECONDS.toMilliseconds(),
                                            SshTool.PROP_SSH_TRIES.getName(), 1),
                                    "check-connectivity", ImmutableList.of("true"));
                    boolean success = (exitstatus == 0);
                    if (success) {
                        credsSuccessful.set(entry.getValue());
                        return true;
                    }
                }
                return false;
            }
        };

        waitForReachable(checker, connectionDetails, credentialsToTry, setup, timeout);
    } finally {
        for (SshMachineLocation machine : machinesToTry.keySet()) {
            getManagementContext().getLocationManager().unmanage(machine);
            Streams.closeQuietly(machine);
        }
    }

    return credsSuccessful.get();
}

From source file:cl.gisred.android.CatastroActivity.java

private void cerrarFormCrear(boolean bSave, View v) {
    if (bSave) {/*from w w  w  .  j  ava2  s . co m*/

        final AtomicReference<String> resp = new AtomicReference<>("");

        if (!validarForm(v)) {
            DialogoConfirmacion oDialog = new DialogoConfirmacion();
            oDialog.show(getFragmentManager(), "tagAlert");
            return;
        } else {
            View vAction = getLayoutValidate(v);
            Map<String, Object> objectMap = new HashMap<>();
            for (View view : vAction.getTouchables()) {

                if (view.getClass().getGenericSuperclass().equals(EditText.class)) {
                    EditText oText = (EditText) view;

                    if (oText.getId() == R.id.txtProducto) {
                        String oVal = (oText.getText().toString().isEmpty()) ? "0" : oText.getText().toString();
                        objectMap.put("producto", oVal);
                    }
                    if (oText.getId() == R.id.txtPoste)
                        objectMap.put("poste", oText.getText().toString());
                    if (oText.getId() == R.id.txtDireccion)
                        objectMap.put("direccion", oText.getText().toString());

                } else if (view.getClass().getGenericSuperclass().equals(Spinner.class)) {
                    Spinner oSpinner = (Spinner) view;
                    String sValue = oSpinner.getSelectedItem().toString();

                    if (oSpinner.getId() == R.id.spinnerEstado)
                        objectMap.put("estado", sValue);
                    else if (oSpinner.getId() == R.id.spinnerTipoEdif)
                        objectMap.put("tipo_edificacion", sValue);
                }
            }

            Graphic newFeatureGraphic = new Graphic(oUbicacion, null, objectMap);
            Graphic[] adds = { newFeatureGraphic };
            LyAddCatastro.applyEdits(adds, null, null, new CallbackListener<FeatureEditResult[][]>() {
                @Override
                public void onCallback(FeatureEditResult[][] featureEditResults) {
                    if (featureEditResults[0] != null) {
                        if (featureEditResults[0][0] != null && featureEditResults[0][0].isSuccess()) {

                            resp.set("Guardado Correctamente Id: " + featureEditResults[0][0].getObjectId());

                            runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    Util.showConfirmation(CatastroActivity.this, resp.get());
                                }
                            });
                        }
                    }
                }

                @Override
                public void onError(Throwable throwable) {
                    resp.set("Error al ingresar: " + throwable.getLocalizedMessage());
                    Log.w("onError", resp.get());

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Toast.makeText(CatastroActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }
    }

    bMapTap = false;
    oUbicacion = null;

    if (mBusquedaLayer != null && myMapView.getLayerByID(mBusquedaLayer.getID()) != null)
        myMapView.removeLayer(mBusquedaLayer);

    if (mUbicacionLayer != null && myMapView.getLayerByID(mUbicacionLayer.getID()) != null)
        myMapView.removeLayer(mUbicacionLayer);

    if (mSeleccionLayer != null && myMapView.getLayerByID(mSeleccionLayer.getID()) != null)
        myMapView.removeLayer(mSeleccionLayer);

    if (bVerCapas)
        toogleCapas(fabVerCapas);

    menuMultipleActions.setVisibility(View.VISIBLE);
    menuCatastroActions.setVisibility(View.VISIBLE);
    fabShowForm.setVisibility(View.GONE);
    formCrear.dismiss();

    if (LyAddCatastro != null)
        LyAddCatastro.setVisible(true);
}

From source file:com.jivesoftware.os.upena.deployable.UpenaMain.java

public AmzaService startAmza(String workingDir, AmzaStats amzaStats, BAInterner baInterner, int writerId,
        RingHost ringHost, RingMember ringMember, OAuthSigner authSigner,
        TenantAwareHttpClient<String> systemTakeClient, TenantAwareHttpClient<String> stripedTakeClient,
        TenantAwareHttpClient<String> ringClient, AtomicReference<Callable<RingTopology>> topologyProvider,
        String clusterDiscoveryName, String multicastGroup, int multicastPort) throws Exception {

    //Deployable deployable = new Deployable(new String[0]);

    SnowflakeIdPacker idPacker = new SnowflakeIdPacker();
    JiveEpochTimestampProvider timestampProvider = new JiveEpochTimestampProvider();

    SickThreads sickThreads = new SickThreads();
    SickPartitions sickPartitions = new SickPartitions();
    //deployable.addHealthCheck(new SickThreadsHealthCheck(deployable.config(AmzaSickThreadsHealthConfig.class), sickThreads));
    //deployable.addHealthCheck(new SickPartitionsHealthCheck(sickPartitions));

    TimestampedOrderIdProvider orderIdProvider = new OrderIdProviderImpl(new ConstantWriterIdProvider(writerId),
            idPacker, timestampProvider);

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, false);

    PartitionPropertyMarshaller partitionPropertyMarshaller = new PartitionPropertyMarshaller() {

        @Override//from   w w w  .  ja v a2  s  .c o m
        public PartitionProperties fromBytes(byte[] bytes) {
            try {
                return mapper.readValue(bytes, PartitionProperties.class);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public byte[] toBytes(PartitionProperties partitionProperties) {
            try {
                return mapper.writeValueAsBytes(partitionProperties);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
    };

    BinaryPrimaryRowMarshaller primaryRowMarshaller = new BinaryPrimaryRowMarshaller(); // hehe you cant change this :)
    BinaryHighwaterRowMarshaller highwaterRowMarshaller = new BinaryHighwaterRowMarshaller(baInterner);

    RowsTakerFactory systemRowsTakerFactory = () -> new HttpRowsTaker(amzaStats, systemTakeClient, mapper,
            baInterner);
    RowsTakerFactory rowsTakerFactory = () -> new HttpRowsTaker(amzaStats, stripedTakeClient, mapper,
            baInterner);

    AvailableRowsTaker availableRowsTaker = new HttpAvailableRowsTaker(ringClient, baInterner, mapper);
    AquariumStats aquariumStats = new AquariumStats();

    QuorumTimeouts quorumTimeoutsConfig = bindDefault(QuorumTimeouts.class);
    HealthTimer quorumLatency = HealthFactory.getHealthTimer(QuorumLatency.class, TimerHealthChecker.FACTORY);

    TriggerTimeoutHealthCheck quorumTimeoutHealthCheck = new TriggerTimeoutHealthCheck(
            () -> amzaStats.getGrandTotal().quorumTimeouts.longValue(), quorumTimeoutsConfig);
    //deployable.addHealthCheck(quorumTimeoutHealthCheck);

    //LABPointerIndexConfig amzaLabConfig = deployable.config(LABPointerIndexConfig.class);
    LABPointerIndexConfig amzaLabConfig = bindDefault(UpenaLABPointerIndexConfig.class);

    AmzaServiceConfig amzaServiceConfig = new AmzaServiceConfig();
    amzaServiceConfig.systemRingSize = 1;
    amzaServiceConfig.workingDirectories = new String[] { new File(workingDir, "state").getAbsolutePath() };
    amzaServiceConfig.aquariumLivelinessFeedEveryMillis = 5_000;
    amzaServiceConfig.checkIfCompactionIsNeededIntervalInMillis = 30_000;
    amzaServiceConfig.deltaMergeThreads = 2;
    amzaServiceConfig.maxUpdatesBeforeDeltaStripeCompaction = 10_000;
    amzaServiceConfig.numberOfTakerThreads = 2;
    amzaServiceConfig.hardFsync = true;
    amzaServiceConfig.takeSlowThresholdInMillis = 1_000;
    amzaServiceConfig.rackDistributionEnabled = false;

    Set<RingMember> blacklistRingMembers = Sets.newHashSet();
    AmzaService amzaService = new AmzaServiceInitializer().initialize(amzaServiceConfig, baInterner,
            aquariumStats, amzaStats, quorumLatency, () -> {
                Callable<RingTopology> ringTopologyCallable = topologyProvider.get();
                if (ringTopologyCallable != null) {
                    try {
                        return ringTopologyCallable.call().entries.size();
                    } catch (Exception x) {
                        LOG.error("issue determining system ring size", x);
                    }
                }
                return -1;
            }, sickThreads, sickPartitions, primaryRowMarshaller, highwaterRowMarshaller, ringMember, ringHost,
            blacklistRingMembers, orderIdProvider, idPacker, partitionPropertyMarshaller,
            (workingIndexDirectories, indexProviderRegistry, ephemeralRowIOProvider, persistentRowIOProvider,
                    partitionStripeFunction) -> {

                indexProviderRegistry
                        .register(
                                new BerkeleyDBWALIndexProvider(BerkeleyDBWALIndexProvider.INDEX_CLASS_NAME,
                                        partitionStripeFunction, workingIndexDirectories),
                                persistentRowIOProvider);

                indexProviderRegistry.register(new LABPointerIndexWALIndexProvider(amzaLabConfig,
                        LABPointerIndexWALIndexProvider.INDEX_CLASS_NAME, partitionStripeFunction,
                        workingIndexDirectories), persistentRowIOProvider);
            }, availableRowsTaker, systemRowsTakerFactory, rowsTakerFactory,
            Optional.<TakeFailureListener>absent(), rowsChanged -> {
            });

    topologyProvider.set(() -> amzaService.getRingReader().getRing(AmzaRingReader.SYSTEM_RING, -1));

    amzaService.start(ringMember, ringHost);
    LOG.info("-----------------------------------------------------------------------");
    LOG.info("|      Amza Service Started");
    LOG.info("-----------------------------------------------------------------------");

    if (clusterDiscoveryName != null) {
        AmzaDiscovery amzaDiscovery = new AmzaDiscovery(amzaService.getRingReader(),
                amzaService.getRingWriter(), clusterDiscoveryName, multicastGroup, multicastPort,
                new AtomicInteger(amzaService.getRingReader().getRingSize(AmzaRingReader.SYSTEM_RING, -1)) // Grrr
        );
        amzaDiscovery.start();
        LOG.info("-----------------------------------------------------------------------");
        LOG.info("|      Amza Service Discovery Online");
        LOG.info("-----------------------------------------------------------------------");
    } else {
        LOG.info("-----------------------------------------------------------------------");
        LOG.info("|     Amza Service is in manual Discovery mode.  No cluster discovery name was specified");
        LOG.info("-----------------------------------------------------------------------");
    }

    return amzaService;
}

From source file:cl.gisred.android.LectorInspActivity.java

private void cerrarDialogCrear(boolean bSave, @Nullable View viewDialog) {
    final AtomicReference<String> resp = new AtomicReference<>("");

    if (bSave) {//  w w w.  ja  v a 2s. c o m
        if (!validarVista(viewDialog)) {
            DialogoConfirmacion oDialog = new DialogoConfirmacion();
            oDialog.show(getFragmentManager(), "tagAlert");
            return;
        } else {
            switch (idResLayoutSelect) {
            case R.layout.dialog_poste:
                oLyAddGraphs = LyAddPoste;
                break;
            case R.layout.dialog_direccion:
                oLyAddGraphs = LyAddDireccion;
                break;
            case R.layout.dialog_cliente:
                oLyAddGraphs = LyAddCliente;
                break;
            case R.layout.dialog_cliente_cnr:
                oLyAddGraphs = LyAddClienteCnr;
                break;
            }

            if (oLyAddGraphs != null) {
                View oView = getLayoutValidate(viewDialog);
                Util oUtil = new Util(oUbicacion);

                ArrayList<Map<String, Object>> oAttrToSave = oUtil.getAttrAddByView(oView, idResLayoutSelect,
                        empresa);

                Map<String, Object> attributes = oAttrToSave.get(0);
                Graphic newFeatureGraphic = new Graphic(oUbicacion, null, attributes);
                Graphic[] adds = { newFeatureGraphic };

                if (idResLayoutSelect == R.layout.dialog_cliente_cnr
                        || idResLayoutSelect == R.layout.dialog_cliente) {
                    addsUnion = Util.addAttrUnionPoint(oAttrToSave, oUbicacion);
                }

                oLyAddGraphs.applyEdits(adds, null, null, new CallbackListener<FeatureEditResult[][]>() {

                    @Override
                    public void onCallback(FeatureEditResult[][] featureEditResults) {
                        if (featureEditResults[0] != null) {
                            if (featureEditResults[0][0] != null && featureEditResults[0][0].isSuccess()) {

                                resp.set(
                                        "Guardado Correctamente Id: " + featureEditResults[0][0].getObjectId());

                                if (idResLayoutSelect == R.layout.dialog_cliente_cnr
                                        || idResLayoutSelect == R.layout.dialog_cliente)
                                    LyAddUnion.applyEdits(addsUnion, null, null, callBackUnion());

                                runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        Util.showConfirmation(LectorInspActivity.this, resp.get());
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        resp.set("Error al grabar: " + throwable.getLocalizedMessage());
                        Log.w("onError", resp.get());

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(LectorInspActivity.this, resp.get(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                });
            }
        }
    } else {
        resp.set("Cancelado");
        Toast.makeText(LectorInspActivity.this, resp.get(), Toast.LENGTH_LONG).show();
    }

    bMapTap = false;

    if (mBusquedaLayer != null && myMapView.getLayerByID(mBusquedaLayer.getID()) != null)
        myMapView.removeLayer(mBusquedaLayer);

    if (mUbicacionLayer != null && myMapView.getLayerByID(mUbicacionLayer.getID()) != null)
        myMapView.removeLayer(mUbicacionLayer);

    if (mSeleccionLayer != null && myMapView.getLayerByID(mSeleccionLayer.getID()) != null)
        myMapView.removeLayer(mSeleccionLayer);

    oUbicacion = null;
    if (bVerCapas)
        toogleCapas(fabVerCapas);
    //setLayerAddToggle(false);
    if (bIngCliente)
        menuMultipleActions.setVisibility(View.VISIBLE);
    fabShowDialog.setVisibility(View.GONE);
    dialogCrear.dismiss();
    if (oLyAddGraphs != null)
        oLyAddGraphs.setVisible(true);
}