auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void apply(final ClassModel model) { final List<FieldModel> resolvedFields = model.getFields(); for (final FieldModel field : resolvedFields) { if (field.isPrivate() && !field.isTransient() && !field.isFinal()) { final String name = field.getName(); final String propertyName = name.substring(0, 1).toUpperCase() + name.substring(1); if (!validGetter(model, field, propertyName) || !validSetter(model, field, propertyName)) { field.setIncluded(getWeight(), false); } } else { field.setIncluded(getWeight(), false); } } }

Target:
public void apply(final ClassModel model) { final List<FieldModel> resolvedFields = model.getFields(); for (final FieldModel field : resolvedFields) { if (field.isPrivate() && !field.isTransient() && !field.isFinal()) { final String name = field.getFieldName(); final String propertyName = name.substring(0, 1).toUpperCase() + name.substring(1); if (!validGetter(model, field, propertyName) || !validSetter(model, field, propertyName)) { field.setIncluded(getWeight(), false); } } else { field.setIncluded(getWeight(), false); } } }
Source:
public void testIsComplexSimpleExpression() { assertTrue(!isComplexTemplate("${value:default}")); }

Target:
public void testIsComplexSimpleExpression() { assertFalse(isComplexTemplate("${value:default}")); }
Source:
private Session openSession() { final Session currentSession = (Session) this.emProvider.get().getDelegate(); final SessionFactory factory = currentSession.getSessionFactory(); return factory.openSession(); }

Target:
protected Session openSession() { final Session currentSession = (Session) this.emProvider.get().getDelegate(); final SessionFactory factory = currentSession.getSessionFactory(); return factory.openSession(); }
Source:
public double isApplicable(VDomainModelReference domainModelReference, EObject domainObject) { if (domainModelReference == null) { reportService.report(new AbstractReport("Warning: The given VControl was null.")); return NOT_APPLICABLE; } if (domainObject == null) { reportService.report(new AbstractReport("Warning: The given domain object was null.")); return NOT_APPLICABLE; } return 1d; }

Target:
public double isApplicable(VDomainModelReference domainModelReference, EObject domainObject) { if (domainModelReference == null) { reportService.report(new AbstractReport("Warning: The given VDomainModelReference was null.")); return NOT_APPLICABLE; } if (domainObject == null) { reportService.report(new AbstractReport("Warning: The given domain object was null.")); return NOT_APPLICABLE; } return 1d; }
Source:
public String eventSalesView(Model model, @PathVariable String key) throws EventNotFoundException{ Event event = eventService.getByKey(key); List<Order> orders = salesService.getAllOrdersByEvent(event); double moneyEarned = 0.0; int ticketsSold = 0; for(Product product: event.getProducts()){ moneyEarned += product.getCost() * product.getSold(); ticketsSold += product.getSold(); } model.addAttribute("orders", orders); model.addAttribute("moneyEarned", moneyEarned); model.addAttribute("ticketsSold", ticketsSold); model.addAttribute("event", event); model.addAttribute("key", key); return "sales/stats/event/index"; }

Target:
public String eventSalesView(Model model, @PathVariable String key) throws EventNotFoundException { Event event = eventService.getByKey(key); List<Order> orders = salesService.getAllOrdersByEvent(event).stream().peek((Order order) -> { order.setOwner(null); order.setChPaymentsReference(null); order.setPaymentMethod(null); }).collect(Collectors.toList()); double moneyEarned = 0.0; int ticketsSold = 0; for (Product product : event.getProducts()) { moneyEarned += product.getCost() * product.getSold(); ticketsSold += product.getSold(); } model.addAttribute("orders", orders); model.addAttribute("moneyEarned", moneyEarned); model.addAttribute("ticketsSold", ticketsSold); model.addAttribute("event", event); model.addAttribute("key", event.getKey()); return "sales/stats/event/index"; }
Source:
private String followTNTTrail(Entity initial){ String name = "tnt"; if (initial != null) { if (initial.getType().equals(EntityType.PRIMED_TNT)) { Entity source = ((TNTPrimed) initial).getSource(); if (source != null) { if (source.getType().equals(EntityType.PLAYER)) { Player player = (Player) source; name = player.getName(); } else if (source.getType().equals(EntityType.PRIMED_TNT)) { Entity newSource = ((TNTPrimed) source).getSource(); if (newSource != null) { name = followTNTTrail(newSource); } } else { name = source.getType().name(); } } else { name = "tnt"; } } else { if (initial.getType().equals(EntityType.PLAYER)) { Player player = (Player) initial; name = player.getName(); } else { name = initial.getType().name(); } } } return name; }

Target:
private String followTNTTrail(Entity initial) { int counter = 10000000; while (initial != null) { if (initial instanceof Player) { return ((Player) initial).getName(); } else if (initial instanceof TNTPrimed) { initial = (((TNTPrimed) initial).getSource()); if (counter < 0) { Location last = initial.getLocation(); plugin.getLogger().warning("TnT chain has exceeded one million, will not continue!"); plugin.getLogger().warning("Last Tnt was at " + last.getX() + ", " + last.getY() + ". " + last.getZ() + " in world " + last.getWorld()); return "tnt"; } counter--; } else { return initial.getType().name(); } } return "tnt"; }
Source:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter printWriter = resp.getWriter(); String containerIdParam = req.getParameter(YARN_CONTAINER_ID); resp.setContentType(APPLICATION_JSON); boolean alive = false; ContainerId yarnContainerId; try { yarnContainerId = ContainerId.fromString(containerIdParam); for (Map.Entry pair : yarnAppState.runningYarnContainers.entrySet()) { YarnContainer yarnContainer = (YarnContainer) pair.getValue(); if (yarnContainer.id().compareTo(yarnContainerId) == 0) { alive = true; } } if (!alive) { heartbeatInvalidCount.inc(); } this.jsonResponse.put("alive", alive); printWriter.write(jsonResponse.toString()); } catch (IllegalArgumentException e) { log.error("Container ID passed is invalid", containerIdParam); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } catch (JSONException e) { log.error("Unable to serialize JSON heartbeat response for container ID with status {}", containerIdParam, alive); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } }

Target:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ContainerId yarnContainerId; PrintWriter printWriter = resp.getWriter(); String containerIdParam = req.getParameter(YARN_CONTAINER_ID); ContainerHeartbeatResponse response; resp.setContentType(APPLICATION_JSON); boolean alive = false; try { yarnContainerId = ContainerId.fromString(containerIdParam); for (YarnContainer yarnContainer : yarnAppState.runningYarnContainers.values()) { if (yarnContainer.id().compareTo(yarnContainerId) == 0) { alive = true; break; } } if (!alive) { heartbeatsExpiredCount.inc(); } response = new ContainerHeartbeatResponse(alive); printWriter.write(mapper.writeValueAsString(response)); } catch (IllegalArgumentException e) { LOG.error("Container ID passed is invalid", containerIdParam); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } }
Source:
public Savepoint setSavepoint() throws SQLException { checkClosed(); if (strict) { throw new SQLFeatureNotSupportedException("Savepoint is not supported."); } return null; }

Target:
public Savepoint setSavepoint() throws SQLException { checkClosed(); throwIfStrictMode("Savepoint is not supported."); return null; }
Source:
private static WebDriverElement createWebDriverElement(Hook hook, WebElement element, WebDriver driver) throws CandybeanException { try { if ("select".equals(element.getTagName())) { return new WebDriverSelector(hook, driver); } return new WebDriverElement(hook, 0, driver, element); } catch (CandybeanException e) { throw e; } }

Target:
private static WebDriverElement createWebDriverElement(Hook hook, WebElement element, WebDriver driver) throws CandybeanException { if ("select".equals(element.getTagName())) { return new WebDriverSelector(hook, driver); } return new WebDriverElement(hook, 0, driver, element); }
Source:
public final Duration toDuration() throws StringValueConversionException { try { return Duration.parse(text); } catch (Exception e) { throw new StringValueConversionException("xxx", e); } }

Target:
public final Duration toDuration() throws StringValueConversionException { try { return Duration.parse(text); } catch (Exception e) { throw new StringValueConversionException("Unable to convert '" + text + "' to a Duration value", e); } }
Source:
private int getReturnCode() { int returnCode = CommandExecutorCodes.Kitchen.SUCCESS.getCode(); if ( getResult().getNrErrors() != 0 ) { getLog().logError( BaseMessages.getString( getPkgClazz(), "Kitchen.Error.FinishedWithErrors" ) ); } return getResult().getResult() ? returnCode : CommandExecutorCodes.Kitchen.ERRORS_DURING_PROCESSING.getCode(); }

Target:
int getReturnCode() { int successCode = CommandExecutorCodes.Kitchen.SUCCESS.getCode(); if ( getResult().getNrErrors() != 0 ) { getLog().logError( BaseMessages.getString( getPkgClazz(), "Kitchen.Error.FinishedWithErrors" ) ); return CommandExecutorCodes.Kitchen.ERRORS_DURING_PROCESSING.getCode(); } return getResult().getResult() ? successCode : CommandExecutorCodes.Kitchen.ERRORS_DURING_PROCESSING.getCode(); }
Source:
public void updateOrbit() { StellarBody parentStar = new StellarBody(); this.orbitTheta = AstronomicalBodyHelper.getOrbitalTheta(orbitalDist, parentStar.getSize()); }

Target:
public void updateOrbit() { this.orbitTheta = AstronomicalBodyHelper.getOrbitalTheta(orbitalDist, getStar().getSize()); }
Source:
protected boolean isReference(Model model, JsonPointer pointer) { TypeDefinition type = model.find(pointer).getType(); if (type instanceof MultipleTypeDefinition) { for (TypeDefinition nestedType : ((MultipleTypeDefinition) type).getMultipleTypes()) { if (getReferencePointerString().equals(nestedType.getPointer().toString())) { return true; } } } JsonPointer pointerToType = type.getPointer(); if (pointerToType == null) { return false; } return getReferencePointerString().equals(pointerToType.toString()); }

Target:
protected boolean isReference(Model model, JsonPointer pointer) { AbstractNode contextNode = model.find(pointer); if (contextNode == null) { return false; } TypeDefinition type = contextNode.getType(); if (type instanceof MultipleTypeDefinition) { for (TypeDefinition nestedType : ((MultipleTypeDefinition) type).getMultipleTypes()) { if (getReferencePointerString().equals(nestedType.getPointer().toString())) { return true; } } } JsonPointer pointerToType = type.getPointer(); if (pointerToType == null) { return false; } return getReferencePointerString().equals(pointerToType.toString()); }
Source:
private static List< Group > fuseCollection( final Collection< Group > c ) { final Deque< Group > champions = new ArrayDeque<>( c ); final List< Group > fused = new ArrayList<>(); if ( champions.size() > 1 ) { while ( !champions.isEmpty() ) { Group champion = champions.pop(); final Set< Group > challengers = new HashSet<>( champions ); challengers.remove( champion ); for ( final Group challenger : challengers ) { final Group fusion = champion.fuse( challenger ); if ( null == fusion ) { } else { champions.remove( challenger ); champion = fusion; } } fused.add( champion ); } } return fused; }

Target:
private static List< Group > fuseCollection( final Collection< Group > c ) { if ( c.size() <= 1 ) return new ArrayList<>( c ); final Deque< Group > champions = new ArrayDeque<>( c ); final List< Group > fused = new ArrayList<>(); while ( !champions.isEmpty() ) { Group champion = champions.pop(); final Set< Group > challengers = new HashSet<>( champions ); challengers.remove( champion ); for ( final Group challenger : challengers ) { final Group fusion = champion.fuse( challenger ); if ( null == fusion ) { } else { champions.remove( challenger ); champion = fusion; } } fused.add( champion ); } return fused; }
Source:
private String getExtraClass(String giverEmail, String instructorEmail, boolean isPublic) { return " giver-display-by-" + (giverEmail.equals(instructorEmail) ? "you" : "others") + " status-display-" + (isPublic ? "public" : "private"); }

Target:
private String getExtraClass(String giverEmail, String instructorEmail, boolean isPublic) { return " giver_display-by-" + (giverEmail.equals(instructorEmail) ? "you" : "others") + " status_display-" + (isPublic ? "public" : "private"); }
Source:
public void missingClassMethodTest() throws IOException, ReplacementFileException { Path file = Paths.get("build/resources/test/randoop/instrument/missingclassreplacement.txt"); thrown.expect(ReplacementFileException.class); String msg = "missingclassreplacement.txt:2: Class not found: randoop.mock.Gamma for line: randoop.MethodReplacements.getAgentPath() randoop.mock.Gamma.delta(alpha.beta.Gamma)"; thrown.expectMessage(msg); HashMap<MethodSignature, MethodSignature> map = ReplacementFileReader.readReplacements(file); }

Target:
public void missingClassMethodTest() throws IOException, ReplacementFileException { Path file = Paths.get("build/resources/test/randoop/instrument/missingclassreplacement.txt"); thrown.expect(ReplacementFileException.class); String msg = "missingclassreplacement.txt:2: Class randoop.mock.Gamma not found for line: randoop.MethodReplacements.getAgentPath() randoop.mock.Gamma.delta(alpha.beta.Gamma)"; thrown.expectMessage(msg); HashMap<MethodSignature, MethodSignature> map = ReplacementFileReader.readReplacements(file); }
Source:
private Resource getComponentResource(String resourceType, ResourceResolver resourceResolver) { String[] resolverSearchPaths = resourceResolver.getSearchPath(); for (String searchPath : resolverSearchPaths) { String tempResourceType = searchPath + resourceType; if (resourceResolver.getResource(tempResourceType) != null) { resourceType = searchPath + resourceType; return resourceResolver.getResource(resourceType); } } return null; }

Target:
private Resource getComponentResource(String resourceType, ResourceResolver resourceResolver) { String[] resolverSearchPaths = resourceResolver.getSearchPath(); for (String searchPath : resolverSearchPaths) { Resource resource = resourceResolver.getResource(searchPath + resourceType); if (resource != null) { return resource; } } return null; }
Source:
public SealVmTemplateCommand(T parameters, CommandContext cmdContext) { super(parameters, cmdContext); if (getParameters().getHostJobId() == null) { getParameters().setHostJobId(Guid.newGuid()); } setVmTemplateId(getParameters().getVmTemplateId()); }

Target:
public SealVmTemplateCommand(T parameters, CommandContext cmdContext) { super(parameters, cmdContext); if (getParameters().getHostJobId() == null) { getParameters().setHostJobId(Guid.newGuid()); } }
Source:
private void recomputeContexts() { ArrayList<IUndoContext> allContexts = new ArrayList<>(); if (triggeringOperation != null) { IUndoContext[] contexts = triggeringOperation.getContexts(); allContexts.addAll(Arrays.asList(contexts)); } for (IUndoableOperation element : children) { for (IUndoContext context : element.getContexts()) { if (!allContexts.contains(context)) { allContexts.add(context); } } } contexts = allContexts; }

Target:
private void recomputeContexts() { ArrayList<IUndoContext> allContexts = new ArrayList<>(); if (triggeringOperation != null) { IUndoContext[] contexts = triggeringOperation.getContexts(); allContexts.addAll(Arrays.asList(contexts)); } for (IUndoableOperation operation : children) { for (IUndoContext context : operation.getContexts()) { if (!allContexts.contains(context)) { allContexts.add(context); } } } contexts = allContexts; }
Source:
private void initUnregisteredVM() { OvfHelper ovfHelper = new OvfHelper(); ovfEntityData = getUnregisteredOVFDataDao().getByEntityIdAndStorageDomain(getParameters().getContainerId(), getParameters().getStorageDomainId()); if (ovfEntityData != null) { try { vmFromConfiguration = ovfHelper.readVmFromOvf(ovfEntityData.getOvfData()); vmFromConfiguration.setVdsGroupId(getParameters().getVdsGroupId()); getParameters().setVm(vmFromConfiguration); getParameters().setDestDomainId(ovfEntityData.getStorageDomainId()); getParameters().setSourceDomainId(ovfEntityData.getStorageDomainId()); if (getParameters().getDiskMap() != null) { vmFromConfiguration.setDiskMap(getParameters().getDiskMap()); vmFromConfiguration.setImages(getDiskImageListFromDiskMap(getParameters().getDiskMap())); } } catch (OvfReaderException e) { log.error("Failed to parse a given ovf configuration: '{}':\n{}", e.getMessage(), ovfEntityData.getOvfData()); log.debug("Exception", e); } } }

Target:
private void initUnregisteredVM() { OvfHelper ovfHelper = new OvfHelper(); ovfEntityData = getUnregisteredOVFDataDao().getByEntityIdAndStorageDomain(getParameters().getContainerId(), getParameters().getStorageDomainId()); if (ovfEntityData != null) { try { vmFromConfiguration = ovfHelper.readVmFromOvf(ovfEntityData.getOvfData()); vmFromConfiguration.setVdsGroupId(getParameters().getVdsGroupId()); getParameters().setVm(vmFromConfiguration); getParameters().setDestDomainId(ovfEntityData.getStorageDomainId()); getParameters().setSourceDomainId(ovfEntityData.getStorageDomainId()); if (getParameters().getDiskMap() != null) { vmFromConfiguration.setDiskMap(getParameters().getDiskMap()); vmFromConfiguration.setImages(getDiskImageListFromDiskMap(getParameters().getDiskMap())); } } catch (OvfReaderException e) { log.error("Failed to parse a given ovf configuration: {}:\n'{}'", e.getMessage(), ovfEntityData.getOvfData()); log.debug("Exception", e); } } }
Source:
public String docs() { return "string {entityID} retruns the persistent unique id of the entity"; }

Target:
public String docs() { return "string {entityID} returns the persistent unique id of the entity"; }
Source:
private void setUpWithCasSupportSetTo(boolean supportsCas) throws Exception { quickTimeoutConfig = ImmutableCassandraKeyValueServiceConfig.copyOf(CassandraContainer.KVS_CONFIG) .withSchemaMutationTimeoutMillis(500); CassandraKeyValueServiceConfigManager simpleManager = CassandraKeyValueServiceConfigManager.createSimpleManager(quickTimeoutConfig); TracingQueryRunner queryRunner = new TracingQueryRunner(log, TracingPrefsConfig.create()); writeConsistency = ConsistencyLevel.EACH_QUORUM; clientPool = CassandraClientPoolImpl.create(simpleManager.getConfig(), TokenRangeWritesLogger.createUninitialized()); lockTable = new UniqueSchemaMutationLockTable( new SchemaMutationLockTables(clientPool, quickTimeoutConfig), LockLeader.I_AM_THE_LOCK_LEADER); heartbeatService = new HeartbeatService( clientPool, queryRunner, HeartbeatService.DEFAULT_HEARTBEAT_TIME_PERIOD_MILLIS, lockTable.getOnlyTable(), writeConsistency); schemaMutationLock = getSchemaMutationLock(supportsCas, simpleManager, queryRunner, SchemaMutationLock.DEFAULT_DEAD_HEARTBEAT_TIMEOUT_THRESHOLD_MILLIS); secondSchemaMutationLock = getSchemaMutationLock(supportsCas, simpleManager, queryRunner, SchemaMutationLock.DEFAULT_DEAD_HEARTBEAT_TIMEOUT_THRESHOLD_MILLIS); lockTestTools = new SchemaMutationLockTestTools(clientPool, lockTable); }

Target:
private void setUpWithCasSupportSetTo(boolean supportsCas) throws Exception { quickTimeoutConfig = ImmutableCassandraKeyValueServiceConfig.copyOf(CassandraContainer.KVS_CONFIG) .withSchemaMutationTimeoutMillis(500); CassandraKeyValueServiceConfigManager simpleManager = CassandraKeyValueServiceConfigManager.createSimpleManager(quickTimeoutConfig); TracingQueryRunner queryRunner = new TracingQueryRunner(log, TracingPrefsConfig.create()); writeConsistency = ConsistencyLevel.EACH_QUORUM; clientPool = CassandraClientPoolImpl.create(simpleManager.getConfig()); lockTable = new UniqueSchemaMutationLockTable( new SchemaMutationLockTables(clientPool, quickTimeoutConfig), LockLeader.I_AM_THE_LOCK_LEADER); heartbeatService = new HeartbeatService( clientPool, queryRunner, HeartbeatService.DEFAULT_HEARTBEAT_TIME_PERIOD_MILLIS, lockTable.getOnlyTable(), writeConsistency); schemaMutationLock = getSchemaMutationLock(supportsCas, simpleManager, queryRunner, SchemaMutationLock.DEFAULT_DEAD_HEARTBEAT_TIMEOUT_THRESHOLD_MILLIS); secondSchemaMutationLock = getSchemaMutationLock(supportsCas, simpleManager, queryRunner, SchemaMutationLock.DEFAULT_DEAD_HEARTBEAT_TIMEOUT_THRESHOLD_MILLIS); lockTestTools = new SchemaMutationLockTestTools(clientPool, lockTable); }
Source:
public Object execute(JobExecutionContext context) throws JobExecutionException { try { JobArguments arguments = context.getJobArguments(); String ownerKey = arguments.getAsString(OWNER_KEY); Owner owner = ownerCurator.getByKey(ownerKey); if (owner == null) { log.warn("Healing attempted against non-existent org id \"{}\"", ownerKey); throw new JobExecutionException( i18n.tr("Healing attempted against non-existent org id \"{}\"", ownerKey)); } if (owner.isAutobindDisabled() || owner.isContentAccessEnabled()) { String caMessage = owner.isContentAccessEnabled() ? " because of the content access mode setting" : ""; throw new JobExecutionException( i18n.tr("Auto-attach is disabled for owner {0}{1}.", owner.getKey(), caMessage)); } Date entitleDate = arguments.getAs(ENTITLE_DATE_KEY, Date.class); StringBuilder result = new StringBuilder(); for (String uuid : ownerCurator.getConsumerUuids(owner).list()) { try { Consumer consumer = consumerCurator.getConsumer(uuid); healSingleConsumer(consumer, owner, entitleDate); result.append("Successfully healed consumer with UUID: ").append(uuid).append("\n"); } catch (Exception e) { log.debug("Healing failed for UUID \"{}\" with message: {}", uuid, e.getMessage()); result.append("Healing failed for UUID: ").append(uuid).append("\n"); } } return result; } catch (Exception e) { log.error("HealEntireOrgJob encountered a problem.", e); throw new JobExecutionException(e.getMessage(), e, false); } }

Target:
public Object execute(JobExecutionContext context) throws JobExecutionException { try { JobArguments arguments = context.getJobArguments(); String ownerKey = arguments.getAsString(OWNER_KEY); Owner owner = ownerCurator.getByKey(ownerKey); if (owner == null) { log.warn("Healing attempted against non-existent org key \"{}\"", ownerKey); throw new JobExecutionException( i18n.tr("Healing attempted against non-existent org key \"{}\"", ownerKey), true); } if (owner.isAutobindDisabled() || owner.isContentAccessEnabled()) { String caMessage = owner.isContentAccessEnabled() ? " because of the content access mode setting" : ""; throw new JobExecutionException( i18n.tr("Auto-attach is disabled for owner {0}{1}.", owner.getKey(), caMessage), true); } Date entitleDate = arguments.getAs(ENTITLE_DATE_KEY, Date.class); StringBuilder result = new StringBuilder(); for (String uuid : ownerCurator.getConsumerUuids(owner).list()) { try { Consumer consumer = consumerCurator.getConsumer(uuid); healSingleConsumer(consumer, owner, entitleDate); result.append("Successfully healed consumer with UUID: ").append(uuid).append("\n"); } catch (Exception e) { log.debug("Healing failed for UUID \"{}\" with message: {}", uuid, e.getMessage()); result.append("Healing failed for UUID: ").append(uuid).append("\n"); } } return result; } catch (Exception e) { log.error("HealEntireOrgJob encountered a problem.", e); throw new JobExecutionException(e.getMessage(), e, false); } }
Source:
public void keyPressed(KeyEvent e) { switch (e.keyCode) { case SWT.SHIFT: { setRangeZoomable(true); return; } case SWT.CTRL: { setDomainZoomable(true); return; } case SWT.SPACE: restoreAutoBounds(); } }

Target:
public void keyPressed(KeyEvent e) { switch (e.keyCode) { case SWT.SHIFT: setRangeZoomable(true); return; case SWT.CTRL: setDomainZoomable(true); return; case SWT.SPACE: restoreAutoBounds(); return; } }
Source:
private void tryToLoadWebView(boolean forceLoad) { System.gc(); if ((!forceLoad && pageIsLoaded) || progressWheel == null) { return; } if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } if (!NetworkUtil.isConnected(getContext())) { showErrorMessage(R.string.reset_no_network_message, FontAwesomeIcons.fa_wifi); return; } showLoadingProgress(); if (!TextUtils.isEmpty(url)) { Map<String, String> map = new HashMap<>(); final String token = loginPrefs.getAuthorizationHeader(); if (token != null) { map.put("Authorization", token); } final EdxCookieManager cookieManager = EdxCookieManager.getSharedInstance(getContext()); if (cookieManager.isSessionCookieMissingOrExpired()) { cookieManager.tryToRefreshSessionCookie(); } else { didReceiveError = false; webView.loadUrl(url); } } }

Target:
private void tryToLoadWebView(boolean forceLoad) { System.gc(); if ((!forceLoad && pageIsLoaded) || progressWheel == null) { return; } if (!EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().register(this); } if (!NetworkUtil.isConnected(getContext())) { showErrorMessage(R.string.reset_no_network_message, FontAwesomeIcons.fa_wifi); return; } showLoadingProgress(); if (!TextUtils.isEmpty(url)) { final EdxCookieManager cookieManager = EdxCookieManager.getSharedInstance(getContext()); if (cookieManager.isSessionCookieMissingOrExpired()) { cookieManager.tryToRefreshSessionCookie(); } else { didReceiveError = false; webView.loadUrl(url); } } }
Source:
private static void checkFieldTypeForSort(FieldDescriptor descriptor, String fieldDescriptions) { for (RealmFieldType aValidFieldTypesForSort : validFieldTypesForSort) { if (aValidFieldTypesForSort == descriptor.getFieldType()) { return; } } throw new IllegalArgumentException(String.format( "Sort is not supported on '%s' field '%s' in '%s'.", descriptor.toString(), descriptor.getFieldName(), fieldDescriptions)); }

Target:
private static void checkFieldTypeForSort(FieldDescriptor descriptor, String fieldDescriptions) { if (!validFieldTypesForSort.contains(descriptor.getFieldType())) { throw new IllegalArgumentException(String.format( "Sort is not supported on '%s' field '%s' in '%s'.", descriptor.toString(), descriptor.getFieldName(), fieldDescriptions)); } }
Source:
public SpiTransaction createServerTransaction(boolean isExplicit, int isolationLevel) { SpiTransaction t = transactionManager.createTransaction(isExplicit, isolationLevel); try { transactionScopeManager.set(t); } catch (PersistenceException existingTransactionError) { t.end(); throw existingTransactionError; } return t; }

Target:
public SpiTransaction createServerTransaction(boolean isExplicit, int isolationLevel) { SpiTransaction t = transactionManager.createTransaction(isExplicit, isolationLevel); if (isExplicit) { try { transactionScopeManager.set(t); } catch (PersistenceException existingTransactionError) { t.end(); throw existingTransactionError; } } return t; }
Source:
public void run() { while (!isInterrupted()) { try { sleep(SLEEP_INTERVAL_MILLIS); long currTime = System.currentTimeMillis(); List<Metric> metrics = _metricService.getMetrics(_dataLagQueryExpression, currTime); if(metrics==null || metrics.isEmpty()) { _logger.info("Data lag detected as metric list is empty"); if(!isDataLagging) { isDataLagging=true; sendDataLagEmailNotification(); } continue; } Metric currMetric = metrics.get(0); if(currMetric.getDatapoints()==null || currMetric.getDatapoints().size()==0) { _logger.info("Data lag detected as data point list is empty"); if(!isDataLagging) { isDataLagging=true; sendDataLagEmailNotification(); } continue; }else { long lastDataPointTime = 0L; for(Long dataPointTime : currMetric.getDatapoints().keySet()) { if(dataPointTime > lastDataPointTime) { lastDataPointTime = dataPointTime; } } if((currTime - lastDataPointTime)> _dataLagThreshold) { _logger.info("Data lag detected as the last data point recieved is more than the data threshold of " + _dataLagThreshold + " ms"); if(!isDataLagging) { isDataLagging=true; sendDataLagEmailNotification(); } continue; } } if(isDataLagging) { isDataLagging = false; sendDataLagEmailNotification(); } }catch(Exception e) { _logger.error("Data lag monitor thread sleep interrupted - " + e.getMessage()); } } }

Target:
public void run() { _logger.info("Data lag monitor thread started"); while (!isInterrupted()) { try { sleep(SLEEP_INTERVAL_MILLIS); long currTime = System.currentTimeMillis(); List<Metric> metrics = _metricService.getMetrics(_dataLagQueryExpression, currTime); if(metrics==null || metrics.isEmpty()) { _logger.info("Data lag detected as metric list is empty"); if(!isDataLagging) { isDataLagging=true; sendDataLagEmailNotification(); } continue; } Metric currMetric = metrics.get(0); if(currMetric.getDatapoints()==null || currMetric.getDatapoints().size()==0) { _logger.info("Data lag detected as data point list is empty"); if(!isDataLagging) { isDataLagging=true; sendDataLagEmailNotification(); } continue; }else { long lastDataPointTime = 0L; for(Long dataPointTime : currMetric.getDatapoints().keySet()) { if(dataPointTime > lastDataPointTime) { lastDataPointTime = dataPointTime; } } if((currTime - lastDataPointTime)> _dataLagThreshold) { _logger.info("Data lag detected as the last data point recieved is more than the data threshold of " + _dataLagThreshold + " ms"); if(!isDataLagging) { isDataLagging=true; sendDataLagEmailNotification(); } continue; } } if(isDataLagging) { isDataLagging = false; sendDataLagEmailNotification(); } }catch(Exception e) { _logger.error("Exception thrown in data lag monitor thread - " + ExceptionUtils.getFullStackTrace(e)); } } }
Source:
protected void updateOvfStoreContent() { if (domainOvfStoresInfoForUpdate.isEmpty()) { return; } updateDate = new Date(); List<Guid> vmAndTemplatesIds = getStorageDomainDAO().getVmAndTemplatesIdsByStorageDomainId(getParameters().getStorageDomainId(), false, false); vmAndTemplatesIds.addAll(getVmStaticDAO().getVmAndTemplatesIdsWithoutAttachedImageDisks(false, false)); byte[] bytes = buildOvfInfoFileByteArray(vmAndTemplatesIds); Pair<StorageDomainOvfInfo, DiskImage> lastOvfStoreForUpdate = domainOvfStoresInfoForUpdate.getLast(); if (lastOvfStoreForUpdate.getFirst().getLastUpdated() != null) { domainOvfStoresInfoForUpdate.removeLast(); } else { lastOvfStoreForUpdate = null; } boolean shouldUpdateLastOvfStore = false; failedOvfDisks = new ArrayList<>(); for (Pair<StorageDomainOvfInfo, DiskImage> pair : domainOvfStoresInfoForUpdate) { shouldUpdateLastOvfStore |= performOvfUpdateForDomain(bytes, pair.getFirst(), pair.getSecond(), vmAndTemplatesIds); } if (shouldUpdateLastOvfStore && lastOvfStoreForUpdate != null) { performOvfUpdateForDomain(bytes, lastOvfStoreForUpdate.getFirst(), lastOvfStoreForUpdate.getSecond(), vmAndTemplatesIds); } if (!failedOvfDisks.isEmpty()) { AuditLogableBase auditLogableBase = new AuditLogableBase(); auditLogableBase.addCustomValue("DataCenterName", getStoragePool().getName()); auditLogableBase.addCustomValue("StorageDomainName", storageDomain.getName()); auditLogableBase.addCustomValue("DisksIds", StringUtils.join(failedOvfDisks, ", ")); AuditLogDirector.log(auditLogableBase, AuditLogType.UPDATE_FOR_OVF_STORES_FAILED); } }

Target:
protected void updateOvfStoreContent() { if (domainOvfStoresInfoForUpdate.isEmpty()) { return; } updateDate = new Date(); List<Guid> vmAndTemplatesIds = getStorageDomainDAO().getVmAndTemplatesIdsByStorageDomainId(getParameters().getStorageDomainId(), false, false); vmAndTemplatesIds.addAll(getVmStaticDAO().getVmAndTemplatesIdsWithoutAttachedImageDisks(false)); byte[] bytes = buildOvfInfoFileByteArray(vmAndTemplatesIds); Pair<StorageDomainOvfInfo, DiskImage> lastOvfStoreForUpdate = domainOvfStoresInfoForUpdate.getLast(); if (lastOvfStoreForUpdate.getFirst().getLastUpdated() != null) { domainOvfStoresInfoForUpdate.removeLast(); } else { lastOvfStoreForUpdate = null; } boolean shouldUpdateLastOvfStore = false; failedOvfDisks = new ArrayList<>(); for (Pair<StorageDomainOvfInfo, DiskImage> pair : domainOvfStoresInfoForUpdate) { shouldUpdateLastOvfStore |= performOvfUpdateForDomain(bytes, pair.getFirst(), pair.getSecond(), vmAndTemplatesIds); } if (shouldUpdateLastOvfStore && lastOvfStoreForUpdate != null) { performOvfUpdateForDomain(bytes, lastOvfStoreForUpdate.getFirst(), lastOvfStoreForUpdate.getSecond(), vmAndTemplatesIds); } if (!failedOvfDisks.isEmpty()) { AuditLogableBase auditLogableBase = new AuditLogableBase(); auditLogableBase.addCustomValue("DataCenterName", getStoragePool().getName()); auditLogableBase.addCustomValue("StorageDomainName", storageDomain.getName()); auditLogableBase.addCustomValue("DisksIds", StringUtils.join(failedOvfDisks, ", ")); AuditLogDirector.log(auditLogableBase, AuditLogType.UPDATE_FOR_OVF_STORES_FAILED); } }
Source:
A loadOrCreate(I id) { A result = load(id).orElseGet(() -> { A created = create(id); lifecycleOf(id).onEntityCreated(AGGREGATE); return created; }); return result; }

Target:
A loadOrCreate(I id) { A result = load(id).orElseGet(() -> createNew(id)); return result; }
Source:
public SolrFilterResult buildSolrQuery() { StringBuilder cond = new StringBuilder("NOT ("); List<String> excludeSets = this.getExcludeSets(); for (int i = 0; i < excludeSets.size(); i++) { if (excludeSets.get(i).substring(0, 4) == "col_") { cond.append("item.collections:"); } else if (excludeSets.get(i).substring(0, 4) == "com_") { cond.append("item.communities:"); } else { throw new UnsupportedOperationException("DSpaceExcludeSetFilter: Unexpected set prefix " + excludeSets.get(i).substring(0, 4)); } cond.append(excludeSets.get(i)); if (i < excludeSets.size() - 1) cond.append(" OR "); } cond.append(")"); return new SolrFilterResult(cond.toString()); }

Target:
public SolrFilterResult buildSolrQuery() { StringBuilder cond = new StringBuilder("NOT ("); List<String> excludeSets = this.getExcludeSets(); for (int i = 0; i < excludeSets.size(); i++) { if (excludeSets.get(i).substring(0, 4).equals("col_")) { cond.append("item.collections:"); } else if (excludeSets.get(i).substring(0, 4).equals("com_")) { cond.append("item.communities:"); } else { throw new UnsupportedOperationException("DSpaceExcludeSetFilter: Unexpected set prefix " + excludeSets.get(i).substring(0, 4)); } cond.append(excludeSets.get(i)); if (i < excludeSets.size() - 1) cond.append(" OR "); } cond.append(")"); return new SolrFilterResult(cond.toString()); }
Source:
public void emit(Event event) { if (!started.get()) { log.error("WTF emit was called while service is not started yet"); return; } if (event instanceof ServiceMetricEvent) { final GraphiteEvent graphiteEvent = graphiteEventConverter.druidEventToGraphite((ServiceMetricEvent) event); if (graphiteEvent == null) { return; } try { final boolean isSuccessful = eventsQueue.offer( graphiteEvent, graphiteEmitterConfig.getEmitWaitTime(), TimeUnit.MILLISECONDS ); if (!isSuccessful) { if (countLostEvents.getAndIncrement() % 1000 == 0) { log.error( "Lost total of [%s] events because of emitter queue is full. Please increase the capacity or/and the consumer frequency", countLostEvents.get() ); } } } catch (InterruptedException e) { log.error(e, "got interrupted with message [%s]", e.getMessage()); Thread.currentThread().interrupt(); } } else if (!emitterList.isEmpty() && event instanceof AlertEvent) { for (Emitter emitter : emitterList) { emitter.emit(event); } } else { log.error("unknown event type [%s]", event.getClass()); return; } }

Target:
public void emit(Event event) { if (!started.get()) { throw new ISE("WTF emit was called while service is not started yet"); } if (event instanceof ServiceMetricEvent) { final GraphiteEvent graphiteEvent = graphiteEventConverter.druidEventToGraphite((ServiceMetricEvent) event); if (graphiteEvent == null) { return; } try { final boolean isSuccessful = eventsQueue.offer( graphiteEvent, graphiteEmitterConfig.getEmitWaitTime(), TimeUnit.MILLISECONDS ); if (!isSuccessful) { if (countLostEvents.getAndIncrement() % 1000 == 0) { log.error( "Lost total of [%s] events because of emitter queue is full. Please increase the capacity or/and the consumer frequency", countLostEvents.get() ); } } } catch (InterruptedException e) { log.error(e, "got interrupted with message [%s]", e.getMessage()); Thread.currentThread().interrupt(); } } else if (!emitterList.isEmpty() && event instanceof AlertEvent) { for (Emitter emitter : emitterList) { emitter.emit(event); } } else if (event instanceof AlertEvent) { AlertEvent alertEvent = (AlertEvent) event; log.error( "The following alert is dropped, description is [%s], severity is [%s]", alertEvent.getDescription(), alertEvent.getSeverity() ); } else { log.error("unknown event type [%s]", event.getClass()); } }
Source:
protected void initDetailModels() { super.initDetailModels(); setClusterVmListModel(new ClusterVmListModel()); setClusterServiceModel(new ClusterServiceModel()); setClusterGlusterHookListModel(new ClusterGlusterHookListModel()); setAffinityGroupListModel(new ClusterAffinityGroupListModel(VdcQueryType.GetAffinityGroupsByClusterId)); ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>(); list.add(new ClusterGeneralModel()); list.add(new ClusterNetworkListModel()); list.add(new ClusterHostListModel()); list.add(getClusterVmListModel()); list.add(getClusterServiceModel()); list.add(getClusterGlusterHookListModel()); list.add(new PermissionListModel()); list.add(getAffinityGroupListModel()); setDetailModels(list); }

Target:
protected void initDetailModels() { super.initDetailModels(); setClusterVmListModel(new ClusterVmListModel()); setClusterServiceModel(new ClusterServiceModel()); setClusterGlusterHookListModel(new ClusterGlusterHookListModel()); setAffinityGroupListModel(new ClusterAffinityGroupListModel()); ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>(); list.add(new ClusterGeneralModel()); list.add(new ClusterNetworkListModel()); list.add(new ClusterHostListModel()); list.add(getClusterVmListModel()); list.add(getClusterServiceModel()); list.add(getClusterGlusterHookListModel()); list.add(new PermissionListModel()); list.add(getAffinityGroupListModel()); setDetailModels(list); }
Source:
private String capitalize(String word) { return Character.toUpperCase(word.charAt(0)) + word.substring(1); }

Target:
private static String capitalize(String word) { return Character.toUpperCase(word.charAt(0)) + word.substring(1); }
Source:
public void execute(Tuple input) { String result = (String) input.getValue(0); String returnInfo = (String) input.getValue(1); LOG.debug("Request Info: {}, Result: {}", returnInfo, result); if (returnInfo != null) { Map<String, Object> retMap; try { retMap = (Map<String, Object>) JSONValue.parseWithException(returnInfo); } catch (ParseException e) { LOG.error("Parseing returnInfo failed", e); _collector.fail(input); return; } final String host = (String) retMap.get("host"); final int port = ObjectReader.getInt(retMap.get("port")); String id = (String) retMap.get("id"); LOG.debug("Request Id: {}, Result: {}", id, result); DistributedRPCInvocations.Iface client = getDRPCClient(host, port); int retryCnt = 0; int maxRetries = 3; while (retryCnt < maxRetries) { retryCnt++; try { LOG.debug("Trying to publish Request Id: {}, Result: {}, to DRPC {}", id, result, host); client.result(id, result); _collector.ack(input); break; } catch (AuthorizationException aze) { LOG.error("Not authorized to return results to DRPC server", aze); _collector.fail(input); throw new RuntimeException(aze); } catch (TException tex) { if (retryCnt >= maxRetries) { LOG.error("Failed to return results to DRPC server", tex); _collector.fail(input); } client = getDRPCClient(host, port); } } } }

Target:
public void execute(Tuple input) { String result = (String) input.getValue(0); String returnInfo = (String) input.getValue(1); LOG.debug("Request Info: {}, Result: {}", returnInfo, result); if (returnInfo != null) { Map<String, Object> retMap; try { retMap = (Map<String, Object>) JSONValue.parseWithException(returnInfo); } catch (ParseException e) { LOG.error("Parseing returnInfo failed", e); _collector.fail(input); return; } final String host = (String) retMap.get("host"); final int port = ObjectReader.getInt(retMap.get("port")); String id = (String) retMap.get("id"); LOG.debug("Request Id: {}, Result: {}", id, result); DistributedRPCInvocations.Iface client = getDRPCClient(host, port); int retryCnt = 0; int maxRetries = 3; while (retryCnt < maxRetries) { retryCnt++; try { if (client != null) { LOG.debug("Trying to publish Request Id: {}, Result: {}, to DRPC {}", id, result, host); client.result(id, result); _collector.ack(input); break; } else { client = getDRPCClient(host, port); } } catch (AuthorizationException aze) { LOG.error("Not authorized to return results to DRPC server", aze); _collector.fail(input); throw new RuntimeException(aze); } catch (TException tex) { if (retryCnt >= maxRetries) { LOG.error("Failed to return results to DRPC server", tex); _collector.fail(input); } client = getDRPCClient(host, port); } } } }
Source:
public void testTransformedPath() { System.setProperty( "ddf.home", Paths.get(System.getProperty("user.dir"), "testTransformedPath").toString()); assertThat( TEST_APR.getPath(), equalTo(Paths.get(USER_DIRECTORY, "testTransformedPath", "test", "path").toString())); }

Target:
public void testTransformedPath() { System.setProperty("ddf.home", Paths.get(USER_DIRECTORY, "testTransformedPath").toString()); assertThat( TEST_APR.getPath(), equalTo(Paths.get(USER_DIRECTORY, "testTransformedPath", "test", "path").toString())); }
Source:
public static Map<URI, ImporterConfig> createConfigEntries(Properties props, AbstractFormatterFactory formatterFactory) { String appName = getProperty(props, "app.name", ""); String streamName = getProperty(props, "stream.name", ""); String region = getProperty(props, "region", ""); String procedure = getProperty(props, "procedure", ""); String secretKey = getProperty(props, "secret.key", ""); String accessKey = getProperty(props, "access.key", ""); String readInterval = getProperty(props, "idle.time.between.reads", "1000"); String maxReadBatchSize = getProperty(props, "max.read.batch.size", "10000"); String taskBackoffTimeMillis = getProperty(props, "task.backoff.time.millis", "500"); List<Shard> shards = discoverShards(region, streamName, accessKey, secretKey, appName); if (shards == null || shards.isEmpty()) { throw new IllegalArgumentException("Kinesis stream " + streamName + " does not have any shards."); } Map<URI, ImporterConfig> configs = new HashMap<>(); int shardCnt = 0; for (Shard shard : shards) { StringBuilder builder = new StringBuilder(128); builder.append("kinesis://").append(region).append("/").append(streamName).append("/").append("shard-") .append(shardCnt++).append("/").append(appName); URI uri = URI.create(builder.toString()); ImporterConfig config = new KinesisStreamImporterConfig(appName, region, streamName, procedure, secretKey, accessKey, Long.parseLong(readInterval), Integer.parseInt(maxReadBatchSize), uri, Long.parseLong(taskBackoffTimeMillis), formatterFactory); configs.put(uri, config); } return configs; }

Target:
public static Map<URI, ImporterConfig> createConfigEntries(Properties props, AbstractFormatterFactory formatterFactory) { String appName = getProperty(props, "app.name", ""); String streamName = getProperty(props, "stream.name", ""); String region = getProperty(props, "region", ""); String procedure = getProperty(props, "procedure", ""); String secretKey = getProperty(props, "secret.key", ""); String accessKey = getProperty(props, "access.key", ""); long readInterval = getPropertyAsLong(props, "idle.time.between.reads", 1000); long maxReadBatchSize = getPropertyAsLong(props, "max.read.batch.size", 10000); long taskBackoffTimeMillis = getPropertyAsLong(props, "task.backoff.time.millis", 500); List<Shard> shards = discoverShards(region, streamName, accessKey, secretKey, appName); if (shards == null || shards.isEmpty()) { throw new IllegalArgumentException("Kinesis stream " + streamName + " does not have any shards."); } Map<URI, ImporterConfig> configs = new HashMap<>(); int shardCnt = 0; for (Shard shard : shards) { StringBuilder builder = new StringBuilder(128); builder.append("kinesis://").append(region).append("/").append(streamName).append("/").append("shard-") .append(shardCnt++).append("/").append(appName); URI uri = URI.create(builder.toString()); ImporterConfig config = new KinesisStreamImporterConfig(appName, region, streamName, procedure, secretKey, accessKey, readInterval, maxReadBatchSize, uri, taskBackoffTimeMillis, formatterFactory); configs.put(uri, config); } return configs; }
Source:
private long validateRefundAndGetAvailableAmount(Charge charge, GatewayAccountEntity gatewayAccountEntity, RefundRequest refundRequest, List<Refund> refundList) { ExternalChargeRefundAvailability refundAvailability; refundAvailability = providers .byName(PaymentGatewayName.valueFrom(gatewayAccountEntity.getGatewayName())) .getExternalChargeRefundAvailability(charge, refundList); checkIfChargeIsRefundableOrTerminate(charge, refundAvailability, gatewayAccountEntity); List<RefundEntity> databaseRefunds = findNotExpungedRefunds(charge.getExternalId()); Map<String, Refund> updatedRefunds = refundList.stream().collect(Collectors.toMap(Refund::getExternalId, refund -> refund)); databaseRefunds.forEach(refundEntity -> updatedRefunds.put(refundEntity.getExternalId(), Refund.from(refundEntity))); long availableToBeRefunded = getTotalAmountAvailableToBeRefunded(charge, new ArrayList<>(updatedRefunds.values())); checkIfRefundRequestIsInConflictOrTerminate(refundRequest, charge, availableToBeRefunded); checkIfRefundAmountWithinLimitOrTerminate(refundRequest, charge, refundAvailability, gatewayAccountEntity, availableToBeRefunded); return availableToBeRefunded; }

Target:
private long validateRefundAndGetAvailableAmount(Charge charge, GatewayAccountEntity gatewayAccountEntity, RefundRequest refundRequest, List<Refund> refundList) { ExternalChargeRefundAvailability refundAvailability; refundAvailability = providers .byName(PaymentGatewayName.valueFrom(gatewayAccountEntity.getGatewayName())) .getExternalChargeRefundAvailability(charge, refundList); checkIfChargeIsRefundableOrTerminate(charge, refundAvailability, gatewayAccountEntity); List<Refund> updatedRefunds = checkForNewRefunds(charge, refundList); long availableToBeRefunded = getTotalAmountAvailableToBeRefunded(charge, updatedRefunds); checkIfRefundRequestIsInConflictOrTerminate(refundRequest, charge, availableToBeRefunded); checkIfRefundAmountWithinLimitOrTerminate(refundRequest, charge, refundAvailability, gatewayAccountEntity, availableToBeRefunded); return availableToBeRefunded; }
Source:
private IProject getSingleProject() { IProject result= null; for (IFile fFile : fFiles) { if (result == null) { result= fFile.getProject(); } else if (!result.equals(fFile.getProject())) { return null; } } for (IFolder fFolder : fFolders) { if (result == null) { result= fFolder.getProject(); } else if (!result.equals(fFolder.getProject())) { return null; } } for (ICompilationUnit fCu : fCus) { if (result == null) { result= fCu.getJavaProject().getProject(); } else if (!result.equals(fCu.getJavaProject().getProject())) { return null; } } return result; }

Target:
private IProject getSingleProject() { IProject result= null; for (IFile file : fFiles) { if (result == null) { result= file.getProject(); } else if (!result.equals(file.getProject())) { return null; } } for (IFolder folder : fFolders) { if (result == null) { result= folder.getProject(); } else if (!result.equals(folder.getProject())) { return null; } } for (ICompilationUnit cu : fCus) { if (result == null) { result= cu.getJavaProject().getProject(); } else if (!result.equals(cu.getJavaProject().getProject())) { return null; } } return result; }