List of usage examples for java.util.concurrent.atomic AtomicReference set
public final void set(V newValue)
From source file:com.dgtlrepublic.anitomyj.Tokenizer.java
/** Tokenize by bracket. */ private void tokenizeByBrackets() { /** a ref to the closing brace of a found opening brace. (e.g "}" if we found an "}") */ AtomicReference<String> matchingBracket = new AtomicReference<>(); /** function to find an opening brace */ BiFunction<Integer, Integer, Integer> findFirstBracket = (start, end) -> { for (int i = start; i < end; i++) { for (Pair<String, String> bracket : brackets) { if (String.valueOf(filename.charAt(i)).equals(bracket.getLeft())) { matchingBracket.set(bracket.getRight()); return i; }/* ww w .ja v a2 s . c om*/ } } return -1; }; boolean isBracketOpen = false; for (int i = 0; i < filename.length();) { int foundIdx; if (!isBracketOpen) { /** look for opening brace */ foundIdx = findFirstBracket.apply(i, filename.length()); } else { /** look for closing brace */ foundIdx = filename.indexOf(matchingBracket.get(), i); } TokenRange range = new TokenRange(i, foundIdx == -1 ? filename.length() : foundIdx - i); if (range.getSize() > 0) { /** check if our range contains any known anime identifies */ tokenizeByPreidentified(isBracketOpen, range); } if (foundIdx != -1) { /** mark as bracket */ addToken(TokenCategory.kBracket, true, new TokenRange(range.getOffset() + range.getSize(), 1)); isBracketOpen = !isBracketOpen; i = foundIdx + 1; } else { break; } } }
From source file:com.jayway.restassured.module.mockmvc.ContentTypeTest.java
@Test public void doesnt_add_default_charset_to_content_type_if_configured_not_to_do_so() { final AtomicReference<String> contentType = new AtomicReference<String>(); given().config(RestAssuredMockMvcConfig.config() .encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false))) .standaloneSetup(new GreetingController()).contentType(ContentType.JSON) .interceptor(new MockHttpServletRequestBuilderInterceptor() { public void intercept(MockHttpServletRequestBuilder requestBuilder) { MultiValueMap<String, Object> headers = Whitebox.getInternalState(requestBuilder, "headers"); contentType.set(String.valueOf(headers.getFirst("Content-Type"))); }// w w w. j av a 2s . c o m }).when().get("/greeting?name={name}", "Johan").then().statusCode(200); assertThat(contentType.get()).isEqualTo("application/json"); }
From source file:org.zodiark.publisher.PublisherTest.java
@Test(enabled = false) public void startStreamingSession() throws IOException, InterruptedException { final ZodiarkClient wowzaClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build(); final CountDownLatch connected = new CountDownLatch(1); final AtomicReference<String> uuid = new AtomicReference<>(); // Fake Wowza Client wowzaClient.handler(new OnEnvelopHandler() { @Override//from w w w .j a va2s.c o m public boolean onEnvelop(Envelope e) throws IOException { Message m = e.getMessage(); switch (m.getPath()) { case WOWZA_CONNECT: // Connected. Listen uuid.set(e.getUuid()); break; case SERVER_VALIDATE_OK: Envelope publisherOk = Envelope .newClientToServerRequest(new Message(new Path(""), e.getMessage().getData())); wowzaClient.send(publisherOk); break; default: // ERROR } connected.countDown(); return false; } }).open(); Envelope wowzaConnect = Envelope.newClientToServerRequest( new Message(new Path(WOWZA_CONNECT), mapper.writeValueAsString(new UserPassword("wowza", "bar")))); wowzaClient.send(wowzaConnect); connected.await(); // Publisher final AtomicReference<PublisherResults> answer = new AtomicReference<>(); final ZodiarkClient publisherClient = new ZodiarkClient.Builder().path("http://127.0.0.1:" + port).build(); final CountDownLatch latch = new CountDownLatch(1); publisherClient.handler(new OnEnvelopHandler() { @Override public boolean onEnvelop(Envelope e) throws IOException { answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class)); latch.countDown(); return true; } }).open(); Envelope createSessionMessage = Envelope .newClientToServerRequest(new Message(new Path(DB_POST_PUBLISHER_SESSION_CREATE), mapper.writeValueAsString(new UserPassword("publisherex", "bar")))); createSessionMessage.setFrom(new From(ActorValue.PUBLISHER)); publisherClient.send(createSessionMessage); latch.await(); assertEquals("OK", answer.get().getResults()); answer.set(null); final CountDownLatch tlatch = new CountDownLatch(1); publisherClient.handler(new OnEnvelopHandler() { @Override public boolean onEnvelop(Envelope e) throws IOException { answer.set(mapper.readValue(e.getMessage().getData(), PublisherResults.class)); tlatch.countDown(); return true; } }); Envelope startStreamingSession = Envelope .newClientToServerRequest(new Message(new Path(VALIDATE_PUBLISHER_STREAMING_SESSION), mapper.writeValueAsString(new WowzaUUID(uuid.get())))); createSessionMessage.setFrom(new From(ActorValue.PUBLISHER)); publisherClient.send(startStreamingSession); tlatch.await(); assertEquals("OK", answer.get().getResults()); }
From source file:com.example.app.profile.ui.user.UserMembershipManagement.java
@Override public void init() { super.init(); final SearchSupplierImpl searchSupplier = getSearchSupplier(); searchSupplier.setSearchUIOperationHandler(this); SearchUIImpl.Options options = new SearchUIImpl.Options("User Role Management"); options.setSearchOnPageLoad(true);//from w w w .j a v a 2 s. co m options.setSearchActions(Collections.emptyList()); options.addSearchSupplier(searchSupplier); options.setHistory(getHistory()); _searchUI = new SearchUIImpl(options); Menu menu = new Menu(CommonButtonText.ADD); menu.setTooltip(ConcatTextSource.create(CommonButtonText.ADD, MEMBERSHIP()).withSpaceSeparator()); AppUtil.enableTooltip(menu); menu.addClassName("entity-action"); AtomicReference<Integer> counter = new AtomicReference<>(0); final TimeZone tz = getSession().getTimeZone(); getProfiles().forEach(profile -> { MenuItem subMenu = getProfileMenuItem(profile); User currentUser = _userDAO.getAssertedCurrentUser(); if (_profileDAO.canOperate(currentUser, profile, tz, _mop.modifyUserRoles())) { counter.set(counter.get() + 1); menu.add(subMenu); } }); menu.setVisible(counter.get() > 0); setDefaultComponent(of("search-wrapper user-role-search", of("entity-actions actions", menu), _searchUI)); }
From source file:com.microsoft.tfs.core.clients.versioncontrol.localworkspace.IgnoreFile.java
/** * Iterates through this IgnoreFile's list of exclusions to determine if the * item should be included, excluded, or if there is no result either way * from this IgnoreFile.// ww w . j av a 2s. co m * * @param path * the local item to check (must not be <code>null</code> or empty) * @param isFolder * <code>true</code> if the local item to check is a folder; * <code>false</code> otherwise * @param startPath * a local item which parents path. Only the path parts after * startPath are checked (must not be <code>null</code> or empty) * @param exclusion * if the return value is non-<code>null</code>, the exclusion which * was applied (may be <code>null</code>) * @return <code>null</code> if no result, <code>true</code> if the item is * excluded, <code>false</code> if the item is included */ public Boolean isExcluded(final String path, final boolean isFolder, final String startPath, final AtomicReference<String> exclusion) { Check.notNullOrEmpty(path, "path"); //$NON-NLS-1$ Check.notNullOrEmpty(startPath, "startPath"); //$NON-NLS-1$ // Debug.Assert(FileSpec.IsSubItem(path, startPath)); if (exclusion != null) { exclusion.set(null); } Boolean toReturn = null; for (final IgnoreEntry ignoreEntry : m_ignoreEntries) { // Index of the first character of the first path part that we are // going to evaluate for exclusions. int i = startPath.length(); if (startPath.charAt(startPath.length() - 1) != File.separatorChar) { i++; } int k = Integer.MAX_VALUE; if (null != ignoreEntry.path) { if (!LocalPath.isChild(ignoreEntry.path, path)) { // This IgnoreEntry applies only to items under a certain // path, and we don't meet the criteria. continue; } k = ignoreEntry.path.length(); if (ignoreEntry.path.charAt(ignoreEntry.path.length() - 1) != File.separatorChar) { k++; } // Skip our start path part ahead i = Math.max(i, k); } while (i >= 0 && i < path.length()) { if (!ignoreEntry.isRecursive && i > k) { break; } // Calculate the length of the current path part. int j = path.indexOf(File.separatorChar, i); if (j < 0) { j = path.length(); } // Don't match IsFolderOnly entries with an item that has // isFolder = false, // if this is the last path part. if (ignoreEntry.isFolderOnly && !isFolder && j == path.length()) { break; } j -= i; boolean match = false; if (ignoreEntry.isEndsWith) { if (ignoreEntry.pattern.length() <= j && 0 == compareCaseInsensitive(path, i + j - ignoreEntry.pattern.length(), ignoreEntry.pattern, 0, ignoreEntry.pattern.length())) { match = true; } } else if (ignoreEntry.isStartsWith) { if (ignoreEntry.pattern.length() <= j && 0 == compareCaseInsensitive(path, i, ignoreEntry.pattern, 0, ignoreEntry.pattern.length())) { match = true; } } else if (ignoreEntry.isComplex) { if (ItemPath.matchesWildcardFile(path.substring(i, i + j), ignoreEntry.pattern)) { match = true; } } else { if (ignoreEntry.pattern.length() == j && 0 == compareCaseInsensitive(path, i, ignoreEntry.pattern, 0, ignoreEntry.pattern.length())) { match = true; } } if (match) { if (ignoreEntry.isExcluded) { toReturn = true; if (exclusion != null) { exclusion.set(ignoreEntry.originalExclusion); } } // Otherwise this is an inclusion; only match if this // is the last path part which matched else if (i + j == path.length()) { toReturn = false; if (exclusion != null) { exclusion.set(ignoreEntry.originalExclusion); } } } i += (j + 1); } } // No declaration either way (excluded or included) return toReturn; }
From source file:org.apache.geode.management.internal.cli.commands.DestroyIndexCommand.java
@CliCommand(value = CliStrings.DESTROY_INDEX, help = CliStrings.DESTROY_INDEX__HELP) @CliMetaData(relatedTopic = { CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA }) @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER, operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY) public Result destroyIndex( @CliOption(key = CliStrings.DESTROY_INDEX__NAME, unspecifiedDefaultValue = "", help = CliStrings.DESTROY_INDEX__NAME__HELP) final String indexName, @CliOption(key = CliStrings.DESTROY_INDEX__REGION, optionContext = ConverterHint.REGION_PATH, help = CliStrings.DESTROY_INDEX__REGION__HELP) final String regionPath, @CliOption(key = { CliStrings.MEMBER, CliStrings.MEMBERS }, optionContext = ConverterHint.MEMBERIDNAME, help = CliStrings.DESTROY_INDEX__MEMBER__HELP) final String[] memberNameOrID, @CliOption(key = { CliStrings.GROUP, CliStrings.GROUPS }, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.DESTROY_INDEX__GROUP__HELP) final String[] group) { Result result;/*from ww w.ja v a2 s.c o m*/ if (StringUtils.isBlank(indexName) && StringUtils.isBlank(regionPath) && ArrayUtils.isEmpty(group) && ArrayUtils.isEmpty(memberNameOrID)) { return ResultBuilder.createUserErrorResult( CliStrings.format(CliStrings.PROVIDE_ATLEAST_ONE_OPTION, CliStrings.DESTROY_INDEX)); } final Cache cache = CacheFactory.getAnyInstance(); String regionName = null; if (regionPath != null) { regionName = regionPath.startsWith("/") ? regionPath.substring(1) : regionPath; } IndexInfo indexInfo = new IndexInfo(indexName, regionName); Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID); if (targetMembers.isEmpty()) { return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE); } ResultCollector rc = CliUtil.executeFunction(destroyIndexFunction, indexInfo, targetMembers); List<Object> funcResults = (List<Object>) rc.getResult(); Set<String> successfulMembers = new TreeSet<>(); Map<String, Set<String>> indexOpFailMap = new HashMap<>(); AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>(); for (Object funcResult : funcResults) { if (!(funcResult instanceof CliFunctionResult)) { continue; } CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult; if (cliFunctionResult.isSuccessful()) { successfulMembers.add(cliFunctionResult.getMemberIdOrName()); if (xmlEntity.get() == null) { xmlEntity.set(cliFunctionResult.getXmlEntity()); } } else { String exceptionMessage = cliFunctionResult.getMessage(); Set<String> failedMembers = indexOpFailMap.get(exceptionMessage); if (failedMembers == null) { failedMembers = new TreeSet<>(); } failedMembers.add(cliFunctionResult.getMemberIdOrName()); indexOpFailMap.put(exceptionMessage, failedMembers); } } if (!successfulMembers.isEmpty()) { InfoResultData infoResult = ResultBuilder.createInfoResultData(); if (StringUtils.isNotBlank(indexName)) { if (StringUtils.isNotBlank(regionPath)) { infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__ON__REGION__SUCCESS__MSG, indexName, regionPath)); } else { infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__SUCCESS__MSG, indexName)); } } else { if (StringUtils.isNotBlank(regionPath)) { infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__ON__REGION__ONLY__SUCCESS__MSG, regionPath)); } else { infoResult.addLine(CliStrings.DESTROY_INDEX__ON__MEMBERS__ONLY__SUCCESS__MSG); } } int num = 0; for (String memberId : successfulMembers) { infoResult.addLine(CliStrings .format(CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId))); } result = ResultBuilder.buildResult(infoResult); } else { ErrorResultData erd = ResultBuilder.createErrorResultData(); if (StringUtils.isNotBlank(indexName)) { erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__FAILURE__MSG, indexName)); } else { erd.addLine("Indexes could not be destroyed for following reasons"); } Set<String> exceptionMessages = indexOpFailMap.keySet(); for (String exceptionMessage : exceptionMessages) { erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__REASON_MESSAGE, exceptionMessage)); erd.addLine(CliStrings.DESTROY_INDEX__EXCEPTION__OCCURRED__ON); Set<String> memberIds = indexOpFailMap.get(exceptionMessage); int num = 0; for (String memberId : memberIds) { erd.addLine(CliStrings.format( CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId))); } erd.addLine(""); } result = ResultBuilder.buildResult(erd); } if (xmlEntity.get() != null) { persistClusterConfiguration(result, () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), group)); } return result; }
From source file:org.apache.nifi.util.hive.HiveConfigurator.java
public Collection<ValidationResult> validate(String configFiles, String principal, String keyTab, AtomicReference<ValidationResources> validationResourceHolder, ComponentLog log) { final List<ValidationResult> problems = new ArrayList<>(); ValidationResources resources = validationResourceHolder.get(); // if no resources in the holder, or if the holder has different resources loaded, // then load the Configuration and set the new resources in the holder if (resources == null || !configFiles.equals(resources.getConfigResources())) { log.debug("Reloading validation resources"); resources = new ValidationResources(configFiles, getConfigurationFromFiles(configFiles)); validationResourceHolder.set(resources); }//from www . j av a 2 s . c o m final Configuration hiveConfig = resources.getConfiguration(); problems.addAll(KerberosProperties.validatePrincipalAndKeytab(this.getClass().getSimpleName(), hiveConfig, principal, keyTab, log)); return problems; }
From source file:org.apache.carbondata.tool.ScanBenchmark.java
@Override public void run(CommandLine line) throws IOException, MemoryException { if (line.hasOption("f")) { String filePath = line.getOptionValue("f"); file = new DataFile(FileFactory.getCarbonFile(filePath)); } else {/* ww w. j a va 2 s . c o m*/ FileCollector collector = new FileCollector(outPuts); collector.collectFiles(dataFolder); if (collector.getNumDataFiles() == 0) { return; } Map<String, DataFile> dataFiles = collector.getDataFiles(); Iterator<DataFile> iterator = dataFiles.values().iterator(); // use the first file and close the rest file = iterator.next(); while (iterator.hasNext()) { iterator.next().close(); } } outPuts.add("\n## Benchmark"); final AtomicReference<FileHeader> fileHeaderRef = new AtomicReference<>(); final AtomicReference<FileFooter3> fileFoorterRef = new AtomicReference<>(); final AtomicReference<DataFileFooter> convertedFooterRef = new AtomicReference<>(); // benchmark read header and footer time benchmarkOperation("ReadHeaderAndFooter", new Operation() { @Override public void run() throws IOException, MemoryException { fileHeaderRef.set(file.readHeader()); fileFoorterRef.set(file.readFooter()); } }); final FileHeader fileHeader = fileHeaderRef.get(); final FileFooter3 fileFooter = fileFoorterRef.get(); // benchmark convert footer benchmarkOperation("ConvertFooter", new Operation() { @Override public void run() throws IOException, MemoryException { convertFooter(fileHeader, fileFooter); } }); // benchmark read all meta and convert footer benchmarkOperation("ReadAllMetaAndConvertFooter", new Operation() { @Override public void run() throws IOException, MemoryException { DataFileFooter footer = readAndConvertFooter(file); convertedFooterRef.set(footer); } }); if (line.hasOption("c")) { String columnName = line.getOptionValue("c"); outPuts.add("\nScan column '" + columnName + "'"); final DataFileFooter footer = convertedFooterRef.get(); final AtomicReference<AbstractRawColumnChunk> columnChunk = new AtomicReference<>(); final int columnIndex = file.getColumnIndex(columnName); final boolean dimension = file.getColumn(columnName).isDimensionColumn(); for (int i = 0; i < footer.getBlockletList().size(); i++) { final int blockletId = i; outPuts.add(String.format("Blocklet#%d: total size %s, %,d pages, %,d rows", blockletId, Strings.formatSize(file.getColumnDataSizeInBytes(blockletId, columnIndex)), footer.getBlockletList().get(blockletId).getNumberOfPages(), footer.getBlockletList().get(blockletId).getNumberOfRows())); benchmarkOperation("\tColumnChunk IO", new Operation() { @Override public void run() throws IOException, MemoryException { columnChunk.set(readBlockletColumnChunkIO(footer, blockletId, columnIndex, dimension)); } }); if (dimensionColumnChunkReader != null) { benchmarkOperation("\tDecompress Pages", new Operation() { @Override public void run() throws IOException, MemoryException { decompressDimensionPages(columnChunk.get(), footer.getBlockletList().get(blockletId).getNumberOfPages()); } }); } else { benchmarkOperation("\tDecompress Pages", new Operation() { @Override public void run() throws IOException, MemoryException { decompressMeasurePages(columnChunk.get(), footer.getBlockletList().get(blockletId).getNumberOfPages()); } }); } } } file.close(); }
From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java
@Test public void testSinkAutoFlush() throws Exception { final ServerSocket server = new ServerSocket(0); final int port = server.getLocalPort(); final SocketClientSink<String> simpleSink = new SocketClientSink<>(host, port, simpleSchema, 0, true); simpleSink.open(new Configuration()); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Thread sinkRunner = new Thread("Test sink runner") { @Override/*from w w w . ja va2s.c o m*/ public void run() { try { // need two messages here: send a fin to cancel the client state:FIN_WAIT_2 while the server is CLOSE_WAIT simpleSink.invoke(TEST_MESSAGE + '\n'); } catch (Throwable t) { error.set(t); } } }; sinkRunner.start(); Socket sk = server.accept(); BufferedReader rdr = new BufferedReader(new InputStreamReader(sk.getInputStream())); String value = rdr.readLine(); sinkRunner.join(); simpleSink.close(); server.close(); if (error.get() != null) { Throwable t = error.get(); t.printStackTrace(); fail("Error in spawned thread: " + t.getMessage()); } assertEquals(TEST_MESSAGE, value); }
From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java
@Override public void sendQueuedMessages( CallableExecutor<Pair<PagingWrapper<Message>, Collection<Throwable>>> batchExec) { LOGGER.info("BEGIN : sendQueuedMessages()"); if (Thread.currentThread().isInterrupted()) { LOGGER.info("Abandoning sendQueuedMessages because of thread interruption"); }// w w w. ja v a 2 s.co m int startRow = 0; final AtomicReference<SortingAndPaging> sap = new AtomicReference<SortingAndPaging>(); sap.set(new SortingAndPaging(ObjectStatus.ACTIVE, startRow, QUEUE_BATCH_SIZE, null, null, null)); // process each batch in its own transaction... don't want to hold // a single transaction open while processing what is effectively // an unbounded number of messages. while (true) { if (Thread.currentThread().isInterrupted()) { LOGGER.info("Abandoning sendQueuedMessages because of thread interruption"); break; } LOGGER.info("Before message queue processing transaction at start row {}", sap.get().getFirstResult()); Pair<PagingWrapper<Message>, Collection<Throwable>> rslt = null; try { if (batchExec == null) { rslt = sendQueuedMessageBatchInTransaction(sap.get()); } else { rslt = batchExec.exec(new Callable<Pair<PagingWrapper<Message>, Collection<Throwable>>>() { @Override public Pair<PagingWrapper<Message>, Collection<Throwable>> call() throws Exception { return sendQueuedMessageBatchInTransaction(sap.get()); } }); } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } if (Thread.currentThread().isInterrupted()) { LOGGER.info("Abandoning sendQueuedMessages because of thread interruption"); break; } PagingWrapper<Message> msgsHandled = rslt.getFirst(); int msgHandledCnt = msgsHandled.getRows() == null ? 0 : msgsHandled.getRows().size(); if (msgHandledCnt == 0 || msgHandledCnt < QUEUE_BATCH_SIZE) { LOGGER.info( "Stop message queue processing. Transaction at" + " start row {} processed fewer messages ({}) than" + " allowed batch size {}.", new Object[] { startRow, msgHandledCnt, QUEUE_BATCH_SIZE }); break; } // Are potentially more msgs to handle and we know at least one // msg in the previous batch errored out. go ahead and grab another // full batch. Grabbing a full batch avoids slowdown when enough // errors accumulate to dramatically reduce the number of // *potentially* valid messages in the previous batch. Collection<Throwable> errors = rslt.getSecond(); if (errors != null && !(errors.isEmpty())) { startRow += msgsHandled.getRows().size(); sap.set(new SortingAndPaging(ObjectStatus.ACTIVE, startRow, QUEUE_BATCH_SIZE, null, null, null)); LOGGER.info( "Need to advance past message queue processing errors." + " Transaction at start row {} processed all {}" + " messages in a max batch size of {}, but were" + " errors.", new Object[] { startRow, msgHandledCnt, QUEUE_BATCH_SIZE }); // lets not get into an excessively tight email loop maybePauseBetweenQueueBatches(); } else { LOGGER.info( "Stop message queue processing. Transaction at" + " start row {} processed all {} messages in a max" + " batch size of {}, but were zero errors. Waiting for" + " next scheduled execution before processing" + " additional messages.", new Object[] { startRow, msgHandledCnt, QUEUE_BATCH_SIZE }); break; } } LOGGER.info("END : sendQueuedMessages()"); }