auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void closeEditors() { IFile file = getBookmarksFile(); FileEditorInput input = new FileEditorInput(file); IWorkbench wb = PlatformUI.getWorkbench(); for (IWorkbenchWindow wbWindow : wb.getWorkbenchWindows()) { for (IWorkbenchPage wbPage : wbWindow.getPages()) { for (IEditorReference editorReference : wbPage.getEditorReferences()) { try { IEditorPart editor = editorReference.getEditor(false); if (editor instanceof TmfEditor && editorReference.getEditorInput().equals(input)) { wbPage.closeEditor(editorReference.getEditor(false), false); } } catch (PartInitException e) { Activator.getDefault().logError(NLS.bind(Messages.TmfCommonProjectElement_ErrorClosingEditor, getName()), e); } } } } }

Target:
public void closeEditors() { IFile file = getBookmarksFile(); FileEditorInput input = new FileEditorInput(file); IWorkbench wb = PlatformUI.getWorkbench(); for (IWorkbenchWindow wbWindow : wb.getWorkbenchWindows()) { for (IWorkbenchPage wbPage : wbWindow.getPages()) { for (IEditorReference editorReference : wbPage.getEditorReferences()) { try { IEditorPart editor = editorReference.getEditor(false); if (editor instanceof ITmfTraceEditor && editorReference.getEditorInput().equals(input)) { wbPage.closeEditor(editor, false); } } catch (PartInitException e) { Activator.getDefault().logError(NLS.bind(Messages.TmfCommonProjectElement_ErrorClosingEditor, getName()), e); } } } } }
Source:
private void drawStar(Tessellator buffer, int solarOrbitalDistance, float sunSize, float r, float g, float b, float multiplier) { IPlanetaryProvider planetaryProvider = (IPlanetaryProvider)mc.theWorld.provider; DimensionProperties properties = (DimensionProperties)planetaryProvider.getDimensionProperties((int)mc.thePlayer.posX, (int)mc.thePlayer.posZ); GL11.glColor4f(r, g , b ,Math.min((multiplier)*2f,1f)); buffer.startDrawingQuads(); float f10 = sunSize*20f*AstronomicalBodyHelper.getBodySizeMultiplier(solarOrbitalDistance); buffer.addVertexWithUV((double)(-f10), 100.0D, (double)(-f10), 0.0D, 0.0D); buffer.addVertexWithUV((double)f10, 100.0D, (double)(-f10), 1.0D, 0.0D); buffer.addVertexWithUV((double)f10, 100.0D, (double)f10, 1.0D, 1.0D); buffer.addVertexWithUV((double)(-f10), 100.0D, (double)f10, 0.0D, 1.0D); buffer.draw(); }

Target:
private void drawStar(Tessellator buffer, int solarOrbitalDistance, float sunSize, float r, float g, float b, float multiplier) { GL11.glColor4f(r, g , b ,Math.min((multiplier)*2f,1f)); buffer.startDrawingQuads(); float f10 = sunSize*20f*AstronomicalBodyHelper.getBodySizeMultiplier(solarOrbitalDistance); buffer.addVertexWithUV((double)(-f10), 100.0D, (double)(-f10), 0.0D, 0.0D); buffer.addVertexWithUV((double)f10, 100.0D, (double)(-f10), 1.0D, 0.0D); buffer.addVertexWithUV((double)f10, 100.0D, (double)f10, 1.0D, 1.0D); buffer.addVertexWithUV((double)(-f10), 100.0D, (double)f10, 0.0D, 1.0D); buffer.draw(); }
Source:
public void sendPushMessage(Variant variant, Collection<String> tokens, UnifiedPushMessage pushMessage, NotificationSenderCallback callback) { if (tokens.isEmpty()) { return; } String payload = pushMessage.getMessage().getSimplePush(); if (payload == null) { payload = ""; } boolean hasWarning = false; for (String clientURL : tokens) { HttpURLConnection conn = null; try { logger.finest("Sending out SimplePush payload: " + payload); conn = put(clientURL, payload); int simplePushStatusCode = conn.getResponseCode(); logger.info("SimplePush Status: " + simplePushStatusCode); if (Status.OK.getStatusCode() != simplePushStatusCode) { logger.severe("Error during PUT execution to SimplePush Network, status code was: " + simplePushStatusCode); hasWarning = true; } } catch (IOException e) { logger.severe("Error during PUT execution to SimplePush Network", e); hasWarning = true; } catch (IllegalArgumentException e) { logger.severe(e.getMessage(), e); hasWarning = true; } finally { if (conn != null) { conn.disconnect(); } } } if(hasWarning){ callback.onError("Error delivering SimplePush payload"); } else { callback.onSuccess(); } }

Target:
public void sendPushMessage(Variant variant, Collection<String> tokens, UnifiedPushMessage pushMessage, NotificationSenderCallback callback) { if (tokens.isEmpty()) { return; } String payload = pushMessage.getMessage().getSimplePush(); if (payload == null) { payload = ""; } boolean hasWarning = false; for (String clientURL : tokens) { HttpURLConnection conn = null; try { logger.finest("Sending out SimplePush payload: " + payload); conn = put(clientURL, payload); int simplePushStatusCode = conn.getResponseCode(); logger.info("SimplePush Status: " + simplePushStatusCode); if (Status.OK.getStatusCode() != simplePushStatusCode) { hasWarning = true; } } catch (Exception e) { logger.severe("Error delivering SimplePush payload", e); hasWarning = true; } finally { if (conn != null) { conn.disconnect(); } } } if (hasWarning) { callback.onError("Error delivering SimplePush payload"); } else { callback.onSuccess(); } }
Source:
public boolean shouldModifyIndexes(FlagAffectedCommand command, InvocationContext ctx, DistributionManager distributionManager, RpcManager rpcManager, Object key) { if (key == null || distributionManager == null) { return true; } DistributionInfo info = distributionManager.getCacheTopology().getDistribution(key); return info.isPrimary() || info.isWriteOwner() && (ctx.isInTxScope() || !ctx.isOriginLocal() || command != null && command.hasAnyFlag(FlagBitSets.PUT_FOR_STATE_TRANSFER)); }

Target:
public boolean shouldModifyIndexes(FlagAffectedCommand command, InvocationContext ctx, DistributionManager distributionManager, RpcManager rpcManager, Object key) { return false; }
Source:
public void run() { List<VDSGroup> vdsGroups = DbFacade.getInstance().getVdsGroupDao().getTrustedClusters(); List<String> curVdsNames = new ArrayList<String>(); List<String> curVdsNames1 = curVdsNames; List<String> curVdsNames2 = new ArrayList<String>(); List<AttestationValue> valueList1 = new ArrayList<AttestationValue> (); List<AttestationValue> valueList2 = new ArrayList<AttestationValue> (); if (vdsGroups == null || vdsGroups.size()==0) { return; } for (VDSGroup vdsGroup: vdsGroups){ vdss = DbFacade.getInstance().getVdsDao().getAllForVdsGroup(vdsGroup.getId()); if (vdss == null || vdss.size() == 0){ break; } for (VDS vds: vdss){ curVdsNames.add(vds.gethost_name()); } } if (curVdsNames.size()> attestationFirstStageSize) { curVdsNames1 = curVdsNames.subList(0,attestationFirstStageSize-1); curVdsNames2 = curVdsNames.subList(attestationFirstStageSize,curVdsNames.size()-1); } valueList1 = AttestationService.getInstance().attestHosts(curVdsNames1); updateCache(valueList1); if (curVdsNames2.size() > 0) { valueList2 = AttestationService.getInstance().attestHosts(curVdsNames2); updateCache(valueList2); } }

Target:
public void run() { List<VDSGroup> vdsGroups = DbFacade.getInstance().getVdsGroupDao().getTrustedClusters(); List<String> vdsNames = new ArrayList<String>(); List<String> curVdsNames = new ArrayList<String>(); int i=0; boolean secondStageFlag =true; List<AttestationValue> valueList = new ArrayList<AttestationValue> (); if (vdsGroups == null || vdsGroups.size()==0) { return; } for (VDSGroup vdsGroup: vdsGroups){ vdss = DbFacade.getInstance().getVdsDao().getAllForVdsGroup(vdsGroup.getId()); if (vdss == null || vdss.size() == 0){ break; } for (VDS vds: vdss){ vdsNames.add(vds.getHostName()); } } while(vdsNames.size()>0 && i<2 && secondStageFlag){ if (vdsNames.size() <=attestationFirstStageSize){ curVdsNames = vdsNames; secondStageFlag=false; }else{ curVdsNames=(i==0)?vdsNames.subList(i, attestationFirstStageSize) :vdsNames.subList(attestationFirstStageSize, vdsNames.size()); } valueList = AttestationService.getInstance().attestHosts(curVdsNames); updateCache(valueList); i++; } }
Source:
boolean isBlank(final DataType dataType) { final String name = dataType.getName(); return name == null || name.isEmpty(); }

Target:
boolean isBlank(final DataType dataType) { return isEmpty(dataType.getName()); }
Source:
private List<SectionMatcher> getLocalAccessSections() { List<SectionMatcher> sm = localAccessSections; if (sm == null) { Collection<AccessSection> fromConfig = config.getAccessSections(); sm = new ArrayList<SectionMatcher>(fromConfig.size()); for (AccessSection section : fromConfig) { if (isAllProjects) { for (final String permissionName : Permission.getPermissionNames()) { if (!Permission.canBeOnWildProject(permissionName)) { section.removePermission(permissionName); } } } SectionMatcher matcher = SectionMatcher.wrap(section); if (matcher != null) { sm.add(matcher); } } localAccessSections = sm; } return sm; }

Target:
private List<SectionMatcher> getLocalAccessSections() { List<SectionMatcher> sm = localAccessSections; if (sm == null) { Collection<AccessSection> fromConfig = config.getAccessSections(); sm = new ArrayList<SectionMatcher>(fromConfig.size()); for (AccessSection section : fromConfig) { if (isAllProjects) { for (final String permissionName : Permission.getPermissionNames()) { if (!Permission.canBeOnWildProject(section.getName(), permissionName)) { section.removePermission(permissionName); } } } SectionMatcher matcher = SectionMatcher.wrap(section); if (matcher != null) { sm.add(matcher); } } localAccessSections = sm; } return sm; }
Source:
public void listPatches(Path target, boolean verbose) { List<PatchInfo> installedPatches = getInstalledPatches(target); if (installedPatches.size() == 0) { out.println(MSG.patchNoPatchesInstalled()); } else { for (PatchInfo patchInfo : installedPatches) { out.println(MSG.patchInfo(patchInfo)); if (verbose) { patchInfo.getOperations().forEach(op -> out.println(" " + op)); } } } }

Target:
public void listPatches(Path target, boolean verbose) { List<PatchInfo> installedPatches = getInstalledPatches(target); if (installedPatches.isEmpty()) { out.println(MSG.patchNoPatchesInstalled()); } else { for (PatchInfo patchInfo : installedPatches) { out.println(MSG.patchInfo(patchInfo)); if (verbose) { patchInfo.getOperations().forEach(op -> out.println(" " + op)); } } } }
Source:
private void assertDateEquals(String actual, Instant instant, ZoneId timeZone) { String dateStrWithAbbr = getDateStringWithAbbr(instant, timeZone); String dateStrWithOffset = getDateStringWithOffset(instant, timeZone); boolean isExpected = actual.equals(dateStrWithAbbr) || actual.equals(dateStrWithOffset); assertTrue(isExpected); }

Target:
private void assertDateEquals(String actual, Instant instant, ZoneId timeZone) { String dateStrWithAbbr = getDateStringWithAbbr(instant, timeZone); String dateStrWithOffset = getDateStringWithOffset(instant, timeZone); assertTrue(actual.equals(dateStrWithAbbr) || actual.equals(dateStrWithOffset)); }
Source:
protected void onNext() { AuthType authType = getSelectedAuthType(); if (authType == AuthType.XOAUTH2) { K9.oAuth2TokenStore.authorizeAPI(mAccount.getEmail(), this, new OAuth2TokenProvider.OAuth2TokenProviderAuthCallback() { @Override public void success() { updateAccountSettings(""); AccountSetupCheckSettings.actionCheckSettings( AccountSetupIncoming.this, mAccount, CheckDirection.INCOMING); } @Override public void failure(Exception e) { AccountSetupIncoming.this.failure(e); } }); return; } updateAccountSettings(mPasswordView.getText().toString()); AccountSetupCheckSettings.actionCheckSettings(this, mAccount, CheckDirection.INCOMING); }

Target:
protected void onNext() { AuthType authType = getSelectedAuthType(); if (authType == AuthType.XOAUTH2) { Globals.getOAuth2TokenProvider().authorizeAPI(mAccount.getEmail(), this, new OAuth2TokenProvider.OAuth2TokenProviderAuthCallback() { @Override public void success() { updateAccountSettings(""); AccountSetupCheckSettings.actionCheckSettings( AccountSetupIncoming.this, mAccount, CheckDirection.INCOMING); } @Override public void failure(AuthorizationException e) { AccountSetupIncoming.this.failure(e); } }); return; } updateAccountSettings(mPasswordView.getText().toString()); AccountSetupCheckSettings.actionCheckSettings(this, mAccount, CheckDirection.INCOMING); }
Source:
public static String toStringWithId(Identifiable<String> obj) { return String.format("[%s][%s]", obj.getGuid(), obj.getName()); }

Target:
public static String toStringWithId(Identifiable<String> obj) { Conditions.checkNotNull(obj, "object"); return String.format("[%s][%s]", obj.getGuid(), obj.getName()); }
Source:
private String validate(Details details) { final DetailAST rcurly = details.rcurly; final DetailAST nextToken = details.nextToken; final boolean shouldCheckLastRcurly = details.shouldCheckLastRcurly; String violation = ""; if (shouldHaveLineBreakBefore(option, details)) { violation = MSG_KEY_LINE_BREAK_BEFORE; } else if (shouldCheckLastRcurly && option != RightCurlyOption.ALONE) { if (rcurly.getLineNo() == nextToken.getLineNo()) { violation = MSG_KEY_LINE_ALONE; } } else if (shouldBeOnSameLine(option, details)) { violation = MSG_KEY_LINE_SAME; } else if (shouldBeAloneOnLine(option, details)) { violation = MSG_KEY_LINE_ALONE; } return violation; }

Target:
private String validate(Details details) { final DetailAST rcurly = details.rcurly; final DetailAST nextToken = details.nextToken; final boolean shouldCheckLastRcurly = details.shouldCheckLastRcurly; String violation = ""; if (shouldHaveLineBreakBefore(option, details)) { violation = MSG_KEY_LINE_BREAK_BEFORE; } else if (shouldCheckLastRcurly && option != RightCurlyOption.ALONE) { if (rcurly.getLineNo() == nextToken.getLineNo()) { violation = MSG_KEY_LINE_ALONE; } } else if (shouldBeOnSameLine(option, details)) { violation = MSG_KEY_LINE_SAME; } else if (shouldBeAloneOnLine(option, details)) { violation = MSG_KEY_LINE_ALONE; } else if (shouldStartLine) { final String targetSourceLine = getLines()[rcurly.getLineNo() - 1]; if (!isOnStartOfLine(details, targetSourceLine)) { violation = MSG_KEY_LINE_NEW; } } return violation; }
Source:
private Logger configureLoggers(String name) { final Logger root = loggerContext .getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); loggerContext.reset(); final LevelChangePropagator propagator = new LevelChangePropagator(); propagator.setContext(loggerContext); propagator.setResetJUL(true); loggerContext.addListener(propagator); root.setLevel(level); if (advancedLoggers != null && advancedLoggers.size() > 0) { for (Entry<String, DefaultLoggerFactory> entry : advancedLoggers .entrySet()) { Logger logger = loggerContext.getLogger(entry.getKey()); logger.setLevel(entry.getValue().getLevel()); for (AppenderFactory appender : entry.getValue().getAppenders()) { Appender<ILoggingEvent> newAppender = appender.build( loggerContext, name, null); logger.addAppender(newAppender); } } } else { for (Map.Entry<String, Level> entry : loggers.entrySet()) { loggerContext.getLogger(entry.getKey()).setLevel( entry.getValue()); } } return root; }

Target:
private Logger configureLoggers(String name) { final Logger root = loggerContext .getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); loggerContext.reset(); final LevelChangePropagator propagator = new LevelChangePropagator(); propagator.setContext(loggerContext); propagator.setResetJUL(true); loggerContext.addListener(propagator); root.setLevel(level); for (Map.Entry<String, JsonNode> entry : loggers.entrySet()) { final Logger logger = loggerContext.getLogger(entry.getKey()); final JsonNode jsonNode = entry.getValue(); if (jsonNode.isTextual()) { Level level = Level.valueOf(jsonNode.asText()); logger.setLevel(level); } else if (jsonNode.isObject()) { DefaultLoggerFactory configuration; try { configuration = Jackson.newObjectMapper().treeToValue(jsonNode, DefaultLoggerFactory.class); } catch (JsonProcessingException e) { throw new IllegalArgumentException("Wrong format of logger '" + entry.getKey() + "'", e); } logger.setLevel(configuration.getLevel()); for (AppenderFactory appender : configuration.getAppenders()) { logger.addAppender(appender.build(loggerContext, name, null)); } } else { throw new IllegalArgumentException("Unsupported format of logger '" + entry.getKey() + "'"); } } return root; }
Source:
protected boolean canDoAction() { setGlusterVolumeId(getGeoRepSession().getMasterVolumeId()); if (!super.canDoAction()) { return false; } if (getGeoRepSession().getStatus() == GeoRepSessionStatus.PASSIVE) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_ALREADY_PAUSED); } return false; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getGeoRepSession().getStatus() == GeoRepSessionStatus.PASSIVE) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_ALREADY_PAUSED); } return false; }
Source:
private void addStateSystem(@NonNull ITmfStateSystem ss, long parentId) { fetchTreeIsComplete &= ss.waitUntilBuilt(0); long id = ENTRY_ID.getAndIncrement(); StateSystemEntryModel stateSystemEntryModel = new StateSystemEntryModel(id, parentId, ss); entryList.add(stateSystemEntryModel); for (Integer attrib : ss.getSubAttributes(ITmfStateSystem.ROOT_ATTRIBUTE, false)) { addSubAttributes(stateSystemEntryModel, ss, attrib); } }

Target:
private void addStateSystem(@NonNull ITmfStateSystem ss, long parentId) { fetchTreeIsComplete &= ss.waitUntilBuilt(0); long id = ENTRY_ID.getAndIncrement(); StateSystemEntryModel stateSystemEntryModel = new StateSystemEntryModel(id, parentId, ss); ssToId.put(ss, id); for (Integer attrib : ss.getSubAttributes(ITmfStateSystem.ROOT_ATTRIBUTE, false)) { addSubAttributes(stateSystemEntryModel, ss, attrib); } entryList.add(stateSystemEntryModel); }
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } ClassTree classTree = (ClassTree) tree; Type superType = classTree.symbol().superClass(); IdentifierTree className = classTree.simpleName(); if (className == null || classTree.symbol().isAbstract() || superType == null || !(superType.is("java.io.InputStream") || superType.is("java.io.FilterInputStream"))) { return; } Optional<MethodTree> readByteIntInt = findMethod(classTree, READ_BYTES_INT_INT); Optional<MethodTree> readInt = findMethod(classTree, READ_INT); if (!readByteIntInt.isPresent()) { String message = readInt.filter(readIntTree -> readIntTree.block().body().isEmpty()) .map(readIntTree -> "Provide an empty override of \"read(byte[],int,int)\" for this class as well.") .orElse("Provide an override of \"read(byte[],int,int)\" for this class."); reportIssue(className, message); } }

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } ClassTree classTree = (ClassTree) tree; Type superType = classTree.symbol().superClass(); IdentifierTree className = classTree.simpleName(); if (className == null || classTree.symbol().isAbstract() || superType == null || !(superType.is("java.io.InputStream") || superType.is("java.io.FilterInputStream"))) { return; } Optional<MethodTree> readByteIntInt = findMethod(classTree, READ_BYTES_INT_INT); if (!readByteIntInt.isPresent()) { String message = findMethod(classTree, READ_INT) .filter(readIntTree -> readIntTree.block().body().isEmpty()) .map(readIntTree -> "Provide an empty override of \"read(byte[],int,int)\" for this class as well.") .orElse("Provide an override of \"read(byte[],int,int)\" for this class."); reportIssue(className, message); } }
Source:
public void testConvertProfileGenericDataRequestDto() { ProfileGenericDataRequest reqData1 = this.makeRequest(); Object obj = this.mapper.map(reqData1, ProfileGenericDataRequestDto.class); assertTrue(obj != null && obj instanceof ProfileGenericDataRequestDto); }

Target:
public void testConvertProfileGenericDataRequestDto() { ProfileGenericDataRequest profileGenericDateRequest = this.makeRequest(); Object result = this.mapper.map(profileGenericDateRequest, ProfileGenericDataRequestDto.class); assertNotNull("mapping ProfileGenericDataRequest should not return null", result); assertThat("mapping ProfileGenericDataRequest should return correct type", result, instanceOf(ProfileGenericDataRequestDto.class)); final ProfileGenericDataRequestDto profileGenericDataRequestDto = (ProfileGenericDataRequestDto) result; assertEquals("mapped values should be identical", profileGenericDataRequestDto.getBeginDate(), DATE); assertEquals("mapped values should be identical", profileGenericDataRequestDto.getEndDate(), DATE); assertEquals("mapped values should be identical", profileGenericDataRequestDto.getDeviceIdentification(), DEVICE_NAME); final ObisCodeValuesDto obisCodeValuesDto = profileGenericDataRequestDto.getObisCode(); assertEquals("mapped values should be identical", obisCodeValuesDto.getA(), profileGenericDateRequest.getObisCode().getA()); }
Source:
public void define(Context context) { NewController controller = context.createController(CONTROLLER_QUALITY_GATES) .setSince("4.3") .setDescription("Manage quality gates, including conditions and project association."); for (QualityGatesWsAction action : actions) { action.define(controller); } controller.createAction("unset_default") .setDescription("Unset the default quality gate is no more authorized. A quality gate is now required.<br>" + "Previously, this web service unset a quality gate as the default quality gate.<br>" + "Required the 'Administer Quality Gates' permission.") .setSince("4.3") .setDeprecatedSince("7.0") .setPost(true) .setHandler(RemovedWebServiceHandler.INSTANCE) .setResponseExample(RemovedWebServiceHandler.INSTANCE.getResponseExample()) .setChangelog( new Change("7.0", "Unset a quality gate is no more authorized") ); controller.done(); }

Target:
public void define(Context context) { NewController controller = context.createController(CONTROLLER_QUALITY_GATES) .setSince("4.3") .setDescription("Manage quality gates, including conditions and project association."); for (QualityGatesWsAction action : actions) { action.define(controller); } controller.createAction("unset_default") .setDescription("This webservice is no more available : a default quality gate is mandatory.") .setSince("4.3") .setDeprecatedSince("7.0") .setPost(true) .setHandler(RemovedWebServiceHandler.INSTANCE) .setResponseExample(RemovedWebServiceHandler.INSTANCE.getResponseExample()) .setChangelog( new Change("7.0", "Unset a quality gate is no more authorized") ); controller.done(); }
Source:
ReconnectingChannel( long maxRefreshMs, Factory connectionFactory, ScheduledExecutorService executorService) throws IOException { Preconditions.checkArgument(maxRefreshMs >= 0L, "maxRefreshTime cannot be less than 0."); this.maxRefreshMs = maxRefreshMs; this.factory = connectionFactory; this.delegate = new ChannelWrapper(factory); this.authority = delegate.channel.authority(); this.refreshExecutor = executorService; if (maxRefreshMs > 0) { double randomizedPercentage = 1D - (.05D * Math.random()); long delay = (long) (this.maxRefreshMs * randomizedPercentage); Runnable refreshRunanable = new Runnable() { @Override public void run() { ChannelWrapper oldDelegate = delegate; try { setDelegate(new ChannelWrapper(factory)); } catch (IOException e) { throw new IllegalStateException("Channel cannot create a new delegate", e); } if(oldDelegate != null) { try { oldDelegate.close(); } catch (IOException e) { log.log(Level.INFO, "Could not close a recycled delegate", e); } } } }; refreshExecutor.scheduleAtFixedRate(refreshRunanable, delay, delay, TimeUnit.MILLISECONDS); } }

Target:
ReconnectingChannel( long maxRefreshMs, Factory connectionFactory, ScheduledExecutorService executorService) throws IOException { Preconditions.checkArgument(maxRefreshMs >= 0L, "maxRefreshMs cannot be less than 0."); this.maxRefreshMs = maxRefreshMs; this.factory = connectionFactory; this.delegate = new ChannelWrapper(factory); this.authority = delegate.channel.authority(); this.refreshExecutor = executorService; if (maxRefreshMs > 0) { double randomizedPercentage = 1D - (.05D * Math.random()); long delay = (long) (this.maxRefreshMs * randomizedPercentage); Runnable refreshRunanable = new Runnable() { @Override public void run() { ChannelWrapper oldDelegate = delegate; try { setDelegate(new ChannelWrapper(factory)); } catch (IOException e) { throw new IllegalStateException("Channel cannot create a new delegate", e); } if(oldDelegate != null) { try { oldDelegate.close(); } catch (IOException e) { log.log(Level.INFO, "Could not close a recycled delegate", e); } } } }; refreshExecutor.scheduleAtFixedRate(refreshRunanable, delay, delay, TimeUnit.MILLISECONDS); } }
Source:
public boolean isReadable(int size) { return buffer.isReadable(); }

Target:
public boolean isReadable(int size) { return buffer.isReadable(size); }
Source:
@Test public void iteratorThrowsIOException() throws IOException { File parent = folder.getRoot(); File file = new File(parent, "object-queue"); QueueFile queueFile = new QueueFile.Builder(file).build(); ObjectQueue<Object> queue = ObjectQueue.create(queueFile, new ObjectQueue.Converter<Object>() { @Override public String from(byte[] bytes) throws IOException { throw new IOException(); } @Override public void toStream(Object o, OutputStream bytes) { } }); queue.add(new Object()); Iterator<Object> iterator = queue.iterator(); try { iterator.next(); fail(); } catch (Throwable ioe) { assertThat(ioe).isInstanceOf(IOException.class); } }

Target:
@Test public void iteratorThrowsIOException() throws IOException { File parent = folder.getRoot(); File file = new File(parent, "object-queue"); QueueFile queueFile = new QueueFile.Builder(file).build(); ObjectQueue<Object> queue = ObjectQueue.create(queueFile, new ObjectQueue.Converter<Object>() { @Override public String from(byte[] bytes) throws IOException { throw new IOException(); } @Override public void toStream(Object o, OutputStream bytes) { } }); queue.add(new Object()); Iterator<Object> iterator = queue.iterator(); try { iterator.next(); fail(); } catch (Exception ioe) { assertThat(ioe).isInstanceOf(IOException.class); } }
Source:
public default TraversalSource with(final String key, final Object value) { final Optional<OptionsStrategy> opt = getStrategies().getStrategy(OptionsStrategy.class); final OptionsStrategy strategy = opt.orElse(OptionsStrategy.EMPTY); final OptionsStrategy.Builder builder = OptionsStrategy.build(); strategy.getOptions().forEach(builder::with); builder.with(key, value); return withStrategies(builder.create()); }

Target:
public default TraversalSource with(final String key, final Object value) { final OptionsStrategy.Builder builder = OptionsStrategy.build(); getStrategies().getStrategy(OptionsStrategy.class) .ifPresent(optionsStrategy -> optionsStrategy.getOptions().forEach(builder::with)); builder.with(key, value); return withStrategies(builder.create()); }
Source:
private <T> AbstractCatalogItem<T> getAbstractCatalogItem(CatalogItem<T> item) { while (item instanceof CatalogItemDo) item = ((CatalogItemDo<T>)item).itemDto; if (item==null) return null; if (item instanceof AbstractCatalogItem) return (AbstractCatalogItem<T>) item; throw new IllegalStateException("Cannot unwrap catalog item '"+item+"' (type "+item.getClass()+") to restore DTO"); }

Target:
private <T> CatalogItemDtoAbstract<T> getAbstractCatalogItem(CatalogItem<T> item) { while (item instanceof CatalogItemDo) item = ((CatalogItemDo<T>)item).itemDto; if (item==null) return null; if (item instanceof CatalogItemDtoAbstract) return (CatalogItemDtoAbstract<T>) item; throw new IllegalStateException("Cannot unwrap catalog item '"+item+"' (type "+item.getClass()+") to restore DTO"); }
Source:
public int read(char[] cbuf, int off, int len) throws IOException { if (off < 0 || (off + len) > cbuf.length) { throw new IndexOutOfBoundsException(); } if (!inputBuffer.hasRemaining()) { return -1; } CharBuffer charbuffer = CharBuffer.wrap(cbuf, off, len); CoderResult result = utf8Decoder.decode(inputBuffer, charbuffer, true); if (result.isError()) { result.throwException(); } if (result.isUnderflow()) { if (!inputBuffer.hasRemaining()) { utf8Decoder.flush(charbuffer); } return charbuffer.position() - off; } else { return charbuffer.position() - off; } }

Target:
public int read(char[] cbuf, int off, int len) throws IOException { if (off < 0 || (off + len) > cbuf.length) { throw new IndexOutOfBoundsException(); } if (len == 0) { return 0; } int countRead = 0; if (hasLeftoverChar) { cbuf[off] = (char) leftoverChar; hasLeftoverChar = false; off++; len--; countRead++; } if (len == 0) { return countRead; } if (!inputBuffer.hasRemaining()) { return -1; } decoder.reset(); if (len == 1) { int charRead = read(); if (charRead == -1) { return countRead == 0 ? -1 : countRead; } cbuf[off] = (char) charRead; return countRead + 1; } CharBuffer charbuffer = CharBuffer.wrap(cbuf, off, len); CoderResult result = decoder.decode(inputBuffer, charbuffer, true); if (result.isError()) { result.throwException(); } if (result.isUnderflow()) { if (!inputBuffer.hasRemaining()) { decoder.flush(charbuffer); } } return countRead + charbuffer.position() - off; }
Source:
private void testBlockingChannelInfo(String host, Port port, int maxConnectionsPerPortPlainText, int maxConnectionsPerPortSSL) throws Exception { Properties props = new Properties(); props.put("connectionpool.max.connections.per.port.plain.text", "" + maxConnectionsPerPortPlainText); props.put("connectionpool.max.connections.per.port.ssl", "" + maxConnectionsPerPortSSL); int maxConnectionsPerChannel = (port.getPortType() == PortType.PLAINTEXT) ? maxConnectionsPerPortPlainText : maxConnectionsPerPortSSL; createAndReleaseSingleChannelTest(props, host, port); overSubscriptionTest(props, host, port, maxConnectionsPerChannel, true); overSubscriptionTest(props, host, port, maxConnectionsPerChannel, false); underSubscriptionTest(props, host, port, (maxConnectionsPerChannel / 2)); }

Target:
private void testBlockingChannelInfo(String host, Port port, int maxConnectionsPerPortPlainText, int maxConnectionsPerPortSSL) throws Exception { Properties props = new Properties(); props.put("connectionpool.max.connections.per.port.plain.text", "" + maxConnectionsPerPortPlainText); props.put("connectionpool.max.connections.per.port.ssl", "" + maxConnectionsPerPortSSL); int maxConnectionsPerHost = (port.getPortType() == PortType.PLAINTEXT) ? maxConnectionsPerPortPlainText : maxConnectionsPerPortSSL; createAndReleaseSingleChannelTest(props, host, port); overSubscriptionTest(props, host, port, maxConnectionsPerHost, true); overSubscriptionTest(props, host, port, maxConnectionsPerHost, false); underSubscriptionTest(props, host, port, (maxConnectionsPerHost / 2)); }
Source:
private Mono<Void> createTempFile() { try (InputStream inputStream = createRandomInputStream(options.getSize()); OutputStream outputStream = new FileOutputStream(TEMP_FILE.toString())) { copyStream(inputStream, outputStream); return Mono.empty(); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
private Mono<Void> createTempFile() { return Mono.fromCallable(() -> { TestDataCreationHelper.writeToFile(TEMP_FILE_PATH, options.getSize(), DEFAULT_BUFFER_SIZE); return 1; }).then(); }
Source:
public TypedOperation selectOperation() { updateBranchCoverageMaybe(); updateWeightsForOperations(); TypedOperation operation = Randomness.randomMemberWeighted(operationSimpleList, methodWeights); incrementInMap(methodSelections, operation); int numSuccessfulInvocations = incrementInMap(methodSuccessfulCalls, operation); maxSuccessfulCalls = Math.max(maxSuccessfulCalls, numSuccessfulInvocations); return operation; }

Target:
public TypedOperation selectOperation() { updateBranchCoverageMaybe(); TypedOperation selectedOperation = Randomness.randomMemberWeighted( operationSimpleList, methodWeights, totalWeightOfMethodsUnderTest); CollectionsPlume.incrementMap(methodSelectionCounts, selectedOperation); updateWeight(selectedOperation); return selectedOperation; }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_FILE) { if (resultCode == RESULT_OK && intent != null) { Uri uri = intent.getData(); String filePath = ""; try { filePath = UriToFilePath.getPathFromUri(CommCareApplication.instance(), uri); } catch (UriToFilePath.NoDataColumnForUriException e) { filePath = getContext().getFilesDir().getAbsolutePath() + "/temp/" + FileUtil.getFileName(uri.toString()); File file = new File(filePath); try { InputStream fileStream = getContext().getContentResolver().openInputStream(uri); FileUtil.ensureFilePathExists(file); FileUtil.copyFile(fileStream, file); } catch (IOException e1) { e1.printStackTrace(); String failureMessage = e1 instanceof FileNotFoundException ? Localization.get("file.not.exist") : Localization.get("file.copy.failed"); Toast.makeText(getActivity(), failureMessage, Toast.LENGTH_LONG).show(); return; } } validateFile(filePath); } else { Toast.makeText(getActivity(), Localization.get("file.not.selected"), Toast.LENGTH_LONG).show(); } } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_FILE) { if (resultCode == RESULT_OK && intent != null) { Uri uri = intent.getData(); String filePath = null; try { filePath = UriToFilePath.getPathFromUri(CommCareApplication.instance(), uri); } catch (UriToFilePath.NoDataColumnForUriException e) { try { filePath = getNewPathFromUri(uri); } catch (IOException ioe) { Logger.exception(LogTypes.TYPE_MAINTENANCE, e); Toast.makeText(getActivity(), Localization.get("file.selection.failed"), Toast.LENGTH_LONG).show(); return; } } validateFile(filePath); } else { Toast.makeText(getActivity(), Localization.get("file.not.selected"), Toast.LENGTH_LONG).show(); } } }
Source:
public void setOriginalResponseData(String originalResponseData) { if(originalResponseData!=null && !originalResponseData.equals("") && originalResponseContentType!= null && originalResponseContentType.toLowerCase().indexOf("application/json")!=-1){ try{ JSONObject originalResponseJSON = new JSONObject(originalResponseData); this.originalResponseData = originalResponseJSON.toString(); }catch(Exception e){ e.printStackTrace(); } }else { this.originalResponseData = originalResponseData; } }

Target:
public void setOriginalResponseData(String originalResponseData) { this.originalResponseData = originalResponseData; }
Source:
private static OutputGroupDeterminer constructOutputGroupDeterminer(OptionHolder transportOptionHolder, OptionHolder distributedOptHolder, StreamDefinition streamDefinition, int endpointCount){ OutputGroupDeterminer groupDeterminer = null; if (distributedOptHolder != null){ int partitionCount = endpointCount; String strategy = distributedOptHolder.validateAndGetStaticValue(DistributedTransport.DISTRIBUTION_STRATEGY_KEY); if (strategy.equalsIgnoreCase(DistributedTransport.DISTRIBUTION_STRATEGY_PARTITIONED)){ String partitionKeyField = distributedOptHolder.validateAndGetStaticValue(DistributedTransport.PARTITION_KEY_FIELD_KEY); int partitioningFieldIndex = streamDefinition.getAttributePosition(partitionKeyField); if (distributedOptHolder.isOptionExists(DistributedTransport.DISTRIBUTION_CHANNELS_KEY)){ partitionCount = Integer.parseInt(distributedOptHolder.validateAndGetStaticValue(DistributedTransport.DISTRIBUTION_CHANNELS_KEY)); } groupDeterminer = new PartitionedGrouping(partitioningFieldIndex, partitionCount); } } if (groupDeterminer == null){ ArrayList<Option> transportOptions = new ArrayList<Option>(transportOptionHolder.getDynamicOptionsKeys().size()); for (String publishGroupDeterminer : transportOptionHolder.getDynamicOptionsKeys()) { transportOptions.add(transportOptionHolder.validateAndGetOption(publishGroupDeterminer)); } if (transportOptions.size() > 0){ groupDeterminer = new DynamicOptionGrouping(transportOptions); } } return groupDeterminer; }

Target:
private static OutputGroupDeterminer constructOutputGroupDeterminer(OptionHolder transportOptionHolder, OptionHolder distributedOptHolder, StreamDefinition streamDefinition, int endpointCount){ OutputGroupDeterminer groupDeterminer = null; if (distributedOptHolder != null){ int partitionCount = endpointCount; String strategy = distributedOptHolder .validateAndGetStaticValue(DistributedTransport.DISTRIBUTION_STRATEGY_KEY); if (strategy.equalsIgnoreCase(DistributedTransport.DISTRIBUTION_STRATEGY_PARTITIONED)){ String partitionKeyField = distributedOptHolder .validateAndGetStaticValue(DistributedTransport.PARTITION_KEY_FIELD_KEY); int partitioningFieldIndex = streamDefinition.getAttributePosition(partitionKeyField); if (distributedOptHolder.isOptionExists(DistributedTransport.DISTRIBUTION_CHANNELS_KEY)){ partitionCount = Integer.parseInt(distributedOptHolder .validateAndGetStaticValue(DistributedTransport.DISTRIBUTION_CHANNELS_KEY)); } groupDeterminer = new PartitionedGroupDeterminer(partitioningFieldIndex, partitionCount); } } if (groupDeterminer == null){ List<Option> dynamicTransportOptions = new ArrayList<Option>(transportOptionHolder .getDynamicOptionsKeys().size()); transportOptionHolder.getDynamicOptionsKeys(). forEach(option -> dynamicTransportOptions.add(transportOptionHolder.validateAndGetOption(option))); if (dynamicTransportOptions.size() > 0){ groupDeterminer = new DynamicOptionGroupDeterminer(dynamicTransportOptions); } } return groupDeterminer; }
Source:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); if (editionManagementState.getPendingInstallationStatus() != EditionManagementState.PendingStatus.NONE) { throw BadRequestException.create("Can't apply a license when applying one is already in progress"); } String licenseParam = request.mandatoryParam(PARAM_LICENSE); License newLicense = License.parse(licenseParam).orElseThrow(() -> BadRequestException.create("The license provided is invalid")); NextState nextState = computeNextState(newLicense); WsUtils.writeProtobuf(buildResponse(nextState), request, response); }

Target:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); if (editionManagementState.getPendingInstallationStatus() != EditionManagementState.PendingStatus.NONE) { throw BadRequestException.create("Can't apply a license when applying one is already in progress"); } String licenseParam = request.mandatoryParam(PARAM_LICENSE); if (licenseParam.isEmpty()) { throw new IllegalArgumentException(String.format("The '%s' parameter is empty", PARAM_LICENSE)); } License newLicense = License.parse(licenseParam).orElseThrow(() -> BadRequestException.create("The license provided is invalid")); NextState nextState = computeNextState(newLicense); WsUtils.writeProtobuf(buildResponse(nextState), request, response); }
Source:
public RemoteViewsFactory onGetViewFactory(Intent intent) { return new MessageListRemoteViewFactory(this.getApplicationContext()); }

Target:
public RemoteViewsFactory onGetViewFactory(Intent intent) { return new MessageListRemoteViewFactory(getApplicationContext()); }
Source:
protected void executeQueryCommand() { final List<VdsNetworkInterface> list = getDbFacade().getInterfaceDao() .getAllInterfacesForVds(getParameters().getId(), getUserID(), getParameters().isFiltered()); List<VdsNetworkInterface> interfaces = new ArrayList<VdsNetworkInterface>(list.size()); if (!list.isEmpty()) { VdsStatic vdsStatic = getDbFacade().getVdsStaticDao().get(getParameters().getId()); Map<String, Network> networks = Entities.entitiesByName( getDbFacade().getNetworkDao().getAllForCluster(vdsStatic.getVdsGroupId())); for (final VdsNetworkInterface i : list) { if (i.getBonded() == null || (i.getBonded() != null && i.getBonded()) && LinqUtils.filter(list, new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface bond) { return StringUtils.equals(bond.getBondName(), i.getName()); } }).size() > 0) { interfaces.add(i); i.setNetworkImplementationDetails(NetworkUtils.calculateNetworkImplementationDetails(networks, i)); } } } Collections.sort(interfaces, new Comparator<VdsNetworkInterface>() { private boolean isBond(VdsNetworkInterface nic) { return (nic.getBonded() != null && nic.getBonded()); } private String extractBondName(VdsNetworkInterface nic) { if (isBond(nic)) { return nic.getName(); } else { return nic.getBondName(); } } @Override public int compare(VdsNetworkInterface nic1, VdsNetworkInterface nic2) { int compRes = LexoNumericComparator.comp(extractBondName(nic1), extractBondName(nic2)); if (compRes != 0) { if (extractBondName(nic1) == null) { return 1; } if (extractBondName(nic2) == null) { return -1; } return compRes; } if (isBond(nic1) != isBond(nic2)) { return isBond(nic1) ? -1 : 1; } return LexoNumericComparator.comp(nic1.getName(), nic2.getName()); } }); getQueryReturnValue().setReturnValue(interfaces); }

Target:
protected void executeQueryCommand() { final List<VdsNetworkInterface> list = getDbFacade().getInterfaceDao() .getAllInterfacesForVds(getParameters().getId(), getUserID(), getParameters().isFiltered()); List<VdsNetworkInterface> interfaces = new ArrayList<VdsNetworkInterface>(list.size()); if (!list.isEmpty()) { VdsStatic vdsStatic = getDbFacade().getVdsStaticDao().get(getParameters().getId()); Map<String, Network> networks = Entities.entitiesByName( getDbFacade().getNetworkDao().getAllForCluster(vdsStatic.getVdsGroupId())); for (final VdsNetworkInterface i : list) { if (i.getBonded() == null || (i.getBonded() != null && i.getBonded()) && LinqUtils.filter(list, new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface bond) { return StringUtils.equals(bond.getBondName(), i.getName()); } }).size() > 0) { interfaces.add(i); i.setNetworkImplementationDetails(NetworkUtils.calculateNetworkImplementationDetails(networks, i)); } } } Collections.sort(interfaces, new NicComparator()); getQueryReturnValue().setReturnValue(interfaces); }
Source:
public void configUpdated(String configName, boolean downloadApplications) { LOGGER.info("Configuration updated, fetching Commcare schema, {}", configName); if (downloadApplications) { reloadConfig(configName); } else { clearApps(configName); } }

Target:
public void configUpdated(String configName, boolean downloadApplications) { if (downloadApplications) { LOGGER.info("Configuration updated, fetching Commcare schema, {}", configName); reloadConfig(configName); } else { LOGGER.info("Configuration updated, not fetching new Commcare schema, {}", configName); clearApps(configName); } }
Source:
protected CommandContext createMigrateVmContext(ExecutionContext parentContext, VM vm) { ExecutionContext ctx = new ExecutionContext(); try { Map<String, String> values = new HashMap<String, String>(); values.put(VdcObjectType.VM.name().toLowerCase(), vm.getName()); values.put(VdcObjectType.VDS.name().toLowerCase(), vm.getRunOnVdsName()); Step step = ExecutionHandler.addSubStep(getExecutionContext(), parentContext.getJob().getStep(StepEnum.EXECUTING), StepEnum.MIGRATE_VM, ExecutionMessageDirector.resolveStepMessage(StepEnum.MIGRATE_VM, values)); ctx.setJob(parentContext.getJob()); ctx.setStep(step); ctx.setMonitored(true); } catch (RuntimeException e) { log.error("Failed to create ExecutionContext for MigrateVmCommand", e); } return dupContext().setExecutionContext(ctx).resetCompensationContext().resetLock(); }

Target:
protected CommandContext createMigrateVmContext(ExecutionContext parentContext, VM vm) { ExecutionContext ctx = new ExecutionContext(); try { Map<String, String> values = new HashMap<String, String>(); values.put(VdcObjectType.VM.name().toLowerCase(), vm.getName()); values.put(VdcObjectType.VDS.name().toLowerCase(), vm.getRunOnVdsName()); Step step = ExecutionHandler.addSubStep(getExecutionContext(), parentContext.getJob().getStep(StepEnum.EXECUTING), StepEnum.MIGRATE_VM, ExecutionMessageDirector.resolveStepMessage(StepEnum.MIGRATE_VM, values)); ctx.setJob(parentContext.getJob()); ctx.setStep(step); ctx.setMonitored(true); } catch (RuntimeException e) { log.error("Failed to create ExecutionContext for MigrateVmCommand", e); } return dupContext().withExecutionContext(ctx).withoutCompensationContext().withoutLock(); }
Source:
public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, CoreText.AssumeUnchangedOperation_adding, rsrcList.size() + 1); caches.clear(); mappings.clear(); try { for (IResource resource : rsrcList) { assumeValid(resource); progress.worked(1); } progress.setWorkRemaining(caches.size()); for (Map.Entry<Repository, DirCache> e : caches.entrySet()) { final Repository db = e.getKey(); final DirCache editor = e.getValue(); progress.setTaskName(NLS.bind( CoreText.AssumeUnchangedOperation_writingIndex, db .getDirectory())); editor.write(); editor.commit(); progress.worked(1); } } catch (RuntimeException e) { throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, e)); } catch (IOException e) { throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, e)); } finally { for (DirCache cache : caches.values()) { cache.unlock(); } caches.clear(); mappings.clear(); } }

Target:
public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, rsrcList.size() * 2); progress.setTaskName(CoreText.AssumeUnchangedOperation_adding); caches.clear(); try { for (IResource resource : rsrcList) { assumeValid(resource); progress.worked(1); } progress.setWorkRemaining(caches.size()); for (Map.Entry<Repository, DirCache> e : caches.entrySet()) { final Repository db = e.getKey(); final DirCache editor = e.getValue(); progress.setTaskName(NLS.bind( CoreText.AssumeUnchangedOperation_writingIndex, db .getDirectory())); editor.write(); editor.commit(); progress.worked(1); } } catch (RuntimeException e) { throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, e)); } catch (IOException e) { throw new CoreException(Activator.error(CoreText.UntrackOperation_failed, e)); } finally { for (DirCache cache : caches.values()) { cache.unlock(); } caches.clear(); } }
Source:
private Collection<File> transactionFiles( File dbLocation ) throws IOException { Collection<File> txFiles = new ArrayList<>(); DirectoryStream<Path> dirStream = Files.newDirectoryStream( dbLocation.toPath(), "neostore.transaction.db.*" ); dirStream.forEach( path -> txFiles.add( path.toFile() ) ); return txFiles; }

Target:
private Collection<File> transactionFiles( File dbLocation ) throws IOException { Collection<File> txFiles = new ArrayList<>(); DirectoryStream<Path> dirStream = Files.newDirectoryStream( dbLocation.toPath(), "neostore.transaction.db.*" ); dirStream.forEach( path -> txFiles.add( path.toFile() ) ); dirStream.close(); return txFiles; }
Source:
public double[] derivative(Trade trade, RatesProvider provider, List<CurveParameterSize> curveOrder) { CalibrationMeasure<Trade> measure = getMeasure(trade.getClass()); CurveCurrencyParameterSensitivities paramSens = measure.sensitivities(trade, provider); CurveUnitParameterSensitivities unitSens = CurveUnitParameterSensitivities.empty(); for (CurveCurrencyParameterSensitivity ccySens : paramSens.getSensitivities()) { unitSens = unitSens.combinedWith(CurveUnitParameterSensitivity.of(ccySens.getMetadata(), ccySens.getSensitivity())); } double[] result = DoubleArrayMath.EMPTY_DOUBLE_ARRAY; for (CurveParameterSize curveParams : curveOrder) { double[] sens = unitSens.findSensitivity(curveParams.getName()) .map(s -> s.getSensitivity()) .orElse(new double[curveParams.getParameterCount()]); result = Doubles.concat(result, sens); } return result; }

Target:
public double[] derivative(Trade trade, RatesProvider provider, List<CurveParameterSize> curveOrder) { CurveUnitParameterSensitivities unitSens = extractSensitivities(trade, provider); double[] result = DoubleArrayMath.EMPTY_DOUBLE_ARRAY; for (CurveParameterSize curveParams : curveOrder) { double[] sens = unitSens.findSensitivity(curveParams.getName()) .map(s -> s.getSensitivity()) .orElse(new double[curveParams.getParameterCount()]); result = Doubles.concat(result, sens); } return result; }