List of usage examples for java.util.concurrent.atomic AtomicReference get
public final V get()
From source file:org.apache.bookkeeper.client.MetadataUpdateLoopTest.java
/** * Hammer test. Kick off a lot of metadata updates concurrently with a ledger manager * that runs callbacks on random threads, and validate all updates complete eventually, * and that the final metadata reflects all the updates. *///from w w w. j av a2 s . c o m @Test public void testHammer() throws Exception { try (NonDeterministicMockLedgerManager lm = new NonDeterministicMockLedgerManager()) { long ledgerId = 1234L; int ensembleSize = 100; List<BookieSocketAddress> initialEnsemble = IntStream.range(0, ensembleSize) .mapToObj((i) -> address(String.format("0.0.0.%d:3181", i))).collect(Collectors.toList()); LedgerMetadata initMeta = LedgerMetadataBuilder.create().withEnsembleSize(ensembleSize) .withDigestType(DigestType.CRC32C).withPassword(new byte[0]) .newEnsembleEntry(0L, initialEnsemble).build(); Versioned<LedgerMetadata> writtenMetadata = lm.createLedgerMetadata(ledgerId, initMeta).get(); AtomicReference<Versioned<LedgerMetadata>> reference = new AtomicReference<>(writtenMetadata); List<BookieSocketAddress> replacementBookies = IntStream.range(0, ensembleSize) .mapToObj((i) -> address(String.format("0.0.%d.1:3181", i))).collect(Collectors.toList()); List<CompletableFuture<Versioned<LedgerMetadata>>> loops = IntStream.range(0, ensembleSize) .mapToObj((i) -> new MetadataUpdateLoop(lm, ledgerId, reference::get, (currentMetadata) -> currentMetadata.getEnsembleAt(0L).contains(initialEnsemble.get(i)), (currentMetadata) -> { List<BookieSocketAddress> ensemble = Lists .newArrayList(currentMetadata.getEnsembleAt(0L)); ensemble.set(i, replacementBookies.get(i)); return LedgerMetadataBuilder.from(currentMetadata) .replaceEnsembleEntry(0L, ensemble).build(); }, reference::compareAndSet).run()) .collect(Collectors.toList()); loops.forEach((l) -> l.join()); Assert.assertEquals(reference.get().getValue().getEnsembleAt(0L), replacementBookies); } }
From source file:com.hurence.logisland.processor.EvaluateJsonPath.java
/** * Provides cleanup of the map for any JsonPath values that may have been created. This will remove common values shared between multiple instances, but will be regenerated when the next * validation cycle occurs as a result of isStale() * * @param processContext context/*from ww w . ja v a 2 s .co m*/ */ /* @OnRemoved public void onRemoved(ProcessContext processContext) { for (PropertyDescriptor propertyDescriptor : getPropertyDescriptors()) { if (propertyDescriptor.isDynamic()) { cachedJsonPathMap.remove(processContext.getProperty(propertyDescriptor).getValue()); } } }*/ @Override public Collection<Record> process(ProcessContext processContext, Collection<Record> records) throws ProcessException { String returnType = processContext.getPropertyValue(RETURN_TYPE).asString(); String representationOption = processContext.getPropertyValue(NULL_VALUE_DEFAULT_REPRESENTATION).asString(); final String nullDefaultValue = NULL_REPRESENTATION_MAP.get(representationOption); /* Build the JsonPath expressions from attributes */ final Map<String, JsonPath> attributeToJsonPathMap = new HashMap<>(); for (final Map.Entry<PropertyDescriptor, String> entry : processContext.getProperties().entrySet()) { if (!entry.getKey().isDynamic()) { continue; } final JsonPath jsonPath = JsonPath.compile(entry.getValue()); attributeToJsonPathMap.put(entry.getKey().getName(), jsonPath); } String jsonInputField = processContext.getPropertyValue(JSON_INPUT_FIELD).asString(); records.forEach(record -> { if (record.hasField(jsonInputField)) { DocumentContext documentContext = null; try { documentContext = validateAndEstablishJsonContext(record.getField(jsonInputField).asString()); } catch (InvalidJsonException e) { logger.error("Record {} did not have valid JSON content.", record); record.addError(ERROR_INVALID_JSON_FIELD, "unable to parse content of field : " + jsonInputField); } final Map<String, String> jsonPathResults = new HashMap<>(); for (final Map.Entry<String, JsonPath> attributeJsonPathEntry : attributeToJsonPathMap.entrySet()) { final String jsonPathAttrKey = attributeJsonPathEntry.getKey(); final JsonPath jsonPathExp = attributeJsonPathEntry.getValue(); final String pathNotFound = processContext.getPropertyValue(PATH_NOT_FOUND).asString(); final AtomicReference<Object> resultHolder = new AtomicReference<>(null); try { final Object result = documentContext.read(jsonPathExp); if (returnType.equals(RETURN_TYPE_SCALAR) && !isJsonScalar(result)) { String error = String.format( "Unable to return a scalar value for the expression %s " + "for Record %s. Evaluated value was %s.", jsonPathExp.getPath(), record.getId(), result.toString()); logger.error(error); record.addError(ERROR_INVALID_JSON_FIELD, error); } resultHolder.set(result); } catch (PathNotFoundException e) { if (pathNotFound.equals(PATH_NOT_FOUND_WARN)) { String error = String.format("Record %s could not find path %s for field %s..", record.getId(), jsonPathExp.getPath(), jsonPathAttrKey); logger.error(error); record.addError(ERROR_INVALID_JSON_FIELD, error); } jsonPathResults.put(jsonPathAttrKey, StringUtils.EMPTY); } final FieldType resultType = getResultType(resultHolder.get()); if (resultType != FieldType.STRING) record.setField(jsonPathAttrKey, resultType, resultHolder.get()); else record.setField(jsonPathAttrKey, resultType, getResultRepresentation(resultHolder.get(), nullDefaultValue)); } } else { String error = String.format("Record %s has no field %s.", record.getId(), jsonInputField); logger.error(error); record.addError(ERROR_INVALID_JSON_FIELD, error); } }); return records; }
From source file:blusunrize.immersiveengineering.api.ApiUtils.java
public static Connection raytraceWires(World world, Vec3d start, Vec3d end, @Nullable Connection ignored) { Map<BlockPos, ImmersiveNetHandler.BlockWireInfo> inDim = ImmersiveNetHandler.INSTANCE.blockWireMap .lookup(world.provider.getDimension()); AtomicReference<Connection> ret = new AtomicReference<>(); AtomicDouble minDistSq = new AtomicDouble(Double.POSITIVE_INFINITY); if (inDim != null) { Utils.rayTrace(start, end, world, (pos) -> { if (inDim.containsKey(pos)) { ImmersiveNetHandler.BlockWireInfo info = inDim.get(pos); for (int i = 0; i < 2; i++) { Set<Triple<Connection, Vec3d, Vec3d>> conns = i == 0 ? info.in : info.near; for (Triple<Connection, Vec3d, Vec3d> conn : conns) { Connection c = conn.getLeft(); if (ignored == null || !c.hasSameConnectors(ignored)) { Vec3d startRelative = start.add(-pos.getX(), -pos.getY(), -pos.getZ()); Vec3d across = conn.getRight().subtract(conn.getMiddle()); double t = Utils.getCoeffForMinDistance(startRelative, conn.getMiddle(), across); t = MathHelper.clamp(0, t, 1); Vec3d closest = conn.getMiddle().add(t * across.x, t * across.y, t * across.z); double distSq = closest.squareDistanceTo(startRelative); if (distSq < minDistSq.get()) { ret.set(c); minDistSq.set(distSq); }// w w w . jav a 2 s . c o m } } } } }); } return ret.get(); }
From source file:com.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java
/** * Retrieves certificate chain of specified host:port using https protocol. * * @param host to get certificate chain from (cannot be null) * @param port of host to connect to/*from w w w . j av a 2s .com*/ * @return certificate chain * @throws Exception Re-thrown from accessing the remote host */ public Certificate[] retrieveCertificatesFromHttpsServer(final String host, final int port) throws Exception { checkNotNull(host); log.info("Retrieving certificate from https://{}:{}", host, port); // setup custom connection manager so we can configure SSL to trust-all SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register(HttpSchemes.HTTP, PlainConnectionSocketFactory.getSocketFactory()) .register(HttpSchemes.HTTPS, sslSocketFactory).build(); final HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry); try { final AtomicReference<Certificate[]> certificates = new AtomicReference<>(); HttpClient httpClient = httpClientManager.create(new Customizer() { @Override public void customize(final HttpClientPlan plan) { // replace connection-manager with customized version needed to fetch SSL certificates plan.getClient().setConnectionManager(connectionManager); // add interceptor to grab peer-certificates plan.getClient().addInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { ManagedHttpClientConnection connection = HttpCoreContext.adapt(context) .getConnection(ManagedHttpClientConnection.class); // grab the peer-certificates from the session if (connection != null) { SSLSession session = connection.getSSLSession(); if (session != null) { certificates.set(session.getPeerCertificates()); } } } }); } }); httpClient.execute(new HttpGet("https://" + host + ":" + port)); return certificates.get(); } finally { // shutdown single-use connection manager connectionManager.shutdown(); } }
From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java
private MapValue removeInternal(String key, Optional<byte[]> value, Optional<MapValue> tombstone) { checkState(!closed, destroyedMessage); checkNotNull(key, ERROR_NULL_KEY);//from w w w . ja v a2 s .c o m checkNotNull(value, ERROR_NULL_VALUE); tombstone.ifPresent(v -> checkState(v.isTombstone())); counter.incrementCount(); AtomicBoolean updated = new AtomicBoolean(false); AtomicReference<MapValue> previousValue = new AtomicReference<>(); items.compute(key, (k, existing) -> { boolean valueMatches = true; if (value.isPresent() && existing != null && existing.isAlive()) { valueMatches = Arrays.equals(value.get(), existing.get()); } if (existing == null) { log.trace("ECMap Remove: Existing value for key {} is already null", k); } if (valueMatches) { if (existing == null) { updated.set(tombstone.isPresent()); } else { updated.set(!tombstone.isPresent() || tombstone.get().isNewerThan(existing)); } } if (updated.get()) { previousValue.set(existing); return tombstone.orElse(null); } else { return existing; } }); return previousValue.get(); }
From source file:org.elasticsearch.xpack.watcher.common.http.HttpClientTests.java
public void testThatHttpClientFailsOnNonHttpResponse() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); AtomicReference<Exception> hasExceptionHappened = new AtomicReference(); try (ServerSocket serverSocket = new MockServerSocket(0, 50, InetAddress.getByName("localhost"))) { executor.execute(() -> {/* www.j a v a2 s. c om*/ try (Socket socket = serverSocket.accept()) { BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); in.readLine(); socket.getOutputStream().write("This is not a HTTP response".getBytes(StandardCharsets.UTF_8)); socket.getOutputStream().flush(); } catch (Exception e) { hasExceptionHappened.set(e); logger.error((Supplier<?>) () -> new ParameterizedMessage("Error in writing non HTTP response"), e); } }); HttpRequest request = HttpRequest.builder("localhost", serverSocket.getLocalPort()).path("/").build(); expectThrows(ClientProtocolException.class, () -> httpClient.execute(request)); assertThat("A server side exception occured, but shouldn't", hasExceptionHappened.get(), is(nullValue())); } finally { terminate(executor); } }
From source file:com.microsoft.tfs.core.clients.versioncontrol.Workstation.java
/** * This helper method inserts a workspace into the Workstation cache. The * caller is responsible for writing out the Workstation cache. */// w ww. j a v a 2 s.c om public WorkspaceInfo insertWorkspaceIntoCache(final Workspace localWorkspace) { final AtomicReference<InternalWorkspaceConflictInfo[]> conflictingWorkspaces = new AtomicReference<InternalWorkspaceConflictInfo[]>(); final WorkspaceInfo workspaceInfo = getCache().insertWorkspace(localWorkspace, conflictingWorkspaces); onNonFatalError(conflictingWorkspaces.get()); return workspaceInfo; }
From source file:hello.MetricsActivator.java
private MessageHandler handlerInAnonymousWrapper(final Object bean) { if (bean != null && bean.getClass().isAnonymousClass()) { final AtomicReference<MessageHandler> wrapped = new AtomicReference<MessageHandler>(); ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { @Override// w w w . j av a2 s. c om public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { field.setAccessible(true); Object handler = field.get(bean); if (handler instanceof MessageHandler) { wrapped.set((MessageHandler) handler); } } }, new FieldFilter() { @Override public boolean matches(Field field) { return wrapped.get() == null && field.getName().startsWith("val$"); } }); return wrapped.get(); } else { return null; } }
From source file:io.pravega.client.stream.impl.ReaderGroupStateManager.java
private Map<Segment, Long> acquireSegment(long timeLag) throws ReinitializationRequiredException { AtomicReference<Map<Segment, Long>> result = new AtomicReference<>(); AtomicBoolean reinitRequired = new AtomicBoolean(false); sync.updateState(state -> {//from w w w. j av a2 s. c om if (!state.isReaderOnline(readerId)) { reinitRequired.set(true); return null; } int toAcquire = calculateNumSegmentsToAcquire(state); if (toAcquire == 0) { result.set(Collections.emptyMap()); return null; } Map<Segment, Long> unassignedSegments = state.getUnassignedSegments(); Map<Segment, Long> acquired = new HashMap<>(toAcquire); List<ReaderGroupStateUpdate> updates = new ArrayList<>(toAcquire); Iterator<Entry<Segment, Long>> iter = unassignedSegments.entrySet().iterator(); for (int i = 0; i < toAcquire; i++) { assert iter.hasNext(); Entry<Segment, Long> segment = iter.next(); acquired.put(segment.getKey(), segment.getValue()); updates.add(new AcquireSegment(readerId, segment.getKey())); } updates.add(new UpdateDistanceToTail(readerId, timeLag)); result.set(acquired); return updates; }); if (reinitRequired.get()) { throw new ReinitializationRequiredException(); } acquireTimer.reset(calculateAcquireTime(sync.getState())); return result.get(); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.Workstation.java
/** * Internal method to save the cache if it has been modified. *///from w ww. j ava2s . c o m public void saveConfigIfDirty() { if (isCacheEnabled()) { final AtomicReference<InternalWorkspaceConflictInfo[]> conflictingWorkspaces = new AtomicReference<InternalWorkspaceConflictInfo[]>(); InternalCacheLoader.saveConfigIfDirty(getCache(), conflictingWorkspaces, cacheMutex, workspaceCacheFile); onNonFatalError(conflictingWorkspaces.get()); } }