auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean accepts(final Resource resource) throws RepositoryException { final ValueMap props = resource.getValueMap(); if (!DamConstants.NT_DAM_ASSETCONTENT.equals(props.get(JcrConstants.JCR_PRIMARYTYPE))) { return false; } if (!props.get(RemoteAssets.IS_REMOTE_ASSET, false)) { return false; } final Calendar lastFailure = props.get(RemoteAssets.REMOTE_SYNC_FAILED, (Calendar) null); if (lastFailure != null && System.currentTimeMillis() < (lastFailure.getTimeInMillis() + (config.getRetryDelay() * 60000))) { return false; } final boolean isAllowedUser = isAllowedUser(resource); if (!isAllowedUser) { return false; } final String path = resource.getPath(); for (final String syncPath : config.getDamSyncPaths()) { if (path.startsWith(syncPath)) { return true; } } return false; }

Target:
protected boolean accepts(final Resource resource) throws RepositoryException { final ValueMap props = resource.getValueMap(); if (!DamConstants.NT_DAM_ASSETCONTENT.equals(props.get(JcrConstants.JCR_PRIMARYTYPE))) { return false; } if (!props.get(RemoteAssets.IS_REMOTE_ASSET, false)) { return false; } final Calendar lastFailure = props.get(RemoteAssets.REMOTE_SYNC_FAILED, (Calendar) null); if (lastFailure != null && System.currentTimeMillis() < (lastFailure.getTimeInMillis() + (config.getRetryDelay() * 60000))) { return false; } final String path = resource.getPath(); for (final String syncPath : config.getDamSyncPaths()) { if (path.startsWith(syncPath)) { return isAllowedUser(resource); } } return false; }
Source:
public static void deletePeopleForLocalBlogIdExceptForFirstPage(int localTableBlogId) { int size = getPeopleCountForLocalBlogId(localTableBlogId); int fetchLimit = PeopleUtils.FETCH_USERS_LIMIT; if (size > fetchLimit) { int deleteCount = size - fetchLimit; String[] args = new String[]{Integer.toString(deleteCount), Integer.toString(localTableBlogId)}; getWritableDb().delete(PEOPLE_TABLE, "person_id " + "IN (SELECT person_id FROM people ORDER BY display_name DESC LIMIT ?) AND local_blog_id=?", args); } }

Target:
public static void deletePeopleForLocalBlogIdExceptForFirstPage(int localTableBlogId) { int size = getPeopleCountForLocalBlogId(localTableBlogId); int fetchLimit = PeopleUtils.FETCH_USERS_LIMIT; if (size > fetchLimit) { int deleteCount = size - fetchLimit; String[] args = new String[] { Integer.toString(localTableBlogId), Integer.toString(deleteCount) }; getWritableDb().delete(PEOPLE_TABLE, "local_blog_id=?1 AND person_id " + "IN (SELECT person_id FROM " + PEOPLE_TABLE + " WHERE local_blog_id=?1 " + "ORDER BY display_name DESC LIMIT ?2)", args); } }
Source:
private static String asText(JsonNode node) { if (node.isNull()) { return null; } if (node.isArray()) { String[] arrayTexts = new String[node.size()]; for (int i = 0; i < node.size(); i++) { arrayTexts[i] = asText(node.get(i)); } return Arrays.toString(arrayTexts); } checkState(node.isValueNode()); return node.asText(); }

Target:
private static String asText(JsonNode node) { checkState(node.isValueNode()); return node.isNull() ? null : node.asText(); }
Source:
private static boolean validateTextClause(Object clause, Boolean[] textClauseLimitReached) { Map<String, Object> textClause; if (clause instanceof Map) { textClause = (Map<String, Object>) clause; if (textClause.size() == 1) { String operator = (String) textClause.keySet().toArray()[0]; if (operator.equals(SEARCH)) { Object clauseOperand = textClause.get(operator); if (textClauseLimitReached[0]) { String msg = "Multiple text search clauses not allowed in a query. " + "Rewrite query to contain at most one text search clause."; logger.log(Level.SEVERE, msg); } else { textClauseLimitReached[0] = true; return validatePredicateValue(clauseOperand, operator); } } else { String msg = String.format("Invalid operator %s in text search", operator); logger.log(Level.SEVERE, msg); } } } else { String msg = String.format("Text search expects a Map, found %s instead.", clause); logger.log(Level.SEVERE, msg); } return false; }

Target:
private static boolean validateTextClause(Object clause, Boolean[] textClauseLimitReached) { Map<String, Object> textClause; if (!(clause instanceof Map)) { String msg = String.format("Text search expects a Map, found %s instead.", clause); logger.log(Level.SEVERE, msg); return false; } textClause = (Map<String, Object>) clause; if (textClause.size() != 1) { String msg = String.format("Unexpected content %s in text search.", textClause); logger.log(Level.SEVERE, msg); return false; } String operator = (String) textClause.keySet().toArray()[0]; if (!operator.equals(SEARCH)) { String msg = String.format("Invalid operator %s in text search", operator); logger.log(Level.SEVERE, msg); return false; } if (textClauseLimitReached[0]) { logger.log(Level.SEVERE, "Multiple text search clauses not allowed in a query. " + "Rewrite query to contain at most one text search clause."); return false; } textClauseLimitReached[0] = true; return validatePredicateValue(textClause.get(operator), operator); }
Source:
public void applyAttributeMappings(Metacard metacard) { this.attributeMappings = new TreeMap<>(); for (String attrKey : attributeList) { String readableKey = getHumanReadableAttribute(attrKey); Attribute attr = metacard.getAttribute(attrKey); if (attr == null) { this.attributeMappings.put(readableKey, new HtmlEmptyValueModel()); } else if (attrKey.equals("thumbnail")) { byte[] imageData = (byte[]) attr.getValue(); this.attributeMappings.put(readableKey, new HtmlMediaModel(imageData)); } else { this.attributeMappings.put(readableKey, new HtmlBasicValueModel(attr.getValue())); } } }

Target:
public void applyAttributeMappings(Metacard metacard) { this.attributeMappings = new TreeMap<>(); for (String attrKey : attributes) { String readableKey = getHumanReadableAttribute(attrKey); Attribute attr = metacard.getAttribute(attrKey); HtmlValueModel model; if (attr == null) { model = new HtmlEmptyValueModel(); this.attributeMappings.put(readableKey, model); } else if (attrKey.equals(Core.THUMBNAIL)) { byte[] imageData = (byte[]) attr.getValue(); model = new HtmlMediaModel(imageData); } else { model = new HtmlBasicValueModel(attr.getValue()); } this.attributeMappings.put(readableKey, model); } }
Source:
public Map<String, String> createRecordsOnServer(int count, String objectType) throws Exception { Map<String, String> idToValues = new HashMap<String, String>(); for (int i = 0; i < count; i++) { String fieldValue = ""; Map<String, Object> fields = new HashMap<String, Object>(); switch (objectType) { case Constants.ACCOUNT: fieldValue = createRecordName(objectType); fields.put(Constants.NAME, fieldValue); break; case Constants.OPPORTUNITY: fieldValue = createRecordName(objectType); fields.put(Constants.NAME, fieldValue); fields.put("StageName", "Prospecting"); DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); fields.put("CloseDate", formatter.format(new Date())); break; default: break; } RestRequest request = RestRequest.getRequestForCreate(ApiVersionStrings.getVersionNumber(targetContext), objectType, fields); RestResponse response = restClient.sendSync(request); String id = response.asJSONObject().getString(LID); idToValues.put(id, fieldValue); } return idToValues; }

Target:
protected Map<String, String> createRecordsOnServer(int count, String objectType) throws Exception { Map<String, String> idToValues = new HashMap<String, String>(); for (int i = 0; i < count; i++) { String fieldValue = createRecordName(objectType); Map<String, Object> fields = new HashMap<String, Object>(); switch (objectType) { case Constants.ACCOUNT: fields.put(Constants.NAME, fieldValue); break; case Constants.OPPORTUNITY: fields.put(Constants.NAME, fieldValue); fields.put("StageName", "Prospecting"); DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); fields.put("CloseDate", formatter.format(new Date())); break; default: break; } RestRequest request = RestRequest.getRequestForCreate(ApiVersionStrings.getVersionNumber(targetContext), objectType, fields); RestResponse response = restClient.sendSync(request); assertNotNull("Response should not be null", response); assertTrue("Response status should be success", response.isSuccess()); String id = response.asJSONObject().getString(LID); idToValues.put(id, fieldValue); } return idToValues; }
Source:
public Set<ServerHolder> getAllServers() { final Set<ServerHolder> servers = new HashSet<>(); for (MinMaxPriorityQueue<ServerHolder> queue : cluster.values()) { servers.addAll(queue); } return servers; }

Target:
public List<ServerHolder> getAllServers() { return cluster.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); }
Source:
private void log(final String message) { System.out.println(message); }

Target:
private void log(final String message) { }
Source:
public Key getTopKey() { if (seenSeek == false) throw new IllegalStateException("never been seeked"); return source.getTopKey(); }

Target:
public Key getTopKey() { if (seenSeek == false) throw new IllegalStateException("never been seeked"); return getSource().getTopKey(); }
Source:
public static void commit(ResourceResolver resourceResolver) { if (resourceResolver == null || !resourceResolver.isLive()) { LOGGER.error("Resource resolver is null or not live while committing resourceResolver"); return; } Session session = resourceResolver.adaptTo(Session.class); if (session == null || !session.isLive()) { LOGGER.error("Resource resolver is null or not live while committing resourceResolver"); return; } try { resourceResolver.refresh(); session.refresh(true); if (resourceResolver.hasChanges()) { resourceResolver.commit(); } if (session.hasPendingChanges()) { session.save(); } } catch (PersistenceException | RepositoryException e) { LOGGER.error("Error occurred while committing resource resolver", e); } }

Target:
public static void commit(ResourceResolver resourceResolver) { if (resourceResolver == null || !resourceResolver.isLive()) { LOGGER.error("Resource resolver is null or not live while committing resourceResolver"); return; } try { resourceResolver.refresh(); if (resourceResolver.hasChanges()) { resourceResolver.commit(); } } catch (PersistenceException e) { LOGGER.error("Error occurred while committing resource resolver", e); } }
Source:
public void open() throws InterpreterException { try { if (ipythonClient != null) { return; } pythonExecutable = getProperty("zeppelin.python", "python"); LOGGER.info("Python Exec: " + pythonExecutable); String checkPrerequisiteResult = checkIPythonPrerequisite(pythonExecutable); if (!StringUtils.isEmpty(checkPrerequisiteResult)) { throw new InterpreterException("IPython prerequisite is not meet: " + checkPrerequisiteResult); } ipythonLaunchTimeout = Long.parseLong( getProperty("zeppelin.ipython.launch.timeout", "30000")); this.zeppelinContext = new PythonZeppelinContext( getInterpreterGroup().getInterpreterHookRegistry(), Integer.parseInt(getProperty("zeppelin.python.maxResult", "1000"))); int ipythonPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); int jvmGatewayPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); LOGGER.info("Launching IPython Kernel at port: " + ipythonPort); LOGGER.info("Launching JVM Gateway at port: " + jvmGatewayPort); int framesize = Integer.parseInt(getProperty("zeppelin.ipython.grpc.framesize", 4 * 1024 * 1024 + "")); ipythonClient = new IPythonClient(ManagedChannelBuilder.forAddress("127.0.0.1", ipythonPort) .usePlaintext(true).maxInboundMessageSize(framesize)); launchIPythonKernel(ipythonPort); setupJVMGateway(jvmGatewayPort); } catch (Exception e) { throw new RuntimeException("Fail to open IPythonInterpreter", e); } }

Target:
public void open() throws InterpreterException { try { if (ipythonClient != null) { return; } pythonExecutable = getProperty("zeppelin.python", "python"); LOGGER.info("Python Exec: " + pythonExecutable); String checkPrerequisiteResult = checkIPythonPrerequisite(pythonExecutable); if (!StringUtils.isEmpty(checkPrerequisiteResult)) { throw new InterpreterException("IPython prerequisite is not meet: " + checkPrerequisiteResult); } ipythonLaunchTimeout = Long.parseLong( getProperty("zeppelin.ipython.launch.timeout", "30000")); this.zeppelinContext = new PythonZeppelinContext( getInterpreterGroup().getInterpreterHookRegistry(), Integer.parseInt(getProperty("zeppelin.python.maxResult", "1000"))); int ipythonPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); int jvmGatewayPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces(); LOGGER.info("Launching IPython Kernel at port: " + ipythonPort); LOGGER.info("Launching JVM Gateway at port: " + jvmGatewayPort); int framesize = Integer.parseInt(getProperty("zeppelin.ipython.grpc.framesize", 32 * 1024 * 1024 + "")); ipythonClient = new IPythonClient(ManagedChannelBuilder.forAddress("127.0.0.1", ipythonPort) .usePlaintext(true).maxInboundMessageSize(framesize)); launchIPythonKernel(ipythonPort); setupJVMGateway(jvmGatewayPort); } catch (Exception e) { throw new RuntimeException("Fail to open IPythonInterpreter", e); } }
Source:
public static GeometryProperty<Geometry> calculateBuffer(Object geometryHolder, double bufferWidth, @Nullable TransformationLog log) { InstanceTraverser traverser = new DepthFirstInstanceTraverser(true); GeometryFinder geoFind = new GeometryFinder(null); traverser.traverse(geometryHolder, geoFind); List<GeometryProperty<?>> geometries = geoFind.getGeometries(); GeometryProperty<?> old_geometry = null; if (!geometries.isEmpty()) { old_geometry = geometries.get(0); if (geometries.size() > 1) { if (log != null) { log.warn(log .createMessage( "Multiple geometries found, but network expansion is only done on the first.", null)); } } } GeometryProperty<Geometry> result = null; if (old_geometry != null) { Geometry new_geometry = null; new_geometry = BufferOp.bufferOp(old_geometry.getGeometry(), bufferWidth); result = new DefaultGeometryProperty<Geometry>(old_geometry.getCRSDefinition(), new_geometry); } return result; }

Target:
public static GeometryProperty<Geometry> calculateBuffer(Object geometryHolder, double bufferWidth, @Nullable TransformationLog log) { InstanceTraverser traverser = new DepthFirstInstanceTraverser(true); GeometryFinder geoFind = new GeometryFinder(null); traverser.traverse(geometryHolder, geoFind); List<GeometryProperty<?>> geometries = geoFind.getGeometries(); GeometryProperty<?> old_geometry = null; if (!geometries.isEmpty()) { old_geometry = geometries.get(0); if (geometries.size() > 1) { if (log != null) { log.warn(log .createMessage( "Multiple geometries found, but network expansion is only done on the first.", null)); } } } GeometryProperty<Geometry> result = null; if (old_geometry != null) { Geometry new_geometry = null; BufferParameters bufferParameters = new BufferParameters(); bufferParameters.setEndCapStyle(CAP_STYLE); new_geometry = BufferOp.bufferOp(old_geometry.getGeometry(), bufferWidth, bufferParameters); result = new DefaultGeometryProperty<Geometry>(old_geometry.getCRSDefinition(), new_geometry); } return result; }
Source:
public ConfigImpl(IAggregator aggregator, boolean forTest) throws URISyntaxException, FileNotFoundException { this.aggregator = aggregator; rawConfig = null; lastModified = 0; configUri = loadConfigUri(); }

Target:
protected ConfigImpl(IAggregator aggregator, boolean forTest) throws URISyntaxException, FileNotFoundException { this.aggregator = aggregator; rawConfig = null; lastModified = 0; configUri = loadConfigUri(); }
Source:
public void run(final Map<String, List<DataInfo>> dataInfos, final Map<String, Map<String, Double>> computeMetrics, final String controllerId, final Map<String, Double> controllerMetrics) { LOG.log(Level.INFO, "Beginning migration"); final Plan plan = optimizer.optimize( getNodeParameters(dataInfos, computeMetrics), getAvailableEvaluators(computeMetrics.size())); if (planExecutionResult.isDone()) { try { LOG.log(Level.INFO, "Previous result: " + planExecutionResult.get()); } catch (final InterruptedException e) { throw new RuntimeException(e); } catch (final ExecutionException e) { throw new RuntimeException(e); } planExecutionResult = planExecutor.execute(plan); try { LOG.log(Level.INFO, "Blocking until the migration is done."); final PlanResult result = planExecutionResult.get(); LOG.log(Level.INFO, "Current result: " + result); } catch (final InterruptedException e) { throw new RuntimeException(e); } catch (final ExecutionException e) { throw new RuntimeException(e); } } }

Target:
public synchronized void run(final Map<String, List<DataInfo>> dataInfos, final Map<String, Map<String, Double>> computeMetrics, final String controllerId, final Map<String, Double> controllerMetrics) { if (isPlanExecuting()) { LOG.log(Level.INFO, "Skipping Optimization, as the previous plan is still executing."); return; } LOG.log(Level.INFO, "Optimization start."); logPreviousResult(); final Plan plan = optimizer.optimize( getEvaluatorParameters(dataInfos, computeMetrics, controllerId, controllerMetrics), getAvailableEvaluators(computeMetrics.size())); planExecutionResult = planExecutor.execute(plan); blockUntilPlanIsExecuted(); LOG.log(Level.INFO, "Optimization complete."); }
Source:
public boolean isKeyStorePassword(char[] password) throws IOException{ if (password==null) return false; assertActivatedKeyStore(); KeyStore testStore=null; try { testStore = KeyStore.getInstance(KEYSTORETYPE); } catch (KeyStoreException e1) { throw new RuntimeException(e1); } InputStream fis = getResource().in(); try { testStore.load(fis, password); } catch (IOException e2) { return false; } catch (Exception e) { throw new RuntimeException(e); } fis.close(); return true; }

Target:
public boolean isKeyStorePassword(char[] password) throws IOException{ if (password==null) return false; assertActivatedKeyStore(); KeyStore testStore=null; try { testStore = KeyStore.getInstance(KEYSTORETYPE); } catch (KeyStoreException e1) { throw new RuntimeException(e1); } try (InputStream fis = getResource().in()) { testStore.load(fis, password); } catch (IOException e2) { return false; } catch (Exception e) { throw new RuntimeException(e); } return true; }
Source:
public Tuple exec(Tuple input) throws IOException { if (sites==null) { initSites(); } String hostname = (String)input.get(5); DefaultDataBag timeline = (DefaultDataBag)input.get(7); Iterator<Tuple> myit = timeline.iterator(); Tuple item; String prevState = "UNKNOWN"; for (int i=0;i<timeline.size();i++) { item = myit.next(); item.append(prevState); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date parsedDate = null; try { parsedDate = dateFormat.parse((String) item.get(0)); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(parsedDate); int the_hours = cal.get(Calendar.HOUR); int am = cal.get(Calendar.AM_PM); if (am>0) the_hours = the_hours + 12; int date_int = (cal.get(Calendar.YEAR) * 10000 ) + ((cal.get(Calendar.MONTH) + 1)*100) + (cal.get(Calendar.DAY_OF_MONTH)); int time_int = (the_hours * 10000) + ((cal.get(Calendar.MINUTE)*100)) + (cal.get(Calendar.SECOND)); item.append(date_int); item.append(time_int); prevState = (String) item.get(1); } input.append((String)sites.get(hostname)); return input; }

Target:
public Tuple exec(Tuple input) throws IOException { if (sites==null) { initSites(); } String hostname = (String)input.get(5); DefaultDataBag timeline = (DefaultDataBag)input.get(7); Iterator<Tuple> myit = timeline.iterator(); Tuple item; String prevState = "UNKNOWN"; for (int i=0;i<timeline.size();i++) { item = myit.next(); item.append(prevState); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date parsedDate = null; try { parsedDate = dateFormat.parse((String) item.get(0)); } catch (ParseException e) { e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(parsedDate); int date_int = (cal.get(Calendar.YEAR) * 10000 ) + ((cal.get(Calendar.MONTH) + 1)*100) + (cal.get(Calendar.DAY_OF_MONTH)); int time_int = (cal.get(Calendar.HOUR_OF_DAY) * 10000) + ((cal.get(Calendar.MINUTE)*100)) + (cal.get(Calendar.SECOND)); item.append(date_int); item.append(time_int); prevState = (String) item.get(1); } input.append((String)sites.get(hostname)); return input; }
Source:
public void setDataConsistentOnStandby(boolean isConsistent) { ReplicationStatusKey key = ReplicationStatusKey.newBuilder().setClusterId(localClusterId).build(); ReplicationStatusVal val = ReplicationStatusVal.newBuilder() .setStatus(LogReplicationMetadata.SyncStatus.STOPPED) .setDataConsistent(isConsistent) .build(); TxBuilder txBuilder = corfuStore.tx(NAMESPACE); txBuilder.update(REPLICATION_STATUS_TABLE, key, val, null); txBuilder.commit(); log.trace("setDataConsistentOnStandby: localClusterId: {}, isConsistent: {}", localClusterId, isConsistent); }

Target:
public void setDataConsistentOnStandby(boolean isConsistent) { ReplicationStatusKey key = ReplicationStatusKey.newBuilder().setClusterId(localClusterId).build(); ReplicationStatusVal val = ReplicationStatusVal.newBuilder() .setDataConsistent(isConsistent) .build(); TxBuilder txBuilder = corfuStore.tx(NAMESPACE); txBuilder.update(REPLICATION_STATUS_TABLE, key, val, null); txBuilder.commit(); log.trace("setDataConsistentOnStandby: localClusterId: {}, isConsistent: {}", localClusterId, isConsistent); }
Source:
Supplier<CassandraKeyValueServiceRuntimeConfig> preprocessKvsRuntimeConfig( Supplier<Optional<KeyValueServiceRuntimeConfig>> runtimeConfig) { return () -> { Optional<KeyValueServiceRuntimeConfig> configOptional = runtimeConfig.get(); return configOptional.map(config -> { Preconditions.checkArgument(config instanceof CassandraKeyValueServiceRuntimeConfig, "CassandraAtlasDbFactory expects an instance of type %s, found %s", CassandraKeyValueServiceRuntimeConfig.class, config.getClass()); return (CassandraKeyValueServiceRuntimeConfig) config; }).orElse(CassandraKeyValueServiceRuntimeConfig.getDefault()); }; }

Target:
Supplier<CassandraKeyValueServiceRuntimeConfig> preprocessKvsRuntimeConfig( Supplier<Optional<KeyValueServiceRuntimeConfig>> runtimeConfig) { return () -> { Optional<KeyValueServiceRuntimeConfig> configOptional = runtimeConfig.get(); return configOptional.map(config -> { if (!(config instanceof CassandraKeyValueServiceRuntimeConfig)) { log.error("Invalid KeyValueServiceRuntimeConfig. Expected a KeyValueServiceRuntimeConfig of type" + " CassandraKeyValueServiceRuntimeConfig, found %s." + " Using latest valid CassandraKeyValueServiceRuntimeConfig.", config.getClass()); return latestValidRuntimeConfig; } latestValidRuntimeConfig = (CassandraKeyValueServiceRuntimeConfig) config; return latestValidRuntimeConfig; }).orElse(CassandraKeyValueServiceRuntimeConfig.getDefault()); }; }
Source:
public static void prepareMongoDatasources() { if (System.getProperty("mongo.backend") == null) { System.setProperty("mongo.backend", "mongo"); } if (System.getProperty("mongo.database") == null) { System.setProperty("mongo.database", "testdb"); } if (System.getProperty("mongo.host") == null) { System.setProperty("mongo.host", "localhost"); } if (System.getProperty("mongo.port") == null) { System.setProperty("mongo.port", String.valueOf(mongoServer.getPort())); } }

Target:
public static void prepareMongoDatasources() { if (System.getProperty("mongo.datasource") == null) { System.setProperty("mongo.datasource", "mongo"); } if (System.getProperty("mongo.database") == null) { System.setProperty("mongo.database", "testdb"); } if (System.getProperty("mongo.host") == null) { System.setProperty("mongo.host", "localhost"); } if (System.getProperty("mongo.port") == null) { System.setProperty("mongo.port", String.valueOf(mongoServer.getPort())); } }
Source:
public TaskRepository getObject(){ TaskRepository taskRepository = null; logger.debug("Creating SimpleTaskRepository that will use a JdbcTaskExecutionDao"); taskRepository = new SimpleTaskRepository(createJdbcTaskExecutionDao()); return taskRepository; }

Target:
public TaskRepository getObject(){ TaskRepository taskRepository = null; logger.debug(String.format("Creating SimpleTaskRepository that will use a %s", JdbcTaskExecutionDao.class.getName())); taskRepository = new SimpleTaskRepository(createJdbcTaskExecutionDao()); return taskRepository; }
Source:
public CreateAllSnapshotsFromVmParameters() { needsLocking = true; snapshotType = SnapshotType.REGULAR; saveMemory = true; diskIdsToIgnoreInChecks = Collections.emptySet(); }

Target:
public CreateAllSnapshotsFromVmParameters() { needsLocking = true; saveMemory = true; diskIdsToIgnoreInChecks = Collections.emptySet(); }
Source:
public BlobInputStream openInputStream(BlobInputStreamOptions options) { options = options == null ? new BlobInputStreamOptions() : options; BlobProperties properties = getProperties(); BlobRange range = options.getRange() == null ? new BlobRange(0) : options.getRange(); int chunkSize = options.getBlockSize() == null ? 4 * Constants.MB : options.getBlockSize(); BlobRequestConditions requestConditions = options.getRequestConditions() == null ? new BlobRequestConditions() : options.getRequestConditions(); requestConditions.setIfMatch(properties.getETag()); return new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize, requestConditions, properties); }

Target:
public BlobInputStream openInputStream(BlobInputStreamOptions options) { options = options == null ? new BlobInputStreamOptions() : options; BlobProperties properties = getProperties(); BlobRange range = options.getRange() == null ? new BlobRange(0) : options.getRange(); int chunkSize = options.getBlockSize() == null ? 4 * Constants.MB : options.getBlockSize(); BlobRequestConditions requestConditions = options.getRequestConditions() == null ? new BlobRequestConditions() : options.getRequestConditions(); if (requestConditions.getIfMatch() == null) { requestConditions.setIfMatch(properties.getETag()); } return new BlobInputStream(client, range.getOffset(), range.getCount(), chunkSize, requestConditions, properties); }
Source:
public static DbEngineDialect loadDbEngineDialect() { final String ENGINE_DB_ENGINE_PROPERTIES = "engine-db-engine.properties"; final String DIALECT = "DbEngineDialect"; final Properties props; try { props = ResourceUtils.loadProperties(DbFacadeLocator.class, ENGINE_DB_ENGINE_PROPERTIES); } catch (IOException exception) { throw new IllegalStateException( "Can't load properties from resource \"" + ENGINE_DB_ENGINE_PROPERTIES + "\".", exception ); } String dialect = props.getProperty(DIALECT); if (dialect == null) { throw new IllegalStateException( "Can't load property \"" + DIALECT + "\" from resource \"" + ENGINE_DB_ENGINE_PROPERTIES + "\"." ); } try { return (DbEngineDialect) Class.forName(dialect).getDeclaredConstructor(Boolean.TYPE).newInstance(false); } catch (Exception exception) { throw new IllegalStateException( "Can't create instance of dialect class \"" + dialect + "\".", exception ); } }

Target:
public static DbEngineDialect loadDbEngineDialect() { final String ENGINE_DB_ENGINE_PROPERTIES = "engine-db-engine.properties"; final String DIALECT = "DbEngineDialect"; final Properties props; try { props = ResourceUtils.loadProperties(DbFacadeLocator.class, ENGINE_DB_ENGINE_PROPERTIES); } catch (IOException exception) { throw new IllegalStateException( "Can't load properties from resource \"" + ENGINE_DB_ENGINE_PROPERTIES + "\".", exception ); } String dialect = props.getProperty(DIALECT); if (dialect == null) { throw new IllegalStateException( "Can't load property \"" + DIALECT + "\" from resource \"" + ENGINE_DB_ENGINE_PROPERTIES + "\"." ); } try { return (DbEngineDialect) Class.forName(dialect).newInstance(); } catch (Exception exception) { throw new IllegalStateException( "Can't create instance of dialect class \"" + dialect + "\".", exception ); } }
Source:
public SupportLevel getCredentialAcquireSupport(Class<? extends Credential> credentialType, String algorithmName) throws RealmUnavailableException { Assert.checkNotNullParam("credentialType", credentialType); SupportLevel supportLevel = stateRef.get().getCredentialAcquireSupport(credentialType, algorithmName); if (supportLevel == null) { throw log.unableToDetermineSupportLevel(); } return supportLevel; }

Target:
public SupportLevel getCredentialAcquireSupport(Class<? extends Credential> credentialType, String algorithmName) throws RealmUnavailableException { Assert.checkNotNullParam("credentialType", credentialType); return stateRef.get().getCredentialAcquireSupport(credentialType, algorithmName); }
Source:
protected String convertToCSV(PersistentResource resource) { if (resource == null) { return null; } StringBuilder str = new StringBuilder(); List<Object[]> json2Csv; try { String jsonStr = resourceToJsonStr(resource); JFlat flat = new JFlat(jsonStr); json2Csv = flat.json2Sheet().headerSeparator("_").getJsonAsSheet(); int index = 0; for (Object[] obj : json2Csv) { if (index++ == 0 && downloadRecordCount != 0) { continue; } String objString = Arrays.toString(obj); if (objString != null) { objString = objString.substring(1, objString.length() - 1); } str.append(objString); if (index == 1) { str.append(System.getProperty("line.separator")); } incrementRecordCount(); } } catch (Exception e) { log.debug("Exception while converting to CSV: {}", e.getMessage()); throw new IllegalStateException(e); } return str.toString(); }

Target:
protected String convertToCSV(PersistentResource resource) { if (resource == null) { return null; } StringBuilder str = new StringBuilder(); List<Object[]> json2Csv; try { String jsonStr = resourceToJsonStr(resource); JFlat flat = new JFlat(jsonStr); json2Csv = flat.json2Sheet().headerSeparator("_").getJsonAsSheet(); int index = 0; for (Object[] obj : json2Csv) { if (index++ == 0 && downloadRecordCount != 1) { continue; } String objString = Arrays.toString(obj); if (objString != null) { objString = objString.substring(1, objString.length() - 1); } str.append(objString); if (index == 1) { str.append(System.getProperty("line.separator")); } } } catch (Exception e) { log.debug("Exception while converting to CSV: {}", e.getMessage()); throw new IllegalStateException(e); } return str.toString(); }
Source:
private IsotopePattern calculateAbundanceAndMass(IsotopePattern current, List<IsotopeContainer> additional) { if (additional == null || additional.size() == 0) return current; List<IsotopeContainer> containers = new ArrayList<>(); if (current == null) { current = new IsotopePattern(); for (IsotopeContainer container : additional) current.addIsotope(container); } else { for (IsotopeContainer container : current.getIsotopes()) { for (IsotopeContainer other : additional) { double abundance = container.getIntensity() * other.getIntensity() * 0.01; double mass = container.getMass() + other.getMass(); IsotopeContainer existing = findExisting(containers, mass, resolution); if (existing != null) { existing.setMass((existing.getMass() + mass) / 2); existing.setIntensity(existing.getIntensity() + abundance); if (storeFormula) { for (IMolecularFormula mf : container.getFormulas()) addDistinctFormula(existing, union(mf, other.getFormula())); } continue; } if (abundance > minAbundance) { IsotopeContainer newcontainer = new IsotopeContainer(mass, abundance); if (storeFormula) { for (IMolecularFormula mf : container.getFormulas()) newcontainer.addFormula(union(mf, other.getFormula())); } containers.add(newcontainer); } } } current = new IsotopePattern(); for (IsotopeContainer container : containers) { current.addIsotope(container); } } return current; }

Target:
private IsotopePattern calculateAbundanceAndMass(IsotopePattern current, List<IsotopeContainer> additional) { if (additional == null || additional.size() == 0) return current; List<IsotopeContainer> containers = new ArrayList<>(); if (current == null) { current = new IsotopePattern(); for (IsotopeContainer container : additional) current.addIsotope(container); } else { for (IsotopeContainer container : current.getIsotopes()) { for (IsotopeContainer other : additional) { double abundance = container.getIntensity() * other.getIntensity() * 0.01; double mass = container.getMass() + other.getMass(); IsotopeContainer existing = findExisting(containers, mass, resolution); if (existing != null) { double newIntensity = existing.getIntensity() + abundance; existing.setMass((existing.getMass()*existing.getIntensity() + mass*abundance) / newIntensity); existing.setIntensity(newIntensity); if (storeFormula) { for (IMolecularFormula mf : container.getFormulas()) addDistinctFormula(existing, union(mf, other.getFormula())); } continue; } if (abundance > minAbundance) { IsotopeContainer newcontainer = new IsotopeContainer(mass, abundance); if (storeFormula) { for (IMolecularFormula mf : container.getFormulas()) newcontainer.addFormula(union(mf, other.getFormula())); } containers.add(newcontainer); } } } current = new IsotopePattern(); for (IsotopeContainer container : containers) { current.addIsotope(container); } } return current; }
Source:
public CompletableFuture<Versioned<LedgerMetadata>> createLedgerMetadata(long ledgerId, LedgerMetadata metadata) { CompletableFuture<Versioned<LedgerMetadata>> promise = new CompletableFuture<>(); String ledgerPath = getLedgerPath(ledgerId); StringCallback scb = new StringCallback() { @Override public void processResult(int rc, String path, Object ctx, String name) { if (rc == Code.OK.intValue()) { promise.complete(new Versioned<>(metadata, new LongVersion(0))); } else if (rc == Code.NODEEXISTS.intValue()) { LOG.warn("Failed to create ledger metadata for which already exist", ledgerId); promise.completeExceptionally(new BKException.BKLedgerExistException()); } else { LOG.error("Could not create node for ledger {}", ledgerId, KeeperException.create(Code.get(rc), path)); promise.completeExceptionally(new BKException.ZKException()); } } }; final byte[] data; try { data = serDe.serialize(metadata); } catch (IOException ioe) { promise.completeExceptionally(new BKException.ZKException(ioe)); return promise; } List<ACL> zkAcls = ZkUtils.getACLs(conf); ZkUtils.asyncCreateFullPathOptimistic(zk, ledgerPath, data, zkAcls, CreateMode.PERSISTENT, scb, null); return promise; }

Target:
public CompletableFuture<Versioned<LedgerMetadata>> createLedgerMetadata(long ledgerId, LedgerMetadata metadata) { CompletableFuture<Versioned<LedgerMetadata>> promise = new CompletableFuture<>(); String ledgerPath = getLedgerPath(ledgerId); StringCallback scb = new StringCallback() { @Override public void processResult(int rc, String path, Object ctx, String name) { if (rc == Code.OK.intValue()) { promise.complete(new Versioned<>(metadata, new LongVersion(0))); } else if (rc == Code.NODEEXISTS.intValue()) { LOG.warn("Failed to create ledger metadata for which already exist", ledgerId); promise.completeExceptionally(new BKException.BKLedgerExistException()); } else { LOG.error("Could not create node for ledger {}", ledgerId, KeeperException.create(Code.get(rc), path)); promise.completeExceptionally(new BKException.ZKException()); } } }; final byte[] data; try { data = serDe.serialize(metadata); } catch (IOException ioe) { promise.completeExceptionally(new BKException.BKMetadataSerializationException(ioe)); return promise; } List<ACL> zkAcls = ZkUtils.getACLs(conf); ZkUtils.asyncCreateFullPathOptimistic(zk, ledgerPath, data, zkAcls, CreateMode.PERSISTENT, scb, null); return promise; }
Source:
private static long getSliceArrayRetainedSizeInBytes(Slice[] values) { long sizeInBytes = sizeOf(values); Map<Object, Boolean> uniqueRetained = new IdentityHashMap<>(); for (Slice value : values) { if (value == null) { continue; } if (value.getBase() != null && uniqueRetained.put(value.getBase(), true) == null) { sizeInBytes += value.getRetainedSize(); } else { sizeInBytes += SLICE_INSTANCE_SIZE; } } return sizeInBytes; }

Target:
private static long getSliceArrayRetainedSizeInBytes(Slice[] values) { long sizeInBytes = sizeOf(values); Map<Object, Boolean> uniqueRetained = new IdentityHashMap<>(); for (Slice value : values) { if (value == null) { continue; } if (value.getBase() != null && uniqueRetained.put(value.getBase(), true) == null) { sizeInBytes += value.getRetainedSize(); } else if (value != EMPTY_SLICE) { sizeInBytes += SLICE_INSTANCE_SIZE; } } return sizeInBytes; }
Source:
public DelegatingSystemTablesProvider(SystemTablesProvider... delegates) { this(Arrays.asList(delegates)); }

Target:
public DelegatingSystemTablesProvider(SystemTablesProvider... delegates) { this(ImmutableList.copyOf(delegates)); }
Source:
default ResourceIterator<Node> findNodes( Label label, String key1, Object value1, String key2, Object value2 ) { throw new UnsupportedOperationException( "Composite findNodes is not supported by this GraphDatabaseService" ); }

Target:
default ResourceIterator<Node> findNodes( Label label, String key1, Object value1, String key2, Object value2 ) { throw new UnsupportedOperationException( "findNodes by multiple property names and values is not supported." ); }
Source:
private <T> void invokeSetter(T r, JSONObject j, String name, Method m) { final Object json = getJsonValueOrDefault(j, name, m.getParameters()[0]); if (json == null) return; Class<?>[] pt = m.getParameterTypes(); final Object value = bindJSON(m.getGenericParameterTypes()[0], pt[0], json); try { m.invoke(r, value); } catch (IllegalAccessException | InvocationTargetException e) { LOGGER.log(WARNING, "Cannot access property " + name + " of " + r.getClass(), e); } }

Target:
private <T> void invokeSetter(T r, JSONObject j, String name, Method m) { final Object json = getJsonValueOrDefault(j, name, m.getParameters()[0]); if (json == null) return; Class<?>[] pt = m.getParameterTypes(); final Object value = bindJSON(m.getGenericParameterTypes()[0], pt[0], json); try { final Set violations = validator.forExecutables().validateParameters(r, m, new Object[]{value}); if (!violations.isEmpty()) throw new ConstraintsValidationException(violations); m.invoke(r, value); } catch (IllegalAccessException | InvocationTargetException e) { LOGGER.log(WARNING, "Cannot access property " + name + " of " + r.getClass(), e); } }
Source:
public void initialize(CNPJ constraintAnnotation) { firstMod11CheckWithSeparator.initialize( createMod11ProxyAnnotation( 9, 14, 16, true ) ); secondMod11CheckWithSeparator.initialize( createMod11ProxyAnnotation( 9, 16, 17, true ) ); firstMod11CheckWithoutSeparator.initialize( createMod11ProxyAnnotation( 9, 11, 12, true ) ); secondMod11CheckWithoutSeparator.initialize( createMod11ProxyAnnotation( 9, 12, 13, true ) ); }

Target:
public void initialize(CNPJ constraintAnnotation) { withSeparatorMod11Validator1.initialize( 0, 14, 16, true, 9, 'X', '0', Mod11Check.ProcessingDirection.RIGHT_TO_LEFT ); withSeparatorMod11Validator2.initialize( 0, 16, 17, true, 9, 'X', '0', Mod11Check.ProcessingDirection.RIGHT_TO_LEFT ); withoutSeparatorMod11Validator1.initialize( 0, 11, 12, true, 9, 'X', '0', Mod11Check.ProcessingDirection.RIGHT_TO_LEFT ); withoutSeparatorMod11Validator2.initialize( 0, 12, 13, true, 9, 'X', '0', Mod11Check.ProcessingDirection.RIGHT_TO_LEFT ); }
Source:
protected Loader<CompletedTask> createLoader(int id, Bundle bundle) { if( id == LOADER_PERSONA ) { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getProfilePersonasUri(mProfileData.getId())); } else if( id == LOADER_STATS ) { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getPersonaOverviewUri(mSelectedPersona, mSelectedPlatformId)); } return null; }

Target:
protected Loader<CompletedTask> createLoader(int id, Bundle bundle) { if( id == LOADER_PERSONA ) { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getProfilePersonasUri(mProfileData.getId())); } else { startLoadingDialog(); return new Bf3Loader(getContext(), UriFactory.getPersonaOverviewUri(mSelectedPersona, mSelectedPlatformId)); } }
Source:
public static void main(String...args) { Cli<BrooklynCommand> parser = buildCli(); try { log.debug("Parsing command line arguments"); BrooklynCommand command = parser.parse(args); log.debug("Executing command: "+command); command.call(); } catch (ParseException pe) { System.err.println("Parse error: " + pe.getMessage()); System.err.println(); callHelpCommand(); System.exit(PARSE_ERROR); } catch (Exception e) { System.err.println("Execution error: " + e.getMessage()); e.printStackTrace(); System.exit(EXECUTION_ERROR); } }

Target:
public static void main(String...args) { Cli<BrooklynCommand> parser = buildCli(); try { log.debug("Parsing command line arguments: {}",args); BrooklynCommand command = parser.parse(args); log.debug("Executing command: {}", command); command.call(); } catch (ParseException pe) { System.err.println("Parse error: " + pe.getMessage()); System.err.println(getUsageInfo(parser)); System.exit(PARSE_ERROR); } catch (Exception e) { log.error("Execution error: {}\n{}" + e.getMessage(),e.getStackTrace()); System.err.println("Execution error: " + e.getMessage()); e.printStackTrace(); System.exit(EXECUTION_ERROR); } }
Source:
public static int ownedQuantity(ArrayList<Order> position, String symbol) { int ownedQuantity = 0; for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { ownedQuantity += stock.getSize(); } } return ownedQuantity; }

Target:
public static int ownedQuantity(ArrayList<Order> position, String symbol) { long ownedQuantity = 0; for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { ownedQuantity += stock.getSize(); } } return ownedQuantity; }
Source:
public static String formatDuration(long nanoseconds) { String[] parts = DurationFormatUtils.formatDuration(nanoseconds / NANOSECONDS_PER_SEC, "H:m:s:S").split(":"); StringBuilder builder = new StringBuilder(); if(Integer.valueOf(parts[0]) > 0){ builder.append(parts[0]).append(" hrs."); } if(Integer.valueOf(parts[1]) > 0){ builder.append(" ").append(parts[1]).append(" min."); } if(Integer.valueOf(parts[2]) > 0){ builder.append(" ").append(parts[2]).append(" sec."); } if(builder.length() == 0) { builder.append("Less than 0 sec."); } return builder.toString().trim(); }

Target:
public static String formatDuration(long nanoseconds) { String[] parts = DurationFormatUtils.formatDuration(nanoseconds / NANOSECONDS_PER_SEC, "H:m:s:S").split(":"); StringBuilder builder = new StringBuilder(); if(Integer.valueOf(parts[0]) > 0){ builder.append(parts[0]).append(" hrs."); } if(Integer.valueOf(parts[1]) > 0){ builder.append(" ").append(parts[1]).append(" min."); } if(Integer.valueOf(parts[2]) > 0){ builder.append(" ").append(parts[2]).append(" sec."); } if(builder.length() == 0) { builder.append("Now"); } return builder.toString().trim(); }
Source:
public void testInitializeStats() throws IOException { describe("Testing the counter values after Abfs is initialised"); AbfsInstrumentation instrumentation = new AbfsInstrumentation(getFileSystem().getUri()); for (int i = 0; i < LARGE_OPS; i++) { instrumentation.incrementStat(AbfsStatistic.CALL_GET_DELEGATION_TOKEN, 1); instrumentation.incrementStat(AbfsStatistic.ERROR_IGNORED, 1); } Map<String, Long> metricMap = instrumentation.toMap(); assertEquals("Mismatch in " + getDelegationTokenOp, LARGE_OPS, (long) metricMap.get(getDelegationTokenOp)); assertEquals("Mismatch in " + errorIgnored, LARGE_OPS, (long) metricMap.get(errorIgnored)); }

Target:
public void testInitializeStats() throws IOException { describe("Testing the counter values after Abfs is initialised"); AbfsCounters instrumentation = new AbfsInstrumentation(getFileSystem().getUri()); for (int i = 0; i < LARGE_OPS; i++) { instrumentation.incrementCounter(AbfsStatistic.CALL_GET_DELEGATION_TOKEN, 1); instrumentation.incrementCounter(AbfsStatistic.ERROR_IGNORED, 1); } Map<String, Long> metricMap = instrumentation.toMap(); assertAbfsStatistics(AbfsStatistic.CALL_GET_DELEGATION_TOKEN, LARGE_OPS, metricMap); assertAbfsStatistics(AbfsStatistic.ERROR_IGNORED, LARGE_OPS, metricMap); }
Source:
private <T extends Message> void fetchUnsyncedMessages(final Account account, final Folder<T> remoteFolder, List<T> unsyncedMessages, final List<Message> smallMessages, final List<Message> largeMessages, final AtomicInteger progress, final int todo, FetchProfile fp) throws MessagingException { final String folder = remoteFolder.getName(); final Date earliestDate = account.getEarliestPollDate(); remoteFolder.fetch(unsyncedMessages, fp, new MessageRetrievalListener<T>() { @Override public void messageFinished(T message, int number, int ofTotal) { try { if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { if (K9.isDebug()) { if (message.isSet(Flag.DELETED)) { Timber.v("Newly downloaded message %s:%s:%s was marked deleted on server, " + "skipping", account, folder, message.getUid()); } else { Timber.d("Newly downloaded message %s is older than %s, skipping", message.getUid(), earliestDate); } } progress.incrementAndGet(); for (MessagingListener l : controller.getListeners()) { l.synchronizeMailboxProgress(account, folder, progress.get(), todo); } return; } if (account.getMaximumAutoDownloadMessageSize() > 0 && message.getSize() > account.getMaximumAutoDownloadMessageSize()) { largeMessages.add(message); } else { smallMessages.add(message); } } catch (Exception e) { Timber.e(e, "Error while storing downloaded message."); } } @Override public void messageStarted(String uid, int number, int ofTotal) { } @Override public void messagesFinished(int total) { } }); }

Target:
private <T extends Message> void fetchUnsyncedMessages(final Account account, final Folder<T> remoteFolder, List<T> unsyncedMessages, final List<Message> smallMessages, final List<Message> largeMessages, final AtomicInteger progress, final int todo, FetchProfile fp) throws MessagingException { final Date earliestDate = account.getEarliestPollDate(); remoteFolder.fetch(unsyncedMessages, fp, new MessageRetrievalListener<T>() { @Override public void messageFinished(T message, int number, int ofTotal) { try { if (message.isSet(Flag.DELETED) || message.olderThan(earliestDate)) { processDeletedOrOldMessage(message, account, remoteFolder.getName(), earliestDate, progress, todo); return; } if (account.getMaximumAutoDownloadMessageSize() > 0 && message.getSize() > account.getMaximumAutoDownloadMessageSize()) { largeMessages.add(message); } else { smallMessages.add(message); } } catch (Exception e) { Timber.e(e, "Error while storing downloaded message."); } } @Override public void messageStarted(String uid, int number, int ofTotal) { } @Override public void messagesFinished(int total) { } }); }
Source:
public List<Diagnosis> getPrimaryDiagnoses(Encounter encounter) { List<Diagnosis> diagnoses = null; if (encounter != null && !encounter.getVoided()) { diagnoses = new ArrayList<Diagnosis>(); for (Diagnosis diagnosis : encounter.getDiagnoses()) { if (diagnosis.getOrder == DIAGNOSIS_ORDER_PRIMARY) { diagnoses.add(diagnosis); } } } return diagnoses; }

Target:
public List<Diagnosis> getPrimaryDiagnoses(Encounter encounter) { List<Diagnosis> diagnoses = new ArrayList<Diagnosis>(); if (encounter != null && !encounter.getVoided()) { for (Diagnosis diagnosis : encounter.getDiagnoses()) { if (diagnosis.getRank() == 1) { diagnoses.add(diagnosis); } } } return diagnoses; }
Source:
private boolean hasCorrespondingNotificationPreference(DocumentReference user, CompositeEvent compositeEvent) { try { for (NotificationPreference notificationPreference: this.modelBridge.getNotificationsPreferences(user)) { if (notificationPreference.getEventType().equals(compositeEvent.getType())) { return notificationPreference.isNotificationEnabled(); } } } catch (NotificationException e) { this.logger.warn( String.format("Unable to retrieve the notifications preferences of [%s]: [%s]", user, e)); } return false; }

Target:
private boolean hasCorrespondingNotificationPreference(DocumentReference user, CompositeEvent compositeEvent) { try { for (NotificationPreference notificationPreference: this.modelBridge.getNotificationsPreferences(user)) { if (notificationPreference.getFormat().equals(NotificationFormat.EMAIL) && notificationPreference.getEventType().equals(compositeEvent.getType())) { return notificationPreference.isNotificationEnabled(); } } } catch (NotificationException e) { this.logger.warn( String.format("Unable to retrieve the notifications preferences of [%s]: [%s]", user, e)); } return false; }