auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ExecutorServiceProvider(int corePoolSize, int maxPoolSize, int queueCapacity) { ThreadFactory factory = new ThreadFactoryBuilder() .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .setNameFormat(this.getClass().getSimpleName() + "-%d") .setDaemon(true) .build(); executor = new ThreadPoolExecutor( corePoolSize, maxPoolSize, 60L, SECONDS, queueCapacity > 0 ? new LinkedBlockingQueue<>(queueCapacity) : new SynchronousQueue<>(), factory); executor.setRejectedExecutionHandler( (r, __) -> LOG.error("Executor rejected to handle the message {}", r)); executor.prestartCoreThread(); }

Target:
public ExecutorServiceProvider(int corePoolSize, int maxPoolSize, int queueCapacity) { ThreadFactory factory = new ThreadFactoryBuilder() .setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance()) .setNameFormat(this.getClass().getSimpleName() + "-%d") .setDaemon(true) .build(); executor = new ThreadPoolExecutor( corePoolSize, maxPoolSize, 60L, SECONDS, queueCapacity > 0 ? new LinkedBlockingQueue<>(queueCapacity) : new SynchronousQueue<>(), factory); executor.setRejectedExecutionHandler( (r, __) -> LOG.warn("Executor rejected to handle the payload {}", r)); executor.prestartCoreThread(); }
Source:
private void mapInstance(Set<MappedRelationship> mappedRelationships, Object parent, FieldInfo reader, Object reference) { String type = reader.relationshipType(); Direction direction = reader.relationshipDirection(); ClassInfo parentInfo = this.session.metaData().classInfo(parent); Long parentId = session.context().nativeId(parent); ClassInfo referenceInfo = this.session.metaData().classInfo(reference); if (referenceInfo != null) { Long referenceId = session.context().nativeId(reference); if (!referenceInfo.isRelationshipEntity()) { if (direction.equals(Direction.OUTGOING)) { MappedRelationship edge = new MappedRelationship(parentId, type, referenceId, null, parentInfo.getUnderlyingClass(), referenceInfo.getUnderlyingClass()); mappedRelationships.add(edge); } else { MappedRelationship edge = new MappedRelationship(referenceId, type, parentId, null, referenceInfo.getUnderlyingClass(), parentInfo.getUnderlyingClass()); mappedRelationships.add(edge); } } else { Object startNode = referenceInfo.getStartNodeReader().read(reference); ClassInfo startNodeInfo = this.session.metaData().classInfo(startNode); Long startNodeId = session.context().nativeId(startNode); Object endNode = referenceInfo.getEndNodeReader().read(reference); ClassInfo endNodeInfo = this.session.metaData().classInfo(endNode); Long endNodeId = session.context().nativeId(endNode); MappedRelationship edge = new MappedRelationship(startNodeId, type, endNodeId, referenceId, startNodeInfo.getUnderlyingClass(), endNodeInfo.getUnderlyingClass()); mappedRelationships.add(edge); } } }

Target:
private void mapInstance(Set<MappedRelationship> mappedRelationships, Object parent, FieldInfo reader, Object reference) { String type = reader.relationshipType(); Direction direction = reader.relationshipDirection(); ClassInfo parentInfo = this.session.metaData().classInfo(parent); Long parentId = session.context().nativeId(parent); ClassInfo referenceInfo = this.session.metaData().classInfo(reference); if (referenceInfo != null) { Long referenceId = session.context().nativeId(reference); if (!referenceInfo.isRelationshipEntity()) { if (direction == Direction.OUTGOING) { MappedRelationship edge = new MappedRelationship(parentId, type, referenceId, null, parentInfo.getUnderlyingClass(), referenceInfo.getUnderlyingClass()); mappedRelationships.add(edge); } else { MappedRelationship edge = new MappedRelationship(referenceId, type, parentId, null, referenceInfo.getUnderlyingClass(), parentInfo.getUnderlyingClass()); mappedRelationships.add(edge); } } else { Object startNode = referenceInfo.getStartNodeReader().read(reference); ClassInfo startNodeInfo = this.session.metaData().classInfo(startNode); Long startNodeId = session.context().nativeId(startNode); Object endNode = referenceInfo.getEndNodeReader().read(reference); ClassInfo endNodeInfo = this.session.metaData().classInfo(endNode); Long endNodeId = session.context().nativeId(endNode); MappedRelationship edge = new MappedRelationship(startNodeId, type, endNodeId, referenceId, startNodeInfo.getUnderlyingClass(), endNodeInfo.getUnderlyingClass()); mappedRelationships.add(edge); } } }
Source:
private List<String> objectsInDatabase(SQLiteDatabase db, String type) { List<String> tables = new ArrayList<>(); Cursor cursor = db.rawQuery("SELECT sql FROM sqlite_master WHERE type = ? AND sql IS NOT NULL", new String[] { type }); try { if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { String sql = cursor.getString(cursor.getColumnIndex("sql")); tables.add("table".equals(type) ? sortTableColumns(sql) : sql); cursor.moveToNext(); } } } finally { cursor.close(); } return tables; }

Target:
private List<String> objectsInDatabase(SQLiteDatabase db, String type) { List<String> databaseObjects = new ArrayList<>(); Cursor cursor = db.rawQuery("SELECT sql FROM sqlite_master WHERE type = ? AND sql IS NOT NULL", new String[] { type }); try { while (cursor.moveToNext()) { String sql = cursor.getString(cursor.getColumnIndex("sql")); String resortedSql = "table".equals(type) ? sortTableColumns(sql) : sql; databaseObjects.add(resortedSql); } } finally { cursor.close(); } return databaseObjects; }
Source:
static Interpolator loadInterpolator(Resources res, Theme theme, int id) throws NotFoundException { XmlResourceParser parser = null; try { parser = res.getAnimation(id); return createInterpolatorFromXml(res, theme, parser); } catch (XmlPullParserException ex) { NotFoundException rnf = new NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id)); rnf.initCause(ex); throw rnf; } catch (IOException ex) { NotFoundException rnf = new NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id)); rnf.initCause(ex); throw rnf; } finally { if (parser != null) { parser.close(); } } }

Target:
static Interpolator loadInterpolator(Resources res, Theme theme, int id) throws NotFoundException { XmlResourceParser parser = null; try { parser = res.getAnimation(id); return createInterpolatorFromXml(res, theme, parser); } catch (XmlPullParserException ex) { NotFoundException rnf = new NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id), ex); throw rnf; } catch (IOException ex) { NotFoundException rnf = new NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id), ex); throw rnf; } finally { if (parser != null) { parser.close(); } } }
Source:
private void autoCrop() { new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { IndeterminateProgressDialog.getInstance().show(); } @Override protected Void doInBackground(Void... params) { Rect shapeBounds = cropAlgorithmSnail(LayerListener.getInstance().getBitmapOfAllLayersToSave()); if (shapeBounds != null) { boxWidth = shapeBounds.width() + 1; boxHeight = shapeBounds.height() + 1; toolPosition.x = shapeBounds.left + (shapeBounds.width() + 1) / 2.0f; toolPosition.y = shapeBounds.top + (shapeBounds.height() + 1) / 2.0f; } return null; } @Override protected void onPostExecute(Void result) { PaintroidApplication.drawingSurface.refreshDrawingSurface(); IndeterminateProgressDialog.getInstance().dismiss(); widthEditText.setText(String.format(Locale.getDefault(), "%d", (int) boxWidth)); heightEditText.setText(String.format(Locale.getDefault(), "%d", (int) boxHeight)); } }.execute(); }

Target:
private void autoCrop() { new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { IndeterminateProgressDialog.getInstance().show(); } @Override protected Void doInBackground(Void... params) { Rect shapeBounds = cropAlgorithmSnail(LayerListener.getInstance().getBitmapOfAllLayersToSave()); if (shapeBounds != null) { boxWidth = shapeBounds.width() + 1; boxHeight = shapeBounds.height() + 1; toolPosition.x = shapeBounds.left + (shapeBounds.width() + 1) / 2.0f; toolPosition.y = shapeBounds.top + (shapeBounds.height() + 1) / 2.0f; } return null; } @Override protected void onPostExecute(Void result) { PaintroidApplication.drawingSurface.refreshDrawingSurface(); IndeterminateProgressDialog.getInstance().dismiss(); setWidthAndHeightTexts(boxHeight, boxWidth); } }.execute(); }
Source:
public void spoutAckedTuple(String streamId, long latencyMs) { String metricName = METRIC_NAME_ACKED + "-" + streamId; Counter c = this.counters.get(metricName); if (c == null) { c = metricRegistry.counter(metricName, this.topologyId, this.componentId, this.taskId, this.workerPort, streamId); this.counters.put(metricName, c); } c.inc(this.samplingRate); metricName = METRIC_NAME_COMPLETE_LATENCY + "-" + streamId; ResettingAverageGauge gauge = this.gauges.get(metricName); if (gauge == null) { gauge = new ResettingAverageGauge(); metricRegistry.gauge(metricName, gauge, this.topologyId, this.componentId, streamId, this.taskId, this.workerPort); this.gauges.put(metricName, gauge); } gauge.addValue(latencyMs); }

Target:
public void spoutAckedTuple(String streamId, long latencyMs) { String metricName = METRIC_NAME_ACKED + "-" + streamId; Counter c = this.getCounter(metricName, streamId); c.inc(this.samplingRate); metricName = METRIC_NAME_COMPLETE_LATENCY + "-" + streamId; RollingAverageGauge gauge = this.getRollingAverageGauge(metricName, streamId); gauge.addValue(latencyMs); }
Source:
synchronized List<ComparisonConfiguration> getComparisonConfigurationsForBaseBranch( String baseBranchName) { List<ComparisonConfiguration> comparisonConfigurationsForBaseBranch = new LinkedList<>(); List<ComparisonConfiguration> comparisonConfigurations = configurationRepository.getConfiguration() .getComparisonConfigurations(); String resolvedBaseBranchName = aliasResolver.resolveBranchAlias(baseBranchName); for (ComparisonConfiguration comparisonConfiguration : comparisonConfigurations) { String resolvedComparisonBranchName = aliasResolver.resolveBranchAlias(comparisonConfiguration.getBaseBranchName()); if (resolvedBaseBranchName.equals(resolvedComparisonBranchName) || resolvedBaseBranchName.matches(resolvedComparisonBranchName)) { comparisonConfigurationsForBaseBranch.add(comparisonConfiguration); } } return comparisonConfigurationsForBaseBranch; }

Target:
synchronized List<ComparisonConfiguration> getComparisonConfigurationsForBaseBranch(String baseBranchName) { List<ComparisonConfiguration> comparisonConfigurationsForBaseBranch = new LinkedList<>(); List<ComparisonConfiguration> comparisonConfigurations = configurationRepository.getConfiguration() .getComparisonConfigurations(); String resolvedBaseBranchName = aliasResolver.resolveBranchAlias(baseBranchName); for (ComparisonConfiguration comparisonConfiguration : comparisonConfigurations) { String resolvedConfigurationBaseBranchName = aliasResolver.resolveBranchAlias(comparisonConfiguration.getBaseBranchName()); if (resolvedBaseBranchName.equals(resolvedConfigurationBaseBranchName) || resolvedBaseBranchName.matches(resolvedConfigurationBaseBranchName)) { comparisonConfigurationsForBaseBranch.add(new ComparisonConfiguration(comparisonConfiguration, resolvedBaseBranchName)); } } return comparisonConfigurationsForBaseBranch; }
Source:
private void createLatestNode(final int hoursAgo) throws Exception { final DateTime now = new DateTime(DateTimeZone.UTC); final DateTime twoHoursAgo = now.minusHours(hoursAgo); final byte[] data = objectMapper.writeValueAsString(twoHoursAgo).getBytes(Charset.forName("UTF-8")); CURATOR.create().creatingParentsIfNeeded().forPath(latestPath, data); }

Target:
private void createLatestNode(final int hoursAgo) throws Exception { final DateTime now = new DateTime(DateTimeZone.UTC); final DateTime pastDate = now.minusHours(hoursAgo); final byte[] data = objectMapper.writeValueAsString(pastDate).getBytes(Charsets.UTF_8); CURATOR.create().creatingParentsIfNeeded().forPath(latestPath, data); }
Source:
private S3Object getObject() throws IOException { AmazonS3 s3 = getClientInstance(); final Configuration config = ConfigurationFactory.getInstance(); final Object object = getObjectKey(); final String bucketName; final String objectKey; if (object instanceof RubyHash) { Map<String, Object> map = convertToHashMap((RubyHash)object); if (map.containsKey("bucket") && map.containsKey("key")) { bucketName = map.get("bucket").toString(); objectKey = map.get("key").toString(); } else { logger.error("Hash does not include bucket and key"); throw new IOException(); } } else { bucketName = config.getString(Key.AMAZONS3RESOLVER_BUCKET_NAME); objectKey = (String)object; } try { logger.info("Requesting from bucket {}", objectKey, bucketName); return s3.getObject(new GetObjectRequest(bucketName, objectKey)); } catch (AmazonS3Exception e) { if (e.getErrorCode().equals("NoSuchKey")) { throw new FileNotFoundException(e.getMessage()); } else { throw new IOException(e); } } }

Target:
private S3Object getObject() throws IOException { AmazonS3 s3 = getClientInstance(); final Configuration config = ConfigurationFactory.getInstance(); final String objectKey = getObjectKey(); if (bucketName == null) { bucketName = config.getString(Key.AMAZONS3RESOLVER_BUCKET_NAME); } try { logger.info("Requesting from bucket {}", objectKey, bucketName); return s3.getObject(new GetObjectRequest(bucketName, objectKey)); } catch (AmazonS3Exception e) { if (e.getErrorCode().equals("NoSuchKey")) { throw new FileNotFoundException(e.getMessage()); } else { throw new IOException(e); } } }
Source:
private void stopVpn() { final NetworkRequest request = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_VPN) .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build(); mCallback = new NetworkCallback() { public void onLost(Network network) { synchronized (mLockShutdown) { Log.i(TAG, "Got lost callback for" + " network=" + network + ",mNetwork" + " = " + mNetwork); if( mNetwork == network){ mLockShutdown.notify(); } } } }; mCM.registerNetworkCallback(request, mCallback); Intent intent = new Intent(mActivity, MyVpnService.class) .putExtra(mPackageName + ".cmd", "disconnect"); mActivity.startService(intent); synchronized (mLockShutdown) { try { Log.i(TAG, "bf mLockShutdown"); mLockShutdown.wait(TIMEOUT_MS); Log.i(TAG, "af mLockShutdown"); } catch(InterruptedException e) } }

Target:
private void stopVpn() { final NetworkRequest request = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_VPN) .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .build(); mCallback = new NetworkCallback() { public void onLost(Network network) { synchronized (mLockShutdown) { Log.i(TAG, "Got lost callback for network=" + network + ",mNetwork = " + mNetwork); if( mNetwork == network){ mLockShutdown.notify(); } } } }; mCM.registerNetworkCallback(request, mCallback); Intent intent = new Intent(mActivity, MyVpnService.class) .putExtra(mPackageName + ".cmd", "disconnect"); mActivity.startService(intent); synchronized (mLockShutdown) { try { Log.i(TAG, "bf mLockShutdown"); mLockShutdown.wait(TIMEOUT_MS); Log.i(TAG, "af mLockShutdown"); } catch(InterruptedException e) } }
Source:
private int computeNumberOfAvailableThreads() { Preconditions.checkState(getServerFactory() instanceof DefaultServerFactory, "Unexpected serverFactory instance on TimeLockServerConfiguration."); DefaultServerFactory serverFactory = (DefaultServerFactory) getServerFactory(); int maxServerThreads = serverFactory.getMaxThreads(); Preconditions.checkNotNull(serverFactory.getApplicationConnectors(), "applicationConnectors of TimeLockServerConfiguration must not be null."); Preconditions.checkState(serverFactory.getApplicationConnectors().get(0) instanceof HttpConnectorFactory, "applicationConnectors of TimeLockServerConfiguration must have a HttpConnectorFactory instance."); HttpConnectorFactory connectorFactory = (HttpConnectorFactory) serverFactory.getApplicationConnectors().get(0); int selectorThreads = connectorFactory.getSelectorThreads().orElse(0); int acceptorThreads = connectorFactory.getAcceptorThreads().orElse(0); return maxServerThreads - selectorThreads - acceptorThreads - 1; }

Target:
private int computeNumberOfAvailableThreads() { Preconditions.checkState(getServerFactory() instanceof DefaultServerFactory, "Unexpected serverFactory instance on TimeLockServerConfiguration."); DefaultServerFactory serverFactory = (DefaultServerFactory) getServerFactory(); int maxServerThreads = serverFactory.getMaxThreads(); Preconditions.checkNotNull(serverFactory.getApplicationConnectors(), "applicationConnectors of TimeLockServerConfiguration must not be null."); Preconditions.checkState(serverFactory.getApplicationConnectors().get(0) instanceof HttpConnectorFactory, "applicationConnectors of TimeLockServerConfiguration must have a HttpConnectorFactory instance."); HttpConnectorFactory connectorFactory = (HttpConnectorFactory) serverFactory.getApplicationConnectors().get(0); int selectorThreads = connectorFactory.getSelectorThreads().orElse(1); int acceptorThreads = connectorFactory.getAcceptorThreads().orElse(1); return maxServerThreads - selectorThreads - acceptorThreads - 1; }
Source:
public final void testAddRemoveMember() throws Exception { CommunityService communityService = new CommunityService(); authenticateEndpoint(communityService.getEndpoint(), properties.getProperty("user1"), properties.getProperty("passwordUser1")); CommunityList communities = communityService.getMyCommunities(); Community community = communities.iterator().next(); Member new_member = new Member(communityService, properties.getProperty("email2")); communityService.addMember(community.getCommunityUuid(), new_member ); MemberList members = communityService.getMembers(community.getCommunityUuid()); for (Member member : members) { assertNotNull(member.getUserid()); assertNotNull(member.getName()); } communityService.removeMember(community.getCommunityUuid(), properties.getProperty("email2")); }

Target:
public final void testAddRemoveMember() throws Exception { CommunityService communityService = new CommunityService(); authenticateEndpoint(communityService.getEndpoint(), properties.getProperty("user1"), properties.getProperty("passwordUser1")); CommunityList communities = communityService.getMyCommunities(); Community community = communities.iterator().next(); Member newMember = new Member(communityService, properties.getProperty("email2")); communityService.addMember(community.getCommunityUuid(), newMember ); MemberList members = communityService.getMembers(community.getCommunityUuid()); for (Member member : members) { assertNotNull(member.getUserid()); assertNotNull(member.getName()); } communityService.removeMember(community.getCommunityUuid(), properties.getProperty("email2")); }
Source:
public RewrittenStatement rewrite(String sql, Binding params, StatementContext ctx) { String sqlUpdated = sql .replaceAll( "(?i)BOOLEAN NOT NULL DEFAULT FALSE", "BIT NOT NULL DEFAULT (0)" ) .replaceAll( "(?i)BOOLEAN NOT NULL DEFAULT TRUE", "BIT NOT NULL DEFAULT (1)" ) .replaceAll( "(?i)BOOLEAN DEFAULT FALSE", "BIT NOT NULL DEFAULT (0)" ) .replaceAll( "(?i)BOOLEAN DEFAULT TRUE", "BIT NOT NULL DEFAULT (1)" ) .replaceAll( "(?i)BOOLEAN", "BIT" ) .replaceAll( "(?i)TRUE", "1" ) .replaceAll( "(?i)FALSE", "0" ) ; return ( new ColonPrefixNamedParamStatementRewriter() ).rewrite( sqlUpdated, params, ctx ); }

Target:
public RewrittenStatement rewrite(String sql, Binding params, StatementContext ctx) { String currentSql = sql; currentSql = REWRITE_PATTERN1.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (0)"); currentSql = REWRITE_PATTERN2.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (1)"); currentSql = REWRITE_PATTERN3.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (0)"); currentSql = REWRITE_PATTERN4.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (1)"); currentSql = REWRITE_PATTERN5.matcher(currentSql).replaceAll("BIT"); currentSql = REWRITE_PATTERN6.matcher(currentSql).replaceAll("1"); currentSql = REWRITE_PATTERN7.matcher(currentSql).replaceAll("0"); return (colonPrefixNamedParamStatementRewriter).rewrite(currentSql, params, ctx); }
Source:
protected static void createMiniSolrCloudCluster() throws Exception { miniSolrCloud = new MiniSolrCloudCluster( 1, getBaseDirPath(), JettyConfig.builder().setContext("/solr").build()); miniSolrCloud.getSolrClient().connect(); System.setProperty("solr.cloud.shardCount", "1"); System.setProperty("solr.cloud.replicationFactor", "1"); System.setProperty("solr.cloud.maxShardPerNode", "1"); System.setProperty("solr.cloud.zookeeper.chroot", "/solr"); System.setProperty("solr.cloud.zookeeper", miniSolrCloud.getZkServer().getZkHost()); System.setProperty("solr.autoSoftCommit.maxTime", String.valueOf(100)); System.setProperty("solr.autoCommit.maxTime", String.valueOf(100)); }

Target:
protected static void createMiniSolrCloudCluster() throws Exception { miniSolrCloud = new MiniSolrCloudCluster( 1, getBaseDirPath(), JettyConfig.builder().setContext("/solr").build()); miniSolrCloud.getSolrClient().connect(); System.setProperty("solr.cloud.shardCount", "1"); System.setProperty("solr.cloud.replicationFactor", "1"); System.setProperty("solr.cloud.maxShardPerNode", "1"); System.setProperty("solr.cloud.zookeeper.chroot", "/solr"); System.setProperty(SolrCommands.ZOOKEEPER_HOSTS_PROP, miniSolrCloud.getZkServer().getZkHost()); System.setProperty("solr.autoSoftCommit.maxTime", String.valueOf(100)); System.setProperty("solr.autoCommit.maxTime", String.valueOf(100)); }
Source:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { Schema inputSchema = getChild().getSchema(); Preconditions.checkState(inputSchema != null, "unable to determine schema in init"); internalAggs = new ArrayList<Aggregator>(); emitEvals = new ArrayList<GenericEvaluator>(); Schema groupingSchema = inputSchema.getSubSchema(gfields); Schema stateSchema = Schema.EMPTY_SCHEMA; for (int i = 0; i < factories.length; ++i) { internalAggs.addAll(factories[i].generateInternalAggs(inputSchema)); List<Expression> emits = factories[i].generateEmitExpressions(inputSchema); Schema newStateSchema = factories[i].generateStateSchema(inputSchema); stateSchema = Schema.merge(stateSchema, newStateSchema); for (Expression exp : emits) { GenericEvaluator evaluator = new GenericEvaluator( exp, new ExpressionOperatorParameter(newStateSchema, newStateSchema)); evaluator.compile(); emitEvals.add(evaluator); } } groupStates = new TupleHashTable( Schema.merge(groupingSchema, stateSchema), MyriaArrayUtils.range(0, gfields.length)); resultBuffer = new TupleBatchBuffer(getSchema()); }

Target:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { Schema inputSchema = getChild().getSchema(); Preconditions.checkState(inputSchema != null, "unable to determine schema in init"); internalAggs = new ArrayList<Aggregator>(); emitEvals = new ArrayList<GenericEvaluator>(); Schema groupingSchema = inputSchema.getSubSchema(gfields); Schema stateSchema = Schema.EMPTY_SCHEMA; PythonFunctionRegistrar pyFuncReg = getPythonFunctionRegistrar(); for (AggregatorFactory factory : factories) { factory.setPyFuncReg(pyFuncReg); internalAggs.addAll(factory.generateInternalAggs(inputSchema)); List<Expression> emits = factory.generateEmitExpressions(inputSchema); Schema newStateSchema = factory.generateStateSchema(inputSchema); stateSchema = Schema.merge(stateSchema, newStateSchema); for (Expression exp : emits) { GenericEvaluator evaluator = null; if (exp.isRegisteredPythonUDF()) { evaluator = new PythonUDFEvaluator( exp, new ExpressionOperatorParameter( inputSchema, stateSchema, getPythonFunctionRegistrar())); } else { evaluator = new GenericEvaluator( exp, new ExpressionOperatorParameter( newStateSchema, newStateSchema, getPythonFunctionRegistrar())); } emitEvals.add(evaluator); } } groupStates = new TupleHashTable( Schema.merge(groupingSchema, stateSchema), MyriaArrayUtils.range(0, gfields.length)); resultBuffer = new TupleBatchBuffer(getSchema()); }
Source:
public void clearRegionCache( String region ) { if ( cacheEnabled ) { Cache cache = regionCache.get( region ); if ( cache != null ) { try { synchronized ( cache ) { cache.clear(); } } catch ( CacheException e ) { CacheManager.logger.error( Messages.getInstance().getString( "CacheManager.ERROR_0006_CACHE_EXCEPTION", e.getLocalizedMessage() ) ); } } else { CacheManager.logger.info( Messages.getInstance().getString( "CacheManager.INFO_0001_CACHE_DOES_NOT_EXIST", region ) ); } } else { CacheManager.logger.warn( Messages.getInstance().getString( "CacheManager.WARN_0001_CACHE_NOT_ENABLED" ) ); } }

Target:
public void clearRegionCache( String region ) { if ( cacheEnabled ) { Cache cache = regionCache.get( region ); if ( cache != null ) { try { cache.clear(); } catch ( CacheException e ) { CacheManager.logger.error( Messages.getInstance().getString( "CacheManager.ERROR_0006_CACHE_EXCEPTION", e.getLocalizedMessage() ) ); } } else { CacheManager.logger.info( Messages.getInstance().getString( "CacheManager.INFO_0001_CACHE_DOES_NOT_EXIST", region ) ); } } else { CacheManager.logger.warn( Messages.getInstance().getString( "CacheManager.WARN_0001_CACHE_NOT_ENABLED" ) ); } }
Source:
public void doWithMessage(final WebServiceMessage message) throws IOException, TransformerException { final SoapMessage soapMessage = (SoapMessage) message; final SoapHeader header = soapMessage.getSoapHeader(); this.keyValues.entrySet().forEach(k -> { final SoapHeaderElement messagePriorityElement = header.addHeaderElement(new QName(NAMESPACE, k.getKey())); messagePriorityElement.setText(k.getValue()); }); }

Target:
public void doWithMessage(final WebServiceMessage message) throws IOException, TransformerException { final SoapMessage soapMessage = (SoapMessage) message; final SoapHeader header = soapMessage.getSoapHeader(); this.keyValues.entrySet().forEach(k -> { final SoapHeaderElement headerElement = header.addHeaderElement(new QName(NAMESPACE, k.getKey())); headerElement.setText(k.getValue()); }); }
Source:
public void switchLanguage(String langCodeCombined) throws IOException { String[] languageCode = langCodeCombined.split("_"); Locale locale; if (languageCode.length == 2) { locale = new Locale(languageCode[0], languageCode[1]); } else { locale = new Locale(languageCode[0]); } try { User user = ServiceManager.getUserService().getById(ServiceManager.getUserService().getAuthenticatedUser().getId()); user.setLanguage(locale.toString()); ServiceManager.getUserService().saveToDatabase(user); } catch (DAOException e) { Helper.setErrorMessage("errorSaving", new Object[] {ObjectType.USER.getTranslationSingular()}, logger, e); } FacesContext context = FacesContext.getCurrentInstance(); context.getViewRoot().setLocale(locale); context.getExternalContext().getSessionMap().put(SESSION_LOCALE_FIELD_ID, locale); context.getExternalContext() .redirect(((HttpServletRequest) context.getExternalContext().getRequest()).getHeader("referer")); }

Target:
public void switchLanguage(String langCodeCombined) throws IOException { String[] languageCode = langCodeCombined.split("_"); Locale locale; if (languageCode.length == 2) { locale = new Locale(languageCode[0], languageCode[1]); } else { locale = new Locale(languageCode[0]); } try { User user = ServiceManager.getUserService().getById(ServiceManager.getUserService().getAuthenticatedUser().getId()); user.setLanguage(locale.toString()); ServiceManager.getUserService().saveToDatabase(user); } catch (DAOException e) { Helper.setErrorMessage("errorSaving", new Object[] {ObjectType.USER.getTranslationSingular()}, logger, e); } FacesContext context = FacesContext.getCurrentInstance(); context.getViewRoot().setLocale(locale); context.getExternalContext().getSessionMap().put(SESSION_LOCALE_FIELD_ID, locale); context.getExternalContext().redirect(null); }
Source:
private void performPromotion() throws IOException { releaseLog.logMessage("Promoting build ..."); PromotionBuilder promotionBuilder = new PromotionBuilder().status(action.getTarget()) .comment(action.getComment()).ciUser(bambooUsername).targetRepo(action.getPromotionRepo()) .dependencies(action.isIncludeDependencies()).copy(action.isUseCopy()) .dryRun(true); releaseLog.logMessage("Performing dry run promotion (no changes are made during dry run) ..."); String buildName = action.getImmutableBuild().getName(); String buildNumber = action.getBuildNumber().toString(); HttpResponse dryResponse = null; HttpResponse wetResponse = null; try { dryResponse = client.stageBuild(buildName, buildNumber, promotionBuilder.build()); if (checkSuccess(dryResponse, true)) { releaseLog.logMessage("Dry run finished successfully. Performing promotion ..."); wetResponse = client.stageBuild(buildName, buildNumber, promotionBuilder.dryRun(false).build()); if (checkSuccess(wetResponse, false)) { releaseLog.logMessage("Promotion completed successfully!"); return; } return; } return; } finally { if (dryResponse != null) { HttpEntity entity = dryResponse.getEntity(); if (entity != null) { EntityUtils.consume(entity); } } if (wetResponse != null) { HttpEntity entity = wetResponse.getEntity(); if (entity != null) { EntityUtils.consume(entity); } } } }

Target:
private void performPromotion() throws IOException { releaseLog.logMessage("Promoting build ..."); PromotionBuilder promotionBuilder = new PromotionBuilder().status(action.getTarget()) .comment(action.getComment()).ciUser(bambooUsername).targetRepo(action.getPromotionRepo()) .dependencies(action.isIncludeDependencies()).copy(action.isUseCopy()) .dryRun(true); releaseLog.logMessage("Performing dry run promotion (no changes are made during dry run) ..."); String buildName = action.getImmutableBuild().getName(); String buildNumber = action.getBuildNumber().toString(); HttpResponse dryResponse = null; HttpResponse wetResponse = null; try { dryResponse = client.stageBuild(buildName, buildNumber, promotionBuilder.build()); if (checkSuccess(dryResponse, true)) { releaseLog.logMessage("Dry run finished successfully. Performing promotion ..."); wetResponse = client.stageBuild(buildName, buildNumber, promotionBuilder.dryRun(false).build()); if (checkSuccess(wetResponse, false)) { releaseLog.logMessage("Promotion completed successfully!"); } } } finally { if (dryResponse != null) { HttpEntity entity = dryResponse.getEntity(); if (entity != null) { EntityUtils.consume(entity); } } if (wetResponse != null) { HttpEntity entity = wetResponse.getEntity(); if (entity != null) { EntityUtils.consume(entity); } } } }
Source:
public static byte[] buildAndSaveKeystore(final List<Ternary<String, String, String>> certs, final String storePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeySpecException { final KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, storePassword != null ? storePassword.toCharArray() : null); for (final Ternary<String, String, String> cert : certs) { if (cert.third() == null) { final Certificate c = buildCertificate(cert.second()); ks.setCertificateEntry(cert.first(), c); } else { final Certificate[] c = new Certificate[certs.size()]; int i = certs.size(); for (final Ternary<String, String, String> ct : certs) { c[i - 1] = buildCertificate(ct.second()); i--; } ks.setKeyEntry(cert.first(), buildPrivateKey(cert.third()), storePassword != null ? storePassword.toCharArray() : null, c); } } try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { ks.store(os, storePassword != null ? storePassword.toCharArray() : null); return os.toByteArray(); } }

Target:
public static byte[] buildAndSaveKeystore(final List<Ternary<String, String, String>> certs, final String storePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeySpecException { Preconditions.checkNotNull(certs, "List of certificates to be saved in keystore cannot be null"); char password[] = null; if (storePassword != null) { password = storePassword.toCharArray(); } final KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, password); for (final Ternary<String, String, String> cert : certs) { if (cert.third() == null) { final Certificate c = buildCertificate(cert.second()); ks.setCertificateEntry(cert.first(), c); } else { final Certificate[] c = new Certificate[certs.size()]; int i = certs.size(); for (final Ternary<String, String, String> ct : certs) { c[i - 1] = buildCertificate(ct.second()); i--; } ks.setKeyEntry(cert.first(), buildPrivateKey(cert.third()), password, c); } } try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { ks.store(os, password); return os.toByteArray(); } }
Source:
public ValidationResult networkQosExistsOrNull() { return vnicProfile.getNetworkQosId() != null && getNetworkQos() == null ? new ValidationResult(VdcBllMessages.NETWORK_QOS_NOT_EXISTS) : ValidationResult.VALID; }

Target:
public ValidationResult networkQosExistsOrNull() { return vnicProfile.getNetworkQosId() == null || getDbFacade().getQosDao().get(vnicProfile.getNetworkQosId()) != null ? ValidationResult.VALID : new ValidationResult(VdcBllMessages.NETWORK_QOS_NOT_EXISTS); }
Source:
public void writeTo(Object object, TreePruner pruner, DataWriter writer) throws IOException { TreePruner child = pruner.accept(object, this); if (child==null) return; Object d = writer.getExportConfig().getExportInterceptor().getValue(this,object,writer.getExportConfig()); if ((d==null && skipNull) || d == ExportInterceptor.SKIP) { return; } if (merge) { if (d != null) { if (d.getClass().getAnnotation(ExportedBean.class) == null) { if(writer.getExportConfig().isSkipIfFail()){ return; } else { throw new NotExportableException(d.getClass()); } } Model model = owner.getOrNull(d.getClass(), parent.type, name); model.writeNestedObjectTo(d, new FilteringTreePruner(parent.HAS_PROPERTY_NAME_IN_ANCESTRY,child), writer); } } else { writer.name(name); writeValue(type, d, child, writer); } }

Target:
public void writeTo(Object object, TreePruner pruner, DataWriter writer) throws IOException { TreePruner child = pruner.accept(object, this); if (child==null) return; Object d = writer.getExportConfig().getExportInterceptor().getValue(this,object, writer.getExportConfig()); if ((d==null && skipNull) || d == ExportInterceptor.SKIP) { return; } if (merge) { if (d != null) { Class<?> objectType = d.getClass(); Model model = owner.getOrNull(objectType, parent.type, name); if (model == null && !writer.getExportConfig().isSkipIfFail()) { throw new NotExportableException(objectType); } else if (model != null) { model.writeNestedObjectTo(d, new FilteringTreePruner(parent.HAS_PROPERTY_NAME_IN_ANCESTRY,child), writer); } } } else { writer.name(name); writeValue(type, d, child, writer); } }
Source:
public void testGetStreamIds() { assertEquals(ImmutableList.of(), ImmutableList.copyOf( new StreamConfig(new MapConfig()).getStreamIds())); StreamConfig streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property", "value"))); assertEquals(ImmutableList.of(STREAM_ID), ImmutableList.copyOf(streamConfig.getStreamIds())); streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property.subProperty", "value"))); assertEquals(ImmutableList.of(STREAM_ID), ImmutableList.copyOf(streamConfig.getStreamIds())); streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property0", "value", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property1", "value", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property.subProperty0", "value", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property.subProperty1", "value", String.format(StreamConfig.STREAM_ID_PREFIX, OTHER_STREAM_ID) + ".property", "value"))); assertEquals(ImmutableList.of(STREAM_ID, OTHER_STREAM_ID), ImmutableList.copyOf(streamConfig.getStreamIds())); }

Target:
public void testGetStreamIds() { assertEquals(ImmutableList.of(), ImmutableList.copyOf( new StreamConfig(new MapConfig()).getStreamIds())); StreamConfig streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property", "value"))); assertEquals(ImmutableSet.of(STREAM_ID), ImmutableSet.copyOf(streamConfig.getStreamIds())); streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property.subProperty", "value"))); assertEquals(ImmutableSet.of(STREAM_ID), ImmutableSet.copyOf(streamConfig.getStreamIds())); streamConfig = new StreamConfig(new MapConfig(ImmutableMap.of( String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property0", "value", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property1", "value", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property.subProperty0", "value", String.format(StreamConfig.STREAM_ID_PREFIX, STREAM_ID) + ".property.subProperty1", "value", String.format(StreamConfig.STREAM_ID_PREFIX, OTHER_STREAM_ID) + ".property", "value"))); assertEquals(ImmutableSet.of(STREAM_ID, OTHER_STREAM_ID), ImmutableSet.copyOf(streamConfig.getStreamIds())); }
Source:
private List<Window> fetchWindowsInQueue() { List<Window> windows = Lists.newArrayList(getWindows()); return ImmutableList.copyOf(Lists.reverse(windows)); }

Target:
private List<Window> fetchWindowsInQueue() { return ImmutableList.copyOf(getWindows()); }
Source:
public void verifyDatasetVersions(Collection collection, CollectionReader collectionReader, Session session) throws ZebedeeException, IOException { if (CMSFeatureFlags.cmsFeatureFlags().isDatasetVersionVerificationEnabled()) { info().collectionID(collection).log("dataset version verification feature enabled verifying collection"); try { versionsService.verifyCollectionDatasets(zebedeeCmsService.getZebedeeReader(), collection, collectionReader, session); } catch (VersionNotFoundException ex) { info().collectionID(collection) .user(session) .exception(ex) .log("error verifying collection datasets"); throw new UnexpectedErrorException(ex.getMessage(), 409); } } }

Target:
public void verifyDatasetVersions(Collection collection, CollectionReader collectionReader, Session session) throws ZebedeeException, IOException { if (CMSFeatureFlags.cmsFeatureFlags().isDatasetVersionVerificationEnabled()) { info().collectionID(collection).log("dataset version verification feature enabled verifying collection"); try { versionsService.verifyCollectionDatasets(zebedeeCmsService.getZebedeeReader(), collection, collectionReader, session); } catch (VersionNotFoundException ex) { error().collectionID(collection) .user(session) .exception(ex) .log("collection approval denied. Error verifying dataset(s) - version(s) not found in either" + " collection or published content"); throw new UnexpectedErrorException(ex.getMessage(), 409); } } }
Source:
public MatchClause append(Filter filter) { boolean wasPreviousSegmentRelationshipEntity = false; for (Filter.NestedPathSegment segment : filter.getNestedPath()) { boolean nestedRelationshipEntity = segment.isNestedRelationshipEntity(); if (!wasPreviousSegmentRelationshipEntity) { if (segment.getRelationshipDirection().equals(Direction.INCOMING)) { clause.append("<"); } clause.append( String.format("-[%s:`%s`]-", nestedRelationshipEntity && isLastSegment(filter, segment) ? "r" + index : "", segment.getRelationshipType())); if (segment.getRelationshipDirection().equals(Direction.OUTGOING)) { clause.append(">"); } } if (!nestedRelationshipEntity && !isLastSegment(filter, segment)) { clause.append(String.format("(:`%s`)", segment.getNestedEntityTypeLabel())); } wasPreviousSegmentRelationshipEntity = nestedRelationshipEntity; } clause.append(String.format("(%s) ", "m" + index)); return this; }

Target:
public MatchClause append(Filter filter) { boolean wasPreviousSegmentRelationshipEntity = false; for (Filter.NestedPathSegment segment : filter.getNestedPath()) { boolean nestedRelationshipEntity = segment.isNestedRelationshipEntity(); if (!wasPreviousSegmentRelationshipEntity) { if (segment.getRelationshipDirection() == Direction.INCOMING) { clause.append("<"); } clause.append( String.format("-[%s:`%s`]-", nestedRelationshipEntity && isLastSegment(filter, segment) ? "r" + index : "", segment.getRelationshipType())); if (segment.getRelationshipDirection() == Direction.OUTGOING) { clause.append(">"); } } if (!nestedRelationshipEntity && !isLastSegment(filter, segment)) { clause.append(String.format("(:`%s`)", segment.getNestedEntityTypeLabel())); } wasPreviousSegmentRelationshipEntity = nestedRelationshipEntity; } clause.append(String.format("(%s) ", "m" + index)); return this; }
Source:
public void testTypeConfiguration() throws Exception { ColumnTypingStrategy strategy = ColumnTypingStrategies.customTypes(ColumnType.STRING, ColumnType.NUMBER); try ( final ColumnTypingSession session = strategy.startColumnTypingSession() ) { assertEquals(ColumnType.STRING, session.getNextColumnType(new ColumnTypingContextImpl(0))); assertEquals(ColumnType.NUMBER, session.getNextColumnType(new ColumnTypingContextImpl(1))); } }

Target:
public void testTypeConfiguration() throws Exception { ColumnTypingStrategy strategy = ColumnTypingStrategies.getCustomStrategy(ColumnType.STRING, ColumnType.NUMBER); try (ColumnTypingSession session = strategy.startColumnTypingSession()) { assertEquals(ColumnType.STRING, session.getNextColumnType(new ColumnTypingContext(0))); assertEquals(ColumnType.NUMBER, session.getNextColumnType(new ColumnTypingContext(1))); } }
Source:
public String jwt(final Authentication authentication) { final Jwt token = (Jwt) authentication.getPrincipal(); @SuppressWarnings("unchecked") final Collection<String> scopes = (Collection<String>) token.getClaims().get("scope"); return String.format( "Hello, %s! You are sucessfully authenticated and granted with %s scopes using a JavaWebToken.", token.getSubject(), scopes.toString()); }

Target:
public String jwt(final Authentication authentication) { final Jwt token = (Jwt) authentication.getPrincipal(); final String scopes = token.getClaimAsString("scope"); return String.format( "Hello, %s! You are sucessfully authenticated and granted with %s scopes using a Jwt.", token.getSubject(), scopes); }
Source:
public static Tuple<String> parseAutoEventValue(String automaticEventValue) { int lastIndex = automaticEventValue.lastIndexOf(":P"); if (lastIndex == -1) { return new Tuple<>(ActivityEventObjectType.ENROLLMENT.name().toLowerCase(), automaticEventValue); } return new Tuple<>(automaticEventValue.substring(0, lastIndex), automaticEventValue.substring(lastIndex+1)); }

Target:
public static Tuple<String> parseAutoEventValue(String automaticEventValue) { int lastIndex = automaticEventValue.lastIndexOf(":P"); if (lastIndex == -1) { return new Tuple<>(null, automaticEventValue); } return new Tuple<>(automaticEventValue.substring(0, lastIndex), automaticEventValue.substring(lastIndex+1)); }
Source:
private IBreakpoint insertAddedElements(BreakpointContainer container, BreakpointContainer refContainer, ModelDelta containerDelta) { IBreakpoint newBreakpoint = null; Object[] children = container.getChildren(); for (Object childElement : refContainer.getChildren()) { Object element = getElement(children, childElement); if (element == null) { if (childElement instanceof BreakpointContainer) { BreakpointContainer.addChildContainer(container, (BreakpointContainer) childElement, containerDelta); } else if(childElement instanceof IBreakpoint) { BreakpointContainer.addBreakpoint(container, (IBreakpoint) childElement, containerDelta); if (newBreakpoint == null) { newBreakpoint = (IBreakpoint) childElement; } } } else if (element instanceof BreakpointContainer) { ModelDelta childDelta = containerDelta.addNode(element, container.getChildIndex(element), IModelDelta.INSTALL, -1); BreakpointContainer.copyOrganizers((BreakpointContainer) element, (BreakpointContainer) childElement); newBreakpoint = insertAddedElements((BreakpointContainer) element, (BreakpointContainer) childElement, childDelta); childDelta.setChildCount(((BreakpointContainer) element).getChildren().length); } } return newBreakpoint; }

Target:
private IBreakpoint insertAddedElements(BreakpointContainer container, BreakpointContainer refContainer, ModelDelta containerDelta) { IBreakpoint newBreakpoint = null; Object[] children = container.getChildren(); for (Object refChildElement : refContainer.getChildren()) { Object element = getElement(children, refChildElement); if (element == null) { if (refChildElement instanceof BreakpointContainer) { BreakpointContainer.addChildContainer(container, (BreakpointContainer) refChildElement, containerDelta); } else if(refChildElement instanceof IBreakpoint) { BreakpointContainer.addBreakpoint(container, (IBreakpoint) refChildElement, containerDelta); if (newBreakpoint == null) { newBreakpoint = (IBreakpoint) refChildElement; } } } else if (element instanceof BreakpointContainer) { ModelDelta childDelta = containerDelta.addNode(element, container.getChildIndex(element), IModelDelta.INSTALL, -1); BreakpointContainer.copyOrganizers((BreakpointContainer) element, (BreakpointContainer) refChildElement); newBreakpoint = insertAddedElements((BreakpointContainer) element, (BreakpointContainer) refChildElement, childDelta); childDelta.setChildCount(((BreakpointContainer) element).getChildren().length); } } return newBreakpoint; }
Source:
public void testSerde() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException { ObjectMapper mapper = new DefaultObjectMapper(); SketchEstimateWithErrorBounds est = new SketchEstimateWithErrorBounds(100.0,101.5,98.5,2); Assert.assertEquals(est, mapper.readValue( mapper.writeValueAsString(est), SketchEstimateWithErrorBounds.class)); }

Target:
public void testSerde() throws IOException { ObjectMapper mapper = new DefaultObjectMapper(); SketchEstimateWithErrorBounds est = new SketchEstimateWithErrorBounds(100.0,101.5,98.5,2); Assert.assertEquals(est, mapper.readValue( mapper.writeValueAsString(est), SketchEstimateWithErrorBounds.class)); }
Source:
public void execute(IProgressMonitor m) throws CoreException { IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor actMonitor) throws CoreException { String taskName; if (branches.size() == 1) taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, branches .iterator().next().getName()); else { StringBuilder names = new StringBuilder(); for (Iterator<Ref> it = branches.iterator(); it.hasNext(); ) { Ref ref = it.next(); names.append(ref.getName()); if (it.hasNext()) names.append(", "); } taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, names.substring(0, names.length() - 2)); } actMonitor.beginTask(taskName, branches.size()); for (Ref branch : branches) { try { new Git(repository).branchDelete().setBranchNames( branch.getName()).setForce(force).call(); status = OK; } catch (NotMergedException e) { status = REJECTED_UNMERGED; break; } catch (CannotDeleteCurrentBranchException e) { status = REJECTED_CURRENT; break; } catch (JGitInternalException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } actMonitor.worked(1); } actMonitor.done(); } }; ResourcesPlugin.getWorkspace().run(action, monitor); }

Target:
public void execute(IProgressMonitor m) throws CoreException { IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor actMonitor) throws CoreException { String taskName; if (branches.size() == 1) taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, branches .iterator().next().getName()); else { StringBuilder names = new StringBuilder(); for (Iterator<Ref> it = branches.iterator(); it.hasNext(); ) { Ref ref = it.next(); names.append(ref.getName()); if (it.hasNext()) names.append(", "); } taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, names); } actMonitor.beginTask(taskName, branches.size()); for (Ref branch : branches) { try { new Git(repository).branchDelete().setBranchNames( branch.getName()).setForce(force).call(); status = OK; } catch (NotMergedException e) { status = REJECTED_UNMERGED; break; } catch (CannotDeleteCurrentBranchException e) { status = REJECTED_CURRENT; break; } catch (JGitInternalException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } actMonitor.worked(1); } actMonitor.done(); } }; ResourcesPlugin.getWorkspace().run(action, monitor); }