auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Set<String> findApplicationIdFromLog(String logFilePath, Logger log) { File logFile = new File(logFilePath); if (!logFile.exists()) { throw new IllegalArgumentException("the logFilePath does not exist: " + logFilePath); } if (!logFile.isFile()) { throw new IllegalArgumentException("the logFilePath specified is not a valid file: " + logFilePath); } if (!logFile.canRead()) { throw new IllegalArgumentException("unable to read the logFilePath specified: " + logFilePath); } BufferedReader br = null; Set<String> applicationIds = new HashSet<String>(); Pattern p = Pattern.compile(".* (application_\\d+_\\d+).*"); try { br = new BufferedReader(new FileReader(logFile)); String input; while ((input = br.readLine()) != null) { Matcher m = p.matcher(input); if (m.find()) { String appId = m.group(1); if (!applicationIds.contains(appId)) { applicationIds.add(appId); } } } } catch (IOException e) { e.printStackTrace(); log.info("Error while trying to find applicationId for Spark log", e); } finally { try { if (br != null) br.close(); } catch (Exception e) { } } return applicationIds; }

Target:
public static Set<String> findApplicationIdFromLog(String logFilePath, Logger log) { File logFile = new File(logFilePath); if (!logFile.exists()) { throw new IllegalArgumentException("the logFilePath does not exist: " + logFilePath); } if (!logFile.isFile()) { throw new IllegalArgumentException("the logFilePath specified is not a valid file: " + logFilePath); } if (!logFile.canRead()) { throw new IllegalArgumentException("unable to read the logFilePath specified: " + logFilePath); } BufferedReader br = null; Set<String> applicationIds = new HashSet<String>(); try { br = new BufferedReader(new FileReader(logFile)); String input; while ((input = br.readLine()) != null) { Matcher m = APPLICATION_ID_PATTERN.matcher(input); if (m.find()) { String appId = m.group(1); applicationIds.add(appId); } } } catch (IOException e) { log.error("Error while trying to find applicationId for Spark log", e); } finally { try { if (br != null) br.close(); } catch (Exception e) { } } return applicationIds; }
Source:
public void setCommandBus(CommandBus commandBus) { this.commandBus = commandBus; this.rescheduler = new Rescheduler(commandBus); }

Target:
protected void setCommandBus(CommandBus commandBus) { this.commandBus = commandBus; this.rescheduler = new Rescheduler(commandBus); }
Source:
public void validate(ServerStoreConfiguration clientStoreConfiguration) throws ClusterTierException, TimeoutException { try { invokeInternalAndWait(endpoint.beginInvoke(), timeouts.getWriteOperationTimeout(), messageFactory.validateServerStore(storeIdentifier , clientStoreConfiguration), false); } catch (ClusterException e) { throw new ClusterTierValidationException("Error validating cluster tier '" + storeIdentifier + "'", e); } }

Target:
public void validate(ServerStoreConfiguration clientStoreConfiguration) throws ClusterTierException, TimeoutException { try { invokeInternalAndWait(endpoint.beginInvoke(), timeouts.getConnectionTimeout(), messageFactory.validateServerStore(storeIdentifier , clientStoreConfiguration), false); } catch (ClusterException e) { throw new ClusterTierValidationException("Error validating cluster tier '" + storeIdentifier + "'", e); } }
Source:
private List<Item> getItems(TreeWalkerAuditEvent event) { final RootNode rootNode; if (event.getRootAst() == null) { rootNode = null; } else { rootNode = new RootNode(event.getRootAst()); } final List<Item> items; try { final XPathDynamicContext xpathDynamicContext = xpathExpression.createDynamicContext(rootNode); items = xpathExpression.evaluate(xpathDynamicContext); } catch (XPathException ex) { throw new IllegalStateException(ex); } return items; }

Target:
private List<Item> getItems(TreeWalkerAuditEvent event) { final RootNode rootNode; if (event.getRootAst() == null) { rootNode = null; } else { rootNode = new RootNode(event.getRootAst()); } final List<Item> items; try { final XPathDynamicContext xpathDynamicContext = xpathExpression.createDynamicContext(rootNode); items = xpathExpression.evaluate(xpathDynamicContext); } catch (XPathException ex) { throw new IllegalStateException("Cannot initialize context and evaluate query: " + xpathQuery, ex); } return items; }
Source:
public static StreamApplication createStreamApplication(Config config) { if (config.get(StreamApplication.APP_CLASS_CONFIG) != null && !config.get(StreamApplication.APP_CLASS_CONFIG).isEmpty()) { TaskConfig taskConfig = new TaskConfig(config); if (taskConfig.getTaskClass() != null && !taskConfig.getTaskClass().isEmpty()) { throw new ConfigException("High level StreamApplication API cannot be used together with low-level API using task.class."); } String appClassName = config.get(StreamApplication.APP_CLASS_CONFIG); try { Class<?> builderClass = Class.forName(appClassName); return (StreamApplication) builderClass.newInstance(); } catch (Throwable t) { String errorMsg = String.format("Failed to validate StreamApplication class from the config. %s = %s", StreamApplication.APP_CLASS_CONFIG, config.get(StreamApplication.APP_CLASS_CONFIG)); log.error(errorMsg, t); throw new ConfigException(String.format("%s is not a StreamApplication.", appClassName)); } } else { return null; } }

Target:
public static StreamApplication createStreamApplication(Config config) { if (config.get(StreamApplication.APP_CLASS_CONFIG) != null && !config.get(StreamApplication.APP_CLASS_CONFIG).isEmpty()) { TaskConfig taskConfig = new TaskConfig(config); if (taskConfig.getTaskClass() != null && !taskConfig.getTaskClass().isEmpty()) { throw new ConfigException("High level StreamApplication API cannot be used together with low-level API using task.class."); } String appClassName = config.get(StreamApplication.APP_CLASS_CONFIG); try { Class<?> builderClass = Class.forName(appClassName); return (StreamApplication) builderClass.newInstance(); } catch (Throwable t) { String errorMsg = String.format("Failed to create StreamApplication class from the config. %s = %s", StreamApplication.APP_CLASS_CONFIG, config.get(StreamApplication.APP_CLASS_CONFIG)); log.error(errorMsg, t); throw new ConfigException(errorMsg, t); } } else { return null; } }
Source:
private void showErrorMessage(@StringRes int errorMsg, @NonNull Icon errorIcon) { if (!pageIsLoaded) { errorTextView.setVisibility(View.VISIBLE); errorTextView.setText(errorMsg); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(errorTextView, null, new IconDrawable(getContext(), errorIcon) .sizeRes(getContext(), R.dimen.content_unavailable_error_icon_size) .colorRes(getContext(), R.color.edx_grayscale_neutral_light), null, null ); tryToClearWebView(); } }

Target:
private void showErrorMessage(@StringRes int errorMsg, @NonNull Icon errorIcon) { if (!pageIsLoaded) { tryToClearWebView(); Context context = getContext(); errorTextView.setVisibility(View.VISIBLE); errorTextView.setText(errorMsg); errorTextView.setCompoundDrawablesWithIntrinsicBounds(null, new IconDrawable(context, errorIcon) .sizeRes(context, R.dimen.content_unavailable_error_icon_size) .colorRes(context, R.color.edx_grayscale_neutral_light), null, null ); } }
Source:
public List<String> getAllExtensions() { final List<String> extensions = new LinkedList<>(); extensions.add(defaultExtension); Optional.ofNullable(otherExtensions).map(Arrays::asList).ifPresent(extensions::addAll); return Collections.unmodifiableList(extensions); }

Target:
public List<String> getAllExtensions() { final List<String> extensions = new LinkedList<>(); extensions.add(defaultExtension); extensions.addAll(Arrays.asList(otherExtensions)); return Collections.unmodifiableList(extensions); }
Source:
private IProject getProject(final IJavaElementDelta delta) { final IJavaProject javaProject = delta.getElement().getJavaProject(); if (javaProject != null) { return javaProject.getProject(); } for (IJavaElementDelta affectedChild : delta.getAffectedChildren()) { return getProject(affectedChild); } return null; }

Target:
private IProject getProject(final IJavaElementDelta delta) { final IJavaProject javaProject = delta.getElement().getJavaProject(); if (javaProject != null) { return javaProject.getProject(); } for (IJavaElementDelta affectedChild : delta.getAffectedChildren()) { final IProject project = getProject(affectedChild); if(project != null) { return project; } } return null; }
Source:
void initDropDownData() { this.isDropDownDataEnum = true; final Map<String, String> currentValueMap = new HashMap<String, String>(); if (constraintList != null && constraintList.getConstraints() != null) { for (FieldConstraint con : constraintList.getConstraints()) { if (con instanceof SingleFieldConstraint) { SingleFieldConstraint sfc = (SingleFieldConstraint) con; String fieldName = sfc.getFieldName(); currentValueMap.put(fieldName, sfc.getValue()); } } } this.dropDownData = oracle.getEnums(this.factType, fieldName, currentValueMap); if (DataType.TYPE_BOOLEAN.equals(this.fieldType) && this.dropDownData != null) { this.isDropDownDataEnum = false; this.dropDownData = DropDownData.create(new String[]{"true", "false"}); } }

Target:
void initDropDownData() { this.isDropDownDataEnum = true; final Map<String, String> currentValueMap = new HashMap<String, String>(); if (constraintList != null && constraintList.getConstraints() != null) { for (FieldConstraint con : constraintList.getConstraints()) { if (con instanceof SingleFieldConstraint) { SingleFieldConstraint sfc = (SingleFieldConstraint) con; String fieldName = sfc.getFieldName(); currentValueMap.put(fieldName, sfc.getValue()); } } } this.dropDownData = oracle.getEnums(this.factType, fieldName, currentValueMap); if (DataType.TYPE_BOOLEAN.equals(this.fieldType) && this.dropDownData == null) { this.isDropDownDataEnum = false; this.dropDownData = DropDownData.create(new String[]{"true", "false"}); } }
Source:
public void testAggregationNodeSymbolMapping() { PlanBuilder builder = new PlanBuilder(new PlanNodeIdAllocator(), metadata); ValuesNode values = builder.values(a, b); AggregationNode aggregation = builder.aggregation(aggregationBuilder -> aggregationBuilder .addGroupingSet(a, b) .addAggregation(c, builder.expression("count(b)"), ImmutableList.of(BIGINT)) .hashSymbol(a) .groupIdSymbol(a) .source(values)); AggregationNode mappedAggregation = SYMBOL_MAPPER.map(aggregation, values); assertEquals(mappedAggregation.getGroupingSets(), singletonList(singletonList(A))); assertEquals(mappedAggregation.getAggregations().keySet(), singleton(c)); assertEquals(getOnlyElement(mappedAggregation.getAggregations().values()).getCall().getArguments(), singletonList(A.toSymbolReference())); assertEquals(mappedAggregation.getHashSymbol().get(), c); assertEquals(mappedAggregation.getGroupIdSymbol().get(), c); }

Target:
public void testAggregationNodeSymbolMapping() { PlanBuilder builder = new PlanBuilder(new PlanNodeIdAllocator(), metadata); ValuesNode values = builder.values(a, b); AggregationNode aggregationNode = builder.aggregation(aggregationBuilder -> aggregationBuilder .addGroupingSet(a, b) .addAggregation(c, builder.expression("count(b)"), ImmutableList.of(BIGINT), a) .hashSymbol(a) .groupIdSymbol(a) .source(values)); AggregationNode mappedAggregationNode = SYMBOL_MAPPER.map(aggregationNode, values); assertEquals(mappedAggregationNode.getGroupingSets(), singletonList(singletonList(A))); assertEquals(mappedAggregationNode.getAggregations().keySet(), singleton(c)); AggregationNode.Aggregation mappedAggregation = getOnlyElement(mappedAggregationNode.getAggregations().values()); assertEquals(mappedAggregation.getCall().getArguments(), singletonList(A.toSymbolReference())); assertEquals(mappedAggregation.getMask().get(), A); assertEquals(mappedAggregationNode.getHashSymbol().get(), A); assertEquals(mappedAggregationNode.getGroupIdSymbol().get(), A); }
Source:
public void voidTestWrite() throws Exception { AmqpTemplate amqpTemplate = mock(AmqpTemplate.class); amqpTemplate.convertAndSend("foo"); amqpTemplate.convertAndSend("bar"); AmqpItemWriter<String> amqpItemWriter = new AmqpItemWriterBuilder<String>().amqpTemplate(amqpTemplate).build(); amqpItemWriter.write(Arrays.asList("foo", "bar")); }

Target:
public void voidTestWrite() throws Exception { AmqpTemplate amqpTemplate = mock(AmqpTemplate.class); AmqpItemWriter<String> amqpItemWriter = new AmqpItemWriterBuilder<String>().amqpTemplate(amqpTemplate).build(); amqpItemWriter.write(Arrays.asList("foo", "bar")); verify(amqpTemplate).convertAndSend("foo"); verify(amqpTemplate).convertAndSend("bar"); }
Source:
private void copyProjects() { File tmpDir = new File(EXTERNAL_STORAGE_ROOT_DIRECTORY, "/tmp"); if (tmpDir.exists()) { try { StorageOperations.deleteDir(tmpDir); } catch (IOException e) { Log.e(TAG, e.getMessage()); } } try { copyProjectsFromExternalToInternalStorage(EXTERNAL_STORAGE_ROOT_DIRECTORY, FlavoredConstants.DEFAULT_ROOT_DIRECTORY); } catch (IOException e) { Log.e(TAG, e.getMessage()); } }

Target:
private static boolean copyProjects() { File tmpDir = new File(OLD_EXTERNAL_STORAGE_ROOT_DIRECTORY, "/tmp"); if (tmpDir.exists()) { try { StorageOperations.deleteDir(tmpDir); } catch (IOException e) { Log.e(TAG, e.getMessage()); } } try { copyFolderRecursive(OLD_EXTERNAL_STORAGE_ROOT_DIRECTORY, FlavoredConstants.DEFAULT_ROOT_DIRECTORY); return true; } catch (IOException e) { Log.e(TAG, e.getMessage()); return false; } }
Source:
static public Expectation<java.util.UUID> insert(final OvsdbClient client, final Table table, Table.OvsdbInsert op) { final Expectation<java.util.UUID> result = new Expectation<>(); Expectation<OperationResult> opResult = singleOp(client, table.getDbSchema(), op); opResult.onComplete(new Expectation.OnComplete<OperationResult>() { @Override public void onSuccess(OperationResult r) { if (r.getCount() > 0) { Row<GenericTableSchema> row = r.getRows().get(0); result.success(table.parseUuid(row)); } else { result.success(null); } } @Override public void onFailure(Throwable exc) { result.failure(exc); } }, callingThreadContext); return result; }

Target:
static public Expectation<java.util.UUID> insert(final OvsdbClient client, final Table table, Table.OvsdbInsert op) { final Expectation<java.util.UUID> result = new Expectation<>(); Expectation<OperationResult> opResult = singleOp(client, table.getDbSchema(), op); opResult.onComplete(new ResultWrapper<java.util.UUID>(result) { @Override public void onSuccess(OperationResult r) { if (r.getCount() > 0) { Row<GenericTableSchema> row = r.getRows().get(0); result.success(table.parseUuid(row)); } else { result.success(null); } } }, callingThreadContext); return result; }
Source:
public DataSource create(Configuration hdpConfig) throws SQLException { LOG.debug("Creating Hikari connection pool for the MetaStore"); String driverUrl = DataSourceProvider.getMetastoreJdbcDriverUrl(hdpConfig); LOG.info("XXX got url " + driverUrl + " from DataSourceProvider"); String user = DataSourceProvider.getMetastoreJdbcUser(hdpConfig); String passwd = DataSourceProvider.getMetastoreJdbcPasswd(hdpConfig); int maxPoolSize = MetastoreConf.getIntVar(hdpConfig, MetastoreConf.ConfVars.CONNECTION_POOLING_MAX_CONNECTIONS); Properties properties = replacePrefix( DataSourceProvider.getPrefixedProperties(hdpConfig, HIKARI)); long connectionTimeout = hdpConfig.getLong(CONNECTION_TIMEOUT_PROPERTY, 30000L); HikariConfig config = null; try { config = new HikariConfig(properties); } catch (Exception e) { throw new SQLException("Cannot create HikariCP configuration: ", e); } config.setMaximumPoolSize(maxPoolSize); config.setJdbcUrl(driverUrl); config.setUsername(user); config.setPassword(passwd); config.setConnectionTimeout(connectionTimeout); return new HikariDataSource(config); }

Target:
public DataSource create(Configuration hdpConfig) throws SQLException { LOG.debug("Creating Hikari connection pool for the MetaStore"); String driverUrl = DataSourceProvider.getMetastoreJdbcDriverUrl(hdpConfig); String user = DataSourceProvider.getMetastoreJdbcUser(hdpConfig); String passwd = DataSourceProvider.getMetastoreJdbcPasswd(hdpConfig); int maxPoolSize = MetastoreConf.getIntVar(hdpConfig, MetastoreConf.ConfVars.CONNECTION_POOLING_MAX_CONNECTIONS); Properties properties = replacePrefix( DataSourceProvider.getPrefixedProperties(hdpConfig, HIKARI)); long connectionTimeout = hdpConfig.getLong(CONNECTION_TIMEOUT_PROPERTY, 30000L); HikariConfig config = null; try { config = new HikariConfig(properties); } catch (Exception e) { throw new SQLException("Cannot create HikariCP configuration: ", e); } config.setMaximumPoolSize(maxPoolSize); config.setJdbcUrl(driverUrl); config.setUsername(user); config.setPassword(passwd); config.setConnectionTimeout(connectionTimeout); return new HikariDataSource(config); }
Source:
private String getAuthToken() { return getIntent().getData().getQueryParameter(SignInActivity.TOKEN_PARAMETER); }

Target:
private @Nullable String getAuthToken() { Uri uri = getIntent().getData(); return uri != null ? uri.getQueryParameter(SignInActivity.TOKEN_PARAMETER) : null; }
Source:
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { Log.w("DBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + "."); DBUpgrader.upgrade(db, oldVersion, newVersion); if (oldVersion == 1090000) { db.execSQL("ALTER TABLE " + TABLE_NAME_FEEDS + " ADD COLUMN " + KEY_FEED_SKIP_INTRO + " INTEGER DEFAULT 0;"); db.execSQL("ALTER TABLE " + TABLE_NAME_FEEDS + " ADD COLUMN " + KEY_FEED_SKIP_ENDING + " INTEGER DEFAULT 0;"); } }

Target:
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { Log.w("DBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + "."); DBUpgrader.upgrade(db, oldVersion, newVersion); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ContainerPlacementMessage message = (ContainerPlacementMessage) o; return getUuid().equals(message.getUuid()) && getDeploymentId().equals(message.getDeploymentId()) && getProcessorId().equals(message.getProcessorId()) && getDestinationHost().equals( message.getDestinationHost()); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ContainerPlacementMessage message = (ContainerPlacementMessage) o; return getTimestamp() == message.getTimestamp() && getUuid().equals(message.getUuid()) && getDeploymentId().equals( message.getDeploymentId()) && getProcessorId().equals(message.getProcessorId()) && getDestinationHost().equals( message.getDestinationHost()) && Objects.equals(getRequestExpiry(), message.getRequestExpiry()) && getStatusCode() == message.getStatusCode(); }
Source:
public SchemaRegistrationResponse register(String subject, String format, String schema) { SchemaRegistrationResponse response = delegate.register(subject,format,schema); cacheManager.getCache("refCache").put(response.getSchemaReference(),schema); cacheManager.getCache("idCache").put(response.getId(),schema); return response; }

Target:
public SchemaRegistrationResponse register(String subject, String format, String schema) { SchemaRegistrationResponse response = delegate.register(subject,format,schema); cacheManager.getCache(ID_CACHE).put(response.getSchemaReference(),schema); cacheManager.getCache(REF_CACHE).put(response.getId(),schema); return response; }
Source:
private ObjectCreator<T> createCreator(List<String> columnNames, ResultSetMetaData metadata, StatementContext ctx) { final int length; try { length = metadata.getColumnCount(); } catch (SQLException e) { throw new ResultSetException("Could not get column count", e, ctx); } if (length != constructor.getParameterCount()) { throw new IllegalStateException(length + " columns in result set, but constructor takes " + constructor.getParameterCount()); } final int[] columnMap = new int[length]; final ColumnMapper<?>[] mappers = new ColumnMapper<?>[length]; for (int i = 0; i < length; i++) { final Type type = constructor.getGenericParameterTypes()[i]; final int paramIndex = parameterIndexForColumn(columnNames.get(i)); if (mappers[paramIndex] != null) { throw new IllegalArgumentException("Column named " + columnNames.get(i) + " maps to multiple parameters"); } mappers[paramIndex] = ctx.findColumnMapperFor(type).orElseThrow(() -> new IllegalArgumentException("Could not find column mapper for type '" + type + "' of parameter for constructor " + constructor)); columnMap[i] = paramIndex; } return rs -> { final Object[] params = new Object[length]; for (int i = 0; i < length; i++) { params[columnMap[i]] = mappers[i].map(rs, i + 1, ctx); } try { return constructor.newInstance(params); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw new RuntimeException(e); } }; }

Target:
private ObjectCreator<T> createCreator(List<String> columnNames, ResultSetMetaData metadata, StatementContext ctx) { final int length = columnNames.size(); if (length != constructor.getParameterCount()) { throw new IllegalStateException(length + " columns in result set, but constructor takes " + constructor.getParameterCount()); } final int[] columnMap = new int[length]; final ColumnMapper<?>[] mappers = new ColumnMapper<?>[length]; for (int i = 0; i < length; i++) { final Type type = constructor.getGenericParameterTypes()[i]; final int paramIndex = parameterIndexForColumn(columnNames.get(i)); if (mappers[paramIndex] != null) { throw new IllegalArgumentException("Column named " + columnNames.get(i) + " maps to multiple parameters"); } mappers[paramIndex] = ctx.findColumnMapperFor(type).orElseThrow(() -> new IllegalArgumentException("Could not find column mapper for type '" + type + "' of parameter for constructor " + constructor)); columnMap[i] = paramIndex; } return rs -> { final Object[] params = new Object[length]; for (int i = 0; i < length; i++) { params[columnMap[i]] = mappers[i].map(rs, i + 1, ctx); } try { return constructor.newInstance(params); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw new RuntimeException(e); } }; }
Source:
public JSONObject getJSONObject() { TextFile df = getDataFile(); if(df.exists()) { long start = System.nanoTime(); try { JSONObject o = JSONObject.fromObject(df.read()); LOGGER.info(() -> String.format("Loaded and parsed %s in %.01fs", df, (System.nanoTime() - start) / 1_000_000_000.0)); return o; } catch (JSONException | IOException e) { LOGGER.log(Level.SEVERE,"Failed to parse "+df,e); df.delete(); return null; } } else { return null; } }

Target:
public JSONObject getJSONObject() { TextFile df = getDataFile(); if(df.exists()) { long start = System.nanoTime(); try { JSONObject o = JSONObject.fromObject(df.read()); LOGGER.fine(() -> String.format("Loaded and parsed %s in %.01fs", df, (System.nanoTime() - start) / 1_000_000_000.0)); return o; } catch (JSONException | IOException e) { LOGGER.log(Level.SEVERE,"Failed to parse "+df,e); df.delete(); return null; } } else { return null; } }
Source:
private Producer<String, String> takeUnderLock(final boolean canCreate) { final Lock lock = canCreate ? rwLock.writeLock() : rwLock.readLock(); lock.lock(); try { if (null != activeProducer) { useCountMetric.inc(); useCount.get(activeProducer).incrementAndGet(); return activeProducer; } else if (canCreate) { activeProducer = new KafkaProducer<>(kafkaLocationManager.getKafkaProducerProperties()); useCountMetric.inc(); useCount.put(activeProducer, new AtomicInteger(1)); LOG.info("New producer instance created: " + activeProducer); return activeProducer; } else { return null; } } finally { lock.unlock(); } }

Target:
private Producer<String, String> takeUnderLock(final boolean canCreate) { final Lock lock = canCreate ? rwLock.writeLock() : rwLock.readLock(); lock.lock(); try { if (null != activeProducer) { useCountMetric.inc(); useCount.get(activeProducer).incrementAndGet(); return activeProducer; } else if (canCreate) { activeProducer = createProducerInstance(); useCountMetric.inc(); useCount.put(activeProducer, new AtomicInteger(1)); LOG.info("New producer instance created: " + activeProducer); return activeProducer; } else { return null; } } finally { lock.unlock(); } }
Source:
protected void onDestroy() { super.onDestroy(); lifecycleSubject.onNext(LifecycleEvent.DESTROY); }

Target:
protected void onDestroy() { lifecycleSubject.onNext(LifecycleEvent.DESTROY); super.onDestroy(); }
Source:
public Supplier<String> supplier() { return () -> { System.out.println("Invoking supplier"); return "hello"; }; }

Target:
public Supplier<String> supplier() { return () -> "hello"; }
Source:
protected Identity getObject(String distinguishedName, String scope) { LdapContext context = null; try { LdapName object = new LdapName(distinguishedName); context = getServiceContext(); Attributes search; search = context.getAttributes(object); if (!isType(search, scope) && !hasPermission(search)){ return null; } return attributesToIdentity(object); } catch (NamingException e) { getLogger().info("Failed to get object: " + distinguishedName, e.getExplanation()); return null; } finally { if (context != null) { getContextPool().returnObject(context); } } }

Target:
protected Identity getObject(String distinguishedName, String scope) { LdapContext context = null; try { LdapName object = new LdapName(distinguishedName); context = getServiceContext(); Attributes search; search = context.getAttributes(object); if (!isType(search, scope) && !hasPermission(search)){ return null; } return attributesToIdentity(object); } catch (NamingException e) { getLogger().info("Failed to get object: : {}", distinguishedName, e.getExplanation()); return null; } finally { if (context != null) { getContextPool().returnObject(context); } } }
Source:
public String getComponentKey() { return getComponent(); }

Target:
public String getComponentKey() { return componentKey; }
Source:
protected Void visitQuerySpecification(QuerySpecification node, Integer indent) { process(node.getSelect(), indent); if (node.getFrom().isPresent()) { append(indent, "FROM"); builder.append('\n'); append(indent, " "); process(node.getFrom().get(), indent); } builder.append('\n'); if (node.getWhere().isPresent()) { append(indent, "WHERE " + formatExpression(node.getWhere().get(), parameters)) .append('\n'); } if (node.getGroupBy().isPresent()) { append(indent, "GROUP BY " + (node.getGroupBy().get().isDistinct() ? " DISTINCT " : "") + formatGroupBy(node.getGroupBy().get().getGroupingElements())).append('\n'); } if (node.getHaving().isPresent()) { append(indent, "HAVING " + formatExpression(node.getHaving().get(), parameters)) .append('\n'); } if (!node.getWindow().isEmpty()) { append(indent, "WINDOW " + node.getWindow().stream().map(wd -> formatWindowDefinition(wd, parameters)).collect(joining(", "))).append('\n'); } if (node.getOrderBy().isPresent()) { process(node.getOrderBy().get(), indent); } if (node.getLimit().isPresent()) { append(indent, "LIMIT " + node.getLimit().get()) .append('\n'); } return null; }

Target:
protected Void visitQuerySpecification(QuerySpecification node, Integer indent) { process(node.getSelect(), indent); if (node.getFrom().isPresent()) { append(indent, "FROM"); builder.append('\n'); append(indent, " "); process(node.getFrom().get(), indent); } builder.append('\n'); if (node.getWhere().isPresent()) { append(indent, "WHERE " + formatExpression(node.getWhere().get(), parameters)) .append('\n'); } if (node.getGroupBy().isPresent()) { append(indent, "GROUP BY " + (node.getGroupBy().get().isDistinct() ? " DISTINCT " : "") + formatGroupBy(node.getGroupBy().get().getGroupingElements())).append('\n'); } if (node.getHaving().isPresent()) { append(indent, "HAVING " + formatExpression(node.getHaving().get(), parameters)) .append('\n'); } if (!node.getWindow().isEmpty()) { append(indent, "WINDOW " + node.getWindow().stream() .map(windowDefinition -> formatWindowDefinition(windowDefinition, parameters)) .collect(joining(", "))).append('\n'); } if (node.getOrderBy().isPresent()) { process(node.getOrderBy().get(), indent); } if (node.getLimit().isPresent()) { append(indent, "LIMIT " + node.getLimit().get()) .append('\n'); } return null; }
Source:
public LdapAuthHealth checkHealth() { boolean isHealthy = true; String details = null; try { LDAPConnection ldapConnection = connectionPool.getConnection(); if (!ldapConnection.isConnected()) { isHealthy = false; } } catch (LDAPException e) { isHealthy = false; } details = new StringBuilder("LDAPConnection [DN: ").append(ldapConfiguration.getBindDn()).append(", Status: ") .append(isHealthy).append("]").toString(); return new LdapAuthHealth(isHealthy, details); }

Target:
public RolesProviderHealth checkHealth() { boolean isHealthy = true; StringBuilder details = null; String failureReason = null; try { LDAPConnection ldapConnection = connectionPool.getConnection(); if (!ldapConnection.isConnected()) { isHealthy = false; } connectionPool.getHealthCheck().ensureConnectionValidForContinuedUse(ldapConnection); } catch (LDAPException e) { failureReason = e.getExceptionMessage(); isHealthy = false; } details = new StringBuilder("LDAPConnection [DN: ").append(ldapConfiguration.getBindDn()).append(", Status: ") .append(isHealthy); if (failureReason != null) { details.append(ldapConfiguration.getBindDn()).append(", Failure Reason: ").append(failureReason); } details.append("]"); return new RolesProviderHealth(isHealthy, details.toString()); }
Source:
private static String sanitizeUrl(final String value) { String url = value.trim(); url = url.replace("\\", "%5C").replace("|", "%7C"); if (url.matches(".*#.*#.*")) { url = url.substring(0, (url.indexOf("#", url.indexOf("#") + 1))); } url = url.replace(" ", "%20"); if (!urlValidator.isValid(url)) { if (!urlValidator.isValid(url)) { for (String urlSplitter : url.split("%20")) { if (urlValidator.isValid(urlSplitter)) return urlSplitter; } if (!urlValidator.isValid(url)) { if (url.matches(".*:/[^/].*")) url = url.replace(":/", "://"); if (!urlValidator.isValid(url)) { url = "http://" + url; if (!urlValidator.isValid(url)) { url = ""; LOG.info( "No absolute URI could be generated from '" + value + "'"); } } } } } return url; }

Target:
private static String sanitizeUrl(final String value) { String url = value.trim(); url = url.replace("\\", "%5C").replace("|", "%7C"); if (url.matches(".*#.*#.*")) { url = url.substring(0, (url.indexOf("#", url.indexOf("#") + 1))); } url = url.replace(" ", "%20"); if (!urlValidator.isValid(url)) { for (String urlSplitter : url.split("%20")) { if (urlValidator.isValid(urlSplitter)) return urlSplitter; } if (url.matches(".*:/[^/].*")) url = url.replace(":/", "://"); if (!urlValidator.isValid(url)) { url = "http://" + url; if (!urlValidator.isValid(url)) { url = ""; LOG.info("No absolute URI could be generated from '" + value + "'"); } } } return url; }
Source:
public boolean isEmpty() { return (root instanceof LeafBucket) && ((LeafBucket) root).size() == 0; }

Target:
public boolean isEmpty() { if (!(root instanceof LeafBucket)) { return false; } LeafBucket b = (LeafBucket) root; return b.size() == 0 && b.nonNotes == null; }
Source:
disableIncludes() { noExpandIncludes = true; includeThrowsException = false; }

Target:
disableIncludes() { disableIncludes(false); }
Source:
private List<CourseAttributes> extractArchivedCourses(List<CourseDetailsBundle> courseBundles) { ArrayList<CourseAttributes> archivedCourses = new ArrayList<CourseAttributes>(); for (CourseDetailsBundle courseBundle : courseBundles) { CourseAttributes course = courseBundle.course; InstructorAttributes curInstructor = logic.getInstructorForGoogleId(course.id, account.googleId); if(curInstructor.isArchived != null){ course.isArchived = curInstructor.isArchived.booleanValue(); } if (course.isArchived) { archivedCourses.add(course); } } return archivedCourses; }

Target:
private List<CourseAttributes> extractArchivedCourses(List<CourseDetailsBundle> courseBundles) { ArrayList<CourseAttributes> archivedCourses = new ArrayList<CourseAttributes>(); for (CourseDetailsBundle courseBundle : courseBundles) { CourseAttributes course = courseBundle.course; InstructorAttributes curInstructor = logic.getInstructorForGoogleId(course.id, account.googleId); if(curInstructor.isArchived != null){ course.isArchived = curInstructor.isArchived; } if (course.isArchived) { archivedCourses.add(course); } } return archivedCourses; }
Source:
public StickyTaskAssignor(final Map<ID, ClientState> clients, final Set<TaskId> allTaskIds, final Set<TaskId> standbyTaskIds) { this.clients = clients; this.allTaskIds = allTaskIds; this.standbyTaskIds = standbyTaskIds; final int maxPairs = standbyTaskIds.size() * (standbyTaskIds.size() - 1) / 2; taskPairs = new TaskPairs(maxPairs); mapPreviousTaskAssignment(clients); }

Target:
public StickyTaskAssignor(final Map<ID, ClientState> clients, final Set<TaskId> allTaskIds, final Set<TaskId> standbyTaskIds) { this.clients = clients; this.allTaskIds = allTaskIds; this.standbyTaskIds = standbyTaskIds; final int maxPairs = allTaskIds.size() * (allTaskIds.size() - 1) / 2; taskPairs = new TaskPairs(maxPairs); mapPreviousTaskAssignment(clients); }
Source:
public boolean isRecoveryEnabled() { switch (this) { case FULL_XA: return true; default: return false; } }

Target:
public boolean isRecoveryEnabled() { return this == FULL_XA; }
Source:
public List<RuleResult<Patient>> evaluate() { List<RuleResult<Patient>> ruleResults = new ArrayList<>(); ruleResults.addAll(patientsWithMissingTBNumberIdentifiers("304df0d0-afe4-4a61-a917-d684b100a65a", "Unit TB Number")); ruleResults.addAll(patientsWithMissingTBNumberIdentifiers("d1cda288-4853-4450-afbc-76bd4e65ea70", "HSD TB Number")); ruleResults.addAll(patientsWithMissingTBNumberIdentifiers("67e9ec2f-4c72-408b-8122-3706909d77ec", "District TB Number")); ruleResults.addAll(patientsWithSimilarTBNumberIdentifiersDuplicatedForASinglePatient("67e9ec2f-4c72-408b-8122-3706909d77ec", "District TB Number")); ruleResults.addAll(patientsWithSimilarTBNumberIdentifiersDuplicatedForASinglePatient("304df0d0-afe4-4a61-a917-d684b100a65a", "Unit TB Number")); ruleResults.addAll(patientsWithSimilarTBNumberIdentifiersDuplicatedForASinglePatient("d1cda288-4853-4450-afbc-76bd4e65ea70", "HSD TB Number")); ruleResults.addAll(patientsWithSimilarTBIdentifiersDuplicatedAcrossMultiplePatients("67e9ec2f-4c72-408b-8122-3706909d77ec", "District TB Number")); ruleResults.addAll(patientsWithSimilarTBIdentifiersDuplicatedAcrossMultiplePatients("304df0d0-afe4-4a61-a917-d684b100a65a", "Unit TB Number")); ruleResults.addAll(patientsWithSimilarTBIdentifiersDuplicatedAcrossMultiplePatients("d1cda288-4853-4450-afbc-76bd4e65ea70", "HSD TB Number")); ruleResults.addAll(patientsWithNoFinalOutcomeNineMonthsAfterStartOfTreatment(DateTime.now())); return ruleResults; }

Target:
public List<RuleResult<Patient>> evaluate() { List<RuleResult<Patient>> ruleResults = new ArrayList<>(); ruleResults.addAll(patientsWithMissingTBNumbers(AijarConstants.UNIT_TB_NUMBER, "Unit TB Number")); ruleResults.addAll(patientsWithMissingTBNumbers(AijarConstants.HSD_TB_NUMBER, "HSD TB Number")); ruleResults.addAll(patientsWithMissingTBNumbers(AijarConstants.DISTRICT_TB_NUMBER, "District TB Number")); ruleResults.addAll(singlePatientWithDuplicateTBNumberAcrossMultipleTreatmentPrograms(AijarConstants.DISTRICT_TB_NUMBER, "District TB Number")); ruleResults.addAll(singlePatientWithDuplicateTBNumberAcrossMultipleTreatmentPrograms(AijarConstants.UNIT_TB_NUMBER, "Unit TB Number")); ruleResults.addAll(singlePatientWithDuplicateTBNumberAcrossMultipleTreatmentPrograms(AijarConstants.HSD_TB_NUMBER, "HSD TB Number")); ruleResults.addAll(multiplePatientsWithTheSameTBIdentifiers(AijarConstants.DISTRICT_TB_NUMBER, "District TB Number")); ruleResults.addAll(multiplePatientsWithTheSameTBIdentifiers(AijarConstants.UNIT_TB_NUMBER, "Unit TB Number")); ruleResults.addAll(multiplePatientsWithTheSameTBIdentifiers(AijarConstants.HSD_TB_NUMBER, "HSD TB Number")); ruleResults.addAll(patientsWithNoFinalOutcomeNineMonthsAfterStartOfTreatment(DateTime.now())); return ruleResults; }
Source:
public int hashCode() { return Objects.hashCode(source, destination, mode, rw); }

Target:
public int hashCode() { return java.util.Objects.hash(source, destination, mode, rw); }
Source:
public CoreMessage putBytesProperty(final String key, final byte[] value) { messageChanged(); getOrCreateProperties().putBytesProperty(key(key), value); return this; }

Target:
public CoreMessage putBytesProperty(final String key, final byte[] value) { return putBytesProperty(key(key), value); }
Source:
public void onWebSocketConnect(Session session) { super.onWebSocketConnect(session); Map<String, Collection<?>> data = new HashMap<String, Collection<?>>(); data.put(KEY_POSITIONS, Context.getConnectionManager().getInitialState(userId)); sendData(data); Context.getConnectionManager().addListener(userId, this); }

Target:
public void onWebSocketConnect(Session session) { super.onWebSocketConnect(session); Map<String, Collection<?>> data = new HashMap<>(); data.put(KEY_POSITIONS, Context.getConnectionManager().getInitialState(userId)); sendData(data); Context.getConnectionManager().addListener(userId, this); }
Source:
public boolean doPostSetUserClaimValues(String userName, Map<String, String> claims, String profileName, UserStoreManager userStoreManager) throws UserStoreException { removeAccessTokenFromCache(userName, userStoreManager); if (!isEnable()) { return true; } return revokeTokensOfLockedUser(userName, userStoreManager); }

Target:
public boolean doPostSetUserClaimValues(String userName, Map<String, String> claims, String profileName, UserStoreManager userStoreManager) throws UserStoreException { if (!isEnable()) { return true; } return revokeTokensOfLockedUser(userName, userStoreManager); }
Source:
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL(); String retryParam = ""; String username = getLoggedInUser(context); String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier()); try { if (context.isRetrying()) { retryParam = "&authFailure=true&authFailureMsg=login.fail.message"; } boolean isTOTPEnabled = TOTPAuthenticatorServiceComponent.getTotpManager().isTOTPEnabledForLocalUser (username); if (isTOTPEnabled) { response.sendRedirect(response.encodeRedirectURL(loginPage + ("?sessionDataKey=" + request .getParameter("sessionDataKey"))) + "&authenticators=" + getName() + "&type=totp" + retryParam + "&username=" + username); } else { response.sendRedirect(response.encodeRedirectURL(loginPage + ("?sessionDataKey=" + request .getParameter("sessionDataKey"))) + "&authenticators=" + getName() + "&type=totp_error" + retryParam + "&username=" + username); } } catch (IOException e) { throw new AuthenticationFailedException("Error when redirecting the totp login response, " + "user : " + username, e); } catch (TOTPException e) { throw new AuthenticationFailedException("Error when checking totp enabled for the user : " + username, e); } }

Target:
protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL(); String retryParam = ""; String username = getLoggedInUser(context); String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier()); try { if (context.isRetrying()) { retryParam = "&authFailure=true&authFailureMsg=login.fail.message"; } boolean isTOTPEnabled = TOTPAuthenticatorServiceComponent.getTotpManager().isTOTPEnabledForLocalUser (username); if (isTOTPEnabled) { response.sendRedirect(response.encodeRedirectURL(loginPage + ("?sessionDataKey=" + CharacterEncoder .getSafeText(request.getParameter("sessionDataKey")))) + "&authenticators=" + getName() + "&type=totp" + retryParam + "&username=" + username); } else { response.sendRedirect(response.encodeRedirectURL(loginPage + ("?sessionDataKey=" + CharacterEncoder .getSafeText(request.getParameter("sessionDataKey")))) + "&authenticators=" + getName() + "&type=totp_error" + retryParam + "&username=" + username); } } catch (IOException e) { throw new AuthenticationFailedException("Error when redirecting the totp login response, " + "user : " + username, e); } catch (TOTPException e) { throw new AuthenticationFailedException("Error when checking totp enabled for the user : " + username, e); } }
Source:
public void testResourceGroupMatch() throws IOException { Path configurationFile = Files.createTempFile("file-session-test", "properties"); ImmutableMap<String, String> properties = ImmutableMap.of("PROPERTY1", "VALUE1", "PROPERTY2", "VALUE2"); SessionMatchSpec spec = new SessionMatchSpec( Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(Pattern.compile("global.pipeline.user_.*")), properties); Files.write(configurationFile, CODEC.toJsonBytes(ImmutableList.of(spec))); SessionPropertyConfigurationManager manager = new FileSessionPropertyManager(new FileSessionPropertyManagerConfig().setConfigFile(configurationFile.toString())); assertEquals(manager.getSystemSessionProperties(CONTEXT), properties); Files.delete(configurationFile); }

Target:
public void testResourceGroupMatch() throws IOException { Map<String, String> properties = ImmutableMap.of("PROPERTY1", "VALUE1", "PROPERTY2", "VALUE2"); SessionMatchSpec spec = new SessionMatchSpec( Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(Pattern.compile("global.pipeline.user_.*")), properties); assertProperties(properties, spec); }
Source:
public void notSupported() throws Exception { context.checking(new Expectations() {{ oneOf(catalog).isSupported(255555); will(returnValue(false)); oneOf(constraintValidator).getDefaultConstraintMessageTemplate(); oneOf(constraintValidator).buildConstraintViolationWithTemplate(with(any(String.class))); }}); boolean isValid = validator.isValid(Sets.newHashSet(255555), constraintValidator); assertFalse(isValid); }

Target:
public void notSupported() throws Exception { context.checking(new Expectations() {{ oneOf(catalog).isSupported(255555); will(returnValue(false)); oneOf(constraintValidator).getDefaultConstraintMessageTemplate(); will(returnValue("Found capability id that is not supported")); oneOf(constraintValidator).buildConstraintViolationWithTemplate("Found capability id that is not supported"); }}); List<Integer> ids = Lists.newArrayList(255555); boolean isValid = validator.isValid(ids, constraintValidator); assertFalse(isValid); }
Source:
public void close() { if (deepCopy) throw new RuntimeException("Calling close on a deep copy is not supported"); closeDeepCopies(); closeLocalityGroupReaders(); if (sampleReaders != null) { for (LocalityGroupReader lgr : sampleReaders) { lgr.close(); } } try { reader.close(); } catch (IOException e) { throw new RuntimeException(e); } finally { } }

Target:
public void close() { if (deepCopy) throw new RuntimeException("Calling close on a deep copy is not supported"); closeDeepCopies(); closeLocalityGroupReaders(); if (sampleReaders != null) { for (LocalityGroupReader lgr : sampleReaders) { lgr.close(); } } try { reader.close(); } catch (IOException e) { throw new UncheckedIOException(e); } finally { } }
Source:
public Action getActionInformation() { return action; }

Target:
public Action getActionInformation() { return new Action() { @Override public Optional<JabRefIcon> getIcon() { return Optional.of(application.getIcon()); } @Override public Optional<KeyBinding> getKeyBinding() { return Optional.of(KeyBinding.PUSH_TO_APPLICATION); } @Override public String getText() { return Localization.lang("Push entries to external application (%0)", application.getApplicationName()); } @Override public String getDescription() { return ""; } }; }
Source:
public void testInspectBigQueryTable() throws InterruptedException, ExecutionException, IOException { InspectBigQueryTable.inspectBigQueryTable( PROJECT_ID, DATASET_ID, TABLE_ID, TOPIC_ID, SUBSCRIPTION_ID); String output = bout.toString(); assertThat(output, containsString("Job created: ")); String jobId = output.split("Job created: ")[1].split("\n")[0]; CancelDlpJobRequest request = CancelDlpJobRequest.newBuilder().setName(jobId).build(); try (DlpServiceClient client = DlpServiceClient.create()) { client.cancelDlpJob(request); } }

Target:
public void testInspectBigQueryTable() throws InterruptedException, ExecutionException, IOException { InspectBigQueryTable.inspectBigQueryTable( PROJECT_ID, DATASET_ID, TABLE_ID, TOPIC_ID, SUBSCRIPTION_ID); TimeUnit.SECONDS.sleep(3); String output = bout.toString(); assertThat(output, containsString("Job created: ")); String jobId = output.split("Job created: ")[1].split("\n")[0]; CancelDlpJobRequest request = CancelDlpJobRequest.newBuilder().setName(jobId).build(); try (DlpServiceClient client = DlpServiceClient.create()) { client.cancelDlpJob(request); } }
Source:
public OAuth2TokenAttributes(Map<String, Object> attributes) { Assert.notEmpty(attributes, "attributes cannot be empty"); this.attributes = attributes; }

Target:
public OAuth2TokenAttributes(Map<String, Object> attributes) { this.attributes = Collections.unmodifiableMap(attributes); }