auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void readNext() throws IOException { Preconditions.checkArgument(in.available() > 0, "Reading past RLE/BitPacking stream."); final int header = BytesUtils.readUnsignedVarInt(in); mode = (header & 1) == 0 ? MODE.RLE : MODE.PACKED; switch (mode) { case RLE: currentCount = header >>> 1; if (DEBUG) LOG.debug("reading " + currentCount + " values RLE"); currentValue = BytesUtils.readIntLittleEndianPaddedOnBitWidth(in, bitWidth); break; case PACKED: int numGroups = header >>> 1; currentCount = numGroups * 8; if (DEBUG) LOG.debug("reading " + currentCount + " values BIT PACKED"); currentBuffer = new int[currentCount]; byte[] bytes = new byte[numGroups * bitWidth]; int bytesToRead = (int)Math.ceil(currentCount * bitWidth / 8.0); bytesToRead = Math.min(bytesToRead, in.available()); new DataInputStream(in).readFully(bytes, 0, bytesToRead); for (int valueIndex = 0, byteIndex = 0; valueIndex < currentCount; valueIndex += 8, byteIndex += bitWidth) { packer.unpack8Values(ByteBuffer.wrap(bytes), byteIndex, currentBuffer, valueIndex); } break; default: throw new ParquetDecodingException("not a valid mode " + mode); } }

Target:
private void readNext() throws IOException { Preconditions.checkArgument(in.available() > 0, "Reading past RLE/BitPacking stream."); final int header = BytesUtils.readUnsignedVarInt(in); mode = (header & 1) == 0 ? MODE.RLE : MODE.PACKED; switch (mode) { case RLE: currentCount = header >>> 1; if (DEBUG) LOG.debug("reading " + currentCount + " values RLE"); currentValue = BytesUtils.readIntLittleEndianPaddedOnBitWidth(in, bitWidth); break; case PACKED: int numGroups = header >>> 1; currentCount = numGroups * 8; if (DEBUG) LOG.debug("reading " + currentCount + " values BIT PACKED"); currentBuffer = new int[currentCount]; ByteBuffer buf = in.toByteBuffer(); int bytesToRead = (int)Math.ceil(currentCount * bitWidth / 8.0); bytesToRead = Math.min(bytesToRead, buf.remaining()); for (int valueIndex = 0, byteIndex = 0; valueIndex < currentCount; valueIndex += 8, byteIndex += bitWidth) { if (byteIndex + bitWidth <= buf.remaining()) { packer.unpack8Values(buf, byteIndex, currentBuffer, valueIndex); } else { byte[] bytes = new byte[bitWidth]; buf.get(bytes, byteIndex, buf.remaining() - byteIndex); packer.unpack8Values(ByteBuffer.wrap(bytes), 0, currentBuffer, valueIndex); } } in.skip(bytesToRead); break; default: throw new ParquetDecodingException("not a valid mode " + mode); } }
Source:
public Map<String, DbParameterAccessor> getAllProcedureParameters( String procName) throws SQLException { String[] qualifiers = NameNormaliser.normaliseName(procName).split( "\\."); String qry = " select type,param_list,returns from mysql.proc where "; if (qualifiers.length == 2) { qry += " lower(db)=? and lower(name)=? "; } else { qry += " (db=database() and lower(name)=?)"; } String type; String paramList; String returns; try (PreparedStatement dc = currentConnection.prepareStatement(qry)) { for (int i = 0; i < qualifiers.length; i++) { dc.setString(i + 1, NameNormaliser.normaliseName(qualifiers[i])); } ResultSet rs = dc.executeQuery(); if (!rs.next()) { throw new SQLException("Unknown procedure " + procName); } type = rs.getString(1); paramList = rs.getString(2); returns = rs.getString(3); rs.close(); } MySqlProcedureParametersParser parser = new MySqlProcedureParametersParser(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; for (ParamDescriptor pd: parser.parseParameters(paramList)) { DbParameterAccessor dbp = createDbParameterAccessor( pd.name, pd.direction, getSqlType(pd.type), getJavaClass(pd.type), position++); allParams.put(NameNormaliser.normaliseName(pd.name), dbp); } if ("FUNCTION".equals(type)) { ParamDescriptor rd = parser.parseReturnType(returns); allParams.put("", new DbParameterAccessor("", Direction.RETURN_VALUE, getSqlType(rd.type), getJavaClass(rd.type), -1, dbfitToJdbcTransformerFactory)); } return allParams; }

Target:
public Map<String, DbParameterAccessor> getAllProcedureParameters( String procName) throws SQLException { String[] qualifiers = NameNormaliser.normaliseName(procName).split( "\\."); String qry = " select type,param_list,returns from mysql.proc where "; if (qualifiers.length == 2) { qry += " lower(db)=? and lower(name)=? "; } else { qry += " (db=database() and lower(name)=?)"; } String type; String paramList; String returns; try (PreparedStatement dc = currentConnection.prepareStatement(qry)) { for (int i = 0; i < qualifiers.length; i++) { dc.setString(i + 1, NameNormaliser.normaliseName(qualifiers[i])); } ResultSet rs = dc.executeQuery(); if (!rs.next()) { throw new SQLException("Unknown procedure " + procName); } type = rs.getString(1); paramList = rs.getString(2); returns = rs.getString(3); rs.close(); } MySqlProcedureParametersParser parser = new MySqlProcedureParametersParser(); Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); int position = 0; for (ParamDescriptor pd: parser.parseParameters(paramList)) { DbParameterAccessor dbp = createDbParameterAccessor( pd.name, pd.direction, getSqlType(pd.type), getJavaClass(pd.type), position++); allParams.put(NameNormaliser.normaliseName(pd.name), dbp); } if ("FUNCTION".equals(type)) { ParamDescriptor rd = parser.parseReturnType(returns); allParams.put("", createDbParameterAccessor( "", Direction.RETURN_VALUE, getSqlType(rd.type), getJavaClass(rd.type), -1)); } return allParams; }
Source:
public Observable<ProgressStatus> getNetworkRequestStatusText() { return networkRequestStatusText; }

Target:
public Observable<ProgressStatus> getNetworkRequestStatusText() { return networkRequestStatusText.hide(); }
Source:
public void init() { this.taskSideInputStorageManager.init(); Map<SystemStreamPartition, String> fileOffsets = taskSideInputStorageManager.getFileOffsets(); this.lastProcessedOffsets.putAll(fileOffsets); this.startingOffsets = getStartingOffsets(fileOffsets, getOldestOffsets()); }

Target:
public void init() { this.taskSideInputStorageManager.init(); Map<SystemStreamPartition, String> fileOffsets = this.taskSideInputStorageManager.getFileOffsets(); LOG.info("File offsets for the task {}: {}", taskName, fileOffsets); this.lastProcessedOffsets.putAll(fileOffsets); LOG.info("Last processed offsets for the task {}: {}", taskName, lastProcessedOffsets); this.startingOffsets = getStartingOffsets(fileOffsets, getOldestOffsets()); LOG.info("Starting offsets for the task {}: {}", taskName, startingOffsets); }
Source:
public static <C extends Credentials> List<C> trackAll(@NonNull Run build, @NonNull List<C> credentials) { if (CredentialsProviderManager.isFingerprintEnabledOrDefault()) { for (Credentials c : credentials) { if (c != null) { try { getOrCreateFingerprintOf(c).addFor(build); } catch (IOException e) { LOGGER.log(Level.FINEST, "Could not track usage of " + c, e); } } } } else { LOGGER.log(Level.FINEST, "TrackAll(Run) called but fingerprints disabled in the global configuration."); } return credentials; }

Target:
public static <C extends Credentials> List<C> trackAll(@NonNull Run build, @NonNull List<C> credentials) { if (CredentialsProvider.FINGERPRINT_ENABLED) { for (Credentials c : credentials) { if (c != null) { try { getOrCreateFingerprintOf(c).addFor(build); } catch (IOException e) { LOGGER.log(Level.FINEST, "Could not track usage of " + c, e); } } } } else { LOGGER.log(Level.FINEST, "TrackAll method (Run variant) called but fingerprints disabled by {0}", FINGERPRINT_ENABLED_NAME); } return credentials; }
Source:
private Object toPrintableResult(JsonNode result) { Class<Map<String, String>> clazz = (Class) Map.class; Map<String, String> resultMap = null; try { resultMap = MAPPER.convertValue(result, clazz); } catch(IllegalArgumentException e) { return result; } if (resultMap.containsKey("password")) { resultMap.put("password", "*****"); } return resultMap; }

Target:
private Object toPrintableResult(JsonNode result) { if (result.isArray()) { return result; } Class<Map<String, String>> clazz = (Class) Map.class; Map<String, String> resultMap = MAPPER.convertValue(result, clazz); if (resultMap.containsKey("password")) { resultMap.put("password", "*****"); } return resultMap; }
Source:
public String toString() { return "CommandSpec{" + "args=" + this.args + ", executor=" + this.executor + ", description=" + this.description + ", extendedDescription=" + this.extendedDescription + ", permission='" + this.permission + '\'' + ", argumentParser=" + this.argumentParser + '}'; }

Target:
public String toString() { return Objects.toStringHelper(this) .add("args", this.args) .add("executor", this.executor) .add("description", this.description) .add("extendedDescription", this.extendedDescription) .add("permission", this.permission) .add("argumentParser", this.argumentParser) .toString(); }
Source:
public AbstractBlockFamily(BlockFamilyDefinition definition, BlockShape shape, BlockBuilderHelper blockBuilder) { }

Target:
protected AbstractBlockFamily(BlockFamilyDefinition definition, BlockShape shape, BlockBuilderHelper blockBuilder) { }
Source:
protected ItemStack dispenseStack(IBlockSource source, ItemStack stack) { World world = source.getWorld(); Direction facing = world.getBlockState(source.getBlockPos()).get(DispenserBlock.FACING); BlockPos pos = source.getBlockPos().offset(facing); if (ItemObedienceStick.applyStick(world, pos)) { return stack; } return super.dispenseStack(source, stack); }

Target:
protected ItemStack dispenseStack(IBlockSource source, ItemStack stack) { World world = source.getWorld(); Direction facing = world.getBlockState(source.getBlockPos()).get(DispenserBlock.FACING); BlockPos pos = source.getBlockPos().offset(facing); setSuccessful(ItemObedienceStick.applyStick(world, pos)); return stack; }
Source:
public void convertLocalizedStringSet() { assertThat(converting(ATTR_NAME_LOC_TEXT_SET)).isEqualTo(""); }

Target:
public void convertLocalizedStringSet() { assertThat(converting(ATTR_NAME_LOC_TEXT_SET)).isEqualTo("localized bar, localized foo"); }
Source:
private void setVmStyleByStatus(boolean mouseOver) { if (isSelected()) { getView().setItemSelectedStyle(); } else { getView().setVmStatusUnselectedStyle(); if (mouseOver) { getView().setItemMouseOverStyle(); } else { if (model.isVmUp() && !consoleInUse()) { getView().setItemRunningStyle(); } else { getView().setItemNotRunningOrConsoleTakenStyle(); } } } if (!model.isPool() && model.getVmConsoles().canConnectToConsole()) { getView().showDoubleClickBanner(); } else { getView().hideDoubleClickBanner(); } }

Target:
private void setVmStyleByStatus(boolean mouseOver) { if (isSelected()) { getView().setItemSelectedStyle(); } else { getView().setVmStatusUnselectedStyle(); if (mouseOver) { getView().setItemMouseOverStyle(); } else { if (model.isVmUp() && !consoleInUse()) { getView().setItemRunningStyle(); } else { getView().setItemNotRunningOrConsoleTakenStyle(); } } } if (mouseOver && !model.isPool() && model.getVmConsoles().canConnectToConsole()) { getView().showDoubleClickBanner(); } else { getView().hideDoubleClickBanner(); } }
Source:
public List<ITimeGraphRowModel> getRowModel(ITmfStateSystem ss, SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { TreeMultimap<Integer, ITmfStateInterval> intervals = TreeMultimap.create(Comparator.naturalOrder(), Comparator.comparing(ITmfStateInterval::getStartTime)); Map<@NonNull Long, @NonNull Integer> entries = getSelectedEntries(filter); Collection<Long> times = getTimes(filter, ss.getStartTime(), ss.getCurrentEndTime()); for (ITmfStateInterval interval : ss.query2D(entries.values(), times)) { if (monitor != null && monitor.isCanceled()) { return null; } intervals.put(interval.getAttribute(), interval); } List<ITimeGraphRowModel> rows = new ArrayList<>(); synchronized (fExecNamesCache) { fExecNamesCache.clear(); } for (Map.Entry<Long, Integer> entry : entries.entrySet()) { if (monitor != null && monitor.isCanceled()) { return null; } List<ITimeGraphState> eventList = new ArrayList<>(); for (ITmfStateInterval interval : intervals.get(entry.getValue())) { eventList.add(createTimeGraphState(interval, ss)); } rows.add(new TimeGraphRowModel(entry.getKey(), eventList)); } if (!ss.waitUntilBuilt(0)) { fTimeEventNames.invalidateAll(); } return rows; }

Target:
public List<ITimeGraphRowModel> getRowModel(ITmfStateSystem ss, SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) throws StateSystemDisposedException { TreeMultimap<Integer, ITmfStateInterval> intervals = TreeMultimap.create(Comparator.naturalOrder(), Comparator.comparing(ITmfStateInterval::getStartTime)); Map<@NonNull Long, @NonNull Integer> entries = getSelectedEntries(filter); Collection<Long> times = getTimes(filter, ss.getStartTime(), ss.getCurrentEndTime()); for (ITmfStateInterval interval : ss.query2D(entries.values(), times)) { if (monitor != null && monitor.isCanceled()) { return null; } intervals.put(interval.getAttribute(), interval); } List<ITimeGraphRowModel> rows = new ArrayList<>(); for (Map.Entry<Long, Integer> entry : entries.entrySet()) { if (monitor != null && monitor.isCanceled()) { return null; } List<ITimeGraphState> eventList = new ArrayList<>(); for (ITmfStateInterval interval : intervals.get(entry.getValue())) { eventList.add(createTimeGraphState(interval, ss)); } rows.add(new TimeGraphRowModel(entry.getKey(), eventList)); } if (!ss.waitUntilBuilt(0)) { fTimeEventNames.invalidateAll(); fExecNamesCache.clear(); } return rows; }
Source:
public NodeAndInitialCredentials<Device> createNodeWithGroupEncodedIntoName(String group, String name, Template template) { PacketTemplateOptions templateOptions = template.getOptions().as(PacketTemplateOptions.class); checkNotNull(templateOptions.getLoginPrivateKey(), "login privateKey must not be null"); Map<String, String> features = templateOptions.getFeatures(); BillingCycle billingCycle = BillingCycle.fromValue(templateOptions.getBillingCycle()); boolean locked = templateOptions.isLocked(); String userdata = templateOptions.getUserData(); Set<String> tags = templateOptions.getTags(); String plan = template.getHardware().getId(); String facility = template.getLocation().getId(); String operatingSystem = template.getImage().getId(); Device device = api.deviceApi(projectId).create( Device.CreateDevice.builder() .hostname(name) .plan(plan) .billingCycle(billingCycle.value()) .facility(facility) .features(features) .operatingSystem(operatingSystem) .locked(locked) .userdata(userdata) .tags(tags) .build() ); nodeRunningPredicate.apply(device.id()); device = api.deviceApi(projectId).get(device.id()); LoginCredentials defaultCredentials = LoginCredentials.builder() .user("root") .privateKey(templateOptions.getLoginPrivateKey()) .build(); return new NodeAndInitialCredentials<Device>(device, device.id(), defaultCredentials); }

Target:
public NodeAndInitialCredentials<Device> createNodeWithGroupEncodedIntoName(String group, String name, Template template) { PacketTemplateOptions templateOptions = template.getOptions().as(PacketTemplateOptions.class); Map<String, String> features = templateOptions.getFeatures(); BillingCycle billingCycle = BillingCycle.fromValue(templateOptions.getBillingCycle()); boolean locked = templateOptions.isLocked(); String userdata = templateOptions.getUserData(); Set<String> tags = templateOptions.getTags(); String plan = template.getHardware().getId(); String facility = template.getLocation().getId(); String operatingSystem = template.getImage().getId(); Device device = api.deviceApi(projectId).create( Device.CreateDevice.builder() .hostname(name) .plan(plan) .billingCycle(billingCycle.value()) .facility(facility) .features(features) .operatingSystem(operatingSystem) .locked(locked) .userdata(userdata) .tags(tags) .build() ); return new NodeAndInitialCredentials<Device>(device, device.id(), null); }
Source:
public static String generateStructMemberParserLine(final StructMember structMember, final String parserFunction) throws ParseException { final StringBuilder outputBuilder = new StringBuilder(); outputBuilder.append(indent(3)). append("response->"). append(Helper.camelToUnderscore(structMember.getName())). append(" = "). append(parserFunction).append("\n"); return outputBuilder.toString(); }

Target:
public static String generateStructMemberParserLine(final StructMember structMember, final String parserFunction) throws ParseException { return indent(3) + "response->" + Helper.camelToUnderscore(structMember.getName()) + " = " + parserFunction + "\n"; }
Source:
public void testDelete() { String content = getExpectedDefString(); when( path.toURI() ).thenReturn( FILE_URI ); org.uberfire.java.nio.file.Path nioPath = Paths.convert( path ); when( ioService.readAllString( nioPath ) ).thenReturn( content ); when( ioService.exists( nioPath ) ).thenReturn( true ); when ( projectService.resolveProject( path ) ).thenReturn( project ); try { when( runtimeManager.getDataSourceDeploymentInfo( getExpectedDef().getUuid() ) ).thenReturn( dataSourceDeploymentInfo ); when( runtimeManager.getDriverDeploymentInfo( getExpectedDef().getUuid() ) ).thenReturn( driverDeploymentInfo ); } catch ( Exception e ) { } editorService.delete( path, COMMENT ); verifyDeleteConditions( ); }

Target:
public void testDelete() throws Exception { String content = getExpectedDefString(); when( path.toURI() ).thenReturn( FILE_URI ); org.uberfire.java.nio.file.Path nioPath = Paths.convert( path ); when( ioService.readAllString( nioPath ) ).thenReturn( content ); when( ioService.exists( nioPath ) ).thenReturn( true ); when( projectService.resolveProject( path ) ).thenReturn( project ); when( runtimeManager.getDataSourceDeploymentInfo( getExpectedDef().getUuid() ) ).thenReturn( dataSourceDeploymentInfo ); when( runtimeManager.getDriverDeploymentInfo( getExpectedDef().getUuid() ) ).thenReturn( driverDeploymentInfo ); editorService.delete( path, COMMENT ); verifyDeleteConditions(); }
Source:
protected void internalRefresh(Object element) { getContentProvider().runWhenReady(IN_UI_SYNC, new Runnable() { public void run() { getViewer().refresh(); } }); getContentProvider().runWhenReady(IN_UI_SYNC, new Runnable() { public void run() { dependencyData.updateDependencies(getSelection(), EMFCompareRCPPlugin.getDefault() .getMergerRegistry()); internalRedraw(); } }); getContentProvider().runWhenReady(IN_UI_SYNC, new Runnable() { public void run() { refreshTitle(); } }); }

Target:
protected void internalRefresh(Object element) { getContentProvider().runWhenReady(IN_UI_SYNC, new Runnable() { public void run() { getViewer().refresh(); } }); getContentProvider().runWhenReady(IN_UI_SYNC, new Runnable() { public void run() { dependencyData.updateDependencies(getSelection(), EMFCompareRCPPlugin.getDefault() .getMergerRegistry()); internalRedraw(); } }); getContentProvider().runWhenReady(IN_UI_ASYNC, new Runnable() { public void run() { if (!getControl().isDisposed()) { refreshTitle(); } } }); }
Source:
public String toString() { return "Erratum [id=" + id + ", title=" + title + ", type=" + type + ", severity=" + severity + "]"; }

Target:
public String toString() { ToStringBuilder builder = ToStringBuilder.forInstance(this); builder.append("id", id); builder.append("title", title); builder.append("type", type); builder.append("severity", severity); return builder.toString(); }
Source:
public InterpretedPageProjectionOutput(DriverYieldSignal yieldSignal, Page page, SelectedPositions selectedPositions) { this.yieldSignal = requireNonNull(yieldSignal, "yieldSignal is null"); this.blocks = requireNonNull(page, "page is null").getBlocks(); this.selectedPositions = requireNonNull(selectedPositions, "selectedPositions is null"); this.nextIndexOrPosition = selectedPositions.getOffset(); if (selectedPositions.isList()) { this.positions = selectedPositions.getPositions(); } else { this.positions = null; } }

Target:
public InterpretedPageProjectionOutput(DriverYieldSignal yieldSignal, Page page, SelectedPositions selectedPositions) { this.yieldSignal = requireNonNull(yieldSignal, "yieldSignal is null"); this.blocks = requireNonNull(page, "page is null").getBlocks(); this.selectedPositions = requireNonNull(selectedPositions, "selectedPositions is null"); this.nextIndexOrPosition = selectedPositions.getOffset(); }
Source:
public void persist_shouldSearchHistoryByChargeId_IgnoringRefundStatusWithStateCreated() { ChargeEntity chargeEntity = new ChargeEntity(); chargeEntity.setId(chargeTestRecord.getChargeId()); RefundEntity refundEntity1 = new RefundEntity(chargeEntity, 100L, null); refundEntity1.setStatus(RefundStatus.CREATED); RefundEntity refundEntity = new RefundEntity(chargeEntity, 100L, null); refundEntity.setStatus(RefundStatus.REFUND_SUBMITTED); refundEntity.setReference("test-refund-entity"); refundDao.persist(refundEntity); List<RefundHistory> refundHistoryList = refundDao.searchHistoryByChargeId(chargeEntity.getId()); assertThat(refundHistoryList.size(), is(1)); RefundHistory refundHistory = refundHistoryList.get(0); assertThat(refundHistory.getId(), is(refundEntity.getId())); assertThat(refundHistory.getExternalId(), is(refundEntity.getExternalId())); assertThat(refundHistory.getAmount(), is(refundEntity.getAmount())); assertThat(refundHistory.getStatus(), is(refundEntity.getStatus())); assertNotNull(refundHistory.getChargeEntity()); assertThat(refundHistory.getChargeEntity().getId(), is(refundEntity.getChargeEntity().getId())); assertThat(refundHistory.getCreatedDate(), is(refundEntity.getCreatedDate())); assertThat(refundHistory.getVersion(), is(refundEntity.getVersion())); assertThat(refundHistory.getReference(), is(refundEntity.getReference())); }

Target:
public void persist_shouldSearchHistoryByChargeId_IgnoringRefundStatusWithStateCreated() { ChargeEntity chargeEntity = new ChargeEntity(); chargeEntity.setId(chargeTestRecord.getChargeId()); RefundEntity refundEntity1 = new RefundEntity(chargeEntity, 100L, userExternalId); refundEntity1.setStatus(RefundStatus.CREATED); RefundEntity refundEntity = new RefundEntity(chargeEntity, 100L, userExternalId); refundEntity.setStatus(RefundStatus.REFUND_SUBMITTED); refundEntity.setReference("test-refund-entity"); refundDao.persist(refundEntity); List<RefundHistory> refundHistoryList = refundDao.searchHistoryByChargeId(chargeEntity.getId()); assertThat(refundHistoryList.size(), is(1)); RefundHistory refundHistory = refundHistoryList.get(0); assertThat(refundHistory.getId(), is(refundEntity.getId())); assertThat(refundHistory.getExternalId(), is(refundEntity.getExternalId())); assertThat(refundHistory.getAmount(), is(refundEntity.getAmount())); assertThat(refundHistory.getStatus(), is(refundEntity.getStatus())); assertNotNull(refundHistory.getChargeEntity()); assertThat(refundHistory.getChargeEntity().getId(), is(refundEntity.getChargeEntity().getId())); assertThat(refundHistory.getCreatedDate(), is(refundEntity.getCreatedDate())); assertThat(refundHistory.getVersion(), is(refundEntity.getVersion())); assertThat(refundHistory.getReference(), is(refundEntity.getReference())); assertThat(userExternalId, is(refundEntity.getUserExternalId())); assertThat(refundHistory.getUserExternalId(), is(refundEntity.getUserExternalId())); }
Source:
public void loadConvertsCodeFieldsWhenControllerIsOnlyCodeFields() throws Exception { this.documentAccessBridge = this.codeFieldImplMocker.getInstance(DocumentAccessBridge.class); doReturn(this.doc).when(this.documentAccessBridge).getDocument(this.patientDocument); List<String> list1 = new LinkedList<>(); list1.add("HP:00000015"); doReturn(list1).when(this.baseProperty1).getValue(); doReturn(list1).when(this.baseProperty2).getValue(); PatientData<List<VocabularyProperty>> result = this.codeFieldImplMocker.getComponentUnderTest().load(this.patient); List<VocabularyProperty> propertyOneList = result.get(PROPERTY_1); List<VocabularyProperty> propertyTwoList = result.get(PROPERTY_2); Assert.assertNotNull(propertyOneList); Assert.assertNotNull(propertyTwoList); }

Target:
public void loadConvertsCodeFieldsWhenControllerIsOnlyCodeFields() throws Exception { this.documentAccessBridge = this.codeFieldImplMocker.getInstance(DocumentAccessBridge.class); doReturn(this.doc).when(this.documentAccessBridge).getDocument(this.patientDocument); List<String> list1 = new LinkedList<>(); list1.add("HP:00000015"); doReturn(list1).when(this.baseProperty1).getValue(); List<String> list2 = new LinkedList<>(); list2.add("HP:00000120"); doReturn(list2).when(this.baseProperty2).getValue(); PatientData<List<VocabularyProperty>> result = this.codeFieldImplMocker.getComponentUnderTest().load(this.patient); List<VocabularyProperty> propertyOneList = result.get(PROPERTY_1); List<VocabularyProperty> propertyTwoList = result.get(PROPERTY_2); Assert.assertNotNull(propertyOneList); Assert.assertNotNull(propertyTwoList); Assert.assertThat(propertyOneList, hasSize(1)); Assert.assertThat(propertyTwoList, hasSize(1)); Assert.assertThat(propertyOneList, contains(hasProperty("id", is("HP:00000015")))); Assert.assertThat(propertyTwoList, contains(hasProperty("id", is("HP:00000120")))); }
Source:
public void addInput(Page page) { verify(probe == null); probe = page; probePosition = 0; joinAddresses = null; joinAddressIndex = 0; }

Target:
public void addInput(Page page) { verify(probe == null); probe = page; probePosition = 0; joinAddresses = null; }
Source:
Object encodeLiteral(Object literal, Class<?> targetType) { if (literal instanceof Envelope) { return geometryBuilder.toObject((Envelope) literal); } else if (literal instanceof Geometry) { return geometryBuilder.toObject((Geometry) literal); } else if (literal instanceof Date) { if (targetType != null && Date.class.isAssignableFrom(targetType)) { return literal; } return ISO8601_SDF.format((Date)literal); } else if (literal instanceof String) { if (targetType != null && Date.class.isAssignableFrom(targetType)) { try { return ISO8601_SDF.parse((String) literal); } catch (ParseException e) { LOGGER.log(Level.WARNING, "Could not parse String literal as ISO-8601 date", e); } } return literal; } else if (literal instanceof Number) { return literal; } else { return literal.toString(); } }

Target:
Object encodeLiteral(Object literal, Class<?> targetType) { if (literal instanceof Envelope) { return geometryBuilder.toObject((Envelope) literal); } else if (literal instanceof Geometry) { return geometryBuilder.toObject((Geometry) literal); } else if (literal instanceof Date) { if (targetType != null && Date.class.isAssignableFrom(targetType)) { return literal; } return ISO8601_SDF.format((Date)literal); } else if (literal instanceof String) { if (targetType != null && Date.class.isAssignableFrom(targetType)) { try { return ISO8601_SDF.parse((String) literal); } catch (ParseException e) { LOGGER.log(Level.WARNING, "Could not parse String literal as ISO-8601 date", e); } } return literal; } else if (literal instanceof Integer || literal instanceof Long || literal instanceof Double) { return literal; } else { return literal.toString(); } }
Source:
public void fromXmlWithInvalidElementThrowsExceptionInDevBuild() throws IOException { final String xmlResponse = "<Object Name=\"file1\" InCache=\"false\" Length=\"256\" Offset=\"0\" TheAnswerToEverything=\"42\" />"; XmlOutput.fromXml(xmlResponse, BulkObject.class); }

Target:
public void fromXmlWithInvalidElementThrowsExceptionInDevBuild() throws IOException { assumeFalse(XmlOutput.isProductionBuild()); final String xmlResponse = "<Object Name=\"file1\" InCache=\"false\" Length=\"256\" Offset=\"0\" TheAnswerToEverything=\"42\" />"; XmlOutput.fromXml(xmlResponse, BulkObject.class); }
Source:
public void accept(String json, Context context) throws RuntimeException { JsonObject body = GSON_PARSER.fromJson(json, JsonObject.class); JsonObject tempJson = body.getAsJsonObject("value"); String currentValue = null; if (tempJson != null) { tempJson = tempJson.getAsJsonObject("fields"); } if (tempJson != null) { tempJson = tempJson.getAsJsonObject("original"); } if (tempJson != null && tempJson.has("stringValue")) { currentValue = tempJson.get("stringValue").getAsString(); } if (currentValue == null) { throw new IllegalArgumentException("Malformed JSON"); } String newValue = currentValue.toUpperCase(); Map<String, String> newFields = new HashMap<>(); newFields.put("original", newValue); String affectedDoc = context.resource().split("/documents/")[1].replace("\"", ""); LOGGER.info(String.format("Replacing value: %s --> %s", currentValue, newValue)); try { FIRESTORE.document(affectedDoc).set(newFields, SetOptions.merge()).get(); } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } }

Target:
public void accept(String json, Context context) { JsonObject body = gson.fromJson(json, JsonObject.class); JsonObject tempJson = body.getAsJsonObject("value"); String currentValue = null; if (tempJson != null) { tempJson = tempJson.getAsJsonObject("fields"); } if (tempJson != null) { tempJson = tempJson.getAsJsonObject("original"); } if (tempJson != null && tempJson.has("stringValue")) { currentValue = tempJson.get("stringValue").getAsString(); } if (currentValue == null) { throw new IllegalArgumentException("Malformed JSON: " + json); } String newValue = currentValue.toUpperCase(Locale.getDefault()); Map<String, String> newFields = new HashMap<>(); newFields.put("original", newValue); String affectedDoc = context.resource().split("/documents/")[1].replace("\"", ""); LOGGER.info(String.format("Replacing value: %s --> %s", currentValue, newValue)); try { FIRESTORE.document(affectedDoc).set(newFields, SetOptions.merge()).get(); } catch (ExecutionException | InterruptedException e) { LOGGER.log(Level.SEVERE, "Error updating Firestore document: " + e.getMessage(), e); } }
Source:
public void copyObjectFail() throws InterruptedException, IOException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404) .addHeader(SwiftHeaders.OBJECT_COPY_FROM, "bar"))); try { SwiftApi api = api(server.getUrl("/").toString(), "openstack-swift"); api.objectApiInRegionForContainer("DFW", "foo") .copy("bar.txt", "bar", "foo.txt"); assertEquals(server.getRequestCount(), 2); assertEquals(server.takeRequest().getRequestLine(), "POST /tokens HTTP/1.1"); RecordedRequest copyRequest = server.takeRequest(); assertEquals(copyRequest.getRequestLine(), "PUT /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/foo/bar.txt HTTP/1.1 "); fail(); } finally { server.shutdown(); } }

Target:
public void copyObjectFail() throws InterruptedException, IOException { MockWebServer server = mockOpenStackServer(); server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource("/access.json")))); server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404) .addHeader(SwiftHeaders.OBJECT_COPY_FROM, "/bogus/foo.txt"))); try { SwiftApi api = api(server.getUrl("/").toString(), "openstack-swift"); api.objectApiInRegionForContainer("DFW", "foo").copy("bar.txt", "bogus", "foo.txt"); } finally { server.shutdown(); } }
Source:
public KafkaEightSimpleConsumerFirehoseFactory( @JsonProperty("brokerList") List<String> brokerList, @JsonProperty("partitionIdList") List<Integer> partitionIdList, @JsonProperty("clientId") String clientId, @JsonProperty("feed") String feed, @JsonProperty("queueBufferLength") Integer queueBufferLength, @JsonProperty("resetOffsetToEarliest") Boolean resetOffsetToEarliest ) { this.brokerList = brokerList; this.partitionIdList = partitionIdList; this.clientId = clientId; this.feed = feed; this.queueBufferLength = queueBufferLength == null ? DEFAULT_QUEUE_BUFFER_LENGTH : queueBufferLength; log.info("queueBufferLength loaded as[%s]", this.queueBufferLength); this.earliest = resetOffsetToEarliest == null ? true : resetOffsetToEarliest.booleanValue(); log.info("Default behavior of cosumer set to earliest? [%s]", this.earliest); }

Target:
public KafkaEightSimpleConsumerFirehoseFactory( @JsonProperty("brokerList") List<String> brokerList, @JsonProperty("partitionIdList") List<Integer> partitionIdList, @JsonProperty("clientId") String clientId, @JsonProperty("feed") String feed, @JsonProperty("queueBufferLength") Integer queueBufferLength, @JsonProperty("resetOffsetToEarliest") Boolean resetOffsetToEarliest ) { this.brokerList = brokerList; Preconditions.checkArgument( brokerList != null && brokerList.size() > 0, "brokerList is null/empty" ); this.partitionIdList = partitionIdList; Preconditions.checkArgument( partitionIdList != null && partitionIdList.size() > 0, "partitionIdList is null/empty" ); this.clientId = clientId; Preconditions.checkArgument( clientId != null && !clientId.isEmpty(), "clientId is null/empty" ); this.feed = feed; Preconditions.checkArgument( feed != null && !feed.isEmpty(), "feed is null/empty" ); this.queueBufferLength = queueBufferLength == null ? DEFAULT_QUEUE_BUFFER_LENGTH : queueBufferLength; Preconditions.checkArgument(queueBufferLength > 0, "queueBufferLength must be positive number"); log.info("queueBufferLength loaded as[%s]", this.queueBufferLength); this.earliest = resetOffsetToEarliest == null ? true : resetOffsetToEarliest.booleanValue(); log.info( "if old offsets are not known, data from partition will be read from [%s] available offset.", this.earliest ? "earliest" : "latest" ); }
Source:
public void sanitizeForSaving() { name = SanitizationHelper.sanitizeForHtml(name); }

Target:
public void sanitizeForSaving() { }
Source:
private void connectAndRefreshAllUpHosts(final boolean commandSucceeded) { for (VDS vds : getAllRunningVdssInPool()) { try { if (!_isLastMaster && commandSucceeded) { try { runVdsCommand( VDSCommandType.RefreshStoragePool, new RefreshStoragePoolVDSCommandParameters(vds.getId(), getStoragePool().getId(), _newMasterStorageDomainId, getStoragePool().getmaster_domain_version())); } catch (VDSExceptionBase ex) { if (VdcBllErrors.StoragePoolUnknown == ex.getVdsError().getCode()) { VDSReturnValue returnVal = runVdsCommand( VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(vds.getId(), getStoragePool().getId(), vds.getvds_spm_id(), _newMasterStorageDomainId, getStoragePool() .getmaster_domain_version())); if (!returnVal.getSucceeded()) { log.errorFormat("Post reconstruct actions (connectPool) did not complete on host {0} in the pool. error {1}", vds.getId(), returnVal.getVdsError().getMessage()); } } else { log.errorFormat("Post reconstruct actions (refreshPool)" + " did not complete on host {0} in the pool. error {1}", vds.getId(), ex.getMessage()); } } } if (!getParameters().isInactive()) { StorageHelperDirector.getInstance() .getItem(getStorageDomain().getstorage_type()) .DisconnectStorageFromDomainByVdsId(getStorageDomain(), vds.getId()); } } catch (Exception e) { log.errorFormat("Post reconstruct actions (connectPool,refreshPool,disconnect storage)" + " did not complete on host {0} in the pool. error {1}", vds.getId(), e.getMessage()); } } }

Target:
private void connectAndRefreshAllUpHosts(final boolean commandSucceeded) { for (VDS vds : getAllRunningVdssInPool()) { try { if (!_isLastMaster && commandSucceeded) { try { runVdsCommand( VDSCommandType.RefreshStoragePool, new RefreshStoragePoolVDSCommandParameters(vds.getId(), getStoragePool().getId(), _newMasterStorageDomainId, getStoragePool().getmaster_domain_version())); } catch (VdcBLLException ex) { if (VdcBllErrors.StoragePoolUnknown == ex.getVdsError().getCode()) { VDSReturnValue returnVal = runVdsCommand( VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(vds.getId(), getStoragePool().getId(), vds.getvds_spm_id(), _newMasterStorageDomainId, getStoragePool() .getmaster_domain_version())); if (!returnVal.getSucceeded()) { log.errorFormat("Post reconstruct actions (connectPool) did not complete on host {0} in the pool. error {1}", vds.getId(), returnVal.getVdsError().getMessage()); } } else { log.errorFormat("Post reconstruct actions (refreshPool)" + " did not complete on host {0} in the pool. error {1}", vds.getId(), ex.getMessage()); } } } if (!getParameters().isInactive()) { StorageHelperDirector.getInstance() .getItem(getStorageDomain().getstorage_type()) .DisconnectStorageFromDomainByVdsId(getStorageDomain(), vds.getId()); } } catch (Exception e) { log.errorFormat("Post reconstruct actions (connectPool,refreshPool,disconnect storage)" + " did not complete on host {0} in the pool. error {1}", vds.getId(), e.getMessage()); } } }
Source:
public CohortMembership getActiveMembership(Patient patient) { return getMemberships().stream().filter(CohortMembership::isActive).filter(m -> m.getPatientId().equals(patient.getPatientId())).findFirst().get(); }

Target:
public CohortMembership getActiveMembership(Patient patient) { return getMemberships().stream().filter(m -> m.isActive() && m.getPatientId().equals(patient.getPatientId())).findFirst().get(); }
Source:
private StreamCollector newRunResponseCollector() { return new StreamCollector() { @Override public void keys( String[] names ) { keys = new ArrayList<>( Arrays.asList( names ) ); } @Override public void record( Value[] fields ) @Override public void statementType( StatementType type ) @Override public void statementStatistics( UpdateStatistics statistics ) @Override public void plan( Plan plan ) @Override public void profile( ProfiledPlan plan ) @Override public void notifications( List<Notification> notifications ) @Override public void done() { if ( keys == null ) { keys = new ArrayList<>(); } } }; }

Target:
private StreamCollector newRunResponseCollector() { return new StreamCollector() { @Override public void keys( String[] names ) { keys = Arrays.asList( names ); } @Override public void record( Value[] fields ) @Override public void statementType( StatementType type ) @Override public void statementStatistics( UpdateStatistics statistics ) @Override public void plan( Plan plan ) @Override public void profile( ProfiledPlan plan ) @Override public void notifications( List<Notification> notifications ) @Override public void done() { if ( keys == null ) { keys = new ArrayList<>(); } } }; }
Source:
private void pruneStore(PersistableNetworkPayloadStore historicalStore, String version) { int preLive = getMapOfLiveData().keySet().size(); getMapOfLiveData().keySet().removeAll(historicalStore.getMap().keySet()); int postLive = getMapOfLiveData().size(); if (preLive > postLive) { log.info("We pruned data from our live data store which are already contained in the historical data store with version {}. " + "The live map had entries before pruning and has entries afterwards.", version, preLive, postLive); } else { log.info("No pruning from historical data store with version was applied", version); } storage.queueUpForSave(store); }

Target:
private void pruneStore(PersistableNetworkPayloadStore historicalStore, String version) { int preLive = getMapOfLiveData().size(); getMapOfLiveData().keySet().removeAll(historicalStore.getMap().keySet()); int postLive = getMapOfLiveData().size(); if (preLive > postLive) { log.info("We pruned data from our live data store which are already contained in the historical data store with version {}. " + "The live map had entries before pruning and has entries afterwards.", version, preLive, postLive); } else { log.info("No pruning from historical data store with version was applied", version); } storage.queueUpForSave(store); }
Source:
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); TcpDiscoverySpi discoSpi = new TcpDiscoverySpi(); discoSpi.setIpFinder(IP_FINDER); cfg.setDiscoverySpi(discoSpi); cfg.setConsistentId(igniteInstanceName); if (disableAutoActivation) cfg.setAutoActivationEnabled(false); cfg.setDataStorageConfiguration( new DataStorageConfiguration().setDefaultDataRegionConfiguration( new DataRegionConfiguration() .setPersistenceEnabled(true) .setMaxSize(100 * 1024 * 1024) .setInitialSize(100 * 1024 * 1024) ) .setDataRegionConfigurations( new DataRegionConfiguration() .setName("memory") .setPersistenceEnabled(false) .setMaxSize(100 * 1024 * 1024) .setInitialSize(100 * 1024 * 1024) ) .setWalMode(WALMode.LOG_ONLY) ); if (userAttrs != null) cfg.setUserAttributes(userAttrs); if (client) cfg.setClientMode(true); return cfg; }

Target:
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setConsistentId(igniteInstanceName); if (disableAutoActivation) cfg.setAutoActivationEnabled(false); cfg.setDataStorageConfiguration( new DataStorageConfiguration().setDefaultDataRegionConfiguration( new DataRegionConfiguration() .setPersistenceEnabled(true) .setMaxSize(100L * 1024 * 1024) .setInitialSize(100L * 1024 * 1024) ) .setDataRegionConfigurations( new DataRegionConfiguration() .setName("memory") .setPersistenceEnabled(false) .setMaxSize(100L * 1024 * 1024) .setInitialSize(100L * 1024 * 1024) ) .setWalMode(WALMode.LOG_ONLY) ); if (userAttrs != null) cfg.setUserAttributes(userAttrs); if (client) cfg.setClientMode(true); return cfg; }
Source:
static List<String> identifySamplesWithSuspiciousContigs(final List<ReadCountCollection> singleSampleTangentNormalizedReadCounts, final Map<String, Double> contigToMedian) { logger.info("Checking for samples with suspicious contigs..."); return singleSampleTangentNormalizedReadCounts.stream().filter(r -> hasSuspiciousContigs(r, contigToMedian)).map(r -> r.columnNames().get(0)).collect(Collectors.toList()); }

Target:
static List<String> identifySamplesWithSuspiciousContigs(final List<ReadCountCollection> singleSampleTangentNormalizedReadCounts, final Map<String, Double> contigToMedian) { logger.info("Checking for samples with suspicious contigs..."); return singleSampleTangentNormalizedReadCounts.stream().filter(rcc -> hasSuspiciousContigs(rcc, contigToMedian)).map(rcc -> rcc.columnNames().get(0)).collect(Collectors.toList()); }
Source:
private List<Project.NameKey> getAllParents(final Project.NameKey projectName) { final List<Project.NameKey> parents = new ArrayList<Project.NameKey>(); Project.NameKey p = projectName; while (p != null) { final ProjectState e = projectCache.get(p); if (e == null) { break; } p = getParentName(e.getProject()); if (p != null) { parents.add(p); } } return parents; }

Target:
private List<Project.NameKey> getAllParents(final Project.NameKey projectName) { final List<Project.NameKey> parents = new ArrayList<Project.NameKey>(); Project.NameKey p = projectName; while (p != null && !parents.contains(p)) { final ProjectState e = projectCache.get(p); if (e == null) { break; } p = getParentName(e.getProject()); if (p != null) { parents.add(p); } } return parents; }
Source:
public void onSuccess(FullJsonResponseHandler.JsonResponse<T> response) { stats.updateSuccess(); stats.responseSize(response.getResponseSize()); try { if (response.getStatusCode() == HttpStatus.OK.code() && response.hasValue()) { callback.success(response.getValue()); } else if (response.getStatusCode() == HttpStatus.SERVICE_UNAVAILABLE.code()) { callback.failed(new ServiceUnavailableException(uri)); } else { Exception cause = response.getException(); if (cause == null) { if (response.getStatusCode() == HttpStatus.OK.code()) { cause = new PrestoException(REMOTE_TASK_ERROR, format("Expected response from %s is empty", uri)); } else { cause = new PrestoException(REMOTE_TASK_ERROR, format("Expected response code from %s to be %s, but was %s: %s%n%s", uri, HttpStatus.OK.code(), response.getStatusCode(), response.getStatusMessage(), response.getResponseBody())); } } else { cause = new PrestoException(REMOTE_TASK_ERROR, format("Unexpected exception raised from %s", uri), cause); } callback.fatal(cause); } } catch (Throwable t) { callback.fatal(t); } }

Target:
public void onSuccess(FullJsonResponseHandler.JsonResponse<T> response) { stats.updateSuccess(); stats.responseSize(response.getResponseSize()); try { if (response.getStatusCode() == HttpStatus.OK.code() && response.hasValue()) { callback.success(response.getValue()); } else if (response.getStatusCode() == HttpStatus.SERVICE_UNAVAILABLE.code()) { callback.failed(new ServiceUnavailableException(uri)); } else { Exception cause = response.getException(); if (cause == null) { if (response.getStatusCode() == HttpStatus.OK.code()) { cause = new PrestoException(REMOTE_TASK_ERROR, format("Expected response from %s is empty", uri)); } else { cause = new PrestoException(REMOTE_TASK_ERROR, format("Expected response code from %s to be %s, but was %s: %s%n%s", uri, HttpStatus.OK.code(), response.getStatusCode(), response.getStatusMessage(), response.getResponseBody())); } } else { cause = new PrestoException(REMOTE_TASK_ERROR, format("Unexpected response from %s", uri), cause); } callback.fatal(cause); } } catch (Throwable t) { callback.fatal(t); } }
Source:
protected DigdagClient buildClient(boolean checkServerVersion) throws IOException, SystemExitException { Properties props = loadSystemProperties(); PluginSet plugins = loadSystemPlugins(props); plugins = plugins.withPlugins(new TdDigdagClientConfigurationPlugin()); List<DigdagClientConfigurator> clientConfigurators = plugins.withInjector(injector).getServiceProviders(DigdagClientConfigurator.class); if (endpoint == null) { endpoint = props.getProperty("client.http.endpoint", DEFAULT_ENDPOINT); } DigdagClient client = buildClient(endpoint, env, props, disableCertValidation, httpHeaders, clientConfigurators); if (checkServerVersion && !disableVersionCheck) { Map<String, Object> remoteVersions = client.getVersion(); String remoteVersion = String.valueOf(remoteVersions.getOrDefault("version", "")); if (!version.version().equals(remoteVersion)) { throw systemExit(String.format("" + "Client and server version mismatch: Client: %s, Server: %s.%n" + "Please run following command locally to download a compatible version with the server:%n" + "%n" + " " + programName + " selfupdate %s%n", version, remoteVersion, remoteVersion)); } } return client; }

Target:
protected DigdagClient buildClient(boolean checkServerVersion) throws IOException, SystemExitException { Properties props = loadSystemProperties(); PluginSet plugins = loadSystemPlugins(props); List<DigdagClientConfigurator> clientConfigurators = plugins.withInjector(injector).getServiceProviders(DigdagClientConfigurator.class); if (endpoint == null) { endpoint = props.getProperty("client.http.endpoint", DEFAULT_ENDPOINT); } DigdagClient client = buildClient(endpoint, env, props, disableCertValidation, httpHeaders, clientConfigurators); if (checkServerVersion && !disableVersionCheck) { Map<String, Object> remoteVersions = client.getVersion(); String remoteVersion = String.valueOf(remoteVersions.getOrDefault("version", "")); if (!version.version().equals(remoteVersion)) { throw systemExit(String.format("" + "Client and server version mismatch: Client: %s, Server: %s.%n" + "Please run following command locally to download a compatible version with the server:%n" + "%n" + " " + programName + " selfupdate %s%n", version, remoteVersion, remoteVersion)); } } return client; }
Source:
public void testGetTableDescriptorsWithNullAndEmptyList() throws IOException { try (Admin admin = getConnection().getAdmin()) { Exception actualError = null; try { HTableDescriptor[] descriptors = admin.getTableDescriptors(null); assertTrue(descriptors.length > 0); } catch (Exception e) { actualError = e; } assertNotNull(actualError); assertTrue(actualError instanceof NullPointerException); actualError = null; try { HTableDescriptor[] descriptors = admin.getTableDescriptors(ImmutableList.<String>of()); assertTrue(descriptors.length > 0); } catch (Exception e) { actualError = e; } assertNull(actualError); } }

Target:
public void testGetTableDescriptorsWithNullAndEmptyList() throws IOException { try (Admin admin = getConnection().getAdmin()) { Exception actualError = null; try { admin.getTableDescriptors(null); } catch (Exception e) { actualError = e; } assertNotNull(actualError); assertTrue(actualError instanceof NullPointerException); assertTrue(admin.getTableDescriptors(ImmutableList.<String>of()).length > 0); } }