auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void createStreamClient() throws IOException { if (streamClient == null) { RestStreamClient.Builder builder = RestStreamClient.builder(host, port); builder.ssl(sslEnabled); if (authToken != null && !authToken.equals("")) { builder.authToken(authToken); } builder.writerPoolSize(writerPoolSize); builder.version(version); try { streamClient = builder.build(); streamClient.create(streamName); } catch (IOException e) { closeClientQuietly(); throw new IOException("Can not create client stream by name: " + streamName, e); } } try { if (writer == null) { writer = streamClient.createWriter(streamName); } } catch (IOException e) { closeWriterQuietly(); throw new IOException("Can not create stream writer by name: " + streamName, e); } }

Target:
private void createStreamClient() throws IOException { if (streamClient == null) { RestStreamClient.Builder builder = RestStreamClient.builder(host, port); builder.ssl(sslEnabled); builder.writerPoolSize(writerPoolSize); builder.version(version); streamClient = builder.build(); try { if (writer == null) { writer = streamClient.createWriter(streamName); } } catch (Throwable t) { closeWriterQuietly(); throw new IOException("Can not create stream writer by name: " + streamName, t); } } }
Source:
@Override public Class<${componentNameClass}Properties> getPropertyClass() { return ${componentNameClass}Properties.class; }

Target:
public Class<${componentNameClass}Properties> getPropertyClass() { return ${componentNameClass}Properties.class; }
Source:
private UpdateResult updateInternal(final int type, final Bson filter, final Bson update, @Nullable final UpdateOptions options) { AtomicReference<UpdateResult> success = new AtomicReference<>(null); AtomicReference<ObjectServerError> error = new AtomicReference<>(null); OsJNIResultCallback<UpdateResult> callback = new OsJNIResultCallback<UpdateResult>(success, error) { @Override protected UpdateResult mapSuccess(Object result) { BsonArray array = JniBsonProtocol.decode((String) result, BsonArray.class, codecRegistry); long matchedCount = array.get(0).asInt32().getValue(); long modifiedCount = array.get(1).asInt32().getValue(); BsonValue upsertedId = array.get(2); if (upsertedId instanceof BsonNull) { upsertedId = null; } return new UpdateResult(matchedCount, modifiedCount, upsertedId); } }; String jsonFilter = JniBsonProtocol.encode(filter, codecRegistry); String jsonUpdate = JniBsonProtocol.encode(update, codecRegistry); switch (type) { case UPDATE_ONE: case UPDATE_MANY: nativeUpdate(type, nativePtr, jsonFilter, jsonUpdate, false, callback); break; case UPDATE_ONE_WITH_OPTIONS: case UPDATE_MANY_WITH_OPTIONS: if (options == null) { throw new IllegalArgumentException("UpdateOptions must not be null."); } nativeUpdate(type, nativePtr, jsonFilter, jsonUpdate, options.isUpsert(), callback); break; default: throw new IllegalArgumentException("Invalid update type: " + type); } return ResultHandler.handleResult(success, error); }

Target:
private UpdateResult updateInternal(final int type, final Bson filter, final Bson update, @Nullable final UpdateOptions options) { AtomicReference<UpdateResult> success = new AtomicReference<>(null); AtomicReference<ObjectServerError> error = new AtomicReference<>(null); OsJNIResultCallback<UpdateResult> callback = new OsJNIResultCallback<UpdateResult>(success, error) { @Override protected UpdateResult mapSuccess(Object result) { BsonArray array = JniBsonProtocol.decode((String) result, BsonArray.class, codecRegistry); long matchedCount = array.get(0).asInt32().getValue(); long modifiedCount = array.get(1).asInt32().getValue(); BsonValue upsertedId = array.get(2); if (upsertedId instanceof BsonNull) { upsertedId = null; } return new UpdateResult(matchedCount, modifiedCount, upsertedId); } }; final String jsonFilter = JniBsonProtocol.encode(filter, codecRegistry); final String jsonUpdate = JniBsonProtocol.encode(update, codecRegistry); switch (type) { case UPDATE_ONE: case UPDATE_MANY: nativeUpdate(type, nativePtr, jsonFilter, jsonUpdate, false, callback); break; case UPDATE_ONE_WITH_OPTIONS: case UPDATE_MANY_WITH_OPTIONS: Util.checkNull(options, "options"); nativeUpdate(type, nativePtr, jsonFilter, jsonUpdate, options.isUpsert(), callback); break; default: throw new IllegalArgumentException("Invalid update type: " + type); } return ResultHandler.handleResult(success, error); }
Source:
public static boolean migrateFixtureDbBytes(SQLiteDatabase db, Context c) { CommCareApplication._().setCustomServiceBindTimeout(60 * 5 * 1000); long start = System.currentTimeMillis(); db.beginTransaction(); ConcreteAndroidDbHelper helper = new ConcreteAndroidDbHelper(c, db); Cursor cur = null; DataInputStream fixtureByteStream = null; try { SqlStorage<Persistable> userFixtureStorage = new SqlStorage<Persistable>("fixture", FormInstance.class, helper); cur = db.query("fixture", new String[]{DbUtil.ID_COL}, null, null, null, null, null); Vector<Integer> ids = SqlStorage.fillIdWindow(cur, DbUtil.ID_COL); for (Integer id : ids) { FormInstance fixture = new FormInstance(); fixtureByteStream = new DataInputStream(new ByteArrayInputStream(userFixtureStorage.readBytes(id))); fixture.migrateSerialization(fixtureByteStream, helper.getPrototypeFactory()); userFixtureStorage.update(id, fixture); } db.setTransactionSuccessful(); return true; } catch (Exception e) { db.setTransactionSuccessful(); Logger.log(AndroidLogger.SOFT_ASSERT, "fixture serialization db migration failed"); Logger.exception(e); return false; } finally { if (fixtureByteStream != null) { try { fixtureByteStream.close(); } catch (Exception e) { } } if (cur != null) { cur.close(); } db.endTransaction(); long elapse = System.currentTimeMillis() - start; Log.d(TAG, "Serialized fixture update complete in " + elapse + "ms"); } }

Target:
public static boolean migrateFixtureDbBytes(SQLiteDatabase db, Context c) { CommCareApplication._().setCustomServiceBindTimeout(60 * 5 * 1000); long start = System.currentTimeMillis(); db.beginTransaction(); ConcreteAndroidDbHelper helper = new ConcreteAndroidDbHelper(c, db); DataInputStream fixtureByteStream = null; try { SqlStorage<Persistable> userFixtureStorage = new SqlStorage<Persistable>("fixture", FormInstance.class, helper); for (SqlStorageIterator i = userFixtureStorage.iterate(false); i.hasMore(); ) { int id = i.nextID(); FormInstance fixture = new FormInstance(); fixtureByteStream = new DataInputStream(new ByteArrayInputStream(userFixtureStorage.readBytes(id))); fixture.migrateSerialization(fixtureByteStream, helper.getPrototypeFactory()); userFixtureStorage.update(id, fixture); } db.setTransactionSuccessful(); return true; } catch (Exception e) { db.setTransactionSuccessful(); Logger.log(AndroidLogger.SOFT_ASSERT, "fixture serialization db migration failed"); Logger.exception(e); return true; } finally { if (fixtureByteStream != null) { try { fixtureByteStream.close(); } catch (Exception e) { } } db.endTransaction(); long elapse = System.currentTimeMillis() - start; Log.d(TAG, "Serialized fixture update complete in " + elapse + "ms"); } }
Source:
protected static void parseGene(String line, ArrayList<Gene> genes, Map<Integer, Gene> geneStart, Map<Integer, Gene> geneEnd, Map<String, Label> geneMap) { String[] tokens = line.split(" "); Gene gene = new Gene(tokens[1], Integer.parseInt(tokens[4]), Integer.parseInt(tokens[5])); genes.add(gene); geneMap.put(gene.getName(), new GeneLabel(gene.getName())); geneMap.put(PREFIX_GENE_START + gene.getName(), new StartGeneLabel(gene.getName(), gene.getStart())); geneMap.put(PREFIX_GENE_END + gene.getName(), new EndGeneLabel(gene.getName(), gene.getEnd())); geneStart.put(Integer.parseInt(tokens[4]), gene); geneEnd.put(Integer.parseInt(tokens[5]), gene); }

Target:
protected static void parseGene(String line, ArrayList<Gene> genes, Map<Integer, Gene> geneStart, Map<Integer, Gene> geneEnd, Map<String, Label> geneMap) { String[] tokens = line.split(TAB); if (GENE_TYPE.equals(tokens[GENE_TYPE_POSITION])) { String[] attributes = tokens[GENE_ATTRIBUTES_POSITION].split(GENE_ATTRIBUTE_DELIMITER); Gene gene = new Gene( attributes[GENE_ATTRIBUTE_DISPLAY_NAME_POSITION] .replace(GENE_DISPLAY_NAME_IDENTIFIER, ""), Integer.parseInt(tokens[GENE_REF_START_POSITION]), Integer.parseInt(tokens[GENE_REF_END_POSITION]) ); genes.add(gene); geneMap.put(gene.getName(), new GeneLabel(gene.getName())); geneMap.put(PREFIX_GENE_START + gene.getName(), new StartGeneLabel(gene.getName(), gene.getStart())); geneMap.put(PREFIX_GENE_END + gene.getName(), new EndGeneLabel(gene.getName(), gene.getEnd())); geneStart.put(Integer.parseInt(tokens[GENE_REF_START_POSITION]), gene); geneEnd.put(Integer.parseInt(tokens[GENE_REF_END_POSITION]), gene); } }
Source:
protected DataStreamSink(DataStream<T> inputStream, StreamSink<T> operator) { this.transformation = new SinkTransformation<>( inputStream.getTransformation(), "Unnamed", operator, inputStream.getExecutionEnvironment().getParallelism()); }

Target:
protected DataStreamSink(DataStream<T> inputStream, StreamSink<T> operator) { this.transformation = new SinkTransformation<T>(inputStream.getTransformation(), "Unnamed", operator, inputStream.getExecutionEnvironment().getParallelism()); }
Source:
protected LoadingLookupFactory( DataFetcher dataFetcher, LoadingCache<String, String> loadingCache, LoadingCache<String, List<String>> reverseLoadingCache, LoadingLookup loadingLookup ) { this.dataFetcher = dataFetcher; this.loadingCache = loadingCache; this.reverseLoadingCache = reverseLoadingCache; this.loadingLookup = loadingLookup; }

Target:
protected LoadingLookupFactory( DataFetcher dataFetcher, LoadingCache<String, String> loadingCache, LoadingCache<String, List<String>> reverseLoadingCache, LoadingLookup loadingLookup ) { this.dataFetcher = Preconditions.checkNotNull(dataFetcher); this.loadingCache = Preconditions.checkNotNull(loadingCache); this.reverseLoadingCache = Preconditions.checkNotNull(reverseLoadingCache); this.loadingLookup = loadingLookup; }
Source:
private void checkVideoStatus(VideoBlockModel unit) { try { final DownloadEntry entry = unit.getDownloadEntry(environment.getStorage()); if ( entry == null ) return; if ( entry.isDownload() ){ if ( entry.isVideoForWebOnly ){ Toast.makeText(getActivity(), getString(R.string.video_only_on_web_short), Toast.LENGTH_SHORT).show(); return; } if(!entry.isDownloaded()){ IDialogCallback dialogCallback = new IDialogCallback() { @Override public void onPositiveClicked() { startOnlinePlay(entry); } @Override public void onNegativeClicked() { ((CourseUnitNavigationActivity) getActivity()).showInfoMessage(getString(R.string.wifi_off_message)); notifyAdapter(); } }; MediaConsentUtils.consentToMediaPlayback(getActivity(), dialogCallback, environment.getConfig()); }else{ if ( AppConstants.offline_flag ){ ((CourseBaseActivity) getActivity()) .showOfflineAccessMessage(); } else { startOnlinePlay(entry); } } } } catch (Exception e) { logger.error(e); } }

Target:
private void checkVideoStatus(VideoBlockModel unit) { try { final DownloadEntry entry = unit.getDownloadEntry(environment.getStorage()); if ( entry == null ) return; if ( entry.isDownload() ){ if ( entry.isVideoForWebOnly ){ Toast.makeText(getActivity(), getString(R.string.video_only_on_web_short), Toast.LENGTH_SHORT).show(); return; } if(!entry.isDownloaded()){ IDialogCallback dialogCallback = new IDialogCallback() { @Override public void onPositiveClicked() { startOnlinePlay(entry); } @Override public void onNegativeClicked() { ((BaseFragmentActivity) getActivity()).showInfoMessage(getString(R.string.wifi_off_message)); notifyAdapter(); } }; MediaConsentUtils.consentToMediaPlayback(getActivity(), dialogCallback, environment.getConfig()); }else{ if ( AppConstants.offline_flag ){ ((CourseBaseActivity) getActivity()) .showOfflineAccessMessage(); } else { startOnlinePlay(entry); } } } } catch (Exception e) { logger.error(e); } }
Source:
private static void exitMethod(JoinPoint joinPoint, Object result, long lengthMillis) { if (android.os.Build.VERSION.SDK_INT >= 18) { Trace.endSection(); } Signature signature = joinPoint.getSignature(); Class<?> cls = signature.getDeclaringType(); String methodName = signature.getName(); boolean hasReturnType = signature instanceof MethodSignature && ((MethodSignature) signature).getReturnType() != void.class; StringBuilder builder = new StringBuilder("\u21E0 ") .append(methodName) .append(" [") .append(lengthMillis) .append("ms]"); if (hasReturnType) { builder.append(" = "); builder.append(Strings.toString(result)); } Log.v(asTag(cls), builder.toString()); }

Target:
private static void exitMethod(JoinPoint joinPoint, Object result, long lengthMillis) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Trace.endSection(); } Signature signature = joinPoint.getSignature(); Class<?> cls = signature.getDeclaringType(); String methodName = signature.getName(); boolean hasReturnType = signature instanceof MethodSignature && ((MethodSignature) signature).getReturnType() != void.class; StringBuilder builder = new StringBuilder("\u21E0 ") .append(methodName) .append(" [") .append(lengthMillis) .append("ms]"); if (hasReturnType) { builder.append(" = "); builder.append(Strings.toString(result)); } Log.v(asTag(cls), builder.toString()); }
Source:
public boolean showSavingProgressDialogIfNeeded() { if (!isAdded()) { return false; } if (!mHtmlModeEnabled) return false; if (mSavingContentProgressDialog != null && mSavingContentProgressDialog.isShowing()) { return true; } mSavingContentProgressDialog = new ProgressDialog(getActivity()); mSavingContentProgressDialog.setCancelable(false); mSavingContentProgressDialog.setIndeterminate(true); mSavingContentProgressDialog.setMessage(getActivity().getString(R.string.long_post_dlg_saving)); mSavingContentProgressDialog.show(); return true; }

Target:
public boolean showSavingProgressDialogIfNeeded() { if (!isAdded()) { return false; } if (!mHtmlModeEnabled) return false; if (mSavingContentProgressDialog != null && mSavingContentProgressDialog.isShowing()) { return true; } if (mSavingContentProgressDialog == null) { mSavingContentProgressDialog = new ProgressDialog(getActivity()); mSavingContentProgressDialog.setCancelable(false); mSavingContentProgressDialog.setIndeterminate(true); mSavingContentProgressDialog.setMessage(getActivity().getString(R.string.long_post_dlg_saving)); } mSavingContentProgressDialog.show(); return true; }
Source:
void stopRegularScan(ScanClient client) { if (client == null) { return; } for (ScanClient c : mRegularScanClients) { if (c.scannerId != client.scannerId) { continue; } client = c; int deliveryMode = getDeliveryMode(client); if (deliveryMode == DELIVERY_MODE_ON_FOUND_LOST) { for (ScanFilter filter : client.filters) { int entriesToFree = getNumOfTrackingAdvertisements(client.settings); if (!manageAllocationOfTrackingAdvertisement(entriesToFree, false)) { Log.e(TAG, "Error freeing for onfound/onlost filter resources " + entriesToFree); try { mService.onScanManagerErrorCallback(client.scannerId, ScanCallback.SCAN_FAILED_INTERNAL_ERROR); } catch (RemoteException e) { Log.e(TAG, "failed on onScanManagerCallback at freeing", e); } } } } break; } mRegularScanClients.remove(client); if (numRegularScanClients() == 0) { if (DBG) { Log.d(TAG, "stop scan"); } gattClientScanNative(false); } removeScanFilters(client.scannerId); }

Target:
void stopRegularScan(ScanClient client) { if (client == null) { return; } int deliveryMode = getDeliveryMode(client); if (deliveryMode == DELIVERY_MODE_ON_FOUND_LOST) { for (ScanFilter filter : client.filters) { int entriesToFree = getNumOfTrackingAdvertisements(client.settings); if (!manageAllocationOfTrackingAdvertisement(entriesToFree, false)) { Log.e(TAG, "Error freeing for onfound/onlost filter resources " + entriesToFree); try { mService.onScanManagerErrorCallback(client.scannerId, ScanCallback.SCAN_FAILED_INTERNAL_ERROR); } catch (RemoteException e) { Log.e(TAG, "failed on onScanManagerCallback at freeing", e); } } } } mRegularScanClients.remove(client); if (numRegularScanClients() == 0) { if (DBG) { Log.d(TAG, "stop scan"); } gattClientScanNative(false); } removeScanFilters(client.scannerId); }
Source:
public VariantEntity convert(DBObject dbObject) { logger.warn("INSIDE MongoDBObjectToVariantEntityConverter.convert"); DBObjectToVariantConverter converter = new DBObjectToVariantConverter( new DBObjectToVariantSourceEntryConverter(VariantStorageManager.IncludeSrc.NO), new DBObjectToVariantStatsConverter() ); return new VariantEntity(converter.convertToDataModelType(dbObject)); }

Target:
public VariantEntity convert(DBObject dbObject) { DBObjectToVariantConverter converter = new DBObjectToVariantConverter( new DBObjectToVariantSourceEntryConverter(VariantStorageManager.IncludeSrc.FIRST_8_COLUMNS), new DBObjectToVariantStatsConverter() ); return new VariantEntity(converter.convertToDataModelType(dbObject)); }
Source:
public void doQuery(List<ITmfStateInterval> currentStateInfo, long t) throws TimeRangeException, StateSystemDisposedException { if (t <= super.getEndTime()) { super.doQuery(currentStateInfo, t); } else { checkValidTime(t); } if (isFinishedBuilding()) { return; } for (int i = 0; i < currentStateInfo.size(); i++) { if (currentStateInfo.get(i) == null) { ITmfStateInterval interval = doSingularQuery(t, i); currentStateInfo.set(i, interval); } } }

Target:
public void doQuery(List<ITmfStateInterval> currentStateInfo, long t) throws TimeRangeException, StateSystemDisposedException { if (t <= getSHT().getTreeEnd()) { super.doQuery(currentStateInfo, t); } else { checkValidTime(t); } if (isFinishedBuilding()) { return; } for (int i = 0; i < currentStateInfo.size(); i++) { if (currentStateInfo.get(i) == null) { ITmfStateInterval interval = doSingularQuery(t, i); currentStateInfo.set(i, interval); } } }
Source:
public void testInferredGenericTypeInfo() throws Exception { byte[] bytes = "[ {\"name\" : \"foo\" } ]".getBytes(); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("application/json"); messageProperties .setInferredArgumentType(Bar.class.getMethod("setFoos", List.class).getGenericParameterTypes()[0]); Message message = new Message(bytes, messageProperties); Object foo = this.converter.fromMessage(message); assertThat(foo, instanceOf(List.class)); assertThat(((List<?>) foo).get(0), instanceOf(Foo.class)); }

Target:
public void testInferredGenericTypeInfo() throws Exception { byte[] bytes = "[ {\"name\" : \"foo\" } ]".getBytes(); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("application/json"); messageProperties.setInferredArgumentType((new ParameterizedTypeReference<List<Foo>>() {}).getType()); Message message = new Message(bytes, messageProperties); Object foo = this.converter.fromMessage(message); assertThat(foo, instanceOf(List.class)); assertThat(((List<?>) foo).get(0), instanceOf(Foo.class)); }
Source:
private boolean isAndroidAppInstalled(String uri) { PackageManager pm = getPackageManager(); boolean app_installed = false; try { pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES); app_installed = true; } catch (PackageManager.NameNotFoundException e) { Log.i("debug", "App not installed on Android device"); app_installed = false; } return app_installed; }

Target:
private boolean isAndroidAppInstalled(String uri) { PackageManager mPackageManager = getPackageManager(); boolean mAppInstalled = false; try { mPackageManager.getPackageInfo(uri, PackageManager.GET_ACTIVITIES); mAppInstalled = true; } catch (PackageManager.NameNotFoundException e) { Log.e(Constants.TAG, "App not installed on Android device"); mAppInstalled = false; } return mAppInstalled; }
Source:
private void prefetch(Topic topic) { switch (topic.getContentType()) { case AVRO: avroSchemaRepo.getSchema(topic); break; case JSON: jsonSchemaRepo.getSchema(topic); break; default: LOGGER.warn("Schema prefetch failed for topic {}: unknown content type {}", topic.getQualifiedName(), topic.getContentType()); break; } }

Target:
private void prefetch(Topic topic) { schemaRepositories.stream() .filter(repo -> repo.canService(topic.getContentType())) .forEach(repo -> repo.getSchema(topic)); }
Source:
public MISTCepStatefulQuery build() { if (cepInput == null || initialState == null || cepStatefulRules.size() == 0 || cepFinalStates.size() == 0) { throw new IllegalStateException("One of cep input, initial state, rules, or final states are not set!"); } return new MISTCepStatefulQuery(cepInput, initialState, cepStatefulRules, cepFinalStates); }

Target:
public MISTCepStatefulQuery build() { if (cepInput == null || initialState == null || cepStatefulRules.size() == 0 || cepFinalState.size() == 0) { throw new IllegalStateException("One of cep input, initial state, rules, or final states are not set!"); } return new MISTCepStatefulQuery(cepInput, initialState, cepStatefulRules, cepFinalState); }
Source:
public AggregatorFactory getCombiningFactory() { return new DoubleLastAggregatorFactory(name, name) { @Override public Aggregator factorize(ColumnSelectorFactory metricFactory, ColumnValueSelector selector) { return new DoubleLastAggregator(null, null) { @Override public void aggregate() { SerializablePair<Long, Double> pair = (SerializablePair<Long, Double>) selector.getObject(); if (pair.lhs >= lastTime) { lastTime = pair.lhs; lastValue = pair.rhs; } } }; } @Override public BufferAggregator factorizeBuffered(ColumnSelectorFactory metricFactory, ColumnValueSelector selector) { return new DoubleLastBufferAggregator(null, null) { @Override public void aggregate(ByteBuffer buf, int position) { SerializablePair<Long, Double> pair = (SerializablePair<Long, Double>) selector.getObject(); long lastTime = buf.getLong(position); if (pair.lhs >= lastTime) { buf.putLong(position, pair.lhs); buf.putDouble(position + Double.BYTES, pair.rhs); } } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("selector", selector); } }; } }; }

Target:
public AggregatorFactory getCombiningFactory() { return new DoubleLastAggregatorFactory(name, name) { @Override public Aggregator factorize(ColumnSelectorFactory metricFactory, ColumnValueSelector selector) { return new DoubleLastAggregator(null, null) { @Override public void aggregate() { SerializablePair<Long, Double> pair = (SerializablePair<Long, Double>) selector.getObject(); if (pair.lhs >= lastTime) { lastTime = pair.lhs; lastValue = pair.rhs; } } }; } @Override public BufferAggregator factorizeBuffered(ColumnSelectorFactory metricFactory, ColumnValueSelector selector) { return new DoubleLastBufferAggregator(null, null) { @Override public void aggregate(ByteBuffer buf, int position) { SerializablePair<Long, Double> pair = (SerializablePair<Long, Double>) selector.getObject(); long lastTime = buf.getLong(position); if (pair.lhs >= lastTime) { buf.putLong(position, pair.lhs); buf.putDouble(position + Long.BYTES, pair.rhs); } } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("selector", selector); } }; } }; }
Source:
public Program(byte[] codeHash, byte[] ops, ProgramInvoke programInvoke, Transaction transaction, SystemProperties config) { this.config = config; this.invoke = programInvoke; this.transaction = transaction; this.codeHash = codeHash == null || FastByteComparisons.equal(HashUtil.EMPTY_DATA_HASH, codeHash) ? null : codeHash; this.ops = nullToEmpty(ops); traceListener = new ProgramTraceListener(config.vmTrace()); this.memory = setupProgramListener(new Memory()); this.stack = setupProgramListener(new Stack()); this.originalRepo = programInvoke.getRepository().getSnapshotTo(programInvoke.getRepository().getRoot()); this.storage = setupProgramListener(new Storage(programInvoke)); this.trace = new ProgramTrace(config, programInvoke); this.blockchainConfig = config.getBlockchainConfig().getConfigForBlock(programInvoke.getNumber().longValue()); }

Target:
public Program(byte[] codeHash, byte[] ops, ProgramInvoke programInvoke, Transaction transaction, SystemProperties config) { this.config = config; this.invoke = programInvoke; this.transaction = transaction; this.codeHash = codeHash == null || FastByteComparisons.equal(HashUtil.EMPTY_DATA_HASH, codeHash) ? null : codeHash; this.ops = nullToEmpty(ops); traceListener = new ProgramTraceListener(config.vmTrace()); this.memory = setupProgramListener(new Memory()); this.stack = setupProgramListener(new Stack()); this.originalRepo = programInvoke.getRepository().clone(); this.storage = setupProgramListener(new Storage(programInvoke)); this.trace = new ProgramTrace(config, programInvoke); this.blockchainConfig = config.getBlockchainConfig().getConfigForBlock(programInvoke.getNumber().longValue()); }
Source:
public void testAddNewRelationship_withIndex() throws Exception { final Node diagram = createNode(CaseManagementDiagram.class); final Node start = createNode(StartNoneEvent.class); final Node end = createNode(EndNoneEvent.class); final Node stage = createNode(AdHocSubprocess.class); final Node candidate = createNode(AdHocSubprocess.class); createChildEdge(diagram, start); createChildEdge(diagram, stage); createChildEdge(diagram, end); final Edge edge = createSequenceFlow(start, stage); createSequenceFlow(stage, end); final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(diagram, candidate, OptionalInt.of(1), Optional.of(diagram), originalIndex); command.addNewRelationship(context); assertTrue(command.in.isPresent()); assertEquals(start, command.in.get()); assertTrue(command.out.isPresent()); assertEquals(stage, command.out.get()); assertTrue(command.edge.isPresent()); assertEquals(edge, command.edge.get()); assertEquals(candidate, ((Edge) diagram.getOutEdges().get(1)).getTargetNode()); assertEquals(candidate, ((Edge) start.getOutEdges().get(0)).getTargetNode()); assertEquals(1, stage.getInEdges().stream().filter(sequencePredicate()).count()); assertEquals(candidate, ((List) stage.getInEdges().stream().filter(sequencePredicate()) .map(e -> ((Edge) e).getSourceNode()).collect(Collectors.toList())).get(0)); }

Target:
public void testAddNewRelationship_withIndex() { final Node diagram = createNode(CaseManagementDiagram.class); final Node start = createNode(StartNoneEvent.class); final Node end = createNode(EndNoneEvent.class); final Node stage = createNode(AdHocSubprocess.class); final Node candidate = createNode(AdHocSubprocess.class); createChildEdge(diagram, start); createChildEdge(diagram, stage); createChildEdge(diagram, end); final Edge edge = createSequenceFlow(start, stage); createSequenceFlow(stage, end); final CaseManagementSetChildNodeGraphCommand command = new CaseManagementSetChildNodeGraphCommand(diagram, candidate, OptionalInt.of(1), Optional.of(diagram), originalIndex); command.addNewRelationship(context); assertTrue(command.in.isPresent()); assertEquals(start, command.in.get()); assertTrue(command.out.isPresent()); assertEquals(stage, command.out.get()); assertTrue(command.edge.isPresent()); assertEquals(edge, command.edge.get()); assertEquals(candidate, ((Edge) diagram.getOutEdges().get(1)).getTargetNode()); assertEquals(candidate, ((Edge) start.getOutEdges().get(0)).getTargetNode()); assertEquals(1, stage.getInEdges().stream().filter(sequencePredicate()).count()); assertEquals(candidate, ((List) stage.getInEdges().stream().filter(sequencePredicate()) .map(e -> ((Edge) e).getSourceNode()).collect(Collectors.toList())).get(0)); }
Source:
private static AdvancedInformation executeAut(AutLaunch launch) { AdvancedInformation info = null; try { final GetAdvancedInfo advInfoCmd = TeslaFactory.eINSTANCE .createGetAdvancedInfo(); final Object obj = launch.execute(advInfoCmd); if (obj instanceof AdvancedInformation) info = (AdvancedInformation) obj; } catch (Exception e) { return (AdvancedInformation) RcpttPlugin.createStatus(e); } return info; }

Target:
private static AdvancedInformation executeAut(AutLaunch launch) { AdvancedInformation info = null; try { final GetAdvancedInfo advInfoCmd = TeslaFactory.eINSTANCE .createGetAdvancedInfo(); final Object obj = launch.execute(advInfoCmd); if (obj instanceof AdvancedInformation) info = (AdvancedInformation) obj; } catch (Exception e) { RcpttPlugin.log(e); } return info; }
Source:
protected TransportOptions createTransportOptions(InetAddress host) { return new TransportOptions( TransportOptions.BigtableTransports.HTTP2_NETTY_TLS, host, options.getPort(), SSL_CONTEXT_FACTORY, elg); }

Target:
protected TransportOptions createTransportOptions(InetAddress host) { return new TransportOptions( TransportOptions.BigtableTransports.HTTP2_NETTY_TLS, host, options.getPort(), TransportOptions.SSL_CONTEXT_FACTORY, elg); }
Source:
public static void main(String[] args) throws Exception { SamzaMonitorService monitorService = null; try { SamzaRestConfig config = parseConfig(args); ReadableMetricsRegistry metricsRegistry = new MetricsRegistryMap(); log.info("Creating new SamzaRestService with config: {}", config); MetricsConfig metricsConfig = new MetricsConfig(config); Map<String, MetricsReporter> metricsReporters = MetricsReporterLoader.getMetricsReporters(metricsConfig, Util.getLocalHost().getHostName()); SamzaRestService restService = new SamzaRestService(new Server(config.getPort()), metricsRegistry, metricsReporters, new ServletContextHandler(ServletContextHandler.SESSIONS)); SamzaRestApplication samzaRestApplication = new SamzaRestApplication(config); ServletContainer container = new ServletContainer(samzaRestApplication); restService.addServlet(container, "/*"); monitorService = new SamzaMonitorService(config, metricsRegistry); monitorService.start(); restService.runBlocking(); monitorService.stop(); } catch (Throwable t) { log.error("Exception in main.", t); } finally { if (monitorService != null) { monitorService.stop(); } } }

Target:
public static void main(String[] args) throws Exception { SamzaMonitorService monitorService = null; try { SamzaRestConfig config = parseConfig(args); ReadableMetricsRegistry metricsRegistry = new MetricsRegistryMap(); log.info("Creating new SamzaRestService with config: {}", config); MetricsConfig metricsConfig = new MetricsConfig(config); Map<String, MetricsReporter> metricsReporters = MetricsReporterLoader.getMetricsReporters(metricsConfig, Util.getLocalHost().getHostName()); SamzaRestService restService = new SamzaRestService(new Server(config.getPort()), metricsRegistry, metricsReporters, new ServletContextHandler(ServletContextHandler.SESSIONS)); SamzaRestApplication samzaRestApplication = new SamzaRestApplication(config); ServletContainer container = new ServletContainer(samzaRestApplication); restService.addServlet(container, "/*"); monitorService = new SamzaMonitorService(config, metricsRegistry); monitorService.start(); restService.runBlocking(); } catch (Throwable t) { log.error("Exception in main.", t); } finally { if (monitorService != null) { monitorService.stop(); } } }
Source:
public void stripPrefixIfPresent() throws Exception { Assert.assertEquals("", mS3UnderFileSystem.stripPrefixIfPresent("s3a://" + BUCKET_NAME)); }

Target:
public void stripPrefixIfPresent() throws Exception { Assert.assertEquals("", mS3UnderFileSystem.stripPrefixIfPresent("s3a://" + BUCKET_NAME)); Assert.assertEquals("", mS3UnderFileSystem.stripPrefixIfPresent("s3a://" + BUCKET_NAME + "/")); Assert.assertEquals("test/", mS3UnderFileSystem.stripPrefixIfPresent("test")); Assert.assertEquals("test/", mS3UnderFileSystem.stripPrefixIfPresent("s3a://" + BUCKET_NAME + "/test/")); }
Source:
public void loadAfter(@NonNull final LoadParams<String> params, @NonNull final LoadCallback<String, DataSnapshot> callback) { mLoadingState.postValue(LoadingState.LOADING_MORE); Query mNewQuery = mQuery.startAt(null, params.key).limitToFirst(params.requestedLoadSize + 1); mNewQuery.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { List<DataSnapshot> data = new ArrayList<>(); String lastKey = null; Iterator<DataSnapshot> iterator = dataSnapshot.getChildren().iterator(); if (iterator.hasNext()) iterator.next(); while (iterator.hasNext()) { DataSnapshot snapshot = iterator.next(); data.add(snapshot); } mLoadingState.postValue(LoadingState.LOADED); mRetryRunnable = null; if (data.isEmpty()) mLoadingState.postValue(LoadingState.FINISHED); else { lastKey = getLastPageKey(data); } callback.onResult(data, lastKey); } else { mRetryRunnable = getRetryLoadAfter(params, callback); setDatabaseNotFoundError(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { mRetryRunnable = getRetryLoadAfter(params, callback); setError(databaseError); } }); }

Target:
public void loadAfter(@NonNull final LoadParams<String> params, @NonNull final LoadCallback<String, DataSnapshot> callback) { mLoadingState.postValue(LoadingState.LOADING_MORE); Query mNewQuery = mQuery.startAt(null, params.key).limitToFirst(params.requestedLoadSize + 1); mNewQuery.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { List<DataSnapshot> data = new ArrayList<>(); String lastKey = null; Iterator<DataSnapshot> iterator = dataSnapshot.getChildren().iterator(); if (iterator.hasNext()) { iterator.next(); } while (iterator.hasNext()) { DataSnapshot snapshot = iterator.next(); data.add(snapshot); } mLoadingState.postValue(LoadingState.LOADED); mRetryRunnable = null; if (data.isEmpty()) mLoadingState.postValue(LoadingState.FINISHED); else { lastKey = getLastPageKey(data); } callback.onResult(data, lastKey); } else { mRetryRunnable = getRetryLoadAfter(params, callback); setDatabaseNotFoundError(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { mRetryRunnable = getRetryLoadAfter(params, callback); setError(databaseError); } }); }
Source:
private void testLocalOperation(CheckRemoteLockAcquiredOnlyOnceTest.CacheOperation o) throws Exception { assert !advancedCache(1).getRpcManager().getTransport().isCoordinator(); assert advancedCache(0).getRpcManager().getTransport().isCoordinator(); tm(0).begin(); o.execute(); assert lockManager(0).isLocked(key); assert !lockManager(1).isLocked(key); assertEquals(controlInterceptor.remoteInvocations, 0); }

Target:
private void testLocalOperation(CheckRemoteLockAcquiredOnlyOnceTest.CacheOperation o) throws Exception { assert !advancedCache(1).getRpcManager().getTransport().isCoordinator(); assert advancedCache(0).getRpcManager().getTransport().isCoordinator(); tm(0).begin(); o.execute(); assert lockManager(0).isLocked(key); assert !lockManager(1).isLocked(key); assertEquals(controlInterceptor.remoteInvocations, 0); tm(0).rollback(); }
Source:
public void onSignupSheetTermsOfServiceClicked() { AnalyticsTracker.track(AnalyticsTracker.Stat.SIGNUP_TERMS_OF_SERVICE_TAPPED); String locale = LanguageUtils.getPatchedCurrentDeviceLanguage(this); if (locale.indexOf("_") > -1) { locale = locale.substring(0, locale.indexOf("_")); } ActivityLauncher.openUrlExternal(this, getResources().getString(R.string.wordpresscom_tos_url, locale)); }

Target:
public void onSignupSheetTermsOfServiceClicked() { AnalyticsTracker.track(AnalyticsTracker.Stat.SIGNUP_TERMS_OF_SERVICE_TAPPED); String locale = LanguageUtils.getPatchedCurrentDeviceLanguage(this); int pos = locale.indexOf("_"); if (pos > -1) { locale = locale.substring(0, pos); } ActivityLauncher.openUrlExternal(this, getResources().getString(R.string.wordpresscom_tos_url, locale)); }
Source:
public void testPullWithUntrackedStash() throws Exception { PullResult res = target.pull().call(); assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty()); assertTrue(res.getMergeResult().getMergeStatus() .equals(MergeStatus.ALREADY_UP_TO_DATE)); writeToFile(sourceFile, "Source change"); source.add().addFilepattern("SomeFile.txt").call(); source.commit().setMessage("Source change in remote").call(); writeToFile(new File(dbTarget.getWorkTree(), "untracked.txt"), "untracked"); RevCommit revCommit = target.stashCreate() .setIndexMessage("message here").setIncludeUntracked(true) .call(); assertNotNull(revCommit); String stashName = revCommit.getName(); res = target.pull().call(); target.stashApply().setStashRef(stashName).call(); }

Target:
public void testPullWithUntrackedStash() throws Exception { target.pull().call(); writeToFile(sourceFile, "Source change"); source.add().addFilepattern("SomeFile.txt").call(); source.commit().setMessage("Source change in remote").call(); writeToFile(new File(dbTarget.getWorkTree(), "untracked.txt"), "untracked"); RevCommit stash = target.stashCreate().setIndexMessage("message here") .setIncludeUntracked(true).call(); assertNotNull(stash); assertTrue(target.status().call().isClean()); assertTrue(target.pull().call().isSuccessful()); assertEquals("[SomeFile.txt, mode:100644, content:Source change]", indexState(dbTarget, CONTENT)); assertFalse(JGitTestUtil.check(dbTarget, "untracked.txt")); assertEquals("Source change", JGitTestUtil.read(dbTarget, "SomeFile.txt")); target.stashApply().setStashRef(stash.getName()).call(); assertEquals("[SomeFile.txt, mode:100644, content:Source change]", indexState(dbTarget, CONTENT)); assertEquals("untracked", JGitTestUtil.read(dbTarget, "untracked.txt")); assertEquals("Source change", JGitTestUtil.read(dbTarget, "SomeFile.txt")); }
Source:
public ExtensionInstanceList getInstances( @PathParam("job-name") final String jobName, @QueryParam("start") final String nominalStart, @QueryParam("end") final String nominalEnd, @DefaultValue("") @QueryParam("instanceStatus") String instanceStatus, @DefaultValue("") @QueryParam("fields") String fields, @DefaultValue("") @QueryParam("orderBy") String orderBy, @DefaultValue("") @QueryParam("sortOrder") String sortOrder, @DefaultValue("0") @QueryParam("offset") final Integer offset, @QueryParam("numResults") Integer resultsPerPage, @DefaultValue("") @QueryParam("doAs") String doAsUser) { resultsPerPage = resultsPerPage == null ? getDefaultResultsPerPage() : resultsPerPage; try { List<Entity> entities = getEntityList("", "", "", TAG_PREFIX_EXTENSION_JOB + jobName, "", doAsUser); HashSet<String> fieldSet = new HashSet<>(Arrays.asList(fields.toUpperCase().split(","))); ExtensionInstanceList instances = new ExtensionInstanceList(entities.size()); for (Entity entity : entities) { InstancesResult entityInstances = super.getStatus( entity.getEntityType().name(), entity.getName(), nominalStart, nominalEnd, null, null, "STATUS:" + instanceStatus, orderBy, sortOrder, offset, resultsPerPage, null); instances.addEntitySummary(new ExtensionInstanceList.EntitySummary( getEntityElement(entity, fieldSet), entityInstances.getInstances())); } return instances; } catch (FalconException | IOException e) { LOG.error("Error when listing instances of extension job: " + jobName + ": ", e); throw FalconWebException.newAPIException(e, Response.Status.BAD_REQUEST); } }

Target:
public ExtensionInstanceList getInstances( @PathParam("job-name") final String jobName, @QueryParam("start") final String nominalStart, @QueryParam("end") final String nominalEnd, @DefaultValue("") @QueryParam("instanceStatus") String instanceStatus, @DefaultValue("") @QueryParam("fields") String fields, @DefaultValue("") @QueryParam("orderBy") String orderBy, @DefaultValue("") @QueryParam("sortOrder") String sortOrder, @DefaultValue("0") @QueryParam("offset") final Integer offset, @QueryParam("numResults") Integer resultsPerPage, @DefaultValue("") @QueryParam("doAs") String doAsUser) { resultsPerPage = resultsPerPage == null ? getDefaultResultsPerPage() : resultsPerPage; try { List<Entity> entities = getEntityList("", "", "", TAG_PREFIX_EXTENSION_JOB + jobName, "", doAsUser); HashSet<String> fieldSet = new HashSet<>(Arrays.asList(fields.toUpperCase().split(","))); ExtensionInstanceList instances = new ExtensionInstanceList(entities.size()); for (Entity entity : entities) { InstancesResult entityInstances = super.getStatus( entity.getEntityType().name(), entity.getName(), nominalStart, nominalEnd, null, null, "STATUS:" + instanceStatus, orderBy, sortOrder, offset, resultsPerPage, null); instances.addEntitySummary(new ExtensionInstanceList.EntitySummary( getEntityElement(entity, fieldSet), entityInstances.getInstances())); } return instances; } catch (FalconException | IOException e) { LOG.error("Error when listing instances of extension job: " + jobName + ": ", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
public void tearDownBtm() throws Exception { if(cacheManager != null) { cacheManager.close(); } transactionManager.shutdown(); if (TransactionManagerServices.isTransactionManagerRunning()) { TransactionManagerServices.getTransactionManager().shutdown(); } }

Target:
public void tearDownBtm() throws Exception { if(cacheManager != null) { cacheManager.close(); } if (TransactionManagerServices.isTransactionManagerRunning()) { TransactionManagerServices.getTransactionManager().shutdown(); } }
Source:
public Map<String, Sketch> extractAggregationResult(AggregationResultHolder aggregationResultHolder) { Map<Predicate, Union> unionMap = aggregationResultHolder.getResult(); if (unionMap == null || unionMap.isEmpty()) { return null; } Map<String, Sketch> result = new HashMap<>(); for (PredicateInfo predicateInfo : _predicateInfoMap.values()) { Sketch sketch = unionMap.get(predicateInfo.getPredicate()).getResult(); if (!sketch.isEmpty()) { result.put(predicateInfo.getStringPredicate(), sketch); } } return result; }

Target:
public Map<String, Sketch> extractAggregationResult(AggregationResultHolder aggregationResultHolder) { Map<Predicate, Union> unionMap = aggregationResultHolder.getResult(); if (unionMap == null || unionMap.isEmpty()) { return Collections.emptyMap(); } Map<String, Sketch> result = new HashMap<>(); for (PredicateInfo predicateInfo : _predicateInfoMap.values()) { Sketch sketch = unionMap.get(predicateInfo.getPredicate()).getResult(); if (!sketch.isEmpty()) { result.put(predicateInfo.getStringPredicate(), sketch); } } return result; }
Source:
public static TestSuite suite() throws IOException { TestSuite suite = new TestSuite(DeclarationGeneratorTests.class.getName()); List<File> testFiles = getTestInputFiles(JS_NO_EXTERNS); for (final File input : testFiles) { File golden = getGoldenFile(input, ".d.ts"); final String goldenText = getTestFileText(golden); ProgramSubject subject = assertThatProgram(input); if (input.getName().contains("_with_platform")) { subject.withPlatform = true; } if (input.getName().contains("_emit_platform_externs")) { subject.emitPlatformExterns = true; } if (input.getName().contains("_output_base")) { subject.emitBase = true; } if (Arrays.asList("partial", "multifilePartial", "crossModuleImports") .contains(input.getParentFile().getName())) { subject.partialInput = true; } subject.extraExternFile = getExternFileNameOrNull(input.getName()); suite.addTest(new DeclarationTest(input.getName(), goldenText, subject)); } return suite; }

Target:
public static TestSuite suite() throws IOException { TestSuite suite = new TestSuite(DeclarationGeneratorTests.class.getName()); List<File> testFiles = getTestInputFiles(JS_NO_EXTERNS); for (final File input : testFiles) { File golden = getGoldenFile(input, ".d.ts"); final String goldenText = getTestFileText(golden); ProgramSubject subject = assertThatProgram(input); if (input.getName().contains("_with_platform")) { subject.withPlatform = true; } if (input.getName().contains("_emit_platform_externs")) { subject.emitPlatformExterns = true; } if (input.getName().contains("_output_base")) { subject.emitBase = true; } if (Arrays.asList("partial", "multifilePartial", "partialCrossModuleImports") .contains(input.getParentFile().getName())) { subject.partialInput = true; } subject.extraExternFile = getExternFileNameOrNull(input.getName()); suite.addTest(new DeclarationTest(input.getName(), goldenText, subject)); } return suite; }
Source:
public void androidAppLinks() throws Exception { study.getAndroidAppLinks().add(TestConstants.ANDROID_APP_LINK); study.getAndroidAppLinks().add(TestConstants.ANDROID_APP_LINK_2); Result result = controller.androidAppLinks(); assertEquals(200, result.status()); TypeReference<List<AndroidAppSiteAssociation>> type = new TypeReference<List<AndroidAppSiteAssociation>>() {}; List<AndroidAppSiteAssociation> links = TestUtils.getResponsePayload(result, type); assertEquals(TestConstants.ANDROID_APP_LINK, links.get(0).getTarget()); assertEquals(TestConstants.ANDROID_APP_LINK_2, links.get(1).getTarget()); }

Target:
public void androidAppLinks() throws Exception { DynamoStudy study2 = new DynamoStudy(); study2.setIdentifier("test-study2"); study2.setSupportEmail("support@email.com"); study2.setPasswordPolicy(PasswordPolicy.DEFAULT_PASSWORD_POLICY); doReturn(ImmutableList.of(study, study2)).when(studyService).getStudies(); study.getAndroidAppLinks().add(TestConstants.ANDROID_APP_LINK); study.getAndroidAppLinks().add(TestConstants.ANDROID_APP_LINK_2); study2.getAndroidAppLinks().add(TestConstants.ANDROID_APP_LINK_3); study2.getAndroidAppLinks().add(TestConstants.ANDROID_APP_LINK_4); Result result = controller.androidAppLinks(); assertEquals(200, result.status()); JsonNode node = TestUtils.getJson(result); assertEquals(TestConstants.ANDROID_APP_LINK, getLinkAtIndex(node, 0)); assertEquals(TestConstants.ANDROID_APP_LINK_2, getLinkAtIndex(node, 1)); assertEquals(TestConstants.ANDROID_APP_LINK_3, getLinkAtIndex(node, 2)); assertEquals(TestConstants.ANDROID_APP_LINK_4, getLinkAtIndex(node, 3)); }
Source:
public void testGetContentForHttp429And200() throws Exception { String validResult = "this is valid result"; HttpContentRetriever service = prepareValidService(); CloseableHttpResponse getRateLimitedContentHttpResponse = mock(CloseableHttpResponse.class); { StatusLine getContentStatusLine = mock(StatusLine.class); when(getRateLimitedContentHttpResponse.getStatusLine()).thenReturn(getContentStatusLine); when(getContentStatusLine.getStatusCode()).thenReturn(429); HttpEntity getContentHttpEntity = mock(HttpEntity.class); when(getRateLimitedContentHttpResponse.getEntity()).thenReturn(getContentHttpEntity); when(getContentHttpEntity.getContent()).thenReturn(new ByteArrayInputStream("".getBytes())); } CloseableHttpResponse getValidContentHttpResponse = mock(CloseableHttpResponse.class); { StatusLine getMovedContentStatusLine = mock(StatusLine.class); HttpEntity getMovedContentHttpEntity = mock(HttpEntity.class); when(getValidContentHttpResponse.getStatusLine()).thenReturn(getMovedContentStatusLine); when(getMovedContentStatusLine.getStatusCode()).thenReturn(200); when(getValidContentHttpResponse.getEntity()).thenReturn(getMovedContentHttpEntity); when(getMovedContentHttpEntity.getContent()).thenReturn(new ByteArrayInputStream(validResult.getBytes())); } when(httpClient.execute(any(HttpGet.class))).thenReturn(getRateLimitedContentHttpResponse, getValidContentHttpResponse); ContentRetrieverResponse response = service.retrieveUrlContent("someUrl"); assertNotNull(response); assertNull(response.getException()); assertEquals(validResult, response.getContent()); }

Target:
public void testGetContentForHttp429And200() throws Exception { String validResult = "this is valid result"; HttpContentRetriever service = prepareValidService(); CloseableHttpResponse getRateLimitedContentHttpResponse = mock(CloseableHttpResponse.class); StatusLine getContentStatusLine = mock(StatusLine.class); when(getRateLimitedContentHttpResponse.getStatusLine()).thenReturn(getContentStatusLine); when(getContentStatusLine.getStatusCode()).thenReturn(429); HttpEntity getContentHttpEntity = mock(HttpEntity.class); when(getRateLimitedContentHttpResponse.getEntity()).thenReturn(getContentHttpEntity); when(getContentHttpEntity.getContent()).thenReturn(new ByteArrayInputStream("".getBytes())); CloseableHttpResponse getValidContentHttpResponse = mock(CloseableHttpResponse.class); StatusLine getMovedContentStatusLine = mock(StatusLine.class); HttpEntity getMovedContentHttpEntity = mock(HttpEntity.class); when(getValidContentHttpResponse.getStatusLine()).thenReturn(getMovedContentStatusLine); when(getMovedContentStatusLine.getStatusCode()).thenReturn(200); when(getValidContentHttpResponse.getEntity()).thenReturn(getMovedContentHttpEntity); when(getMovedContentHttpEntity.getContent()).thenReturn(new ByteArrayInputStream(validResult.getBytes())); when(httpClient.execute(any(HttpGet.class))).thenReturn(getRateLimitedContentHttpResponse, getValidContentHttpResponse); ContentRetrieverResponse response = service.retrieveUrlContent("someUrl"); assertNotNull(response); assertNull(response.getException()); assertEquals(validResult, response.getContent()); }