auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String redirectToEdit(String urlSuffix) { try { String referrer = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap() .get("referer"); String callerViewId = referrer.substring(referrer.lastIndexOf("/") + 1); if (!callerViewId.isEmpty() && callerViewId.contains("projects.jsf")) { return "/pages/rulesetEdit" + urlSuffix; } else { return "/pages/RegelsaetzeBearbeiten" + urlSuffix; } } catch (NullPointerException e) { return "/pages/ProjekteBearbeiten" + urlSuffix; } }

Target:
private String redirectToEdit(String urlSuffix) { try { String referrer = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap() .get("referer"); String callerViewId = referrer.substring(referrer.lastIndexOf("/") + 1); if (!callerViewId.isEmpty() && callerViewId.contains("projects.jsf")) { return "/pages/rulesetEdit" + urlSuffix; } else { return "/pages/RegelsaetzeBearbeiten" + urlSuffix; } } catch (NullPointerException e) { return "/pages/RegelsaetzeBearbeiten" + urlSuffix; } }
Source:
private boolean sourceIsAvailable(String sourceId){ try { final SourceInfoRequest sourceInfoRequest = new SourceInfoRequestSources(false, Collections.singleton(sourceId)); final SourceInfoResponse sourceInfoResponse = catalogFramework.getSourceInfo(sourceInfoRequest); final Set<SourceDescriptor> sourceDescriptors = sourceInfoResponse.getSourceInfo(); final SourceDescriptor sourceDescriptor = Iterables.getOnlyElement(sourceDescriptors); return sourceDescriptor.isAvailable(); } catch (Exception e){ LOGGER.info("Couldn't get availability on source {}: {}", sourceId, e); } return false; }

Target:
private int sourceIsAvailable(String sourceId) { try { final SourceInfoRequest sourceInfoRequest = new SourceInfoRequestSources(false, Collections.singleton(sourceId)); final SourceInfoResponse sourceInfoResponse = catalogFramework.getSourceInfo(sourceInfoRequest); final Set<SourceDescriptor> sourceDescriptors = sourceInfoResponse.getSourceInfo(); if (sourceDescriptors.isEmpty()) { return STATUS_PENDING; } final SourceDescriptor sourceDescriptor = Iterables.getOnlyElement(sourceDescriptors); if (sourceDescriptor.getLastAvailabilityDate() == null) { return STATUS_PENDING; } if (sourceDescriptor.isAvailable()) { return AVAILABLE; } } catch (Exception e) { LOGGER.info("Couldn't get availability on source {}", sourceId, e); } return UNAVAILABLE; }
Source:
private Response<AnalyzeSentimentResultCollection> toAnalyzeSentimentResultCollectionResponse( Response<SentimentResponse> response) { final SentimentResponse sentimentResponse = response.getValue(); final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment)); } for (DocumentError documentError : sentimentResponse.getErrors()) { analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new AnalyzeSentimentResultCollection(analyzeSentimentResults, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics()))); }

Target:
private Response<AnalyzeSentimentResultCollection> toAnalyzeSentimentResultCollectionResponse( Response<SentimentResponse> response) { final SentimentResponse sentimentResponse = response.getValue(); final List<AnalyzeSentimentResult> analyzeSentimentResults = new ArrayList<>(); final List<DocumentSentiment> documentSentiments = sentimentResponse.getDocuments(); for (DocumentSentiment documentSentiment : documentSentiments) { analyzeSentimentResults.add(convertToAnalyzeSentimentResult(documentSentiment, documentSentiments)); } for (DocumentError documentError : sentimentResponse.getErrors()) { analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, toTextAnalyticsError(documentError.getError()), null)); } return new SimpleResponse<>(response, new AnalyzeSentimentResultCollection(analyzeSentimentResults, sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null : toBatchStatistics(sentimentResponse.getStatistics()))); }
Source:
public URL getQueueUrl() { try { return new URL(client.url()); } catch (MalformedURLException ex) { throw new RuntimeException("Queue URL is malformed"); } }

Target:
public URL getQueueUrl() { try { return new URL(client.url()); } catch (MalformedURLException ex) { LOGGER.asError().log("Queue URL is malformed"); throw new RuntimeException("Queue URL is malformed"); } }
Source:
public static boolean isKeyFrame(byte[] buf, int off, int len){ if (!isValid(buf, off, len)) { return false; } if((buf[off] & P_BIT) != 0 || (buf[off] & B_BIT) == 0) { return false; } int loff = off + 1; if ((buf[off] & I_BIT) != 0) { loff += 1; if ((buf[off + 1] & (1 << 7)) != 0) { loff += 1; } } return ((buf[loff] & 0xE) >> 1) == 0 || (buf[loff] & 0x1) == 0; }

Target:
public static boolean isKeyFrame(byte[] buf, int off, int len) { if (!isValid(buf, off, len)) { return false; } if((buf[off] & P_BIT) != 0 || (buf[off] & B_BIT) == 0 || (buf[off] & L_BIT) == 0 ) { return false; } int loff = off + 1; if ((buf[off] & I_BIT) != 0) { loff += 1; if ((buf[off + 1] & (1 << 7)) != 0) { loff += 1; } } return ((buf[loff] & SID_MASK) >> 1) == 0 || (buf[loff] & D_MASK) == 0; }
Source:
public void handleFileUpload(FileUploadEvent event) { UploadedFile file = event.getFile(); try { massImportService.importFromCSV(selectedCatalog, file, projectId, templateId); FacesContext context = FacesContext.getCurrentInstance(); String path = context.getExternalContext().getRequestContextPath() + processListPath; context.getExternalContext().redirect(path); } catch (IOException e) { Helper.setErrorMessage(Helper.getTranslation("errorReading", file.getFileName())); } catch (ImportException e) { Helper.setErrorMessage(e.getLocalizedMessage(), logger, e); } }

Target:
public void handleFileUpload(FileUploadEvent event) { UploadedFile file = event.getFile(); try { massImportService.importFromCSV(selectedCatalog, file, projectId, templateId); FacesContext context = FacesContext.getCurrentInstance(); String path = context.getExternalContext().getRequestContextPath() + PROCESS_LIST_PATH; context.getExternalContext().redirect(path); } catch (IOException e) { Helper.setErrorMessage(Helper.getTranslation("errorReading", file.getFileName())); } catch (ImportException e) { Helper.setErrorMessage(e.getLocalizedMessage(), logger, e); } }
Source:
public List<Boolean> commitCursors(final String streamId, final String subscriptionId, final List<NakadiCursor> cursors, final Span parentSpan) throws ServiceTemporarilyUnavailableException, InvalidCursorException, InvalidStreamIdException, NoSuchEventTypeException, InternalNakadiException, NoSuchSubscriptionException, UnableProcessException, AccessDeniedException { TracingService.activateSpan(parentSpan, false) .setTag("subscription", subscriptionId) .setTag("stream.id", streamId); try { final Subscription subscription = subscriptionCache.getSubscription(subscriptionId); authorizationValidator.authorizeSubscriptionView(subscription); authorizationValidator.authorizeSubscriptionCommit(subscription); validateSubscriptionCommitCursors(subscription, cursors); final ZkSubscriptionClient zkClient = zkSubscriptionFactory.createClient( subscription, LogPathBuilder.build(subscriptionId, streamId, "offsets")); validateStreamId(cursors, streamId, zkClient, subscriptionId); return zkClient.commitOffsets( cursors.stream().map(cursorConverter::convertToNoToken).collect(Collectors.toList()), new SubscriptionCursorComparator(new NakadiCursorComparator(eventTypeCache))); } catch (Exception e) { TracingService.logErrorInSpan(parentSpan, e.getMessage()); throw e; } }

Target:
public List<Boolean> commitCursors(final String streamId, final String subscriptionId, final List<NakadiCursor> cursors, final Span parentSpan) throws ServiceTemporarilyUnavailableException, InvalidCursorException, InvalidStreamIdException, NoSuchEventTypeException, InternalNakadiException, NoSuchSubscriptionException, UnableProcessException, AccessDeniedException { parentSpan.setTag("subscription", subscriptionId).setTag("stream.id", streamId); try { final Subscription subscription = subscriptionCache.getSubscription(subscriptionId); authorizationValidator.authorizeSubscriptionView(subscription); authorizationValidator.authorizeSubscriptionCommit(subscription); validateSubscriptionCommitCursors(subscription, cursors, parentSpan); final ZkSubscriptionClient zkClient = zkSubscriptionFactory.createClient( subscription, LogPathBuilder.build(subscriptionId, streamId, "offsets")); validateStreamId(cursors, streamId, zkClient, subscriptionId, parentSpan); return zkClient.commitOffsets( cursors.stream().map(cursorConverter::convertToNoToken).collect(Collectors.toList()), new SubscriptionCursorComparator(new NakadiCursorComparator(eventTypeCache))); } catch (Exception e) { TracingService.logErrorInSpan(parentSpan, e.getMessage()); throw e; } }
Source:
public void testHiveCommands() throws Exception { SqlParserHelper helper = new SqlParserHelper(SqlDialect.HIVE); parser = helper.getSqlParser(); List<TestItem> testItems = Arrays.asList( TestItem.invalidSql("SHOW PARTITIONS ", SqlExecutionException.class, "Encountered \"<EOF>\""), TestItem.validSql("SHOW PARTITIONS t1", SqlDialect.HIVE, SqlCommand.SHOW_PARTITIONS, "SHOW PARTITIONS t1") ); for (TestItem item : testItems) { tableEnv.getConfig().setSqlDialect(item.sqlDialect); runTestItem(item); } }

Target:
public void testHiveCommands() throws Exception { List<TestItem> testItems = Collections.singletonList( TestItem.validSql(SqlDialect.HIVE, "SHOW PARTITIONS t1", SqlCommand.SHOW_PARTITIONS, "SHOW PARTITIONS t1") ); for (TestItem item : testItems) { tableEnv.getConfig().setSqlDialect(item.sqlDialect); runTestItem(item); } }
Source:
private PreparedStatement getPreparedStatement(String queryString) throws SQLException { PreparedStatement statement = conn.prepareStatement(queryString); statement.setFetchSize(statementOptions.getFetchSize()); statement.setMaxFieldSize(statementOptions.getMaxFieldSize()); statement.setQueryTimeout(statementOptions.getQueryTimeout()); statement.setMaxRows(statementOptions.getMaxRows()); return statement; }

Target:
private PreparedStatement getPreparedStatement(String queryString) throws SQLException { PreparedStatement statement = conn.prepareStatement(queryString); if (statementOptions.getFetchSize() != null) { statement.setFetchSize(statementOptions.getFetchSize()); } if (statementOptions.getMaxFieldSize() != null) { statement.setMaxFieldSize(statementOptions.getMaxFieldSize()); } if (statementOptions.getQueryTimeout() != null) { statement.setQueryTimeout(statementOptions.getQueryTimeout()); } if (statementOptions.getMaxRows() != null) { statement.setMaxRows(statementOptions.getMaxRows()); } return statement; }
Source:
public void handleRequest(HttpServerExchange serverExchange) throws Exception { if (OPTIONS.equals(serverExchange.getRequestMethod()) && serverExchange.getRequestHeaders().contains(ORIGIN)) { containerHandler.handleRequest(serverExchange); return; } String path = serverExchange.getRelativePath(); if (path == null || path.equals("") || path.equals("/") || path.equals("/status") || path.equals ("/static")) { containerHandler.handleRequest(serverExchange); return; } authenticator.handleRequest(serverExchange); }

Target:
public void handleRequest(HttpServerExchange serverExchange) throws Exception { if (OPTIONS.equals(serverExchange.getRequestMethod()) && serverExchange.getRequestHeaders().contains(ORIGIN)) { containerHandler.handleRequest(serverExchange); return; } String path = serverExchange.getRelativePath(); if (path == null || path.equals("") || path.equals("/") || path.equals("/status") || path.startsWith("/static")) { containerHandler.handleRequest(serverExchange); return; } if (SECURITY_OPTIONS.contains(DISABLED)) { containerHandler.handleRequest(serverExchange); return; } String authorizationHeader = serverExchange.getRequestHeaders().getFirst(AUTHORIZATION); if (authorizationHeader == null) { endExchange(serverExchange, FORBIDDEN); } else if (authorizationHeader.startsWith(BEARER_PREFIX) && SECURITY_OPTIONS.contains(OPENSHIFT_OAUTH)) { tokenAuthenticator.handleRequest(serverExchange); } else if (authorizationHeader.startsWith(BASIC_PREFIX) && SECURITY_OPTIONS.contains(HTPASSWD)) { basicAuthenticator.handleRequest(serverExchange); } else { endExchange(serverExchange, FORBIDDEN); } }
Source:
private String buildHashedCanonicalRequest(String method, String endpoint, String hashedPayload, String canonicalizedHeadersString, String signedHeaders) { StringBuilder buffer = new StringBuilder(); buffer.append(method).append("\n"); buffer.append(endpoint).append("\n"); buffer.append("").append("\n"); buffer.append(canonicalizedHeadersString).append("\n"); buffer.append(signedHeaders).append("\n"); buffer.append(hashedPayload); return sha256(buffer.toString().getBytes()); }

Target:
private static String buildHashedCanonicalRequest(String method, String endpoint, String hashedPayload, String canonicalizedHeadersString, String signedHeaders) { return sha256((method + "\n" + endpoint + "\n" + "" + "\n" + canonicalizedHeadersString + "\n" + signedHeaders + "\n" + hashedPayload).getBytes()); }
Source:
HelixAccountService(HelixPropertyStore<ZNRecord> helixStore, AccountServiceMetrics accountServiceMetrics, Notifier<String> notifier, ScheduledExecutorService scheduler, HelixAccountServiceConfig config) throws IOException { this.helixStore = Objects.requireNonNull(helixStore, "helixStore cannot be null"); this.accountServiceMetrics = Objects.requireNonNull(accountServiceMetrics, "accountServiceMetrics cannot be null"); this.notifier = notifier; this.scheduler = scheduler; this.config = config; this.accountInfoMapRef = new AtomicReference<>(new AccountInfoMap(accountServiceMetrics)); this.backup = new LocalBackup(this.accountServiceMetrics, config); if (notifier != null) { notifier.subscribe(ACCOUNT_METADATA_CHANGE_TOPIC, changeTopicListener); } else { logger.warn("Notifier is null. Account updates cannot be notified to other entities. Local account cache may not " + "be in sync with remote account data."); accountServiceMetrics.nullNotifierCount.inc(); } if (config.useNewZNodePath) { accountMetadataStore = new RouterStore(this.accountServiceMetrics, backup, helixStore, router); } else { accountMetadataStore = new LegacyMetadataStore(this.accountServiceMetrics, backup, helixStore); initialFetchAndSchedule(); } }

Target:
HelixAccountService(HelixPropertyStore<ZNRecord> helixStore, AccountServiceMetrics accountServiceMetrics, Notifier<String> notifier, ScheduledExecutorService scheduler, HelixAccountServiceConfig config) throws IOException { this.helixStore = Objects.requireNonNull(helixStore, "helixStore cannot be null"); this.accountServiceMetrics = Objects.requireNonNull(accountServiceMetrics, "accountServiceMetrics cannot be null"); this.notifier = notifier; this.scheduler = scheduler; this.config = config; this.accountInfoMapRef = new AtomicReference<>(new AccountInfoMap(accountServiceMetrics)); this.backup = new LocalBackup(this.accountServiceMetrics, config); if (config.useNewZNodePath) { accountMetadataStore = new RouterStore(this.accountServiceMetrics, backup, helixStore, router); } else { accountMetadataStore = new LegacyMetadataStore(this.accountServiceMetrics, backup, helixStore); initialFetchAndSchedule(); } }
Source:
public void test_selectByComponentUuidsAndMetricIds() { LiveMeasureDto measure1 = newLiveMeasure().setMetricId(metric.getId()); LiveMeasureDto measure2 = newLiveMeasure().setMetricId(metric.getId()); underTest.insert(db.getSession(), measure1); underTest.insert(db.getSession(), measure2); List<LiveMeasureDto> selected = underTest.selectByComponentUuidsAndMetricIds(db.getSession(), asList(measure1.getComponentUuid(), measure2.getComponentUuid()), singletonList(metric.getId())); assertThat(selected) .extracting(LiveMeasureDto::getComponentUuid, LiveMeasureDto::getProjectUuid, LiveMeasureDto::getMetricId, LiveMeasureDto::getValue, LiveMeasureDto::getDataAsString) .containsExactlyInAnyOrder( Tuple.tuple(measure1.getComponentUuid(), measure1.getProjectUuid(), measure1.getMetricId(), measure1.getValue(), measure1.getDataAsString()), Tuple.tuple(measure2.getComponentUuid(), measure2.getProjectUuid(), measure2.getMetricId(), measure2.getValue(), measure2.getDataAsString())); assertThat(underTest.selectByComponentUuidsAndMetricIds(db.getSession(), emptyList(), singletonList(metric.getId()))).isEmpty(); assertThat(underTest.selectByComponentUuidsAndMetricIds(db.getSession(), singletonList(measure1.getComponentUuid()), emptyList())).isEmpty(); }

Target:
public void test_selectByComponentUuidsAndMetricIds() { LiveMeasureDto measure1 = newLiveMeasure().setMetricId(metric.getId()); LiveMeasureDto measure2 = newLiveMeasure().setMetricId(metric.getId()); underTest.insert(db.getSession(), measure1); underTest.insert(db.getSession(), measure2); List<LiveMeasureDto> selected = underTest.selectByComponentUuidsAndMetricIds(db.getSession(), asList(measure1.getComponentUuid(), measure2.getComponentUuid()), singletonList(metric.getId())); assertThat(selected) .extracting(LiveMeasureDto::getComponentUuid, LiveMeasureDto::getProjectUuid, LiveMeasureDto::getMetricId, LiveMeasureDto::getValue, LiveMeasureDto::getDataAsString) .containsExactlyInAnyOrder( tuple(measure1.getComponentUuid(), measure1.getProjectUuid(), measure1.getMetricId(), measure1.getValue(), measure1.getDataAsString()), tuple(measure2.getComponentUuid(), measure2.getProjectUuid(), measure2.getMetricId(), measure2.getValue(), measure2.getDataAsString())); assertThat(underTest.selectByComponentUuidsAndMetricIds(db.getSession(), emptyList(), singletonList(metric.getId()))).isEmpty(); assertThat(underTest.selectByComponentUuidsAndMetricIds(db.getSession(), singletonList(measure1.getComponentUuid()), emptyList())).isEmpty(); }
Source:
protected boolean canDoAction() { setStoragePoolId(getParameters().getStoragePoolId()); if (getStoragePool() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST); return false; } if (getQuotaId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_IS_NOT_VALID); return false; } if (getDbFacade().getQuotaDAO().getById(getQuotaId()) == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_NOT_EXIST); return false; } return true; }

Target:
protected boolean canDoAction() { if (getStoragePool() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST); return false; } if (getQuotaId() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_IS_NOT_VALID); return false; } if (getDbFacade().getQuotaDAO().getById(getQuotaId()) == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_NOT_EXIST); return false; } return true; }
Source:
public void testLockedStreamInTxCommit(Boolean shouldCommit) throws SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, RollbackException { for (int i = 0; i < 5; i++) { cache.put(i, "value" + i); } TransactionManager tm = cache.getAdvancedCache().getTransactionManager(); tm.begin(); try { cache.getAdvancedCache().lockedStream().forEach((c, e) -> c.put(e.getKey(), e.getValue() + "-changed")); if (shouldCommit) { tm.commit(); } else { tm.rollback(); } } finally { if (tm.getStatus() == Status.STATUS_ACTIVE) { tm.rollback(); } } for (int i = 0; i < 5; i++) { assertEquals("value" + i + "-changed", cache.get(i)); } }

Target:
public void testLockedStreamInTxCommit(Boolean shouldCommit) throws Exception { for (int i = 0; i < 5; i++) { cache.put(i, "value" + i); } TransactionManager tm = cache.getAdvancedCache().getTransactionManager(); TestingUtil.withTx(tm, () -> { cache.getAdvancedCache().lockedStream().forEach((c, e) -> c.put(e.getKey(), e.getValue() + "-changed")); if (!shouldCommit) tm.setRollbackOnly(); return null; }); for (int i = 0; i < 5; i++) { assertEquals("value" + i + "-changed", cache.get(i)); } }
Source:
protected final void addCacheDetails() { assert cache != null; final String cacheType = cache.getType().getL10n(); final String cacheSize = cache.showSize() ? " (" + cache.getSize().getL10n() + ")" : ""; details.add(R.string.cache_type, cacheType + cacheSize); details.add(R.string.cache_geocode, cache.getGeocode()); details.addCacheState(cache); cacheDistance = details.addDistance(cache, cacheDistance); details.addDifficulty(cache); details.addTerrain(cache); details.addEventDate(cache); if (cache.getRating() > 0) { details.addRating(cache); } else { acquireGCVote(); } final int favCount = cache.getFavoritePoints(); if (favCount >= 0) { details.add(R.string.cache_favorite, favCount + "×"); } final View view = getView(); assert view != null; final Button buttonMore = ButterKnife.findById(view, R.id.more_details); buttonMore.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View arg0) { CacheDetailActivity.startActivity(getActivity(), geocode); getActivity().finish(); } }); registerForContextMenu(buttonMore); }

Target:
protected final void addCacheDetails() { assert cache != null; final String cacheType = cache.getType().getL10n(); final String cacheSize = cache.showSize() ? " (" + cache.getSize().getL10n() + ")" : ""; details.add(R.string.cache_type, cacheType + cacheSize); details.add(R.string.cache_geocode, cache.getGeocode()); details.addCacheState(cache); cacheDistance = details.addDistance(cache, cacheDistance); details.addDifficulty(cache); details.addTerrain(cache); details.addEventDate(cache); if (cache.getRating() > 0) { details.addRating(cache); } else { acquireGCVote(); } final int favCount = cache.getFavoritePoints(); if (favCount >= 0) { details.add(R.string.cache_favorite, res.getString(R.string.favorite_count, favCount)); } final View view = getView(); assert view != null; final Button buttonMore = ButterKnife.findById(view, R.id.more_details); buttonMore.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View arg0) { CacheDetailActivity.startActivity(getActivity(), geocode); getActivity().finish(); } }); registerForContextMenu(buttonMore); }
Source:
TransactionDecodeContext(AdvancedCache<byte[], byte[]> cache, XidImpl xid) { this.xid = xid; this.rpcManager = cache.getRpcManager(); this.localAddress = rpcManager != null ? rpcManager.getAddress() : null; ComponentRegistry registry = cache.getComponentRegistry(); this.commandsFactory = registry.getCommandsFactory(); this.transactionTable = registry.getComponent(TransactionTable.class); this.clusteringDependentLogic = registry.getComponent(ClusteringDependentLogic.class); this.serverTransactionTable = registry.getComponent(ServerTransactionTable.class); this.tm = (EmbeddedTransactionManager) cache.getTransactionManager(); this.txState = serverTransactionTable.getGlobalState(xid); }

Target:
TransactionDecodeContext(AdvancedCache<byte[], byte[]> cache, XidImpl xid) { this.xid = xid; this.rpcManager = cache.getRpcManager(); this.localAddress = rpcManager != null ? rpcManager.getAddress() : null; ComponentRegistry registry = cache.getComponentRegistry(); this.commandsFactory = registry.getCommandsFactory(); this.transactionTable = registry.getComponent(TransactionTable.class); this.clusteringDependentLogic = registry.getComponent(ClusteringDependentLogic.class); this.serverTransactionTable = registry.getComponent(ServerTransactionTable.class); this.txState = serverTransactionTable.getGlobalState(xid); }
Source:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { req.bindJSON(this, json); refreshConnectionMap(); save(); return super.configure(req, json); }

Target:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { connections = req.bindJSONToList(GitLabConnection.class, json.get("connections")); useAuthenticatedEndpoint = json.getBoolean("useAuthenticatedEndpoint"); refreshConnectionMap(); save(); return super.configure(req, json); }
Source:
private void addDeployableCacheStoresProcessors(OperationContext context) { context.addStep(new AbstractDeploymentChainStep() { protected void execute(DeploymentProcessorTarget processorTarget) { int basePriority = POST_MODULE_PRIORITY; processorTarget.addDeploymentProcessor("infinispan", Phase.POST_MODULE, ++basePriority, new AdvancedCacheLoaderExtensionProcessor()); processorTarget.addDeploymentProcessor("infinispan", Phase.POST_MODULE, ++basePriority, new AdvancedCacheWriterExtensionProcessor()); processorTarget.addDeploymentProcessor("infinispan", Phase.POST_MODULE, ++basePriority, new AdvancedLoadWriteStoreExtensionProcessor()); processorTarget.addDeploymentProcessor("infinispan", Phase.POST_MODULE, ++basePriority, new CacheLoaderExtensionProcessor()); processorTarget.addDeploymentProcessor("infinispan", Phase.POST_MODULE, ++basePriority, new CacheWriterExtensionProcessor()); processorTarget.addDeploymentProcessor("infinispan", Phase.POST_MODULE, ++basePriority, new ExternalStoreExtensionProcessor()); processorTarget.addDeploymentProcessor("infinispan", Phase.DEPENDENCIES, DEPENDENCIES_PRIORITY_PRIORITY, new ServerExtensionDependenciesProcessor()); } }, OperationContext.Stage.RUNTIME); context.getServiceTarget().addService(DeployedCacheStoreFactoryService.SERVICE_NAME, new DeployedCacheStoreFactoryService()).install(); }

Target:
private void addDeployableCacheStoresProcessors(OperationContext context) { context.addStep(new AbstractDeploymentChainStep() { protected void execute(DeploymentProcessorTarget processorTarget) { int basePriority = POST_MODULE_PRIORITY; processorTarget.addDeploymentProcessor(INFINISPAN_SUBSYSTEM_NAME, Phase.POST_MODULE, ++basePriority, new AdvancedCacheLoaderExtensionProcessor()); processorTarget.addDeploymentProcessor(INFINISPAN_SUBSYSTEM_NAME, Phase.POST_MODULE, ++basePriority, new AdvancedCacheWriterExtensionProcessor()); processorTarget.addDeploymentProcessor(INFINISPAN_SUBSYSTEM_NAME, Phase.POST_MODULE, ++basePriority, new AdvancedLoadWriteStoreExtensionProcessor()); processorTarget.addDeploymentProcessor(INFINISPAN_SUBSYSTEM_NAME, Phase.POST_MODULE, ++basePriority, new CacheLoaderExtensionProcessor()); processorTarget.addDeploymentProcessor(INFINISPAN_SUBSYSTEM_NAME, Phase.POST_MODULE, ++basePriority, new CacheWriterExtensionProcessor()); processorTarget.addDeploymentProcessor(INFINISPAN_SUBSYSTEM_NAME, Phase.POST_MODULE, ++basePriority, new ExternalStoreExtensionProcessor()); processorTarget.addDeploymentProcessor(INFINISPAN_SUBSYSTEM_NAME, Phase.DEPENDENCIES, DEPENDENCIES_PRIORITY_PRIORITY, new ServerExtensionDependenciesProcessor()); } }, OperationContext.Stage.RUNTIME); context.getServiceTarget().addService(DeployedCacheStoreFactoryService.SERVICE_NAME, new DeployedCacheStoreFactoryService()).install(); }
Source:
private static boolean isColonOfCaseOrDefault(DetailAST colonAst) { boolean result = false; final DetailAST parent = colonAst.getParent(); if (parent.getType() == TokenTypes.LITERAL_CASE || parent.getType() == TokenTypes.LITERAL_DEFAULT) { result = true; } return result; }

Target:
private static boolean isColonOfCaseOrDefault(DetailAST colonAst) { final DetailAST parent = colonAst.getParent(); return parent.getType() == TokenTypes.LITERAL_CASE || parent.getType() == TokenTypes.LITERAL_DEFAULT; }
Source:
public Version getFullVersion() { if (mFullVersion == null) { try { if (getSoftwareVersion() != null && getSoftwareRevision() != null) { String stringVersion; String[] revision = getSoftwareRevision().split("[.]", -1); if (revision.length > 1) { stringVersion = StringFormat.format("%s.%s", getSoftwareVersion(), getSoftwareRevision()); } else { stringVersion = StringFormat.format("%s.0.%s", getSoftwareVersion(), getSoftwareRevision()); } mFullVersion = new Version(stringVersion); } } catch (Exception e) { } } return mFullVersion; }

Target:
public Version getFullVersion() { if (mFullVersion == null) { try { if (getSoftwareVersion() != null && getSoftwareRevision() != null) { String stringVersion; String[] revision = getSoftwareRevision().split("[.]", -1); if (revision.length > 1) { stringVersion = StringFormat.format("%s.%s", getSoftwareVersion(), getSoftwareRevision()); } else { stringVersion = StringFormat.format("%s.0.%s", getSoftwareVersion(), getSoftwareRevision()); } mFullVersion = new Version(stringVersion); } } catch (Exception e) { log.info(StringFormat.format("Couldn't parse vds version: %s , %s", getSoftwareVersion(), getSoftwareRevision())); } } return mFullVersion; }
Source:
@Test public void requestThrowingNonFatalErrorBeforeExecuteFailsExecute() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new ToStringConverterFactory()) .build(); Service service = retrofit.create(Service.class); server.enqueue(new MockResponse()); final AtomicInteger writeCount = new AtomicInteger(); Object a = new Object() { @Override public String toString() { writeCount.incrementAndGet(); throw new AssertionError("Broken!"); } }; Call<String> call = service.postRequestBody(a); try { call.request(); fail(); } catch (AssertionError expected) { assertThat(expected).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); try { call.execute(); fail(); } catch (AssertionError expected) { assertThat(expected).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); }

Target:
@Test public void requestThrowingNonFatalErrorBeforeExecuteFailsExecute() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new ToStringConverterFactory()) .build(); Service service = retrofit.create(Service.class); server.enqueue(new MockResponse()); final AtomicInteger writeCount = new AtomicInteger(); Object a = new Object() { @Override public String toString() { writeCount.incrementAndGet(); throw new Error("Broken!"); } }; Call<String> call = service.postRequestBody(a); try { call.request(); fail(); } catch (Error e) { assertThat(e).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); try { call.execute(); fail(); } catch (Error e) { assertThat(e).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); }
Source:
public List<String> writeLines() { if(id == -1) { throw new IllegalStateException("Site ID is -1"); } List<String> lines = new ArrayList<>(); MagicPath path = getPath(); lines.add("#newsite " + id); lines.add("#level " + level); lines.add("#rarity 5"); lines.add("#path " + path.PathToInteger(path.name)); lines.add("#name \"" + name + "\""); lines.addAll(writeFeatureLines()); lines.add("#end"); lines.add(""); return lines; }

Target:
public List<String> writeLines() { if(id == -1) { throw new IllegalStateException("Site ID is -1"); } List<String> lines = new ArrayList<>(); lines.add("#newsite " + id); lines.add("#level " + level); lines.add("#rarity 5"); lines.add("#path " + getPath().number); lines.add("#name \"" + name + "\""); lines.addAll(writeFeatureLines()); lines.add("#end"); lines.add(""); return lines; }
Source:
public void testProcessDescription() throws Exception { final File pkgDir = temp.newFolder(); final GenerateMojo.GeneratorUtility utility = mojo.new GeneratorUtility(); final RestClient client = mockRestClient(); mojo.descriptions = new ObjectDescriptions(client, 0, null, null, null, null, mojo.getLog()); Set<String> sObjectNames = StreamSupport.stream(mojo.descriptions.fetched().spliterator(), false) .map(d -> d.getName()) .collect(Collectors.toSet()); mojo.processDescription(pkgDir, description, utility, sObjectNames); for (final String source : sources) { final String expected = fileNameAdapter.apply(source); final File generatedFile = new File(pkgDir, source); final String generatedContent = FileUtils.readFileToString(generatedFile, StandardCharsets.UTF_8); final String expectedContent = IOUtils.toString( CamelSalesforceMojoOutputTest.class.getResource("/generated/" + expected), StandardCharsets.UTF_8); Assert.assertEquals("Generated source file in " + source + " must be equal to the one present in test/resources/" + expected, expectedContent, generatedContent); } }

Target:
public void testProcessDescription() throws Exception { final File pkgDir = temp.newFolder(); final GenerateMojo.GeneratorUtility utility = mojo.new GeneratorUtility(); final RestClient client = mockRestClient(); mojo.descriptions = new ObjectDescriptions(client, 0, null, null, null, null, mojo.getLog()); Set<String> sObjectNames = StreamSupport.stream(mojo.descriptions.fetched().spliterator(), false) .map(SObjectDescription::getName) .collect(Collectors.toSet()); mojo.processDescription(pkgDir, description, utility, sObjectNames); for (final String source : sources) { final String expected = fileNameAdapter.apply(source); final File generatedFile = new File(pkgDir, source); final String generatedContent = FileUtils.readFileToString(generatedFile, StandardCharsets.UTF_8); final String expectedContent = IOUtils.toString( CamelSalesforceMojoOutputTest.class.getResource("/generated/" + expected), StandardCharsets.UTF_8); Assert.assertEquals("Generated source file in " + source + " must be equal to the one present in test/resources/" + expected, expectedContent, generatedContent); } }
Source:
private static HttpURLConnection setupUrlConnection(final String method, final URL url, final boolean write, final Map<String,String> additionalHeaders) throws IOException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setAllowUserInteraction(false); getGoogleCredentials() .getRequestMetadata() .entrySet() .forEach( entry -> entry .getValue() .forEach( value -> connection.addRequestProperty(entry.getKey(), value))); additionalHeaders.forEach(connection::addRequestProperty); connection.setRequestMethod(method); connection.setDoInput(true); connection.setDoOutput(write); return connection; }

Target:
private static HttpURLConnection setupUrlConnection(final String method, final URL url, final boolean write, final Map<String,String> additionalHeaders) throws IOException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setAllowUserInteraction(false); getGoogleCredentials() .getRequestMetadata() .forEach( (headerName, headerValues) -> headerValues .forEach( value -> connection.addRequestProperty(headerName, value)) ); additionalHeaders.forEach(connection::addRequestProperty); connection.setRequestMethod(method); connection.setDoInput(true); connection.setDoOutput(write); return connection; }
Source:
public Block ngrams(@SqlType("array(T)") Block array, @SqlType(StandardTypes.BIGINT) long n) { checkCondition(n > 0, INVALID_FUNCTION_ARGUMENT, "N must be positive"); checkCondition(n <= Integer.MAX_VALUE, INVALID_FUNCTION_ARGUMENT, "N is too large"); n = min(array.getPositionCount(), n); BlockBuilder parts = arrayType.createBlockBuilder(null, array.getPositionCount() - (int) n + 1); int[] ids = new int[array.getPositionCount()]; for (int position = 0; position < ids.length; position++) { ids[position] = position; } for (int i = 0; i <= array.getPositionCount() - n; i++) { arrayType.writeObject(parts, array.getPositions(ids, i, (int) n)); } return parts.build(); }

Target:
public static Block ngrams(@SqlType("array(T)") Block array, @SqlType(StandardTypes.BIGINT) long n) { checkCondition(n > 0, INVALID_FUNCTION_ARGUMENT, "N must be positive"); checkCondition(n <= Integer.MAX_VALUE, INVALID_FUNCTION_ARGUMENT, "N is too large"); int numOfRecords = toIntExact(min(array.getPositionCount(), n)); int totalRecords = array.getPositionCount() - numOfRecords + 1; int[] ids = new int[totalRecords * numOfRecords]; int[] offset = new int[totalRecords + 1]; for (int i = 0; i < totalRecords; i++) { for (int j = 0; j < numOfRecords; j++) { ids[i * numOfRecords + j] = i + j; } offset[i + 1] = (i + 1) * numOfRecords; } return ArrayBlock.fromElementBlock(totalRecords, Optional.empty(), offset, array.getPositions(ids, 0, totalRecords * numOfRecords)); }
Source:
private void parseAllocationsFileInBackground(final Project project, final VirtualFile file) { final Task.Modal parseTask = new Task.Modal(project, "Parsing allocations file", false) { private AllocationInfo[] myAllocations; private String errorMessage; @Override public void run(@NotNull ProgressIndicator indicator) { indicator.setIndeterminate(true); final File allocationsFile = VfsUtilCore.virtualToIoFile(file); ByteBuffer data; try { data = ByteBufferUtil.mapFile(allocationsFile, 0, ByteOrder.BIG_ENDIAN); } catch (IOException ex) { errorMessage = "Error reading from allocations file " + allocationsFile.getAbsolutePath(); throw new ProcessCanceledException(); } try { myAllocations = AllocationsParser.parse(data); } catch (final Throwable throwable) { errorMessage = "Unexpected error while parsing allocations file: " + Throwables.getRootCause(throwable).getMessage(); throw new ProcessCanceledException(); } } @Override public void onSuccess() { myAllocationsViewPanel.setAllocations(myAllocations); } @Override public void onCancel() { Messages.showErrorDialog(project, errorMessage, getName()); } }; ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { parseTask.queue(); } }); }

Target:
private void parseAllocationsFileInBackground(final Project project, final VirtualFile file) { final Task.Modal parseTask = new Task.Modal(project, "Parsing allocations file", false) { private AllocationInfo[] myAllocations; private String myErrorMessage; @Override public void run(@NotNull ProgressIndicator indicator) { indicator.setIndeterminate(true); final File allocationsFile = VfsUtilCore.virtualToIoFile(file); ByteBuffer data; try { data = ByteBufferUtil.mapFile(allocationsFile, 0, ByteOrder.BIG_ENDIAN); } catch (IOException ex) { myErrorMessage = "Error reading from allocations file " + allocationsFile.getAbsolutePath(); throw new ProcessCanceledException(); } try { myAllocations = AllocationsParser.parse(data); } catch (final Throwable throwable) { myErrorMessage = "Unexpected error while parsing allocations file: " + Throwables.getRootCause(throwable).getMessage(); throw new ProcessCanceledException(); } } @Override public void onSuccess() { myAllocationsViewPanel.setAllocations(myAllocations); } @Override public void onCancel() { Messages.showErrorDialog(project, myErrorMessage, getName()); } }; ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { parseTask.queue(); } }); }
Source:
public static void registerKey(BaseKey key) { Preconditions.checkArgument( !registeredKeys.containsKey(key.getName()), "Key [%s] has already been registered as a context key", key.getName() ); registeredKeys.put(key.getName(), key); }

Target:
public static synchronized void registerKey(BaseKey key) { Preconditions.checkArgument( !registeredKeys.containsKey(key.getName()), "Key [%s] has already been registered as a context key", key.getName() ); registeredKeys.put(key.getName(), key); }
Source:
public void testProgressConversionToUnits() { TaskChartModelFacade mockChartModel = EasyMock.createMock(TaskChartModelFacade.class); TaskManager taskManager = TestSetupHelper.newTaskManagerBuilder() .withCalendar(new WeekendCalendarImpl()).build(); Task task = createTask(taskManager); task.setStart(TestSetupHelper.newMonday()); task.setDuration(taskManager.createLength(2)); Canvas primitives = new Canvas(); Rectangle r = primitives.createRectangle(0, 0, 100, 10); assertEquals(1, task.getActivities().size()); primitives.bind(r, task.getActivities().get(0)); EasyMock.expect(mockChartModel.getTaskRectangles(task)).andReturn(Collections.singletonList(r)); EasyMock.replay(mockChartModel); ChangeTaskProgressRuler ruler = new ChangeTaskProgressRuler(task, mockChartModel); assertEquals("0", ruler.convertPercentsToUnits(0)); assertEquals("0+", ruler.convertPercentsToUnits(1)); assertEquals("1", ruler.convertPercentsToUnits(50)); assertEquals("1+", ruler.convertPercentsToUnits(51)); assertEquals("1+", ruler.convertPercentsToUnits(99)); assertEquals("2", ruler.convertPercentsToUnits(100)); EasyMock.verify(mockChartModel); }

Target:
public void testProgressConversionToUnits() { TimeDuration taskDuration = new TimeDurationImpl(GPTimeUnitStack.DAY, 2); assertEquals("0", new ChangeTaskProgressRuler.Progress(0, taskDuration).toUnits()); assertEquals("0+", new ChangeTaskProgressRuler.Progress(1, taskDuration).toUnits()); assertEquals("1", new ChangeTaskProgressRuler.Progress(50, taskDuration).toUnits()); assertEquals("1+", new ChangeTaskProgressRuler.Progress(51, taskDuration).toUnits()); assertEquals("1+", new ChangeTaskProgressRuler.Progress(99, taskDuration).toUnits()); assertEquals("2", new ChangeTaskProgressRuler.Progress(100, taskDuration).toUnits()); }
Source:
public void testBasicClusteredWriteBehind() throws Exception { PersistentCacheManager cacheManager = createCacheManager(); Cache<Long, String> cache = cacheManager.getCache(CACHE_NAME, Long.class, String.class); for (int i = 0; i < 10; i++) { cache.put(KEY, String.valueOf(i)); } assertValue(cache, String.valueOf(9)); CLUSTER.getClusterControl().terminateActive(); CLUSTER.getClusterControl().waitForActive(); CLUSTER.getClusterControl().startOneServer(); assertValue(cache, String.valueOf(9)); checkValueFromLoaderWriter(cache, String.valueOf(9)); cache.clear(); }

Target:
public void testBasicClusteredWriteBehind() throws Exception { PersistentCacheManager cacheManager = createCacheManager(); Cache<Long, String> cache = cacheManager.getCache(CACHE_NAME, Long.class, String.class); for (int i = 0; i < 10; i++) { cache.put(KEY, String.valueOf(i)); } assertValue(cache, "9"); CLUSTER.getClusterControl().terminateActive(); CLUSTER.getClusterControl().waitForActive(); CLUSTER.getClusterControl().startOneServer(); Thread.sleep(1000); assertValue(cache, "9"); checkValueFromLoaderWriter(cache, String.valueOf(9)); cache.clear(); }
Source:
static String getBranchStatus(Repository repo) throws IOException { String localName = repo.getBranch(); if (localName == null) return null; String trackingName = getTrackingBranch(repo, localName); if (trackingName == null) return null; Ref tracking = repo.getRef(trackingName); if (tracking == null) return null; Ref local = repo.getRef(localName); if (local == null) return null; RevWalk walk = new RevWalk(repo.newObjectReader()); RevCommit localCommit = walk.parseCommit(local.getObjectId()); RevCommit trackingCommit = walk.parseCommit(tracking.getObjectId()); walk.setRevFilter(RevFilter.MERGE_BASE); walk.markStart(localCommit); walk.markStart(trackingCommit); RevCommit mergeBase = walk.next(); if (mergeBase == null) return null; int localCount = count(walk, localCommit, mergeBase); int trackingCount = count(walk, trackingCommit, mergeBase); if (localCount == 0 && trackingCount == 0) return null; StringBuilder sb = new StringBuilder(); if (localCount != 0) { sb.append(" "); sb.append("↑"); sb.append(localCount); } if (trackingCount != 0) { sb.append(" "); sb.append("↓"); sb.append(trackingCount); } return sb.toString(); }

Target:
static String getBranchStatus(Repository repo) throws IOException { String branchName = repo.getBranch(); if (branchName == null) return null; BranchTrackingStatus status = BranchTrackingStatus.of(repo, branchName); if (status == null) return null; if (status.getAheadCount() == 0 && status.getBehindCount() == 0) return null; String formattedStatus = GitLabelProvider.formatBranchTrackingStatus(status); return formattedStatus; }
Source:
void loadAmmo(final Entity shooter, final FiringPlan plan) { if (null == shooter) { return; } if (null == plan) { return; } for (final WeaponFireInfo info : plan) { final Mounted currentWeapon = info.getWeapon(); if (null == currentWeapon) { continue; } final WeaponType weaponType = (WeaponType) currentWeapon.getType(); if (AmmoType.T_NA == weaponType.getAmmoType()) { continue; } final Mounted mountedAmmo = getPreferredAmmo(shooter, info.getTarget(), weaponType); if ((null != mountedAmmo) && !shooter.loadWeapon(currentWeapon, mountedAmmo)) { owner.log(getClass(), "loadAmmo(Entity, Targetable)", LogLevel.WARNING, shooter.getDisplayName() + " tried to load " + currentWeapon.getName() + " with ammo " + mountedAmmo.getDesc() + " but failed somehow."); } final WeaponAttackAction action = info.getAction(); action.setAmmoId(shooter.getEquipmentNum(mountedAmmo)); action.setAmmoCarrier(mountedAmmo.getEntity().getId()); info.setAction(action); owner.sendAmmoChange(info.getShooter().getId(), shooter.getEquipmentNum(currentWeapon), shooter.getEquipmentNum(mountedAmmo)); } }

Target:
void loadAmmo(final Entity shooter, final FiringPlan plan) { if (null == shooter) { return; } if (null == plan) { return; } for (final WeaponFireInfo info : plan) { final Mounted currentWeapon = info.getWeapon(); if (null == currentWeapon) { continue; } final WeaponType weaponType = (WeaponType) currentWeapon.getType(); if (AmmoType.T_NA == weaponType.getAmmoType()) { continue; } final Mounted mountedAmmo = getPreferredAmmo(shooter, info.getTarget(), weaponType); if ((null != mountedAmmo) && !shooter.loadWeapon(currentWeapon, mountedAmmo)) { owner.log(getClass(), "loadAmmo(Entity, Targetable)", LogLevel.WARNING, shooter.getDisplayName() + " tried to load " + currentWeapon.getName() + " with ammo " + mountedAmmo.getDesc() + " but failed somehow."); continue; } final WeaponAttackAction action = info.getAction(); action.setAmmoId(shooter.getEquipmentNum(mountedAmmo)); action.setAmmoCarrier(mountedAmmo.getEntity().getId()); info.setAction(action); owner.sendAmmoChange(info.getShooter().getId(), shooter.getEquipmentNum(currentWeapon), shooter.getEquipmentNum(mountedAmmo)); } }
Source:
public void onFocusChanged(final ObaStop stop, final HashMap<String, ObaRoute> routes, final Location location) { mStopChangedHandler.post(new Runnable() { public void run() { if (stop != null) { mFocusStopId = stop.getId(); } else { } if (mOnFocusChangedListener != null) { mOnFocusChangedListener.onFocusChanged(stop, routes, location); } } }); }

Target:
public void onFocusChanged(final ObaStop stop, final HashMap<String, ObaRoute> routes, final Location location) { mStopChangedHandler.post(new Runnable() { public void run() { if (stop != null) { mFocusStopId = stop.getId(); } else { mFocusStopId = null; } if (mOnFocusChangedListener != null) { mOnFocusChangedListener.onFocusChanged(stop, routes, location); } } }); }
Source:
public int compare(Viewer viewer, Object o1, Object o2) { IFileRevision e1 = adaptToFileRevision(o1); IFileRevision e2 = adaptToFileRevision(o2); int result = 0; if (e1 == null || e2 == null) { result = super.compare(viewer, o1, o2); } else { for (int element : SORT_ORDERS_BY_COLUMN[columnNumber]) { result = compareColumnValue(element, e1, e2); if (result != 0) break; } } if (reversed) result = -result; return result; }

Target:
public int compare(Viewer viewer, Object o1, Object o2) { IFileRevision e1 = adaptToFileRevision(o1); IFileRevision e2 = adaptToFileRevision(o2); int result = 0; if (e1 == null || e2 == null) { result = super.compare(viewer, o1, o2); } else { for (int columnSortOrder : SORT_ORDERS_BY_COLUMN[columnNumber]) { result = compareColumnValue(columnSortOrder, e1, e2); if (result != 0) break; } } if (reversed) result = -result; return result; }
Source:
public void unmarshalActionMultiConstraintBendableMatchDifferentLength() throws RuleModelDRLPersistenceException { String actionString = "scoreHolder.addMultiConstraintMatch(kcontext, new int[] {-1}, new int[] {2, -3});"; IAction action = extension.unmarshal(actionString); ActionMultiConstraintBendableMatch expectedAction = new ActionMultiConstraintBendableMatch(Arrays.asList(new ActionBendableHardConstraintMatch(0, "-1")), Arrays.asList(new ActionBendableSoftConstraintMatch(0, "2"), new ActionBendableSoftConstraintMatch(1, "-3"))); assertEquals(expectedAction, action); }

Target:
public void unmarshalActionMultiConstraintBendableMatchDifferentLength() throws RuleModelDRLPersistenceException { final String actionString = "scoreHolder.addMultiConstraintMatch(kcontext, new int[] {-1}, new int[] {2, -3});"; final IAction action = extension.unmarshal(actionString); final List<ActionBendableHardConstraintMatch> hardConstraintList = Arrays.asList(new ActionBendableHardConstraintMatch(0, "-1")); final List<ActionBendableSoftConstraintMatch> softConstraintList = Arrays.asList(new ActionBendableSoftConstraintMatch(0, "2"), new ActionBendableSoftConstraintMatch(1, "-3")); final ActionMultiConstraintBendableMatch expectedAction = new ActionMultiConstraintBendableMatch(hardConstraintList, softConstraintList); assertEquals(expectedAction, action); }