auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void dispose() { super.dispose(); if (this.tabFolder != null) { this.tabFolder.dispose(); this.tabFolder = null; } tabItems.clear(); for (ModelExplorerTabDescriptor tabDescriptor : ModelExplorerTabRegistry.getRegisteredExtensions()) { IModelExplorerTabExtension tab = tabDescriptor.getTabExtension(); if (tab != null) { tab.dispose(); } } if (permissionAuthoritySessionManagerListener != null) { SessionManager.INSTANCE.removeSessionsListener(permissionAuthoritySessionManagerListener); permissionAuthoritySessionManagerListener = null; <START> } <END> }</code><technical_language>refreshJob field set null dispose</technical_language>

Target:
public void dispose() { super.dispose(); if (this.tabFolder != null) { this.tabFolder.dispose(); this.tabFolder = null; } tabItems.clear(); for (ModelExplorerTabDescriptor tabDescriptor : ModelExplorerTabRegistry.getRegisteredExtensions()) { IModelExplorerTabExtension tab = tabDescriptor.getTabExtension(); if (tab != null) { tab.dispose(); } } lockDecorationUpdater.unregister(); }
Source:
<code>public Analyzer wrapNormalizer(String name, Analyzer normalizer) { <START> return new HibernateSearchNormalizerWrapper( normalizer, name ); <END> }</code><technical_language>Minor nitpicking weird order of parameters reversed 2 lines</technical_language>

Target:
public Analyzer wrapNormalizer(String name, Analyzer normalizer) { return new HibernateSearchNormalizerWrapper( name, normalizer ); }
Source:
<code>public void unmarksResidueIfClientGoesAway() { List<Integer> firstResponse = allocator.getRelevantModuli(KEY); time.addAndGet(5_000_000L); <START> allocator.loadingCache.cleanUp(); <END> allocator.getRelevantModuli(KEY); verify(generator, times(2)).getAndMarkResidue(); verify(generator, times(1)).unmarkResidue(Iterables.getOnlyElement(firstResponse)); verifyNoMoreInteractions(generator); }</code><technical_language>need do this, (imo) incorrect for cache return expired evicting yet. checked, do this either</technical_language>

Target:
public void unmarksResidueIfClientGoesAway() { List<Integer> firstResponse = allocator.getRelevantModuli(KEY); time.addAndGet(5_000_000L); allocator.getRelevantModuli(KEY); scheduler.runUntilIdle(); verify(generator, times(2)).getAndMarkResidue(); verify(generator, times(1)).unmarkResidue(Iterables.getOnlyElement(firstResponse)); verifyNoMoreInteractions(generator); }
Source:
<code>public Object returnValue() { <START> throw new SlimError(SlimError.extractSlimMessage(conversionException.getMessage())+ "\nTryed to invoke: " + methodName, conversionException, "", true); <END> }</code><technical_language>suggestion throw new SlimError(SlimError.extractSlimMessage(conversionException.getMessage())+ "\nTried invoke: " + methodName, conversionException, "", true); This impact unit tests</technical_language>

Target:
public Object returnValue() { throw new SlimError(SlimError.extractSlimMessage(conversionException.getMessage())+ "\nTried to invoke: " + methodName, conversionException, "", true); }
Source:
<code>private static boolean publishFiles(Collection collection, CollectionReader collectionReader, String encryptionPassword, String userEmail) throws IOException { boolean filesPublished = false; try { <START> collection.description.publishStartDate = new Date(); <END> SendFilteredCollectionFiles(collection, collectionReader, encryptionPassword); filesPublished = CommitPublish(collection, userEmail, encryptionPassword); } catch (IOException e) { SlackNotification.alarm(String.format("Exception publishing collection: %s: %s", collection.description.name, e.getMessage())); logError(e, "exception publishing collection").collectionName(collection).log(); Map<String, String> publishTransactionIds = collection.description.publishTransactionIds; if (publishTransactionIds != null && publishTransactionIds.size() > 0) { logInfo("attempting rollback of collection publishing transaction").collectionName(collection).log(); rollbackPublish(publishTransactionIds, encryptionPassword); } } finally { collection.save(); } return filesPublished; }</code><technical_language>collection.getDescription() if exists</technical_language>

Target:
private static boolean publishFiles(Collection collection, CollectionReader collectionReader, String encryptionPassword, String userEmail) throws IOException { boolean filesPublished = false; try { collection.getDescription().publishStartDate = new Date(); SendFilteredCollectionFiles(collection, collectionReader, encryptionPassword); filesPublished = CommitPublish(collection, userEmail, encryptionPassword); } catch (IOException e) { SlackNotification.alarm(String.format("Exception publishing collection: %s: %s", collection.getDescription().getName(), e.getMessage())); logError(e, "exception publishing collection").collectionName(collection).log(); Map<String, String> publishTransactionIds = collection.getDescription().publishTransactionIds; if (publishTransactionIds != null && publishTransactionIds.size() > 0) { logInfo("attempting rollback of collection publishing transaction") .collectionName(collection) .addParameter("transaction_ids", publishTransactionIds) .log(); rollbackPublish(publishTransactionIds, encryptionPassword); } } finally { collection.save(); } return filesPublished; }
Source:
<code>private PopupContextTreeMenu getPopupContextTreeMenuDelete() { if (popupContextTreeMenuDelete == null) { popupContextTreeMenuDelete = new PopupContextTreeMenu(); popupContextTreeMenuDelete.setAction( new DeleteContextAction() { private static final long serialVersionUID = 1L; @Override <START> protected ArrayList<Context> getContexts() { <END> ArrayList<Context> contexts = new ArrayList<Context>(); for (Integer id : popupContextTreeMenuDelete.getContextIds()) { contexts.add(Model.getSingleton().getSession().getContext(id)); } return contexts; } }); popupContextTreeMenuDelete.setText(Constant.messages.getString("context.delete.popup")); } return popupContextTreeMenuDelete; }</code><technical_language>This change is binary compatible</technical_language>

Target:
private PopupContextTreeMenu getPopupContextTreeMenuDelete() { if (popupContextTreeMenuDelete == null) { popupContextTreeMenuDelete = new PopupContextTreeMenu(); popupContextTreeMenuDelete.setAction( new DeleteContextAction() { private static final long serialVersionUID = 1L; @Override protected List<Context> getContexts() { List<Context> contexts = new ArrayList<Context>(); for (Integer id : popupContextTreeMenuDelete.getContextIds()) { contexts.add(Model.getSingleton().getSession().getContext(id)); } return contexts; } @Override protected Context getContext() { return Model.getSingleton() .getSession() .getContext(popupContextTreeMenuDelete.getContextId()); } }); popupContextTreeMenuDelete.setText(Constant.messages.getString("context.delete.popup")); } return popupContextTreeMenuDelete; }
Source:
<code>private void proceedGuaranteedMemoryCheck() { for (VmInternalData vmInternalData : _runningVms.values()) { VM savedVm = _vmDict.get(vmInternalData.getVmDynamic().getId()); VmStatistics vmStatistics = vmInternalData.getVmStatistics(); if (vmStatistics.getCurrentMemory() != null && vmStatistics.getCurrentMemory() > 0 && savedVm.getMinAllocatedMem() > vmStatistics.getCurrentMemory() / TO_MEGA_BYTES) { AuditLogableBase auditLogable = new AuditLogableBase(); auditLogable.addCustomValue("VmName", savedVm.getName()); auditLogable.addCustomValue("VdsName", this._vds.getName()); auditLogable.addCustomValue("MemGuaranteed", String.valueOf(savedVm.getMinAllocatedMem())); <START> auditLogable.addCustomValue("MemActual", vmStatistics.getCurrentMemory().toString()); <END> auditLog(auditLogable, AuditLogType.VM_MEMORY_UNDER_GUARANTEED_VALUE); } } }</code><technical_language>i this is in MB in message MB, no</technical_language>

Target:
private void proceedGuaranteedMemoryCheck() { for (VmInternalData vmInternalData : _runningVms.values()) { VM savedVm = _vmDict.get(vmInternalData.getVmDynamic().getId()); VmStatistics vmStatistics = vmInternalData.getVmStatistics(); if (vmStatistics.getCurrentMemory() != null && vmStatistics.getCurrentMemory() > 0 && savedVm.getMinAllocatedMem() > vmStatistics.getCurrentMemory() / TO_MEGA_BYTES) { AuditLogableBase auditLogable = new AuditLogableBase(); auditLogable.addCustomValue("VmName", savedVm.getName()); auditLogable.addCustomValue("VdsName", this._vds.getName()); auditLogable.addCustomValue("MemGuaranteed", String.valueOf(savedVm.getMinAllocatedMem())); auditLogable.addCustomValue("MemActual", Long.toString((vmStatistics.getCurrentMemory() / TO_MEGA_BYTES))); auditLog(auditLogable, AuditLogType.VM_MEMORY_UNDER_GUARANTEED_VALUE); } } }
Source:
<code>public String createMachine( TargetHandlerParameters parameters ) throws TargetException { if(ipTable == null && parameters != null && parameters.getTargetProperties() != null) { String ips = parameters.getTargetProperties().get(IP_ADDRESSES); if(ips != null) { String iplist[] = ips.trim().split("\\s*,\\s*"); for(String ip : iplist) { <START> if(ipTable == null) ipTable = new HashMap<>(); <END> ipTable.put(ip, false); } } } String machineId = parameters.getScopedInstancePath() + " (" + TARGET_ID + ")"; this.machineIdToRunning.put( machineId, "" ); return machineId; }</code><technical_language>This line useless if iPtable initialized in class new HashMap<>( 0 )</technical_language>

Target:
public String createMachine( TargetHandlerParameters parameters ) throws TargetException { if(parameters != null && parameters.getTargetProperties() != null) { String ips = parameters.getTargetProperties().get(IP_ADDRESSES); if(ips != null) { String iplist[] = ips.trim().split("\\s*,\\s*"); for(String ip : iplist) ipTable.put(ip, false); } } String machineId = parameters.getScopedInstancePath() + " (" + TARGET_ID + ")"; this.machineIdToIp.put( machineId, "" ); return machineId; }
Source:
<code>public void shouldCallHtmlEscape() throws OperationException { Map<String, Object> params = new HashMap<>(); <START> params.put("script", "Context.htmlEscape = Fn.htmlEscape(\" cou&cou \");"); <END> try (OperationContext ctx = new OperationContext()) { automationService.run(ctx, "RunScript", params); assertEquals(" cou&amp;cou ", ctx.get("htmlEscape")); } }</code><technical_language>Map.of method build map</technical_language>

Target:
public void shouldCallHtmlEscape() throws OperationException { Map<String, Object> params = Map.of("script", "Context.htmlEscape = Fn.htmlEscape(\" cou&cou \");"); try (OperationContext ctx = new OperationContext()) { automationService.run(ctx, "RunScript", params); assertEquals(" cou&amp;cou ", ctx.get("htmlEscape")); } }
Source:
<code><START> public IOWorkers.Selector getWorkerSelector() { <END> return workerSelector; }</code><technical_language>@clevertension do need expose IOWorkers.Selector? completely unnecessary me</technical_language>

Target:
IOWorkers.Selector getWorkerSelector() { return workerSelector; }
Source:
<code>public void tradePerformed(Order order, double matchPrice) throws StockMarketExpection { if (order instanceof BuyOrder) { this.cashInHand -= matchPrice * order.getSize(); position.add(order); ordersPlaced.remove(order); } else { for (int i = 0; i < position.size(); i++){ if (order == ordersPlaced.get(i)){ if(order.getSize() != <START> position.get(i).getSize() ){ <END> this.cashInHand += matchPrice * order.getSize(); ordersPlaced.remove(order); return; } } } this.cashInHand += matchPrice * order.getSize(); position.remove(order); ordersPlaced.remove(order); } }</code><technical_language>message chain</technical_language>

Target:
public void tradePerformed(Order order, double matchPrice) throws StockMarketExpection { if (order instanceof BuyOrder) { this.cashInHand -= matchPrice * order.getSize(); position.add(order); ordersPlaced.remove(order); } else { for (int i = 0; i < position.size(); i++){ int place = ordersPlaced.get(i); if (order == place){ if(order.getSize() != position.get(i).getSize() ){ this.cashInHand += matchPrice * order.getSize(); ordersPlaced.remove(order); return; } } } this.cashInHand += matchPrice * order.getSize(); position.remove(order); ordersPlaced.remove(order); } }
Source:
<code>public OpenTSDBRateOption(RateOptions rateOptions) { if (null != rateOptions) { if (null != rateOptions.getCounter()) { counter = rateOptions.getCounter(); } if (null != rateOptions.getCounterMax()) { counterMax = rateOptions.getCounterMax(); } if (null != rateOptions.getResetThreshold()) { resetValue = rateOptions.getResetThreshold(); } if (null != rateOptions.getDropResets()) { dropResets = rateOptions.getDropResets(); } <START> else if ((counterMax == Long.MAX_VALUE) && (resetValue == 0)) { <END> dropResets = true; } } }</code><technical_language>for defaults instead of for set in passed in rateOptions</technical_language>

Target:
public OpenTSDBRateOption(RateOptions rateOptions) { if (null != rateOptions) { if (null != rateOptions.getCounter()) { counter = rateOptions.getCounter(); } if (null != rateOptions.getCounterMax()) { counterMax = rateOptions.getCounterMax(); } if (null != rateOptions.getResetThreshold()) { resetValue = rateOptions.getResetThreshold(); } if (null != rateOptions.getDropResets()) { dropResets = rateOptions.getDropResets(); } else if ((null != rateOptions.getCounterMax()) && (null != rateOptions.getResetThreshold())) { dropResets = false; } else if ((counterMax == Long.MAX_VALUE) && (resetValue == 0)) { dropResets = true; } } }
Source:
<code>public void registerErrorPages(ErrorPageRegistry registry) { registry.addErrorPages( <START> new ErrorPage(HttpStatus.FORBIDDEN, "/error/status-code"), <END> new ErrorPage(HttpStatus.NOT_FOUND, SiteUrl.NOT_FOUND_PAGE), new ErrorPage(RequestRejectedException.class, SiteUrl.NOT_FOUND_PAGE), new ErrorPage(Exception.class, SiteUrl.INTERNAL_ERROR_PAGE) ); }</code><technical_language>This change is incorrect, please, revert</technical_language>

Target:
public void registerErrorPages(ErrorPageRegistry registry) { registry.addErrorPages( new ErrorPage(HttpStatus.FORBIDDEN, SiteUrl.FORBIDDEN_PAGE), new ErrorPage(HttpStatus.NOT_FOUND, SiteUrl.NOT_FOUND_PAGE), new ErrorPage(RequestRejectedException.class, SiteUrl.NOT_FOUND_PAGE), new ErrorPage(Exception.class, SiteUrl.INTERNAL_ERROR_PAGE) ); }
Source:
<code>public boolean write(int addr, WR3223Commands command, String data) throws IOException { if (data == null || data.length() > 6 || data.length() == 0) { throw new IllegalArgumentException("Not valid data format."); } if (inputStream.available() > 0) { inputStream.skipBytes(inputStream.available()); } byte[] message = new byte[10 + data.length()]; message[0] = EOT; setControllerAddressToMessage(message, addr, 1); message[5] = STX; setCommandToMessage(message, command, 6); byte[] d = data.getBytes(); for (int ii = 0; ii < data.length(); ii++) { message[8 + ii] = d[ii]; } message[message.length - 2] = ETX; byte chkSum = (byte) buildCheckSum(message, 6, message.length - 2); message[message.length - 1] = chkSum; outputStream.write(message); outputStream.flush(); if (logger.isDebugEnabled()) { logger.debug("Write data: {}", bytesToHexString(message)); } if (waitUntilDataAvailable(1, 5000l)) { int answer = inputStream.readByte(); if (logger.isDebugEnabled()) { logger.debug("Answer from WR3223 {}.", Integer.toHexString(answer)); } if (answer == ACK) { return true; } logger.error("Command with data not accepted.", command.name(), data); } else { <START> logger.error("Timout. No answer for command with data {}.", command.name(), data); <END> } return false; }</code><technical_language>"Timeout"</technical_language>

Target:
public boolean write(int addr, WR3223Commands command, String data) throws IOException { if (data == null || data.length() > 6 || data.length() == 0) { throw new IllegalArgumentException("Not valid data format."); } if (inputStream.available() > 0) { inputStream.skipBytes(inputStream.available()); } byte[] message = new byte[10 + data.length()]; message[0] = EOT; setControllerAddressToMessage(message, addr, 1); message[5] = STX; setCommandToMessage(message, command, 6); byte[] d = data.getBytes(); for (int ii = 0; ii < data.length(); ii++) { message[8 + ii] = d[ii]; } message[message.length - 2] = ETX; byte chkSum = (byte) buildCheckSum(message, 6, message.length - 2); message[message.length - 1] = chkSum; outputStream.write(message); outputStream.flush(); if (logger.isDebugEnabled()) { logger.debug("Write data: {}", bytesToHexString(message)); } if (waitUntilDataAvailable(1, 5000l)) { int answer = inputStream.readByte(); if (logger.isDebugEnabled()) { logger.debug("Answer from WR3223 {}.", Integer.toHexString(answer)); } if (answer == ACK) { return true; } logger.error("Command with data not accepted.", command.name(), data); } else { logger.error("Timeout. No answer for command with data {}.", command.name(), data); } return false; }
Source:
<code>private String constructGroupId(KafkaConnectionString srcConnString, String dstConnString) { String groupId = srcConnString + "-to-" + dstConnString; <START> return _isGroupIdHashingEnabled ? AbstractKafkaConnector.hashGroupId(groupId) : groupId; <END> }</code><technical_language>human recognizable/redable in groupID</technical_language>

Target:
private String constructGroupId(KafkaConnectionString srcConnString, String dstConnString) { return srcConnString + "-to-" + dstConnString; }
Source:
<code>public ItemEventFactory() { super(Sets.newHashSet(ItemCommandEvent.TYPE, ItemStateEvent.TYPE, ItemStateChangedEvent.TYPE, ItemAddedEvent.TYPE, ItemUpdatedEvent.TYPE, ItemRemovedEvent.TYPE, GroupItemStateChangedEvent.TYPE, <START> ItemTriggerEvent.TYPE)); <END> }</code><technical_language>item events, I add ThingEventFactory</technical_language>

Target:
public ItemEventFactory() { super(Sets.newHashSet(ItemCommandEvent.TYPE, ItemStateEvent.TYPE, ItemStateChangedEvent.TYPE, ItemAddedEvent.TYPE, ItemUpdatedEvent.TYPE, ItemRemovedEvent.TYPE, GroupItemStateChangedEvent.TYPE)); }
Source:
<code>private void createRoutingDataPath(HelixZkClient zkClient, String zkAddress) { try { zkClient.createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, true); } catch (ZkNodeExistsException e) { } <START> ZNRecord znRecord = new ZNRecord(MetadataStoreRoutingConstants.ROUTING_DATA_PATH); <END> znRecord.setListField(MetadataStoreRoutingConstants.ROUTING_ZK_ADDRESS_KEY, Collections.singletonList(zkAddress)); zkClient.writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, znRecord); }</code><technical_language>path contains"/" symbol. OK</technical_language>

Target:
public static void createRoutingDataPath(HelixZkClient zkClient, String zkAddress) { try { zkClient.createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, true); } catch (ZkNodeExistsException e) { } ZNRecord znRecord = new ZNRecord(MetadataStoreRoutingConstants.ROUTING_DATA_PATH.substring(1)); znRecord.setListField(MetadataStoreRoutingConstants.ROUTING_ZK_ADDRESS_KEY, Collections.singletonList(zkAddress)); zkClient.writeData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, znRecord); }
Source:
<code>public void message(DCCppReply l) { if (l.isTurnoutReply()) { <START> log.debug("received Turnout Reply message: {}", l.toString()); <END> int addr = l.getTOIDInt(); if (addr >= 0) { log.debug("message has address: {}", addr); String s = getSystemNamePrefix() + addr; DCCppTurnout found = (DCCppTurnout) getBySystemName(s); if ( found == null) { ((DCCppTurnout) provideTurnout(s)).setFeedbackMode(Turnout.MONITORING); ((DCCppTurnout) provideTurnout(s)).initmessage(l); } else { found.message(l); } } } else if (l.isOutputCmdReply()) { log.debug("received Output Cmd Reply message: {}", l.toString()); int addr = l.getOutputNumInt(); if (addr >= 0) { log.debug("message has address: {}", addr); String s = getSystemNamePrefix() + addr; DCCppTurnout found = (DCCppTurnout) getBySystemName(s); if (found == null) { ((DCCppTurnout) provideTurnout(s)).setFeedbackMode(Turnout.EXACT); ((DCCppTurnout) provideTurnout(s)).initmessage(l); } else { found.message(l); } } } }</code><technical_language>This toString() removed too</technical_language>

Target:
public void message(DCCppReply l) { if (l.isTurnoutReply()) { log.debug("received Turnout Reply message: '{}'", l); int addr = l.getTOIDInt(); if (addr >= 0) { log.debug("message has address: {}", addr); String s = getSystemNamePrefix() + addr; DCCppTurnout found = (DCCppTurnout) getBySystemName(s); if ( found == null) { ((DCCppTurnout) provideTurnout(s)).setFeedbackMode(Turnout.MONITORING); ((DCCppTurnout) provideTurnout(s)).initmessage(l); } else { found.message(l); } } } else if (l.isOutputCmdReply()) { log.debug("received Output Cmd Reply message: '{}'", l); int addr = l.getOutputNumInt(); if (addr >= 0) { log.debug("message has address: {}", addr); String s = getSystemNamePrefix() + addr; DCCppTurnout found = (DCCppTurnout) getBySystemName(s); if (found == null) { ((DCCppTurnout) provideTurnout(s)).setFeedbackMode(Turnout.EXACT); ((DCCppTurnout) provideTurnout(s)).initmessage(l); } else { found.message(l); } } } }
Source:
<code><START> public static SessionFactory<FTPFile> ftpSessionFactory() { <END> return FtpStreamingMessageSourceTests.sessionFactory(); }</code><technical_language>beans static? is overhead. critical. mind</technical_language>

Target:
public SessionFactory<FTPFile> ftpSessionFactory() { return FtpStreamingMessageSourceTests.sessionFactory(); }
Source:
<code>private void applyTriallelicFilter(final VariantContext vc, final Collection<String> filters) { if (vc.hasAttribute(GATKVCFConstants.TUMOR_LOD_KEY)) { final double[] tumorLods = getArrayAttribute(vc, GATKVCFConstants.TUMOR_LOD_KEY); final long numPassingAltAlleles = Arrays.stream(tumorLods).filter(x -> x > MTFAC.TUMOR_LOD_THRESHOLD).count(); <START> if (numPassingAltAlleles > (MTFAC.numAltAllelesThreshold + 1)) { <END> filters.add(GATKVCFConstants.TRIALLELIC_SITE_FILTER_NAME); } } }</code><technical_language>number of passing alt alleles, get ride of +1</technical_language>

Target:
private void applyTriallelicFilter(final VariantContext vc, final Collection<String> filters) { if (vc.hasAttribute(GATKVCFConstants.TUMOR_LOD_KEY)) { final double[] tumorLods = getArrayAttribute(vc, GATKVCFConstants.TUMOR_LOD_KEY); final long numPassingAltAlleles = Arrays.stream(tumorLods).filter(x -> x > MTFAC.TUMOR_LOD_THRESHOLD).count(); if (numPassingAltAlleles > MTFAC.numAltAllelesThreshold) { filters.add(GATKVCFConstants.TRIALLELIC_SITE_FILTER_NAME); } } }
Source:
<code>private MetadataInterface createMetadataForPhysicalPageNumber(int currentPhysicalOrder) throws MetadataTypeNotAllowedException { <START> MetadataTypeInterface metadataTypeInterface = this.myPrefs.getMetadataTypeByName("physPageNumber"); <END> MetadataInterface metadataInterface = UghImplementation.INSTANCE.createMetadata(metadataTypeInterface); metadataInterface.setStringValue(String.valueOf(++currentPhysicalOrder)); return metadataInterface; }</code><technical_language>Interface appended variable name</technical_language>

Target:
private MetadataInterface createMetadataForPhysicalPageNumber(int currentPhysicalOrder) throws MetadataTypeNotAllowedException { MetadataTypeInterface metadataType = this.myPrefs.getMetadataTypeByName("physPageNumber"); MetadataInterface metadata = UghImplementation.INSTANCE.createMetadata(metadataType); metadata.setStringValue(String.valueOf(++currentPhysicalOrder)); return metadata; }
Source:
<code><START> private boolean distributionNotUniform() { <END> List<Long> values = writesPerRange.asMapOfRanges().values().stream().map(AtomicLong::get) .collect(Collectors.toList()); return MathUtils.confidenceDistributionIsNotUniform(values) > CONFIDENCE_FOR_LOGGING; }</code><technical_language>I get this a single number. create a Gauge table reports calculated confidence of uniformity. (Feel free put this feature creep in a follow PR!)</technical_language>

Target:
private boolean distributionNotUniform() { List<Long> values = writesPerRange.asMapOfRanges().values().stream().map(AtomicLong::get) .collect(Collectors.toList()); return MathUtils.calculateConfidenceThatDistributionIsNotUniform(values) > CONFIDENCE_FOR_LOGGING; }
Source:
<code>public void handleCherryPick(Shell shell, GerritClient gerritClient, ChangeInfo changeInfo, RevisionInfo revision) { fGerritClient = gerritClient; fChangeInfo = changeInfo; BranchInfo[] listBranchesCmdResult = listBranches(); List<String> listBranchesRef = new ArrayList<String>(); Iterator<BranchInfo> it = Arrays.asList(listBranchesCmdResult).iterator(); while (it.hasNext()) { listBranchesRef.add(it.next().getRef()); } final CherryPickDialog cherryPickDialog = new CherryPickDialog(shell, listBranchesRef, revision.getCommit().getMessage()); Display.getDefault().syncExec(new Runnable() { public void run() { <START> while (true) { <END> String cherryPickCmdResult = ""; int ret = cherryPickDialog.open(); if (ret == IDialogConstants.OK_ID) { cherryPickCmdResult = cherryPickRevision(fChangeInfo.getId(), revision.getId(), cherryPickDialog.getBranch(), cherryPickDialog.getMessage()); if (!cherryPickCmdResult.isEmpty()) { MessageDialog.open(MessageDialog.ERROR, null, Messages.CherryPickRevision_9, cherryPickCmdResult, SWT.NONE); } else { break; } } else { break; } } } }); }</code><technical_language>a fan of while(true) break approach</technical_language>

Target:
public void handleCherryPick(Shell shell, GerritClient gerritClient, ChangeInfo changeInfo, RevisionInfo revision) { fGerritClient = gerritClient; fChangeInfo = changeInfo; BranchInfo[] listBranchesCmdResult = listBranches(); List<String> listBranchesRef = new ArrayList<String>(); Iterator<BranchInfo> it = Arrays.asList(listBranchesCmdResult).iterator(); while (it.hasNext()) { listBranchesRef.add(it.next().getRef()); } final CherryPickDialog cherryPickDialog = new CherryPickDialog(shell, listBranchesRef, revision.getCommit().getMessage()); Display.getDefault().syncExec(new Runnable() { public void run() { boolean isDone = false; while (!isDone) { String cherryPickCmdResult = ""; int ret = cherryPickDialog.open(); if (ret == IDialogConstants.OK_ID) { cherryPickCmdResult = cherryPickRevision(fChangeInfo.getId(), revision.getId(), cherryPickDialog.getBranch(), cherryPickDialog.getMessage()); if (!cherryPickCmdResult.isEmpty()) { MessageDialog.open(MessageDialog.ERROR, null, Messages.CherryPickRevision_9, cherryPickCmdResult, SWT.NONE); } else { UIUtils.openAnotherEditor(fChangeInfo, fGerritClient); isDone = true; } } else { isDone = true; } } } }); }
Source:
<code>public ImmutableSpongeSneakingData(boolean sneaking) { <START> super(ImmutableSneakingData.class, sneaking, Keys.IS_SNEAKING, SneakingData.class); <END> }</code><technical_language>argument needs implementation class, in this case, SpongeSneakingData.class</technical_language>

Target:
public ImmutableSpongeSneakingData(boolean sneaking) { super(ImmutableSneakingData.class, sneaking, Keys.IS_SNEAKING, SpongeSneakingData.class); }
Source:
<code>private static final Object[][] getArticleName() { return new Object[][] { <START> { "QAarticle" }, <END> { "QAVeryLongArticleNameQAVeryLongArticleNameQAVeryLongArticleNameQAVeryLongArticleNameQAVeryLongArticleNameQAVeryLongArticleName" }, { "QA_article" }, { "123123123123" } }; }</code><technical_language>DataProviders article's names inside</technical_language>

Target:
private static final Object[][] getArticleName() { return new Object[][] { { "Gonzo" }, { "100" }, { "What's" }, { "Kermit_the_Frog" }, { "3, 2, 1" }, { "1-2-3-4-5!" }, { "(Sumpin' New)" }, { "109:" }, }; }
Source:
<code>public static void updateWidget(Context context) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); int appWidgetIds[] = appWidgetManager.getAppWidgetIds(new ComponentName(context, BookmarksWidget.class)); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.listViewWidget); <START> <END> }</code><technical_language>remove this extra line</technical_language>

Target:
public static void updateWidget(Context context) { AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); int appWidgetIds[] = appWidgetManager.getAppWidgetIds(new ComponentName(context, BookmarksWidget.class)); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.list_view_widget); }
Source:
<code>public PropertyValidationResult validate(Entity entity, Serializable instance, Map<String, FieldMetadata> entityFieldMetadata, Map<String, String> validationConfiguration, BasicFieldMetadata propertyMetadata, String propertyName, String value) { String otherField = validationConfiguration.get("otherField"); FieldManager fm = PersistenceManagerFactory.getPersistenceManager().getDynamicEntityDao().getFieldManager(); boolean valid = true; String message = ""; Date startDate = null; Date endDate = null; if(value == null || value.equals("") || otherField == null || otherField.equals("")) return new PropertyValidationResult(true); try { startDate = (Date) fm.getFieldValue(instance, otherField); endDate = (Date) fm.getFieldValue(instance, propertyName); } <START> catch (Exception e) { <END> valid = false; message = e.getMessage(); } if(valid && endDate != null && startDate != null && endDate.before(startDate)) { valid = false; message = END_DATE_BEFORE_START; } if(valid) return new PropertyValidationResult(true); else return new PropertyValidationResult(false,message); }</code><technical_language>1. a pokemon exceptions (gotta catch 'em all) possible. If multiple exceptions, Java 7 syntax like: java } catch (DateFormatException | IllegalArgumentException e) { // do error handling } 2. Put catch line } block this: java try { // do stuff } catch (DateFormatException | SomeOtherException e) { // error handling }</technical_language>

Target:
public PropertyValidationResult validate(Entity entity, Serializable instance, Map<String, FieldMetadata> entityFieldMetadata, Map<String, String> validationConfiguration, BasicFieldMetadata propertyMetadata, String propertyName, String value) { String otherField = validationConfiguration.get("otherField"); FieldManager fm = PersistenceManagerFactory.getPersistenceManager().getDynamicEntityDao().getFieldManager(); boolean valid = true; String message = ""; Date startDate = null; Date endDate = null; if (StringUtils.isBlank(value) || StringUtils.isBlank(otherField)) { return new PropertyValidationResult(true); } try { startDate = (Date) fm.getFieldValue(instance, otherField); endDate = (Date) fm.getFieldValue(instance, propertyName); } catch (IllegalAccessException | FieldNotAvailableException e) { valid = false; message = e.getMessage(); } if (valid && endDate != null && startDate != null && endDate.before(startDate)) { valid = false; message = END_DATE_BEFORE_START; } return new PropertyValidationResult(valid, message); }
Source:
<code>protected Serialization findSerialization(String resultType, ContentType contentType) { <START> for (Serialization serialization : serializationsProvider.get()) { <END> if (serialization.canDeserialize(resultType, contentType)) { return serialization; } } return null; }</code><technical_language>Is this method called often? extract provider call a lazy field</technical_language>

Target:
protected Serialization findSerialization(String resultType, ContentType contentType) { for (Serialization serialization : getSerializations()) { if (serialization.canDeserialize(resultType, contentType)) { return serialization; } } return null; }
Source:
<code>public boolean moveCellsRight() { boolean dirty = false; if (moveCellsRightLoop()) dirty = true; for (int y = 0; y < GRID_WIDTH; y++) { for (int x = (GRID_WIDTH - 1); x > 0; x--) { int xx = x - 1; dirty = combineCells(xx, y, x, y, dirty); } } if (moveCellsRightLoop()) <START> dirty = true; <END> return dirty; }</code><technical_language>google style</technical_language>

Target:
public boolean moveCellsRight() { boolean dirty = false; if (moveCellsRightLoop()) dirty = true; for (int j = 0; j < GRID_WIDTH; j++) { for (int i = (GRID_WIDTH - 1); i > 0; i--) { int previousI = i - 1; dirty = combineCells(previousI, j, i, j, dirty); } } if (moveCellsRightLoop()) dirty = true; return dirty; }
Source:
<code>public static String createAuthorization(final OAuthService service) throws IOException { <START> List<String> scopes = Arrays.asList("repo", "user", "gist"); <END> Authorization auth = new Authorization(); auth.setNote(APP_NOTE); auth.setNoteUrl(APP_NOTE_URL); auth.setScopes(scopes); auth = service.createAuthorization(auth); return auth != null ? auth.getToken() : null; }</code><technical_language>this a static final List is is places? (here line 123)</technical_language>

Target:
public static String createAuthorization(final OAuthService service) throws IOException { Authorization auth = new Authorization(); auth.setNote(APP_NOTE); auth.setNoteUrl(APP_NOTE_URL); auth.setScopes(SCOPES); auth = service.createAuthorization(auth); return auth != null ? auth.getToken() : null; }
Source:
<code>public void testMultipleReadsToSameColumnRangeAcrossRows() { byte[] row1 = PtBytes.toBytes("row1"); byte[] row2 = PtBytes.toBytes("row2"); Transaction transaction = startTransaction(); <START> Map<byte[], BatchingVisitable<Map.Entry<Cell, byte[]>>> columnRange = <END> transaction.getRowsColumnRange(TEST_TABLE, ImmutableList.of(row1), BatchColumnRangeSelection.create(PtBytes.toBytes("col"), PtBytes.toBytes("col0"), 1)); columnRange.values().forEach(visitable -> visitable.batchAccept(10, t -> true)); Map<byte[], BatchingVisitable<Map.Entry<Cell, byte[]>>> columnRangeDifferentRow = transaction.getRowsColumnRange(TEST_TABLE, ImmutableList.of(row2), BatchColumnRangeSelection.create(PtBytes.toBytes("col"), PtBytes.toBytes("col0"), 1)); columnRangeDifferentRow.values().forEach(visitable -> visitable.batchAccept(10, t -> true)); put(transaction, "mutation to ensure", "conflict", "handling"); transaction.commit(); }</code><technical_language>Share BatchColumnRangeSelection clearer prevent breaking test updating other</technical_language>

Target:
public void testMultipleReadsToSameColumnRangeAcrossRows() { byte[] row = PtBytes.toBytes("row"); byte[] differentRow = PtBytes.toBytes("differentRow"); Transaction transaction = startTransaction(); BatchColumnRangeSelection sameColumnRangeSelection = BatchColumnRangeSelection.create(PtBytes.toBytes("col"), PtBytes.toBytes("col0"), 1); Map<byte[], BatchingVisitable<Map.Entry<Cell, byte[]>>> columnRangeResultForRow = transaction.getRowsColumnRange(TEST_TABLE, ImmutableList.of(row), sameColumnRangeSelection); columnRangeResultForRow.values().forEach(visitable -> visitable.batchAccept(10, t -> true)); Map<byte[], BatchingVisitable<Map.Entry<Cell, byte[]>>> columnRangeResultForDifferentRow = transaction.getRowsColumnRange(TEST_TABLE, ImmutableList.of(differentRow), sameColumnRangeSelection); columnRangeResultForDifferentRow.values().forEach(visitable -> visitable.batchAccept(10, t -> true)); put(transaction, "mutation to ensure", "conflict", "handling"); transaction.commit(); }
Source:
<code><START> private Promise loadNodes(final Map<String, JSITDefinitions> existingDefinitions, <END> final DMNIncludedModel model, final List<DMNIncludedNode> result) { String filePath = ""; for (final Map.Entry<String, JSITDefinitions> entry : existingDefinitions.entrySet()) { filePath = entry.getKey(); final JSITDefinitions definitions = Js.uncheckedCast(entry.getValue()); if (Objects.equals(model.getNamespace(), definitions.getNamespace())) { break; } } final String path = filePath; return contentService.loadFile(path) .then(content -> { return promises.create((success, fail) -> { diagramService.transform(content, new ServiceCallback<Diagram>() { @Override public void onSuccess(final Diagram item) { final List<DMNIncludedNode> nodes = diagramUtils .getDRGElements(item) .stream() .map(node -> includedModelFactory.makeDMNIncludeNode(path, model, node)) .collect(Collectors.toList()); result.addAll(nodes); success.onInvoke(nodes); } @Override public void onError(final ClientRuntimeError error) { LOGGER.log(Level.SEVERE, error.getMessage()); fail.onInvoke(error); } }); }); }); }</code><technical_language>IntelliJ is warning this method, I solve using: suggestion private Promise<List<DMNIncludedNode>> loadNodes(final Map<String, JSITDefinitions> existingDefinitions,</technical_language>

Target:
private Promise<List<DMNIncludedNode>> loadNodes(final Map<String, JSITDefinitions> existingDefinitions, final DMNIncludedModel model, final List<DMNIncludedNode> result) { String filePath = ""; for (final Map.Entry<String, JSITDefinitions> entry : existingDefinitions.entrySet()) { filePath = entry.getKey(); final JSITDefinitions definitions = Js.uncheckedCast(entry.getValue()); if (Objects.equals(model.getNamespace(), definitions.getNamespace())) { break; } } final String path = filePath; return contentService.loadFile(path) .then(content -> promises.create((success, fail) -> { diagramService.transform(content, new ServiceCallback<Diagram>() { @Override public void onSuccess(final Diagram item) { final List<DMNIncludedNode> nodes = diagramUtils .getDRGElements(item) .stream() .map(node -> includedModelFactory.makeDMNIncludeNode(path, model, node)) .collect(Collectors.toList()); result.addAll(nodes); success.onInvoke(nodes); } @Override public void onError(final ClientRuntimeError error) { LOGGER.log(Level.SEVERE, error.getMessage()); fail.onInvoke(error); } }); })); }
Source:
<code>private static String thriftDDLToString(ThriftDDL thriftDDL) { if (thriftDDL == null) { return EMPTY_STRING; } List<ThriftField> fields = thriftDDL.getFields(); if (fields == null || fields.isEmpty()) { return EMPTY_STRING; } <START> StringBuilder sb = new StringBuilder(); <END> sb.append(THRIFT_STRUCT).append(SPACE).append(thriftDDL.getTableName()).append(SPACE).append(START_STRUCT); List<String> fieldNames = fields.stream() .map(field -> SPACE + field.getType() + SPACE + field.getName()) .collect(toList()); sb.append(Joiner.on(",").join(fieldNames)); sb.append(END_STRUCT); return sb.toString(); }</code><technical_language>abbreviate variables names</technical_language>

Target:
private static String thriftDDLToString(ThriftDDL thriftDDL) { if (thriftDDL == null) { return EMPTY_STRING; } List<ThriftField> fields = thriftDDL.getFields(); if (fields == null || fields.isEmpty()) { return EMPTY_STRING; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(THRIFT_STRUCT) .append(SPACE) .append(thriftDDL.getTableName()) .append(SPACE) .append(START_STRUCT); stringBuilder.append(fields.stream() .map(field -> SPACE + field.getType() + SPACE + field.getName()) .collect(Collectors.joining(","))); stringBuilder.append(END_STRUCT); return stringBuilder.toString(); }
Source:
<code>public List<VdsNetworkInterface> getAllInterfacesByDataCenterId(Guid dataCenterId) { return getCallsHandler().executeReadList("GetInterfacesByDataCenterId", <START> new VdsNetworkInterfaceRowMapper(qosDaoRetriever), <END> getCustomMapSqlParameterSource().addValue("data_center_id", dataCenterId)); }</code><technical_language>a "new" object? qosDaoRetriever is final</technical_language>

Target:
public List<VdsNetworkInterface> getAllInterfacesByDataCenterId(Guid dataCenterId) { return getCallsHandler().executeReadList("GetInterfacesByDataCenterId", qosDaoInterfaceMapper, getCustomMapSqlParameterSource().addValue("data_center_id", dataCenterId)); }
Source:
<code>public CustomIndexArray(Map<Integer, T> src) { Integer lowerIndex = Integer.MAX_VALUE; Integer upperIndex = Integer.MIN_VALUE; <START> for (Map.Entry<Integer, T> entry : src.entrySet()) { END> Integer key = entry.getKey(); if (key < lowerIndex) { lowerIndex = key; } if (key > upperIndex) { upperIndex = key; } } this.baseIndex = lowerIndex; this.elemCount = upperIndex - lowerIndex + 1; this.elements = makeNullInitializedArray(elemCount); for (Map.Entry<Integer, T> entry : src.entrySet()) { elements.set(entry.getKey() - baseIndex, entry.getValue()); } }</code><technical_language>nit: src.keySet() simpler values</technical_language>

Target:
public CustomIndexArray(Map<Integer, T> src) { Integer lowerIndex = Integer.MAX_VALUE; Integer upperIndex = Integer.MIN_VALUE; for (Integer key : src.keySet()) { if (key < lowerIndex) { lowerIndex = key; } if (key > upperIndex) { upperIndex = key; } } this.baseIndex = lowerIndex; this.elemCount = upperIndex - lowerIndex + 1; this.elements = makeNullInitializedArray(elemCount); for (Map.Entry<Integer, T> entry : src.entrySet()) { elements.set(entry.getKey() - baseIndex, entry.getValue()); } }
Source:
<code>public @ResponseBody List<Game> getGamesByTeam( HttpSession session, @PathVariable int id) { if(session.getAttribute("member") == null) { return null; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, true, false, false); <START> return (List<Game>) (team == null ? null : team.getGames()); <END> }</code><technical_language>change return type of this method</technical_language>

Target:
public @ResponseBody Set<Game> getGamesByTeam( HttpSession session, @PathVariable int id) { if (session.getAttribute("member") == null) { return null; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, true, false, false); return (team == null ? null : team.getGames()); }
Source:
<code>private String getElasticsearchMajorVersion(URL elasticsearchUrl) { return httpClient.send(HttpRequestBuilder.<String>forUrl(elasticsearchUrl.toString()) .method("GET") .successHandler(new HttpClient.ResponseHandler<String>() { @Override public String handleResponse(HttpRequest<?> httpRequest, InputStream inputStream, Integer statusCode, IOException e) throws IOException { JsonNode clusterResponse = JsonUtils.getMapper().readTree(inputStream); String version = clusterResponse.has("version") ? clusterResponse.get("version").get("number").asText() : "0.0.0"; logger.info(String.format("Elasticsearch Version: %s", version)); StringTokenizer stringTokenizer = new StringTokenizer(version, "."); <START> return stringTokenizer.nextToken(); <END> } }) .build()); }</code><technical_language>parse Integer</technical_language>

Target:
private Integer getElasticsearchMajorVersion(URL elasticsearchUrl) { return httpClient.send(HttpRequestBuilder.<Integer>forUrl(elasticsearchUrl.toString()) .method("GET") .successHandler(new HttpClient.ResponseHandler<Integer>() { @Override public Integer handleResponse(HttpRequest<?> httpRequest, InputStream inputStream, Integer statusCode, IOException e) throws IOException { JsonNode clusterResponse = JsonUtils.getMapper().readTree(inputStream); String version = clusterResponse.has("version") ? clusterResponse.get("version").get("number").asText() : "0.0.0"; logger.info(String.format("Elasticsearch Version: %s", version)); StringTokenizer stringTokenizer = new StringTokenizer(version, "."); try { return Integer.valueOf(stringTokenizer.nextToken()); } catch (NumberFormatException nfe) { return null; } } }).build()); }
Source:
<code>private Optional<File[]> retrieveFiles() throws IOException { Optional<File[]> connectorFiles = Optional.empty(); Resource connectorRootPath = new ClassPathResource(connectorRoot); if (connectorRootPath.exists()) { connectorFiles = Optional.ofNullable(connectorRootPath.getFile().listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { <START> if (name.toLowerCase().endsWith(".json")) { <END> return true; } else { return false; } } }) ); } return connectorFiles; }</code><technical_language>This block simplified return name.toLowerCase().endsWith(".json")</technical_language>

Target:
private Optional<File[]> retrieveFiles() throws IOException { Optional<File[]> connectorFiles = Optional.empty(); Resource connectorRootPath = new ClassPathResource(connectorRoot); if (connectorRootPath.exists()) { connectorFiles = Optional.ofNullable(connectorRootPath.getFile().listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return (name.toLowerCase().endsWith(".json")); } }) ); } return connectorFiles; }
Source:
<code>private void writeJobStatusToConfigMap(JobID jobID, JobSchedulingStatus status) throws IOException { LOG.debug("Setting scheduling state for job to {}.", jobID, status); final String key = getKeyForJobId(jobID); try { kubeClient.checkAndUpdateConfigMap( configMapName, configMap -> { if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) { <START> configMap.getData().put(key, status.name()); return Optional.of(configMap); <END> } return Optional.empty(); } ).get(); } catch (Exception e) { throw new IOException("Failed to set " + status.name() + " state in ConfigMap " + configMapName + " for job " + jobID, e); } }</code><technical_language>check original try avoid update if is changed</technical_language>

Target:
private void writeJobStatusToConfigMap(JobID jobID, JobSchedulingStatus status) throws IOException { LOG.debug("Setting scheduling state for job to {}.", jobID, status); final String key = getKeyForJobId(jobID); try { kubeClient.checkAndUpdateConfigMap( configMapName, configMap -> { if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) { final Optional<JobSchedulingStatus> optional = getJobStatus(configMap, jobID); if (!optional.isPresent() || optional.get() != status) { configMap.getData().put(key, status.name()); return Optional.of(configMap); } } return Optional.empty(); } ).get(); } catch (Exception e) { throw new IOException("Failed to set " + status.name() + " state in ConfigMap " + configMapName + " for job " + jobID, e); } }
Source:
<code>private List<MemoryAllocation> mergeQueryAllocations(List<MemoryAllocation> left, List<MemoryAllocation> right) { <START> verify(left != null, "left is null"); <END> verify(right != null, "right is null"); Map<String, MemoryAllocation> mergedAllocations = new HashMap<>(); for (MemoryAllocation allocation : left) { mergedAllocations.put(allocation.getTag(), allocation); } for (MemoryAllocation allocation : right) { mergedAllocations.merge( allocation.getTag(), allocation, (a, b) -> new MemoryAllocation(a.getTag(), a.getAllocation() + b.getAllocation())); } return new ArrayList<>(mergedAllocations.values()); }</code><technical_language>requireNonNull</technical_language>

Target:
private List<MemoryAllocation> mergeQueryAllocations(List<MemoryAllocation> left, List<MemoryAllocation> right) { requireNonNull(left, "left is null"); requireNonNull(right, "right is null"); Map<String, MemoryAllocation> mergedAllocations = new HashMap<>(); for (MemoryAllocation allocation : left) { mergedAllocations.put(allocation.getTag(), allocation); } for (MemoryAllocation allocation : right) { mergedAllocations.merge( allocation.getTag(), allocation, (a, b) -> new MemoryAllocation(a.getTag(), a.getAllocation() + b.getAllocation())); } return new ArrayList<>(mergedAllocations.values()); }
Source:
<code>public void testIncludedCipher() throws Exception { HttpServerConfig config = new HttpServerConfig() .setHttpsEnabled(true) .setHttpsPort(0) .setKeystorePath(KEY_STORE_PATH) .setKeystorePassword(KEY_STORE_PASSWORD) .setHttpsIncludedCipherSuites("TLS_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"); NodeInfo nodeInfo = new NodeInfo("test"); HttpServerInfo httpServerInfo = new HttpServerInfo(config, nodeInfo); HttpServer server = createServer(nodeInfo, httpServerInfo, config); try { server.start(); URI httpsUri = httpServerInfo.getHttpsUri(); HttpClient httpClient = createClientIncludeCiphers("TLS_RSA_WITH_AES_128_CBC_SHA"); httpClient.GET(httpsUri); httpClient = createClientIncludeCiphers("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"); httpClient.GET(httpsUri); httpClient = createClientIncludeCiphers("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"); try { httpClient.GET(httpsUri); <START> Assert.fail("SSL handshake should fail because client only accept a cipher the server doesn't include"); <END> } catch (ExecutionException e) { } } finally { server.stop(); } }</code><technical_language>Static import</technical_language>

Target:
public void testIncludedCipher() throws Exception { HttpServerConfig config = new HttpServerConfig() .setHttpsEnabled(true) .setHttpsPort(0) .setKeystorePath(KEY_STORE_PATH) .setKeystorePassword(KEY_STORE_PASSWORD) .setHttpsIncludedCipherSuites(CIPHER_1 + "," + CIPHER_2); NodeInfo nodeInfo = new NodeInfo("test"); HttpServerInfo httpServerInfo = new HttpServerInfo(config, nodeInfo); HttpServer server = createServer(nodeInfo, httpServerInfo, config); try { server.start(); URI httpsUri = httpServerInfo.getHttpsUri(); HttpClient httpClient = createClientIncludeCiphers(CIPHER_1); httpClient.GET(httpsUri); httpClient = createClientIncludeCiphers(CIPHER_2); httpClient.GET(httpsUri); httpClient = createClientIncludeCiphers(CIPHER_3); try { httpClient.GET(httpsUri); Assert.fail("SSL handshake should fail because client included only ciphers the server didn't include"); } catch (ExecutionException e) { } } finally { server.stop(); } }