auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected PlanNodeStatsEstimate visitInPredicate(InPredicate node, Void context) { if (!(node.getValueList() instanceof InListExpression) || !(node.getValue() instanceof SymbolReference)) { return visitExpression(node, context); } InListExpression inList = (InListExpression) node.getValueList(); PlanNodeStatsEstimate statsSum = inList.getValues().stream() .map(inValue -> process(new ComparisonExpression(EQUAL, node.getValue(), inValue))) .reduce(filterForFalseExpression(), PlanNodeStatsEstimateMath::addStatsAndSumDistinctValues); if (isNaN(statsSum.getOutputRowCount())) { return visitExpression(node, context); } Symbol inValueSymbol = Symbol.from(node.getValue()); SymbolStatsEstimate symbolStats = input.getSymbolStatistics(inValueSymbol); double notNullValuesBeforeIn = input.getOutputRowCount() * (1 - symbolStats.getNullsFraction()); SymbolStatsEstimate newSymbolStats = statsSum.getSymbolStatistics(inValueSymbol) .mapDistinctValuesCount(newDistinctValuesCount -> min(newDistinctValuesCount, symbolStats.getDistinctValuesCount())); return input.mapOutputRowCount(rowCount -> min(statsSum.getOutputRowCount(), notNullValuesBeforeIn)) .mapSymbolColumnStatistics(inValueSymbol, oldSymbolStats -> newSymbolStats); }

Target:
protected PlanNodeStatsEstimate visitInPredicate(InPredicate node, Void context) { if (!(node.getValue() instanceof SymbolReference) || !(node.getValueList() instanceof InListExpression)) { return visitExpression(node, context); } InListExpression inList = (InListExpression) node.getValueList(); PlanNodeStatsEstimate statsSum = inList.getValues().stream() .map(inValue -> process(new ComparisonExpression(EQUAL, node.getValue(), inValue))) .reduce(filterForFalseExpression(), PlanNodeStatsEstimateMath::addStatsAndSumDistinctValues); if (isNaN(statsSum.getOutputRowCount())) { return visitExpression(node, context); } Symbol inValueSymbol = Symbol.from(node.getValue()); SymbolStatsEstimate symbolStats = input.getSymbolStatistics(inValueSymbol); double notNullValuesBeforeIn = input.getOutputRowCount() * (1 - symbolStats.getNullsFraction()); SymbolStatsEstimate newSymbolStats = statsSum.getSymbolStatistics(inValueSymbol) .mapDistinctValuesCount(newDistinctValuesCount -> min(newDistinctValuesCount, symbolStats.getDistinctValuesCount())); return input.mapOutputRowCount(rowCount -> min(statsSum.getOutputRowCount(), notNullValuesBeforeIn)) .mapSymbolColumnStatistics(inValueSymbol, oldSymbolStats -> newSymbolStats); }
Source:
private void checkForNewDevices() { logger.debug("Refreshing bluetooth device list..."); Set<String> newAddresses = new HashSet<>(); List<tinyb.BluetoothDevice> tinybDevices = adapter.getDevices(); logger.debug("Found bluetooth devices.", tinybDevices.size()); synchronized (tinybDeviceCache) { tinybDeviceCache.clear(); tinybDevices.stream().forEach(d -> tinybDeviceCache.put(d.getAddress(), d)); } for (tinyb.BluetoothDevice tinybDevice : tinybDevices) { synchronized (devices) { newAddresses.add(tinybDevice.getAddress()); BlueZBluetoothDevice device = (BlueZBluetoothDevice) devices.get(tinybDevice.getAddress()); if (device == null) { createAndRegisterBlueZDevice(tinybDevice); } else { device.setTinybDevice(tinybDevice); notifyDiscoveryListeners(device); } } } synchronized (devices) { Set<String> oldAdresses = devices.keySet(); for (String address : oldAdresses) { if (!newAddresses.contains(address)) { devices.remove(address); } } } }

Target:
private void checkForNewDevices() { logger.debug("Refreshing Bluetooth device list..."); Set<String> newAddresses = new HashSet<>(); List<tinyb.BluetoothDevice> tinybDevices = adapter.getDevices(); logger.debug("Found Bluetooth devices.", tinybDevices.size()); synchronized (tinybDeviceCache) { tinybDeviceCache.clear(); tinybDevices.stream().forEach(d -> tinybDeviceCache.put(d.getAddress(), d)); } for (tinyb.BluetoothDevice tinybDevice : tinybDevices) { synchronized (devices) { newAddresses.add(tinybDevice.getAddress()); BlueZBluetoothDevice device = (BlueZBluetoothDevice) devices.get(tinybDevice.getAddress()); if (device == null) { createAndRegisterBlueZDevice(tinybDevice); } else { device.updateTinybDevice(tinybDevice); notifyDiscoveryListeners(device); } } } synchronized (devices) { Set<String> oldAdresses = devices.keySet(); for (String address : oldAdresses) { if (!newAddresses.contains(address)) { devices.remove(address); } } } }
Source:
public boolean isGeneratedSource(@NotNull VirtualFile file, @NotNull Project project) { AndroidProject androidProject = Projects.getAndroidProject(file, project); if (androidProject != null) { return VfsUtilCore.isAncestor(androidProject.getBuildFolder(), VfsUtilCore.virtualToIoFile(file), false); } return false; }

Target:
public boolean isGeneratedSource(@NotNull VirtualFile file, @NotNull Project project) { AndroidProject androidProject = Projects.getAndroidModel(file, project); if (androidProject != null) { return isAncestor(androidProject.getBuildFolder(), virtualToIoFile(file), false); } return false; }
Source:
public void testUploadWidget() { UploadWidget.startActivity(intentsTestRule.getActivity(), MainActivity.UPLOAD_WIDGET_REQUEST_CODE, new UploadWidget.LaunchOptions(UploadWidget.RequiredAction.START_NOW, Collections.singletonList(Uri.fromFile(assetFile)))); onView(withId(R.id.crop_action)).perform(click()); onView(withId(R.id.doneButton)).perform(click()); onView(withId(R.id.uploadFab)).perform(click()); }

Target:
public void testUploadWidget() { UploadWidget.startActivity(intentsTestRule.getActivity(), MainActivity.UPLOAD_WIDGET_REQUEST_CODE, new UploadWidget.Options(UploadWidget.Action.START_NOW, Collections.singletonList(Uri.fromFile(assetFile)))); onView(withId(R.id.crop_action)).perform(click()); onView(withId(R.id.doneButton)).perform(click()); onView(withId(R.id.uploadFab)).perform(click()); }
Source:
private static Document getIncludeDoc(String loc) throws Exception { Document doc = null; File locFile = null; if (loc.startsWith("http:") || loc.startsWith("https:")) { if (isValidURL(loc)) { URL url = new URL(loc); URLConnection connection = url.openConnection(); doc = getDocumentBuilder().parse(connection.getInputStream()); } } else if (loc.startsWith("file:")) { if (isValidURL(loc)) { locFile = new File(loc); if (locFile.exists()) { InputStream inputStream = new FileInputStream(locFile.getCanonicalPath()); doc = getDocumentBuilder().parse(inputStream); } } } else if (loc.startsWith("ftp:")) { } else { if (configDirectory != null && configDirectory.exists()) { locFile = new File(configDirectory, loc); if (locFile.exists()) { InputStream inputStream = new FileInputStream(locFile.getCanonicalPath()); doc = getDocumentBuilder().parse(inputStream); } } if (locFile == null || !locFile.exists()) { locFile = new File(getServerFile().getParentFile(), loc); InputStream inputStream = new FileInputStream(locFile.getCanonicalPath()); doc = getDocumentBuilder().parse(inputStream); } } return doc; }

Target:
private static Document getIncludeDoc(String loc) throws Exception { Document doc = null; File locFile = null; if (loc.startsWith("http:") || loc.startsWith("https:")) { if (isValidURL(loc)) { URL url = new URL(loc); URLConnection connection = url.openConnection(); doc = getDocumentBuilder().parse(connection.getInputStream()); } } else if (loc.startsWith("file:")) { if (isValidURL(loc)) { locFile = new File(loc); if (locFile.exists()) { InputStream inputStream = new FileInputStream(locFile.getCanonicalPath()); doc = getDocumentBuilder().parse(inputStream); } } } else if (loc.startsWith("ftp:")) { } else { locFile = new File(loc); if (locFile.isAbsolute()) { InputStream inputStream = new FileInputStream(locFile.getCanonicalPath()); doc = getDocumentBuilder().parse(inputStream); } else { if (configDirectory != null && configDirectory.exists()) { locFile = new File(configDirectory, loc); } if (locFile == null || !locFile.exists()) { locFile = new File(getServerFile().getParentFile(), loc); } if (locFile != null && locFile.exists()) { InputStream inputStream = new FileInputStream(locFile.getCanonicalPath()); doc = getDocumentBuilder().parse(inputStream); } } } return doc; }
Source:
public void removeOperatorsFromRoamingGroup() throws Exception { Object operatorID1 = operatorRepository.create(new NewOperator("name1", OperatorState.ACTIVE, "description1", "dName1", "fName1", "emergency")); Object operatorID2 = operatorRepository.create(new NewOperator("name2", OperatorState.ACTIVE, "description2", "dName2", "fName2", "emergency")); Object roamingGroupID = roamingRepository.create(new NewRoamingGroup("name", "description", RoamingGroupType.INTERNATIONAL)); roamingRepository.assignOperators(new ID(roamingGroupID), Lists.newArrayList(new ID(operatorID1), new ID(operatorID2))); List<ID> unnecessaryIDs = Lists.newArrayList(new ID(operatorID2)); roamingRepository.removeOperators(new ID(roamingGroupID), unnecessaryIDs); RoamingGroup got = roamingRepository.findById(new ID(roamingGroupID)).get(); Operator operator = new Operator(new ID(operatorID1), "name1", OperatorState.ACTIVE, "description1", "dName1", "fName1", "emergency"); RoamingGroup want = new RoamingGroup(new ID(roamingGroupID), "name", "description", RoamingGroupType.INTERNATIONAL, Lists.newArrayList(operator)); assertThat(got, deepEquals(want)); }

Target:
public void removeOperatorsFromRoamingGroup() throws Exception { Object operID1 = operatorRepository.create(new NewOperator("name1", OperatorState.ACTIVE, "description1", "dName1", "fName1", "emergency")); Object operID2 = operatorRepository.create(new NewOperator("name2", OperatorState.ACTIVE, "description2", "dName2", "fName2", "emergency")); Object groupID = roamingRepository.create(new NewRoamingGroup("name", "description", RoamingGroupType.INTERNATIONAL)); roamingRepository.assignOperators(new ID(groupID), Lists.newArrayList(new ID(operID1), new ID(operID2))); roamingRepository.removeOperators(new ID(groupID), Lists.newArrayList(new ID(operID2))); List<RoamingGroup> got = roamingRepository.findAll(); Operator operator = new Operator(new ID(operID1), "name1", OperatorState.ACTIVE, "description1", "dName1", "fName1", "emergency"); List<RoamingGroup> want = Lists.newArrayList(new RoamingGroup(new ID(groupID), "name", "description", RoamingGroupType.INTERNATIONAL, Lists.newArrayList(operator))); assertThat(got, deepEquals(want)); }
Source:
public static Pair<Long, TimeUnitConverter.TimeUnit> convert(long inValue, TimeUnit inUnit, TimeUnit outUnit) { if(inUnit.getOrder() < outUnit.getOrder()) { for(int i = outUnit.getOrder(); i > inUnit.getOrder(); i-- ) { inValue /= TimeUnit.timeUnits.get(i-1).getSecond(); } } else { for(int i = outUnit.getOrder(); i < inUnit.getOrder(); i++ ) { inValue *= TimeUnit.timeUnits.get(i).getSecond(); } } Pair<Long , TimeUnitConverter.TimeUnit> timePair = new Pair<Long, TimeUnitConverter.TimeUnit>(inValue, outUnit); return timePair; }

Target:
public static Pair<Long, TimeUnitConverter.TimeUnit> convert(long inValue, TimeUnit inUnit, TimeUnit outUnit) { if(inUnit.getOrder() < outUnit.getOrder()) { for(int i = outUnit.getOrder(); i > inUnit.getOrder(); i-- ) { inValue = inValue/TimeUnit.timeUnits.get(i-1).getSecond(); } } else { for(int i = outUnit.getOrder(); i < inUnit.getOrder(); i++ ) { inValue = inValue * TimeUnit.timeUnits.get(i).getSecond(); } } Pair<Long , TimeUnitConverter.TimeUnit> timePair = new Pair<Long, TimeUnitConverter.TimeUnit>(inValue, outUnit); return timePair; }
Source:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = new HashMap<String, String>(); jobProperties.put(VdcObjectType.VmTemplate.name().toLowerCase(), (getVmTemplateName() == null) ? "" : getVmTemplateName()); } return jobProperties; }

Target:
public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = new HashMap<String, String>(); jobProperties.put(VdcObjectType.VmTemplate.name().toLowerCase(), (getVmTemplateName() == null) ? "" : getVmTemplateName()); jobProperties.put(VdcObjectType.StoragePool.name().toLowerCase(), getStoragePoolName()); } return jobProperties; }
Source:
public void unselectsSelection() throws Exception { bot.radio("SWT.MULTI").click(); bot.checkBox("Listen").select(); bot.button("Clear").click(); tree = bot.treeInGroup("Tree"); tree.select(new int[] { 1 }); SWTBotText text = bot.textInGroup("Listeners"); bot.button("Clear").click(); tree.unselect(); assertEquals(0, tree.selectionCount()); assertEventMatches(text, "MouseDown [3]: MouseEvent{Tree time=-550222259 data=null button=1 stateMask=0x40000 x=0 y=0 count=1}"); assertEventMatches(text, "Selection [13]: SelectionEvent{Tree time=-550222256 data=null item=TreeItem {Node 2} detail=0 x=0 y=0 width=0 height=0 stateMask=0xc0000 text=null doit=true}"); assertEventMatches(text, "MouseUp [4]: MouseEvent{Tree time=-550222255 data=null button=1 stateMask=0xc0000 x=0 y=0 count=1}"); tree.select(new int[] { 1, 2 }); assertEquals(2, tree.selectionCount()); tree.select(new int[] {}); assertEquals(0, tree.selectionCount()); tree.select(new String[] { "Node 2", "Node 4" }); assertEquals(2, tree.selectionCount()); tree.select(new int[] {}); assertEquals(0, tree.selectionCount()); }

Target:
public void unselectsSelection() throws Exception { bot.radio("SWT.MULTI").click(); bot.checkBox("Listen").select(); bot.button("Clear").click(); tree = bot.treeInGroup("Tree"); tree.select(new int[] { 1 }); SWTBotText text = bot.textInGroup("Listeners"); bot.button("Clear").click(); tree.unselect(); assertEquals(0, tree.selectionCount()); assertEventMatches(text, "MouseDown [3]: MouseEvent{Tree time=0 data=null button=1 stateMask=0x40000 x=0 y=0 count=1}"); assertEventMatches(text, "Selection [13]: SelectionEvent{Tree time=0 data=null item=TreeItem {Node 2} detail=0 x=0 y=0 width=0 height=0 stateMask=0xc0000 text=null doit=true}"); assertEventMatches(text, "MouseUp [4]: MouseEvent{Tree time=0 data=null button=1 stateMask=0xc0000 x=0 y=0 count=1}"); }
Source:
public void load(Map<String, Object> parameters) { super.load(parameters); if ((objectClass = (String) parameters.get(OBJECT_CLASS)) == null) { throw new NullPointerException("Missing param [" + OBJECT_CLASS + "] in the setup"); } if (!isAlphanumeric(objectClass)) { throw new NullPointerException("object class '" + objectClass + "' contains non-alphanumeric characters"); } usernameCnPattern = Pattern.compile("(cn=[a-zA-Z_]+)"); LOGGER.log(Level.FINE, "LdapUser plugin loaded with objectclass={0}", objectClass); }

Target:
public void load(Map<String, Object> parameters) { super.load(parameters); if ((objectClass = (String) parameters.get(OBJECT_CLASS)) == null) { throw new NullPointerException("Missing param [" + OBJECT_CLASS + "] in the setup"); } if (!isAlphanumeric(objectClass)) { throw new NullPointerException("object class '" + objectClass + "' contains non-alphanumeric characters"); } LOGGER.log(Level.FINE, "LdapUser plugin loaded with objectclass={0}", objectClass); }
Source:
private void recordDroppedEvent(EntryEventImpl event) { final boolean isDebugEnabled = logger.isDebugEnabled(); if (this.eventProcessor != null) { this.eventProcessor.registerEventDroppedInPrimaryQueue(event); } else { EntryEventImpl emptyEvent = new EntryEventImpl(event.getKey(), false); emptyEvent.setRegion(event.getRegion()); emptyEvent.setTailKey(event.getTailKey()); tmpDroppedEvents.add(emptyEvent); if (isDebugEnabled) { logger.debug("added to tmpDroppedEvents event: {}", event); } } }

Target:
private void recordDroppedEvent(EntryEventImpl event) { if (this.eventProcessor != null) { this.eventProcessor.registerEventDroppedInPrimaryQueue(event); } else { tmpDroppedEvents.add(event); if (logger.isDebugEnabled()) { logger.debug("added to tmpDroppedEvents event: {}", event); } } }
Source:
private JdbcReadOptions getJdbcReadOptions(ReadableConfig readableConfig) { final Optional<String> partitionColumnName = readableConfig.getOptional(READ_PARTITION_COLUMN); final Optional<Long> partitionLower = readableConfig.getOptional(READ_PARTITION_LOWER_BOUND); final Optional<Long> partitionUpper = readableConfig.getOptional(READ_PARTITION_UPPER_BOUND); final Optional<Integer> numPartitions = readableConfig.getOptional(READ_PARTITION_NUM); final JdbcReadOptions.Builder builder = JdbcReadOptions.builder(); if (partitionColumnName.isPresent()) { builder.setPartitionColumnName(partitionColumnName.get()); builder.setPartitionLowerBound(partitionLower.get()); builder.setPartitionUpperBound(partitionUpper.get()); builder.setNumPartitions(numPartitions.get()); } readableConfig.getOptional(READ_FETCH_SIZE).ifPresent(builder::setFetchSize); return builder.build(); }

Target:
private JdbcReadOptions getJdbcReadOptions(ReadableConfig readableConfig) { final Optional<String> partitionColumnName = readableConfig.getOptional(SCAN_PARTITION_COLUMN); final JdbcReadOptions.Builder builder = JdbcReadOptions.builder(); if (partitionColumnName.isPresent()) { builder.setPartitionColumnName(partitionColumnName.get()); builder.setPartitionLowerBound(readableConfig.get(SCAN_PARTITION_LOWER_BOUND)); builder.setPartitionUpperBound(readableConfig.get(SCAN_PARTITION_UPPER_BOUND)); builder.setNumPartitions(readableConfig.get(SCAN_PARTITION_NUM)); } readableConfig.getOptional(SCAN_FETCH_SIZE).ifPresent(builder::setFetchSize); return builder.build(); }
Source:
private void queryInterfaces() { VDS vds = getEntity(); IdQueryParameters params = new IdQueryParameters(vds.getId()); params.setRefresh(false); Frontend.getInstance().runQuery(QueryType.GetVdsInterfacesByVdsId, params, new AsyncQuery<>((QueryReturnValue returnValue) -> { allExistingNics = returnValue.getReturnValue(); existingVlanDevicesByVlanId = mapVlanDevicesByVlanId(); initCreateOrUpdateBondParameters(); initNicLabelsParameters(); queryTLVInformations(); })); }

Target:
private void queryInterfaces() { VDS vds = getEntity(); IdQueryParameters params = new IdQueryParameters(vds.getId()); params.setRefresh(false); Frontend.getInstance().runQuery(QueryType.GetVdsInterfacesByVdsId, params, new AsyncQuery<>((QueryReturnValue returnValue) -> { allExistingNics = returnValue.getReturnValue(); existingVlanDevicesByVlanId = mapVlanDevicesByVlanId(); initCreateOrUpdateBondParameters(); initNicLabelsParameters(); queryTLVInformations(); queryNetworkAttachments(); })); }
Source:
public final void reloadConfig() { config.load(); money = _getMoney(); unlimited = _getUnlimited(); powertools = _getPowertools(); homes = _getHomes(); lastLocation = _getLastLocation(); lastTeleportTimestamp = _getLastTeleportTimestamp(); lastHealTimestamp = _getLastHealTimestamp(); jail = _getJail(); mails = _getMails(); teleportEnabled = _getTeleportEnabled(); godmode = _getGodModeEnabled(); muted = _getMuted(); muteTimeout = _getMuteTimeout(); muteReason = _getMuteReason (); jailed = _getJailed(); jailTimeout = _getJailTimeout(); lastLogin = _getLastLogin(); lastLogout = _getLastLogout(); lastLoginAddress = _getLastLoginAddress(); afk = _getAfk(); geolocation = _getGeoLocation(); isSocialSpyEnabled = _isSocialSpyEnabled(); isNPC = _isNPC(); arePowerToolsEnabled = _arePowerToolsEnabled(); kitTimestamps = _getKitTimestamps(); nickname = _getNickname(); ignoredPlayers = _getIgnoredPlayers(); logoutLocation = _getLogoutLocation(); lastAccountName = _getLastAccountName(); commandCooldowns = _getCommandCooldowns(); acceptingPay = _getAcceptingPay(); confirmPay = _getConfirmPay(); }

Target:
public final void reloadConfig() { config.load(); money = _getMoney(); unlimited = _getUnlimited(); powertools = _getPowertools(); homes = _getHomes(); lastLocation = _getLastLocation(); lastTeleportTimestamp = _getLastTeleportTimestamp(); lastHealTimestamp = _getLastHealTimestamp(); jail = _getJail(); mails = _getMails(); teleportEnabled = _getTeleportEnabled(); godmode = _getGodModeEnabled(); muted = _getMuted(); muteTimeout = _getMuteTimeout(); muteReason = _getMuteReason(); jailed = _getJailed(); jailTimeout = _getJailTimeout(); lastLogin = _getLastLogin(); lastLogout = _getLastLogout(); lastLoginAddress = _getLastLoginAddress(); afk = _getAfk(); geolocation = _getGeoLocation(); isSocialSpyEnabled = _isSocialSpyEnabled(); isNPC = _isNPC(); arePowerToolsEnabled = _arePowerToolsEnabled(); kitTimestamps = _getKitTimestamps(); nickname = _getNickname(); ignoredPlayers = _getIgnoredPlayers(); logoutLocation = _getLogoutLocation(); lastAccountName = _getLastAccountName(); commandCooldowns = _getCommandCooldowns(); acceptingPay = _getAcceptingPay(); confirmPay = _getConfirmPay(); confirmClear = _getConfirmClear(); }
Source:
public SavedHttpAttachment(String name, Map<String,Object> attachmentData, URI attachmentURI) throws IOException { super(name, (String)attachmentData.get("content_type"), Encoding.Plain); Boolean stub = (Boolean) attachmentData.get("stub"); Number length = (Number)attachmentData.get("length"); String digest = (String)attachmentData.get("digest"); String revpos = (String)attachmentData.get("revpos"); String data = (String)attachmentData.get("data"); if(!stub){ byte[] dataArray = data.getBytes(); InputStream is = Base64InputStreamFactory.get(new ByteArrayInputStream(dataArray)); this.data = IOUtils.toByteArray(is); } this.attachmentURI = attachmentURI; this.size = length.intValue(); }

Target:
public SavedHttpAttachment(String name, Map<String,Object> attachmentData, URI attachmentURI) throws IOException { super(name, (String)attachmentData.get("content_type"), Encoding.Plain); Boolean stub = (Boolean) attachmentData.get("stub"); Number length = (Number)attachmentData.get("length"); String data = (String)attachmentData.get("data"); if(!stub){ byte[] dataArray = data.getBytes(); InputStream is = Base64InputStreamFactory.get(new ByteArrayInputStream(dataArray)); this.data = IOUtils.toByteArray(is); } this.attachmentURI = attachmentURI; this.size = length.intValue(); }
Source:
public List<Object> next() { try { if (!resultSet.next()) { return null; } getObjects(results); return Arrays.asList(results); } catch (SQLException ex) { throw new DatabaseException("Failed to fetch next rows", ex); } }

Target:
public List<Object> next() { try { if (!resultSet.next()) { return null; } return getObjects(); } catch (SQLException ex) { throw new DatabaseException("Failed to fetch next rows", ex); } }
Source:
public String getStandardLeafName( String nodeName, HttpMessage msg, List<NameValuePair> params) { StringBuilder sb = new StringBuilder(); String method = msg.getRequestHeader().getMethod(); sb.append(method); sb.append(":"); sb.append(nodeName); sb.append(Session.getParamDisplayString(params, NameValuePair.TYPE_QUERY_STRING)); if (method.equalsIgnoreCase(HttpRequestHeader.POST)) { String contentType = msg.getRequestHeader().getHeader(HttpHeader.CONTENT_TYPE); if (contentType != null && contentType.startsWith("multipart/form-data")) { sb.append("(multipart/form-data)"); } else { sb.append(Session.getParamDisplayString(params, NameValuePair.TYPE_POST_DATA)); } } return sb.toString(); }

Target:
public String getStandardLeafName( String nodeName, HttpMessage msg, List<NameValuePair> params) { return Model.getSingleton() .getSession() .getLeafName( nodeName, msg.getRequestHeader().getMethod(), msg.getRequestHeader().getHeader(HttpHeader.CONTENT_TYPE), params); }
Source:
public @NonNull TmfModelResponse<@NonNull Map<@NonNull String, @NonNull String>> fetchTooltip(@NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) { ITmfStateSystem ss = getAnalysisModule().getStateSystem(); Map<@NonNull Long, @NonNull Integer> entries = getSelectedEntries(filter); Collection<@NonNull Integer> quarks = entries.values(); long start = filter.getStart(); if (ss == null || quarks.size() != 1 || !getAnalysisModule().isQueryable(start)) { return new TmfModelResponse<>(null, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); } int quark = quarks.iterator().next(); try { Map<String, String> retMap = null; ITmfStateInterval state = ss.querySingleState(start, quark); Object object = state.getValue(); if (object instanceof String) { retMap = Collections.singletonMap("value", object.toString()); } else { retMap = Collections.emptyMap(); } return new TmfModelResponse<>(retMap, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); } catch (StateSystemDisposedException e) { return new TmfModelResponse<>(null, ITmfResponse.Status.CANCELLED, CommonStatusMessage.TASK_CANCELLED); } }

Target:
public @NonNull TmfModelResponse<@NonNull Map<@NonNull String, @NonNull String>> fetchTooltip(@NonNull SelectionTimeQueryFilter filter, @Nullable IProgressMonitor monitor) { return new TmfModelResponse<>(null, ITmfResponse.Status.COMPLETED, CommonStatusMessage.COMPLETED); }
Source:
public boolean visit(MethodInvocation node) { if (isMethod(node, "android.view.View", "findViewById", "int")) { FindViewByIdItem item = new FindViewByIdItem(node); items.add(item); } return VISIT_SUBTREE; }

Target:
public boolean visit(MethodInvocation node) { if (isMethod(node, "android.view.View", "findViewById", "int")) { FindViewByIdItem item = new FindViewByIdItem(); if (item.setAssignment(node)) { items.add(item); } } return VISIT_SUBTREE; }
Source:
protected void commit(Expression expr) { Operation op = (Operation) input; Class container = (Class) input.eContainer(); if (op.getMethods().isEmpty()) { OpaqueBehavior ob = (OpaqueBehavior) ModelUtils.create(container, UMLPackage.Literals.OPAQUE_BEHAVIOR); ob.getBodies().add(expr.getBody()); ob.getLanguages().add(expr.getLanguage()); container.getOwnedBehaviors().add(ob); op.getMethods().add(ob); } else { OpaqueBehavior ob = (OpaqueBehavior) op.getMethods().get(0); int index = ob.getLanguages().indexOf(expr.getLanguage()); if (index == -1) { ob.getLanguages().add(expr.getLanguage()); ob.getBodies().add(expr.getBody()); } else { ob.getBodies().set(index, expr.getBody()); } } }

Target:
protected void commit(Expression expr) { Operation op = (Operation) input; Class container = (Class) input.eContainer(); if (op.getMethods().isEmpty()) { OpaqueBehavior ob = (OpaqueBehavior) ModelUtils.create(container, UMLPackage.Literals.OPAQUE_BEHAVIOR); ob.getBodies().add(expr.getBody()); ob.getLanguages().add(expr.getLanguage()); container.getOwnedBehaviors().add(ob); op.getMethods().add(ob); } else { OpaqueBehavior ob = (OpaqueBehavior) op.getMethods().get(0); int index = ob.getLanguages().indexOf(expr.getLanguage()); if (index == -1) { ob.getLanguages().add(expr.getLanguage()); index = ob.getLanguages().size() - 1; } int numFillBody = ob.getLanguages().size() - ob.getBodies().size(); while (numFillBody-- > 0) { ob.getBodies().add(""); } ob.getBodies().set(index, expr.getBody()); } }
Source:
public <C> Stream<Match> match(Object object, Captures captures, C context) { if (previous.isPresent()) { return previous.get().match(object, captures, context) .flatMap(match -> accept(object, match.captures(), context)); } else { return accept(object, captures, context); } }

Target:
public final <C> Stream<Match> match(Object object, Captures captures, C context) { if (previous.isPresent()) { return previous.get().match(object, captures, context) .flatMap(match -> accept(object, match.captures(), context)); } else { return accept(object, captures, context); } }
Source:
void doneWithIt() { synchronized (refCounts) { if (refCounts == 0) { pollingCache.close(); } refCounts -= 1; } }

Target:
void doneWithIt() { synchronized (refCounts) { if (refCounts.get() == 0) { pollingCache.close(); } refCounts.decrementAndGet(); } }
Source:
public QueryContext parseContext(HttpServletRequest request) throws QueryParseException { return new QueryContext( configFetcher.sourcesFor(request).or(ApplicationSources.DEFAULT_SOURCES), annotationExtractor.extractFromRequest(request), selectionBuilder.build(request) ); }

Target:
public QueryContext parseContext(HttpServletRequest request) throws QueryParseException { return new QueryContext( configFetcher.sourcesFor(request).or(ApplicationSources.defaults()), annotationExtractor.extractFromRequest(request), selectionBuilder.build(request) ); }
Source:
private void assertThatPostCanBeUnfollowed(PostDetailsPage page) { final PostActionsRow postActions = page.getPost().findNewestPost().findPostActions(); postActions.clickFollow(); sleepForOneSecond(); Assertion.assertFalse(postActions.isFollowed(), SHOULD_UNFOLLOW_MESSAGE); }

Target:
private void assertThatPostCanBeUnfollowed(PostDetailsPage page) { final PostActionsRow postActions = page.getPost().findNewestPost().findPostActions(); postActions.clickFollow(); Assertion.assertFalse(postActions.isFollowed(), SHOULD_UNFOLLOW_MESSAGE); }
Source:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { try { abvs.reset(); abvs.getDataOutput().write(ValueTag.JS_NULL_TAG); result.set(abvs); } catch (IOException e) { throw new SystemException(ErrorCode.SYSE0001, e); } }

Target:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { XDMConstants.setJsNull(result); }
Source:
public void handleEditPostResult(int resultCode, Intent data) { if (resultCode == RESULT_OK && data != null && isAdded()) { boolean hasChanges = data.getBooleanExtra(EditPostActivity.EXTRA_HAS_CHANGES, false); final long postId = data.getLongExtra(EditPostActivity.EXTRA_POSTID, -1); boolean isPublishable = data.getBooleanExtra(EditPostActivity.EXTRA_IS_PUBLISHABLE, false) && postId != -1; boolean savedLocally = data.getBooleanExtra(EditPostActivity.EXTRA_SAVED_AS_LOCAL_DRAFT, false); if (hasChanges) { if (!NetworkUtils.isNetworkAvailable(getActivity())) { ToastUtils.showToast(getActivity(), R.string.error_publish_no_network, ToastUtils.Duration.SHORT); } else { if (isPublishable) { if (savedLocally) { Snackbar.make(getActivity().findViewById(R.id.coordinator), R.string.editor_post_saved_locally_not_published, Snackbar.LENGTH_LONG) .setAction(R.string.button_publish, new View.OnClickListener() { @Override public void onClick(View v) { Post post = WordPress.wpDB.getPostForLocalTablePostId(postId); publishPost(post); } }).show(); } else { Snackbar.make(getActivity().findViewById(R.id.coordinator), R.string.editor_post_saved_online_not_published, Snackbar.LENGTH_LONG) .setAction(R.string.button_publish, new View.OnClickListener() { @Override public void onClick(View v) { Post post = WordPress.wpDB.getPostForLocalTablePostId(postId); publishPost(post); } }).show(); } } else { if (savedLocally) { ToastUtils.showToast(getActivity(), R.string.editor_post_saved_locally); } else { ToastUtils.showToast(getActivity(), R.string.editor_post_saved_online); } } } } } }

Target:
public void handleEditPostResult(int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && data != null && isAdded()) { boolean hasChanges = data.getBooleanExtra(EditPostActivity.EXTRA_HAS_CHANGES, false); final PostModel post = (PostModel)data.getSerializableExtra(EditPostActivity.EXTRA_POST); boolean isPublishable = post != null && PostUtils.isPublishable(post); boolean savedLocally = data.getBooleanExtra(EditPostActivity.EXTRA_SAVED_AS_LOCAL_DRAFT, false); if (hasChanges) { if (savedLocally && !NetworkUtils.isNetworkAvailable(getActivity())) { ToastUtils.showToast(getActivity(), R.string.error_publish_no_network, ToastUtils.Duration.SHORT); } else { if (isPublishable) { if (savedLocally) { Snackbar.make(getActivity().findViewById(R.id.coordinator), R.string.editor_post_saved_locally_not_published, Snackbar.LENGTH_LONG) .setAction(R.string.button_publish, new View.OnClickListener() { @Override public void onClick(View v) { publishPost(post); } }).show(); } else if (PostStatus.fromPost(post) == PostStatus.DRAFT) { Snackbar.make(getActivity().findViewById(R.id.coordinator), R.string.editor_post_saved_online_not_published, Snackbar.LENGTH_LONG) .setAction(R.string.button_publish, new View.OnClickListener() { @Override public void onClick(View v) { publishPost(post); } }).show(); } } else { if (savedLocally) { ToastUtils.showToast(getActivity(), R.string.editor_post_saved_locally); } else { ToastUtils.showToast(getActivity(), R.string.editor_post_saved_online); } } } } } }
Source:
void pollQueue() { int emitted = 0; do { counter.set(1); long produced = 0; long r = requested.get(); for (;;) { if (child.isUnsubscribed()) return; Throwable error; if (finished) { if ((error = this.error) != null) { queue.clear(); child.onError(error); return; } else if (queue.isEmpty()) { child.onCompleted(); return; } } if (r > 0) { Object o = queue.poll(); if (o != null) { child.onNext(on.getValue(o)); r--; emitted++; produced++; } else { break; } } else { break; } } if (produced > 0 && requested.get() != Long.MAX_VALUE) { requested.addAndGet(-produced); } } while (counter.decrementAndGet() > 0); if (emitted > 0) { request(emitted); } }

Target:
void pollQueue() { int emitted = 0; final AtomicLong localRequested = this.requested; final AtomicLong localCounter = this.counter; do { localCounter.set(1); long produced = 0; long r = localRequested.get(); for (;;) { if (child.isUnsubscribed()) return; Throwable error; if (finished) { if ((error = this.error) != null) { queue.clear(); child.onError(error); return; } else if (queue.isEmpty()) { child.onCompleted(); return; } } if (r > 0) { Object o = queue.poll(); if (o != null) { child.onNext(on.getValue(o)); r--; emitted++; produced++; } else { break; } } else { break; } } if (produced > 0 && localRequested.get() != Long.MAX_VALUE) { localRequested.addAndGet(-produced); } } while (localCounter.decrementAndGet() > 0); if (emitted > 0) { request(emitted); } }
Source:
public void cancel() throws InterruptedException { super.cancel(); info("Cancel called. Killing the launched MR jobs on the cluster"); String azExecId = jobProps.getString("azkaban.flow.execid"); final String logFilePath = String.format("%s/_job.%s.%s.log", getWorkingDirectory(), azExecId, getId()); info("log file path is: " + logFilePath); HadoopJobUtils.proxyUserKillAllSpawnedHadoopJobs(logFilePath, jobProps, tokenFile, getLog()); }

Target:
public void cancel() throws InterruptedException { super.cancel(); info("Cancel called. Killing the launched MR jobs on the cluster"); String azExecId = jobProps.getString(CommonJobProperties.EXEC_ID); final String logFilePath = String.format("%s/_job.%s.%s.log", getWorkingDirectory(), azExecId, getId()); info("log file path is: " + logFilePath); HadoopJobUtils.proxyUserKillAllSpawnedHadoopJobs(logFilePath, jobProps, tokenFile, getLog()); }
Source:
protected void validateRackAwareness() { if (dataNodes.size() > 0) { Iterator<DataNode> dataNodeIter = dataNodes.iterator(); boolean lastHasRackId = dataNodeIter.next().hasRackId(); while (dataNodeIter.hasNext()) { boolean currHasRackId = dataNodeIter.next().hasRackId(); if (lastHasRackId != currHasRackId) { throw new IllegalStateException("dataNodes in datacenter must all have defined rack IDs or none at all"); } lastHasRackId = currHasRackId; } this.rackAware = lastHasRackId; } }

Target:
private void validateRackAwareness() { if (dataNodes.size() > 0) { Iterator<DataNode> dataNodeIter = dataNodes.iterator(); boolean hasRackId = (dataNodeIter.next().getRackId() >= 0); while (dataNodeIter.hasNext()) { if (hasRackId != (dataNodeIter.next().getRackId() >= 0)) { throw new IllegalStateException("dataNodes in datacenter: " + name + " must all have defined rack IDs or none at all"); } } this.rackAware = hasRackId; } }
Source:
public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { if (!(node instanceof AggregationNode)) { return Optional.empty(); } AggregationNode parent = (AggregationNode) node; Map<Symbol, AggregationNode.Aggregation> assignments = parent.getAggregations(); if (assignments.size() == 0 || assignments.size() > 1) { return Optional.empty(); } for (Map.Entry<Symbol, AggregationNode.Aggregation> entry : assignments.entrySet()) { AggregationNode.Aggregation aggregation = entry.getValue(); requireNonNull(aggregation, "aggregation is null"); Signature signature = aggregation.getSignature(); FunctionCall functionCall = aggregation.getCall(); if (!"count".equals(signature.getName()) || !functionCall.getArguments().isEmpty()) { return Optional.empty(); } } PlanNode child = lookup.resolve(parent.getSource()); if (!(child instanceof AggregationNode)) { return Optional.empty(); } if (ScalarQueryUtil.isScalar(child, lookup)) { return Optional.of(new ValuesNode(node.getId(), node.getOutputSymbols(), ImmutableList.of(ImmutableList.of(new LongLiteral("1"))))); } return Optional.empty(); }

Target:
public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { AggregationNode parent = (AggregationNode) node; Map<Symbol, AggregationNode.Aggregation> assignments = parent.getAggregations(); if (parent.hasDefaultOutput() && assignments.size() != 1) { return Optional.empty(); } for (Map.Entry<Symbol, AggregationNode.Aggregation> entry : assignments.entrySet()) { AggregationNode.Aggregation aggregation = entry.getValue(); requireNonNull(aggregation, "aggregation is null"); Signature signature = aggregation.getSignature(); FunctionCall functionCall = aggregation.getCall(); if (!"count".equals(signature.getName()) || !functionCall.getArguments().isEmpty()) { return Optional.empty(); } } if (!assignments.isEmpty() && isScalar(parent.getSource(), lookup)) { return Optional.of(new ValuesNode(node.getId(), node.getOutputSymbols(), ImmutableList.of(ImmutableList.of(new LongLiteral("1"))))); } return Optional.empty(); }
Source:
public void broadcastIntent(Intent intent, String permission) throws IOException, JadbException { List<String> args = new ArrayList<>(); args.add("broadcast"); intent.generate(args); if(permission != null){ args.add("--receiver-permission"); args.add(permission); } InputStream stream = device.executeShell("am", args.toArray(new String[args.size()])); int i; do{ i = stream.read(); } while (i != -1); stream.close(); }

Target:
public void broadcastIntent(Intent intent, String permission) throws IOException, JadbException { List<String> args = new ArrayList<>(); args.add("broadcast"); intent.generate(args); if (permission != null) { args.add("--receiver-permission"); args.add(permission); } try (InputStream stream = device.executeShell("am", args.toArray(new String[args.size()]))) { Stream.flushRead(stream); } }
Source:
public void should_get_black_cat_count_by_using_group_by_and_having() { final long expectedBlackCatCount = 6L; final long actualBlackCatCount = query().from(cat) .select(catEntity.name.count()) .groupBy(catEntity.color) .having(catEntity.name.count().goe(1)) .fetchOne(); assertEquals(expectedBlackCatCount, actualBlackCatCount); }

Target:
public void should_get_black_cat_count_by_using_group_by_and_having() { final long expectedTabbyCatCount = 2L; final Cat tabbyColorCatFoo = new Cat("Foo", 7, Color.TABBY); final Cat tabbyColorCatBar = new Cat("Bar", 8, Color.TABBY); insertEntitiesForTest(Arrays.asList(tabbyColorCatFoo, tabbyColorCatBar)); final long actualTabbyCatCount = query().from(cat) .select(catEntity.name.count()) .groupBy(catEntity.color) .having(catEntity.name.count().eq(2L)) .fetchOne(); removeEntitiesForTest(Arrays.asList(tabbyColorCatFoo, tabbyColorCatBar)); assertEquals(expectedTabbyCatCount, actualTabbyCatCount); }
Source:
public Saveable[] getSaveables() { if (!hasSaveablesProvider()) { ISaveablePart saveablePart = getSite().getPage().getActiveEditor(); if (saveablePart instanceof ISaveablesSource) { return ((ISaveablesSource) saveablePart).getSaveables(); } } return super.getSaveables(); }

Target:
public Saveable[] getSaveables() { if (!hasSaveablesProvider()) { IEditorPart saveablePart = getSite().getPage().getActiveEditor(); return saveablePart instanceof ISaveablesSource ? ((ISaveablesSource) saveablePart).getSaveables() : new Saveable[] { new DefaultSaveable(saveablePart) }; } return super.getSaveables(); }
Source:
public boolean shouldDisplay() throws IOException, ServletException { if (!Functions.hasPermission(Jenkins.ADMINISTER)) { return false; } if (getActiveAdministrativeMonitorsCount() == 0) { return false; } StaplerRequest req = Stapler.getCurrentRequest(); if (req == null) { return false; } List<Ancestor> ancestors = req.getAncestors(); if (ancestors == null || ancestors.size() == 0) { return false; } Ancestor a = ancestors.get(ancestors.size() - 1); Object o = a.getObject(); if (o instanceof HudsonIsLoading) { return false; } if (o instanceof HudsonIsRestarting) { return false; } if (o instanceof Jenkins) { String url = a.getRestOfUrl(); if (ignoredJenkinsRestOfUrls.contains(url)) { return false; } } return true; }

Target:
public boolean shouldDisplay() throws IOException, ServletException { if (!Functions.hasPermission(Jenkins.ADMINISTER)) { return false; } StaplerRequest req = Stapler.getCurrentRequest(); if (req == null) { return false; } List<Ancestor> ancestors = req.getAncestors(); if (ancestors == null || ancestors.size() == 0) { return false; } Ancestor a = ancestors.get(ancestors.size() - 1); Object o = a.getObject(); if (o instanceof HudsonIsLoading) { return false; } if (o instanceof HudsonIsRestarting) { return false; } if (o instanceof Jenkins) { String url = a.getRestOfUrl(); if (ignoredJenkinsRestOfUrls.contains(url)) { return false; } } if (getActiveAdministrativeMonitorsCount() == 0) { return false; } return true; }
Source:
public Response getAllSchemaVersions(@PathParam("schemaName") String schemaName, @Context SecurityContext securityContext) { try { LOG.info("Get all versions for schema : {}", schemaName); Collection<SchemaVersionInfo> schemaVersionInfos = schemaRegistryClient.getAllVersions(schemaName); Collection<String> schemaVersions = new ArrayList<>(); if (schemaVersionInfos != null && !schemaVersionInfos.isEmpty()) { LOG.debug("######### Received schema versions from schema registry: {}", schemaVersionInfos); for (SchemaVersionInfo schemaVersionInfo: schemaVersionInfos) { schemaVersions.add(schemaVersionInfo.getVersion().toString()); } return WSUtils.respondEntities(schemaVersions, OK); } else { LOG.debug("######### Received null response for schema versions from schema registry for schema: {}", schemaName); return WSUtils.respondEntity(schemaVersions, NOT_FOUND); } } catch (SchemaNotFoundException e) { LOG.error("Schema not found: [{}]", schemaName, e); throw EntityNotFoundException.byId(schemaName); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public Response getAllSchemaVersions(@PathParam("schemaName") String schemaName, @Context SecurityContext securityContext) { try { LOG.info("Get all versions for schema : {}", schemaName); Collection<SchemaVersionInfo> schemaVersionInfos = schemaRegistryClient.getAllVersions(schemaName); Collection<String> schemaVersions = new ArrayList<>(); if (schemaVersionInfos != null && !schemaVersionInfos.isEmpty()) { LOG.debug("######### Received schema versions from schema registry: {}", schemaVersionInfos); for (SchemaVersionInfo schemaVersionInfo: schemaVersionInfos) { schemaVersions.add(schemaVersionInfo.getVersion().toString()); } return WSUtils.respondEntities(schemaVersions, OK); } else { LOG.debug("######### Received null response for schema versions from schema registry for schema: {}", schemaName); return WSUtils.respondEntity(schemaVersions, NOT_FOUND); } } catch (SchemaNotFoundException e) { LOG.error("Schema not found: [{}]", schemaName, e); throw EntityNotFoundException.byName(schemaName); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public MessageChannel getDiscardChannel() { String channelName = this.discardChannelName; if (channelName != null) { this.discardChannel = getChannelResolver().resolveDestination(channelName); this.discardChannelName = null; } return this.discardChannel; }

Target:
public MessageChannel getDiscardChannel() { if (this.discardChannel == null) { String channelName = this.discardChannelName; if (channelName != null) { this.discardChannel = getChannelResolver().resolveDestination(channelName); this.discardChannelName = null; } } return this.discardChannel; }
Source:
public void setPictureAs(OCFile file) { if (file != null){ if (file.isDown()) { File externalFile = new File(file.getStoragePath()); Uri sendUri = Uri.fromFile(externalFile); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setDataAndType(sendUri, file.getMimetype()); intent.putExtra("mimeType", file.getMimetype()); mFileActivity.startActivityForResult(Intent.createChooser(intent, "Set As"), 200); } else { } } else { Log_OC.wtf(TAG, "Trying to send a NULL OCFile"); } }

Target:
public void setPictureAs(OCFile file) { if (file != null){ if (file.isDown()) { File externalFile = new File(file.getStoragePath()); Uri sendUri = Uri.fromFile(externalFile); Intent intent = new Intent(Intent.ACTION_ATTACH_DATA); intent.setDataAndType(sendUri, file.getMimetype()); intent.putExtra("mimeType", file.getMimetype()); mFileActivity.startActivityForResult(Intent.createChooser(intent, mFileActivity.getString(R.string.set_as)), 200); } else { } } else { Log_OC.wtf(TAG, "Trying to send a NULL OCFile"); } }
Source:
public void protocolTypesTestCase() throws IOException, InterruptedException, InternalServerException { BrokerManagerService brokerManagerService = mock(BrokerManagerService.class); List<String> protocolsList = new ArrayList<>(); protocolsList.add("amqp-v1.0"); protocolsList.add("mqtt-v3.1.1"); Protocols protocols = new Protocols(); protocols.setProtocol(protocolsList); when(brokerManagerService.getSupportedProtocols()).thenReturn(protocols); mbRESTService.setBrokerManagerService(brokerManagerService); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(Constants.BASE_URL + "/protocol-types"); getRequest.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); HttpResponse response = httpClient.execute(getRequest); HttpEntity responseEntity = response.getEntity(); String content = StringUtils.EMPTY; if (responseEntity != null) { content = EntityUtils.toString(responseEntity); } Assert.assertTrue(content != null && content.contains("amqp-v1.0") && content.contains("mqtt-v3.1.1"), "Unexpected protocols"); Assert.assertEquals(response.getStatusLine().getStatusCode(), Response.Status.OK.getStatusCode(), "200 not received"); httpClient.getConnectionManager().shutdown(); }

Target:
public void protocolTypesTestCase() throws IOException, InterruptedException, InternalServerException { BrokerManagerService brokerManagerService = mock(BrokerManagerService.class); List<String> protocolsList = new ArrayList<>(); protocolsList.add("amqp-v0.91"); Protocols protocols = new Protocols(); protocols.setProtocol(protocolsList); when(brokerManagerService.getSupportedProtocols()).thenReturn(protocols); mbRESTService.setBrokerManagerService(brokerManagerService); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(Constants.BASE_URL + "/protocol-types"); getRequest.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); HttpResponse response = httpClient.execute(getRequest); HttpEntity responseEntity = response.getEntity(); String content = StringUtils.EMPTY; if (responseEntity != null) { content = EntityUtils.toString(responseEntity); } Assert.assertTrue(content != null && content.contains("amqp-v0.91"), "Unexpected protocols"); Assert.assertEquals(response.getStatusLine().getStatusCode(), Response.Status.OK.getStatusCode(), "200 not received"); httpClient.getConnectionManager().shutdown(); }