auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Score score(Item subject, Item candidate) { if (subject.getYear() == null && candidate.getYear() == null) { return nullYearScore; } if (subject.getYear() == null || candidate.getYear() == null) { return mismatchScore; } return subject.getYear().equals(candidate.getYear()) ? matchScore : mismatchScore; }

Target:
protected Score score(Item subject, Item candidate) { if (subject.getYear() == null && candidate.getYear() == null) { return treatNullYearsAsMatch ? matchScore : nullYearScore; } if (subject.getYear() == null || candidate.getYear() == null) { return nullYearScore; } return subject.getYear().equals(candidate.getYear()) ? matchScore : mismatchScore; }
Source:
protected void ExecuteVdsBrokerCommand() { storage_pool storagePool = DbFacade.getInstance().getStoragePoolDAO().get(getVds().getstorage_pool_id()); boolean grayedOutLUNsEnabled = Config.<Boolean> GetValue( ConfigValues.GrayedOutLUNsEnabled, storagePool.getcompatibility_version().getValue()); XmlRpcStruct options = new XmlRpcStruct(); if (grayedOutLUNsEnabled) { options.add(VdsProperties.includePartitioned, "true"); } _result = getBroker() .getDeviceList( (int) getParameters().getStorageType().getValue(), options); ProceedProxyReturnValue(); setReturnValue(ParseLUNList(_result.lunList)); }

Target:
protected void ExecuteVdsBrokerCommand() { storage_pool storagePool = DbFacade.getInstance().getStoragePoolDAO().get(getVds().getstorage_pool_id()); boolean grayedOutLUNsEnabled = Config.<Boolean> GetValue( ConfigValues.FilteringLUNsEnabled, storagePool.getcompatibility_version().getValue()); XmlRpcStruct options = new XmlRpcStruct(); if (grayedOutLUNsEnabled) { options.add(VdsProperties.includePartitioned, "true"); } _result = getBroker() .getDeviceList( (int) getParameters().getStorageType().getValue(), options); ProceedProxyReturnValue(); setReturnValue(ParseLUNList(_result.lunList)); }
Source:
protected void executeCommand() { VM vm = getVm(); if (vm.getClusterId().equals(getParameters().getClusterId())) { setSucceeded(true); return; } List<Network> networks = getNetworkDao().getAllForCluster(getParameters().getClusterId()); List<VmNic> interfaces = getVmNicDao().getAllForVm(getParameters().getVmId()); for (final VmNic iface : interfaces) { if (iface.getVnicProfileId() != null) { final Network network = NetworkHelper.getNetworkByVnicProfileId(iface.getVnicProfileId()); boolean networkFoundInCluster = networks.stream().anyMatch(n -> Objects.equals(n.getId(), network.getId())); if (!networkFoundInCluster) { iface.setVnicProfileId(null); getVmNicDao().update(iface); } } } if (vm.getDedicatedVmForVdsList().size() > 0) { vm.setDedicatedVmForVdsList(Collections.<Guid>emptyList()); dedicatedHostWasCleared = true; } vm.setClusterId(getParameters().getClusterId()); CpuProfile cpuProfile = getCpuProfileDao().getAllForCluster( vm.getClusterId(), getUserId(), true, ActionGroup.ASSIGN_CPU_PROFILE).get(0); vm.setCpuProfileId(cpuProfile.getId()); getVmStaticDao().update(vm.getStaticData()); List<AffinityGroup> allAffinityGroupsByVmId = DbFacade.getInstance().getAffinityGroupDao().getAllAffinityGroupsByVmId(vm.getId()); if (!allAffinityGroupsByVmId.isEmpty()) { StringBuilder sb = new StringBuilder(); for (AffinityGroup affinityGroup : allAffinityGroupsByVmId) { sb.append(affinityGroup.getName() + " "); } log.info("Due to cluster change, removing VM from associated affinity group(s): {}", sb); DbFacade.getInstance().getAffinityGroupDao().removeVmFromAffinityGroups(vm.getId()); } setSucceeded(true); }

Target:
protected void executeCommand() { VM vm = getVm(); if (vm.getClusterId().equals(getParameters().getClusterId())) { setSucceeded(true); return; } List<Network> networks = getNetworkDao().getAllForCluster(getParameters().getClusterId()); List<VmNic> interfaces = getVmNicDao().getAllForVm(getParameters().getVmId()); for (final VmNic iface : interfaces) { if (iface.getVnicProfileId() != null) { final Network network = NetworkHelper.getNetworkByVnicProfileId(iface.getVnicProfileId()); boolean networkFoundInCluster = networks.stream().anyMatch(n -> Objects.equals(n.getId(), network.getId())); if (!networkFoundInCluster) { iface.setVnicProfileId(null); getVmNicDao().update(iface); } } } if (vm.getDedicatedVmForVdsList().size() > 0) { vm.setDedicatedVmForVdsList(Collections.<Guid>emptyList()); dedicatedHostWasCleared = true; } vm.setClusterId(getParameters().getClusterId()); CpuProfileHelper.assignFirstCpuProfile(vm.getStaticData(), getUserId()); getVmStaticDao().update(vm.getStaticData()); List<AffinityGroup> allAffinityGroupsByVmId = DbFacade.getInstance().getAffinityGroupDao().getAllAffinityGroupsByVmId(vm.getId()); if (!allAffinityGroupsByVmId.isEmpty()) { StringBuilder sb = new StringBuilder(); for (AffinityGroup affinityGroup : allAffinityGroupsByVmId) { sb.append(affinityGroup.getName() + " "); } log.info("Due to cluster change, removing VM from associated affinity group(s): {}", sb); DbFacade.getInstance().getAffinityGroupDao().removeVmFromAffinityGroups(vm.getId()); } setSucceeded(true); }
Source:
public List<RunT> getLastBuildsOverThreshold(int numberOfBuilds, Result threshold) { RunT r = getLastBuild(); return r.getBuildsOverThreshold(r, numberOfBuilds, threshold); }

Target:
public List<RunT> getLastBuildsOverThreshold(int numberOfBuilds, Result threshold) { RunT r = getLastBuild(); return r.getBuildsOverThreshold(numberOfBuilds, threshold); }
Source:
public TopologyInfo(EmbeddedCacheManager cacheManager, Config.Scope config, boolean embedded) { String siteName; String nodeName; boolean isGeneratedNodeName = false; if (!embedded) { Transport transport = cacheManager.getTransport(); if (transport != null) { nodeName = cacheManager.getCacheManagerConfiguration().transport().nodeName(); siteName = cacheManager.getCacheManagerConfiguration().transport().siteId(); if (siteName == null) { siteName = System.getProperty(InfinispanConnectionProvider.JBOSS_SITE_NAME); } } else { nodeName = System.getProperty(InfinispanConnectionProvider.JBOSS_NODE_NAME); siteName = System.getProperty(InfinispanConnectionProvider.JBOSS_SITE_NAME); } if (nodeName == null || nodeName.equals("localhost")) { isGeneratedNodeName = true; nodeName = generateNodeName(); } } else { boolean clustered = config.getBoolean("clustered", false); nodeName = config.get("nodeName", System.getProperty(InfinispanConnectionProvider.JBOSS_NODE_NAME)); if (nodeName != null && nodeName.isEmpty()) { nodeName = null; } siteName = config.get("siteName", System.getProperty(InfinispanConnectionProvider.JBOSS_SITE_NAME)); if (siteName != null && siteName.isEmpty()) { siteName = null; } if (nodeName == null) { if (!clustered) { isGeneratedNodeName = true; nodeName = generateNodeName(); } else { throw new IllegalStateException("You must set jboss.node.name if you use clustered mode for InfinispanConnectionProvider"); } } } this.myNodeName = nodeName; this.mySiteName = siteName; this.isGeneratedNodeName = isGeneratedNodeName; }

Target:
public TopologyInfo(EmbeddedCacheManager cacheManager, Config.Scope config, boolean embedded) { String siteName; String nodeName; boolean isGeneratedNodeName = false; if (!embedded) { Transport transport = cacheManager.getTransport(); if (transport != null) { nodeName = transport.getAddress().toString(); siteName = cacheManager.getCacheManagerConfiguration().transport().siteId(); if (siteName == null) { siteName = System.getProperty(InfinispanConnectionProvider.JBOSS_SITE_NAME); } } else { nodeName = System.getProperty(InfinispanConnectionProvider.JBOSS_NODE_NAME); siteName = System.getProperty(InfinispanConnectionProvider.JBOSS_SITE_NAME); } if (nodeName == null || nodeName.equals("localhost")) { isGeneratedNodeName = true; nodeName = generateNodeName(); } } else { boolean clustered = config.getBoolean("clustered", false); nodeName = config.get("nodeName", System.getProperty(InfinispanConnectionProvider.JBOSS_NODE_NAME)); if (nodeName != null && nodeName.isEmpty()) { nodeName = null; } siteName = config.get("siteName", System.getProperty(InfinispanConnectionProvider.JBOSS_SITE_NAME)); if (siteName != null && siteName.isEmpty()) { siteName = null; } if (nodeName == null) { if (!clustered) { isGeneratedNodeName = true; nodeName = generateNodeName(); } else { throw new IllegalStateException("You must set jboss.node.name if you use clustered mode for InfinispanConnectionProvider"); } } } this.myNodeName = nodeName; this.mySiteName = siteName; this.isGeneratedNodeName = isGeneratedNodeName; }
Source:
public void testSchemaStoreRetrieval() { assertNotNull(Framework.getService(SchemaStore.class)); assertNotNull(Framework.getService(AvroSchemaStoreService.class)); }

Target:
public void testSchemaStoreRetrieval() { assertNotNull(Framework.getService(SchemaStore.class)); }
Source:
public void MessageWall_017_CloseAndReopenThread() { MessageWallPageObject wall = new MessageWallPageObject(driver); String timeStamp = wall.getTimeStamp(); String title = PageContent.messageWallTitlePrefix + timeStamp; String message = PageContent.messageWallMessagePrefix + timeStamp; wall.openWikiPage(); CommonFunctions.logInCookie(Properties.userNameStaff, Properties.passwordStaff); wall.openMessageWall(Properties.userNameStaff); wall.writeMessage(title, message); wall.clickPostButton(); wall.verifyPostedMessageWithTitle(title, message); wall.closeThread("reason"); wall.reopenThread(); CommonFunctions.logOut(driver); }

Target:
public void MessageWall_017_CloseAndReopenThread() { MessageWallPageObject wall = new MessageWallPageObject(driver); timeStamp = wall.getTimeStamp(); title = PageContent.messageWallTitlePrefix + timeStamp; message = PageContent.messageWallMessagePrefix + timeStamp; wall.openWikiPage(); CommonFunctions.logInCookie(Properties.userNameStaff, Properties.passwordStaff); wall.openMessageWall(Properties.userNameStaff); wall.writeMessage(title, message); wall.clickPostButton(); wall.verifyPostedMessageWithTitle(title, message); wall.closeThread(PageContent.messageWallCloseReopenReason); wall.reopenThread(); CommonFunctions.logOut(driver); }
Source:
public void write(DataOutput out) throws IOException { }

Target:
public void write(DataOutput out) throws IOException { throw new UnsupportedOperationException(); }
Source:
public static MapboxWebMapType fromBundle(Bundle bundle) { AirMapType airMapType = AirMapType.fromBundle(bundle); return new MapboxWebMapType(airMapType.getFileName(), airMapType.getMapUrl(), airMapType.getDomain(), bundle.getString(ARG_MAPBOX_ACCESS_TOKEN, ""), bundle.getString(ARG_MAPBOX_MAPID, "")); }

Target:
public static MapboxWebMapType fromBundle(Bundle bundle) { AirMapType airMapType = AirMapType.fromBundle(bundle); String mapboxAccessToken = bundle.getString(ARG_MAPBOX_ACCESS_TOKEN, ""); String mapboxMapId = bundle.getString(ARG_MAPBOX_MAPID, ""); return new MapboxWebMapType(airMapType.getFileName(), airMapType.getMapUrl(), airMapType.getDomain(), mapboxAccessToken, mapboxMapId); }
Source:
public Collection<PluginInfo> getUninstalledPlugins() { return listJarFiles(uninstalledPluginsDir()) .stream() .map(PluginInfo::create) .collect(Collectors.toList()); }

Target:
public Collection<PluginInfo> getUninstalledPlugins() { return listJarFiles(uninstalledPluginsDir()) .stream() .map(PluginInfo::create) .collect(MoreCollectors.toList()); }
Source:
public synchronized void cancel() { super.cancel(); while (fEventsQueue.size() >= 1) { fEventIterator.next(); } fEventsQueue.put(END_EVENT); fEventsQueue.flushInputBuffer(); }

Target:
public synchronized void cancel() { super.cancel(); while (!fEventsQueue.isEmpty()) { fEventIterator.next(); } fEventsQueue.put(END_EVENT); fEventsQueue.flushInputBuffer(); }
Source:
public void remoteAck(final long seq) { m_es.execute(new Runnable() { @Override public void run() { try { if (!isMaster()) { if (exportLog.isDebugEnabled()) { exportLog.debug("Skip remote RELEASE_BUFFER message for " + seq + " because current stream is master now"); } return; } localAck(seq, seq); if (m_coordinator.isSafePoint(seq)) { if (exportLog.isDebugEnabled()) { exportLog.debug("Passed safe point " + seq + ", resume polling."); } pollImpl(m_pollTask); } } catch (Exception e) { exportLog.error("Error acking export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error acking export buffer", true, e); } } }); }

Target:
public void remoteAck(final long seq) { m_es.execute(new Runnable() { @Override public void run() { try { if (isMaster()) { if (exportLog.isDebugEnabled()) { exportLog.debug("Skip remote RELEASE_BUFFER message for " + seq + " because current stream is master now"); } return; } localAck(seq, seq); if (m_coordinator.isSafePoint(seq)) { if (exportLog.isDebugEnabled()) { exportLog.debug("Passed safe point " + seq + ", resume polling."); } pollImpl(m_pollTask); } } catch (Exception e) { exportLog.error("Error acking export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error acking export buffer", true, e); } } }); }
Source:
public UnsynchronizedSpeedControllerRuntimeException() { super(getName() + "'s CustomSpeedControllers report different speeds"); }

Target:
public UnsynchronizedSpeedControllerRuntimeException() { super(getName() + "'s SpeedControllers report different speeds"); }
Source:
public boolean deleteImage(String id) { Snapshot snapshot = api.snapshotApi().getSnapshot(id); if (snapshot != null) try { logger.debug(">> deleting snapshot %s..", id); return api.snapshotApi().deleteSnapshot(id); } catch (Exception ex) { logger.error(ex, ">> error deleting snapshot %s..", id); } return true; }

Target:
public boolean deleteImage(String id) { Snapshot snapshot = api.snapshotApi().getSnapshot(id); boolean deleted = false; if (snapshot != null) try { logger.debug(">> deleting snapshot %s..", id); if (api.snapshotApi().deleteSnapshot(id)) { deleted = true; images.removeImage(id); } } catch (Exception ex) { logger.error(ex, ">> error deleting snapshot %s..", id); } return deleted; }
Source:
MembershipManager(Node node, ClusterServiceImpl clusterService, Lock clusterServiceLock) { this.node = node; this.clusterService = clusterService; this.clusterServiceLock = clusterServiceLock; this.nodeEngine = node.getNodeEngine(); this.logger = node.getLogger(getClass()); this.mastershipClaimTimeoutSeconds = node.getProperties().getInteger(MASTERSHIP_CLAIM_TIMEOUT_SECONDS); int partialDisconnectionResolutionHeartbeatCount = node.getProperties().getInteger( PARTIAL_MEMBER_DISCONNECTION_RESOLUTION_HEARTBEAT_COUNT); this.partialDisconnectionDetectionEnabled = partialDisconnectionResolutionHeartbeatCount > 0; long heartbeatIntervalMs = SECONDS.toMillis(node.getProperties().getInteger(HEARTBEAT_INTERVAL_SECONDS)); long partialDisconnectivityDetectionIntervalMs = partialDisconnectionResolutionHeartbeatCount * heartbeatIntervalMs; long heartbeatTimeoutMs = SECONDS.toMillis(node.getProperties().getInteger(MAX_NO_HEARTBEAT_SECONDS)); if (!partialDisconnectionDetectionEnabled) { partialDisconnectivityDetectionIntervalMs = Long.MAX_VALUE; } else if (heartbeatTimeoutMs < partialDisconnectivityDetectionIntervalMs) { partialDisconnectivityDetectionIntervalMs = heartbeatTimeoutMs; } this.partialDisconnectionHandler = new PartialDisconnectionHandler(partialDisconnectivityDetectionIntervalMs, node.getProperties().getInteger(PARTIAL_MEMBER_DISCONNECTION_RESOLUTION_ALGORITHM_TIMEOUT_SECONDS)); registerThisMember(); }

Target:
MembershipManager(Node node, ClusterServiceImpl clusterService, Lock clusterServiceLock) { this.node = node; this.clusterService = clusterService; this.clusterServiceLock = clusterServiceLock; this.nodeEngine = node.getNodeEngine(); this.logger = node.getLogger(getClass()); this.mastershipClaimTimeoutSeconds = node.getProperties().getInteger(MASTERSHIP_CLAIM_TIMEOUT_SECONDS); int partialDisconnectionResolutionHeartbeatCount = node.getProperties().getInteger( PARTIAL_MEMBER_DISCONNECTION_RESOLUTION_HEARTBEAT_COUNT); this.partialDisconnectionDetectionEnabled = partialDisconnectionResolutionHeartbeatCount > 0; this.partialDisconnectionHandler = new PartialDisconnectionHandler(node.getProperties()); registerThisMember(); }
Source:
public String getQueueName() { if (isUseUserCRPref() && userComputeResourcePreference != null && userComputeResourcePreference.getPreferredBatchQueue() != null) { return userComputeResourcePreference.getPreferredBatchQueue(); } else if (isValid(processModel.getProcessResourceSchedule().getQueueName())) { return processModel.getProcessResourceSchedule().getQueueName(); } else { return gatewayComputeResourcePreference.getPreferredBatchQueue(); } }

Target:
public String getQueueName() { if (isValid(processModel.getProcessResourceSchedule().getQueueName())) { return processModel.getProcessResourceSchedule().getQueueName(); } else if (isUseUserCRPref() && userComputeResourcePreference != null && userComputeResourcePreference.getPreferredBatchQueue() != null) { return userComputeResourcePreference.getPreferredBatchQueue(); } else { return gatewayComputeResourcePreference.getPreferredBatchQueue(); } }
Source:
protected ByteBuffer computeNext() { ByteBuffer chunk = chunks.poll(); while (chunk == null) { try (TraceTokenScope ignored = registerTraceToken(traceToken)) { writer.write(); } catch (Exception e) { throw propagate(e); } chunk = chunks.poll(); } if (chunk == DONE) { return endOfData(); } bytesWritten.addAndGet(chunk.position()); chunk.flip(); return chunk; }

Target:
protected ByteBuffer computeNext() { ByteBuffer chunk = chunks.poll(); if (chunk == null) { try (TraceTokenScope ignored = registerTraceToken(traceToken)) { while (chunk == null) { try { writer.write(); } catch (Exception e) { throw propagate(e); } chunk = chunks.poll(); } } } if (chunk == DONE) { return endOfData(); } bytesWritten.addAndGet(chunk.position()); chunk.flip(); return chunk; }
Source:
private static String toRpn(String str) { MyStack<Character> s = new MyStack<Character>(); String resStr = ""; StringBuilder builder = new StringBuilder(); for (int i = 0; i < str.length(); ++i) { char cur; if (Character.isDigit(str.charAt(i))) { builder.append(str.charAt(i)); if (i != str.length() - 1 && !Character.isDigit(str.charAt(i + 1))) { builder.append(","); } else if (i == str.length() - 1) builder.append(","); } else { if (str.charAt(i) == '(') { s.push(str.charAt(i)); } else { if (str.charAt(i) == '+' || str.charAt(i) == '-' || str.charAt(i) == '/' || str.charAt(i) == '*') { while (!s.isEmpty()) { if (s.peek() == '/' || s.peek() == '*' || ((s.peek() == '-' || s.peek() == '+') && (str .charAt(i) == '-' || str.charAt(i) == '+'))) { builder.append(s.pop().charValue()).append(","); } else break; if (s.isEmpty() || s.peek() == '(') { break; } } s.push(str.charAt(i)); } else { if (str.charAt(i) == ')') { while (!s.isEmpty() && s.peek() != '(') { builder.append(s.pop().charValue()).append(","); } } else { if (str.charAt(i) != ' ' && str.charAt(i) != '\n' && str.charAt(i) != '\t') { return ""; } } } } } if (i == str.length() - 1) { while (!s.isEmpty()) { if (!s.isEmpty()) { cur = s.pop().charValue(); if (cur != '(') builder.append(cur).append(","); } } } } resStr = builder.toString(); return resStr; }

Target:
private static String toRpn(String str) { LinkedList<Character> s = new LinkedList<Character>(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < str.length(); ++i) { char cur; if (Character.isDigit(str.charAt(i))) { builder.append(str.charAt(i)); if (i != str.length() - 1 && !Character.isDigit(str.charAt(i + 1))) { builder.append(","); } else if (i == str.length() - 1) { builder.append(","); } } else { if (str.charAt(i) == '(') { s.push(str.charAt(i)); } else { if (str.charAt(i) == '+' || str.charAt(i) == '-' || str.charAt(i) == '/' || str.charAt(i) == '*') { while (!s.isEmpty()) { if (s.peek() == '/' || s.peek() == '*' || ((s.peek() == '-' || s.peek() == '+') && (str .charAt(i) == '-' || str.charAt(i) == '+'))) { builder.append(s.pop().charValue()).append(","); } else { break; } if (s.isEmpty() || s.peek() == '(') { break; } } s.push(str.charAt(i)); } else { if (str.charAt(i) == ')') { while (!s.isEmpty() && s.peek() != '(') { builder.append(s.pop().charValue()).append(","); } } else { if (!Character.isWhitespace(str.charAt(i))) { return ""; } } } } } if (i == str.length() - 1) { while (!s.isEmpty()) { cur = s.pop().charValue(); if (cur != '(') { builder.append(cur).append(","); } } } } return builder.toString(); }
Source:
public static void setup() { callerImpl = new CallerImpl<CallManager.CallEvent>(null) { @Override public CallManager.CallEvent callForEvent(DatabaseClient client, CallArgs args) throws Exception { return null; } }; callbackGeneratorTest = new CallbackGeneratorTest(); }

Target:
public static void setup() { DatabaseClient adminClient = Common.newServerAdminClient("java-unittest-modules"); JSONDocumentManager docMgr = adminClient.newJSONDocumentManager(); DocumentMetadataHandle docMeta = new DocumentMetadataHandle(); docMeta.getPermissions().add("rest-reader", DocumentMetadataHandle.Capability.EXECUTE); endpointUtil.setupEndpointSingleRequired(docMgr, docMeta, "singleAtomic", "double"); adminClient.release(); callableEndpoint = endpointUtil.makeCallableEndpoint("singleAtomic"); caller = endpointUtil.makeOneCaller(callableEndpoint, Double.class); }
Source:
public boolean isExpired() { try { JWT jwt = this.getIdToken(); JWTClaimsSet claims = jwt.getJWTClaimsSet(); Date expiresOn = claims.getExpirationTime(); Calendar now = Calendar.getInstance(); now.add( Calendar.MINUTE, 5 ); if (expiresOn.before(now.getTime())) { return true; } } catch (ParseException e) { throw new TechnicalException(e); } return false; }

Target:
public boolean isExpired() { try { JWT jwt = this.getIdToken(); JWTClaimsSet claims = jwt.getJWTClaimsSet(); Date expiresOn = claims.getExpirationTime(); Calendar now = Calendar.getInstance(); now.add( Calendar.SECOND, idTokenExpireAdvance ); if (expiresOn.before(now.getTime())) { return true; } } catch (ParseException e) { throw new TechnicalException(e); } return false; }
Source:
static IdToken getIdToken(String serviceAccountEmail, Credentials credentials, HttpTransport transport, String targetAudience, boolean includeEmail, Map<String, ?> additionalFields) throws IOException { IdToken token; token = getOIDCToken(serviceAccountEmail, credentials, transport, targetAudience, includeEmail, additionalFields); return token; }

Target:
static IdToken getIdToken( String serviceAccountEmail, Credentials credentials, HttpTransport transport, String targetAudience, boolean includeEmail, Map<String, ?> additionalFields) throws IOException { String idTokenUrl = String.format(ID_TOKEN_URL_FORMAT, serviceAccountEmail); GenericUrl genericUrl = new GenericUrl(idTokenUrl); GenericData idTokenRequest = new GenericData(); idTokenRequest.set("audience", targetAudience); idTokenRequest.set("includeEmail", includeEmail); for (Map.Entry<String, ?> entry : additionalFields.entrySet()) { idTokenRequest.set(entry.getKey(), entry.getValue()); } JsonHttpContent idTokenContent = new JsonHttpContent(OAuth2Utils.JSON_FACTORY, idTokenRequest); HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials); HttpRequest request = transport.createRequestFactory(adapter).buildPostRequest(genericUrl, idTokenContent); JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY); request.setParser(parser); request.setThrowExceptionOnExecuteError(false); HttpResponse response = request.execute(); int statusCode = response.getStatusCode(); if (statusCode >= 400 && statusCode < HttpStatusCodes.STATUS_CODE_SERVER_ERROR) { GenericData responseError = response.parseAs(GenericData.class); Map<String, Object> error = OAuth2Utils.validateMap(responseError, "error", PARSE_ERROR_MESSAGE); String errorMessage = OAuth2Utils.validateString(error, "message", PARSE_ERROR_MESSAGE); throw new IOException( String.format("Error code %s trying to getIDToken: %s", statusCode, errorMessage)); } if (statusCode != HttpStatusCodes.STATUS_CODE_OK) { throw new IOException( String.format( "Unexpected Error code %s trying to getIDToken: %s", statusCode, response.parseAsString())); } InputStream content = response.getContent(); if (content == null) { throw new IOException("Empty content from generateIDToken server request."); } GenericJson responseData = response.parseAs(GenericJson.class); String rawToken = OAuth2Utils.validateString(responseData, "token", PARSE_ERROR_MESSAGE); return IdToken.create(rawToken); }
Source:
public void getAppConfigForUser() { Survey survey = Survey.create(); survey.setIdentifier("theIdentifier"); survey.setGuid(SURVEY_REF_LIST.get(0).getGuid()); survey.setCreatedOn(SURVEY_REF_LIST.get(0).getCreatedOn().getMillis()); when(surveyService.getSurvey(SURVEY_KEY)).thenReturn(survey); CriteriaContext context = new CriteriaContext.Builder() .withClientInfo(ClientInfo.fromUserAgentCache("app/7 (Motorola Flip-Phone; Android/14) BridgeJavaSDK/10")) .withStudyIdentifier(TEST_STUDY).build(); AppConfig appConfig2 = setupConfigsForUser(); AppConfig match = service.getAppConfigForUser(context, true); assertEquals(appConfig2, match); assertEquals("theIdentifier", match.getSurveyReferences().get(0).getIdentifier()); }

Target:
public void getAppConfigForUser() { Survey survey = Survey.create(); survey.setIdentifier("theIdentifier"); survey.setGuid(SURVEY_REF_LIST.get(0).getGuid()); survey.setCreatedOn(SURVEY_REF_LIST.get(0).getCreatedOn().getMillis()); when(surveyService.getSurvey(SURVEY_KEY, false)).thenReturn(survey); CriteriaContext context = new CriteriaContext.Builder() .withClientInfo(ClientInfo.fromUserAgentCache("app/7 (Motorola Flip-Phone; Android/14) BridgeJavaSDK/10")) .withStudyIdentifier(TEST_STUDY).build(); AppConfig appConfig2 = setupConfigsForUser(); AppConfig match = service.getAppConfigForUser(context, true); assertEquals(appConfig2, match); assertEquals("theIdentifier", match.getSurveyReferences().get(0).getIdentifier()); }
Source:
public static TestTable getSerialTable() { return new TestTable( TableSchema.builder() .field("f0", DataTypes.SMALLINT()) .field("f1", DataTypes.INT()) .field("f2", DataTypes.SMALLINT()) .field("f3", DataTypes.INT()) .field("f4", DataTypes.BIGINT()) .field("f5", DataTypes.BIGINT()) .build(), "f0 smallserial, " + "f1 serial, " + "f2 serial2, " + "f3 serial4, " + "f4 serial8, " + "f5 bigserial", "0," + "1," + "2," + "3," + "4," + "5" ); }

Target:
public static TestTable getSerialTable() { return new TestTable( TableSchema.builder() .field("f0", DataTypes.SMALLINT().notNull()) .field("f1", DataTypes.INT().notNull()) .field("f2", DataTypes.SMALLINT().notNull()) .field("f3", DataTypes.INT().notNull()) .field("f4", DataTypes.BIGINT().notNull()) .field("f5", DataTypes.BIGINT().notNull()) .build(), "f0 smallserial, " + "f1 serial, " + "f2 serial2, " + "f3 serial4, " + "f4 serial8, " + "f5 bigserial", "32767," + "2147483647," + "32767," + "2147483647," + "9223372036854775807," + "9223372036854775807" ); }
Source:
private boolean isExportCommandAvailable() { ArrayList<Disk> disks = (ArrayList<Disk>) getSelectedItems(); if (disks == null || disks.size() < 1) { return false; } for (Disk disk : disks) { if (disk.getDiskStorageType() != DiskStorageType.IMAGE) { return false; } DiskImage diskImage = (DiskImage) disk; if (diskImage.getImageStatus() != ImageStatus.OK || !diskImage.getParentId().equals(Guid.Empty)) { return false; } } return true; }

Target:
private boolean isExportCommandAvailable() { ArrayList<Disk> disks = (ArrayList<Disk>) getSelectedItems(); if (disks == null || disks.isEmpty()) { return false; } for (Disk disk : disks) { if (disk.getDiskStorageType() != DiskStorageType.IMAGE) { return false; } DiskImage diskImage = (DiskImage) disk; if (diskImage.getImageStatus() != ImageStatus.OK || !diskImage.getParentId().equals(Guid.Empty)) { return false; } } return true; }
Source:
private static void removeOutputFiles(@NotNull Collection<String> removedFiles, @NotNull File... outputDirectories) { for (File dir : outputDirectories) { List<File> outputErlangModuleFiles = ContainerUtil.concat(getBeams(findErlFiles(removedFiles), dir), getAppsOutput(findAppFiles(removedFiles), dir)); for (File output : outputErlangModuleFiles) { if (output.exists()) { output.delete(); } } } }

Target:
private static void removeOutputFiles(@NotNull Collection<String> removedFiles, @NotNull File... outputDirectories) { for (File dir : outputDirectories) { List<File> outputErlangModuleFiles = ContainerUtil.concat(getBeams(findErlFiles(removedFiles), dir), getAppsOutput(findAppFiles(removedFiles), dir)); for (File output : outputErlangModuleFiles) { if (output.exists() && !output.delete()) { LOG.warn("Can't delete file " + output.getAbsolutePath()); } } } }
Source:
public void testSendMultipleBroadcasts() throws InterruptedException { int[] values = new int[] {30, 60, -30, -60}; List<UserVariable> variables = createProject(values); baseActivityTestRule.launchActivity(null); Thread.sleep(1500); for (int i = 0; i < variables.size(); i++) { UiTestUtils.waitForVariableValueEquals(variables.get(i), values[i], 2000); } }

Target:
public void testSendMultipleBroadcasts() throws InterruptedException { baseActivityTestRule.launchActivity(null); for (int i = 0; i < userVariables.size(); i++) { Assert.assertTrue(StageTestUtils.userVariableEqualsWithinTimeout(userVariables.get(i), VALUES[i], 2000)); } }
Source:
public Set<URI> getHasSelfImplyingType(final Resource type){ final Set<URI> properties = new HashSet<>(); properties.addAll(hasSelfByType.get(type)); if (type instanceof URI) { for (final URI subtype : findParents(subClassOfGraph, (URI) type)) { properties.addAll(hasSelfByType.get(subtype)); } } return properties; }

Target:
public Set<URI> getHasSelfImplyingType(final Resource type){ final Set<URI> properties = new HashSet<>(); Set<URI> tempProperties = hasSelfByType.get(type); if (tempProperties != null) { properties.addAll(tempProperties); } if (type instanceof URI) { for (final URI subtype : findParents(subClassOfGraph, (URI) type)) { tempProperties = hasSelfByType.get(subtype); if (tempProperties != null) { properties.addAll(tempProperties); } } } return properties; }
Source:
protected Ecdsa() { super("NONEwithEDCSA"); }

Target:
protected Ecdsa() { super("NONEwithECDSA"); }
Source:
public ICommandShell createCommandShell() { LTTngToolsFileShell shell = fShell; if (shell == null) { shell = new LTTngToolsFileShell(); if ((fTestFile != null) && (fScenario != null)) { shell.loadScenarioFile(fTestFile); shell.setScenario(fScenario); } fShell = shell; } return shell; }

Target:
public ICommandShell createCommandShell() { LTTngToolsFileShell shell = fShell; if (shell == null) { shell = new LTTngToolsFileShell(); if ((fTestFile != null) && (fScenario != null)) { shell.loadScenarioFile(fTestFile); shell.setScenario(fScenario); fShell = shell; } fShell = shell; } return shell; }
Source:
private JsonToRowDataConverter wrapIntoNullableConverter( JsonToRowDataConverter converter) { return jsonNode -> { if (jsonNode == null || jsonNode.isNull() || jsonNode instanceof MissingNode) { return null; } try { return converter.convert(jsonNode); } catch (Throwable t) { if (!ignoreParseErrors) { throw t; } return null; } }; }

Target:
private JsonToRowDataConverter wrapIntoNullableConverter( JsonToRowDataConverter converter) { return jsonNode -> { if (jsonNode == null || jsonNode.isNull() || jsonNode.isMissingNode()) { return null; } try { return converter.convert(jsonNode); } catch (Throwable t) { if (!ignoreParseErrors) { throw t; } return null; } }; }
Source:
public T take() { fOutputLock.lock(); try { if (fOutputBuffer.isEmpty()) { @SuppressWarnings("null") Deque<T> value = fInnerQueue.remove(); if (!value.isEmpty()) { Activator.instance().logError("Queue chunk not empty " + value); } while (fInnerQueue.isEmpty()) { fInnerQueueNotEmpty.await(); } fOutputBuffer = checkNotNull(fInnerQueue.peek()); } T element = checkNotNull(fOutputBuffer.remove()); fSize.decrementAndGet(); return element; } catch (InterruptedException e) { Activator.instance().logError(BUFFERED_QUEUE_INTERRUPTED, e); Thread.currentThread().interrupt(); throw new IllegalStateException(e); } finally { fOutputLock.unlock(); } }

Target:
public T take() { fOutputLock.lock(); try { if (fOutputBuffer.isEmpty()) { Deque<T> value = fInnerQueue.remove(); if (!value.isEmpty()) { Activator.instance().logError("Queue chunk not empty " + value); } while (fInnerQueue.isEmpty()) { fInnerQueueNotEmpty.await(); } fOutputBuffer = checkNotNull(fInnerQueue.peek()); } T element = checkNotNull(fOutputBuffer.remove()); fSize.decrementAndGet(); return element; } catch (InterruptedException e) { Activator.instance().logError(BUFFERED_QUEUE_INTERRUPTED, e); Thread.currentThread().interrupt(); throw new IllegalStateException(e); } finally { fOutputLock.unlock(); } }
Source:
private Change computeChangeFromGamma(CompositeKeyHashMap<TransactionRecord, Integer, Artifact> bulkLoaded, IOseeBranch startTxBranch, ChangeItem item) { Change change = null; try { int artId = item.getArtId(); Long destGamma = item.getDestinationVersion().getGammaId(); Long baseGamma = item.getBaselineVersion().getGammaId(); Artifact startTxArtifact; Artifact endTxArtifact; if (txDelta.areOnTheSameBranch()) { startTxArtifact = bulkLoaded.get(txDelta.getStartTx(), artId); endTxArtifact = bulkLoaded.get(txDelta.getEndTx(), artId); } else { startTxArtifact = bulkLoaded.get(txDelta.getEndTx(), artId); endTxArtifact = bulkLoaded.get(txDelta.getStartTx(), artId); } Artifact baseTxArtifact; if ((baseGamma != null) && baseGamma.equals(destGamma)) { baseTxArtifact = startTxArtifact; } else { if (baseGamma == null) { baseTxArtifact = endTxArtifact; } baseTxArtifact = bulkLoaded.get(txDelta.getStartTx().getBranch().getBaseTransaction(), artId); } ArtifactDelta artifactDelta = new ArtifactDelta(txDelta, startTxArtifact, endTxArtifact, baseTxArtifact); change = createChangeObject(bulkLoaded, item, txDelta, startTxBranch, artifactDelta); change.setChangeItem(item); } catch (Exception ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); change = new ErrorChange(startTxBranch, item.getArtId(), ex.toString()); } return change; }

Target:
private Change computeChangeFromGamma(CompositeKeyHashMap<TransactionRecord, Integer, Artifact> bulkLoaded, IOseeBranch startTxBranch, ChangeItem item) { Change change = null; try { int artId = item.getArtId(); Long destGamma = item.getDestinationVersion().getGammaId(); Long baseGamma = item.getBaselineVersion().getGammaId(); Artifact startTxArtifact; Artifact endTxArtifact; if (txDelta.areOnTheSameBranch()) { startTxArtifact = bulkLoaded.get(txDelta.getStartTx(), artId); endTxArtifact = bulkLoaded.get(txDelta.getEndTx(), artId); } else { startTxArtifact = bulkLoaded.get(txDelta.getEndTx(), artId); endTxArtifact = bulkLoaded.get(txDelta.getStartTx(), artId); } Artifact baseTxArtifact; if ((baseGamma != null) && baseGamma.equals(destGamma)) { baseTxArtifact = startTxArtifact; } else { baseTxArtifact = bulkLoaded.get(txDelta.getStartTx().getBranch().getBaseTransaction(), artId); } ArtifactDelta artifactDelta = new ArtifactDelta(txDelta, startTxArtifact, endTxArtifact, baseTxArtifact); change = createChangeObject(bulkLoaded, item, txDelta, startTxBranch, artifactDelta); change.setChangeItem(item); } catch (Exception ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); change = new ErrorChange(startTxBranch, item.getArtId(), ex.toString()); } return change; }
Source:
private void shutdownMySqlAbandonedConnectionCleanupThread() { try { Class<?> cleanupThreadsClass = findMySqlDriverClass(); if (cleanupThreadsClass == null) { logger.warn("No AbandonedConnectionCleanupThread class found. Check if thread class is between " + CONNECTION_CLEANUP_THREAD_KNOWN_CLASS_ADDRESES.toString()); throw new ClassNotFoundException(CONNECTION_CLEANUP_THREAD_KNOWN_CLASS_ADDRESES.get(0)); } shutdownMySqlConnectionCleanupThreads(cleanupThreadsClass); try { cleanMySqlCleanupThreadsThreadFactory(cleanupThreadsClass); } catch (NoSuchFieldException e) { logger.warn("Error cleaning threadFactory from AbandonedConnectionCleanupThread executor service"); } } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.warn("Unable to shutdown MySql's AbandonedConnectionCleanupThread", e); } }

Target:
private void shutdownMySqlAbandonedConnectionCleanupThread() { try { Class<?> cleanupThreadsClass = findMySqlDriverClass(); shutdownMySqlConnectionCleanupThreads(cleanupThreadsClass); cleanMySqlCleanupThreadsThreadFactory(cleanupThreadsClass); } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { logger.warn("Unable to shutdown MySql's AbandonedConnectionCleanupThread", e); } }
Source:
public void dispose() { fSegmentArray = null; }

Target:
public void dispose() { fSegmentArray = null; fTableViewer = null; fComparator = null; }
Source:
private boolean isWorkItemAvailable(final PortableWorkDefinition pwd) { if (isNewColumn()) { return !getPresenter() .getModel() .getActionCols() .stream() .filter(a -> a instanceof ActionWorkItemCol52) .map(a -> ((ActionWorkItemCol52) a).getWorkItemDefinition()) .anyMatch(p -> p.getName().equals(pwd.getName())); } return true; }

Target:
private boolean isWorkItemAvailable(final PortableWorkDefinition pwd) { final boolean isUsedInModel = getPresenter() .getModel() .getActionCols() .stream() .filter(a -> a instanceof ActionWorkItemCol52) .map(a -> ((ActionWorkItemCol52) a).getWorkItemDefinition()) .anyMatch(p -> p.getName().equals(pwd.getName())); if (isNewColumn()) { return !isUsedInModel; } else if (!isWorkItemSet()) { return !isUsedInModel; } else { final String pwdName = pwd.getName(); return pwdName.equals(getWorkItemDefinition().getName()) || !isUsedInModel; } }
Source:
protected Manager(HttpPipeline httpPipeline, AzureProfile profile, InnerT innerManagementClient) { this.httpPipeline = httpPipeline; if (httpPipeline != null) { ResourceManager.Configurable resourceConfigurable = ResourceManager.configure(); withInternalHttpPipeline(resourceConfigurable, httpPipeline); this.resourceManager = resourceConfigurable.authenticate(null, profile).withDefaultSubscription(); } this.subscriptionId = profile.getSubscriptionId(); this.environment = profile.getEnvironment(); this.innerManagementClient = innerManagementClient; }

Target:
protected Manager(HttpPipeline httpPipeline, AzureProfile profile, InnerT innerManagementClient) { this.httpPipeline = httpPipeline; if (httpPipeline != null) { this.resourceManager = AzureConfigurableImpl .configureHttpPipeline(httpPipeline, ResourceManager.configure()) .authenticate(null, profile) .withDefaultSubscription(); } this.subscriptionId = profile.getSubscriptionId(); this.environment = profile.getEnvironment(); this.innerManagementClient = innerManagementClient; }
Source:
private Iterable<XeSource> bouts(final Request req, final String query) throws IOException { final Iterable<Bout> bouts; if (StringUtils.isBlank(query)) { long since = Inbox.NEVER; final Iterator<String> param = new RqHref.Base(req).href() .param("since").iterator(); if (param.hasNext()) { since = Long.parseLong(param.next()); } bouts = Iterables.limit(new RqAlias(this.base, req).alias().inbox() .jump(since).iterate(), Inbox.PAGE ); } else { bouts = new RqAlias(this.base, req).alias().inbox().search(query); } return new XeTransform<>( bouts, new XeTransform.Func<Bout>() { @Override public XeSource transform(final Bout bout) throws IOException { return TkInbox.source(bout); } } ); }

Target:
private Iterable<XeSource> bouts(final Request req, final String query) throws IOException { final Iterable<Bout> bouts; final Inbox inbox = new RqAlias(this.base, req).alias().inbox(); if (StringUtils.isBlank(query)) { long since = Inbox.NEVER; final Iterator<String> param = new RqHref.Base(req).href() .param("since").iterator(); if (param.hasNext()) { since = Long.parseLong(param.next()); } bouts = inbox.jump(since).iterate(); } else { bouts = inbox.search(query); } return new XeTransform<>( Iterables.limit(bouts, Inbox.PAGE), new XeTransform.Func<Bout>() { @Override public XeSource transform(final Bout bout) throws IOException { return TkInbox.source(bout); } } ); }
Source:
private Session getOrOpenTargetSession(final URI sessionResourceUri) { Session session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); if (session == null) { ModelingProjectManager.INSTANCE.loadAndOpenRepresentationsFile(sessionResourceUri, true); try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { throw new RuntimeException(e); } session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); } return session; }

Target:
private Session getOrOpenTargetSession(final URI sessionResourceUri) { Session session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); if (session == null) { ModelingProjectManager.INSTANCE.loadAndOpenRepresentationsFile(sessionResourceUri, true); try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { } session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); } return session; }
Source:
public <T> T readObject(Class<T> clazz) throws IOException, ClassNotFoundException { int classNameLength = dis.readInt(); int bytesLength = dis.readInt(); if (classNameLength < 0 || bytesLength < 0) { throw new IOException(); } byte[] classNameBytes = new byte[classNameLength]; dis.read(classNameBytes, 0, classNameLength); byte[] bytes = new byte[bytesLength]; dis.read(bytes, 0, bytesLength); T result; if (Utils.WRAPPER_SET.contains(clazz) || clazz.isArray() || clazz.isEnum()) { Schema<Wrapper> schema = RuntimeSchema.getSchema(Wrapper.class); Wrapper wrapper = schema.newMessage(); ProtobufIOUtil.mergeFrom(bytes, wrapper, schema); result = (T) wrapper.getData(); } else { Schema<T> schema = RuntimeSchema.getSchema(clazz); result = schema.newMessage(); ProtobufIOUtil.mergeFrom(bytes, result, schema); } return result; }

Target:
public <T> T readObject(Class<T> clazz) throws IOException, ClassNotFoundException { int classNameLength = dis.readInt(); int bytesLength = dis.readInt(); if (classNameLength < 0 || bytesLength < 0) { throw new IOException(); } byte[] classNameBytes = new byte[classNameLength]; dis.read(classNameBytes, 0, classNameLength); byte[] bytes = new byte[bytesLength]; dis.read(bytes, 0, bytesLength); T result; if (WrapperUtils.needWrapper(clazz)) { Schema<Wrapper> schema = RuntimeSchema.getSchema(Wrapper.class); Wrapper wrapper = schema.newMessage(); ProtobufIOUtil.mergeFrom(bytes, wrapper, schema); result = (T) wrapper.getData(); } else { Schema<T> schema = RuntimeSchema.getSchema(clazz); result = schema.newMessage(); ProtobufIOUtil.mergeFrom(bytes, result, schema); } return result; }
Source:
private void _startTimeout() { ClockModel pc = getClockModel(Clock.ID_PERIOD); ClockModel tc = getClockModel(Clock.ID_TIMEOUT); requestBatchStart(); if (tc.isRunning()) { if (getTimeoutOwner()=="") { setTimeoutOwner("O"); } else { setTimeoutOwner(""); } return; } pc.stop(); _endLineup(); _endJam(false); _endIntermission(false); setInPeriod(true); tc.startNext(); }

Target:
private void _startTimeout() { ClockModel pc = getClockModel(Clock.ID_PERIOD); ClockModel tc = getClockModel(Clock.ID_TIMEOUT); requestBatchStart(); if (tc.isRunning()) { if (getTimeoutOwner()==TIMEOUT_OWNER_NONE) { setTimeoutOwner(TIMEOUT_OWNER_OTO); } else { setTimeoutOwner(TIMEOUT_OWNER_NONE); } requestBatchEnd(); return; } pc.stop(); _endLineup(); _endJam(false); _endIntermission(false); setInPeriod(true); tc.startNext(); requestBatchEnd(); }
Source:
public void testResponseStreamConsumedByReadingStream() throws Exception { final RestResponse response = getStreamTestResponse(); try (InputStream in = response.asInputStream()) { inputStreamToString(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } final RestResponse anotherResponse = getStreamTestResponse(); assertNotNull(anotherResponse); }

Target:
public void testResponseStreamConsumedByReadingStream() throws Exception { final RestResponse response = getStreamTestResponse(); try { InputStream in = response.asInputStream(); inputStreamToString(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } final RestResponse anotherResponse = getStreamTestResponse(); assertNotNull(anotherResponse); }
Source:
private InputStream fakeBody(final String... dispositions) { final String boundary = "AaB02x"; final Collection<String> parts = new LinkedList<String>(); for (final String disposition : dispositions) { parts.add(String.format("--%s", boundary)); parts.add(disposition); } parts.add("Content-Transfer-Encoding: utf-8"); parts.add(""); parts.add("the start\r\t\n\u20ac\n\n\n\t\r\t\n\n\n\r\n the end"); parts.add(String.format("--%s--", boundary)); return new ByteArrayInputStream( RqMultipart.Fake.join(parts.iterator()).getBytes() ); }

Target:
private static InputStream fakeBody(final String... dispositions) { final StringBuilder builder = new StringBuilder(); for (final String disposition : dispositions) { builder.append(String.format("--%s%s", BOUNDARY, "\r\n")) .append(disposition) .append("\r\n"); } builder.append("Content-Transfer-Encoding: utf-8\r\n") .append(String.format("--%s--", BOUNDARY)); return new ByteArrayInputStream( builder.toString().getBytes() ); }
Source:
public static ImageDescriptor[] getImages(String value, Bundle definingBundle) { URL[] urls = getURLs(value, definingBundle); if (urls == null || urls.length <= 0) { return null; } ImageDescriptor[] images = new ImageDescriptor[urls.length]; for (int i = 0; i < images.length; ++i) { images[i] = ImageDescriptor.createFromURL(urls[i]); } return images; }

Target:
protected static List<ImageDescriptor> getImages(String value, Bundle definingBundle) { List<URL> urls = getURLs(value, definingBundle); if (urls == null || urls.isEmpty()) { return Collections.emptyList(); } List<ImageDescriptor> images = new ArrayList<>(urls.size()); urls.forEach(u -> images.add(ImageDescriptor.createFromURL(u))); return images; }
Source:
public void getFile( @NotBlank(message = "Source file path cannot be empty.") final String srcRemotePath, @NotBlank(message = "Destination local path cannot be empty") final String dstLocalPath ) throws GenieException { final long start = System.nanoTime(); log.debug("Called with src path and destination path {}", srcRemotePath, dstLocalPath); final File outputFile = new File(dstLocalPath); try (final FileOutputStream fos = new FileOutputStream(outputFile)) { this.restTemplate.execute( srcRemotePath, HttpMethod.GET, requestEntity -> requestEntity.getHeaders().setAccept(Lists.newArrayList(MediaType.ALL)), new ResponseExtractor<Void>() { @Override public Void extractData(final ClientHttpResponse response) throws IOException { ByteStreams.copy(response.getBody(), fos); return null; } } ); } catch (final IOException e) { throw new GenieServerException(e); } finally { this.downloadTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }

Target:
public void getFile( @NotBlank(message = "Source file path cannot be empty.") final String srcRemotePath, @NotBlank(message = "Destination local path cannot be empty") final String dstLocalPath ) throws GenieException { final long start = System.nanoTime(); log.debug("Called with src path and destination path {}", srcRemotePath, dstLocalPath); try { final File outputFile = new File(dstLocalPath); if (!this.isValid(srcRemotePath)) { throw new GenieServerException("Unable to download " + srcRemotePath + " not a valid URL"); } this.restTemplate.execute( srcRemotePath, HttpMethod.GET, requestEntity -> requestEntity.getHeaders().setAccept(Lists.newArrayList(MediaType.ALL)), new ResponseExtractor<Void>() { @Override public Void extractData(final ClientHttpResponse response) throws IOException { FileUtils.copyInputStreamToFile(response.getBody(), outputFile); return null; } } ); } finally { this.downloadTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }