auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testGetAllIpBlocks() { List<IpBlock> ipBlocks = api.ipBlockApi().getAllIpBlock(); assertNotNull(ipBlocks); }

Target:
public void testGetAllIpBlocks() { List<IpBlock> ipBlocks = api.ipBlockApi().getAllIpBlock(); assertNotNull(ipBlocks); assertFalse(ipBlocks.isEmpty()); }
Source:
public V get(final String key) { return super.get(key.toLowerCase()); }

Target:
public V get(final String key) { return this.map.get(key.toLowerCase()); }
Source:
private synchronized Pair<Item, Boolean> getItem( @NonNull File inputFile, @NonNull File outFile, @NonNull BuildToolInfo buildToolInfo) throws IOException { Key itemKey = Key.of(inputFile, buildToolInfo.getRevision()); Item item = mMap.get(itemKey); boolean newItem = false; if (item == null) { item = new Item(inputFile, outFile, Files.hash(inputFile, Hashing.sha1()), new CountDownLatch(1)); mMap.put(itemKey, item); newItem = true; } return Pair.of(item, newItem); }

Target:
private synchronized Pair<Item, Boolean> getItem( @NonNull File inputFile, @NonNull File outFile, @NonNull BuildToolInfo buildToolInfo) throws IOException { Key itemKey = Key.of(inputFile, buildToolInfo.getRevision()); Item item = mMap.get(itemKey); boolean newItem = (item == null); if (item == null) { item = new Item(inputFile, outFile, Files.hash(inputFile, Hashing.sha1()), new CountDownLatch(1)); mMap.put(itemKey, item); } return Pair.of(item, newItem); }
Source:
public boolean repeatUntilResponseIsNot(final String expectedResponse) { RepeatCompletion completion; if (expectedResponse == null) { completion = new RepeatLastCall() { @Override public boolean isFinished() { return response() == null; } }; } else { completion = new RepeatLastCall() { @Override public boolean isFinished() { Object actual = response(); return !compareActualToExpected(expectedResponse, actual); } }; } return repeatUntil(completion); }

Target:
public boolean repeatUntilResponseIsNot(final String expectedResponse) { return repeatUntilNot(createResponseIsCompletion(expectedResponse)); }
Source:
private List<NameValuePair> buildCommonParams(Site site, int start, int rows, SearchCriterion sortOrder, SearchCriterion dateRange, boolean forHomePage, Map<String, String> rawQueryParams) { List<NameValuePair> params = buildCommonParams(site, start,rows,sortOrder, dateRange, forHomePage); Iterator it = rawQueryParams.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>)it.next(); params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return params; }

Target:
private List<NameValuePair> buildCommonParams(Site site, int start, int rows, SearchCriterion sortOrder, SearchCriterion dateRange, boolean forHomePage, Map<String, String> rawQueryParams) { List<NameValuePair> params = buildCommonParams(site, start,rows,sortOrder, dateRange, forHomePage); for (Map.Entry<String, String> entry: rawQueryParams.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } return params; }
Source:
public void inflateDisbursementDate() { mfDatePicker = MFDatePicker.newInsance(this); loanDisbursementDates.setText(MFDatePicker.getDatePickedAsString()); loanDisbursementDates.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mfDatePicker.show(getActivity().getSupportFragmentManager(), FragmentConstants .DFRAG_DATE_PICKER); } }); }

Target:
public void inflateDisbursementDate() { mfDatePicker = MFDatePicker.newInsance(this); tvLoanDisbursementDates.setText(MFDatePicker.getDatePickedAsString()); }
Source:
private int readOneBlock(final byte[] b, final int off, final int len) throws IOException { int validation = validate(b, off, len); if (validation < 1) { return validation; } if (bCursor == limit) { if (fCursor >= contentLength) { return -1; } long bytesRead = 0; bCursor = 0; limit = 0; if (buffer == null) { LOG.debug("created new buffer size {}", bufferSize); buffer = new byte[bufferSize]; } if (-1 == fCursorAfterLastRead || fCursorAfterLastRead == fCursor || b.length >= bufferSize) { bytesRead = readInternal(fCursor, buffer, 0, bufferSize, false); } else { bytesRead = readInternal(fCursor, buffer, 0, b.length, true); } if (bytesRead == -1) { return -1; } limit += bytesRead; fCursor += bytesRead; fCursorAfterLastRead = fCursor; } return copyToUserBuffer(b, off, len); }

Target:
private int readOneBlock(final byte[] b, final int off, final int len) throws IOException { if (len == 0) { return 0; } if (!validate(b, off, len)) { return -1; } if (bCursor == limit) { if (fCursor >= contentLength) { return -1; } long bytesRead = 0; bCursor = 0; limit = 0; if (buffer == null) { LOG.debug("created new buffer size {}", bufferSize); buffer = new byte[bufferSize]; } if (alwaysReadBufferSize) { bytesRead = readInternal(fCursor, buffer, 0, bufferSize, false); } else { if (-1 == fCursorAfterLastRead || fCursorAfterLastRead == fCursor || b.length >= bufferSize) { bytesRead = readInternal(fCursor, buffer, 0, bufferSize, false); } else { bytesRead = readInternal(fCursor, buffer, 0, b.length, true); } } if (firstRead) { firstRead = false; } if (bytesRead == -1) { return -1; } limit += bytesRead; fCursor += bytesRead; fCursorAfterLastRead = fCursor; } return copyToUserBuffer(b, off, len); }
Source:
Optional<VintageTestDescriptor> lookupTestDescriptor(Description description) { List<VintageTestDescriptor> descriptors = descriptionToDescriptors.get(description); if (descriptors == null) { return Optional.empty(); } if (descriptors.size() == 1) { return Optional.of(getOnlyElement(descriptors)); } return descriptors.stream() .filter(testDescriptor -> { @SuppressWarnings("ReferenceEquality") boolean result = (description == testDescriptor.getDescription()); return result; }) .findFirst(); }

Target:
Optional<VintageTestDescriptor> lookupTestDescriptor(Description description) { List<VintageTestDescriptor> descriptors = descriptionToDescriptors.get(description); if (descriptors == null) { return Optional.empty(); } if (descriptors.size() == 1) { return Optional.of(getOnlyElement(descriptors)); } return descriptors.stream() .filter(testDescriptor -> description == testDescriptor.getDescription()) .findFirst(); }
Source:
public Condition createCondition(Condition condition) { List<String> errors = new ArrayList<>(); if (condition.isEmpty()) { errors.add("Condition resource is null"); return null; } if (condition.getSubject().isEmpty()) { errors.add("No subject"); return null; } org.openmrs.Condition openMrsCondition = Context.getService(org.openmrs.api.ConditionService.class) .saveCondition(generateOpenMrsCondition(condition)); FHIRUtils.checkGeneratorErrorList(errors); return generateFHIRCondition(openMrsCondition); }

Target:
public Condition createCondition(Condition condition) { if (condition.isEmpty()) { throw new UnprocessableEntityException("condition resource cannot be null"); } if (condition.getSubject().isEmpty()) { throw new UnprocessableEntityException("condition subject cannot be null"); } org.openmrs.Condition openMrsCondition = Context.getService(org.openmrs.api.ConditionService.class) .saveCondition(generateOpenMrsCondition(condition)); return generateFHIRCondition(openMrsCondition); }
Source:
protected void handleCleanStatefulCheckpointRequest( REQID rid, SocketChannel channel, CheckpointManager.CleanStatefulCheckpointRequest request ) { LOG.info("Got a clean request from " + request.toString() + " host:port " + channel.socket().getRemoteSocketAddress()); boolean res = checkpointsBackend.dispose(request, topologyName); Common.StatusCode statusCode = res ? Common.StatusCode.OK : Common.StatusCode.NOTOK; CheckpointManager.CleanStatefulCheckpointResponse.Builder responseBuilder = CheckpointManager.CleanStatefulCheckpointResponse.newBuilder(); responseBuilder.setStatus(Common.Status.newBuilder().setStatus(statusCode)); if (res) { LOG.info("Dispose checkpoint successful"); } else { LOG.info("Dispose checkpoint not successful"); } sendResponse(rid, channel, responseBuilder.build()); }

Target:
protected void handleCleanStatefulCheckpointRequest( REQID rid, SocketChannel channel, CheckpointManager.CleanStatefulCheckpointRequest request ) { LOG.info(String.format("Got a clean request from %s running at host:port %s", request.toString(), channel.socket().getRemoteSocketAddress())); boolean deleteAll = request.hasCleanAllCheckpoints() && request.getCleanAllCheckpoints(); Common.StatusCode statusCode = Common.StatusCode.OK; String errorMessage = ""; try { statefulStorage.dispose(topologyName, request.getOldestCheckpointPreserved(), deleteAll); LOG.info("Dispose checkpoint successful"); } catch (StatefulStorageException e) { errorMessage = String.format("Request to dispose checkpoint failed for oldest Checkpoint " + "%s and deleteAll? %b", request.getOldestCheckpointPreserved(), deleteAll); statusCode = Common.StatusCode.NOTOK; LOG.log(Level.WARNING, errorMessage, e); } CheckpointManager.CleanStatefulCheckpointResponse.Builder responseBuilder = CheckpointManager.CleanStatefulCheckpointResponse.newBuilder(); responseBuilder.setStatus(Common.Status.newBuilder().setStatus(statusCode) .setMessage(errorMessage)); sendResponse(rid, channel, responseBuilder.build()); }
Source:
private void throwIfInvalidGroupMetadata(ConsumerGroupMetadata groupMetadata) { if (groupMetadata == null) { throw new IllegalStateException("Consumer group metadata could not be null"); } else if (groupMetadata.groupId() == null) { throw new IllegalStateException("Passed in group metadata " + groupMetadata + " has empty group.id"); } else if (groupMetadata.generationId() > 0 && JoinGroupRequest.UNKNOWN_MEMBER_ID.equals(groupMetadata.memberId())) { throw new IllegalStateException("Passed in group metadata " + groupMetadata + " has generationId > 0 but member.id "); } }

Target:
private void throwIfInvalidGroupMetadata(ConsumerGroupMetadata groupMetadata) { if (groupMetadata == null) { throw new IllegalArgumentException("Consumer group metadata could not be null"); } else if (groupMetadata.generationId() > 0 && JoinGroupRequest.UNKNOWN_MEMBER_ID.equals(groupMetadata.memberId())) { throw new IllegalArgumentException("Passed in group metadata " + groupMetadata + " has generationId > 0 but member.id "); } }
Source:
public Set<Command> getCommands() { Set<Command> commands = new HashSet<>(); commands.add(new ActivateCommand()); commands.add(new DeprecatedActivateCommand()); commands.add(new AttachCommand()); commands.add(new DeprecatedAttachCommand()); commands.add(new DetachCommand()); commands.add(new DeprecatedDetachCommand()); commands.add(new ImportCommand()); commands.add(new DeprecatedImportCommand()); commands.add(new ExportCommand()); commands.add(new DeprecatedExportCommand()); commands.add(new GetCommand()); commands.add(new DeprecatedGetCommand()); commands.add(new SetCommand()); commands.add(new DeprecatedSetCommand()); commands.add(new UnsetCommand()); commands.add(new DeprecatedUnsetCommand()); commands.add(new DiagnosticCommand()); commands.add(new DeprecatedDiagnosticCommand()); commands.add(new RepairCommand()); commands.add(new DeprecatedRepairCommand()); commands.add(new LogCommand()); commands.add(new DeprecatedLogCommand()); commands.add(new LockConfigCommand()); commands.add(new DeprecatedLockConfigCommand()); commands.add(new UnlockConfigCommand()); commands.add(new DeprecatedUnlockConfigCommand()); return commands; }

Target:
public Map<String, Command> getCommands() { Map<String, Command> commands = new HashMap<>(); commands.put("activate", new ActivateCommand()); commands.put("attach", new AttachCommand()); commands.put("detach", new DetachCommand()); commands.put("import", new ImportCommand()); commands.put("export", new ExportCommand()); commands.put("get", new GetCommand()); commands.put("set", new SetCommand()); commands.put("unset", new UnsetCommand()); commands.put("diagnostic", new DiagnosticCommand()); commands.put("repair", new RepairCommand()); commands.put("log", new LogCommand()); commands.put("lock-config", new LockConfigCommand()); commands.put("unlock-config", new UnlockConfigCommand()); return unmodifiableMap(commands); }
Source:
protected String getValue(Environment env, Map params) throws TemplateModelException, IOException { String path = getStringValue(params.get("path")); String targetJournal = getStringValue(params.get("journalKey")); String handlerName = getStringValue(params.get("handlerName")); boolean absoluteLink = getBoolValue(params.get("absoluteLink")); boolean urlDecodeLink = getBoolValue(params.get("urlDecodeLink")); SitePageContext sitePageContext = new SitePageContext(siteResolver, env); Site site = sitePageContext.getSite(); Link.Factory linkFactory = (targetJournal == null) ? (absoluteLink ? Link.toAbsoluteAddress(site) : Link.toLocalSite(site)) : Link.toForeignSite(site, targetJournal, siteSet); final Link link; if (handlerName != null) { Map<String, ?> variables = TemplateModelUtil.getAsMap((TemplateModel) params.get("pathVariables")); ListMultimap<String, ?> queryParameters = TemplateModelUtil.getAsMultimap((TemplateModel) params.get("queryParameters")); List<?> wildcardValues = TemplateModelUtil.getAsList((TemplateModel) params.get("wildcardValues")); link = linkFactory.toPattern(requestMappingContextDictionary, handlerName, variables, queryParameters, wildcardValues); } else if (path != null) { link = linkFactory.toPath(path); } else { throw new RuntimeException("Either a path or handlerName parameter is required"); } String url = link.get(sitePageContext.getRequest()); if (urlDecodeLink) { url = URLDecoder.decode(url, "UTF-8"); } return url; }

Target:
protected String getValue(Environment env, Map params) throws TemplateModelException, IOException { String path = getStringValue(params.get("path")); String targetJournal = getStringValue(params.get("journalKey")); String handlerName = getStringValue(params.get("handlerName")); boolean absoluteLink = getBoolValue(params.get("absoluteLink")); SitePageContext sitePageContext = new SitePageContext(siteResolver, env); Site site = sitePageContext.getSite(); Link.Factory linkFactory = (targetJournal == null) ? (absoluteLink ? Link.toAbsoluteAddress(site) : Link.toLocalSite(site)) : Link.toForeignSite(site, targetJournal, siteSet); final Link link; if (handlerName != null) { Map<String, ?> variables = TemplateModelUtil.getAsMap((TemplateModel) params.get("pathVariables")); ListMultimap<String, ?> queryParameters = TemplateModelUtil.getAsMultimap((TemplateModel) params.get("queryParameters")); List<?> wildcardValues = TemplateModelUtil.getAsList((TemplateModel) params.get("wildcardValues")); link = linkFactory.toPattern(requestMappingContextDictionary, handlerName, variables, queryParameters, wildcardValues); } else if (path != null) { link = linkFactory.toPath(path); } else { throw new RuntimeException("Either a path or handlerName parameter is required"); } return link.get(sitePageContext.getRequest()); }
Source:
public boolean deleteCertificate(String alias) throws CertificateManagerException { final Map<String, String> trustStoreProperties = getTrustStoreSystemProperties(); String storeType = trustStoreProperties.get(TRUST_STORE_TYPE_KEY); final String storeLoc = trustStoreProperties.get(TRUST_STORE_KEY); final String passkey = trustStoreProperties.get(TRUST_STORE_PASSWORD_KEY); FileInputStream is = null; FileOutputStream os = null; boolean isDeleteSuccessful = false; try { KeyStore tstore = KeyStore.getInstance(storeType); if (!PKCS11_TYPE.equalsIgnoreCase(storeType)) { is = new FileInputStream(storeLoc); } tstore.load(is, passkey.toCharArray()); X509Certificate publicCert = getDefaultCertificate(null); String publicAlias = tstore.getCertificateAlias(publicCert); if (StringUtils.equalsIgnoreCase(alias, publicAlias)) { throw new CertificateManagerException("System cannot remove its own public cert"); } if (tstore.containsAlias(alias)) { tstore.deleteEntry(alias); os = new FileOutputStream(storeLoc); tstore.store(os, passkey.toCharArray()); isDeleteSuccessful = true; } } catch (final IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException ex) { LOG.error("Unable to delete the Certifiate: ", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getMessage(), ex); } finally { closeStream(is, os); } return isDeleteSuccessful; }

Target:
public boolean deleteCertificate(String alias) throws CertificateManagerException { final Map<String, String> trustStoreProperties = getTrustStoreSystemProperties(); String storeType = trustStoreProperties.get(TRUST_STORE_TYPE_KEY); final String storeLoc = trustStoreProperties.get(TRUST_STORE_KEY); final String passkey = trustStoreProperties.get(TRUST_STORE_PASSWORD_KEY); FileInputStream is = null; FileOutputStream os = null; boolean isDeleteSuccessful = false; try { KeyStore tstore = KeyStore.getInstance(storeType); if (!PKCS11_TYPE.equalsIgnoreCase(storeType)) { is = new FileInputStream(storeLoc); } tstore.load(is, passkey.toCharArray()); List<X509Certificate> publicCerts = getDefaultCertificates(); for (X509Certificate publicCert : publicCerts) { String publicAlias = tstore.getCertificateAlias(publicCert); if (StringUtils.equalsIgnoreCase(alias, publicAlias)) { throw new CertificateManagerException("System cannot remove its own public cert"); } } if (tstore.containsAlias(alias)) { tstore.deleteEntry(alias); os = new FileOutputStream(storeLoc); tstore.store(os, passkey.toCharArray()); isDeleteSuccessful = true; } } catch (final IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException ex) { throw new CertificateManagerException(ex.getMessage(), ex); } finally { closeStream(is, os); } return isDeleteSuccessful; }
Source:
default void updateChannelIfNotExist(String loginName, String channel) { UserPointModel userPointModel = findByLoginName(loginName); if (userPointModel != null && (userPointModel.getChannel() == null || "".equals(userPointModel.getChannel()))) { updateChannel(loginName, channel, new Date()); } }

Target:
default void updateChannelIfNotExist(String loginName, String channel) { UserPointModel userPointModel = findByLoginName(loginName); if (userPointModel != null && StringUtils.isEmpty(userPointModel.getChannel())) { updateChannel(loginName, channel, new Date()); } }
Source:
private BoundedMetricsQuery applyTimeRange(final MetricsQuery query, final Instant scheduled, final ChronoUnit period) { final ZonedDateTime latest = ZonedDateTime.ofInstant(scheduled, ZoneOffset.UTC).truncatedTo(period); final ZonedDateTime previous = latest.minus(1, period); return new DefaultBoundedMetricsQuery.Builder() .setStartTime(previous) .setEndTime(latest) .setQuery(query.getQuery()) .setFormat(query.getQueryFormat()) .build(); }

Target:
private BoundedMetricsQuery applyTimeRange(final MetricsQuery query, final Instant scheduled, final ChronoUnit period) { final ZonedDateTime adjustedScheduled = scheduled.minus(_queryOffset).atZone(ZoneOffset.UTC); final ZonedDateTime latest = adjustedScheduled.truncatedTo(period); final ZonedDateTime previous = latest.minus(1, period); return new DefaultBoundedMetricsQuery.Builder() .setStartTime(previous) .setEndTime(latest) .setQuery(query.getQuery()) .setFormat(query.getQueryFormat()) .build(); }
Source:
protected final void commitContextEntries(InvocationContext ctx, FlagAffectedCommand command, Metadata metadata) { final Flag stateTransferFlag = extractStateTransferFlag(ctx, command); final boolean isClear = isClearKeys(ctx, command); if (stateTransferFlag == null && isClear) { if (stateConsumer != null) { stateConsumer.stopApplyingState(); } if (xSiteStateConsumer != null) { xSiteStateConsumer.endStateTransfer(); } } if (ctx instanceof SingleKeyNonTxInvocationContext) { SingleKeyNonTxInvocationContext singleKeyCtx = (SingleKeyNonTxInvocationContext) ctx; commitEntryIfNeeded(ctx, command, singleKeyCtx.getCacheEntry(), stateTransferFlag, metadata); } else { Set<Map.Entry<Object, CacheEntry>> entries = ctx.getLookedUpEntries().entrySet(); Iterator<Map.Entry<Object, CacheEntry>> it = entries.iterator(); final Log log = getLog(); while (it.hasNext()) { Map.Entry<Object, CacheEntry> e = it.next(); CacheEntry entry = e.getValue(); if (!commitEntryIfNeeded(ctx, command, entry, stateTransferFlag, metadata)) { if (trace) { if (entry == null) log.tracef("Entry for key %s is null : not calling commitUpdate", e.getKey()); else log.tracef("Entry for key %s is not changed(%s): not calling commitUpdate", e.getKey(), entry); } } } } }

Target:
protected final void commitContextEntries(InvocationContext ctx, FlagAffectedCommand command, Metadata metadata) { final Flag stateTransferFlag = extractStateTransferFlag(ctx, command); if (stateTransferFlag == null) { stopStateTransferIfNeeded(ctx, command); } if (ctx instanceof SingleKeyNonTxInvocationContext) { SingleKeyNonTxInvocationContext singleKeyCtx = (SingleKeyNonTxInvocationContext) ctx; commitEntryIfNeeded(ctx, command, singleKeyCtx.getCacheEntry(), stateTransferFlag, metadata); } else { Set<Map.Entry<Object, CacheEntry>> entries = ctx.getLookedUpEntries().entrySet(); Iterator<Map.Entry<Object, CacheEntry>> it = entries.iterator(); final Log log = getLog(); while (it.hasNext()) { Map.Entry<Object, CacheEntry> e = it.next(); CacheEntry entry = e.getValue(); if (!commitEntryIfNeeded(ctx, command, entry, stateTransferFlag, metadata)) { if (trace) { if (entry == null) log.tracef("Entry for key %s is null : not calling commitUpdate", e.getKey()); else log.tracef("Entry for key %s is not changed(%s): not calling commitUpdate", e.getKey(), entry); } } } } }
Source:
public Object start(IApplicationContext context) throws Exception { String[] arguments = (String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS); List<String> asList = Arrays.asList(arguments); if (asList.contains("-help") || Arrays.asList(arguments).contains("--help")) { System.out.println(Messages.bind(Messages.CommandLineUsage)); return IApplication.EXIT_OK; } try { ResourcesPlugin.getWorkspace(); } catch (NoClassDefFoundError noClassError) { if (noClassError.getCause() instanceof ClassNotFoundException) { ClassNotFoundException classNotFoundException = (ClassNotFoundException) noClassError.getCause(); if (classNotFoundException.getException() instanceof BundleException) { BundleException bundleException = (BundleException) classNotFoundException.getException(); if (bundleException.getCause() instanceof IllegalStateException) { System.out.println(Messages.bind(Messages.WorkspaceRequired)); return 1; } } } throw noClassError; } return new CodeFormatterApplication().start(context); }

Target:
public Object start(IApplicationContext context) throws Exception { String[] arguments = (String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS); List<String> args = Arrays.asList(arguments); if (args.isEmpty() || args.contains("-help") || Arrays.asList(arguments).contains("--help")) { System.out.println(Messages.bind(Messages.CommandLineUsage)); return IApplication.EXIT_OK; } try { ResourcesPlugin.getWorkspace(); } catch (NoClassDefFoundError noClassError) { if (noClassError.getCause() instanceof ClassNotFoundException) { ClassNotFoundException classNotFoundException = (ClassNotFoundException) noClassError.getCause(); if (classNotFoundException.getException() instanceof BundleException) { BundleException bundleException = (BundleException) classNotFoundException.getException(); if (bundleException.getCause() instanceof IllegalStateException) { System.err.println(Messages.bind(Messages.WorkspaceRequired)); System.out.println(Messages.bind(Messages.CommandLineUsage)); return 1; } } } throw noClassError; } return new CodeFormatterApplication().start(context); }
Source:
private boolean readAndConsumeFile() throws IOException { if (this.fileBytesLeft <= 0 && inputBuffer.size() >= SIZE_LEN) { this.fileBytesLeft = readAndConsumeLength(); openRandomInFile(); } boolean readComplete = isInFileComplete(); int available = inputBuffer.size(); if (!readComplete && isInFileBufferFilled()) { byte[] bytes = inputBuffer.toByteArray(); int read = Math.min(available, this.fileBytesLeft); writeInFileData(bytes, read); available -= read; inputBuffer.reset(); if (available > 0) { inputBuffer.write(bytes, read, available); } readComplete = isInFileComplete(); } if (readComplete) { closeInFile(); } return readComplete; }

Target:
private boolean readAndConsumeFile() throws IOException { if (isWaitingForFile()) { this.fileBytesLeft = readAndConsumeLength(); openRandomInFile(); } boolean readComplete = isInFileComplete(); int available = inputBuffer.size(); if (!readComplete && isInFileBufferFilled()) { byte[] bytes = inputBuffer.toByteArray(); int read = Math.min(available, this.fileBytesLeft); writeInFileData(bytes, read); available -= read; inputBuffer.reset(); if (available > 0) { inputBuffer.write(bytes, read, available); } readComplete = isInFileComplete(); } if (readComplete) { closeInFile(); } return readComplete; }
Source:
public void closeForm() { if (refactor.isWidgetOpened()) { refactor.clickCancelButtonRefactorForm(); } if (editor.anyTabIsOpen()) { editor.closeAllTabs(); } }

Target:
public void closeForm() { if (refactor.isWidgetOpened()) { refactor.clickCancelButtonRefactorForm(); } if (editor.isAnyTabsOpened()) { editor.closeAllTabs(); } }
Source:
private void updateCopyAndMoveCommandAvailability(List<Disk> disks) { boolean isCopyAllowed = true; boolean isMoveAllowed = true; Disk firstDisk = disks.get(0); if (disks == null || disks.isEmpty() || firstDisk.getDiskStorageType() != DiskStorageType.IMAGE) { disableMoveAndCopyCommands(); return; } NGuid datacenterId = ((DiskImage) firstDisk).getStoragePoolId(); for (Disk disk : disks) { if (!isCopyAllowed && !isMoveAllowed || disk.getDiskStorageType() != DiskStorageType.IMAGE) { disableMoveAndCopyCommands(); return; } DiskImage diskImage = (DiskImage) disk; if (diskImage.getImageStatus() != ImageStatus.OK || !datacenterId.equals(diskImage.getStoragePoolId())) { disableMoveAndCopyCommands(); return; } if (disk.getVmEntityType() == VmEntityType.TEMPLATE) { isMoveAllowed = false; } else { isCopyAllowed = false; } } getCopyCommand().setIsExecutionAllowed(isCopyAllowed); getMoveCommand().setIsExecutionAllowed(isMoveAllowed); }

Target:
private void updateCopyAndMoveCommandAvailability(List<Disk> disks) { boolean isCopyAllowed = true; boolean isMoveAllowed = true; Disk firstDisk = disks.get(0); if (disks == null || disks.isEmpty() || firstDisk.getDiskStorageType() != DiskStorageType.IMAGE) { disableMoveAndCopyCommands(); return; } NGuid datacenterId = ((DiskImage) firstDisk).getStoragePoolId(); for (Disk disk : disks) { if ((!isCopyAllowed && !isMoveAllowed) || disk.getDiskStorageType() != DiskStorageType.IMAGE) { disableMoveAndCopyCommands(); return; } DiskImage diskImage = (DiskImage) disk; if (diskImage.getImageStatus() != ImageStatus.OK || !datacenterId.equals(diskImage.getStoragePoolId())) { disableMoveAndCopyCommands(); return; } if (disk.getVmEntityType() == VmEntityType.TEMPLATE) { isMoveAllowed = false; } else { isCopyAllowed = false; } } getCopyCommand().setIsExecutionAllowed(isCopyAllowed); getMoveCommand().setIsExecutionAllowed(isMoveAllowed); }
Source:
public static void deletePaths(final Iterable<Path> paths) { for (final Path p : paths) { boolean deleted; try { deleted = Files.deleteIfExists(p); } catch (IOException e) { deleted = false; } if (!deleted) System.err.println("Could not delete file " + p); } }

Target:
public static void deletePaths(final Iterable<Path> paths) { for (final Path p : paths) { try { Files.delete(p); } catch (IOException e) { System.err.println("Could not delete file " + p); } } }
Source:
public static boolean isMemoryDeviceHotUnpluggable(VmDevice memoryDevice) { if (!isMemory(memoryDevice)) { throw new RuntimeException("Memory device expected but device " + memoryDevice + " obtained."); } return getSpecParamsIntValue(memoryDevice, SPEC_PARAM_SIZE).isPresent() && getSpecParamsIntValue(memoryDevice, SPEC_PARAM_NODE).isPresent(); }

Target:
public static boolean isMemoryDeviceHotUnpluggable(VmDevice memoryDevice) { if (!isMemory(memoryDevice)) { throw new IllegalArgumentException("Memory device expected but device " + memoryDevice + " obtained."); } return getSpecParamsIntValue(memoryDevice, SPEC_PARAM_SIZE).isPresent() && getSpecParamsIntValue(memoryDevice, SPEC_PARAM_NODE).isPresent(); }
Source:
public void shouldConvertAvroToJson() throws IOException { byte json = avroToJsonConverter.convert(avroUser.create("Bob", 50, "blue")); assertThat(new String(json)).isEqualTo("{\"name\":\"Bob\",\"age\":50,\"favoriteColor\":\"blue\"}"); }

Target:
public void shouldConvertAvroToJson() throws IOException { byte json = avroToJsonConverter.convert(avroUser.create("Bob", 50, "blue")); assertThatJson(new String(json)).isEqualTo("{\"name\": \"Bob\",\"age\": 50,\"favoriteColor\": \"blue\"}"); }
Source:
private static Map<Class<? extends Entity>, ControllerFactory> setDefaultControllerFactories() { Map<Class<? extends Entity>, ControllerFactory> factories = new HashMap<>(); factories.put(Tank.class, new ControllerFactory() { private static final long serialVersionUID = 1L; @Override public void create(Entity entity) { entity.addController(new KeyboardTankController((Tank)entity)); } }); return factories; }

Target:
private static Map<Class<? extends Entity>, ControllerFactory> setDefaultControllerFactories() { Map<Class<? extends Entity>, ControllerFactory> factories = new HashMap<>(); factories.put(Tank.class, new ControllerFactory() { private static final long serialVersionUID = 1L; @Override public void create(Entity entity) { entity.addController(new KeyboardTankController((Tank)entity)); } }); factories.put(Pillbox.class, new ControllerFactory() { private static final long serialVersionUID = 1L; @Override public void create(Entity entity) { entity.addController(new AIPillboxController((Pillbox)entity)); } }); return factories; }
Source:
private void identifyZeroCarrier(@NonNull final String xCarrierFromHeader, @NonNull final String xCarrierMetaFromHeader) { Handler wikipediaZeroHandler = new Handler(new Handler.Callback() { private WikipediaZeroTask curZeroTask; @Override public boolean handleMessage(Message msg) { WikipediaZeroTask zeroTask = new WikipediaZeroTask( app.getApiForMobileSite(app.getSite()), app.getUserAgent()) { @Override public void onFinish(ZeroConfig config) { L.d("New Wikipedia Zero config: " + config); xCarrier = xCarrierFromHeader; if (config != null) { zeroCarrierString = xCarrierFromHeader; zeroCarrierMetaString = xCarrierMetaFromHeader; zeroConfig = config; zeroEnabled = true; zeroFunnel = new WikipediaZeroUsageFunnel(app, zeroCarrierString, StringUtil.emptyIfNull(zeroCarrierMetaString)); app.getBus().post(new WikipediaZeroStateChangeEvent()); curZeroTask = null; } acquiringCarrierMessage = false; } @Override public void onCatch(Throwable caught) { L.w("Wikipedia Zero eligibility check failed"); curZeroTask = null; acquiringCarrierMessage = false; } }; if (curZeroTask != null) { curZeroTask.cancel(); } curZeroTask = zeroTask; curZeroTask.execute(); acquiringCarrierMessage = true; return true; } }); wikipediaZeroHandler.removeMessages(MESSAGE_ZERO_CS); Message zeroMessage = Message.obtain(); zeroMessage.what = MESSAGE_ZERO_CS; zeroMessage.obj = "zero_eligible_check"; wikipediaZeroHandler.sendMessage(zeroMessage); }

Target:
private void identifyZeroCarrier(@NonNull final String xCarrierFromHeader, @NonNull final String xCarrierMetaFromHeader) { Handler wikipediaZeroHandler = new Handler(new Handler.Callback() { private WikipediaZeroTask curZeroTask; @Override public boolean handleMessage(Message msg) { WikipediaZeroTask zeroTask = new WikipediaZeroTask( app.getApiForMobileSite(app.getSite()), app.getUserAgent()) { @Override public void onFinish(ZeroConfig config) { L.i("New Wikipedia Zero config: " + config); xCarrier = xCarrierFromHeader; if (config != null) { zeroCarrierString = xCarrierFromHeader; zeroCarrierMetaString = xCarrierMetaFromHeader; zeroConfig = config; zeroEnabled = true; zeroFunnel = new WikipediaZeroUsageFunnel(app, zeroCarrierString, StringUtil.emptyIfNull(zeroCarrierMetaString)); app.getBus().post(new WikipediaZeroStateChangeEvent()); curZeroTask = null; } acquiringCarrierMessage = false; } @Override public void onCatch(Throwable caught) { L.w("Wikipedia Zero eligibility check failed", caught); curZeroTask = null; acquiringCarrierMessage = false; } }; if (curZeroTask != null) { curZeroTask.cancel(); } curZeroTask = zeroTask; curZeroTask.execute(); acquiringCarrierMessage = true; return true; } }); wikipediaZeroHandler.removeMessages(MESSAGE_ZERO_CS); Message zeroMessage = Message.obtain(); zeroMessage.what = MESSAGE_ZERO_CS; zeroMessage.obj = "zero_eligible_check"; wikipediaZeroHandler.sendMessage(zeroMessage); }
Source:
public JBlock getOnDestroyViewAfterSuperBlock() { if (onDestroyViewAfterSuperBlock == null) { setContentViewRelatedMethods(); } return onDestroyViewAfterSuperBlock; }

Target:
private JBlock getOnDestroyViewAfterSuperBlock() { if (onDestroyViewAfterSuperBlock == null) { setContentViewRelatedMethods(); } return onDestroyViewAfterSuperBlock; }
Source:
public synchronized boolean bridgeLogout() { logger.trace("bridgeLogout() called."); logger.trace("bridgeLogout(): emptying authentication token."); authenticationToken = ""; Logout bcp = this.bridgeAPI().logout(); if (bridgeCommunicate(bcp, false)) { logger.trace("bridgeLogout(): communication succeeded."); if (bcp.isCommunicationSuccessful()) { logger.trace("bridgeLogout(): logout successful."); return true; } } return false; }

Target:
public synchronized boolean bridgeLogout() { logger.trace("bridgeLogout() called: emptying authentication token."); authenticationToken = ""; Logout bcp = bridgeAPI().logout(); if (bridgeCommunicate(bcp, false)) { logger.trace("bridgeLogout(): communication succeeded."); if (bcp.isCommunicationSuccessful()) { logger.trace("bridgeLogout(): logout successful."); return true; } } return false; }
Source:
protected Object fastClone(final Object o, final Map<Object, Object> clones) throws IllegalAccessException { if ((o instanceof Term && !((Term) o).isMutable())) { return o; } else { return super.fastClone(o, clones); } }

Target:
protected Object fastClone(final Object o, final Map<Object, Object> clones) throws IllegalAccessException { if (o instanceof Term && !((Term) o).isMutable()) { return o; } else { return super.fastClone(o, clones); } }
Source:
protected Object execute(Object data) { String userFormat; if (data == null) { throw new ExecutionPlanRuntimeException("Invalid input given to time:dayOfWeek(dateValue," + "dateFormat) function" + ". First " + "argument cannot be null"); } userFormat = (String) data; String source = null; FastDateFormat userSpecificFormat; Date userSpecifiedDate; try { source = (String) data; userSpecificFormat = FastDateFormat.getInstance(userFormat); userSpecifiedDate = userSpecificFormat.parse(source); return getDayOfWeek(userSpecifiedDate); } catch (ParseException e) { String errorMsg = "Provided format " + userFormat + " does not match with the timestamp " + source + e .getMessage(); throw new ExecutionPlanRuntimeException(errorMsg, e); } catch (ClassCastException e) { String errorMsg = "Provided Data type cannot be cast to desired format. " + e.getMessage(); throw new ExecutionPlanRuntimeException(errorMsg, e); } }

Target:
protected Object execute(Object data) { String userFormat; if (data == null) { throw new ExecutionPlanRuntimeException("Invalid input given to time:dayOfWeek(dateValue," + "dateFormat) function" + ". First " + "argument cannot be null"); } userFormat = TimeExtensionConstants.EXTENSION_TIME_DEFAULT_DATE_FORMAT; String source; try { source = (String) data; String inputData[] = source.split(" "); DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = format.parse(inputData[0]); return getDayOfWeek(date); } catch (ParseException e) { String errorMsg = "Provided format " + userFormat + " does not match with the timestamp " + source + e .getMessage(); throw new ExecutionPlanRuntimeException(errorMsg, e); } } catch (ClassCastException e) { String errorMsg = "Provided Data type cannot be cast to desired format. " + e.getMessage(); throw new ExecutionPlanRuntimeException(errorMsg, e); } }
Source:
public void valueOfCodeCanFindByMatchingCode() { final MantaErrorCode expectedLimitError = MantaErrorCode.INVALID_LIMIT_ERROR; final MantaErrorCode expectedNoApiError = MantaErrorCode.NO_API_SERVERS_AVAILABLE; final MantaErrorCode expectedObjectNotFoundError = MantaErrorCode.OBJECT_NOT_FOUND_ERROR; final MantaErrorCode actualLimitError = MantaErrorCode.valueOfCode("InvalidLimit"); final MantaErrorCode actualNoApiError = MantaErrorCode.valueOfCode("NoApiServersAvailable"); final MantaErrorCode actualObjectNotFoundError = MantaErrorCode.valueOfCode("ObjectNotFoundError"); Assert.assertEquals(actualLimitError, expectedLimitError); Assert.assertEquals(actualNoApiError, expectedNoApiError); Assert.assertEquals(actualObjectNotFoundError, expectedObjectNotFoundError); }

Target:
public void valueOfCodeCanFindByMatchingCode() { final MantaErrorCode actualLimitError = MantaErrorCode.valueOfCode("InvalidLimit"); final MantaErrorCode actualNoApiError = MantaErrorCode.valueOfCode("NoApiServersAvailable"); final MantaErrorCode actualObjectNotFoundError = MantaErrorCode.valueOfCode("ObjectNotFoundError"); Assert.assertEquals(actualLimitError, INVALID_LIMIT_ERROR); Assert.assertEquals(actualNoApiError, NO_API_SERVERS_AVAILABLE); Assert.assertEquals(actualObjectNotFoundError, OBJECT_NOT_FOUND_ERROR); }
Source:
private static void assertSortOrdersAreEqual(final SAMFileHeader newHeader, final File inputFile) throws IOException { final SAMFileHeader origHeader = SamReaderFactory.makeDefault().open(inputFile).getFileHeader(); final SAMFileHeader.SortOrder newSortOrder = newHeader.getSortOrder(); if (newSortOrder != SAMFileHeader.SortOrder.unsorted && newSortOrder != origHeader.getSortOrder()) { throw new SAMException("Sort order of new header does not match the original file, needs to be " + origHeader.getSortOrder()); } }

Target:
private static void assertSortOrdersAreEqual(final SAMFileHeader newHeader, final File inputFile) throws IOException { final SamReader reader = SamReaderFactory.makeDefault().open(inputFile); final SAMFileHeader origHeader = reader.getFileHeader(); final SAMFileHeader.SortOrder newSortOrder = newHeader.getSortOrder(); if (newSortOrder != SAMFileHeader.SortOrder.unsorted && newSortOrder != origHeader.getSortOrder()) { throw new SAMException("Sort order of new header does not match the original file, needs to be " + origHeader.getSortOrder()); } reader.close(); }
Source:
private Map<PlanNodeId, SplitSource> visitScanAndFilter(TableScanNode scan, Optional<FilterNode> filter) { Set<DynamicFilter> dynamicFilters = filter .map(FilterNode::getPredicate) .map(ExpressionUtils::extractDynamicFilters) .map(ExtractDynamicFiltersResult::getDynamicFilters) .orElse(ImmutableSet.of()); SplitSource splitSource; if (!dynamicFilters.isEmpty()) { System.out.printf("[DistributedExecutionPlanner] Dynamic filters: %s\n", dynamicFilters); List<ListenableFuture<DynamicFilterDescription>> futuresList = dynamicFilterDescriptionFutureSupplier.get(session.getQueryId().toString(), dynamicFilters, scan.getAssignments()); splitSource = splitManager.getSplits(session, scan.getLayout().get(), Futures.allAsList(futuresList)); } else { splitSource = splitManager.getSplits(session, scan.getLayout().get()); } splitSources.add(splitSource); return ImmutableMap.of(scan.getId(), splitSource); }

Target:
private Map<PlanNodeId, SplitSource> visitScanAndFilter(TableScanNode scan, Optional<FilterNode> filter) { Set<DynamicFilter> dynamicFilters = filter .map(FilterNode::getPredicate) .map(DynamicFilterUtils::extractDynamicFilters) .map(ExtractDynamicFiltersResult::getDynamicFilters) .orElse(ImmutableSet.of()); List<Future<DynamicFilterDescription>> futuresList = ImmutableList.of(); if (!dynamicFilters.isEmpty()) { log.debug("Dynamic filters: %s", dynamicFilters); futuresList = dynamicFilterDescriptionFutureSupplier.get(session.getQueryId().toString(), dynamicFilters, scan.getAssignments()); } SplitSource splitSource = splitManager.getSplits(session, scan.getLayout().get(), futuresList); splitSources.add(splitSource); return ImmutableMap.of(scan.getId(), splitSource); }
Source:
public PackReverseIndex(final PackIndex packIndex) { index = packIndex; final long cnt = index.getObjectCount(); if (cnt > Integer.MAX_VALUE) throw new IllegalArgumentException( JGitText.get().hugeIndexesAreNotSupportedByJgitYet); if (cnt == 0) { bucketSize = Long.MAX_VALUE; offsetIndex = new int[1]; nth = new int[0]; return; } final long[] offsetsBySha1 = new long[(int) cnt]; long maxOffset = 0; int ith = 0; for (final MutableEntry me : index) { final long o = me.getOffset(); offsetsBySha1[ith++] = o; if (o > maxOffset) maxOffset = o; } bucketSize = maxOffset / cnt + 1; offsetIndex = new int[(int) cnt]; int[] bucketValues = new int[(int) cnt + 1]; for (int oi = 0; oi < offsetsBySha1.length; oi++) { final long o = offsetsBySha1[oi]; final int bucketIndexPos = (int) (o / bucketSize); final int bucketValuesPos = oi + 1; final int current = offsetIndex[bucketIndexPos]; offsetIndex[bucketIndexPos] = bucketValuesPos; bucketValues[bucketValuesPos] = current; } int nthByOffset = 0; nth = new int[offsetsBySha1.length]; for (int bi = 0; bi < offsetIndex.length; bi++) { final int start = nthByOffset; for (int vi = offsetIndex[bi]; vi > 0; vi = bucketValues[vi]) { final int nthBySha1 = vi - 1; final long o = offsetsBySha1[nthBySha1]; int insertion = nthByOffset++; for (; start < insertion; insertion--) { if (o > offsetsBySha1[nth[insertion - 1]]) break; nth[insertion] = nth[insertion - 1]; } nth[insertion] = nthBySha1; } offsetIndex[bi] = nthByOffset; } }

Target:
public PackReverseIndex(final PackIndex packIndex) { index = packIndex; final long cnt = index.getObjectCount(); if (cnt > Integer.MAX_VALUE) throw new IllegalArgumentException( JGitText.get().hugeIndexesAreNotSupportedByJgitYet); if (cnt == 0) { bucketSize = Long.MAX_VALUE; offsetIndex = new int[1]; nth = new int[0]; return; } final long[] offsetsBySha1 = new long[(int) cnt]; long maxOffset = 0; int ith = 0; for (final MutableEntry me : index) { final long o = me.getOffset(); offsetsBySha1[ith++] = o; if (o > maxOffset) maxOffset = o; } bucketSize = maxOffset / cnt + 1; int[] bucketIndex = new int[(int) cnt]; int[] bucketValues = new int[(int) cnt + 1]; for (int oi = 0; oi < offsetsBySha1.length; oi++) { final long o = offsetsBySha1[oi]; final int bucket = (int) (o / bucketSize); final int bucketValuesPos = oi + 1; final int current = bucketIndex[bucket]; bucketIndex[bucket] = bucketValuesPos; bucketValues[bucketValuesPos] = current; } int nthByOffset = 0; nth = new int[offsetsBySha1.length]; offsetIndex = bucketIndex; for (int bi = 0; bi < bucketIndex.length; bi++) { final int start = nthByOffset; for (int vi = bucketIndex[bi]; vi > 0; vi = bucketValues[vi]) { final int nthBySha1 = vi - 1; final long o = offsetsBySha1[nthBySha1]; int insertion = nthByOffset++; for (; start < insertion; insertion--) { if (o > offsetsBySha1[nth[insertion - 1]]) break; nth[insertion] = nth[insertion - 1]; } nth[insertion] = nthBySha1; } offsetIndex[bi] = nthByOffset; } }
Source:
public static <T extends ITmfEventAspect> Object resolveEventAspectOfClassForEvent( ITmfTrace trace, Class<T> aspectClass, @NonNull ITmfEvent event) { Object obj = null; for (T aspect : getEventAspectsOfClass(trace, aspectClass)) { obj = aspect.resolve(event); if (obj != null) { return obj; } } return null; }

Target:
public static <T extends ITmfEventAspect> Object resolveEventAspectOfClassForEvent( ITmfTrace trace, Class<T> aspectClass, @NonNull ITmfEvent event) { Iterable<ITmfEventAspect> aspects = trace.getEventAspects(); for (ITmfEventAspect aspect : aspects) { if (aspectClass.isAssignableFrom(aspect.getClass())) { Object obj = aspect.resolve(event); if (obj != null) { return obj; } } } return null; }
Source:
private static void createContainer() { if (sqsContainer == null) { sqsContainer = new GenericContainer("roribio16/alpine-sqs") .withStartupTimeout(Duration.ofMinutes(3)); sqsContainer.start(); } }

Target:
private static void createContainer() { if (sqsContainer == null) { sqsContainer = new GenericContainer("roribio16/alpine-sqs") .withExposedPorts(9324) .waitingFor(Wait.forHttp("/?Action=GetQueueUrl&QueueName=default")); sqsContainer.start(); } }
Source:
public void cookieRenewal() throws Exception { final String renewalCookieValue = "AuthSession=\"RenewCookie_a2ltc3RlYmVsOjUxMzRBQTUzOtiY2_IDUIdsTJEVNEjObAbyhrgz\";"; mockWebServer.enqueue(MockWebServerResource.OK_COOKIE); mockWebServer.enqueue(new MockResponse().setResponseCode(200).addHeader("Set-Cookie", String.format(Locale.ENGLISH, "%s;", renewalCookieValue)) .setBody("{\"hello\":\"world\"}\r\n")); mockWebServer.enqueue(new MockResponse()); CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer) .username("a") .password("b") .build(); c.executeRequest(Http.GET(c.getBaseUri())); mockWebServer.takeRequest(); mockWebServer.takeRequest(); c.executeRequest(Http.GET(c.getBaseUri())); assertEquals("The server should have received 4 requests", 3, mockWebServer .getRequestCount()); RecordedRequest request = mockWebServer.takeRequest(); String headerValue = request.getHeader("Cookie"); Assert.assertEquals("AuthSession=\"RenewCookie_a2ltc3RlYmVsOjUxMzRBQTUzOtiY2_IDUIdsTJEVNEjObAbyhrgz\"", headerValue); }

Target:
public void cookieRenewal() throws Exception { final String renewalCookieValue = "AuthSession=\"RenewCookie_a2ltc3RlYmVsOjUxMzRBQTUzOtiY2_IDUIdsTJEVNEjObAbyhrgz\";"; mockWebServer.enqueue(MockWebServerResource.OK_COOKIE); mockWebServer.enqueue(new MockResponse().setResponseCode(200).addHeader("Set-Cookie", String.format(Locale.ENGLISH, "%s;", renewalCookieValue)) .setBody("{\"hello\":\"world\"}\r\n")); mockWebServer.enqueue(new MockResponse()); CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer) .username("a") .password("b") .build(); c.executeRequest(Http.GET(c.getBaseUri())); c.executeRequest(Http.GET(c.getBaseUri())); assertEquals("The server should have received 3 requests", 3, mockWebServer .getRequestCount()); mockWebServer.takeRequest(); mockWebServer.takeRequest(); RecordedRequest request = mockWebServer.takeRequest(); String headerValue = request.getHeader("Cookie"); Assert.assertEquals("AuthSession=\"RenewCookie_a2ltc3RlYmVsOjUxMzRBQTUzOtiY2_IDUIdsTJEVNEjObAbyhrgz\"", headerValue); }
Source:
public void addSegments(Iterable<DataSegment> segments) { try { for (DataSegment segment : segments) { serverManager.loadSegment(segment); File segmentInfoCacheFile = new File(config.getSegmentInfoCacheDirectory(), segment.getIdentifier()); try { jsonMapper.writeValue(segmentInfoCacheFile, segment); } catch (IOException e) { removeSegment(segment); throw new SegmentLoadingException( e, "Failed to write to disk segment info cache file[%s]", segmentInfoCacheFile ); } } try { announcer.announceSegments(segments); } catch (IOException e) { removeSegments(segments); throw new SegmentLoadingException(e, "Failed to announce segments[%s]", segments); } } catch (SegmentLoadingException e) { log.makeAlert(e, "Failed to load segments for dataSource") .addData("segments", segments) .emit(); } }

Target:
public void addSegments(Iterable<DataSegment> segments) { try { for (DataSegment segment : segments) { serverManager.loadSegment(segment); File segmentInfoCacheFile = new File(config.getSegmentInfoCacheDirectory(), segment.getIdentifier()); if (!segmentInfoCacheFile.exists()) { try { jsonMapper.writeValue(segmentInfoCacheFile, segment); } catch (IOException e) { removeSegment(segment); throw new SegmentLoadingException( e, "Failed to write to disk segment info cache file[%s]", segmentInfoCacheFile ); } } } try { announcer.announceSegments(segments); } catch (IOException e) { removeSegments(segments); throw new SegmentLoadingException(e, "Failed to announce segments[%s]", segments); } } catch (SegmentLoadingException e) { log.makeAlert(e, "Failed to load segments for dataSource") .addData("segments", segments) .emit(); } }