auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { Socket socket; OutputStream outputStream = null; try { socket = serverSocket.accept(); String response = getResponse(socket); outputStream = socket.getOutputStream(); writeResponseHeader(outputStream); write(response.getBytes(), outputStream); outputStream.flush(); } catch (IOException e) { } finally { StreamUtils.quietlyClose(outputStream); } }

Target:
public void run() { Socket socket = null; OutputStream outputStream = null; try { socket = serverSocket.accept(); String response = getResponse(socket); outputStream = socket.getOutputStream(); writeResponseHeader(outputStream); write(response.getBytes(), outputStream); outputStream.flush(); } catch (IOException e) { } finally { StreamUtils.quietlyClose(outputStream); } }
Source:
public static MessageType fromId(String id) { for(MessageType current : values()) { if(current.getId().equals(id)) { return current; } } return UNKNOWN; }

Target:
public static Optional<MessageType> fromId(String id) { for (MessageType current : values()) { if (current.getId().equals(id)) { return Optional.of(current); } } return Optional.empty(); }
Source:
public void execute() throws MojoExecutionException, MojoFailureException { try { initGitFlowConfig(); checkUncommittedChanges(); final String releaseBranch = gitFindBranches( gitFlowConfig.getReleaseBranchPrefix(), true); if (StringUtils.isNotBlank(releaseBranch)) { throw new MojoFailureException( "Release branch already exists. Cannot start release."); } if (fetchRemote) { gitFetchRemoteAndCreate(gitFlowConfig.getDevelopmentBranch()); gitFetchRemoteAndCompare(gitFlowConfig.getDevelopmentBranch()); } gitCheckout(gitFlowConfig.getDevelopmentBranch()); if (!allowSnapshots) { checkSnapshotDependencies(); } final String releaseVersion = getReleaseVersion(); String branchName = gitFlowConfig.getReleaseBranchPrefix(); if (!sameBranchName) { branchName += releaseVersion; } if (commitDevelopmentVersionAtStart) { commitProjectVersion(releaseVersion, commitMessages.getReleaseStartMessage()); gitCreateBranch(branchName, gitFlowConfig.getDevelopmentBranch()); final String nextSnapshotVersion = getNextSnapshotVersion(releaseVersion); commitProjectVersion(nextSnapshotVersion, commitMessages.getReleaseFinishMessage()); gitCheckout(branchName); } else { gitCreateAndCheckout(branchName, gitFlowConfig.getDevelopmentBranch()); commitProjectVersion(releaseVersion, commitMessages.getReleaseStartMessage()); } if (installProject) { mvnCleanInstall(); } if (pushRemote) { gitPush(gitFlowConfig.getDevelopmentBranch(), false); gitPush(branchName, false); } } catch (CommandLineException e) { getLog().error(e); } catch (VersionParseException e) { getLog().error(e); } }

Target:
public void execute() throws MojoExecutionException, MojoFailureException { try { initGitFlowConfig(); checkUncommittedChanges(); final String releaseBranch = gitFindBranches( gitFlowConfig.getReleaseBranchPrefix(), true); if (StringUtils.isNotBlank(releaseBranch)) { throw new MojoFailureException( "Release branch already exists. Cannot start release."); } if (fetchRemote) { gitFetchRemoteAndCreate(gitFlowConfig.getDevelopmentBranch()); gitFetchRemoteAndCompare(gitFlowConfig.getDevelopmentBranch()); } gitCheckout(gitFlowConfig.getDevelopmentBranch()); if (!allowSnapshots) { checkSnapshotDependencies(); } final String releaseVersion = getReleaseVersion(); String branchName = gitFlowConfig.getReleaseBranchPrefix(); if (!sameBranchName) { branchName += releaseVersion; } if (commitDevelopmentVersionAtStart) { commitProjectVersion(releaseVersion, commitMessages.getReleaseStartMessage()); gitCreateBranch(branchName, gitFlowConfig.getDevelopmentBranch()); final String nextSnapshotVersion = getNextSnapshotVersion(releaseVersion); commitProjectVersion(nextSnapshotVersion, commitMessages.getReleaseFinishMessage()); gitCheckout(branchName); } else { gitCreateAndCheckout(branchName, gitFlowConfig.getDevelopmentBranch()); commitProjectVersion(releaseVersion, commitMessages.getReleaseStartMessage()); } if (installProject) { mvnCleanInstall(); } if (pushRemote) { if (commitDevelopmentVersionAtStart) { gitPush(gitFlowConfig.getDevelopmentBranch(), false); } gitPush(branchName, false); } } catch (CommandLineException e) { getLog().error(e); } catch (VersionParseException e) { getLog().error(e); } }
Source:
private void checkForDuplicates(List<WindupRuleProvider> providers) { Set<WindupRuleProvider> dupeSet = new HashSet<>(providers.size()); for (WindupRuleProvider provider : providers) { if (dupeSet.contains(provider)) { throw new WindupException("Found two providers with the same id: " + provider.getID()); } dupeSet.add(provider); } }

Target:
private void checkForDuplicates(List<WindupRuleProvider> providers) { Map<WindupRuleProvider, WindupRuleProvider> dupeSet = new HashMap<>(providers.size()); for (WindupRuleProvider provider : providers) { WindupRuleProvider previousProvider = dupeSet.get(provider); if (previousProvider != null) { String typeMessage; if (previousProvider.getClass().equals(provider.getClass())) { typeMessage = " (type: " + Proxies.unwrapProxyClassName(provider.getClass()) + ")"; } else { typeMessage = " (types: " + Proxies.unwrapProxyClassName(previousProvider.getClass()) + " and " + Proxies.unwrapProxyClassName(provider.getClass()) + ")"; } throw new WindupException("Found two providers with the same id: " + provider.getID() + typeMessage); } dupeSet.put(provider, provider); } }
Source:
public void setup() throws Exception{ this.metadataStore = new HazelcastMetadataStore(map); metadataStore.afterPropertiesSet(); }

Target:
public void setup() throws Exception { this.metadataStore = new HazelcastMetadataStore(map); this.metadataStore.afterPropertiesSet(); }
Source:
public CompletableFuture<Optional<Pair<PublicKeyHash, PublicBoxingKey>>> getPublicKeys(String username) { CompletableFuture<Optional<Pair<PublicKeyHash, PublicBoxingKey>>> empty = new CompletableFuture<>(); empty.complete(Optional.empty()); return network.coreNode.getPublicKeyHash(username) .thenCompose(signerOpt -> !signerOpt.isPresent() ? empty : getSigningKey(signerOpt.get()) .thenCompose(signer -> getWriterData(network, signerOpt.get(), signerOpt.get()) .thenCompose(wd -> getBoxingKey(wd.props.followRequestReceiver.get()) .thenApply(boxer -> Optional.of(new Pair<>(signerOpt.get(), boxer)))))); }

Target:
public CompletableFuture<Optional<Pair<PublicKeyHash, PublicBoxingKey>>> getPublicKeys(String username) { return network.coreNode.getPublicKeyHash(username) .thenCompose(signerOpt -> signerOpt.map(signer -> getSigningKey(signer) .thenCompose(signer2 -> getWriterData(network, signerOpt.get(), signerOpt.get()) .thenCompose(wd -> getBoxingKey(wd.props.followRequestReceiver.get()) .thenApply(boxer -> Optional.of(new Pair<>(signerOpt.get(), boxer)))))) .orElse(CompletableFuture.completedFuture(Optional.empty()))); }
Source:
private String getTerm(URL url) throws MalformedURLException { String query = url.getQuery(); if (query != null) return Utils.parseUrlQuery(query, "tags"); if (query == null) { if ((query = url.getPath()).startsWith("/post/index/")) { query = query.substring(12); int pos = query.indexOf('/'); if (pos == -1) return null; query = query.substring(pos + 1); if (query.endsWith("/")) query = query.substring(0, query.length() - 1); try { return URLDecoder.decode(query, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } else if (query.startsWith("/pool/show/")) { query = query.substring(11); if (query.endsWith("/")) query = query.substring(0, query.length() - 1); return query; } } return null; }

Target:
private String getTerm(URL url) throws MalformedURLException{ if(gidPattern==null) gidPattern=Pattern.compile("^https?://(www\\.)?e621\\.net/post/index/[^/]+/([a-zA-Z0-9$_.+!*'(),%-]+)(/.*)?(#.*)?$"); if(gidPatternPool==null) gidPatternPool=Pattern.compile("^https?://(www\\.)?e621\\.net/pool/show/([a-zA-Z0-9$_.+!*'(),%-]+)(\\?.*)?(/.*)?(#.*)?$"); Matcher m = gidPattern.matcher(url.toExternalForm()); if(m.matches()) return m.group(2); m = gidPatternPool.matcher(url.toExternalForm()); if(m.matches()) return m.group(2); throw new MalformedURLException("Expected e621.net URL format: e621.net/post/index/1/searchterm - got "+url+" instead"); }
Source:
public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (status == NO_ERROR_STATUS) { complete(buf.readInt()); } else { complete(XAResource.XA_OK); } }

Target:
public void acceptResponse(ByteBuf buf, short status, HeaderDecoder decoder) { if (status == NO_ERROR_STATUS) { complete(buf.readInt()); } else { complete(XAException.XA_HEURRB); } }
Source:
public void onRequestPermissionsResult (int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (mCurrentChangeRequest == null) { throw new IllegalStateException("mCurrentChangeRequest should be set before using cached request"); } if (requestCode == REQUEST_AUDIO_PERMISSION && permissions.length == 1) { recreateEditingUi(mCurrentChangeRequest); } if (requestCode == REQUEST_CAMERA_PERMISSION && permissions.length == 1) { recreateEditingUi(mCurrentChangeRequest); } }

Target:
public void onRequestPermissionsResult (int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (mCurrentChangeRequest == null) { cancelActivityWithAssertionFailure("mCurrentChangeRequest should be set before requesting permissions"); return; } Timber.d("onRequestPermissionsResult. Code: %d", requestCode); if (requestCode == REQUEST_AUDIO_PERMISSION && permissions.length == 1) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { recreateEditingUIUsingCachedRequest(); return; } UIUtils.showThemedToast(this, getResources().getString(R.string.multimedia_editor_audio_permission_refused), true); UIRecreationHandler.onRequiredPermissionDenied(mCurrentChangeRequest, this); } if (requestCode == REQUEST_CAMERA_PERMISSION && permissions.length == 1) { if (grantResults[0] != PackageManager.PERMISSION_GRANTED) { UIUtils.showThemedToast(this, getResources().getString(R.string.multimedia_editor_camera_permission_refused), true); } recreateEditingUIUsingCachedRequest(); } }
Source:
protected boolean checkIfLunDiskCanBeAdded() { LUNs lun = ((LunDisk) getParameters().getDiskInfo()).getLun(); switch (lun.getLunType()) { case UNKNOWN: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); case ISCSI: if (lun.getLunConnections() == null || lun.getLunConnections().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } for (StorageServerConnections conn : lun.getLunConnections()) { if (StringUtils.isEmpty(conn.getiqn()) || StringUtils.isEmpty(conn.getconnection()) || StringUtils.isEmpty(conn.getport())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } } break; } if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE); } return validate(getSnapshotValidator().vmNotDuringSnapshot(getVmId())) && validate(getSnapshotValidator().vmNotInPreview(getVmId())) && validate(new VmValidator(getVm()).vmNotLocked()); }

Target:
protected boolean checkIfLunDiskCanBeAdded() { LUNs lun = ((LunDisk) getParameters().getDiskInfo()).getLun(); switch (lun.getLunType()) { case UNKNOWN: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); case ISCSI: if (lun.getLunConnections() == null || lun.getLunConnections().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } for (StorageServerConnections conn : lun.getLunConnections()) { if (StringUtils.isEmpty(conn.getiqn()) || StringUtils.isEmpty(conn.getconnection()) || StringUtils.isEmpty(conn.getport())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } } break; } if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE); } if (getVm() == null) { return true; } return validate(getSnapshotValidator().vmNotDuringSnapshot(getVmId())) && validate(getSnapshotValidator().vmNotInPreview(getVmId())) && validate(new VmValidator(getVm()).vmNotLocked()); }
Source:
public List<CompletePaxosHistoryForNamespaceAndUseCase> getHistory() throws RuntimeException { Map<NamespaceAndUseCase, Long> lastVerifiedSequences = KeyedStream .of(getNamespaceAndUseCaseTuples().stream()) .map(namespaceAndUseCase -> verificationProgressStateCache.computeIfAbsent(namespaceAndUseCase, this::getOrInsertVerificationState)) .collectToMap(); List<HistoryQuery> historyQueries = KeyedStream.stream(lastVerifiedSequences) .mapEntries(this::buildHistoryQuery) .values() .collect(Collectors.toList()); PaxosHistoryOnSingleNode localPaxosHistory = localHistoryLoader.getLocalPaxosHistory( lastVerifiedSequences); List<List<LogsForNamespaceAndUseCase>> rawHistoryFromAllRemotes = remoteHistoryProviders.stream().map( remote -> fetchHistoryFromRemote(historyQueries, remote)).collect(Collectors.toList()); List<Map<NamespaceAndUseCase, Map<Long, LearnedAndAcceptedValue>>> historyLogsFromRemotes = rawHistoryFromAllRemotes.stream() .map(this::buildHistoryFromRemoteResponse) .collect(Collectors.toList()); return lastVerifiedSequences.keySet().stream() .map(namespaceAndUseCase -> buildCompleteHistory( namespaceAndUseCase, localPaxosHistory, historyLogsFromRemotes)) .collect(Collectors.toList()); }

Target:
public List<CompletePaxosHistoryForNamespaceAndUseCase> getHistory() { Map<NamespaceAndUseCase, Long> lastVerifiedSequences = getNamespaceAndUseCaseToLastVerifiedSeqMap(); PaxosHistoryOnSingleNode localPaxosHistory = localHistoryLoader.getLocalPaxosHistory(lastVerifiedSequences); List<HistoryQuery> historyQueries = getHistoryQueryListForRemoteServers(lastVerifiedSequences); List<PaxosHistoryOnRemote> rawHistoryFromAllRemotes = getHistoriesFromRemoteServers(historyQueries); List<NamespaceAndUseCaseWiseConsolidatedLearnerAndAcceptorRecords> historyFromAllRemotes = buildHistoryFromRemoteResponses(rawHistoryFromAllRemotes); return consolidateAndGetHistoriesAcrossAllNodes( lastVerifiedSequences, localPaxosHistory, historyFromAllRemotes); }
Source:
public void testFirstNameIsChosenForSerialization() { MyClass target = new MyClass("v1", "v2"); assertTrue(gson.toJson(target).contains("\"name1\":\"v2\"")); }

Target:
public void testFirstNameIsChosenForSerialization() { MyClass target = new MyClass("v1", "v2"); assertEquals("{\"name\":\"v1\",\"name1\":\"v2\"}", gson.toJson(target)); }
Source:
public VmConsoles getVmConsoles() { return poolRepresentative == null ? consolesCache.getVmConsolesForVm((VM) getEntity()) : consolesCache.getVmConsolesForPool(poolRepresentative); }

Target:
public VmConsoles getVmConsoles() { return poolRepresentative == null ? consolesFactory.getVmConsolesForVm((VM) getEntity()) : consolesFactory.getVmConsolesForPool(poolRepresentative); }
Source:
SupplierWithException<BufferPool, IOException> createBufferPoolFactory( int numberOfSubpartitions, ResultPartitionType type) { return () -> { int maxNumberOfMemorySegments = type.isBounded() ? numberOfSubpartitions * networkBuffersPerChannel + floatingNetworkBuffersPerGate : Integer.MAX_VALUE; int numRequiredBuffers = numberOfSubpartitions + 1; if (isSortMergeBlockingShuffle(type, numberOfSubpartitions)) { maxNumberOfMemorySegments = Math.max( numberOfSubpartitions * networkBuffersPerChannel + floatingNetworkBuffersPerGate, maxBuffersPerSortMergePartition); numRequiredBuffers = Math.min(numRequiredBuffers, maxBuffersPerSortMergePartition); } return bufferPoolFactory.createBufferPool( numRequiredBuffers, maxNumberOfMemorySegments, numberOfSubpartitions, maxBuffersPerChannel); }; }

Target:
SupplierWithException<BufferPool, IOException> createBufferPoolFactory( int numberOfSubpartitions, ResultPartitionType type) { return () -> { int maxNumberOfMemorySegments = type.isBounded() ? numberOfSubpartitions * networkBuffersPerChannel + floatingNetworkBuffersPerGate : Integer.MAX_VALUE; int numRequiredBuffers = !type.isPipelined() && numberOfSubpartitions >= sortShuffleMinParallelism ? sortShuffleMinBuffers : numberOfSubpartitions + 1; return bufferPoolFactory.createBufferPool( numRequiredBuffers, maxNumberOfMemorySegments, numberOfSubpartitions, maxBuffersPerChannel); }; }
Source:
public boolean onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(R.id.comments); MenuItem favoriteGuide = menu.findItem(R.id.favorite_guide); TextView countView = ((TextView) item.getActionView().findViewById(R.id.comment_count)); if (mGuide != null) { int stepIndex = getStepIndex(); int commentCount = 0; if (stepIndex < 0) { commentCount = mGuide.getCommentCount(); } else { commentCount = mGuide.getStep(stepIndex).getCommentCount(); } Log.d("GuideStep", "onPrepareOptionsMenu " + commentCount); if (countView != null) { countView.setText(commentCount + ""); } } boolean favorited = mGuide != null ? mGuide.isFavorited() : false; favoriteGuide.setIcon(favorited ? R.drawable.ic_action_favorite_filled : R.drawable.ic_action_favorite_empty); favoriteGuide.setEnabled(!mFavoriting && mGuide != null); favoriteGuide.setTitle(favorited ? R.string.unfavorite_guide : R.string.favorite_guide); return super.onPrepareOptionsMenu(menu); }

Target:
public boolean onPrepareOptionsMenu(Menu menu) { MenuItem comments = menu.findItem(R.id.comments); MenuItem favoriteGuide = menu.findItem(R.id.favorite_guide); MenuItem reloadGuide = menu.findItem(R.id.reload_guide); MenuItem editGuide = menu.findItem(R.id.edit_guide); TextView countView = ((TextView)comments.getActionView().findViewById(R.id.comment_count)); if (mGuide != null) { int stepIndex = getStepIndex(); int commentCount = 0; if (stepIndex < 0) { commentCount = mGuide.getCommentCount(); } else { commentCount = mGuide.getStep(stepIndex).getCommentCount(); } if (countView != null) { countView.setText(commentCount + ""); } } boolean favorited = mGuide != null && mGuide.isFavorited(); favoriteGuide.setIcon(favorited ? R.drawable.ic_action_favorite_filled : R.drawable.ic_action_favorite_empty); favoriteGuide.setEnabled(!mFavoriting && mGuide != null); favoriteGuide.setTitle(favorited ? R.string.unfavorite_guide : R.string.favorite_guide); reloadGuide.setEnabled(mGuide != null); editGuide.setEnabled(mGuide != null); if (mIsOfflineGuide) { reloadGuide.setVisible(false); editGuide.setVisible(false); favoriteGuide.setVisible(false); } return super.onPrepareOptionsMenu(menu); }
Source:
public VoltNIOWriteStream writeStream() { assert(m_writeStream != null && m_writeStream instanceof VoltNIOWriteStream); return (VoltNIOWriteStream) m_writeStream; }

Target:
public VoltNIOWriteStream writeStream() { assert(m_writeStream != null); return m_writeStream; }
Source:
public void call(final Subscriber<? super String> subscriber) { final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if(!subscriber.isUnsubscribed()) subscriber.onNext(key); } }; subscriber.add(Subscriptions.create(new Action0() { @Override public void call() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); } })); sharedPreferences.registerOnSharedPreferenceChangeListener(listener); }

Target:
public void call(final Subscriber<? super String> subscriber) { final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { subscriber.onNext(key); } }; subscriber.add(Subscriptions.create(new Action0() { @Override public void call() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); } })); sharedPreferences.registerOnSharedPreferenceChangeListener(listener); }
Source:
public String getDlmsAttributeValues(final int classId, final String obisCode) throws SimulatorTriggerClientException { final String key = this.buildKeyPathSegment(classId, obisCode); final Response response = this.getWebClientInstance().path(DYNAMIC_ATTRIBUTES_PATH).path(key).get(); try { this.checkResponseStatus(response); } catch (final ResponseException e) { throw new SimulatorTriggerClientException("getDlmsAttributeValues response exception", e); } return response.readEntity(String.class); }

Target:
public final Properties getDlmsAttributeValues(final int classId, final String obisCode) throws SimulatorTriggerClientException { final String key = this.buildKeyPathSegment(classId, obisCode); final Response response = this.getWebClientInstance().path(DYNAMIC_ATTRIBUTES_PATH).path(key).get(); try { this.checkResponseStatus(response); } catch (final ResponseException e) { throw new SimulatorTriggerClientException("getDlmsAttributeValues response exception", e); } return response.readEntity(Properties.class); }
Source:
public Optional<HostLocation> get() { Optional<HostLocation> location = overrideLocation.get(); if (location.isPresent()) { return location; } return locationSupplier.get(); }

Target:
public Optional<HostLocation> get() { Optional<HostLocation> location = overrideLocationSupplier.get(); if (location.isPresent()) { return location; } return locationSupplier.get(); }
Source:
public void loadLoginPage() { if (loginOptions.jwt == null || loginOptions.loginUrl == null) { loginOptions.loginUrl = getLoginUrl(); } if (loginOptions.jwt != null) { new SwapJWTForAccessTokenTask().execute(loginOptions); } this.doLoadPage(false); }

Target:
public void loadLoginPage() { if (TextUtils.isEmpty(loginOptions.jwt)) { loginOptions.loginUrl = getLoginUrl(); doLoadPage(false); } else { new SwapJWTForAccessTokenTask().execute(loginOptions); } }
Source:
public static boolean addAppender(String name, Properties properties) { if (getAppendersNames().contains(name)) { logger.warn("A logger appender with the name '{}' exists. Cannot add a new logger appender with the same name", name); } else { try { Method method = PropertyConfigurator.class.getDeclaredMethod("parseAppender", Properties.class, String.class); method.setAccessible(true); makeMDCProperties(); Appender appender = (Appender)method.invoke(new PropertyConfigurator(), properties, name); if (appender == null) { logger.warn("Cannot add a new logger appender. Name: {}, Properties: {}", name, properties); } else { LogManager.getRootLogger().addAppender(appender); return true; } } catch (Exception ex) { logger.warn("Cannot add a new logger appender. Name: {}, Properties: {}", name, properties, ex); } } return false; }

Target:
public static boolean addAppender(String name, Properties properties) { if (getAppendersNames().contains(name)) { logger.warn("A logger appender with the name '{}' exists. Cannot add a new logger appender with the same name", name); } else { try { Method method = PropertyConfigurator.class.getDeclaredMethod("parseAppender", Properties.class, String.class); method.setAccessible(true); Appender appender = (Appender)method.invoke(new PropertyConfigurator(), properties, name); if (appender == null) { logger.warn("Cannot add a new logger appender. Name: {}, Properties: {}", name, properties); } else { LogManager.getRootLogger().addAppender(appender); return true; } } catch (Exception ex) { logger.warn("Cannot add a new logger appender. Name: {}, Properties: {}", name, properties, ex); } } return false; }
Source:
public <T extends Number> Converter<Number, T> getConverter(Class<T> targetType) { NumberToNumber converter = cache.get(targetType); if (converter == null) { converter = new NumberToNumber<>(targetType); cache.put(targetType, converter); } return converter; }

Target:
public <T extends Number> Converter<Number, T> getConverter(Class<T> targetType) { return (NumberToNumber) CACHE.computeIfAbsent(targetType.getName(), t-> new NumberToNumber(targetType)); }
Source:
public HttpConfig(URIish uri) { StoredConfig userConfig = GlobalConfigCache.getInstance() .getUserConfig(); try { userConfig.load(); } catch (IOException | ConfigInvalidException e) { LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); init(new Config(), uri); return; } init(userConfig, uri); }

Target:
public HttpConfig(URIish uri) { StoredConfig userConfig = null; try { userConfig = GlobalConfigCache.getInstance().getUserConfig(); } catch (IOException | ConfigInvalidException e) { LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); init(new Config(), uri); return; } init(userConfig, uri); }
Source:
byte[] getData() { return this.data.get(); }

Target:
private byte[] getData() { return this.data.get(); }
Source:
public void addCatalogVersion(final String catalogResource) throws Exception { final StandaloneCatalog inputCatalogVersion = XMLLoader.getObjectFromString(Resources.getResource(catalogResource).toExternalForm(), StandaloneCatalog.class); final StandaloneCatalogWithPriceOverride inputCatalogVersionWithOverride = new StandaloneCatalogWithPriceOverride(inputCatalogVersion, priceOverride, internalTenantContext.getTenantRecordId(), internalCallContextFactory); if (versionedCatalog == null) { versionedCatalog = new DefaultVersionedCatalog(new ArrayList<>()); } versionedCatalog.add(inputCatalogVersionWithOverride); }

Target:
public void addCatalogVersion(final String catalogResource) throws Exception { final StandaloneCatalog inputCatalogVersion = XMLLoader.getObjectFromString(Resources.getResource(catalogResource).toExternalForm(), StandaloneCatalog.class); final StandaloneCatalogWithPriceOverride inputCatalogVersionWithOverride = new StandaloneCatalogWithPriceOverride(inputCatalogVersion, priceOverride, internalTenantContext.getTenantRecordId(), internalCallContextFactory); if (versionedCatalog == null) { versionedCatalog = new DefaultVersionedCatalog(); } versionedCatalog.add(inputCatalogVersionWithOverride); }
Source:
public Queue<Object> tempInboundMessages() { if (tempInboundMessages == null) { tempInboundMessages = new ConcurrentLinkedQueue<Object>(); } return tempInboundMessages; }

Target:
private Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> tempInboundMessages() { if (tempInboundMessages == null) { tempInboundMessages = new ArrayDeque<AbstractMap.SimpleEntry<Object, ChannelPromise>>(); } return tempInboundMessages; }
Source:
public BuildCommand updateTo(String baseDir, RevisionContext revisionContext) { String workingDir = material.workingdir(new File(baseDir)).getPath(); String revision = revisionContext.getLatestRevision().getRevision(); String clientName = material.clientName(new File(workingDir)); return compose( secret(material.getPassword()), export("P4PORT", material.getServerAndPort(), false), export("P4USER", material.getUserName(), false), export("P4PASSWD", material.getPassword(), true), export("P4CLIENT", clientName, false), constructClient(workingDir, clientName), cleanWorkingDir(workingDir), echo(format("[%s] Start updating %s at revision %s from %s", GoConstants.PRODUCT_NAME, material.updatingTarget(), revision, material.getServerAndPort())), sync(workingDir, revision), echo(format("[%s] Done.\n", GoConstants.PRODUCT_NAME)) ); }

Target:
public BuildCommand updateTo(String baseDir, RevisionContext revisionContext) { String workingDir = material.workingdir(new File(baseDir)).getPath(); String revision = revisionContext.getLatestRevision().getRevision(); this.clientName = material.clientName(new File(workingDir)); return compose( secret(material.getPassword()), loginIfUsingTickets(), constructClient(workingDir, clientName), cleanWorkingDir(workingDir), echo(format("[%s] Start updating %s at revision %s from %s", GoConstants.PRODUCT_NAME, material.updatingTarget(), revision, material.getServerAndPort())), sync(workingDir, revision), echo(format("[%s] Done.\n", GoConstants.PRODUCT_NAME)) ); }
Source:
private boolean handleDefinedMappings() { boolean errorOccurred = false; Set<String> handledTargets = new HashSet<String>(); if ( method.getMappingOptions().hasNestedTargetReferences() ) { if ( handleDefinedNestedTargetMapping( handledTargets ) ) { errorOccurred = true; } } for ( Map.Entry<String, List<Mapping>> entry : methodMappings.entrySet() ) { for ( Mapping mapping : entry.getValue() ) { TargetReference targetReference = mapping.getTargetReference(); if ( targetReference.isValid() ) { if ( !handledTargets.contains( first( targetReference.getPropertyEntries() ).getFullName() ) ) { if ( handleDefinedMapping( mapping, handledTargets ) ) { errorOccurred = true; } } } else { errorOccurred = true; } } } for ( String handledTarget : handledTargets ) { unprocessedTargetProperties.remove( handledTarget ); unprocessedDefinedTargets.remove( handledTarget ); } return errorOccurred; }

Target:
private boolean handleDefinedMappings() { boolean errorOccurred = false; Set<String> handledTargets = new HashSet<String>(); if ( method.getMappingOptions().hasNestedTargetReferences() ) { errorOccurred = handleDefinedNestedTargetMapping( handledTargets ); } for ( Map.Entry<String, List<Mapping>> entry : methodMappings.entrySet() ) { for ( Mapping mapping : entry.getValue() ) { TargetReference targetReference = mapping.getTargetReference(); if ( targetReference.isValid() ) { if ( !handledTargets.contains( first( targetReference.getPropertyEntries() ).getFullName() ) ) { if ( handleDefinedMapping( mapping, handledTargets ) ) { errorOccurred = true; } } } else { errorOccurred = true; } } } for ( String handledTarget : handledTargets ) { unprocessedTargetProperties.remove( handledTarget ); unprocessedDefinedTargets.remove( handledTarget ); } return errorOccurred; }
Source:
public final <M, T> Binding bindList( IObservableList<T> targetObservableList, IObservableList<M> modelObservableList, UpdateListStrategy<? super T, ? extends M> targetToModel, UpdateListStrategy<? super M, ? extends T> modelToTarget) { UpdateListStrategy<? super T, ? extends M> targetToModelStrategy = targetToModel != null ? targetToModel : createTargetToModelUpdateListStrategy(targetObservableList, modelObservableList); UpdateListStrategy<? super M, ? extends T> modelToTargetStrategy = modelToTarget != null ? modelToTarget : createModelToTargetUpdateListStrategy(modelObservableList, targetObservableList); targetToModelStrategy.fillDefaults(targetObservableList, modelObservableList); modelToTargetStrategy.fillDefaults(modelObservableList, targetObservableList); ListBinding<M, T> result = new ListBinding<>(targetObservableList, modelObservableList, targetToModelStrategy, modelToTargetStrategy); result.init(this); return result; }

Target:
public final <T, M> Binding bindList( IObservableList<T> targetObservableList, IObservableList<M> modelObservableList, UpdateListStrategy<? super T, ? extends M> targetToModel, UpdateListStrategy<? super M, ? extends T> modelToTarget) { UpdateListStrategy<? super T, ? extends M> targetToModelStrategy = targetToModel != null ? targetToModel : createTargetToModelUpdateListStrategy(targetObservableList, modelObservableList); UpdateListStrategy<? super M, ? extends T> modelToTargetStrategy = modelToTarget != null ? modelToTarget : createModelToTargetUpdateListStrategy(modelObservableList, targetObservableList); targetToModelStrategy.fillDefaults(targetObservableList, modelObservableList); modelToTargetStrategy.fillDefaults(modelObservableList, targetObservableList); ListBinding<M, T> result = new ListBinding<>(targetObservableList, modelObservableList, targetToModelStrategy, modelToTargetStrategy); result.init(this); return result; }
Source:
protected List<String> getStablePartitionList(ResourceControllerDataProvider clusterData, IdealState currentIdealState) { List<String> partitions = clusterData.getStablePartitionList(currentIdealState.getResourceName()); Set<String> currentPartitionSet = currentIdealState.getPartitionSet(); if (partitions.size() != currentPartitionSet.size() || !currentPartitionSet .containsAll(partitions)) { LOG.warn("The current partition set has been modified and it is different from the cached " + "stable list {}. Use the current partition set.", currentPartitionSet.toString(), partitions.toString()); partitions = new ArrayList<>(currentPartitionSet); } return partitions; }

Target:
protected List<String> getStablePartitionList(ResourceControllerDataProvider clusterData, IdealState currentIdealState) { List<String> partitions = clusterData.getStablePartitionList(currentIdealState.getResourceName()); if (partitions == null) { Set<String> currentPartitionSet = currentIdealState.getPartitionSet(); LOG.warn("The current partition set has not been cached in the stable partition list. " + "Use the IdealState partition set directly.", currentPartitionSet.toString()); partitions = new ArrayList<>(currentPartitionSet); } return partitions; }
Source:
RtRelease(final Request req, final Coordinates coords, final int nmbr) { this.release = nmbr; this.request = initRequest(req, coords) .back(); }

Target:
RtRelease(final Request req, final Coordinates coords, final int nmbr) { this.release = nmbr; this.request = req.uri() .path("/repos") .path(coords.user()) .path(coords.repo()) .path("/releases") .path(String.valueOf(this.release)) .back(); this.requestURI = this.request.uri(); }
Source:
public ClusterLevel makeClusterLevel(String version) { ClusterLevel level = new ClusterLevel(); level.setId(version); if (!isFiltered()) { CpuTypes cpuTypes = new CpuTypes(); for (ServerCpu serverCpu : getServerCpuList(version)) { CpuType cpuType = new CpuType(); cpuType.setName(serverCpu.getCpuName()); cpuType.setLevel(serverCpu.getLevel()); cpuType.setArchitecture(CPUMapper.map(serverCpu.getArchitecture(), null)); cpuTypes.getCpuTypes().add(cpuType); } level.setCpuTypes(cpuTypes); } Permits permits = new Permits(); for (ActionGroup actionGroup : getActionGroups()) { Permit permit = PermitMapper.map(actionGroup, null); permits.getPermits().add(permit); } level.setPermits(permits); ClusterFeatures features = new ClusterFeatures(); for (AdditionalFeature clusterFeature : getAdditionalFeatureList(version)) { org.ovirt.engine.api.model.ClusterFeature feature = ClusterFeaturesMapper.map(clusterFeature, null); features.getClusterFeatures().add(feature); } level.setClusterFeatures(features); return LinkHelper.addLinks(level); }

Target:
public ClusterLevel makeClusterLevel(String version) { ClusterLevel level = new ClusterLevel(); level.setId(version); if (!isFiltered()) { CpuTypes cpuTypes = new CpuTypes(); for (ServerCpu serverCpu : getServerCpuList(version)) { CpuType cpuType = new CpuType(); cpuType.setName(serverCpu.getCpuName()); cpuType.setLevel(serverCpu.getLevel()); cpuType.setArchitecture(CPUMapper.map(serverCpu.getArchitecture(), null)); cpuTypes.getCpuTypes().add(cpuType); } level.setCpuTypes(cpuTypes); } Permits permits = new Permits(); for (ActionGroup actionGroup : getActionGroups()) { Permit permit = PermitMapper.map(actionGroup, null); permits.getPermits().add(permit); } level.setPermits(permits); ClusterFeatures features = new ClusterFeatures(); getAdditionalFeatureList(version).forEach(clusterFeature -> { org.ovirt.engine.api.model.ClusterFeature feature = ClusterFeaturesMapper.map(clusterFeature, null); features.getClusterFeatures().add(feature); }); level.setClusterFeatures(features); return LinkHelper.addLinks(level); }
Source:
private void updateHostInFenceFlow(Guid hostId, boolean isInFenceFlow) { VdsDynamic vdsDynamic = vdsDynamicDao.get(hostId); vdsDynamic.setInFenceFlow(isInFenceFlow); vdsDynamicDao.update(vdsDynamic); }

Target:
private void updateHostInFenceFlow(Guid hostId, boolean isInFenceFlow) { TransactionSupport.executeInNewTransaction(() -> { VdsDynamic vdsDynamic = vdsDynamicDao.get(hostId); vdsDynamic.setInFenceFlow(isInFenceFlow); vdsDynamicDao.update(vdsDynamic); return null; }); }
Source:
private static ModelNode executeOverHttp(URI mgmtURI, String operation) throws IOException { CloseableHttpClient httpClient = getHttpClient(mgmtURI); HttpEntity operationEntity = new StringEntity(operation, ContentType.APPLICATION_JSON); HttpPost httpPost = new HttpPost(mgmtURI); httpPost.setEntity(operationEntity); HttpResponse response; ModelNode responseNode; try{ response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } responseNode = ModelNode.fromJSONStream(response.getEntity().getContent()); EntityUtils.consume(entity); } catch (IOException ex) { ex.printStackTrace(); return null; } finally { httpClient.close(); } return responseNode; }

Target:
private static ModelNode executeOverHttp(URI mgmtURI, String operation) throws IOException { CloseableHttpClient httpClient = createHttpClient(mgmtURI); HttpEntity operationEntity = new StringEntity(operation, ContentType.APPLICATION_JSON); HttpPost httpPost = new HttpPost(mgmtURI); httpPost.setEntity(operationEntity); HttpResponse response; ModelNode responseNode; try { response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } responseNode = ModelNode.fromJSONStream(response.getEntity().getContent()); EntityUtils.consume(entity); } finally { httpClient.close(); } return responseNode; }
Source:
public void setDynamicMethodInvocation(String dmiValue) { if (!BooleanUtils.toBoolean(dmiValue)) { if (LOG.isDebugEnabled()) { LOG.debug("DMI is disabled, adding DMI related excluded patterns"); } setAdditionalExcludePatterns("^(action|method):.*"); } else if (LOG.isWarnEnabled()) { LOG.warn("DMI is enabled, *NOT* adding DMI related excluded patterns"); } }

Target:
protected void setDynamicMethodInvocation(String dmiValue) { if (BooleanUtils.toBoolean(dmiValue) == false) { LOG.debug("DMI is disabled, adding DMI related excluded patterns"); setAdditionalExcludePatterns("^(action|method):.*"); } else { LOG.warn("DMI is enabled, *NOT* adding DMI related excluded patterns"); } }
Source:
public HttpClient get() { final DruidHttpClientConfig config = getConfigProvider().get().get(); final HttpClientConfig.Builder builder = HttpClientConfig .builder() .withNumConnections(config.getNumConnections()) .withReadTimeout(config.getReadTimeout()) .withWorkerCount(config.getNumMaxThreads()) .withCompressionCodec( HttpClientConfig.CompressionCodec.valueOf(StringUtils.toUpperCase(config.getCompressionCodec())) ); if (getSslContextBinding() != null) { builder.withSslContext(getSslContextBinding().getProvider().get()); } return HttpClientInit.createClient( builder.build(), LifecycleUtils.asMmxLifecycle(getLifecycleProvider().get()) ); }

Target:
public HttpClient get() { final DruidHttpClientConfig config = getConfigProvider().get().get(); final HttpClientConfig.Builder builder = HttpClientConfig .builder() .withNumConnections(config.getNumConnections()) .withReadTimeout(config.getReadTimeout()) .withWorkerCount(config.getNumMaxThreads()) .withCompressionCodec( HttpClientConfig.CompressionCodec.valueOf(StringUtils.toUpperCase(config.getCompressionCodec())) ); if (getSslContextBinding() != null) { builder.withSslContext(getSslContextBinding().getProvider().get()); } HttpClient client = HttpClientInit.createClient( builder.build(), LifecycleUtils.asMmxLifecycle(getLifecycleProvider().get()) ); if (isEscalated) { return escalatingAuthenticator.createEscalatedClient(client); } else { return client; } }
Source:
public void get(String url) throws WebDriverException { if (!url.equals(GitHubURL.LOGIN_PAGE)) { UI.events.triggerEvent(new NavigateToPageEvent(url)); } if (isTestChromeDriver) { logger.info("Test loading page: " + url); testGet(); } else { if (driver.getCurrentUrl().equalsIgnoreCase(url)) { logger.info("Already on page: " + url + " will not load it again. "); } else { logger.info("Previous page was: " + driver.getCurrentUrl()); logger.info("Loading page: " + url); driver.get(url); } } }

Target:
public void get(String url) throws WebDriverException { if (isTestChromeDriver) { if (!url.equalsIgnoreCase(GitHubURL.LOGIN_PAGE)) { UI.events.triggerEvent(new NavigateToPageEvent(url)); } logger.info("Test loading page: " + url); testGet(); } else { if (driver.getCurrentUrl().equalsIgnoreCase(url)) { logger.info("Already on page: " + url + " will not load it again. "); } else { logger.info("Previous page was: " + driver.getCurrentUrl()); logger.info("Loading page: " + url); driver.get(url); } } }
Source:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("RassXmlAgencyEntry [number:").append(number); sb.append(", fullName:").append(fullName); sb.append(", typeCode:").append(typeCode); sb.append(", reportsToAgencyNumber:").append(reportsToAgencyNumber); sb.append(", commonName:").append(commonName); sb.append(", agencyOrigin:").append(agencyOrigin); sb.append(KFSConstants.SQUARE_BRACKET_RIGHT); return sb.toString(); }

Target:
public String toString() { return ToStringBuilder.reflectionToString(this); }
Source:
Future<List<?>> singleScan() { assert deploymentOperationsFactory != null : "deploymentOperationsFactory is null"; return scheduledExecutor.submit(new ManualScanCallable()); }

Target:
void singleScan() { assert deploymentOperationsFactory != null : "deploymentOperationsFactory is null"; ManualScanCallable manualScan = new ManualScanCallable(); scheduledExecutor.submit(manualScan); }
Source:
private List<HtmlContext> performAttack(HttpMessage sourceMsg, String param, String attack, HttpMessage sinkMsg, HtmlContext targetContext, int ignoreFlags, boolean findDecoded) { if (isStop()) { return null; } HttpMessage sourceMsg2 = sourceMsg.cloneRequest(); setParameter(sourceMsg2, param, attack); try { sendAndReceive(sourceMsg2); } catch (Exception e) { log.error(e.getMessage(), e); } if (isStop()) { return null; } HttpMessage sinkMsg2 = sinkMsg.cloneRequest(); try { sendAndReceive(sinkMsg2); } catch (Exception e) { log.error(e.getMessage(), e); } if (isStop()) { return null; } HtmlContextAnalyser hca = new HtmlContextAnalyser(sourceMsg2); if (Plugin.AlertThreshold.HIGH.equals(this.getAlertThreshold())) { return hca.getHtmlContexts(findDecoded ? getURLDecode(attack) : attack, targetContext, ignoreFlags); } return hca.getHtmlContexts(findDecoded ? getURLDecode(attack) : attack); }

Target:
private List<HtmlContext> performAttack(HttpMessage sourceMsg, String param, String attack, HttpMessage sinkMsg, HtmlContext targetContext, int ignoreFlags, boolean findDecoded) { if (isStop()) { return null; } HttpMessage sourceMsg2 = sourceMsg.cloneRequest(); setParameter(sourceMsg2, param, attack); try { sendAndReceive(sourceMsg2); } catch (Exception e) { log.error(e.getMessage(), e); } if (isStop()) { return null; } HttpMessage sinkMsg2 = sinkMsg.cloneRequest(); try { sendAndReceive(sinkMsg2); } catch (Exception e) { log.error(e.getMessage(), e); } if (isStop()) { return null; } HtmlContextAnalyser hca = new HtmlContextAnalyser(sinkMsg2); if (Plugin.AlertThreshold.HIGH.equals(this.getAlertThreshold())) { return hca.getHtmlContexts(findDecoded ? getURLDecode(attack) : attack, targetContext, ignoreFlags); } return hca.getHtmlContexts(findDecoded ? getURLDecode(attack) : attack); }
Source:
public void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) .reason("NOT FOUND") .headers(Collections.<String, Collection<String>>emptyMap()) .body((byte[]) null) .build(); assertThat((byte[]) new JacksonDecoder().decode(response, byte[].class)).isEmpty(); }

Target:
public void notFoundDecodesToEmpty() throws Exception { Response response = Response.builder() .status(404) .reason("NOT FOUND") .headers(Collections.<String, Collection<String>>emptyMap()) .build(); assertThat((byte[]) new JacksonDecoder().decode(response, byte[].class)).isEmpty(); }
Source:
public String getHeader() throws IOException { TokenCache tokenCache = getCachedHeader(); CacheState state = (tokenCache == null) ? CacheState.Expired : tokenCache.getCacheState(); if (state == CacheState.Expired) { synchronized (isRefreshing) { if (!isRefreshing.get()) { isRefreshing.set(true); doRefresh(); } else { while (isRefreshing.get()) { try { isRefreshing.wait(250); } catch (InterruptedException e) { throw new IOException(e); } } } } tokenCache = getCachedHeader(); } else if (state == CacheState.Stale) { asyncRefresh(); } return tokenCache.header; }

Target:
private String getHeader() throws IOException { HeaderCacheElement headerCache = getCachedHeader(); CacheState state = (headerCache == null) ? CacheState.Expired : headerCache.getCacheState(); if (state == CacheState.Expired) { syncRefresh(); headerCache = getCachedHeader(); } else if (state == CacheState.Stale) { asyncRefresh(); } return headerCache.header; }
Source:
private void disconnect() { influxDB = null; }

Target:
private void disconnect() { influxDB = null; connected = false; }
Source:
public void execute() throws MojoFailureException, MojoExecutionException { try { verifyMuleIsStarted(); deployApplications(); waitForDeployments(); } catch (MuleControllerException e) { throw new MojoFailureException("Error deploying application: [" + application + "]: " + e.getMessage()); } catch (RuntimeException e) { throw new MojoExecutionException("Unexpected error deploying application: [" + application + "]", e); } }

Target:
public void execute() throws DeploymentException { try { verifyMuleIsStarted(); deployApplications(); waitForDeployments(); } catch (MuleControllerException e) { throw new DeploymentException("Error deploying application: [" + application + "]: " + e.getMessage()); } catch (RuntimeException e) { throw new DeploymentException("Unexpected error deploying application: [" + application + "]", e); } }
Source:
private void compareWith(OpenEvent event) { IStructuredSelection selection = (IStructuredSelection) event .getSelection(); if (selection.isEmpty() || !(selection.getFirstElement() instanceof StagingEntry)) return; StagingEntry stagingEntry = (StagingEntry) selection.getFirstElement(); askToOpenProject(stagingEntry); if (stagingEntry.isSubmodule()) return; switch (stagingEntry.getState()) { case ADDED: case CHANGED: case REMOVED: runCommand(ActionCommands.COMPARE_INDEX_WITH_HEAD_ACTION, selection); break; case CONFLICTING: runCommand(ActionCommands.MERGE_TOOL_ACTION, selection); break; case MISSING: case MISSING_AND_CHANGED: case MODIFIED: case MODIFIED_AND_CHANGED: case MODIFIED_AND_ADDED: case UNTRACKED: default: if (Activator.getDefault().getPreferenceStore().getBoolean( UIPreferences.STAGING_VIEW_COMPARE_MODE)) { runCommand(ActionCommands.COMPARE_WITH_INDEX_ACTION, selection); } else { openSelectionInEditor(selection); } } }

Target:
private void compareWith(OpenEvent event) { IStructuredSelection selection = (IStructuredSelection) event .getSelection(); if (selection.isEmpty() || !(selection.getFirstElement() instanceof StagingEntry)) return; StagingEntry stagingEntry = (StagingEntry) selection.getFirstElement(); if (stagingEntry.isSubmodule()) return; askToOpenProject(stagingEntry); switch (stagingEntry.getState()) { case ADDED: case CHANGED: case REMOVED: runCommand(ActionCommands.COMPARE_INDEX_WITH_HEAD_ACTION, selection); break; case CONFLICTING: runCommand(ActionCommands.MERGE_TOOL_ACTION, selection); break; case MISSING: case MISSING_AND_CHANGED: case MODIFIED: case MODIFIED_AND_CHANGED: case MODIFIED_AND_ADDED: case UNTRACKED: default: if (Activator.getDefault().getPreferenceStore().getBoolean( UIPreferences.STAGING_VIEW_COMPARE_MODE)) { runCommand(ActionCommands.COMPARE_WITH_INDEX_ACTION, selection); } else { openSelectionInEditor(selection); } } }
Source:
private static String stripTypeParameters(String type) { int typeParamStart = type.indexOf("<"); if (typeParamStart != -1) { return type.substring(0, typeParamStart); } else { return type; } }

Target:
private static String stripTypeParameters(String type) { int typeParamStart = type.indexOf('<'); if (typeParamStart != -1) { return type.substring(0, typeParamStart); } else { return type; } }