auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
@Override public void actionPerformed(final ActionEvent actionEvent) { final TargetEnvironment env = obsComp.getTargetEnvironment(); final GuideEnvironment ge = env.getGuideEnvironment(); final Option<IndexedGuideGroup> iggOpt = positionTable.getSelectedGroupOrParentGroup(env) .filter(igg -> !igg.group().isAutomatic()) .orElse(() -> { return appendNewGroup(obsComp, positionTable); }); final TargetEnvironment newEnv = obsComp.getTargetEnvironment(); Option<GuideProbeTargets> opt = iggOpt.flatMap(igg -> igg.group().get(probe)); final Integer groupIndex = iggOpt.map(IndexedGuideGroup::index).getOrElse(ge.getPrimaryIndex()); final SPTarget target = new SPTarget(); final GuideProbeTargets targets = opt .map(gpt -> gpt.update(OptionsList.UpdateOps.appendAsPrimary(target))) .getOrElse(GuideProbeTargets.create(probe, target)); obsComp.setTargetEnvironment(newEnv.setGuideEnvironment( newEnv.getGuideEnvironment().putGuideProbeTargets(groupIndex, targets))); positionTable.selectTarget(target); SwingUtilities.invokeLater(EdCompTargetList.this::showTargetTag); }

Target:
@Override public void actionPerformed(final ActionEvent actionEvent) { final TargetEnvironment env = obsComp.getTargetEnvironment(); final GuideEnvironment ge = env.getGuideEnvironment(); final Option<Tuple2<TargetEnvironment,IndexedGuideGroup>> resultOpt = positionTable.getSelectedGroupOrParentGroup(env) .filter(igg -> !igg.group().isAutomatic()) .map(igg -> (Tuple2<TargetEnvironment,IndexedGuideGroup>) new Pair<>(env, igg)) .orElse(() -> appendNewGroup(obsComp, positionTable)); resultOpt.foreach(result -> { final TargetEnvironment newEnv = result._1(); final IndexedGuideGroup igg = result._2(); final Option<GuideProbeTargets> gptOpt = igg.group().get(probe); final Integer groupIndex = igg.index(); final SPTarget target = new SPTarget(); final GuideProbeTargets targets = gptOpt .map(gpt -> gpt.update(OptionsList.UpdateOps.appendAsPrimary(target))) .getOrElse(GuideProbeTargets.create(probe, target)); final TargetEnvironment newEnvWithTarget = newEnv.setGuideEnvironment(newEnv.getGuideEnvironment() .putGuideProbeTargets(groupIndex, targets)); obsComp.setTargetEnvironment(newEnvWithTarget); positionTable.selectTarget(target); SwingUtilities.invokeLater(EdCompTargetList.this::showTargetTag); }); }
Source:
private void populateArticle(ViewHolder mViewHolder, ViewGroup container, final Activity.PlusObject.Attachments attachment) { if(attachment == null) return; View attachmentView = createAttachmentView(mViewHolder, container, R.layout.news_item_article, 1); mViewHolder.title.setText(attachment.getDisplayName()); try { mViewHolder.attachmentContent.setText(new URL(attachment.getUrl()).getHost()); } catch (MalformedURLException e) { e.printStackTrace(); } if (attachment.getImage() == null && attachment.getFullImage() == null) { mViewHolder.articleImage.setVisibility(View.GONE); } else { String imageUrl = null; if (attachment.getFullImage() != null) { imageUrl = attachment.getFullImage().getUrl(); } if (attachment.getImage() != null) { imageUrl = attachment.getImage().getUrl(); } mViewHolder.articleImage.setImageDrawable(null); if (imageUrl != null) { mViewHolder.articleImage.setVisibility(View.VISIBLE); App.getInstance().getPicasso() .load(imageUrl) .into(mViewHolder.articleImage); } else { mViewHolder.articleImage.setVisibility(View.GONE); } } attachmentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(attachment.getUrl())); mContext.startActivity(i); } }); }

Target:
private void populateArticle(ViewHolder mViewHolder, ViewGroup container, final Activity.PlusObject.Attachments attachment) { if (attachment == null) return; View attachmentView = createAttachmentView(mViewHolder, container, R.layout.news_item_article, 1); mViewHolder.title.setText(attachment.getDisplayName()); try { mViewHolder.attachmentContent.setText(new URL(attachment.getUrl()).getHost()); } catch (MalformedURLException e) { e.printStackTrace(); } if (attachment.getImage() == null && attachment.getFullImage() == null) { mViewHolder.articleImage.setVisibility(View.GONE); } else { mViewHolder.articleImage.setImageDrawable(null); String imageUrl = getAttachmentImageUrl(attachment); if (imageUrl != null) { mViewHolder.articleImage.setVisibility(View.VISIBLE); App.getInstance().getPicasso() .load(imageUrl) .into(mViewHolder.articleImage); } else { mViewHolder.articleImage.setVisibility(View.GONE); } } attachmentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(attachment.getUrl())); mContext.startActivity(i); } }); }
Source:
boolean wouldPushProject(Project.NameKey project) { if (projectMatch != null) { if (projectMatch.endsWith("/*")) { return project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1)); } String projectPattern; if (isRE(projectMatch)) { projectPattern = projectMatch.substring(1); } else { projectPattern = projectMatch; } return (new RegExp(projectPattern, RegExp.NONE)). toAutomaton().run(project.get()); } return true; }

Target:
boolean wouldPushProject(Project.NameKey project) { if (projectMatch != null) { if (isRE(projectMatch)) { return (new RegExp(projectMatch, RegExp.NONE)). toAutomaton().run(project.get()); } else if (projectMatch.endsWith("/*")) { return project.get().startsWith( projectMatch.substring(0, projectMatch.length() - 1)); } else { return project.get().equals(projectMatch); } } return true; }
Source:
protected Span[] assertSpansReportedKindInAnyOrder(@Nullable Span.Kind kind1, @Nullable Span.Kind kind2) throws InterruptedException { if (Objects.equals(kind1, kind2)) { throw new AssertionError("Expected test to pass different span kinds"); } Span span1 = takeSpan(), span2 = takeSpan(); Stream.of(span1, span2).forEach(span -> assertThat(span.kind()) .withFailMessage("Expected %s to have kind=%s or %s", span, kind1, kind2) .isIn(kind1, kind2)); if (Objects.equals(span1.kind(), span2.kind())) { throw new AssertionError("Expected span " + span1 + " to have different kind than " + span2); } Span[] result = new Span[] {span1, span2}; return result[0].kind() == kind1 ? result : new Span[] {span2, span1}; }

Target:
protected Span[] assertSpansReportedKindInAnyOrder(@Nullable Span.Kind kind1, @Nullable Span.Kind kind2) throws InterruptedException { if (Objects.equals(kind1, kind2)) { throw new AssertionError("Expected test to pass different span kinds"); } Span span1 = takeSpan(), span2 = takeSpan(); for (Span span : Arrays.asList(span1, span2)) { assertThat(span.kind()) .withFailMessage("Expected %s to have kind=%s or %s", span, kind1, kind2) .isIn(kind1, kind2); } if (Objects.equals(span1.kind(), span2.kind())) { throw new AssertionError("Expected span " + span1 + " to have different kind than " + span2); } Span[] result = new Span[] {span1, span2}; return result[0].kind() == kind1 ? result : new Span[] {span2, span1}; }
Source:
public SortedSet<Fun.Tuple2<String, Fun.Tuple2>> getStopTimesForStop (String stop_id) { SortedSet<Fun.Tuple2<String, Fun.Tuple2>> index = this.stopStopTimeSet .subSet(new Fun.Tuple2<>(stop_id, null), new Fun.Tuple2(stop_id, Fun.HI)); return index; }

Target:
public List<StopTime> getStopTimesForStop (String stop_id) { SortedSet<Tuple2<String, Tuple2>> index = this.stopStopTimeSet .subSet(new Tuple2<>(stop_id, null), new Tuple2(stop_id, Fun.HI)); return index.stream() .map(tuple -> this.stop_times.get(tuple.b)) .sorted((a, b) -> Integer.compare(a.arrival_time, b.arrival_time)) .collect(Collectors.toList()); }
Source:
private void notifyAndMigrateDataSetObservers() { Adapter adapter = contributionsListFragment.getAdapter(); for (DataSetObserver observer : observersWaitingForLoad) { adapter.registerDataSetObserver(observer); } observersWaitingForLoad.clear(); for (DataSetObserver observer : observersWaitingForLoad) { observer.onChanged(); } if (!ConfigUtils.isBetaFlavour()) { setUploadCount(); } else { betaSetUploadCount(getTotalMediaCount()); } }

Target:
private void notifyAndMigrateDataSetObservers() { Adapter adapter = contributionsListFragment.getAdapter(); for (DataSetObserver observer : observersWaitingForLoad) { adapter.registerDataSetObserver(observer); } observersWaitingForLoad.clear(); for (DataSetObserver observer : observersWaitingForLoad) { observer.onChanged(); } if (ConfigUtils.isBetaFlavour()) { betaSetUploadCount(getTotalMediaCount()); } else { setUploadCount(); } }
Source:
public <C extends JdbiConfig<C>> C get(Class<C> configClass) { return (C) cache.computeIfAbsent(configClass, c -> createFromParent(configClass) .orElseGet(() -> create(configClass))); }

Target:
public <C extends JdbiConfig<C>> C get(Class<C> configClass) { JdbiConfig<?> config = cache.computeIfAbsent(configClass, c -> createFromParent(configClass) .orElseGet(() -> create(configClass))); return configClass.cast(config); }
Source:
public void theDeviceShouldBeRemoved(final String deviceIdentification) throws Throwable { final Device device = this.deviceRepository.findByDeviceIdentification(deviceIdentification); Assert.assertNull(device); final List<DeviceAuthorization> devAuths = this.deviceAuthorizationRepository.findByDevice(device); Assert.assertTrue(devAuths.size() == 0); }

Target:
public void theDeviceShouldBeRemoved(final String deviceIdentification) throws Throwable { final Device device = this.deviceRepository.findByDeviceIdentification(deviceIdentification); Assert.assertNotNull(device); final List<DeviceAuthorization> devAuths = this.deviceAuthorizationRepository.findByDevice(device); Assert.assertTrue(devAuths.size() == 0); }
Source:
DiskImageBase getDisk() { if (_disk == null) { _disk = (DiskImageBase) getDbFacade().getDiskDao().get(getParameters().getObjectId()); } return _disk; }

Target:
private DiskImageBase getDisk() { return _disk; }
Source:
private List<String> getListOfIpAddresses(String ipAddressesAsString) { if (ipAddressesAsString == null) { return Collections.emptyList(); } return Arrays.asList(StringUtils.split(ipAddressesAsString,DELIMITER)); }

Target:
private List<String> getListOfIpAddresses(String ipAddressesAsString) { return ipAddressesAsString == null ? null : Arrays.asList(StringUtils.split(ipAddressesAsString, DELIMITER)); }
Source:
public <T extends EhcacheEntityResponse> void removeResponseListener(Class<T> responseType, ResponseListener<T> responseListener) { List<ResponseListener<? extends EhcacheEntityResponse>> responseListeners = this.responseListeners.get(responseType); if (responseListener != null) { responseListeners.remove(responseListener); } }

Target:
public <T extends EhcacheEntityResponse> void removeResponseListener(Class<T> responseType, ResponseListener<T> responseListener) { List<ResponseListener<? extends EhcacheEntityResponse>> responseListeners = this.responseListeners.get(responseType); if (responseListeners != null) { responseListeners.remove(responseListener); } }
Source:
public void testInvalidConnUpdateCacheFrequencyShouldThrow() throws Exception { Properties props = PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES); ArrayList<String> invalidUCF = new ArrayList<>(); invalidUCF.add("GIBBERISH"); invalidUCF.add("10000.6"); for (String connLevelUCF : invalidUCF) { props.put(QueryServices.DEFAULT_UPDATE_CACHE_FREQUENCY_ATRRIB, connLevelUCF); try { DriverManager.getConnection(getUrl(), props); fail(); } catch (IllegalArgumentException e) { assertEquals("Connection's phoenix.default.update.cache.frequency can only be set to 'ALWAYS', 'NEVER' or a millisecond numeric value.", e.getMessage()); } } }

Target:
public void testInvalidConnUpdateCacheFrequencyShouldThrow() throws Exception { Properties props = PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES); ArrayList<String> invalidUCF = new ArrayList<>(); invalidUCF.add("GIBBERISH"); invalidUCF.add("10000.6"); for (String connLevelUCF : invalidUCF) { props.put(QueryServices.DEFAULT_UPDATE_CACHE_FREQUENCY_ATRRIB, connLevelUCF); try { DriverManager.getConnection(getUrl(), props); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Connection's " + QueryServices.DEFAULT_UPDATE_CACHE_FREQUENCY_ATRRIB)); } } }
Source:
public void testMultipartUploadMultiplePartsKnownETag() throws Exception { BlobStore blobStore = view.getBlobStore(); String container = getContainerName(); String expectedETag = "\"84462a16f6a60478d50148808aa609c1-2\""; int partSize = 5 * (int) Math.pow(2, 20); try { String name = "blob-name"; BlobBuilder blobBuilder = blobStore.blobBuilder(name); Blob blob = blobBuilder.build(); MultipartUpload mpu = blobStore.initiateMultipartUpload(container, blob.getMetadata(), new PutOptions()); byte[] content = new byte[partSize]; Arrays.fill(content, (byte) 'b'); Payload payload = Payloads.newByteArrayPayload(content); payload.getContentMetadata().setContentLength((long) partSize); MultipartPart part1 = blobStore.uploadMultipartPart(mpu, 1, payload); MultipartPart part2 = blobStore.uploadMultipartPart(mpu, 2, payload); List<MultipartPart> parts = blobStore.listMultipartUpload(mpu); assertThat(parts).hasSize(2); assertThat(parts.get(0).partNumber()).isEqualTo(part1.partNumber()); assertThat(parts.get(0).partSize()).isEqualTo(part1.partSize()); assertThat(parts.get(0).partETag()).isEqualTo(part1.partETag()); assertThat(parts.get(1).partNumber()).isEqualTo(part2.partNumber()); assertThat(parts.get(1).partSize()).isEqualTo(part2.partSize()); assertThat(parts.get(1).partETag()).isEqualTo(part2.partETag()); blobStore.completeMultipartUpload(mpu, ImmutableList.of(part1, part2)); BlobMetadata newBlobMetadata = blobStore.blobMetadata(container, name); assertThat(newBlobMetadata.getETag()).isEqualTo(expectedETag); } finally { returnContainer(container); } }

Target:
public void testMultipartUploadMultiplePartsKnownETag() throws Exception { BlobStore blobStore = view.getBlobStore(); String container = getContainerName(); String expectedETag = "\"84462a16f6a60478d50148808aa609c1-2\""; int partSize = 5 * 1024 * 1024; try { String name = "blob-name"; BlobBuilder blobBuilder = blobStore.blobBuilder(name); Blob blob = blobBuilder.build(); MultipartUpload mpu = blobStore.initiateMultipartUpload(container, blob.getMetadata(), new PutOptions()); byte[] content = new byte[partSize]; Arrays.fill(content, (byte) 'b'); Payload payload = Payloads.newByteArrayPayload(content); payload.getContentMetadata().setContentLength((long) partSize); MultipartPart part1 = blobStore.uploadMultipartPart(mpu, 1, payload); MultipartPart part2 = blobStore.uploadMultipartPart(mpu, 2, payload); blobStore.completeMultipartUpload(mpu, ImmutableList.of(part1, part2)); BlobMetadata newBlobMetadata = blobStore.blobMetadata(container, name); assertThat(newBlobMetadata.getETag()).isEqualTo(expectedETag); } finally { returnContainer(container); } }
Source:
public static Path unpack(Path zipFilePath, Path destDirPath) throws IOException{ if (Files.exists(destDirPath)) { Files.delete(destDirPath); } Files.createDirectory(destDirPath); byte[] buffer = new byte[1024]; ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath.toFile())); ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { File newFile = new File(destDirPath.toFile(), zipEntry.getName()); newFile.toPath().getParent().toFile().mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zipInputStream.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); zipEntry = zipInputStream.getNextEntry(); } zipInputStream.closeEntry(); zipInputStream.close(); return destDirPath; }

Target:
public static Path unpack(Path zipFilePath, Path destDirPath) throws IOException { if (Files.exists(destDirPath)) { Files.delete(destDirPath); } Files.createDirectory(destDirPath); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath.toFile())); ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { Path newFile = destDirPath.resolve(zipEntry.getName()); Files.createDirectories(newFile.getParent()); Files.copy(zipInputStream, newFile); zipEntry = zipInputStream.getNextEntry(); } zipInputStream.closeEntry(); zipInputStream.close(); return destDirPath; }
Source:
private boolean contains(T item, ListDataProvider<T> dataProvider) { return contains(item, dataProvider, getItems()); }

Target:
private boolean contains(T item, ListDataProvider<T> dataProvider) { final Object itemIdentifier = getIdentifier(item, dataProvider::getId); return getItems().anyMatch(i -> itemIdentifier.equals( getIdentifier(i, dataProvider::getId))); }
Source:
ClientDMNType getDMNType(final Map<String, JSITItemDefinition> allDefinitions, final JSITItemDefinition itemDefinition, final String namespace, final Map<String, ClientDMNType> dmnTypesMap) { final Map<String, ClientDMNType> fields = new HashMap<>(); boolean isCollection = itemDefinition.getIsCollection(); if (itemDefinition.getTypeRef() != null) { final ClientDMNType clientDmnType = getOrCreateDMNType(allDefinitions, itemDefinition.getTypeRef(), namespace, dmnTypesMap); if (clientDmnType != null) { if (clientDmnType.isComposite()) { fields.putAll(clientDmnType.getFields()); } isCollection = clientDmnType.isCollection() || isCollection; } else { throw new IllegalStateException( "Item: " + itemDefinition.getName() + " refers to typeRef: " + itemDefinition.getTypeRef() + " which can't be found. The item can be missing or required items sort is wrong"); } } final List<JSITItemDefinition> itemComponent = itemDefinition.getItemComponent(); return new ClientDMNType(namespace, itemDefinition.getName(), itemDefinition.getId(), isCollection, itemComponent != null && !itemComponent.isEmpty(), fields, null); }

Target:
ClientDMNType getDMNType(final Map<String, JSITItemDefinition> allDefinitions, final JSITItemDefinition itemDefinition, final String namespace, final Map<String, ClientDMNType> dmnTypesMap) { final Map<String, ClientDMNType> fields = new HashMap<>(); boolean isCollection = itemDefinition.getIsCollection(); if (itemDefinition.getTypeRef() != null) { final ClientDMNType clientDmnType = getOrCreateDMNType(allDefinitions, itemDefinition.getTypeRef(), namespace, dmnTypesMap); if (clientDmnType != null) { if (clientDmnType.isComposite()) { fields.putAll(clientDmnType.getFields()); } isCollection = clientDmnType.isCollection() || isCollection; } else { throw new IllegalStateException( "Item: " + itemDefinition.getName() + " refers to typeRef: " + itemDefinition.getTypeRef() + " which can't be found."); } } final List<JSITItemDefinition> itemComponent = itemDefinition.getItemComponent(); return new ClientDMNType(namespace, itemDefinition.getName(), itemDefinition.getId(), isCollection, itemComponent != null && !itemComponent.isEmpty(), fields, null); }
Source:
public void onErrorDownloadTranslations() { Snackbar .make(mTranslationLayout, R.string.error_getting_translation_list, Snackbar.LENGTH_SHORT) .show(); }

Target:
public void onErrorDownloadTranslations() { Snackbar .make(translationRecycler, R.string.error_getting_translation_list, Snackbar.LENGTH_SHORT) .show(); }
Source:
private BenchmarkPhaseEvent reportProgressUntilFinished(int queriesSubmitted, boolean continueOnFailure) { int completed = 0; double lastProgress = 0; Map<Status, Integer> statusCount = new EnumMap<>(Status.class); while (completed < queriesSubmitted) { try { BenchmarkQueryEvent event = completionService.take().get(); completed++; statusCount.compute(event.getEventStatus(), (status, count) -> count == null ? 1 : count + 1); if (event.getEventStatus().equals(FAILED) && !continueOnFailure) { executor.shutdownNow(); return postEvent(BenchmarkPhaseEvent.failed(phaseName, event.getErrorMessage())); } double progress = ((double) completed) / queriesSubmitted * 100; if (progress - lastProgress > 0.5 || completed == queriesSubmitted) { log.info("Progress: %s succeeded, %s failed, %s submitted, %.2f%% done", statusCount.getOrDefault(SUCCEEDED, 0), statusCount.getOrDefault(FAILED, 0), queriesSubmitted, progress); lastProgress = progress; } } catch (InterruptedException e) { currentThread().interrupt(); if (!continueOnFailure) { executor.shutdownNow(); return postEvent(BenchmarkPhaseEvent.failed(phaseName, e.toString())); } } catch (ExecutionException e) { executor.shutdownNow(); if (!continueOnFailure) { executor.shutdownNow(); return postEvent(BenchmarkPhaseEvent.failed(phaseName, e.toString())); } } } if (statusCount.getOrDefault(FAILED, 0) > 0) { return postEvent(BenchmarkPhaseEvent.completedWithFailures(phaseName, format("%s out of %s submitted queries failed", statusCount.get(FAILED), queriesSubmitted))); } return postEvent(BenchmarkPhaseEvent.succeeded(phaseName)); }

Target:
private BenchmarkPhaseEvent reportProgressUntilFinished(int queriesSubmitted, boolean continueOnFailure) { int completed = 0; double lastProgress = 0; Map<Status, Integer> statusCount = new EnumMap<>(Status.class); while (completed < queriesSubmitted) { try { BenchmarkQueryEvent event = completionService.take().get(); completed++; statusCount.compute(event.getEventStatus(), (status, count) -> count == null ? 1 : count + 1); if (event.getEventStatus() == FAILED && !continueOnFailure) { executor.shutdownNow(); return postEvent(BenchmarkPhaseEvent.failed(phaseName, event.getErrorMessage())); } double progress = ((double) completed) / queriesSubmitted * 100; if (progress - lastProgress > 0.5 || completed == queriesSubmitted) { log.info("Progress: %s succeeded, %s failed, %s submitted, %.2f%% done", statusCount.getOrDefault(SUCCEEDED, 0), statusCount.getOrDefault(FAILED, 0), queriesSubmitted, progress); lastProgress = progress; } } catch (InterruptedException e) { currentThread().interrupt(); if (!continueOnFailure) { executor.shutdownNow(); return postEvent(BenchmarkPhaseEvent.failed(phaseName, e.toString())); } } catch (ExecutionException e) { executor.shutdownNow(); if (!continueOnFailure) { executor.shutdownNow(); return postEvent(BenchmarkPhaseEvent.failed(phaseName, e.toString())); } } } if (statusCount.getOrDefault(FAILED, 0) > 0) { return postEvent(BenchmarkPhaseEvent.completedWithFailures(phaseName, format("%s out of %s submitted queries failed", statusCount.get(FAILED), queriesSubmitted))); } return postEvent(BenchmarkPhaseEvent.succeeded(phaseName)); }
Source:
public void call(final Subscriber<? super T> o) { final Iterator<? extends T> it; boolean b; try { it = is.iterator(); b = it.hasNext(); } catch (Throwable ex) { Exceptions.throwOrReport(ex, o); return; } if (!b && !o.isUnsubscribed()) { o.onCompleted(); } else { o.setProducer(new IterableProducer<T>(o, it)); } }

Target:
public void call(final Subscriber<? super T> o) { final Iterator<? extends T> it; boolean b; try { it = is.iterator(); b = it.hasNext(); } catch (Throwable ex) { Exceptions.throwOrReport(ex, o); return; } if (!o.isUnsubscribed()) { if (!b) { o.onCompleted(); } else { o.setProducer(new IterableProducer<T>(o, it)); } } }
Source:
public static String parseProcessingFailureResponse(InputStream responseStream) { try { KXmlParser baseParser = ElementParser.instantiateParser(responseStream); ElementParser<String> responseParser = new ElementParser<String>(baseParser) { @Override public String parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode("OpenRosaResponse"); nextTag("message"); String natureOfResponse = parser.getAttributeValue(null, "nature"); if ("processing_failure".equals(natureOfResponse)) { return parser.nextText(); } return ""; } }; return responseParser.parse(); } catch (IOException | InvalidStructureException | XmlPullParserException | UnfullfilledRequirementsException e) { Log.e(TAG, "Error while parsing form upload response"); e.printStackTrace(); } return ""; }

Target:
public static String parseProcessingFailureResponse(InputStream responseStream) throws IOException, InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException { KXmlParser baseParser = ElementParser.instantiateParser(responseStream); ElementParser<String> responseParser = new ElementParser<String>(baseParser) { @Override public String parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode("OpenRosaResponse"); nextTag("message"); String natureOfResponse = parser.getAttributeValue(null, "nature"); if ("processing_failure".equals(natureOfResponse)) { return parser.nextText(); } else { throw new UnfullfilledRequirementsException( "<message> for 422 response did not contain expected content", CommCareElementParser.SEVERITY_UNKOWN); } } }; return responseParser.parse(); }
Source:
private List<ExtMap> searchDirectoryUsers(QueryData data) { log.debug("Entered searchDirectoryUsers"); ExtensionProxy authz = AuthenticationUtils.getExtensionProfileByAuthzName(ssoContext, data.getAuthz()).getAuthz(); List<ExtMap> results = new ArrayList<>(); for (String namespace : getNamespaces(data)) { results.addAll(DirectoryUtils.findDirectoryUsersByQuery(authz, namespace, data.getQuery())); } log.debug("DirectoryUtils.findDirectoryUsersByQuery returned users in authz for query {}", results.size(), data.getAuthz(), data.getQuery()); return results; }

Target:
private List<ExtMap> searchDirectoryUsers(QueryData data) { log.debug("Entered searchDirectoryUsers"); ExtensionProxy authz = AuthenticationUtils.getExtensionProfileByAuthzName(ssoContext, data.getAuthz()).getAuthz(); List<ExtMap> results = new ArrayList<>(); getNamespaces(data).forEach((namespace) -> results.addAll(DirectoryUtils.findDirectoryUsersByQuery(authz, namespace, data.getQuery()))); log.debug("DirectoryUtils.findDirectoryUsersByQuery returned users in authz for query {}", results.size(), data.getAuthz(), data.getQuery()); return results; }
Source:
public Response intercept(Chain chain) throws IOException { try { return chain.proceed(chain.request()); } catch (Throwable t) { if (t instanceof IOException) { throw (IOException) t; } throw new IOException("Caught a non-IOException while executing a call. " + "This is a serious bug and requires investigation. Rethrowing " + "as an IOException in order to avoid blocking a thread", t); } }

Target:
public Response intercept(Chain chain) throws IOException { try { return chain.proceed(chain.request()); } catch (Throwable t) { if (t instanceof IOException) { throw (IOException) t; } throw new SafeIoException("Caught a non-IOException. " + "This is a serious bug and requires investigation. Rethrowing " + "as an IOException in order to avoid blocking a Dispatcher thread", t); } }
Source:
private int getAmOrPmKeyCode(int amOrPm) { if (mAmKeyCode == -1 || mPmKeyCode == -1) { KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD); char amChar; char pmChar; for (int i = 0; i < Math.max(mAmText.length(), mPmText.length()); i++) { amChar = mAmText.toLowerCase(Locale.getDefault()).charAt(i); pmChar = mPmText.toLowerCase(Locale.getDefault()).charAt(i); if (amChar != pmChar) { KeyEvent[] events = kcm.getEvents(new char[]{amChar, pmChar}); if (events.length == 4) { mAmKeyCode = events[0].getKeyCode(); mPmKeyCode = events[2].getKeyCode(); } else { Log.e(TAG, "Unable to find keycodes for AM and PM."); } break; } } } if (amOrPm == AM) { return mAmKeyCode; } else if (amOrPm == PM) { return mPmKeyCode; } return -1; }

Target:
private int getAmOrPmKeyCode(int amOrPm) { if (mAmKeyCode == -1 || mPmKeyCode == -1) { KeyCharacterMap kcm = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD); char amChar; char pmChar; for (int i = 0; i < Math.max(mAmText.length(), mPmText.length()); i++) { amChar = mAmText.toLowerCase(Locale.getDefault()).charAt(i); pmChar = mPmText.toLowerCase(Locale.getDefault()).charAt(i); if (amChar != pmChar) { KeyEvent[] events = kcm.getEvents(new char[]{amChar, pmChar}); if (events != null && events.length == 4) { mAmKeyCode = events[0].getKeyCode(); mPmKeyCode = events[2].getKeyCode(); } else { Log.e(TAG, "Unable to find keycodes for AM and PM."); } break; } } } if (amOrPm == AM) { return mAmKeyCode; } else if (amOrPm == PM) { return mPmKeyCode; } return -1; }
Source:
public void stopContainer(String containerId, int killWait) throws DockerAccessException { try { String url = urlBuilder.stopContainer(containerId, killWait); log.verbose(Logger.LogVerboseCategory.API,"POSTing %s", url); delegate.post(url, HTTP_NO_CONTENT, HTTP_NOT_MODIFIED); } catch (IOException e) { throw new DockerAccessException(e, "Unable to stop container id [%s]", containerId); } }

Target:
public void stopContainer(String containerId, int killWait) throws DockerAccessException { try { String url = urlBuilder.stopContainer(containerId, killWait); log.verbose(Logger.LogVerboseCategory.API,"POST %s", url); delegate.post(url, HTTP_NO_CONTENT, HTTP_NOT_MODIFIED); } catch (IOException e) { throw new DockerAccessException(e, "Unable to stop container id [%s]", containerId); } }
Source:
private static void runPersistentWorker() throws Exception { ByteArrayOutputStream buf = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(buf); PrintStream realStdOut = System.out; PrintStream realStdErr = System.err; try { System.setOut(ps); System.setErr(ps); while (true) { try { WorkRequest request = WorkRequest.parseDelimitedFrom(System.in); if (request == null) { break; } int exitCode = processRequest(request.getArgumentsList()); ps.flush(); WorkResponse.newBuilder() .setExitCode(exitCode) .setOutput(buf.toString()) .build() .writeDelimitedTo(realStdOut); realStdOut.flush(); buf.reset(); } catch (IOException e) { logger.severe(e.getMessage()); e.printStackTrace(realStdErr); } } } finally { System.setOut(realStdOut); System.setErr(realStdErr); } }

Target:
private static int runPersistentWorker() throws Exception { ByteArrayOutputStream buf = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(buf, true); PrintStream realStdOut = System.out; PrintStream realStdErr = System.err; try { System.setOut(ps); System.setErr(ps); while (true) { try { WorkRequest request = WorkRequest.parseDelimitedFrom(System.in); if (request == null) { break; } int exitCode = processRequest(request.getArgumentsList()); ps.flush(); WorkResponse.newBuilder() .setExitCode(exitCode) .setOutput(buf.toString()) .build() .writeDelimitedTo(realStdOut); realStdOut.flush(); buf.reset(); } catch (IOException e) { logger.severe(e.getMessage()); e.printStackTrace(realStdErr); return 1; } } } finally { System.setOut(realStdOut); System.setErr(realStdErr); } return 0; }
Source:
public void reset() { Schedulers.io().scheduleDirect(() -> { DataStore.clearTrailHistory(); history.clear(); }); }

Target:
public void reset() { Schedulers.io().scheduleDirect(new Runnable() { @Override public void run() { DataStore.clearTrailHistory(); history.clear(); } }); }
Source:
public void handle(final TypedMessage typedMessage) throws MessageHandlingException { try { final String messageType = typedMessage.getType(); logger.debug("Handling: " + messageType); for (final EventHandler<E> eventHandler : eventHandlers.get(messageType)) { final E event = AbstractEvent.newEvent(eventHandler.getEventClass(), typedMessage.getPayload()); if (!eventHandler.getEventClass().isAssignableFrom(event.getClass())) { throw new IllegalStateException("Event of type " + event.getClass() + " is not compatible with " + eventHandler.getEventClass() + " in event handler"); } eventHandler.handle(event); } } catch (final Exception e) { throw new MessageHandlingException(e.getMessage(), e); } }

Target:
public void handle(final TypedMessage typedMessage) throws MessageHandlingException { try { final String messageType = typedMessage.getType(); logger.debug("Handling: " + messageType); for (final EventHandler<E> eventHandler : eventHandlers.get(messageType)) { try { final E event = AbstractEvent.newEvent(eventHandler.getEventClass(), typedMessage.getPayload()); if (!eventHandler.getEventClass().isAssignableFrom(event.getClass())) { throw new IllegalStateException("Event of type " + event.getClass() + " is not compatible with " + eventHandler.getEventClass() + " in event handler"); } eventHandler.handle(event); } catch (final Exception e) { logger.error("Error handling message: " + typedMessage, e); } } } catch (final Exception e) { throw new MessageHandlingException(e.getMessage(), e); } }
Source:
public com.google.gwtorm.client.Key<?>[] members() { return new com.google.gwtorm.client.Key<?>[] {accountId, patchKey}; }

Target:
public com.google.gwtorm.client.Key<?>[] members() { return new com.google.gwtorm.client.Key<?>[] {patchKey}; }
Source:
public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { try { Object stage; if (!readNeedsLock(ctx, command)) { stage = invokeNext(ctx, command); } else { Collection<?> keys = command.getKeys(); if (!needRemoteLocks(ctx, keys, command)) { acquireLocalLocks(ctx, command, keys); stage = invokeNext(ctx, command); } else { final TxInvocationContext txContext = (TxInvocationContext) ctx; LockControlCommand lcc = cf.buildLockControlCommand(keys, command.getFlagsBitSet(), txContext.getGlobalTransaction()); stage = invokeNextThenApply(ctx, lcc, (rCtx, rLockCommand, rv) -> { acquireLocalLocks(rCtx, command, keys); return invokeNext(rCtx, command); }); } } return makeStage(stage).andFinally(ctx, command, (rCtx, rCommand, rv, t) -> { if (t != null) { releaseLocksOnFailureBeforePrepare(rCtx); } }); } catch (Throwable t) { releaseLocksOnFailureBeforePrepare(ctx); throw t; } }

Target:
public Object visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { try { Object stage; if (!readNeedsLock(ctx, command)) { stage = invokeNext(ctx, command); } else { Collection<?> keys = command.getKeys(); if (!needRemoteLocks(ctx, keys, command)) { acquireLocalLocks(ctx, command, keys); stage = invokeNext(ctx, command); } else { final TxInvocationContext txContext = (TxInvocationContext) ctx; LockControlCommand lcc = cf.buildLockControlCommand(keys, command.getFlagsBitSet(), txContext.getGlobalTransaction()); stage = invokeNextThenApply(ctx, lcc, (rCtx, rLockCommand, rv) -> { acquireLocalLocks(rCtx, command, keys); return invokeNext(rCtx, command); }); } } return makeStage(stage).andExceptionally(ctx, command, (rCtx, rCommand, t) -> { releaseLocksOnFailureBeforePrepare(rCtx); throw t; }); } catch (Throwable t) { releaseLocksOnFailureBeforePrepare(ctx); throw t; } }
Source:
public int getMinExposureCompensation() { return 0; }

Target:
public int getMinExposureCompensation() { return -6; }
Source:
void pause() { if (downloadBatchStatus.status() == PAUSED || downloadBatchStatus.status() == DOWNLOADED) { return; } downloadBatchStatus.markAsPaused(downloadsBatchPersistence); notifyCallback(downloadBatchStatus); for (DownloadFile downloadFile : downloadFiles) { downloadFile.pause(); } }

Target:
void pause() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); if (status == PAUSED || status == DOWNLOADED) { return; } downloadBatchStatus.markAsPaused(downloadsBatchPersistence); notifyCallback(downloadBatchStatus); for (DownloadFile downloadFile : downloadFiles) { downloadFile.pause(); } }
Source:
public static Collection getParameters() { List<Object[]> combinations = new ArrayList<>(); combinations.add(new Object[]{SNAPSHOT, TWO_SIX_THREE, TWO_SIX_THREE}); return combinations; }

Target:
public static Collection getParameters() { List<Object[]> combinations = new ArrayList<>(); combinations.add(new Object[]{SNAPSHOT, TWO_SIX_THREE, TWO_SIX_THREE}); combinations.add(new Object[]{SNAPSHOT, TWO_ZERO, TWO_ZERO}); combinations.add(new Object[]{SNAPSHOT, TWO_ONE, TWO_ONE}); combinations.add(new Object[]{SNAPSHOT, TWO_FOUR, TWO_FOUR}); return combinations; }
Source:
public JCheckBox getInverseCheckbox() { if (inverseCheckbox == null) { inverseCheckbox = new JCheckBox(Constant.messages.getString("websocket.filter.label.regex.inverse")); inverseCheckbox.setSelected(false); } return inverseCheckbox; }

Target:
public JCheckBox getInverseCheckbox() { if (inverseCheckbox == null) { inverseCheckbox = new JCheckBox(Constant.messages.getString("websocket.filter.label.regex.inverse")); } return inverseCheckbox; }
Source:
public boolean isLaunched(Agent agent, InstanceProcess process, Instance machine) throws MachineException { Server server = machine.getRuntime().getServers().get(exposedPort); if (server != null) { try { LOG.error("Ping ssh agent"); String[] hostPort = server.getAddress().split(":"); try (@SuppressWarnings("unused") Socket socket = new Socket(hostPort[0], Integer.parseInt(hostPort[1]))) { return true; } } catch (Exception ignored) { } } return false; }

Target:
public boolean isLaunched(Agent agent, InstanceProcess process, Instance machine) throws MachineException { Server server = machine.getRuntime().getServers().get(exposedPort); if (server != null) { try { String[] hostPort = server.getAddress().split(":"); try (@SuppressWarnings("unused") Socket socket = new Socket(hostPort[0], Integer.parseInt(hostPort[1]))) { return true; } } catch (Exception ignored) { } } return false; }
Source:
public void run(StreamApplication app) { SystemAdmins systemAdmins = null; try { systemAdmins = buildAndStartSystemAdmins(); StreamManager streamManager = buildStreamManager(systemAdmins); ExecutionPlan plan = getExecutionPlan(app, streamManager); String executionPlanJson = plan.getPlanAsJson(); writePlanJsonFile(executionPlanJson); LOG.info("Execution Plan: \n" + executionPlanJson); String planId = String.valueOf(executionPlanJson.hashCode()); createStreams(planId, plan.getIntermediateStreams(), streamManager); if (plan.getJobConfigs().isEmpty()) { throw new SamzaException("No jobs to run."); } plan.getJobConfigs().forEach(jobConfig -> { LOG.debug("Starting job StreamProcessor with config {}", jobConfig.getName(), jobConfig); LocalStreamProcessorLifeCycleListener listener = new LocalStreamProcessorLifeCycleListener(); StreamProcessor processor = createStreamProcessor(jobConfig, graphSpec, listener); listener.setProcessor(processor); processors.add(processor); }); numProcessorsToStart.set(processors.size()); processors.forEach(StreamProcessor::start); } catch (Throwable throwable) { appStatus = ApplicationStatus.unsuccessfulFinish(throwable); shutdownLatch.countDown(); throw new SamzaException(String.format("Failed to start application: %s.", app), throwable); } finally { if (systemAdmins != null) { systemAdmins.stop(); } } }

Target:
public void run(StreamApplication app) { StreamManager streamManager = null; try { streamManager = buildAndStartStreamManager(); ExecutionPlan plan = getExecutionPlan(app, streamManager); String executionPlanJson = plan.getPlanAsJson(); writePlanJsonFile(executionPlanJson); LOG.info("Execution Plan: \n" + executionPlanJson); String planId = String.valueOf(executionPlanJson.hashCode()); createStreams(planId, plan.getIntermediateStreams(), streamManager); if (plan.getJobConfigs().isEmpty()) { throw new SamzaException("No jobs to run."); } plan.getJobConfigs().forEach(jobConfig -> { LOG.debug("Starting job StreamProcessor with config {}", jobConfig.getName(), jobConfig); LocalStreamProcessorLifeCycleListener listener = new LocalStreamProcessorLifeCycleListener(); StreamProcessor processor = createStreamProcessor(jobConfig, graphSpec, listener); listener.setProcessor(processor); processors.add(processor); }); numProcessorsToStart.set(processors.size()); processors.forEach(StreamProcessor::start); } catch (Throwable throwable) { appStatus = ApplicationStatus.unsuccessfulFinish(throwable); shutdownLatch.countDown(); throw new SamzaException(String.format("Failed to start application: %s.", app), throwable); } finally { if (streamManager != null) { streamManager.stop(); } } }
Source:
public OperationFuture<ServerRef> removePublicIp(ServerRef serverRef) { ServerMetadata serverMetadata = findByRef(serverRef); List<JobFuture> jobFutures = new ArrayList<>(); serverMetadata.getDetails().getIpAddresses() .stream() .map(IpAddress::getPublicIp) .filter(notNull()) .forEach(address -> jobFutures.add(removePublicIp(serverRef, address).jobFuture())); return new OperationFuture<>( serverRef, new ParallelJobsFuture(jobFutures) ); }

Target:
public OperationFuture<ServerRef> removePublicIp(ServerRef serverRef) { ServerMetadata serverMetadata = findByRef(serverRef); List<JobFuture> jobFutures = serverMetadata.getDetails().getIpAddresses() .stream() .map(IpAddress::getPublicIp) .filter(notNull()) .map(address -> removePublicIp(serverRef, address).jobFuture()) .collect(toList()); return new OperationFuture<>( serverRef, new ParallelJobsFuture(jobFutures) ); }
Source:
public List<Currency> getCurrencyForName(final String name) { List<Currency> list = _namesToCurrency.get(name); if (list == null) { return new ArrayList<>(); } return _namesToCurrency.get(name); }

Target:
public List<Currency> getCurrencyForName(final String name) { return _namesToCurrency.get(name); }
Source:
public void run(InputStream inputStream) { Scanner scanner = new Scanner(inputStream); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.equalsIgnoreCase("stop")) { commandSender.print("Stopping!"); break; } if (line.startsWith("save")) { String[] bits = line.split(" "); if (bits.length == 0) { commandSender.print("Usage: save <filename>"); continue; } World world = platform.getWorlds().get(0); if (world instanceof ClipboardWorld) { File file; if (bits.length >= 2) { file = new File(bits[1]); } else { file = commandSender.openFileSaveDialog(new String[]{"schem"}); } if (file == null) { commandSender.printError("Please choose a file."); continue; } try(ClipboardWriter writer = BuiltInClipboardFormat.SPONGE_SCHEMATIC.getWriter(new FileOutputStream(file))) { writer.write((Clipboard) world); commandSender.print("Saved to file"); } catch (IOException e) { e.printStackTrace(); } } continue; } WorldEdit.getInstance().getEventBus().post(new CommandEvent( commandSender, line )); } scanner.close(); }

Target:
public void run(InputStream inputStream) { try (Scanner scanner = new Scanner(inputStream)) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.equals("stop")) { commandSender.print("Stopping!"); break; } CommandEvent event = new CommandEvent(commandSender, line); WorldEdit.getInstance().getEventBus().post(event); if (!event.isCancelled()) { commandSender.printError("Unknown command!"); } else { saveAllWorlds(false); } } } finally { saveAllWorlds(false); } }
Source:
public void verifyZoomingByGesture (PerformTouchAction touchAction, String zoomMethod) { Shooter shooter = new Shooter(); ImageComparison ic = new ImageComparison(); File beforeZooming = shooter.capturePage(driver); switch (zoomMethod) { case "gesture": touchAction.zoomInOutPointXY(50, 50, 50, 100, PerformTouchAction.ZOOM_WAY_IN, 3000); break; case "tap": touchAction.tapOnPointXY(50, 50, 140, 0); touchAction.tapOnPointXY(50, 50, 140, 3000); break; default: break; } File afterZoomIn = shooter.capturePage(driver); if (!ic.areFilesTheSame(beforeZooming, afterZoomIn)) { PageObjectLogging.log("verifyZoomingByGesture", "Zoom in by " + zoomMethod + " works", true); } else { PageObjectLogging.log("verifyZoomingByGesture", "Zoom in by " + zoomMethod + " doesn't work", false); } switch (zoomMethod) { case "gesture": touchAction.zoomInOutPointXY(50, 50, 50, 140, PerformTouchAction.ZOOM_WAY_OUT, 3000); break; case "tap": touchAction.tapOnPointXY(50, 50, 140, 0); touchAction.tapOnPointXY(50, 50, 140, 3000); break; default: break; } File afterZoomOut = shooter.capturePage(driver); if (ic.areFilesTheSame(beforeZooming, afterZoomOut)) { PageObjectLogging.log("verifyZoomingByGesture", "Zoom out by " + zoomMethod + " works", true); } else { PageObjectLogging.log("verifyZoomingByGesture", "Zoom out by " + zoomMethod + " doesn't work", false); } }

Target:
public void verifyZoomingByGesture (PerformTouchAction touchAction, String zoomMethod) { Shooter shooter = new Shooter(); ImageComparison ic = new ImageComparison(); File beforeZooming = shooter.capturePage(driver); switch (zoomMethod) { case "gesture": touchAction.zoomInOutPointXY(50, 50, 50, 100, PerformTouchAction.ZOOM_WAY_IN, 3000); break; case "tap": touchAction.tapOnPointXY(50, 50, 140, 0); touchAction.tapOnPointXY(50, 50, 140, 3000); break; default: break; } File afterZoomIn = shooter.capturePage(driver); if (ic.areFilesTheSame(beforeZooming, afterZoomIn)) { PageObjectLogging.log("verifyZoomingByGesture", "Zoom in by " + zoomMethod + " doesn't work", false); } else { PageObjectLogging.log("verifyZoomingByGesture", "Zoom in by " + zoomMethod + " works", true); } switch (zoomMethod) { case "gesture": touchAction.zoomInOutPointXY(50, 50, 50, 140, PerformTouchAction.ZOOM_WAY_OUT, 3000); break; case "tap": touchAction.tapOnPointXY(50, 50, 140, 0); touchAction.tapOnPointXY(50, 50, 140, 3000); break; default: break; } File afterZoomOut = shooter.capturePage(driver); if (ic.areFilesTheSame(beforeZooming, afterZoomOut)) { PageObjectLogging.log("verifyZoomingByGesture", "Zoom out by " + zoomMethod + " works", true); } else { PageObjectLogging.log("verifyZoomingByGesture", "Zoom out by " + zoomMethod + " doesn't work", false); } }
Source:
private void analyzeCoreContext(JavaContentAssistInvocationContext context, CompletionContext coreContext) { final ICompilationUnit cu= context.getCompilationUnit(); final CompletionProposalCollector collector= new CompletionProposalCollector(cu) { @Override public void acceptContext(final CompletionContext c) { super.acceptContext(c); updateTemplateEngine(c); } }; collector.setInvocationContext(context); collector.setRequireExtendedContext(true); try { cu.codeComplete(context.getInvocationOffset(), collector); } catch (JavaModelException e) { e.printStackTrace(); } }

Target:
private void analyzeCoreContext(JavaContentAssistInvocationContext context, CompletionContext coreContext) { if (coreContext.isExtended()) { updateTemplateEngine(coreContext); } else { final ICompilationUnit cu= context.getCompilationUnit(); final CompletionProposalCollector collector= new CompletionProposalCollector(cu) { @Override public void acceptContext(final CompletionContext c) { super.acceptContext(c); updateTemplateEngine(c); } }; collector.setInvocationContext(context); collector.setRequireExtendedContext(true); try { cu.codeComplete(context.getInvocationOffset(), collector); } catch (JavaModelException e) { e.printStackTrace(); } } }
Source:
private Response getSchema() { ByteArrayOutputStream baos = null; InputStream is = null; byte[] buffer = new byte[4096]; try { baos = new ByteArrayOutputStream(); is = Thread.currentThread().getContextClassLoader().getResourceAsStream(API_SCHEMA); int count; while ((count = is.read(buffer)) != -1) { baos.write(buffer, 0, count); } baos.flush(); return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename = " + SCHEMA_NAME) .build(); } catch (IOException e) { LOG.error("Loading api.xsd file failed.", e); return Response.serverError().build(); } finally { try { if (baos != null) baos.close(); if (is != null) is.close(); } catch (IOException e) { log.error("cannot close a resource", e); } } }

Target:
private Response getSchema() { ByteArrayOutputStream baos = null; InputStream is = null; byte[] buffer = new byte[4096]; try { baos = new ByteArrayOutputStream(); is = Thread.currentThread().getContextClassLoader().getResourceAsStream(API_SCHEMA); int count; while ((count = is.read(buffer)) != -1) { baos.write(buffer, 0, count); } baos.flush(); return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename = " + SCHEMA_NAME) .build(); } catch (IOException e) { LOG.error("Loading api.xsd file failed.", e); return Response.serverError().build(); } finally { try { if (baos != null) baos.close(); if (is != null) is.close(); } catch (IOException e) { LOG.error("cannot close a resource", e); } } }
Source:
public void waitUntilReceived(long seconds) { logger.info("Expecting to receive messages", expectedMessages.size()); await().atMost(adjust(new Duration(seconds, TimeUnit.SECONDS))).until(() -> receivedRequests.size() == expectedMessages.size()); synchronized (receivedRequests) { assertThat(receivedRequests.stream().map(LoggedRequest::getBodyAsString).collect(toList())).containsAll(expectedMessages); } }

Target:
public void waitUntilReceived(long seconds) { logger.info("Expecting to receive messages", expectedMessages.size()); await().atMost(adjust(new Duration(seconds, TimeUnit.SECONDS))).until(() -> assertThat(receivedRequests.size()).isGreaterThanOrEqualTo(expectedMessages.size())); synchronized (receivedRequests) { assertThat(receivedRequests.stream().map(LoggedRequest::getBodyAsString).collect(toList())).containsAll(expectedMessages); } }