auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Scope selectExchangeScopeForPartitionedRemoteExchange(PlanNode exchangeSource, boolean nullsAndAnyReplicated) { boolean streamMarkDistinct = SystemSessionProperties.isStreamMarkDistinctWithMaterializedExchangeEnabled(session); if (nullsAndAnyReplicated || exchangeSource.getOutputVariables().isEmpty() || streamMarkDistinct) { return REMOTE_STREAMING; } switch (exchangeMaterializationStrategy) { case ALL: return REMOTE_MATERIALIZED; case NONE: return REMOTE_STREAMING; default: throw new IllegalStateException("Unexpected exchange materialization strategy: " + exchangeMaterializationStrategy); } }

Target:
private Scope selectExchangeScopeForPartitionedRemoteExchange(PlanNode exchangeSource, boolean nullsAndAnyReplicated) { if (nullsAndAnyReplicated || exchangeSource.getOutputVariables().isEmpty()) { return REMOTE_STREAMING; } switch (exchangeMaterializationStrategy) { case ALL: return REMOTE_MATERIALIZED; case NONE: return REMOTE_STREAMING; default: throw new IllegalStateException("Unexpected exchange materialization strategy: " + exchangeMaterializationStrategy); } }
Source:
private void showInstructions(final int messageIndex){ String positiveString = messageIndex < MESSAGEIDS.length-1? "Next" : "Done"; String negativeString = messageIndex > 0 ? "Back" : "Skip"; new AlertDialog.Builder(activity) .setMessage(MESSAGEIDS[messageIndex]) .setPositiveButton(positiveString, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { if(messageIndex < MESSAGEIDS.length-1){ showInstructions(messageIndex+1); } } }) .setNegativeButton(negativeString, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(messageIndex > 0 ){ showInstructions(messageIndex-1); } } }).show(); }

Target:
private void showInstructions(final int messageIndex){ String positiveString = messageIndex < MESSAGEIDS.length-1? "Next" : "Done"; String negativeString = messageIndex > WELCOME_INDEX ? "Back" : "Skip"; new AlertDialog.Builder(activity) .setMessage(MESSAGEIDS[messageIndex]) .setPositiveButton(positiveString, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { if(messageIndex < MESSAGEIDS.length-1){ showInstructions(messageIndex+1); } } }) .setNegativeButton(negativeString, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(messageIndex > WELCOME_INDEX ){ showInstructions(messageIndex-1); } } }).show(); }
Source:
public Observable<DataPoint<RatioMap>> findAvailabilityRatioMap( String tenantId, List<String> metrics, long start, long end, int limit, Order order) { checkArgument(isValidTimeRange(start, end), "Invalid time range"); Observable<DataPoint<RatioMap>> result = Observable.from(metrics) .map(id -> new MetricId<>(tenantId, MetricType.AVAILABILITY, id)) .flatMap(this::findMetric) .map(metric -> findDataPoints(metric.getMetricId(), start, end, limit, order)) .compose(o -> buildRatioMapSeries(o, order, AvailabilityType::getText)); if (limit > 0) { result = result.limit(limit); } return result; }

Target:
public Observable<DataPoint<RatioMap>> findAvailabilityRatioMap( String tenantId, List<String> metrics, long start, long end, int limit, Order order) { checkArgument(isValidTimeRange(start, end), "Invalid time range"); Observable<DataPoint<RatioMap>> result = Observable.from(metrics) .map(id -> new MetricId<>(tenantId, MetricType.AVAILABILITY, id)) .flatMap(this::findMetric) .map(metric -> findDataPoints(metric.getMetricId(), start, end, limit, order)) .compose(o -> buildRatioMapSeries(o, order, AvailabilityType::getText)); if (limit > 0) { result = result.take(limit); } return result; }
Source:
private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) { dismissLoadingDialog(); OCFile renamedFile = operation.getFile(); if (result.isSuccess()) { FileFragment details = getSecondFragment(); if (details != null) if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) { ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount()); showDetails(renamedFile); } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) { ((PreviewMediaFragment) details).updateFile(renamedFile); if (PreviewMediaFragment.canBePreviewed(renamedFile)) { int position = ((PreviewMediaFragment)details).getPosition(); startMediaPreview(renamedFile, position, true); } else { getFileOperationsHelper().openFile(renamedFile); } } if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) { refreshListOfFilesFragment(); } } else { if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) { Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG); msg.show(); } if (result.getCode().equals(ResultCode.INVALID_CHARACTER_IN_NAME)) { Toast msg = Toast.makeText(this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG); msg.show(); } else { Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG); msg.show(); if (result.isSslRecoverableException()) { mLastSslUntrustedServerResult = result; showUntrustedCertDialog(mLastSslUntrustedServerResult); } } } }

Target:
private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) { dismissLoadingDialog(); OCFile renamedFile = operation.getFile(); if (result.isSuccess()) { FileFragment details = getSecondFragment(); if (details != null) { if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) { ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount()); showDetails(renamedFile); } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) { ((PreviewMediaFragment) details).updateFile(renamedFile); if (PreviewMediaFragment.canBePreviewed(renamedFile)) { int position = ((PreviewMediaFragment)details).getPosition(); startMediaPreview(renamedFile, position, true); } else { getFileOperationsHelper().openFile(renamedFile); } } } if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) { refreshListOfFilesFragment(); } } else { if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) { Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG); msg.show(); } if (result.getCode().equals(ResultCode.INVALID_CHARACTER_IN_NAME)) { Toast msg = Toast.makeText(this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG); msg.show(); } else { Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG); msg.show(); if (result.isSslRecoverableException()) { mLastSslUntrustedServerResult = result; showUntrustedCertDialog(mLastSslUntrustedServerResult); } } } }
Source:
public T remove(String key) { validate(); if (!containsKey(key)) return null; LinkedList<T> entities = litems.get(key); if (entities != null && entities.size() > 1) { throw new SplunkException(SplunkException.AMBIGUOUS, "Key has multiple values, specify a namespace"); } if (entities == null) return null; T entity = entities.get(0); entity.remove(); litems.remove(key); invalidate(); return entity; }

Target:
public T remove(String key) { validate(); if (!containsKey(key)) return null; LinkedList<T> entities = linkedListItems.get(key); if (entities != null && entities.size() > 1) { throw new SplunkException(SplunkException.AMBIGUOUS, "Key has multiple values, specify a namespace"); } if (entities == null) return null; T entity = entities.get(0); entity.remove(); invalidate(); return entity; }
Source:
public void select(Map<String, String> idsAndLabels) { LOG.info("Selecting terms with ids and labels in Select2 with id {}...", idsAndLabels, id); for (Map.Entry<String, String> entry : idsAndLabels.entrySet()) { if (entry.getKey().isEmpty() || entry.getValue().isEmpty()) continue; LOG.debug("Click select."); WebElement select2Option = driver.findElement(selectedOptionSelector); select2Option.click(); LOG.debug("Wait for text input box..."); WebElement select2InputText = driver.findElement(By .cssSelector(multi ? "#s2id_" + id + " input" : "#select2-drop input")); LOG.debug("Empty text input box.."); select2InputText.clear(); LOG.debug("Text input box empty. Entering term..."); select2InputText.sendKeys(entry.getKey()); try { LOG.debug("Waiting for match.."); WebElement match = driver.findElement(By .xpath(" + entry.getKey() + "']| + entry.getKey() + "']")); LOG.debug("Click match.."); match.click(); } catch (Exception ex) { LOG.warn("Element was stale when clicking"); } LOG.debug("Waiting for selection to appear in the list of search choices..."); tenSecondWait.until(textToBePresentInElementLocated( multi ? By.xpath(" LOG.debug("Selected '{}'.", entry); } LOG.debug("Selected terms with ids and labels {}. Selected labels are: {}.", idsAndLabels, getSelectedLabels()); }

Target:
public void select(Map<String, String> idsAndLabels) { LOG.info("Selecting terms with ids and labels in Select2 with id {}...", idsAndLabels, id); for (Map.Entry<String, String> entry : idsAndLabels.entrySet()) { if (entry.getKey().isEmpty() || entry.getValue().isEmpty()) continue; LOG.debug("Click select."); WebElement select2Option = driver.findElement(selectedOptionSelector); select2Option.click(); LOG.debug("Wait for text input box..."); WebElement select2InputText = driver.findElement(By .cssSelector(multi ? "#s2id_" + id + " input" : "#select2-drop input")); LOG.debug("Empty text input box.."); select2InputText.clear(); LOG.debug("Text input box empty. Entering term..."); select2InputText.sendKeys(entry.getKey()); LOG.debug("Waiting for match.."); WebElement match = driver.findElement(By .xpath(" + entry.getKey() + "']| + entry.getKey() + "']")); LOG.debug("Click match.."); match.click(); LOG.debug("Waiting for selection to appear in the list of search choices..."); tenSecondWait.until(textToBePresentInElementLocated( multi ? By.xpath(" LOG.debug("Selected '{}'.", entry); } LOG.debug("Selected terms with ids and labels {}. Selected labels are: {}.", idsAndLabels, getSelectedLabels()); }
Source:
public void cleanRemotelyLoadedFiles(String disconnectedUserMac){ Set<PlaylistEntry> toRemoveForRemoteLoad = new HashSet<PlaylistEntry>(); for(PlaylistEntry entry : remotelyLoaded) { synchronized(entryMutex){ if(!entry.isLoaded() && entry.getMacAddress().equals(disconnectedUserMac)){ toRemoveForRemoteLoad.add(entry); } } } remotelyLoaded.removeAll(toRemoveForRemoteLoad); Set<PlaylistEntry> toRemoveForToLoad = new HashSet<PlaylistEntry>(); for (PlaylistEntry entry : toLoadQueue) { synchronized(entryMutex) { if (entry.getMacAddress().equals(disconnectedUserMac)) { entry.setLoaded(false); toRemoveForToLoad.add(entry); } } } toLoadQueue.removeAll(toRemoveForToLoad); }

Target:
public void cleanRemotelyLoadedFiles(String disconnectedUserMac){ Set<PlaylistEntry> toRemove = new HashSet<PlaylistEntry>(); for(PlaylistEntry entry : remotelyLoaded) { synchronized(entryMutex){ if(!entry.isLoaded() && entry.getMacAddress().equals(disconnectedUserMac)){ toRemove.add(entry); } } } remotelyLoaded.removeAll(toRemove); toRemove = new HashSet<PlaylistEntry>(); for (PlaylistEntry entry : toLoadQueue) { synchronized(entryMutex) { if (entry.getMacAddress().equals(disconnectedUserMac)) { entry.setLoaded(false); toRemove.add(entry); } } } toLoadQueue.removeAll(toRemove); }
Source:
public void testDisallowed() { assertThatThrownBy(() -> dao.disallowed("43")) .isInstanceOf(UnableToCreateStatementException.class) .hasMessageContaining("named parameter"); }

Target:
public void testDisallowed() { dao.getHandle().getConfig(SqlStatements.class).setUnusedBindingAllowed(true); assertThatThrownBy(() -> dao.disallowed("43")) .isInstanceOf(UnableToCreateStatementException.class) .hasMessageContaining("named parameter"); }
Source:
public Plan optimize(final Map<String, List<EvaluatorParameters>> evalParamsMap, final int availableEvaluators) { if (callsSkipped < callsToSkip) { callsSkipped++; return PlanImpl.newBuilder().build(); } if (callsMade == maxCallsToMake || evalParamsMap.isEmpty()) { return PlanImpl.newBuilder().build(); } final String evaluatorToAdd = "new-" + callsMade; callsMade++; final PlanImpl.Builder planBuilder = PlanImpl.newBuilder(); for (final String namespace : evalParamsMap.keySet()) { planBuilder.addEvaluatorToAdd(namespace, evaluatorToAdd); EvaluatorParameters srcEvaluator = null; for (final EvaluatorParameters evaluator : evalParamsMap.get(namespace)) { if (evaluator.getDataInfo().getNumBlocks() != 0) { srcEvaluator = evaluator; break; } } if (srcEvaluator == null) { LOG.log(Level.WARNING, "Cannot choose source evaluator to move its data to new evaluator in {0}", namespace); continue; } final DataInfo srcDataInfo = srcEvaluator.getDataInfo(); final int numBlocksToMove = srcDataInfo.getNumBlocks() / 2; final TransferStep transferStep = new TransferStepImpl( srcEvaluator.getId(), evaluatorToAdd, new DataInfoImpl(numBlocksToMove)); planBuilder.addTransferStep(namespace, transferStep); } return planBuilder.build(); }

Target:
public Plan optimize(final Map<String, List<EvaluatorParameters>> evalParamsMap, final int availableEvaluators) { if (callsSkipped < callsToSkip) { callsSkipped++; return PlanImpl.newBuilder().build(); } if (callsMade == maxCallsToMake || evalParamsMap.isEmpty()) { return PlanImpl.newBuilder().build(); } final String evaluatorToAdd = "new-" + callsMade; callsMade++; final PlanImpl.Builder planBuilder = PlanImpl.newBuilder(); for (final String namespace : evalParamsMap.keySet()) { planBuilder.addEvaluatorToAdd(namespace, evaluatorToAdd); EvaluatorParameters srcEvaluator = null; for (final EvaluatorParameters evaluator : evalParamsMap.get(namespace)) { if (evaluator.getDataInfo().getNumBlocks() > 0) { srcEvaluator = evaluator; break; } } if (srcEvaluator == null) { LOG.log(Level.WARNING, "Cannot choose source evaluator to move its data to new evaluator in {0}", namespace); continue; } final DataInfo srcDataInfo = srcEvaluator.getDataInfo(); final int numBlocksToMove = srcDataInfo.getNumBlocks() / 2; final TransferStep transferStep = new TransferStepImpl( srcEvaluator.getId(), evaluatorToAdd, new DataInfoImpl(numBlocksToMove)); planBuilder.addTransferStep(namespace, transferStep); } return planBuilder.build(); }
Source:
private void parseTree(List<Block> sourceBlocks) { Block matchStartBlock = null; int count = 0; Block mappingCursor = this.mappingTree.getChildren().get(0); Block sourceBlock = sourceBlocks.get(0); while (sourceBlock != null) { while (mappingCursor != null) { if (blockEquals(sourceBlock, mappingCursor)) { if (matchStartBlock == null) { matchStartBlock = sourceBlock; } count++; mappingCursor = mappingCursor.getChildren().get(0); if (mappingCursor instanceof ImageBlock) { for (int i = 0; i < count - 1; i++) { matchStartBlock.getParent().removeBlock(matchStartBlock.getNextSibling()); } sourceBlock = mappingCursor.clone(); matchStartBlock.getParent().replaceChild(sourceBlock, matchStartBlock); mappingCursor = null; matchStartBlock = null; count = 0; } else { break; } } else { mappingCursor = mappingCursor.getNextSibling(); } } List<Block> filteredSourceBlocks = this.filter.filter(sourceBlock.getChildren()); if (!filteredSourceBlocks.size().isEmpty()) { parseTree(filteredSourceBlocks); } else if (mappingCursor == null) { mappingCursor = this.mappingTree.getChildren().get(0); count = 0; matchStartBlock = null; } sourceBlock = this.filter.getNextSibling(sourceBlock); } }

Target:
private void parseTree(List<Block> sourceBlocks) { Block matchStartBlock = null; int count = 0; Block mappingCursor = this.mappingTree.getChildren().get(0); Block sourceBlock = sourceBlocks.get(0); while (sourceBlock != null) { while (mappingCursor != null) { if (blockEquals(sourceBlock, mappingCursor)) { if (matchStartBlock == null) { matchStartBlock = sourceBlock; } count++; mappingCursor = mappingCursor.getChildren().get(0); if (mappingCursor instanceof ImageBlock) { for (int i = 0; i < count - 1; i++) { matchStartBlock.getParent().removeBlock(matchStartBlock.getNextSibling()); } sourceBlock = mappingCursor.clone(); matchStartBlock.getParent().replaceChild(sourceBlock, matchStartBlock); mappingCursor = null; matchStartBlock = null; count = 0; } else { break; } } else { mappingCursor = mappingCursor.getNextSibling(); } } List<Block> filteredSourceBlocks = this.filter.filter(sourceBlock.getChildren()); if (filteredSourceBlocks.size() > 0) { parseTree(filteredSourceBlocks); } else if (mappingCursor == null) { mappingCursor = this.mappingTree.getChildren().get(0); count = 0; matchStartBlock = null; } sourceBlock = this.filter.getNextSibling(sourceBlock); } }
Source:
public void onEvictNotice(EvictNotice notice) { System.out.println("Evict Notice: " + notice.toJson()); Object key; try { key = gson.fromJson(notice.keyJson, Class.forName(notice.keyClass)); } catch (JsonSyntaxException e) { log.error("Invalid json syntax for key", e); return; } catch (ClassNotFoundException e) { log.error("Could not find key class", e); return; } cacheManager.invalidate(notice.pluginName, notice.cacheName, key); }

Target:
public void onEvictNotice(EvictNotice notice) { Object key; try { key = gson.fromJson(notice.keyJson, Class.forName(notice.keyClass)); } catch (JsonSyntaxException e) { log.error("Invalid json syntax for key", e); return; } catch (ClassNotFoundException e) { log.error("Could not find key class", e); return; } cacheManager.invalidate(notice.pluginName, notice.cacheName, key); }
Source:
public static String constructHadoopTags(Props props, String[] keys) { String[] keysAndValues = new String[keys.length + 1]; for (int i = 0; i < keys.length; i++) { if (props.containsKey(keys[i])) { keysAndValues[i] = keys[i] + ":" + props.get(keys[i]); } } if (props.containsKey(CommonJobProperties.PROJECT_NAME) && props.containsKey(CommonJobProperties.FLOW_ID)) { String constructedTag = "workflowid:" + props.get(CommonJobProperties.PROJECT_NAME) + HadoopConfigurationInjector.WORKFLOW_ID_SEPERATOR + props.get(CommonJobProperties.FLOW_ID); constructedTag = constructedTag.substring(0, Math.min(constructedTag.length(), APPLICATION_TAG_MAX_LENGTH)); keysAndValues[keys.length] = constructedTag; } Joiner joiner = Joiner.on(',').skipNulls(); return joiner.join(keysAndValues); }

Target:
public static String constructHadoopTags(Props props, String[] keys) { String[] keysAndValues = new String[keys.length]; for (int i = 0; i < keys.length; i++) { if (props.containsKey(keys[i])) { String tag = keys[i] + ":" + props.get(keys[i]); keysAndValues[i] = tag.substring(0, Math.min(tag.length(), HadoopJobUtils.APPLICATION_TAG_MAX_LENGTH)); } } Joiner joiner = Joiner.on(',').skipNulls(); return joiner.join(keysAndValues); }
Source:
public void reportLookingSid(long sid) { if (minTimeToWaitForEpoch < 0 || timeStartWaitForEpoch < 0 || !waitingForNewEpoch) { return; } if (voteSet == null || !voteSet.hasSid(sid)) { return; } if (Time.currentElapsedTime() - timeStartWaitForEpoch > minTimeToWaitForEpoch) { quitLeading(); } }

Target:
public void reportLookingSid(long sid) { if (maxTimeToWaitForEpoch < 0 || timeStartWaitForEpoch < 0 || !waitingForNewEpoch) { return; } if (voteSet == null || !voteSet.hasSid(sid)) { return; } if (Time.currentElapsedTime() - timeStartWaitForEpoch > maxTimeToWaitForEpoch) { quitLeading(); } }
Source:
public Optional<BreakableData> createFrom(DataHolder dataHolder) { return null; }

Target:
public Optional<BreakableData> createFrom(DataHolder dataHolder) { if (dataHolder instanceof ItemStack) { NBTTagCompound tag = ((ItemStack) dataHolder).getTagCompound(); if (tag == null) { return Optional.<BreakableData>of(new SpongeBreakableData()); } NBTTagList blockIds = tag.getTagList(NbtDataUtil.ITEM_BREAKABLE_BLOCKS, NbtDataUtil.TAG_STRING); if (blockIds.hasNoTags()) { return Optional.<BreakableData>of(new SpongeBreakableData()); } Set<BlockType> blockTypes = Sets.newHashSetWithExpectedSize(blockIds.tagCount()); for (int i = 0; i < blockIds.tagCount(); i++) { Optional<BlockType> blockType = Sponge.getGame().getRegistry() .getType(BlockType.class, blockIds.getStringTagAt(i)); if (blockType.isPresent()) { blockTypes.add(blockType.get()); } } return Optional.<BreakableData>of(new SpongeBreakableData(blockTypes)); } return Optional.empty(); }
Source:
public void visitNode(Tree tree) { SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree; List<CaseGroupTree> caseGroupTrees = switchStatementTree.cases(); CFG cfg = CFG.buildCFG(Collections.singletonList(tree), true); CFG.Block entry = cfg.entry(); List<CFG.Block> cfgCases = new ArrayList<>(entry.successors()); if (!hasDefaultClause(switchStatementTree)) { cfgCases.remove(cfgCases.size() - 1); } List<CFG.Block> cases = Lists.reverse(cfgCases); IntStream.range(1, cases.size()) .filter(i -> cases.get(i).predecessors().stream().anyMatch(predecessor -> !tree.equals(predecessor.terminator()))) .filter(i -> !intentionalFallThrough(caseGroupTrees.get(i - 1), caseGroupTrees.get(i))) .mapToObj(i -> caseGroupTrees.get(i - 1).labels()) .map(caseGroupLabels -> caseGroupLabels.get(caseGroupLabels.size() - 1)) .forEach(label -> reportIssue(label, "End this switch case with an unconditional break, return or throw statement.")); }

Target:
public void visitNode(Tree tree) { SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree; List<CaseGroupTree> caseGroupTrees = switchStatementTree.cases(); CFG cfg = CFG.buildCFG(Collections.singletonList(tree), true); Set<CFG.Block> switchSuccessors = cfg.entry().successors(); Map<CFG.Block, CaseGroupTree> cfgBlockToCaseGroupMap = createMapping(switchSuccessors, caseGroupTrees); switchSuccessors.stream() .filter(cfgBlockToCaseGroupMap.keySet()::contains) .flatMap(cfgBlock -> getForbiddenCaseGroupPredecessors(cfgBlock, cfgBlockToCaseGroupMap)) .map(CaseGroupTree::labels) .map(caseGroupLabels -> caseGroupLabels.get(caseGroupLabels.size() - 1)) .forEach(label -> reportIssue(label, "End this switch case with an unconditional break, return or throw statement.")); }
Source:
public String read() throws IOException { byte[] bytes = null; if (getPath() != null) { StorageReader storageReader = getStorage().getStorageReader(getPath()); bytes = storageReader.read(); } else { StorageReader storageReader = getStorage().getStorageReader(getInputSplit()); if (skipFirst && getInputSplit().getStart() > 0) { byte[] skipBytes = storageReader.read(); if (log.isDebugEnabled()) { log.info("skipping first entry: " + new String(skipBytes)); } skipFirst = false; } bytes = storageReader.read(); } return bytes != null && bytes.length > 0 ? new String(bytes) : null; }

Target:
public String read() throws IOException { byte[] bytes = null; if (getPath() != null) { StorageReader storageReader = getStorage().getStorageReader(getPath()); bytes = storageReader.read(); } else { StorageReader storageReader = getStorage().getStorageReader(getInputSplit()); if (skipFirst.compareAndSet(true, false) && getInputSplit().getStart() > 0) { byte[] skipBytes = storageReader.read(); if (log.isDebugEnabled()) { log.info("skipping first entry: " + new String(skipBytes)); } } bytes = storageReader.read(); } return bytes != null && bytes.length > 0 ? new String(bytes) : null; }
Source:
private FeatureType buildFeatureType( FeatureTypeInfo info, boolean handleProjectionPolicy, FeatureType ft) throws IOException { if (ft instanceof SimpleFeatureType) { SimpleFeatureType sft = (SimpleFeatureType) ft; SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder(); tb.setName(info.getName()); tb.setNamespaceURI(info.getNamespace().getURI()); if (ft.getGeometryDescriptor() != null) { tb.setDefaultGeometry(ft.getGeometryDescriptor().getLocalName()); } if (info.getAttributes() == null || info.getAttributes().isEmpty()) { for (PropertyDescriptor pd : ft.getDescriptors()) { if (!(pd instanceof AttributeDescriptor)) { continue; } AttributeDescriptor ad = (AttributeDescriptor) pd; if (handleProjectionPolicy) { ad = handleDescriptor(ad, info); } tb.add(ad); } } else { for (AttributeTypeInfo att : info.getAttributes()) { String attName = att.getName(); PropertyDescriptor pd = ft.getDescriptor(attName); if (pd == null || !(pd instanceof AttributeDescriptor)) { throw new IOException( "the SimpleFeatureType " + info.getPrefixedName() + " does not contains the configured attribute " + attName + ". Check your schema configuration"); } AttributeDescriptor ad = (AttributeDescriptor) pd; ad = handleDescriptor(ad, info); tb.add(ad); } } ft = tb.buildFeatureType(); } return ft; }

Target:
private FeatureType buildFeatureType( FeatureTypeInfo info, boolean handleProjectionPolicy, FeatureType ft) throws IOException { if (ft instanceof SimpleFeatureType) { SimpleFeatureType sft = (SimpleFeatureType) ft; SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder(); tb.init(sft); tb.setName(info.getName()); tb.setNamespaceURI(info.getNamespace().getURI()); tb.setAttributes((AttributeDescriptor[]) null); if (info.getAttributes() == null || info.getAttributes().isEmpty()) { for (PropertyDescriptor pd : ft.getDescriptors()) { if (!(pd instanceof AttributeDescriptor)) { continue; } AttributeDescriptor ad = (AttributeDescriptor) pd; if (handleProjectionPolicy) { ad = handleDescriptor(ad, info); } tb.add(ad); } } else { for (AttributeTypeInfo att : info.getAttributes()) { String attName = att.getName(); PropertyDescriptor pd = ft.getDescriptor(attName); if (pd == null || !(pd instanceof AttributeDescriptor)) { throw new IOException( "the SimpleFeatureType " + info.getPrefixedName() + " does not contains the configured attribute " + attName + ". Check your schema configuration"); } AttributeDescriptor ad = (AttributeDescriptor) pd; ad = handleDescriptor(ad, info); tb.add(ad); } } ft = tb.buildFeatureType(); } return ft; }
Source:
public void before() { CONF.put("aws.region", "us-east-1"); mUdbConfiguration = new UdbConfiguration(CONF); mUdbContext = new UdbContext(null, null, "glue", "null", DB_NAME, DB_NAME); }

Target:
public void before() { Map<String, String> conf = ImmutableMap.of("aws.region", "us-east-1"); mUdbConfiguration = new UdbConfiguration(conf); mUdbContext = new UdbContext(null, null, "glue", "null", DB_NAME, DB_NAME); }
Source:
private void connectionNotEstablishedSend(final ByteBuffer buffer) { LOG.error("Trying to wait on {}. It has not connected yet.", this.getClass().getSimpleName()); if (!queing) { queing = true; failedStarts += 1; LOG.error("attempt out of {}", failedStarts, MAX_FAILED_STARTS); final Thread retryThread = new Thread() { @Override @SuppressWarnings("PMD.CommentRequired") public void run() { try { Thread.sleep(MIN_SLEEP_TIME); queing = false; send(buffer); } catch (InterruptedException e) { LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); } catch (ConnectionException e) { LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); } } }; retryThread.start(); } else { LOG.error("Adding a queuedMessage"); queuedMessages.add(buffer); } }

Target:
private void connectionNotEstablishedSend(final ByteBuffer buffer) { LOG.error("Trying to wait on {}. It has not connected yet.", this.getClass().getSimpleName()); if (!queing) { queing = true; failedStarts += 1; LOG.error("attempt out of {}", failedStarts, MAX_FAILED_STARTS); final Thread retryThread = new Thread() { @Override @SuppressWarnings("PMD.CommentRequired") public void run() { try { Thread.sleep(MIN_SLEEP_TIME); queing = false; send(buffer); } catch (InterruptedException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); } catch (ConnectionException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); } } }; retryThread.start(); } else { LOG.info("Adding a queuedMessage"); queuedMessages.add(buffer); LOG.info("queuedMessage size is now: {}", queuedMessages.size()); } }
Source:
private <T extends Serializable> T readFromMetastorage(String key) { metaLock.readLock().lock(); try { if (metastorage == null) return null; try { return metastorage.read(key); } catch (IgniteCheckedException e) { log.error("Error read from metastore.", e); return null; } } finally { metaLock.readLock().unlock(); } }

Target:
private <T extends Serializable> T readFromMetastorage(String key) { if (roMetastorage == null) return null; try { return roMetastorage.read(key); } catch (IgniteCheckedException e) { throw new IgniteException(e); } }
Source:
private void handleStartProvisioningIfNeeded(int type, boolean showProvisioningUi) { if (!isValidDownstreamType(type)) return; if (!mCurrentTethers.contains(type)) mCurrentTethers.add(type); mCallback.onMaybeStartProvisioning(); if (isTetherProvisioningRequired()) { if (mCellularPermitted.size() == 0) { mCellularUpstreamPermitted = false; } if (mUsingCellularAsUpstream) { if (showProvisioningUi) { runUiTetherProvisioning(type); } else { runSilentTetherProvisioning(type); } mNeedReRunProvisioningUi = false; } else { mNeedReRunProvisioningUi |= showProvisioningUi; } } else { mCellularUpstreamPermitted = true; } }

Target:
private void handleStartProvisioningIfNeeded(int type, boolean showProvisioningUi) { if (!isValidDownstreamType(type)) return; if (!mCurrentTethers.contains(type)) mCurrentTethers.add(type); mCallback.onBeforeProvisioning(); if (isTetherProvisioningRequired()) { if (mCellularPermitted.size() == 0) { mCellularUpstreamPermitted = false; } if (mUsingCellularAsUpstream) { if (showProvisioningUi) { runUiTetherProvisioning(type); } else { runSilentTetherProvisioning(type); } mNeedReRunProvisioningUi = false; } else { mNeedReRunProvisioningUi |= showProvisioningUi; } } else { mCellularUpstreamPermitted = true; } }
Source:
public void g_V_out_in_valuesXnameX_fold_dedupXlocalX_unfold() { final Traversal<Vertex, String> traversal = get_g_V_out_in_valuesXnameX_fold_dedupXlocalX_unfold(); final List<String> names = traversal.toList(); assertEquals(3, names.size()); assertThat(names, containsInAnyOrder("marko", "josh", "peter")); }

Target:
public void g_V_out_in_valuesXnameX_fold_dedupXlocalX_unfold() { final Traversal<Vertex, String> traversal = get_g_V_out_in_valuesXnameX_fold_dedupXlocalX_unfold(); printTraversalForm(traversal); checkResults(Arrays.asList("marko", "josh", "peter"), traversal); }
Source:
public Response getLabel(@QueryParam("target_date_millis") final Long targetDayTimestamp, @QueryParam("timezone_offset_millis") final Integer timeZoneOffset, @Scope({OAuthScope.SLEEP_LABEL_BASIC}) final AccessToken accessToken){ if(targetDayTimestamp == null || timeZoneOffset == null){ return Response.status(Response.Status.BAD_REQUEST).build(); } final DateTimeZone userLocalTimeZone = DateTimeZone.forOffsetMillis(timeZoneOffset); final DateTime userLocalDateTime = new DateTime(targetDayTimestamp, userLocalTimeZone).withTimeAtStartOfDay(); final DateTime roundedUserLocalTimeInUTC = new DateTime(userLocalDateTime.getMillis(), DateTimeZone.UTC); final Optional<SleepLabel> sleepLabelOptional = sleepLabelDAO.getByAccountAndDate( accessToken.accountId, roundedUserLocalTimeInUTC, timeZoneOffset ); if(sleepLabelOptional.isPresent()){ return Response.ok(sleepLabelOptional.get()).build(); }else{ return Response.status(Response.Status.NO_CONTENT).build(); } }

Target:
public Response getLabel(@QueryParam("target_date_millis") final Long targetDayTimestamp, @QueryParam("timezone_offset_millis") final Integer timeZoneOffset, @Scope({OAuthScope.SLEEP_LABEL_BASIC}) final AccessToken accessToken){ if(targetDayTimestamp == null || timeZoneOffset == null){ return Response.status(Response.Status.BAD_REQUEST).build(); } final DateTimeZone userLocalTimeZone = DateTimeZone.forOffsetMillis(timeZoneOffset); final DateTime userLocalDateTime = new DateTime(targetDayTimestamp, userLocalTimeZone).withTimeAtStartOfDay(); final DateTime roundedUserLocalTimeInUTC = new DateTime(userLocalDateTime.getMillis(), DateTimeZone.UTC); final Optional<SleepLabel> sleepLabelOptional = sleepLabelDAO.getByAccountAndDate( accessToken.accountId, roundedUserLocalTimeInUTC, timeZoneOffset ); if(sleepLabelOptional.isPresent()){ return Response.ok(sleepLabelOptional.get()).build(); }else{ return Response.status(Response.Status.NOT_FOUND).build(); } }
Source:
public Region(String chromosome, int start) { this.chromosome = chromosome; this.start = start; this.end = Integer.MAX_VALUE; }

Target:
public Region(String chromosome, int start) { this(chromosome, start, Integer.MAX_VALUE); }
Source:
public ITransformedNetwork getTransformedApprovedNetworks(List<INetwork> networkList) throws QuadrigaStorageException { ITransformedNetwork networkJSon = null; List<INetworkNodeInfo> networkTopNodesList = new ArrayList<INetworkNodeInfo>(); for(INetwork curnetwork: networkList){ try { List<INetworkNodeInfo> curTopNodesList = networkManager.getNetworkTopNodes(curnetwork.getNetworkId()); networkTopNodesList.addAll(curTopNodesList) ; } catch (QuadrigaStorageException e) { logger.error("DB Error while getting network top nodes", e); return null; } } networkJSon = transformer.transformNetwork(networkTopNodesList); return networkJSon; }

Target:
public ITransformedNetwork getTransformedApprovedNetworks(List<INetwork> networkList) throws QuadrigaStorageException { List<INetworkNodeInfo> networkTopNodesList = new ArrayList<INetworkNodeInfo>(); for(INetwork curnetwork: networkList){ try { List<INetworkNodeInfo> curTopNodesList = networkManager.getNetworkTopNodes(curnetwork.getNetworkId()); networkTopNodesList.addAll(curTopNodesList) ; } catch (QuadrigaStorageException e) { logger.error("DB Error while getting network top nodes", e); throw e; } } return transformer.transformNetwork(networkTopNodesList); }
Source:
public void dropFunction(QualifiedFunctionName functionName, Optional<List<TypeSignature>> parameterTypes, boolean exists) { Optional<FunctionNamespaceManager<?>> functionNamespaceManager = getServingFunctionNamespaceManager(functionName.getFunctionNamespace()); if (!functionNamespaceManager.isPresent()) { throw new PrestoException(GENERIC_USER_ERROR, format("Cannot drop function in function namespace: %s", functionName.getFunctionNamespace())); } functionNamespaceManager.get().dropFunction(functionName, parameterTypes, exists); }

Target:
public void dropFunction(QualifiedFunctionName functionName, Optional<List<TypeSignature>> parameterTypes, boolean exists) { Optional<FunctionNamespaceManager<?>> functionNamespaceManager = getServingFunctionNamespaceManager(functionName.getFunctionNamespace()); if (functionNamespaceManager.isPresent()) { functionNamespaceManager.get().dropFunction(functionName, parameterTypes, exists); } else if (!exists) { throw new PrestoException(FUNCTION_NOT_FOUND, format("Function not found: %s", functionName.getFunctionNamespace())); } }
Source:
public ValidationResult nicNameIsSet() { return ValidationResult.failWith(EngineMessage.HOST_NETWORK_INTERFACE_NOT_EXIST) .when(attachment.getNicName() == null); }

Target:
public ValidationResult nicNameIsSet() { return ValidationResult.failWith(EngineMessage.HOST_NETWORK_INTERFACE_DOES_NOT_HAVE_NAME_SET) .when(attachment.getNicName() == null); }
Source:
public void testTaskFailedUpdate() { AnnotationConfigApplicationContext createContext = new AnnotationConfigApplicationContext(); createContext.register(TestDefaultConfiguration.class, PropertyPlaceholderAutoConfiguration.class); createContext.refresh(); final Appender mockAppender = TestVerifierUtils.getMockAppender(); this.listener = createContext.getBean(TaskLifecycleListener.class); listener.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[]{}, createContext, new RuntimeException("This was expected"))); TestVerifierUtils.verifyLogEntryExists(mockAppender, "Updating: TaskExecution{executionId='" + listener.getTaskExecution().getExecutionId()); assertEquals("Update should report that exit code is zero", 1, listener.getTaskExecution().getExitCode()); assertTrue("Stack trace missing from exit message", listener.getTaskExecution().getExitMessage().startsWith("java.lang.RuntimeException: This was expected")); }

Target:
public void testTaskFailedUpdate() { context.refresh(); final Appender mockAppender = TestVerifierUtils.getMockAppender(); this.listener = context.getBean(TaskLifecycleListener.class); listener.onApplicationEvent(new ApplicationFailedEvent(new SpringApplication(), new String[]{}, context, new RuntimeException("This was expected"))); TestVerifierUtils.verifyLogEntryExists(mockAppender, "Updating: TaskExecution{executionId='" + listener.getTaskExecution().getExecutionId()); assertEquals("Update should report that exit code is one", 1, listener.getTaskExecution().getExitCode()); assertTrue("Stack trace missing from exit message", listener.getTaskExecution().getExitMessage().startsWith("java.lang.RuntimeException: This was expected")); }
Source:
public Subsorts(Module module) { sorts = JavaConversions.asJavaCollection(module.definedSorts()).stream() .map(s -> Sort.of(s.name())) .collect(Collectors.toSet()); this.subsort = ArrayTable.create(sorts, sorts); Set<org.kframework.kore.Sort> kSorts = Sets.newHashSet(Sorts.K(), Sorts.KList(), Sorts.KItem(), Sorts.KLabel(), Sorts.KBott(), Sorts.KVariable(), Sorts.KString()); for (org.kframework.kore.Sort sort1 : Collections.iterable(module.definedSorts())) { for (org.kframework.kore.Sort sort2 : Collections.iterable(module.definedSorts())) { subsort.put( Sort.of(sort1.name()), Sort.of(sort2.name()), module.subsorts().$greater(sort1, sort2)); } } }

Target:
public Subsorts(Module module) { sorts = JavaConversions.asJavaCollection(module.definedSorts()).stream() .map(s -> Sort.of(s.name())) .collect(Collectors.toSet()); this.subsort = ArrayTable.create(sorts, sorts); for (org.kframework.kore.Sort sort1 : Collections.iterable(module.definedSorts())) { for (org.kframework.kore.Sort sort2 : Collections.iterable(module.definedSorts())) { subsort.put( Sort.of(sort1.name()), Sort.of(sort2.name()), module.subsorts().$greater(sort1, sort2)); } } }
Source:
public void testEntrySetRemove() { Map<Object, String> values = putValuesInCache(); final Cache<Object, Object> cache = cache(0, CACHE_NAME); cache.getAdvancedCache().addInterceptor(new BaseCustomInterceptor() { @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { assertTrue(command.hasAnyFlag(FlagBitSets.SKIP_CACHE_STORE)); return super.visitRemoveCommand(ctx, command); } }, 0); for (Iterator<Map.Entry<Object, Object>> it = cache(0, CACHE_NAME).getAdvancedCache().withFlags( Flag.SKIP_CACHE_STORE).entrySet().iterator(); it.hasNext();) { Map.Entry<Object, Object> entry = it.next(); Object key = entry.getKey(); assertEquals(values.get(key), entry.getValue()); it.remove(); } for (Iterator<Map.Entry<Object, Object>> it = cache(0, CACHE_NAME).getAdvancedCache().withFlags( Flag.SKIP_CACHE_STORE).entrySet().iterator(); it.hasNext();) { Map.Entry<Object, Object> entry = it.next(); log.tracef("%s", entry); } assertEquals(0, cache.size()); }

Target:
public void testEntrySetRemove() { Map<Object, String> values = putValuesInCache(); final Cache<Object, Object> cache = cache(0, CACHE_NAME); cache.getAdvancedCache().addInterceptor(new BaseCustomInterceptor() { @Override public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable { assertTrue(command.hasAnyFlag(FlagBitSets.SKIP_CACHE_STORE)); return super.visitRemoveCommand(ctx, command); } }, 0); for (Iterator<Map.Entry<Object, Object>> it = cache(0, CACHE_NAME).getAdvancedCache().withFlags( Flag.SKIP_CACHE_STORE).entrySet().iterator(); it.hasNext();) { Map.Entry<Object, Object> entry = it.next(); Object key = entry.getKey(); assertEquals(values.get(key), entry.getValue()); it.remove(); } assertEquals(0, cache.size()); }
Source:
public void testInvertSortKey() { assertEquals("FFFFFFFFFFFFFFFF", ChangeUtil.invertSortKey( "0000000000000000").toUpperCase()); assertEquals("0000000000000001", ChangeUtil.invertSortKey( "FFFFFFFFFFFFFFFE").toUpperCase()); assertEquals("0001600000000000", ChangeUtil.invertSortKey( "FFFE9FFFFFFFFFFF").toUpperCase()); assertEquals("/", ChangeUtil.invertSortKey("z").toUpperCase()); assertEquals("Z", ChangeUtil.invertSortKey("/").toUpperCase()); }

Target:
public void testInvertSortKey() { assertEquals("FFFFFFFFFFFFFFFF", ChangeUtil.invertSortKey( "0000000000000000").toUpperCase()); assertEquals("0000000000000001", ChangeUtil .invertSortKey("FFFFFFFFFFFFFFFE")); assertEquals("0001600000000000", ChangeUtil .invertSortKey("FFFE9FFFFFFFFFFF")); assertEquals("/", ChangeUtil.invertSortKey("z")); assertEquals("Z", ChangeUtil.invertSortKey("/").toUpperCase()); }
Source:
public void testChangeModeToDisabledAndBack() throws Exception { HaMgmtNode n1 = createMaster(Duration.PRACTICALLY_FOREVER); n1.mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachine.class)); @SuppressWarnings("unused") TestApplication app = createFirstAppAndPersist(n1); HaMgmtNode n2 = createHotStandby(Duration.PRACTICALLY_FOREVER); n1.ha.changeMode(HighAvailabilityMode.DISABLED); n2.ha.changeMode(HighAvailabilityMode.AUTO); assertMaster(n2); assertEquals(n1.ha.getNodeState(), ManagementNodeState.FAILED); Assert.assertTrue(n1.mgmt.getApplications().isEmpty(), "n1 should have had no apps; instead had: "+n1.mgmt.getApplications()); Assert.assertTrue(n1.mgmt.getEntityManager().getEntities().isEmpty(), "n1 should have had no entities; instead had: "+n1.mgmt.getEntityManager().getEntities()); Assert.assertTrue(n1.mgmt.getLocationManager().getLocations().isEmpty(), "n1 should have had no locations; instead had: "+n1.mgmt.getLocationManager().getLocations()); n1.ha.changeMode(HighAvailabilityMode.HOT_STANDBY); assertHotStandby(n1); Assert.assertFalse(n1.mgmt.getApplications().isEmpty(), "n1 should have had apps now"); Assert.assertFalse(n1.mgmt.getApplications().isEmpty(), "n1 should have had locations now"); n2.ha.changeMode(HighAvailabilityMode.DISABLED); n1.ha.changeMode(HighAvailabilityMode.AUTO); assertMaster(n1); assertEquals(n2.ha.getNodeState(), ManagementNodeState.FAILED); }

Target:
public void testChangeModeToDisabledAndBack() throws Exception { HaMgmtNode n1 = createMaster(Duration.PRACTICALLY_FOREVER); n1.mgmt.getLocationManager().createLocation(LocationSpec.create(LocalhostMachine.class)); @SuppressWarnings("unused") TestApplication app = createFirstAppAndPersist(n1); HaMgmtNode n2 = createHotStandby(Duration.PRACTICALLY_FOREVER); n1.ha.changeMode(HighAvailabilityMode.DISABLED); n2.ha.changeMode(HighAvailabilityMode.AUTO); assertMaster(n2); assertEquals(n1.ha.getNodeState(), ManagementNodeState.FAILED); Assert.assertTrue(n1.mgmt.getApplications().isEmpty(), "n1 should have had no apps; instead had: "+n1.mgmt.getApplications()); Assert.assertTrue(n1.mgmt.getEntityManager().getEntities().isEmpty(), "n1 should have had no entities; instead had: "+n1.mgmt.getEntityManager().getEntities()); Assert.assertTrue(n1.mgmt.getLocationManager().getLocations().isEmpty(), "n1 should have had no locations; instead had: "+n1.mgmt.getLocationManager().getLocations()); n1.ha.changeMode(HighAvailabilityMode.HOT_STANDBY); assertHotStandby(n1); Assert.assertFalse(n1.mgmt.getApplications().isEmpty(), "n1 should have had apps now"); Assert.assertFalse(n1.mgmt.getLocationManager().getLocations().isEmpty(), "n1 should have had locations now"); n2.ha.changeMode(HighAvailabilityMode.DISABLED); n1.ha.changeMode(HighAvailabilityMode.AUTO); assertMaster(n1); assertEquals(n2.ha.getNodeState(), ManagementNodeState.FAILED); }
Source:
public AbstractHttpRequestExecutingMessageHandler(Expression uriExpression) { Assert.notNull(uriExpression, "URI Expression is required"); this.uriExpression = uriExpression; this.uriFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.TEMPLATE_AND_VALUES); }

Target:
public AbstractHttpRequestExecutingMessageHandler(Expression uriExpression) { Assert.notNull(uriExpression, "URI Expression is required"); this.uriExpression = uriExpression; }
Source:
public void testResetFromWatcher() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); final CountDownLatch latch = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if ( event.getType() == Event.EventType.NodeCreated ) { try { removerClient.checkExists().usingWatcher(this).forPath("/yo"); } catch ( Exception e ) { e.printStackTrace(); } } else if ( event.getType() == Event.EventType.NodeDeleted ) { latch.countDown(); } } }; removerClient.checkExists().usingWatcher(watcher).forPath("/yo"); Assert.assertEquals(removerClient.getRemovalManager().getEntries().size(), 1); removerClient.create().forPath("/yo"); timing.sleepABit(); Assert.assertEquals(removerClient.getRemovalManager().getEntries().size(), 1); removerClient.delete().forPath("/yo"); Assert.assertTrue(timing.awaitLatch(latch)); Assert.assertEquals(removerClient.getRemovalManager().getEntries().size(), 0); } finally { CloseableUtils.closeQuietly(client); } }

Target:
public void testResetFromWatcher() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try { client.start(); final WatcherRemovalFacade removerClient = (WatcherRemovalFacade)client.newWatcherRemoveCuratorFramework(); final CountDownLatch createdLatch = new CountDownLatch(1); final CountDownLatch deletedLatch = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if ( event.getType() == Event.EventType.NodeCreated ) { try { removerClient.checkExists().usingWatcher(this).forPath("/yo"); } catch ( Exception e ) { e.printStackTrace(); } createdLatch.countDown(); } else if ( event.getType() == Event.EventType.NodeDeleted ) { deletedLatch.countDown(); } } }; removerClient.checkExists().usingWatcher(watcher).forPath("/yo"); Assert.assertEquals(removerClient.getRemovalManager().getEntries().size(), 1); removerClient.create().forPath("/yo"); Assert.assertTrue(timing.awaitLatch(createdLatch)); Assert.assertEquals(removerClient.getRemovalManager().getEntries().size(), 1); removerClient.delete().forPath("/yo"); Assert.assertTrue(timing.awaitLatch(deletedLatch)); Assert.assertEquals(removerClient.getRemovalManager().getEntries().size(), 0); } finally { CloseableUtils.closeQuietly(client); } }
Source:
public void readsOneChunk() throws IOException { final String data = "1234567890abcdef"; final String length = Integer.toHexString(data.length()); final InputStream stream = new RqChunk( new RqFake( Arrays.asList( "GET /h?a=1", "Host: www.example.com", CHUNKED_HEADER ), Joiner.on(CRLF).join( length, data, END_OF_CHUNK ) ) ).body(); final byte[] buf = new byte[data.length()]; MatcherAssert.assertThat( stream.read(buf), Matchers.equalTo(data.length()) ); MatcherAssert.assertThat(buf, Matchers.equalTo(data.getBytes())); MatcherAssert.assertThat(stream.available(), Matchers.equalTo(0)); }

Target:
public void readsOneChunk() throws IOException { final String data = "1234567890abcdef"; final String length = Integer.toHexString(data.length()); final InputStream stream = new RqChunk( new RqFake( Arrays.asList( "GET /h?a=1", "Host: www.example.com", CHUNKED_HEADER ), Joiner.on(CRLF).join( length, data, END_OF_CHUNK, "" ) ) ).body(); final byte[] buf = new byte[data.length()]; MatcherAssert.assertThat( stream.read(buf), Matchers.equalTo(data.length()) ); MatcherAssert.assertThat(buf, Matchers.equalTo(data.getBytes())); MatcherAssert.assertThat(stream.available(), Matchers.equalTo(0)); }