auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run(final SpringConfiguration configuration, final Environment environment) throws Exception { START log.info("_____spring scanning________*******************"); END initializeSpring(configuration, environment); // Do the dropwizard registrations addResources(environment); addHealthChecks(environment); addTasks(environment); addManaged(environment); } clean up message

Target:
public void run(final SpringConfiguration configuration, final Environment environment) throws Exception { initializeSpring(configuration, environment); // Do the dropwizard registrations addResources(environment); addHealthChecks(environment); addTasks(environment); addManaged(environment); }
Source:
private static JSONObject createJsonFileObject(InputStream stream) throws IOException, JSONException { String line; StringBuilder result = new StringBuilder(); // Reads from stream BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { // Read each line of the GeoJSON file into a string while ((line = reader.readLine()) != null) { result.append(line); } } finally { START reader.close(); END } // Converts the result string into a JSONObject return new JSONObject(result.toString()); } This can potentially throw an `IOException`.

Target:
private static JSONObject createJsonFileObject(InputStream stream) throws IOException, JSONException { String line; StringBuilder result = new StringBuilder(); // Reads from stream BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); // Read each line of the GeoJSON file into a string while ((line = reader.readLine()) != null) { result.append(line); } reader.close(); // Converts the result string into a JSONObject return new JSONObject(result.toString()); }
Source:
START public void setExecutionAudit(BiConsumer<RequestData, Authentication> executionAudit) { END this.executionAudit = executionAudit; } Since it's a testing facility I'd make the methods around it at least package private. Another possible approach would be to manually register a RequestPostProcessor that does the same work using GeoServerExtensionsHelper.singleton

Target:
void setExecutionAudit(BiConsumer<RequestData, Authentication> executionAudit) { this.executionAudit = executionAudit; }
Source:
START public void useEqualsWhenTrueThenCustomMediaTypeIsMatched() throws HttpMediaTypeNotAcceptableException { END request.addHeader("Accept", "text/unique"); matcher = new MediaTypeRequestMatcher(new MediaType("text", "unique")); matcher.setUseEquals(true); assertThat(matcher.matches(request)).isTrue(); } A number of these tests don't actually throw an `HttpMediaTypeNotAcceptableException`. Will you please remove the `throws` from the signature where it is unnecessary? This way, the expectations of the test are clearer.

Target:
public void useEqualsWhenTrueThenCustomMediaTypeIsMatched() { request.addHeader("Accept", "text/unique"); matcher = new MediaTypeRequestMatcher(new MediaType("text", "unique")); matcher.setUseEquals(true); assertThat(matcher.matches(request)).isTrue(); }
Source:
default void executeTask(final KeyFilter<? super K> filter, BiConsumer<? super K, InternalCacheEntry<K, V>> action) throws InterruptedException { START iterator().forEachRemaining(ice -> { END if (filter == null || filter.accept(ice.getKey())) { action.accept(ice.getKey(), ice); } }); } Could use `forEach` here too, otherwise we're not really gaining anything from using a lambda

Target:
default void executeTask(final KeyFilter<? super K> filter, BiConsumer<? super K, InternalCacheEntry<K, V>> action) throws InterruptedException { forEach(ice -> { if (filter == null || filter.accept(ice.getKey())) { action.accept(ice.getKey(), ice); } }); }
Source:
private void sendRelationshipErrorMessage( final String relationName, final User user ) { START SystemMessageEventUtil systemMessageEventUtil = SystemMessageEventUtil.getInstance(); END try { systemMessageEventUtil.pushMessage( new SystemMessageBuilder() .setMessage(LanguageUtil.format( user.getLocale(), "contenttypes.field.properties.relationship.required.error", relationName) ) .setSeverity(MessageSeverity.INFO) .setType(MessageType.SIMPLE_MESSAGE) .create(), list(user.getUserId()) ); } catch (LanguageException e) { throw new DotRuntimeException(e); } } set as final

Target:
private void sendRelationshipErrorMessage( final String relationName, final User user ) { final SystemMessageEventUtil systemMessageEventUtil = SystemMessageEventUtil.getInstance(); try { systemMessageEventUtil.pushMessage( new SystemMessageBuilder() .setMessage(LanguageUtil.format( user.getLocale(), "contenttypes.field.properties.relationship.required.error", relationName) ) .setSeverity(MessageSeverity.INFO) .setType(MessageType.SIMPLE_MESSAGE) .create(), list(user.getUserId()) ); } catch (LanguageException e) { throw new DotRuntimeException(e); } }
Source:
START public synchronized void updateCommittedTail(long newCommittedTail) { END committedTail.updateAndGet(curr -> { if (newCommittedTail <= curr) { return curr; } return newCommittedTail; }); } Is synchronized necessary here?

Target:
public void updateCommittedTail(long newCommittedTail) { committedTail.updateAndGet(curr -> { if (newCommittedTail <= curr) { return curr; } return newCommittedTail; }); }
Source:
private boolean isNestedCopyfile(CopyFile copyfile) { START if (copyfile.dest.indexOf('/') == -1) // If the copyfile is at root level then it won't be nested. return false; for (RepoProject proj : filteredProjects) { if (proj.getPath().compareTo(copyfile.dest) > 0) // Early return as remaining projects can't be ancestor of this // copyfile config (filteredProjects is sorted). return false; END if (proj.isAncestorOf(copyfile.dest)) { return true; } } return false; } nit: missing braces around if bodies (https://wiki.eclipse.org/EGit/Contributor_Guide#Braces_for_one-line_statements)

Target:
private boolean isNestedCopyfile(CopyFile copyfile) { if (copyfile.dest.indexOf('/') == -1) { // If the copyfile is at root level then it won't be nested. return false; } for (RepoProject proj : filteredProjects) { if (proj.getPath().compareTo(copyfile.dest) > 0) { // Early return as remaining projects can't be ancestor of this // copyfile config (filteredProjects is sorted). return false; } if (proj.isAncestorOf(copyfile.dest)) { return true; } } return false; }
Source:
public void write(OutputStream out) { try { IOUtils.copy(results.getInputStream(), out); } catch (IOException e) { START log.warn(e.getMessage()); END throw new WebApplicationException(Response.status(Status.SERVICE_UNAVAILABLE) .entity("Service Unavailable, IO Exception with Search Engine").build()); } finally { results.disconnect(); } } The exception should be logged completely.

Target:
public void write(OutputStream out) { try { IOUtils.copy(results.getInputStream(), out); } catch (IOException e) { log.warn(e.getMessage(), e); throw new WebApplicationException(Response.status(Status.SERVICE_UNAVAILABLE) .entity("Service Unavailable, IO Exception with Search Engine").build()); } finally { results.disconnect(); } }
Source:
private static Collection<@NonNull TmfAbstractAnalysisRequirement> getSubRequirements() { Set<@NonNull String> requiredEventsFields = START Collections.singleton( ITraceEventConstants.DURATION); END TmfAnalysisEventFieldRequirement entryReq = new TmfAnalysisEventFieldRequirement( StringUtils.EMPTY, requiredEventsFields); return Collections.singleton(entryReq); } this can fit on one line

Target:
private static Collection<@NonNull TmfAbstractAnalysisRequirement> getSubRequirements() { TmfAnalysisEventFieldRequirement entryReq = new TmfAnalysisEventFieldRequirement( StringUtils.EMPTY, Collections.singleton(ITraceEventConstants.DURATION)); return Collections.singleton(entryReq); }
Source:
START protected boolean allowPausedModeWork(boolean internalCall, boolean adminConnection) { END return (VoltDB.instance().getMode() != OperationMode.PAUSED || internalCall || adminConnection); } Why not static as others? Same to function `makeQuickResponse `.

Target:
static protected boolean allowPausedModeWork(boolean internalCall, boolean adminConnection) { return (VoltDB.instance().getMode() != OperationMode.PAUSED || internalCall || adminConnection); }
Source:
public Queue<ControllerAction> getInputQueue() { Queue<ControllerAction> result = new ArrayDeque<>(); START result.addAll(queuedActions); END queuedActions.clear(); return result; } Have you considered skipping the line above by having something like `Queue<ControllerAction> result = new ArrayDeque(queuedActions);`

Target:
public Queue<ControllerAction> getInputQueue() { Queue<ControllerAction> result = new ArrayDeque<>(queuedActions); queuedActions.clear(); return result; }
Source:
private void runLibertyMojoCreate() throws MojoExecutionException { createParams.addAll(commonParams); START createParams.addAll(commonServerParams); END Xpp3Dom config = stripConfigElements(getLibertyPluginConfig(), createParams); log.info("Running liberty:create goal"); runLibertyMojo("create", config); } If `createParams` should always have `commonParams` and `commonServerParams`, why not just define it that way to start with? And I think you could make the collection a static final variable at the class level.

Target:
private void runLibertyMojoCreate() throws MojoExecutionException { Xpp3Dom config = stripConfigElements(getLibertyPluginConfig(), createParams); log.info("Running liberty:create goal"); runLibertyMojo("create", config); }
Source:
START private ProgramState closeResource(ProgramState programState, final SymbolicValue target) { END if (target != null && isOpened(programState, target)) { return programState.addConstraint(target.wrappedValue(), NullConstraint.CLOSED); } return programState; } Please fix this issue.

Target:
private static ProgramState closeResource(ProgramState programState, final SymbolicValue target) { if (target != null && isOpened(programState, target)) { return programState.addConstraint(target.wrappedValue(), NullConstraint.CLOSED); } return programState; }
Source:
public LongWrappingDimensionSelector(LongColumnSelector selector, ExtractionFn extractionFn) { this.delegate = selector; START this.exFn = extractionFn; END } This selector is going to throw NPE on get() if extractionFn is null, so it's better to throw it in construction: ``` this.extractionFn = Preconditions.checkNotNull(extractionFn, "extractionFn"); ```

Target:
public LongWrappingDimensionSelector(LongColumnSelector selector, ExtractionFn extractionFn) { this.selector = selector; this.extractionFn = extractionFn; }
Source:
private String getCurrentUser() { // authenticator is not used if there is not any user Account[] accountList = mAcctManager .getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE); START return accountList[0].name; END } can account list be null or empty here?

Target:
private String getCurrentUser() { // authenticator is not used if there is not any user Account[] accountList = mAcctManager .getAccountsByType(AuthenticationConstants.Broker.BROKER_ACCOUNT_TYPE); if (accountList != null && accountList.length > 0) { return accountList[0].name; } return null; }
Source:
private boolean isExpired(Long issuedAt, Long lifetime) { START return lifetime != -1 && issuedAt + lifetime < System.currentTimeMillis() / 1000; END } Suggest using parenthesis to clarify order of operator evaluation

Target:
private boolean isExpired(Long issuedAt, Long lifetime) { return lifetime != -1 && ((issuedAt + lifetime) < (System.currentTimeMillis() / 1000)); }
Source:
private void onSafeDelete() { if (context.getEditorModelContent().getOriginalClassName() != null) { //if we are about to delete a .java file that could be parsed without errors, and we can calculate the //className then we can check for class usages prior to deletion. final String className = context.getEditorModelContent().getOriginalClassName(); showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_deletion_of_used_class(className), versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> onDelete(versionRecordManager.getPathToLatest()), () -> { START }); END } else { //we couldn't parse the class, so no check can be done. Just proceed with the standard //file deletion procedure. onDelete(versionRecordManager.getPathToLatest()); } } Looks to me like the last parameter never does anything, but not sure if there is some location that uses it and it is just not in the diff.

Target:
public void onSafeDelete() { if (context.getEditorModelContent().getOriginalClassName() != null) { //if we are about to delete a .java file that could be parsed without errors, and we can calculate the //className then we can check for class usages prior to deletion. final String className = context.getEditorModelContent().getOriginalClassName(); showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_deletion_of_used_class(className), versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> onDelete(versionRecordManager.getPathToLatest()), () -> { }); } else { //we couldn't parse the class, so no check can be done. Just proceed with the standard //file deletion procedure. onDelete(versionRecordManager.getPathToLatest()); } }
Source:
START public V get(final String key) { END return super.get(key.toLowerCase()); } Missing @Override annotations?

Target:
public V get(final String key) { return this.map.get(key.toLowerCase()); }
Source:
public static byte[] byteBufferToArray(ByteBuffer buf) { byte[] arr = new byte[buf.remaining()]; int prevPosition = buf.position(); buf.get(arr); START buf.position(prevPosition); END return arr; } nit: maybe use `finally` to restore this value.

Target:
public static byte[] byteBufferToArray(ByteBuffer buf) { byte[] arr = new byte[buf.remaining()]; int prevPosition = buf.position(); try { buf.get(arr); } finally { buf.position(prevPosition); } return arr; }
Source:
private boolean deleteRef() { if (!fs.retryFailedLockFileCommit()) return ref.delete(); // file deletion fails on windows if another // thread is reading the file concurrently // So let's try 10 times... for (int i = 0; i < 10; i++) { START if (ref.delete()) { END return true; } try { Thread.sleep(100); } catch (InterruptedException e) { // ignore } } return false; } Style-nit: Braces aren't necessary here.

Target:
private boolean deleteRef() { if (!fs.retryFailedLockFileCommit()) return ref.delete(); // file deletion fails on windows if another // thread is reading the file concurrently // So let's try 10 times... for (int i = 0; i < 10; i++) { if (ref.delete()) return true; try { Thread.sleep(100); } catch (InterruptedException e) { return false; } } return false; }
Source:
public Partition getPartitionObj(int idx) throws Exception { return partitionObjs == null ? null : START (Partition)JSONMessageFactory.getTObj(partitionObjs.get(idx), Partition.class); END } Some of the partitionObjs entries can be NULL if the table is not partitioned. Need to handle it.

Target:
public Partition getPartitionObj(int idx) throws Exception { return (partitionObjs == null ? null : (partitionObjs.get(idx) == null ? null : (Partition)JSONMessageFactory.getTObj(partitionObjs.get(idx), Partition.class))); }
Source:
public void lock() { try { this.mutex.acquire(); } catch (Exception e) { START throw new MessagingException("Failed to aquire mutex at " + this.path, e); END } } This isn't a Messaging component and from other side using this one within a Messaging component, raising a `MessagingException` from here, we prevent re-throwing a correct `MessagingException` with `failedMessage` context. So, for me simple `RuntimeException` is enough in this context. WDYT?

Target:
public void lock() { try { this.mutex.acquire(); } catch (Exception e) { throw new RuntimeException("Failed to aquire mutex at " + this.path, e); } }
Source:
protected void executeCommand() { initConnectionList(true); for (Map.Entry<StorageType, List<StorageServerConnections>> connectionToType : getConnectionsTypeMap().entrySet()) { disconnectStorageByType(connectionToType.getKey(), connectionToType.getValue()); } START if (FeatureSupported.cinderProviderSupported(getStoragePool().getCompatibilityVersion())) { END // Unregister all libvirt secrets if needed unregisterLibvirtSecrets(); } } please move it to inside the method to be consistent...

Target:
protected void executeCommand() { initConnectionList(true); for (Map.Entry<StorageType, List<StorageServerConnections>> connectionToType : getConnectionsTypeMap().entrySet()) { disconnectStorageByType(connectionToType.getKey(), connectionToType.getValue()); } unregisterLibvirtSecrets(); }
Source:
protected void executeVdsBrokerCommand() { UpdateGlusterGeoRepKeysVDSParameters parameters = getParameters(); status = getBroker().glusterGeoRepKeysUpdate(parameters.getRemoteUserName(), START new ArrayList<>(parameters.getGeoRepPubKeys())); END proceedProxyReturnValue(); } Why you create new List here? getGeoRepPubKeys returns a list already.

Target:
protected void executeVdsBrokerCommand() { UpdateGlusterGeoRepKeysVDSParameters parameters = getParameters(); status = getBroker().glusterGeoRepKeysUpdate(parameters.getGeoRepPubKeys(), parameters.getRemoteUserName()); proceedProxyReturnValue(); }
Source:
public static void beforeClass() throws Exception { // Create a user adminSynapse = new SynapseAdminClientImpl(); SynapseClientHelper.setEndpoints(adminSynapse); adminSynapse.setUsername(StackConfigurationSingleton.singleton().getMigrationAdminUsername()); adminSynapse.setApiKey(StackConfigurationSingleton.singleton().getMigrationAdminAPIKey()); START synapse = new SynapseClientImpl(); END userId = SynapseClientHelper.createUser(adminSynapse, synapse); } You are not setting the endpoints for this client

Target:
public static void beforeClass() throws Exception { // Create a user adminSynapse = new SynapseAdminClientImpl(); SynapseClientHelper.setEndpoints(adminSynapse); adminSynapse.setUsername(StackConfigurationSingleton.singleton().getMigrationAdminUsername()); adminSynapse.setApiKey(StackConfigurationSingleton.singleton().getMigrationAdminAPIKey()); synapse = new SynapseClientImpl(); userId = SynapseClientHelper.createUser(adminSynapse, synapse); SynapseClientHelper.setEndpoints(synapse); }
Source:
public void close() { waitForSendComplete(); // Close the buffers before closing the operators; this is needed as buffer ownership // is attached to the receive operators. suppressingClose(buffers); // close operator context for (OperatorContextImpl opContext : contexts) { suppressingClose(opContext); } START closeNotConsumedRFWs(); END suppressingClose(bufferManager); suppressingClose(allocator); } I see that all the bloomFilters of RFW are allocated using [fragment context allocator](https://github.com/apache/drill/blob/master/exec/java-exec/src/main/java/org/apache/drill/exec/physical/impl/join/HashJoinBatch.java#L836) not operator context so why does the order in which `closeNotConsumedRFWs()` is called matters here ?

Target:
public void close() { waitForSendComplete(); // Close the buffers before closing the operators; this is needed as buffer ownership // is attached to the receive operators. suppressingClose(buffers); closeNotConsumedRFWs(); // close operator context for (OperatorContextImpl opContext : contexts) { suppressingClose(opContext); } suppressingClose(bufferManager); suppressingClose(allocator); }
Source:
public Long getPeerRouterId(String publicMacAddress, final long routerId) { final SearchCriteria<NicVO> sc = PeerRouterSearch.create(); sc.setParameters("instanceId", routerId); sc.setParameters("macAddress", publicMacAddress); sc.setParameters("vmType", VirtualMachine.Type.DomainRouter); NicVO nicVo = findOneBy(sc); if (nicVo != null) { START return (new Long(nicVo.getInstanceId())); END } return null; } Let the auto-boxing and auto-unboxing do this for you. When you do this manually the pool of String/numbers of java will not be used. You just need to return `nicVo.getInstanceId()`

Target:
public Long getPeerRouterId(String publicMacAddress, final long routerId) { final SearchCriteria<NicVO> sc = PeerRouterSearch.create(); sc.setParameters("instanceId", routerId); sc.setParameters("macAddress", publicMacAddress); sc.setParameters("vmType", VirtualMachine.Type.DomainRouter); NicVO nicVo = findOneBy(sc); if (nicVo != null) { return nicVo.getInstanceId(); } return null; }
Source:
public List<Tree.Kind> nodesToVisit() { START ArrayList<Tree.Kind> nodesToVisit = new ArrayList<>(super.nodesToVisit()); END nodesToVisit.add(Tree.Kind.CLASS); nodesToVisit.add(Tree.Kind.ASSIGNMENT); nodesToVisit.add(Tree.Kind.STATIC_INITIALIZER); return nodesToVisit; } Use `List<Tree.Kind>` for the variable declaration (always use interface for declaration, and implementation for instantiation.)

Target:
public List<Tree.Kind> nodesToVisit() { List<Tree.Kind> nodesToVisit = new ArrayList<>(super.nodesToVisit()); nodesToVisit.add(Tree.Kind.CLASS); nodesToVisit.add(Tree.Kind.ASSIGNMENT); nodesToVisit.add(Tree.Kind.STATIC_INITIALIZER); return nodesToVisit; }
Source:
public void testXmlDeniesDuplicateGroupConfig() { expectDuplicateElementError("group"); START String groupConfig = " <group>\n" END + " <name>foobar</name>\n" + " <password>dev-pass</password>\n" + " </group>\n"; buildConfig(HAZELCAST_START_TAG + groupConfig + groupConfig + HAZELCAST_END_TAG, null); } Super Minor: Format XMLs in this test to look like (unless you have some autoformatting, etc., then you can leave it as it is): ``` String groupConfig = " <group>\n" + " <name>foobar</name>\n" + " <password>dev-pass</password>\n" + " </group>\n"; ```

Target:
public void testXmlDeniesDuplicateGroupConfig() { expectDuplicateElementError("group"); String groupConfig = "" + " <group>\n" + " <name>foobar</name>\n" + " <password>dev-pass</password>\n" + " </group>\n"; buildConfig(HAZELCAST_START_TAG + groupConfig + groupConfig + HAZELCAST_END_TAG); }
Source:
public boolean accepts( Event<?> evt ) { return applicationStatusSource.getSystemStatus().isNexusStarted() && ( evt instanceof RepositoryRegistryRepositoryEvent ) START || ( evt instanceof RepositoryConfigurationUpdatedEvent ); END } You could also put the isNexusStarted method call after the "evt instanceof ..." checks - this should perform better because you'd avoid calling the synchronous method for other Nexus events. Also maybe add brackets to make it clear whether the status check applies to both events or just the registry one.

Target:
public boolean accepts( Event<?> evt ) { return ( ( evt instanceof RepositoryRegistryRepositoryEvent ) || ( evt instanceof RepositoryConfigurationUpdatedEvent ) ) && applicationStatusSource.getSystemStatus().isNexusStarted(); }
Source:
public static ISynchronizeService getSyncService(String syncServiceId) { ISynchronizeServiceDescriptor desc = SynchronizeServiceRegistry.getSynchronizeServiceDescriptor(syncServiceId); if(desc == null) START return null; END return desc.getService(); } Braces required by coding convention.

Target:
public static ISynchronizeService getSyncService(String syncServiceId) { ISynchronizeServiceDescriptor desc = SynchronizeServiceRegistry.getSynchronizeServiceDescriptor(syncServiceId); if(desc == null) { return null; } return desc.getService(); }
Source:
private int getExtendedFlags() { START if (!isExtended()) { END return 0; } return NB.decodeUInt16(info, infoOffset + P_FLAGS2) << 16; } I would prefer: if (isExtended()) return NB.decodeUInt16(info, infoOffset + P_FLAGS2) << 16; else return 0;

Target:
private int getExtendedFlags() { if (isExtended()) return NB.decodeUInt16(info, infoOffset + P_FLAGS2) << 16; else return 0; }
Source:
protected void update(final Map<String, Object> attributes) { final String id = (String) attributes.get(getIdAttribute()); logger.debug("Updating id: with attributes: {}", id, attributes); final Map<String,Object> profile = profiles.get(id); if (profile != null) { profile.putAll(attributes); } else { START insert(attributes); END } } Cannot we just do: `profiles.put(id, attributes);`?

Target:
protected void update(final Map<String, Object> attributes) { final String id = (String) attributes.get(getIdAttribute()); logger.debug("Updating id: with attributes: {}", id, attributes); final Map<String,Object> profile = profiles.get(id); if (profile != null) { profile.putAll(attributes); } else { profiles.put(id, attributes); } }
Source:
private <T extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { if (dao instanceof BaseDAODbFacade) { START initBaseDAO((BaseDAODbFacade) dao); END } return (T) dao; } } log.error("Can't find dao for " + daoType); return null; } I still be able to see this line :/

Target:
private <T extends DAO> T getDao(Class<T> daoType) { for (DAO dao : daos) { if (daoType.isAssignableFrom(dao.getClass())) { return (T) dao; } } log.error("Can't find dao for " + daoType); return null; }
Source:
private DatabaseClient(final String url) { MongoClient mongoClient = null; try { mongoClient = new MongoClient(url); } catch (UnknownHostException e) { LOG.info(LoggingConstants.EXCEPTION_MESSAGE, e); } if (mongoClient == null) { return; } database = mongoClient.getDB("submissions"); if (database == null) { START LOG.info("Db is null!"); END } else { setUpIndexes(); } } chnge to error

Target:
private DatabaseClient(final String url) { MongoClient mongoClient = null; try { mongoClient = new MongoClient(url); } catch (UnknownHostException e) { LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); } if (mongoClient == null) { return; } database = mongoClient.getDB("submissions"); if (database == null) { LOG.error("Db is null!"); } else { setUpIndexes(); } }
Source:
public void undo() { START if (fbType instanceof BasicFBType) { ((BasicFBType) fbType).getAlgorithm().add(((BasicFBType) fbType).getAlgorithm().indexOf(newAlgorithm), oldAlgorithm); updateECActions(false); ((BasicFBType) fbType).getAlgorithm().remove(newAlgorithm); } END } this shows that the algorithm list should be moved to the base fb. otherwise change alg type will not work for siimple fbs.

Target:
public void undo() { ((BasicFBType) fbType).getAlgorithm().add(((BasicFBType) fbType).getAlgorithm().indexOf(newAlgorithm), oldAlgorithm); updateECActions(false); ((BasicFBType) fbType).getAlgorithm().remove(newAlgorithm); }
Source:
public long getLastSchedulingCycleRuntimeDelayMs() { START return System.currentTimeMillis() - lastSchedulingCycleRunTimeMs.get(); END } nit: static import currentTimeMillis

Target:
public long getLastSchedulingCycleRuntimeDelayMs() { return currentTimeMillis() - lastSchedulingCycleRunTimeMs.get(); }
Source:
public void synchronizeMailboxSynchronous_withAccountPolicySetToExpungeOnPoll_shouldExpungeRemoteFolder() throws Exception { messageCountInRemoteFolder(1); when(account.getExpungePolicy()).thenReturn(Account.Expunge.EXPUNGE_ON_POLL); configureRemoteStoreWithFolder(); controller.synchronizeMailboxSynchronous(account, FOLDER_NAME, listener, null); START verify(remoteFolder).expunge(anySet()); END } `anySet()` is pretty weak. Can't we verify we pass in the right IDs?

Target:
public void synchronizeMailboxSynchronous_withAccountPolicySetToExpungeOnPoll_shouldExpungeRemoteFolder() throws Exception { messageCountInRemoteFolder(1); when(account.getExpungePolicy()).thenReturn(Account.Expunge.EXPUNGE_ON_POLL); configureRemoteStoreWithFolder(); controller.synchronizeMailboxSynchronous(account, FOLDER_NAME, listener, null); verify(remoteFolder).expunge(); }
Source:
public void onBackPressed() { Fragment currentFragment = fragmentManager .findFragmentById(R.id.fragment_holder); if (currentFragment instanceof About) { fragmentManager.popBackStack(FragmentTags.CARD_LIST, 0); START return; END } super.onBackPressed(); } I prefer an `else` instead of this `return`.

Target:
public void onBackPressed() { Fragment currentFragment = fragmentManager .findFragmentById(R.id.fragment_holder); if (currentFragment instanceof About) { fragmentManager.popBackStack(FragmentTags.CARD_LIST, 0); } else { super.onBackPressed(); } }
Source:
public boolean select(Viewer viewer, Object parent, Object element) { START IBreakpoint breakpoint = (IBreakpoint) element; END IInteractionElement interactionElement = ContextCore.getContextManager().getElement( structureBridge.getHandleIdentifier(breakpoint)); if (interactionElement == null) { return true; } return !interactionElement.getInterest().isInteresting(); } An instanceof check would be good in case other items are added to the view in the future.

Target:
public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IBreakpoint) { IBreakpoint breakpoint = (IBreakpoint) element; IInteractionElement interactionElement = ContextCore.getContextManager().getElement( structureBridge.getHandleIdentifier(breakpoint)); if (interactionElement == null) { return true; } return !interactionElement.getInterest().isInteresting(); } return true; }
Source:
public void scanFile(JavaFileScannerContext context) { super.context = context; if (isRegularExpression) { try { searchPattern = Pattern.compile(headerFormat, Pattern.DOTALL); START } catch (RuntimeException e) { END throw new IllegalArgumentException("[" + getClass().getSimpleName() + "] Unable to compile the regular expression: " + headerFormat, e); } } else { expectedLines = headerFormat.split("(?:\r)?\n|\r"); } visitFile(context.getFile()); } seems quite wide to catch all RuntimeException : http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#compile(java.lang.String)

Target:
public void scanFile(JavaFileScannerContext context) { super.context = context; if (isRegularExpression) { if (searchPattern == null) { try { searchPattern = Pattern.compile(headerFormat, Pattern.DOTALL); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("[" + getClass().getSimpleName() + "] Unable to compile the regular expression: " + headerFormat, e); } } } else { expectedLines = headerFormat.split("(?:\r)?\n|\r"); } visitFile(context.getFile()); }
Source:
private boolean isAllowedToClone(Object value) { if(value == null){ System.out.print("null"); START } END return Objects.nonNull(value) && ((value instanceof String) || (classUtils.isPrimitiveClass(value.getClass()))); } This method needs to enhance. I mean If the first `if` is true, then the code bellow is always false. Also I think `System.out.print("null");` should be replaced with some log.

Target:
private boolean isAllowedToClone(Object value) { return Objects.nonNull(value) && ((value instanceof String) || (classUtils.isPrimitiveClass(value.getClass()))); }
Source:
public void validate(GlobalConfiguration globalConfig) { START if(mediaType != null) { END CONFIG.ignoringSpecificMediaTypes(); key().mediaType(mediaType); value().mediaType(mediaType); } keyContentTypeBuilder.validate(); valueContentTypeBuilder.validate(); } Nitpick: space

Target:
public void validate(GlobalConfiguration globalConfig) { }
Source:
public static void createDir(String path) throws IOException { try { Files.createDirectories(Paths.get(path)); } catch (AccessDeniedException e) { START LOG.info("Fail to create folder " + path + "caused by AccessDeniedException"); END } } 1. trick to use `LOG`: add exception as the last argument and it will be logged as the cause automatically. like this: ```java LOG.info("Fail to create folder " + path, e); ``` 2. actually i think we should throw this exception rather than swallow it. Why do you catch and convert the exception to log message?

Target:
public static void createDir(String path) throws IOException { Files.createDirectories(Paths.get(path)); }
Source:
public TraceStatusDMData() { START this(false, false, false, 0, 0, 0, "", "", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ END fTracingSupported = false; } Why not use null instead of ""?

Target:
public TraceStatusDMData() { fTracingSupported = false; }
Source:
public ThrottlingExceptionRoutePolicy(int threshold, long failureWindow, long halfOpenAfter, List<Class<?>> handledExceptions) { this.throttledExceptions = handledExceptions; this.failureWindow = failureWindow; this.halfOpenAfter = halfOpenAfter; this.failureThreshold = threshold; START this.keepOpen.set(false); END } I would replace those statements above with `this(handledExceptions,failureWindow,halfOpenAfter,threshold,false)`.

Target:
public ThrottlingExceptionRoutePolicy(int threshold, long failureWindow, long halfOpenAfter, List<Class<?>> handledExceptions) { this(threshold, failureWindow, halfOpenAfter, handledExceptions, false); }
Source:
public void markRequestException(Exception e) { START String errorMessage = e.getMessage().replaceAll(REGEX, "."); END metricsRegistry.meter(errorNamespace(metricNamespace, e, errorMessage)).mark(); } Using the error message in the metric could get really messy. These are arbitrary strings, and could be very long. For Error, we're using the error code–a _very_ different thing, since these are well known, and short. The exception type name is enough for Exceptions.

Target:
public void markRequestException(Exception e) { metricsRegistry.meter(errorNamespace(metricNamespace, e, null)).mark(); }
Source:
public void anonUserOnMobileCanSeeAppPromotion() { Promoting promoting = findPromoting(); Assertion.assertTrue(promoting.isMobileBannerDisplayed()); START Assertion.assertStringContains(promoting.getPromotionAppMobileText(), MOBILE_PROMOTION_TEXT); END } Perhaps you can use static imports for everything form Assertion?

Target:
public void anonUserOnMobileCanSeeAppPromotion() { Promoting promoting = findPromoting(); assertTrue(promoting.isMobileBannerDisplayed()); assertStringContains(promoting.getPromotionAppMobileText(), MOBILE_PROMOTION_TEXT); }
Source:
public void testWrongSelectionBug534319singleThread() throws Exception { START waitForNonConsoleJobs(); END // Run a few times since the problem doesn't occur always int iterations = 5; final String typeName = "Bug534319singleThread"; final String breakpointMethodName = "breakpointMethod"; doTestWrongSelectionBug534319(iterations, typeName, breakpointMethodName); } Maybe move this to doTestWrongSelectionBug534319.

Target:
public void testWrongSelectionBug534319singleThread() throws Exception { // Run a few times since the problem doesn't occur always int iterations = 5; final String typeName = "Bug534319singleThread"; final String breakpointMethodName = "breakpointMethod"; doTestWrongSelectionBug534319(iterations, typeName, breakpointMethodName); }
Source:
START private boolean validateServers(Set<String> serverNames) { END for (String serverName : serverNames) { if (getVdsStaticDao().getAllForHost(serverName).size() > 0 || getVdsStaticDao().getAllWithIpAddress(serverName).size() > 0) { return true; } } return false; } Normally, a 'validate' method should return true in case of success, and false if validation failed.

Target:
private boolean validateServers(Set<String> serverNames) { for (String serverName : serverNames) { if (getVdsStaticDao().getAllForHost(serverName).size() > 0 || getVdsStaticDao().getAllWithIpAddress(serverName).size() > 0) { return false; } } return true; }
Source:
public void update() { fboId = frameBuffersManager.getFBO(fboName).fboId; task.setFboId(fboId); START task.setFboName(fboName); END } I don't think the fboName is ever going to change, will it?

Target:
public void update() { fboId = frameBuffersManager.getFBO(fboName).fboId; task.setFboId(fboId); }
Source:
public static String getContext() { START return Bugsnag.getClient().getContext(); END } Ah - guessing that we are using static `Bugsnag` everywhere to make this whole interface possible. Any workarounds you can think of that would avoid depending on the static class?

Target:
public static String getContext() { return getClient().getContext(); }
Source:
public NameRevCommand add(Iterable<ObjectId> ids) throws MissingObjectException, JGitInternalException { START for (ObjectId id : ids) { END add(id); } return this; } No curly braces.

Target:
public NameRevCommand add(Iterable<ObjectId> ids) throws MissingObjectException, JGitInternalException { for (ObjectId id : ids) add(id); return this; }
Source:
START public ParseFirewallRules(Json json) { END super(json, TypeLiteral.get(FirewallRules.class)); } Remove the public modifier from all injection constructors.

Target:
ParseFirewallRules(Json json) { super(json, TypeLiteral.get(FirewallRules.class)); }
Source:
START public int value( ) { END return rand.nextInt(); } shouldn't be private for all the types ?

Target:
private int value() { return rand.nextInt(); }
Source:
private void setUpHttpLogging() throws IOException { if ( !getConfig().get( http_logging_enabled ) ) { return; } AsyncRequestLog requestLog = new AsyncRequestLog( dependencyResolver.resolveDependency( FileSystemAbstraction.class ), START config.get( GraphDatabaseSettings.log_timezone ).getZoneId(), END config.get( http_log_path ).toString(), config.get( http_logging_rotation_size ), config.get( http_logging_rotation_keep_number ) ); webServer.setRequestLog( requestLog ); } Static import, for consistency? :)

Target:
private void setUpHttpLogging() throws IOException { if ( !getConfig().get( http_logging_enabled ) ) { return; } AsyncRequestLog requestLog = new AsyncRequestLog( dependencyResolver.resolveDependency( FileSystemAbstraction.class ), config.get( log_timezone ).getZoneId(), config.get( http_log_path ).toString(), config.get( http_logging_rotation_size ), config.get( http_logging_rotation_keep_number ) ); webServer.setRequestLog( requestLog ); }
Source:
public void testIterationStart(LoopIterationEvent event) { JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables(); if ((getControlledByThread() && !jMeterVariables.isSameUserOnNextIteration()) START || getClearEachIteration()) { END log.debug("Initialise cookies from pre-defined list"); // No need to call clear setProperty(initialCookies.clone()); } } Does that mean `getClearEachIteration` impacts the result no matter of `getControlledByThread`?

Target:
public void testIterationStart(LoopIterationEvent event) { JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables(); if ((getControlledByThread() && !jMeterVariables.isSameUserOnNextIteration()) || (!getControlledByThread() && getClearEachIteration())) { log.debug("Initialise cookies from pre-defined list"); // No need to call clear setProperty(initialCookies.clone()); } }
Source:
private void appendRows(Map<Integer, Map<Integer, String>> rowsMap) { if (!rowsMap.isEmpty()) { START rowsMap.forEach((rowIndex, cellValueMap) -> { END model.insertRow(rowIndex, new ScenarioGridRow()); cellValueMap.forEach((columnIndex, cellValue) -> model.setCell(rowIndex, columnIndex, () -> new ScenarioGridCell(new ScenarioGridCellValue(cellValue)))); }); } } I believe using `forEach` ensures nothing is done if collection is empty. We should remove the outer `if`.

Target:
private void appendRows(Map<Integer, Map<Integer, String>> rowsMap) { rowsMap.forEach((rowIndex, cellValueMap) -> { model.insertRow(rowIndex, new ScenarioGridRow()); cellValueMap.forEach((columnIndex, cellValue) -> model.setCell(rowIndex, columnIndex, () -> new ScenarioGridCell(new ScenarioGridCellValue(cellValue)))); }); }
Source:
public static boolean isAllowedToSettings(String loginId, Project project) { if(loginId == null) { return false; } START User user = User.findByLoginId(loginId); END if(user == null || user.isAnonymous()) { return false; } if(user.isSiteManager() || ProjectUser.isManager(user.id, project.id)) { return true; } return false; } findByLoginId은 구조적으로 null을 return 하지 않음 (...) 방어코드를 줄이기 위해 NullUser Pattern이 쓰였는데 나중에 도입된거라 조금 아쉽게 만들어져 있긴 함

Target:
public static boolean isAllowedToSettings(String loginId, Project project) { if(loginId == null) { return false; } User user = User.findByLoginId(loginId); if(user.isAnonymous()) { return false; } if(user.isSiteManager() || ProjectUser.isManager(user.id, project.id)) { return true; } return false; }
Source:
public void invalidate() { mActionMode.invalidate(); START if (mMenu != null) { mMenu.invalidate(); } END } Either no brackets or put invalidate on its own line.

Target:
public void invalidate() { mActionMode.invalidate(); if (mMenu != null) mMenu.invalidate(); }
Source:
private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(myProjectSystemId); out.writeObject(myModuleName); out.writeObject(myRootDirPath); synchronized (myProxyDelegateLock) { if (myProxyDelegate == null) { // Compute the proxy object in case the proxy operation scheduled in the pooled thread is not yet completed. myProxyDelegate = reproxy(AndroidProject.class, START myDelegate);; END } } out.writeObject(myProxyDelegate); out.writeObject(mySelectedVariantName); out.writeObject(mySelectedTestArtifactName); } double semicolon

Target:
private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(myProjectSystemId); out.writeObject(myModuleName); out.writeObject(myRootDirPath); synchronized (myProxyDelegateLock) { if (myProxyDelegate == null) { // Compute the proxy object in case the proxy operation scheduled in the pooled thread is not yet completed. myProxyDelegate = reproxy(AndroidProject.class, myDelegate); } } out.writeObject(myProxyDelegate); out.writeObject(mySelectedVariantName); out.writeObject(mySelectedTestArtifactName); }
Source:
public MainEventHandler() { String connectionlessProtocolList = Context.getConfig().getString("status.ignoreOffline"); if (connectionlessProtocolList != null) { connectionlessProtocols.addAll(Arrays.asList(connectionlessProtocolList.split(","))); } START logEvents = Sets.newHashSet(Context.getConfig().getString("logger.events", DEFAULT_LOGGER_EVENTS).split(",")); END } I would prefer to use standard Java API instead and minimize dependencies usage when possible.

Target:
public MainEventHandler() { String connectionlessProtocolList = Context.getConfig().getString("status.ignoreOffline"); if (connectionlessProtocolList != null) { connectionlessProtocols.addAll(Arrays.asList(connectionlessProtocolList.split(","))); } logEvents = new HashSet<>(Arrays.asList( Context.getConfig().getString("logger.events", DEFAULT_LOGGER_EVENTS).split(","))); }
Source:
public E getRandomValue() throws NoSuchElementException { List<E> enumConstants = getFilteredList(); START if (enumConstants.isEmpty()) { END throw new NoSuchElementException("No enum element available for random picking."); } int randomIndex = random.nextInt(enumConstants.size()); return enumConstants.get(randomIndex); } this should be checked at construction time. If the guy is excluding all values from the enum, throw him a beautiful IllegalArgumentException. Hence, `getRandomValue` should not declare throwing NoSuchElementException

Target:
public E getRandomValue() { List<E> enumConstants = getFilteredList(); int randomIndex = random.nextInt(enumConstants.size()); return enumConstants.get(randomIndex); }
Source:
public void setColor(int color) { START this.setColor(color, END color); } remove this.

Target:
public void setColor(int color) { setColor(color, color); }
Source:
private boolean shouldBypassThrottling(HttpServletRequest request) { if (enableThrottlingIfHeader == null START || enableThrottlingIfHeader.length() == 0) { END return false; } return request.getHeader(enableThrottlingIfHeader) == null; } A HTTP header named "" should probably be treated as invalid, I think we should refuse it at construction, not try to coerce it here.

Target:
private boolean shouldBypassThrottling(HttpServletRequest request) { if (enableThrottlingIfHeader == null) return false; return request.getHeader(enableThrottlingIfHeader) == null; }
Source:
private void print(List<List<Object>> keys, List<ValueUpdater> updaters) { for (int i = 0; i < keys.size(); i++) { ValueUpdater valueUpdater = updaters.get(i); Object arg = ((CombinerValueUpdater) valueUpdater).getArg(); START LOG.debug("updateCount = {}, keys = => updaterArgs = {}", updateCount, keys.get(i), arg); END } } should this just print with info level since this is a debugState why make another hop to enable debug for this topology.

Target:
private void print(List<List<Object>> keys, List<ValueUpdater> updaters) { for (int i = 0; i < keys.size(); i++) { ValueUpdater valueUpdater = updaters.get(i); Object arg = ((CombinerValueUpdater) valueUpdater).getArg(); LOG.info("updateCount = {}, keys = => updaterArgs = {}", updateCount, keys.get(i), arg); } }
Source:
public MockSCMSource(String controllerId, String repository, List<SCMSourceTrait> traits) { START super(); END this.controllerId = controllerId; this.repository = repository; this.traits = new ArrayList<SCMSourceTrait>(traits); } can be omitted

Target:
public MockSCMSource(String controllerId, String repository, List<SCMSourceTrait> traits) { this.controllerId = controllerId; this.repository = repository; this.traits = new ArrayList<SCMSourceTrait>(traits); }
Source:
public MockSerializationResult(Proxifier proxifier, XStreamBuilder xstreambuilder, GsonSerializerBuilder gsonBuilder) { START super(proxifier); END this.response = new MockHttpServletResponse(); this.extractor = new DefaultTypeNameExtractor(); this.xstreambuilder = xstreambuilder; this.gsonBuilder = gsonBuilder; this.environment = new NullEnvironment(); } change to `this(proxifier, ...., new NullEnvironment())`

Target:
public MockSerializationResult(Proxifier proxifier, XStreamBuilder xstreambuilder, GsonSerializerBuilder gsonBuilder) { this(proxifier, xstreambuilder, gsonBuilder, new NullEnvironment()); }
Source:
START public LocalCacheFileSystem(FileSystem fs, FileSystemContext fsContext) { END super(fs); mFsContext = fsContext; // needs to be moved outside FileSystem constructor mLocalCacheManager = new LocalCacheManager(mFsContext); } I don't feel very good about this constructor. It seems counter-intuitive to have the fsContext as an argument here. There is already an fsContext embededed within the `fs` object. Is there a better way to access it?

Target:
public LocalCacheFileSystem(FileSystem fs, FileSystemContext fsContext) { super(fs); mFsContext = fsContext; }
Source:
public long getID() { START if (!isConnected()) { END throw new IllegalStateException("Session must be connected first."); } return mSessionID; } I'd remove the whole guard, and simply return null (mSessionID MUST be set to null when the session has left a realm already - and of course it must be null when the transport is detached then too)

Target:
public long getID() { return mSessionID; }
Source:
static public <T> Flux<T> fluxInlineIfPossibleAsObs(Callable<Flux<T>> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { // shortcut return Flux.defer(() -> { try { return function.call(); } catch (Exception e) { START return Mono.error(e); END } }); } else { return BackoffRetryUtility.fluxExecuteRetry(() -> function.call(), retryPolicy); } } Shouldn't this return `Flux.error(e)` ?

Target:
static public <T> Flux<T> fluxInlineIfPossibleAsObs(Callable<Flux<T>> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { // shortcut return Flux.defer(() -> { try { return function.call(); } catch (Exception e) { return Flux.error(e); } }); } else { return BackoffRetryUtility.fluxExecuteRetry(() -> function.call(), retryPolicy); } }
Source:
public int getTreeDepth() { START if (currVisit == null) END return 0; return currVisit.depth; } style nit: missing braces

Target:
public int getTreeDepth() { if (currVisit == null) { return 0; } return currVisit.depth; }
Source:
public Future<BlobInfo> getBlobInfo(String blobId) { FutureResult<BlobInfo> futureResult = new FutureResult<BlobInfo>(); OperationController oc = getOperationController(); if (oc == null) { completeOperation(futureResult, null, null, ROUTER_CLOSED_EXCEPTION); } else { oc.getBlobInfo(blobId, futureResult, null); } START return futureResult; END } Any reason not to do `getBlobInfo(blobId, null)` directly? `completeOperation()` handles null callbacks anyway. Similar question for similar functions.

Target:
public Future<BlobInfo> getBlobInfo(String blobId) { return getBlobInfo(blobId, null); }
Source:
public void shouldNotLogMessageAsInfo() { START logFeature.setLevel(DEPRECATED_LOGGER, "FATAL"); END System.setProperty(Framework.NUXEO_DEV_SYSTEM_PROP, "false"); logDeprecatedMessageAndVerify(false); } Talked in real, we can use `loggerClass` to do what we want.

Target:
public void shouldNotLogMessageAsInfo() { logDeprecatedMessageAndVerify(false); }