auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Network update(Network incoming) { org.ovirt.engine.core.common.businessentities.Network network = map(incoming, map(get())); network.getCluster().setnetwork_id(network.getId()); network.getCluster().setcluster_id(cluster.getVDSGroup().getId()); performAction(VdcActionType.UpdateNetworkOnCluster, new NetworkClusterAttachmentParameters(network.getCluster())); return get(); }

Target:
public Network update(Network incoming) { org.ovirt.engine.core.common.businessentities.Network network = map(incoming, map(get())); network.getCluster().setnetwork_id(network.getId()); network.getCluster().setcluster_id(cluster.getVDSGroup().getId()); performAction(VdcActionType.UpdateNetworkOnCluster, new NetworkClusterParameters(network.getCluster())); return get(); }
Source:
private static void initFacets(@CheckForNull Fingerprint fingerprint){ if (fingerprint==null) return; for (FingerprintFacet facet : fingerprint.facets) facet._setOwner(fingerprint); }

Target:
private static void initFacets(@CheckForNull Fingerprint fingerprint) { if (fingerprint == null) { return; } for (FingerprintFacet facet : fingerprint.facets) { facet._setOwner(fingerprint); } }
Source:
public Set<StreamPartition<Integer>> getAssignment() { Set<TopicPartition> topicPartitions = consumer.assignment(); return topicPartitions .stream() .map((TopicPartition e) -> new StreamPartition<>(e.topic(), e.partition())) .collect(Collectors.toSet()); }

Target:
public Set<StreamPartition<Integer>> getAssignment() { Set<TopicPartition> topicPartitions = consumer.assignment(); return topicPartitions .stream() .map(e -> new StreamPartition<>(e.topic(), e.partition())) .collect(Collectors.toSet()); }
Source:
public TMapImportDefinition buildMapImportDefinition(String key, Object object) { if (!Objects.nonNull(object)) return null; TMapImportDefinition mapImportDefinition = new TMapImportDefinition(); mapImportDefinition.put(key, buildImportDefinition(object)); return mapImportDefinition; }

Target:
public TMapImportDefinition buildMapImportDefinition(String key, Object object) { if (Objects.isNull(object)) return null; TMapImportDefinition mapImportDefinition = new TMapImportDefinition(); mapImportDefinition.put(key, buildImportDefinition(object)); return mapImportDefinition; }
Source:
public Module(NinjaProperties ninjaProperties) { if(ninjaProperties == null) { throw new IllegalArgumentException("null properties"); } this.ninjaProperties = ninjaProperties; }

Target:
public Module(NinjaProperties ninjaProperties) { if(ninjaProperties == null) { throw new IllegalArgumentException("Received null as an instance of NinjaProperties"); } this.ninjaProperties = ninjaProperties; }
Source:
public List<ContactTrackingSummaryByCampaignReport> getSummaryByCampaign(String accessToken, String contactId) throws ConstantContactServiceException{ List<ContactTrackingSummaryByCampaignReport> summary = null; try { StringBuilder sb = new StringBuilder(); sb.append(Config.Endpoints.BASE_URL).append(String.format(Config.Endpoints.CONTACTS_TRACKING_REPORTS_BY_CAMPAIGN_SUMMARY, contactId)); String url = sb.toString(); CUrlResponse response = getRestClient().get(url, accessToken); if (response.hasData()) { summary = Component.listFromJSON(response.getBody(), ContactTrackingSummaryByCampaignReport.class); } if (response.isError()) { ConstantContactServiceException constantContactException = new ConstantContactServiceException( ConstantContactServiceException.RESPONSE_ERR_SERVICE); response.getInfo().add(new CUrlRequestError("url", url)); constantContactException.setErrorInfo(response.getInfo()); throw constantContactException; } } catch (ConstantContactServiceException e) { throw new ConstantContactServiceException(e); } catch (Exception e) { throw new ConstantContactServiceException(e); } return summary; }

Target:
public List<ContactTrackingSummaryByCampaignReport> getSummaryByCampaign(String accessToken, String contactId) throws ConstantContactServiceException{ List<ContactTrackingSummaryByCampaignReport> summary = null; try { StringBuilder sb = new StringBuilder(); sb.append(Config.Endpoints.BASE_URL).append(String.format(Config.Endpoints.CONTACTS_TRACKING_REPORTS_BY_CAMPAIGN_SUMMARY, contactId)); String url = sb.toString(); CUrlResponse response = getRestClient().get(url, accessToken); if (response.hasData()) { summary = Component.listFromJSON(response.getBody(), ContactTrackingSummaryByCampaignReport.class); } if (response.isError()) { ConstantContactServiceException constantContactException = new ConstantContactServiceException( ConstantContactServiceException.RESPONSE_ERR_SERVICE); response.getInfo().add(new CUrlRequestError("url", url)); constantContactException.setErrorInfo(response.getInfo()); throw constantContactException; } } catch (Exception e) { throw new ConstantContactServiceException(e); } return summary; }
Source:
public Issue getUpstreamIssue(final PullRequest pullRequest) throws NotFoundException, MalformedURLException { Objects.requireNonNull(pullRequest, "url cannot be null"); checkIssueTrackerExists(); if (this.isUpstreamRequired(pullRequest)) { final String body = pullRequest.getBody(); final String[] url = extractURLs(body, UPSTREAM_ISSUE, false); if (url == null || url.length == 0 || url[0] == null) return null; else return getIssue(new URL(url[0])); } else { return null; } }

Target:
public Issue getUpstreamIssue(final PullRequest pullRequest) throws NotFoundException, MalformedURLException { Objects.requireNonNull(pullRequest, "pull request cannot be null"); checkIssueTrackerExists(); if (this.isUpstreamRequired(pullRequest)) { final String body = pullRequest.getBody(); final String[] url = extractURLs(body, UPSTREAM_ISSUE, false); if (url == null || url.length == 0 || url[0] == null) return null; else return getIssue(new URL(url[0])); } else { return null; } }
Source:
public void report() { DSeries request = new DSeries(); addGaugesAndUnregisterOnException(request); counters.values().forEach(request::addCounter); meters.values().forEach(request::addMeter); int totalMetrics = request.getSeries().size(); int fromIndex = 0; while (fromIndex < totalMetrics) { int toIndex = Math.min(fromIndex + maxMetricsPerRequestValue, totalMetrics); try { client.send(new DSeries(request.getSeries().subList(fromIndex, toIndex))); } catch (SocketTimeoutException e) { LOGGER.warn("Failed reporting metrics to Datadog because of socket timeout: {}", e.getMessage()); } catch (Exception e) { LOGGER.warn("Failed reporting metrics to Datadog.", e); } fromIndex = toIndex; } LOGGER.debug("Reported series with size {}.", totalMetrics); counters.values().forEach(DCounter::ackReport); }

Target:
public void report() { DSeries request = new DSeries(); addGaugesAndUnregisterOnException(request); counters.values().forEach(request::addCounter); meters.values().forEach(request::addMeter); int totalMetrics = request.getSeries().size(); int fromIndex = 0; while (fromIndex < totalMetrics) { int toIndex = Math.min(fromIndex + maxMetricsPerRequestValue, totalMetrics); try { DSeries chunk = new DSeries(request.getSeries().subList(fromIndex, toIndex)); client.send(chunk); chunk.getSeries().forEach(DMetric::ackReport); LOGGER.debug("Reported series with size {}.", chunk.getSeries().size()); } catch (SocketTimeoutException e) { LOGGER.warn("Failed reporting metrics to Datadog because of socket timeout: {}", e.getMessage()); } catch (Exception e) { LOGGER.warn("Failed reporting metrics to Datadog.", e); } fromIndex = toIndex; } }
Source:
public void testImportElementOnlyAppearsInTopLevel() throws IOException { File config1 = createConfigFile("hz1", ".yaml"); FileOutputStream os1 = new FileOutputStream(config1); String config1Yaml = "" + "hazelcast-client:\n" + " instance-name: my-instance"; writeStringToStreamAndClose(os1, config1Yaml); String yaml = "" + "hazelcast-client:\n" + " network:\n" + " import:\n" + " - file:/ ClientConfig clientConfig = buildConfig(yaml); assertNotEquals("my-instance", clientConfig.getInstanceName()); }

Target:
public void testImportElementOnlyAppearsInTopLevel() throws IOException { File config1 = createConfigFile("hz1", ".yaml"); FileOutputStream os1 = new FileOutputStream(config1); String config1Yaml = "" + "hazelcast-client:\n" + " instance-name: my-instance"; writeStringToStreamAndClose(os1, config1Yaml); String yaml = "" + "hazelcast-client:\n" + " network:\n" + " import:\n" + " - file:/ ClientConfig clientConfig = buildConfig(yaml); assertNull(clientConfig.getInstanceName()); }
Source:
public boolean isNewerJenkinsServer() { return Type.JENKINS.equals(type) && HudsonServerInfo.JENKINS_1_511.compareTo(version) < 0; }

Target:
public boolean isNewerJenkinsServer() { return Type.JENKINS.equals(type) && JENKINS_1_511.compareTo(version) < 0; }
Source:
protected AnyFieldRegexFilter(final Builder builder) { super("*", builder.filter); pattern = Pattern.compile(filter.trim()); }

Target:
protected AnyFieldRegexFilter(final Builder builder) { super(".*", builder.filter); pattern = Pattern.compile(filter.trim()); }
Source:
public ListenableFuture<R> apply(T argument) { checkState(!closed, "AsyncTimelockRefresher is already shut down"); SettableFuture<R> result = SettableFuture.create(); buffer.publishEvent((refresh, sequence) -> { refresh.result = result; refresh.argument = argument; }); return result; }

Target:
public ListenableFuture<R> apply(T argument) { checkState(!closed, "Autobatcher is already shut down"); SettableFuture<R> result = SettableFuture.create(); buffer.publishEvent((refresh, sequence) -> { refresh.result = result; refresh.argument = argument; }); return result; }
Source:
public void initChannel(SocketChannel socket) throws IOException, NoSuchAlgorithmException, CertificateException { ChannelPipeline pipeline = socket.pipeline(); if(enableSSL) { SslHandler sslHandler = sslBuilder.build(socket.alloc()); pipeline.addLast(SSL_HANDLER, sslHandler); } pipeline.addLast(idleExecutorGroup, IDLESTATE_HANDLER, new IdleStateHandler(clientInactivityTimeoutSeconds, IDLESTATE_WRITER_IDLE_TIME_SECONDS , clientInactivityTimeoutSeconds)); pipeline.addLast(BEATS_ACKER, new AckEncoder()); pipeline.addLast(KEEP_ALIVE_HANDLER, new KeepAliveHandler()); pipeline.addLast(BEATS_PARSER, new BeatsParser()); pipeline.addLast(new DefaultEventExecutorGroup(DEFAULT_BEATS_HANDLER_THREAD), BEATS_HANDLER, new BeatsHandler(this.message)); }

Target:
public void initChannel(SocketChannel socket) throws IOException, NoSuchAlgorithmException, CertificateException { ChannelPipeline pipeline = socket.pipeline(); if(enableSSL) { SslHandler sslHandler = sslBuilder.build(socket.alloc()); pipeline.addLast(SSL_HANDLER, sslHandler); } pipeline.addLast(idleExecutorGroup, IDLESTATE_HANDLER, new IdleStateHandler(clientInactivityTimeoutSeconds, IDLESTATE_WRITER_IDLE_TIME_SECONDS , clientInactivityTimeoutSeconds)); pipeline.addLast(BEATS_ACKER, new AckEncoder()); pipeline.addLast(KEEP_ALIVE_HANDLER, new KeepAliveHandler()); pipeline.addLast(BEATS_PARSER, new BeatsParser()); pipeline.addLast(beatsHandlerExecutorGroup, BEATS_HANDLER, new BeatsHandler(this.message)); }
Source:
public void updateNewVendorStatusInPaymentWorks(List<PaymentWorksNewVendorUpdateVendorStatus> paymentWorksUpdateNewVendorStatus) { String jsonString = new PaymentWorksUtil().pojoToJsonString(paymentWorksUpdateNewVendorStatus); Client client = buildClient(); String URL = (new StringBuilder(getPaymentworksApiUrl()).append(NEW_VENDOR_REQUEST_UPDATE_STATUS)).toString(); LOG.info("updateNewVendorStatusInPaymentWorks. json string: " + jsonString); ClientResponse response = client.handle(buildClientRequest(URL, jsonString)); LOG.debug("updateNewVendorStatusInPaymentWorks, Status: " + response.getStatus()); if (response.getStatus() == 200) { LOG.debug("updateNewVendorStatusInPaymentWorks, New Vendor Request status updated"); } else { LOG.error("updateNewVendorStatusInPaymentWorks, Failed to update New Vendor Request status: " + response.getEntity(String.class)); } }

Target:
public void updateNewVendorStatusInPaymentWorks( List<PaymentWorksNewVendorUpdateVendorStatus> paymentWorksUpdateNewVendorStatus) { String jsonString = getPaymentWorksUtilityService().pojoToJsonString(paymentWorksUpdateNewVendorStatus); Client client = buildClient(); String URL = (new StringBuilder(getPaymentworksApiUrl()).append(NEW_VENDOR_REQUEST_UPDATE_STATUS)).toString(); LOG.info("updateNewVendorStatusInPaymentWorks. json string: " + jsonString); ClientResponse response = client.handle(buildClientRequest(URL, jsonString)); if (response.getStatus() == HttpURLConnection.HTTP_OK) { LOG.debug("updateNewVendorStatusInPaymentWorks, New Vendor Request status updated"); } else { LOG.error("updateNewVendorStatusInPaymentWorks, Failed to update New Vendor Request status: " + response.getEntity(String.class)); throw new RuntimeException("Unable to update new vendor status in PaymentWorks"); } }
Source:
public void showShipMenu(final Spaceship ship) { final CharSequence orders[] = new CharSequence[]{ SpacecraftOrder.MOVE.name(), SpacecraftOrder.ATTACK.name(), SpacecraftOrder.COLONISE.name(), SpacecraftOrder.ENTER_WORMHOLE.name() }; AlertDialog.Builder builder = new AlertDialog.Builder(ctxt); builder.setTitle(ship.getClass().getSimpleName()); builder.setItems(orders, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: selectedShip = ship; SELECT_MODE = (selectedShip != null) ? 1 : 0; CURRENTLY_ORDERING = true; break; case 1: setSelectedShipForOnClick(); UnitActions.attackSystem(selectedShip, globalGameData); break; case 2: setSelectedShipForOnClick(); if (selectedShip instanceof ColonyShip) { if (sectors[currentX][currentY].hasSystem()) { if (!sectors[currentX][currentY].getSystem().hasOwner()) { selectedShip.clearCourse(); ((ColonyShip) selectedShip).colonise(); makeToast("Colonising..."); } else { showError("This system is already colonised " + sectors[currentX][currentY].getSystem().getOwner()); } } else { showError("This system cannot be colonised"); } } break; case 3: setSelectedShipForOnClick(); Sector selectedSector = getSelectedSector(currentX, currentY); if (selectedSector instanceof Wormhole) { selectedShip.enterWormhole(); makeToast("Entering wormhole"); } else { makeToast("No wormhole to enter"); } default: Log.wtf("Clicked ", "" + which); } } }); AlertDialog shipDialog = builder.create(); int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT; shipDialog.getWindow().setLayout(100, WRAP_CONTENT); shipDialog.show(); sound_yessir.start(); }

Target:
public void showShipMenu(final Spaceship ship) { final CharSequence orders[] = new CharSequence[]{ SpacecraftOrder.MOVE.name(), SpacecraftOrder.ATTACK.name(), SpacecraftOrder.COLONISE.name(), SpacecraftOrder.ENTER_WORMHOLE.name() }; AlertDialog.Builder builder = new AlertDialog.Builder(ctxt); builder.setTitle(ship.getClass().getSimpleName()); builder.setItems(orders, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { orderShip(ship, which); } }); AlertDialog shipDialog = builder.create(); int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT; shipDialog.getWindow().setLayout(100, WRAP_CONTENT); shipDialog.show(); sound_yessir.start(); }
Source:
public BugzillaRestRepositorySettingsPage(TaskRepository taskRepository, AbstractRepositoryConnector connector, AbstractRepositoryConnectorUi connectorUi) { super("Bugzilla REST Repository Settings", DESCRIPTION, taskRepository, connector == null ? (BugzillaRestConnector.getDefault() == null ? new BugzillaRestConnector() : BugzillaRestConnector.getDefault()) : connector, connectorUi == null ? new BugzillaRestRepositoryConnectorUi() : connectorUi); setNeedsAnonymousLogin(true); setNeedsValidateOnFinish(true); }

Target:
public BugzillaRestRepositorySettingsPage(TaskRepository taskRepository, AbstractRepositoryConnector connector, AbstractRepositoryConnectorUi connectorUi) { super("Bugzilla REST Repository Settings", DESCRIPTION, taskRepository, connector, connectorUi); setNeedsAnonymousLogin(true); setNeedsValidateOnFinish(true); }
Source:
public void doSystemCancel_chargeStatusDuringAuthorisation_DoesNotNeedCancellationWithProvider(String chargeStatus) throws Exception { var status = ChargeStatus.fromString(chargeStatus); String externalChargeId = "external-charge-id"; Long gatewayAccountId = nextLong(); ChargeEntity chargeEntity = aValidChargeEntity() .withExternalId(externalChargeId) .withTransactionId("transaction-id") .withStatus(status) .build(); when(mockQueryService.isTerminableWithGateway(chargeEntity)).thenReturn(false); when(mockChargeDao.findByExternalIdAndGatewayAccount(externalChargeId, gatewayAccountId)).thenReturn(Optional.of(chargeEntity)); chargeCancelService.doSystemCancel(externalChargeId, gatewayAccountId); verify(mockPaymentProvider, never()).cancel(any()); verify(chargeService).transitionChargeState(externalChargeId, SYSTEM_CANCELLED); verifyNoMoreInteractions(ignoreStubs(mockChargeDao)); }

Target:
public void doSystemCancel_chargeStatusDuringAuthorisation_DoesNotNeedCancellationWithProvider(String chargeStatus) throws Exception { var status = ChargeStatus.fromString(chargeStatus); String externalChargeId = "external-charge-id"; Long gatewayAccountId = nextLong(); ChargeEntity chargeEntity = aValidChargeEntity() .withExternalId(externalChargeId) .withTransactionId("transaction-id") .withStatus(status) .build(); when(mockQueryService.isTerminableWithGateway(chargeEntity)).thenReturn(false); when(mockChargeDao.findByExternalIdAndGatewayAccount(externalChargeId, gatewayAccountId)).thenReturn(Optional.of(chargeEntity)); chargeCancelService.doSystemCancel(externalChargeId, gatewayAccountId); verify(mockPaymentProvider, never()).cancel(any()); verify(chargeService).transitionChargeState(externalChargeId, SYSTEM_CANCELLED); }
Source:
public static final AbstractTextColumn<Disk> getAllocationColumn(String sortBy) { AbstractTextColumn<Disk> column = new AbstractEnumColumn<Disk, VolumeType>() { @Override protected VolumeType getRawValue(Disk object) { return object.getDiskStorageType() == DiskStorageType.IMAGE || object.getDiskStorageType() == DiskStorageType.CINDER ? ((DiskImage) object).getVolumeType() : null; } @Override public SafeHtml getTooltip(Disk object) { if (object.getDiskStorageType() != DiskStorageType.IMAGE && object.getDiskStorageType() != DiskStorageType.CINDER) { return null; } DiskImage diskImage = (DiskImage) object; if (diskImage.getSnapshots().isEmpty()) { return null; } VolumeType originalVolumeType = diskImage.getSnapshots().get(diskImage.getSnapshots().size() - 1).getVolumeType(); return SafeHtmlUtils.fromString( StringFormat.format("%s: %s", AssetProvider.getConstants().originalAllocationDisk(), EnumTranslator.getInstance().translate(originalVolumeType))); } }; return makeSortable(column, sortBy); }

Target:
public static final AbstractTextColumn<Disk> getAllocationColumn(String sortBy) { AbstractTextColumn<Disk> column = new AbstractEnumColumn<Disk, VolumeType>() { @Override protected VolumeType getRawValue(Disk object) { return object.getDiskStorageType() == DiskStorageType.IMAGE || object.getDiskStorageType() == DiskStorageType.CINDER ? ((DiskImage) object).getVolumeType() : null; } @Override public SafeHtml getTooltip(Disk object) { if (object.getDiskStorageType() != DiskStorageType.IMAGE && object.getDiskStorageType() != DiskStorageType.CINDER) { return null; } VolumeType originalVolumeType = null; for (DiskImage snapshot : ((DiskImage) object).getSnapshots()) { if (snapshot.getParentId() == null || snapshot.getParentId().equals(Guid.Empty)) { originalVolumeType = snapshot.getVolumeType(); break; } } if (originalVolumeType == null) { return null; } return SafeHtmlUtils.fromString( StringFormat.format("%s: %s", AssetProvider.getConstants().originalAllocationDisk(), EnumTranslator.getInstance().translate(originalVolumeType))); } }; return makeSortable(column, sortBy); }
Source:
public Future<Response> submit() { if (client.httpEngine() instanceof AsyncClientHttpEngine) { return asyncSubmit(getFutureExtractorFunction(false, null), result -> result, getAsyncAbortedFunction(null), getAsyncExceptionFunction(null)); } else { return executorSubmit(client.asyncInvocationExecutor(), null, result -> result); } }

Target:
public Future<Response> submit() { return doSubmit(false, null, result -> result); }
Source:
private String normalizableDateRangeForXML(String dateRange) { if (dateRange.indexOf('/') >= 0) { String[] dates = dateRange.split("/", 2); Instant dateFromInstant = instantFromIso(dates[0]); Instant dateToInstant = instantFromIso(dates[1]); String dateFrom = ""; String dateTo = ""; if (dateFromInstant != null) { dateFrom = Objects.toString(dateFromInstant.toEpochMilli()); } if (dateToInstant != null) { dateTo = Objects.toString(dateToInstant.toEpochMilli()); } return dateFrom + '/' + dateTo; } return null; }

Target:
private String normalizableDateRangeForXML(String dateRange) { if (dateRange.indexOf('/') >= 0) { String[] dates = dateRange.split("/", 2); Instant dateFromInstant = instantFromIso(dates[0]); Instant dateToInstant = instantFromIso(dates[1]); final String dateFrom = (dateFromInstant != null) ? Objects.toString(dateFromInstant.toEpochMilli()) : ""; final String dateTo = (dateToInstant != null) ? Objects.toString(dateToInstant.toEpochMilli()) : ""; return dateFrom + '/' + dateTo; } return null; }
Source:
private static void addFormattedText(XWPFRun run, String text, int fontSize, boolean bold) { addFormattedText(run, text, "Calibri", fontSize, bold, null); }

Target:
private static void addFormattedText(XWPFRun run, String text, int fontSize, boolean bold) { addFormattedText(run, text, FONT_FAMILY, fontSize, bold, null); }
Source:
public boolean hasNext() throws IOException { if( csvWriter == null ){ throw new IOException("Writer has been closed"); } if (this.appending) { return false; } return iterator.hasNext(); }

Target:
public boolean hasNext() throws IOException { if( csvWriter == null ){ return false; } if (this.appending) { return false; } return iterator.hasNext(); }
Source:
protected void stubPost(UrlMatchingStrategy url, String responseFile) throws Exception { stubFor(post(url) .withHeader("Authorization", equalTo("Basic dXNlcjpwYXNz")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(IOUtils.toString(getClass().getResourceAsStream(responseFile))))); }

Target:
protected void stubPost(UrlMatchingStrategy url, String responseFile) throws Exception { stubFor(post(url) .withHeader("Authorization", equalTo("Basic dXNlcjpwYXNz")) .willReturn(aResponse() .withStatus(HttpStatus.SC_OK) .withHeader("Content-Type", "application/json") .withBody(IOUtils.toString(getClass().getResourceAsStream(responseFile))))); }
Source:
private static <T, R> Function<T, Observable<R>> convertSingleMapperToObservableMapper( final Function<? super T, ? extends SingleSource<? extends R>> mapper) { return new Function<T, Observable<R>>() { @SuppressWarnings("unchecked") @Override public Observable<R> apply(T t) throws Exception { SingleSource<? extends R> source = mapper.apply(t); Single<? extends R> single; if (source instanceof Single) { single = (Single<? extends R>) source; } else { single = Single.unsafeCreate(source); } return (Observable<R>) single.toObservable(); } }; }

Target:
private static <T, R> Function<T, Observable<R>> convertSingleMapperToObservableMapper( final Function<? super T, ? extends SingleSource<? extends R>> mapper) { ObjectHelper.requireNonNull(mapper, "mapper is null"); return new ObservableMapper<T,R>(mapper); }
Source:
private boolean isNumberZero(String literalValue) { return !literalValue.matches(".*[1-9]+.*") || (literalValue.startsWith("0x") && !literalValue.substring(2).matches(".*[1-9a-fA-F]+.*")); }

Target:
private static boolean isNumberZero(String literalValue) { return isNullCharacter(literalValue) || !(literalValue.matches("(.)*[1-9]+(.)*") || literalValue.matches("(0x|0X){1}(.)*[1-9a-fA-F]+(.)*") || literalValue.matches("(0b|0B){1}(.)*[1]+(.)*")); }
Source:
public DataReader(IConnectionInterface connectionInterface) { this.connectionInterface = connectionInterface; }

Target:
public DataReader(IConnectionInterface connectionInterface) { if (connectionInterface == null) throw new NullPointerException("Connection interface cannot be null."); this.connectionInterface = connectionInterface; }
Source:
public Multimap<CallStackDepth, ICalledFunction> queryCallStacks(Collection<CallStackDepth> callstacks, Collection<Long> times) { Map<Integer, CallStackDepth> quarks = new HashMap<>(); for (CallStackDepth csDepth : callstacks) { quarks.put(csDepth.getQuark(), csDepth); } Multimap<CallStackDepth, ICalledFunction> map = ArrayListMultimap.create(); try { Iterable<ITmfStateInterval> query2d = fStateSystem.query2D(quarks.keySet(), times); for (ITmfStateInterval callInterval : query2d) { if (!callInterval.getStateValue().isNull()) { CallStackDepth callStackDepth = Objects.requireNonNull(quarks.get(callInterval.getAttribute())); map.put(callStackDepth, callStackDepth.getCallStack().getFunctionFromInterval(callInterval)); } } } catch (IndexOutOfBoundsException | TimeRangeException | StateSystemDisposedException e) { e.printStackTrace(); } return map; }

Target:
public Multimap<CallStackDepth, ISegment> queryCallStacks(Collection<CallStackDepth> callstacks, Collection<Long> times) { Map<Integer, CallStackDepth> quarks = new HashMap<>(); for (CallStackDepth csDepth : callstacks) { quarks.put(csDepth.getQuark(), csDepth); } Multimap<CallStackDepth, ISegment> map = Objects.requireNonNull(ArrayListMultimap.create()); Collection<Long> queryTimes = getTimes(fStateSystem, times); try { Iterable<ITmfStateInterval> query2d = fStateSystem.query2D(quarks.keySet(), queryTimes); for (ITmfStateInterval callInterval : query2d) { CallStackDepth callStackDepth = Objects.requireNonNull(quarks.get(callInterval.getAttribute())); if (!callInterval.getStateValue().isNull()) { map.put(callStackDepth, callStackDepth.getCallStack().getFunctionFromInterval(callInterval)); } else { map.put(callStackDepth, new NullFunction(callInterval)); } } } catch (IndexOutOfBoundsException | TimeRangeException | StateSystemDisposedException e) { e.printStackTrace(); } return map; }
Source:
public Iterable<Method> allPublicMethods() { final Collection<Method> methods = new ArrayList<Method>(0); final Predicate<Method> predicate = new MethodPredicate(); for (final Class<?> clazz : this.allTypes()) { methods.addAll( Collections2.filter( Arrays.asList(clazz.getDeclaredMethods()), predicate ) ); } return methods; }

Target:
public Iterable<Method> allPublicMethods() { return Iterables.concat( Iterables.transform( this.allTypes(), new Function<Class<?>, Iterable<Method>>() { @Override public Iterable<Method> apply(final Class<?> input) { return Iterables.filter( Arrays.asList(input.getDeclaredMethods()), new Predicate<Method>() { @Override public boolean apply(final Method method) { return Modifier.isPublic( method.getModifiers() ); } } ); } } ) ); }
Source:
public void testApplicationSelectInsertWithAPI() throws Exception { try { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); lma.prepareDAG(new ApplicationSelectInsertWithAPI(), conf); LocalMode.Controller lc = lma.getController(); lc.runAsync(); Assert.assertTrue(waitTillDirAppears(outputFolder, 20000)); lc.shutdown(); } catch (Exception e) { Assert.fail("constraint violations: " + e); } File file = new File(outputFolder); File file1 = new File(outputFolder + file.list()[0]); List<String> strings = FileUtils.readLines(file1); String[] actualLines = strings.toArray(new String[strings.size()]); String[] expectedLines = new String[]{"15/02/2016 10:18:00 +0000,15/02/2016 00:00:00 +0000,OILPAINT4", "", "15/02/2016 10:19:00 +0000,15/02/2016 00:00:00 +0000,OILPAINT5", ""}; Assert.assertTrue(Arrays.deepEquals(actualLines, expectedLines)); }

Target:
public void testApplicationSelectInsertWithAPI() throws Exception { try { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); lma.prepareDAG(new ApplicationSelectInsertWithAPI(), conf); LocalMode.Controller lc = lma.getController(); lc.runAsync(); Assert.assertTrue(waitTillFileIsPopulated(outputFolder, 40000)); lc.shutdown(); } catch (Exception e) { Assert.fail("constraint violations: " + e); } File file = new File(outputFolder); File file1 = new File(outputFolder + file.list()[0]); List<String> strings = FileUtils.readLines(file1); String[] actualLines = strings.toArray(new String[strings.size()]); String[] expectedLines = new String[]{"15/02/2016 10:18:00 +0000,15/02/2016 00:00:00 +0000,OILPAINT4", "", "15/02/2016 10:19:00 +0000,15/02/2016 00:00:00 +0000,OILPAINT5", ""}; Assert.assertTrue(Arrays.deepEquals(actualLines, expectedLines)); }
Source:
public static void writeUuid(ByteBuffer buf, UUID uuid) { buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); }

Target:
private static void writeUuid(ByteBuffer buf, UUID uuid) { buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); }
Source:
private JSONObject getSummaryDetails(Map<String, ISuiteResult> results) { Object firstSuite = results.keySet().toArray()[0]; ISuiteResult result = results.get(firstSuite); ITestContext testContext = result.getTestContext(); int passedTests = testContext.getPassedTests().getAllResults().size(); int failedTests = testContext.getFailedTests().getAllResults().size(); int skippedTests = testContext.getSkippedTests().getAllResults().size(); String suiteName = testContext.getName(); Date startDate = testContext.getStartDate(); Date endDate = testContext.getEndDate(); long duration = endDate.getTime() - startDate.getTime(); JSONObject jsonSummary = new JSONObject(); jsonSummary.put("suite_name", suiteName); jsonSummary.put("passed", passedTests); jsonSummary.put("failed", failedTests); jsonSummary.put("skipped", skippedTests); jsonSummary.put("duration", duration / 1000); return jsonSummary; }

Target:
private JSONObject getSummaryDetails(Map<String, ISuiteResult> results) { Object firstSuite = results.keySet().toArray()[0]; ISuiteResult result = results.get(firstSuite); ITestContext testContext = result.getTestContext(); int passedTests = testContext.getPassedTests().getAllResults().size(); int failedTests = testContext.getFailedTests().getAllResults().size(); int skippedTests = testContext.getSkippedTests().getAllResults().size(); String suiteName = testContext.getName(); JSONObject jsonSummary = new JSONObject(); jsonSummary.put("suite_name", suiteName); jsonSummary.put("passed", passedTests); jsonSummary.put("failed", failedTests); jsonSummary.put("skipped", skippedTests); jsonSummary.put("duration", Duration.of(testContext.getEndDate().getTime() - testContext.getStartDate().getTime(), ChronoUnit.SECONDS)); return jsonSummary; }
Source:
protected void executeCommand() { SetupNetworksParameters parameters = new AddNetworksByLabelParametersBuilder().buildParameters(getNic(), getLabel(), getClusterNetworksByLabel()); parameters.setShouldBeLogged(false); VdcReturnValueBase result = getBackend().runInternalAction(VdcActionType.PersistentSetupNetworks, parameters); if (result.getSucceeded()) { getReturnValue().setActionReturnValue(getLabel()); } else { propagateFailure(result); } setSucceeded(result.getSucceeded()); }

Target:
protected void executeCommand() { PersistentSetupNetworksParameters parameters = new AddNetworksByLabelParametersBuilder().buildParameters(getNic(), getLabel(), getClusterNetworksByLabel()); parameters.setShouldBeLogged(false); VdcReturnValueBase result = getBackend().runInternalAction(VdcActionType.PersistentSetupNetworks, parameters); if (result.getSucceeded()) { getReturnValue().setActionReturnValue(getLabel()); } else { propagateFailure(result); } setSucceeded(result.getSucceeded()); }
Source:
public void typed_predicate_factory_should_allow_typed_predicate_assertions() { Predicate<String> predicate = Strings::isNullOrEmpty; assertThat((Object) predicate).instanceOf(predicate(String.class)).accepts(""); }

Target:
void typed_predicate_factory_should_allow_typed_predicate_assertions() { Object value = (Predicate<String>) Strings::isNullOrEmpty; PredicateAssert<String> result = assertThat(value).asInstanceOf(predicate(String.class)); result.accepts(""); }
Source:
public void fireProcessBean(BeanManagerImpl beanManager, Bean<?> bean, Extension extension) { if (isProcessBeanObserved()) { if (bean instanceof ManagedBean<?>) { ProcessManagedBeanImpl.fire(beanManager, (ManagedBean<?>) bean); } else if (bean instanceof SessionBean<?>) { ProcessSessionBeanImpl.fire(beanManager, Reflections.<SessionBean<Object>> cast(bean)); } else if (bean instanceof ProducerField<?, ?>) { ProcessProducerFieldImpl.fire(beanManager, (ProducerField<?, ?>) bean); } else if (bean instanceof ProducerMethod<?, ?>) { ProcessProducerMethodImpl.fire(beanManager, (ProducerMethod<?, ?>) bean); } else { if (isProcessSynthethicBeanObserved()) { ProcessSynthethicBeanImpl.fire(beanManager, bean, extension); } ProcessBeanImpl.fire(beanManager, bean); } } }

Target:
public void fireProcessBean(BeanManagerImpl beanManager, Bean<?> bean, Extension extension) { if (isProcessBeanObserved()) { if (bean instanceof ManagedBean<?>) { ProcessManagedBeanImpl.fire(beanManager, (ManagedBean<?>) bean); } else if (bean instanceof SessionBean<?>) { ProcessSessionBeanImpl.fire(beanManager, Reflections.<SessionBean<Object>>cast(bean)); } else if (bean instanceof ProducerField<?, ?>) { ProcessProducerFieldImpl.fire(beanManager, (ProducerField<?, ?>) bean); } else if (bean instanceof ProducerMethod<?, ?>) { ProcessProducerMethodImpl.fire(beanManager, (ProducerMethod<?, ?>) bean); } else { if (extension != null) { ProcessSynthethicBeanImpl.fire(beanManager, bean, extension); } ProcessBeanImpl.fire(beanManager, bean); } } }
Source:
protected void createUniqueConstraintsIfMissing(DatastoreProvider provider, List<UniqueConstraintDetails> constraints) { List<Statement> statements = new ArrayList<>(); for ( UniqueConstraintDetails constraint : constraints ) { log.tracef( "Creating unique constraint for nodes labeled as %1$s on property %2$s", constraint.getLabel(), constraint.getProperty() ); StringBuilder queryBuilder = new StringBuilder( "CREATE CONSTRAINT ON (n:" ); escapeIdentifier( queryBuilder, constraint.getLabel().name() ); queryBuilder.append( ") ASSERT n." ); escapeIdentifier( queryBuilder, constraint.getProperty() ); queryBuilder.append( " IS UNIQUE" ); statements.add( new Statement( queryBuilder.toString() ) ); } run( provider, statements ); }

Target:
protected void createUniqueConstraintsIfMissing(DatastoreProvider provider, List<UniqueConstraintDetails> constraints) { List<Statement> statements = new ArrayList<>(); for ( UniqueConstraintDetails constraint : constraints ) { log.tracef( "Creating unique constraint for nodes labeled as %1$s on property %2$s", constraint.getLabel(), constraint.getProperty() ); statements.add( new Statement( constraint.asCypherQuery() ) ); } run( provider, statements ); }
Source:
private static byte[] qrCodePNGBytes(String uri) { Writer qrWriter = new QRCodeWriter(); BitMatrix matrix; try { matrix = qrWriter.encode(uri, com.google.zxing.BarcodeFormat.QR_CODE, 320, 240); } catch (WriterException e) { throw new RuntimeException(e); } ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { MatrixToImageWriter.writeToStream(matrix, "PNG", stream); } catch (IOException e) { throw new RuntimeException(e); } return stream.toByteArray(); }

Target:
private static byte[] qrCodePNGBytes(String uri) { Writer qrWriter = new QRCodeWriter(); BitMatrix matrix; try { matrix = qrWriter.encode(uri, BarcodeFormat.QR_CODE, 320, 240); } catch (WriterException e) { throw new RuntimeException(e); } ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { MatrixToImageWriter.writeToStream(matrix, "PNG", stream); } catch (IOException e) { throw new RuntimeException(e); } return stream.toByteArray(); }
Source:
public void declareOutputFields(OutputFieldsDeclarer declarer) { if (modelProcessor == null) { throw new RuntimeException("modelProcessor cannot be null"); } for (org.apache.streamline.streams.layout.component.Stream stream : modelProcessor.getOutputStreams()) { declarer.declareStream(stream.getId(), new Fields(StreamlineEvent.STREAMLINE_EVENT)); } }

Target:
public void declareOutputFields(OutputFieldsDeclarer declarer) { for (Stream stream : modelProcessor.getOutputStreams()) { declarer.declareStream(stream.getId(), new Fields(StreamlineEvent.STREAMLINE_EVENT)); } }
Source:
public void postContent(@NonNull TaskRepository repository, @NonNull ITask task, @NonNull AbstractTaskAttachmentSource source, @Nullable String comment, @Nullable TaskAttribute attachmentAttribute, @Nullable IProgressMonitor monitor) throws CoreException { try { monitor = Policy.monitorFor(monitor); monitor.beginTask("addAttachment Data", IProgressMonitor.UNKNOWN); BugzillaRestClient client = connector.getClient(repository); try { IOperationMonitor progress = OperationUtil.convert(monitor, "get Attachment Data", 3); progress.addFlag(OperationFlag.BACKGROUND); client.addAttachment(task.getTaskId(), comment, source, attachmentAttribute, progress); } catch (BugzillaRestException e) { throw new CoreException(new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, 2, "Error add attachment data.\n\n" + e.getMessage(), e)); } } finally { monitor.done(); } }

Target:
public void postContent(@NonNull TaskRepository repository, @NonNull ITask task, @NonNull AbstractTaskAttachmentSource source, @Nullable String comment, @Nullable TaskAttribute attachmentAttribute, @Nullable IProgressMonitor monitor) throws CoreException { try { monitor = Policy.monitorFor(monitor); monitor.beginTask("addAttachment Data", IProgressMonitor.UNKNOWN); BugzillaRestClient client = connector.getClient(repository); try { IOperationMonitor progress = OperationUtil.convert(monitor, "get Attachment Data", 3); client.addAttachment(task.getTaskId(), comment, source, attachmentAttribute, progress); } catch (BugzillaRestException e) { throw new CoreException(new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, 2, "Error add attachment data.\n\n" + e.getMessage(), e)); } } finally { monitor.done(); } }
Source:
private Image loadImage() { String b64 = getBASE64Image(); if(b64 != null) { BufferedImage newImage = null; ByteArrayInputStream bais = null; try { bais = new ByteArrayInputStream( Base64.getDecoder().decode(b64.getBytes())); newImage = ImageIO.read(bais); } catch (Throwable ex) { ex.printStackTrace(); } return newImage; } else{ return null; } }

Target:
private Image loadImage() { String b64 = getBASE64Image(); if (b64 != null) { BufferedImage newImage = null; try (ByteArrayInputStream bais = new ByteArrayInputStream( Base64.getDecoder().decode(b64.getBytes()))) { newImage = ImageIO.read(bais); } catch (Exception ex) { MegaMek.getLogger().error(this, ex); } return newImage; } else { return null; } }
Source:
public void searchChargesByPartialCardHolderNameMatch() { Long chargeId = 12L; TestCharge testCharge = DatabaseFixtures .withDatabaseTestHelper(databaseTestHelper) .aTestCharge() .withTestAccount(defaultTestAccount) .withCardDetails(defaultTestCardDetails.withChargeId(chargeId)) .withChargeId(chargeId) .insert(); ChargeSearchParams params = new ChargeSearchParams() .withCardHolderNameLike(CardHolderName.of("pay")); List<ChargeEntity> charges = chargeDao.findAllBy(params); assertThat(charges.size(), is(1)); assertCharge("visa", testCharge, charges.get(0)); }

Target:
public void searchChargesByPartialCardHolderNameMatch() { String cardHolderName = "Mr. McPayment"; Long chargeId = 12L; TestCharge testCharge = DatabaseFixtures .withDatabaseTestHelper(databaseTestHelper) .aTestCharge() .withTestAccount(defaultTestAccount) .withCardDetails(defaultTestCardDetails .withChargeId(chargeId) .withCardHolderName(cardHolderName)) .withChargeId(chargeId) .insert(); ChargeSearchParams params = new ChargeSearchParams() .withCardHolderNameLike(CardHolderName.of("pay")); List<ChargeEntity> charges = chargeDao.findAllBy(params); assertThat(charges.size(), is(1)); ChargeEntity charge = charges.get(0); assertCharge("visa", testCharge, charge); assertThat(charge.getCardDetails().getCardHolderName(), is(cardHolderName)); assertThat(charge.getCardDetails().getLastDigitsCardNumber(), is(testCharge.cardDetails.getLastDigitsCardNumber())); }
Source:
public boolean isExcluded(@NonNull SCMSourceRequest request, @NonNull SCMHead head) { if (head instanceof BranchSCMHead && request instanceof GitHubSCMSourceRequest) { for (GHPullRequest p : ((GitHubSCMSourceRequest) request).getPullRequests()) { GHRepository headRepo = p.getHead().getRepository(); if (headRepo != null && p.getBase().getRepository().getFullName().equalsIgnoreCase(headRepo.getFullName()) && p.getHead().getRef().equals(head.getName())) { LOGGER.log(Level.WARNING, "Ignoring because " + "current strategy excludes branches that ARE also filed as a pull request" , new Object[]{head.toString()}); return true; } } } return false; }

Target:
public boolean isExcluded(@NonNull SCMSourceRequest request, @NonNull SCMHead head) { if (head instanceof BranchSCMHead && request instanceof GitHubSCMSourceRequest) { for (GHPullRequest p : ((GitHubSCMSourceRequest) request).getPullRequests()) { GHRepository headRepo = p.getHead().getRepository(); if (headRepo != null && p.getBase().getRepository().getFullName().equalsIgnoreCase(headRepo.getFullName()) && p.getHead().getRef().equals(head.getName())) { request.listener().getLogger().format( "Ignoring %s because current strategy excludes branches " + "that ARE also filed as a pull request%n" , head.toString()); return true; } } } return false; }
Source:
public PartPresenter getPartByPath(Path path) { for (TabItem tab : parts.keySet()) { if (((EditorTab)tab).getFile().getLocation().equals(path)) { return parts.get(tab); } } return null; }

Target:
public PartPresenter getPartByPath(Path path) { for (TabItem tab : parts.keySet()) { EditorTab editorTab = (EditorTab)tab; Path currentPath = editorTab.getFile().getLocation(); if (currentPath.equals(path)) { return parts.get(tab); } } return null; }
Source:
public void destroyNode(String id) { try { suspendNode(id); serverStopped.apply(id); } catch (Exception e) { e.printStackTrace(); } api.getVirtualServerApi().destroy(id); String systemId = toSystemId.apply(id); systemNormal.apply(systemId); }

Target:
public void destroyNode(String id) { suspendNode(id); serverStopped.apply(id); api.getVirtualServerApi().destroy(id); String systemId = toSystemId.apply(id); systemNormal.apply(systemId); }
Source:
private void setCommonTaskMembers(AbstractTask task, CRTask crTask) { CRTask crTaskOnCancel = crTask.getOnCancel(); if(crTaskOnCancel != null) task.setCancelTask(toAbstractTask(crTaskOnCancel)); else task.setOnCancelConfig(OnCancelConfig.killAllChildProcess()); task.runIfConfigs = toRunIfConfigs(crTask.getRunIf()); }

Target:
private void setCommonTaskMembers(AbstractTask task, CRTask crTask) { CRTask crTaskOnCancel = crTask.getOnCancel(); if(crTaskOnCancel != null) task.setCancelTask(toAbstractTask(crTaskOnCancel)); task.runIfConfigs = toRunIfConfigs(crTask.getRunIf()); }
Source:
public void applicationTheme_importCSS_isUsed() { open(); checkLogsForErrors(); Assert.assertEquals("Imported FontAwesome css file should be applied.", "\"Font Awesome 5 Brands\"", $(SpanElement.class).id(FONTAWESOME_ID) .getCssValue("font-family")); }

Target:
public void applicationTheme_importCSS_isUsed() { open(); checkLogsForErrors(); Assert.assertEquals( "Imported FontAwesome css file should be applied.", "\"Font Awesome 5 Free\"", $(SpanElement.class).id(FONTAWESOME_ID) .getCssValue("font-family")); String iconUnicode = getCssPseudoElementValue(FONTAWESOME_ID, "::before"); Assert.assertEquals( "Font-Icon from FontAwesome css file should be applied.", "\"\uf0f4\"", iconUnicode); getDriver().get(getRootURL() + "/path/VAADIN/static/@fortawesome/fontawesome-free/webfonts/fa-solid-900.svg"); Assert.assertFalse("Font resource should be available", driver.getPageSource().contains("HTTP ERROR 404 Not Found")); }
Source:
public void testBatchObjects() throws Exception { Repository repo = repoProvider.createGeogig("repo1", null); repoProvider.getTestRepository("repo1").initializeRpository(); new TestData(repo).init("testGeoGig", "geogig@geogig.org").loadDefaultData(); Iterator<RevCommit> masterCommits = repo.command(LogOp.class).call(); repo.command(CheckoutOp.class).setSource("branch1").call(); Iterator<RevCommit> branch1Commits = repo.command(LogOp.class).call(); JsonObject json = new JsonObject(); JsonArray want = new JsonArray(); json.add("want", want); JsonArray have = new JsonArray(); json.add("have", have); while (masterCommits.hasNext()) { want.add(masterCommits.next().getId().toString()); } while (branch1Commits.hasNext()) { have.add(branch1Commits.next().getId().toString()); } MockHttpServletRequestBuilder post = MockMvcRequestBuilders.post("/repos/repo1/repo/batchobjects").contentType( MediaType.APPLICATION_JSON).content(getBytes(json)); perform(post).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM)); repo.close(); }

Target:
public void testBatchObjects() throws Exception { Repository repo = repoProvider.createGeogig("repo1", null); repoProvider.getTestRepository("repo1").initializeRpository(); new TestData(repo).init("testGeoGig", "geogig@geogig.org").loadDefaultData(); Iterator<RevCommit> masterCommits = repo.command(LogOp.class).call(); repo.command(CheckoutOp.class).setSource("branch1").call(); Iterator<RevCommit> branch1Commits = repo.command(LogOp.class).call(); JsonObject json = new JsonObject(); JsonArray want = new JsonArray(); json.add("want", want); JsonArray have = new JsonArray(); json.add("have", have); while (masterCommits.hasNext()) { want.add(masterCommits.next().getId().toString()); } while (branch1Commits.hasNext()) { have.add(branch1Commits.next().getId().toString()); } MockHttpServletRequestBuilder post = MockMvcRequestBuilders.post("/repos/repo1/repo/batchobjects").contentType( MediaType.APPLICATION_JSON).content(getBytes(json)); byte[] content = perform(post).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM)) .andReturn().getResponse().getContentAsByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(content); final ObjectSerializingFactory serialFac = DataStreamSerializationFactoryV1.INSTANCE; final int expectedNumRevObjects = 14; int actualNumRevObjects = 0; while (bais.available() > 0) { byte[] rawId = new byte[ObjectId.NUM_BYTES]; bais.read(rawId); ObjectId oid = ObjectId.createNoClone(rawId); serialFac.read(oid, bais); ++actualNumRevObjects; } assertEquals("Incorrect number of RevObjects in BatchObjects response", expectedNumRevObjects, actualNumRevObjects); repo.close(); }
Source:
public final void setOutputStream(OutputStream outputStream) { final OutputStreamWriter osw = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8); writer = new PrintWriter(osw); }

Target:
private void setOutputStream(OutputStream outputStream) { final OutputStreamWriter osw = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8); writer = new PrintWriter(osw); }