auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private int removeModule(IModule[] module, IProgressMonitor monitor) throws CoreException { IControllableServerBehavior beh = JBossServerBehaviorUtils.getControllableBehavior(getServer()); if( beh != null ) { IPublishController pc = (IPublishController)beh.getController(IPublishController.SYSTEM_ID); if( pc instanceof IPrimaryPublishController) { return ((IPrimaryPublishController)pc).removeModule(module, monitor); } } return IServer.PUBLISH_STATE_UNKNOWN; }

Target:
can't you reuse the server instance you collected in publishModule()?
Source:
public static String implodeStrings(String[] strings) { StringBuffer buffer = new StringBuffer(); for( int i = 0; i < strings.length; i++ ) buffer.append(strings[i]).append(','); return buffer.toString(); }

Target:
this doesn't belong here. If we don't have a generic concatenation method available in foundation already, then either use [StringUtils.join from commons-lang](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#join%28java.lang.Object[]%29) or [Joiner from guava](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Joiner.html)
Source:
public void performCancel(IProgressMonitor monitor) throws CoreException { super.performCancel(monitor); trackNewServerEvent(UsageEventType.FAILED_VALUE); }

Target:
we should not use constants for these values. Better to have a method return value as otherwise everything have to be recompiled to pick up a possible change
Source:
private IModuleResource[] getCleanedChildren(IModuleResource[] children) { // Depth-first cleaning ArrayList<IModuleResource> cleaned = new ArrayList<IModuleResource>(); IModuleResource tmp = null; for( int i = 0; i < children.length; i++ ) { tmp = getCleanedResource(children[i]); if( tmp != null ) cleaned.add(tmp); } return cleaned.toArray(new IModuleResource[cleaned.size()]); }

Target:
Should initialize list size with children.length
Source:
public boolean canRestartModule(IModule[] module) { if( module.length == 1 ) return true; return false; }

Target:
should module[0] == null be considered?
Source:
protected IModule promptForModule(ArrayList<IModule> modules) { if(modules.size() == 1 ) return modules.get(0); // TODO prompt return modules.get(0); }

Target:
protected method, IndexOutOfBoundException friendly
Source:
protected synchronized void forceStop() { System.out.println("Stopping in forcestop"); //$NON-NLS-1$ // just terminate the process. if( isProcessRunning()) { try { process.terminate(); addForceStopEvent(); } catch( DebugException e ) { addForceStopFailedEvent(e); } } process = null; getActualBehavior().setServerStopped(); nextStopRequiresForce = false; }

Target:
no system out please - use tracing.
Source:
private synchronized void handleProcessTerminatedEvent(ProcessTerminatedDebugListener listener) { // If there's a new process that's not equal to myProcess, // then the server is already starting again if( listener.myProcess != null && !listener.myProcess.equals(getProcess())) return; System.out.println(getProcess()); if( getServer().getServerState() != IServer.STATE_STOPPED) { stopPolling(); addProcessTerminatedEvent(); getActualBehavior().setServerStopped(); } DebugPlugin.getDefault().removeDebugEventListener(listener); processListener = null; process = null; nextStopRequiresForce = false; }

Target:
more unnecesaary println
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (MapzenApplication) getApplication(); app.inject(this); BugSenseHandler.initAndStartSession(this, "ebfa8fd7"); BugSenseHandler.addCrashExtraData("OEM", Build.MANUFACTURER); app = (MapzenApplication) getApplication(); setContentView(R.layout.base); initMapFragment(); gpsPromptDialogFragment = new MapzenGPSPromptDialogFragment(); initMapController(); initLocationClient(); initAlarm(); initSavedSearches(); }

Target:
looks like a bad merge ... assigning app is already included above.
Source:
public boolean isLoggedIn() { Token accessToken = getAccessToken(); return (accessToken != null) ? true : false; }

Target:
this can be simplified by: ``` return accessToken != null ```
Source:
private void animateViewTransitions() { fadeOutMotto(); delayButtonHandler = new Handler(); delayButtonHandler.postDelayed(new Runnable() { @Override public void run() { setMottoInvisible(); fadeInLoginView(); } } , 2000); }

Target:
why on separate line?
Source:
protected void onServiceConnectionLost(int errorCode) { Logger.e(TAG + "onServiceConectionLost for peer = " + mConnectionId + "error code =" + errorCode); if (GearAgentService.getConnection() != null) { GearAgentService.setConnection(null); } }

Target:
Is this if statement needed? Seems ok to just set to null.
Source:
public void onCreate_debugViewShouldBeVisible() throws Exception { enableDebugMode(Robolectric.application.getApplicationContext()); BaseActivity act = TestHelper.initBaseActivity(); assertThat(act.findViewById(R.id.debugging)).isVisible(); }

Target:
FYI `getApplicationContext()` is generally not needed unless you need to access the application from a non-application context. Here it just returns the same instance as `application` under the hood.
Source:
public AutoCompleteAdapter(Context context, BaseActivity act, String[] columns) { super(context, new MatrixCursor(columns), 0); this.context = context; this.app = (MapzenApplication) act.getApplication(); this.act = act; }

Target:
Field act does not exist in AutoCompleteAdapter?
Source:
private void initResultsFragment() { pagerResultsFragment = new PagerResultsFragment(); pagerResultsFragment.setAct(this); pagerResultsFragment.setApp(app); pagerResultsFragment.setAdapter(new SearchViewAdapter(this, getSupportFragmentManager())); // TODO remove fugly HACK pagerResultsFragment.setMapFragment(mapFragment); }

Target:
This shouldn't be necessary. The fragment can get the app from the activity.
Source:
public ExtensionBootstrapper(final ServletContext context, final Configuration configuration) { this.configuration = configuration; this.context = context; this.context.setAttribute(ExtensionContext.class.getName(), ExtensionController.getInstance()); ExtensionController.getInstance().init(this.context); }

Target:
do we need this anylonger?
Source:
public static boolean isValidEmailFormat ( String email ) { boolean isValid = false; try { InternetAddress emailAddress = new InternetAddress(email); emailAddress.validate(); isValid = true; } catch (AddressException ex) { isValid = false; logger.error("Email " + email + " is invalid"); } return isValid; }

Target:
i would change the log level here to `warn` (if not `info`). (`error` is usually reserved for severe issues that affect the application health. on the other hand, this is very much a normal operation of handling invalid user input - `info` sounds like a better fit imho)
Source:
private void onReceiveTimeout(ReceiveTimeout message, ActorRef self, ActorRef sender) throws Exception { if (logger.isInfoEnabled()) { logger.info("Conference Received Timeout, will stop conference now."); } onStopConference(new StopConference(SUPER_ADMIN_ACCOUNT_SID), self, sender); }

Target:
@maria-farooq Maybe we should differentiate the StopConference initiated by SuperAdmin and the one initiated by the timer. This is just an idea, not sure about the implementation but I think if it sounds feasible to you we should investigate it
Source:
public MockMediaGateway() { super(); system = context().system(); connectionToEndpointMap = new ConcurrentHashMap<ActorRef, ActorRef>(); connEndpointMap = new ConcurrentHashMap<String, String>(); }

Target:
considering this is Actor state, and concurrency should be already solved by Actor model, is there any particular intention on using ConcurrentHashMap??
Source:
public DeleteBulkFactory(Settings settings, MetadataExtractor metaExtractor, EsMajorVersion version) { // we only want a specific serializer for this particular bulk factory super(settings.copy().setSerializerValueWriterClassName(NoDataWriter.class.getName()), metaExtractor, version); }

Target:
Also not required if we use a new implementation of `BulkCommand`
Source:
public BufferedRestClient(Settings settings) { this.settings = settings; this.client = new RestClient(settings); String tempIndex = settings.getTargetResource(); if (tempIndex == null) { tempIndex = ""; } this.index = tempIndex; this.resource = new Resource(index); if (this.settings.getParentIdPath() != null) enableParentChildIndex = true; else enableParentChildIndex = false; trace = log.isTraceEnabled(); }

Target:
enableParentChildIndex = ( this.settings.getParentIdPath() != null ) ? true: false;
Source:
public void shutdownAndAwaitTerminationWithTimeoutExpireTest() throws InterruptedException { SingleThreadScheduler sts = new SingleThreadScheduler(); executeTestRunnables(sts, 1000 * 10); long start = Clock.accurateForwardProgressingMillis(); assertFalse(sts.shutdownAndAwaitTermination(DELAY_TIME)); System.out.println(Clock.accurateForwardProgressingMillis() - start); assertTrue(Clock.accurateForwardProgressingMillis() - start >= (DELAY_TIME - ALLOWED_VARIANCE)); }

Target:
Please remove System.out calls
Source:
public void setFailure(Throwable failure) { if (failure == null) { failure = new Exception(); } synchronized (resultLock) { this.failure = failure; if (! setDone()) { return; } } // call outside of lock listenerHelper.callListeners(); }

Target:
should probably change the overloaded variable name failure here.
Source:
public QueueSet getQueueSet(TaskPriority priority) { switch (priority) { case High: return highPriorityQueueSet; case Low: return lowPriorityQueueSet; default: throw new UnsupportedOperationException(); } }

Target:
this might be quicker as an if/else if/else.
Source:
public void stopAndDrainQueueInto(List<Runnable> removedTasks) { stopIfRunning(); synchronized (executeQueueRemoveLock) { clearQueue(executeQueue, removedTasks); } synchronized (scheduleQueue.getModificationLock()) { clearQueue(scheduleQueue, removedTasks); } }

Target:
does locking here really buy us anything? We are not locking when we .add on this queue so I would not think it would matter.
Source:
public String getBearerToken(HttpServletRequest request) { String authorization = request.getHeader("Authorization"); if (authorization == null) { throw new IllegalArgumentException("No access_token submitted!"); } return authorization.substring("Bearer ".length(), authorization.length()); }

Target:
shouldn't this method be static? it seems to me like an ordinary utility function. are there any reasons you have to manage a singleton instance of this class with spring?
Source:
public void addGame(@NotNull Game game) { GamePanel panel = new GamePanel(getGlassPane(), game); if(mTabbedPane.getTabCount() != 0) { mTabbedPane.addTab(game.getGameType() + mTabbedPane.getTabCount(), panel); } else{ mTabbedPane.addTab(game.getGameType(), panel); } mTabbedPane.setSelectedComponent(panel); mCardLayout.show(mCardPanel, KEY_TABS); }

Target:
We don't need this change, and even if we decide we want it, it needs to be in a separate commit
Source:
public TaskScheduler resolveTaskScheduler() { return resolveSchedulerBean(TaskScheduler.class); }

Target:
Can we make this package private instead?
Source:
public void clearKey(String tabName, String key) { Map<String, Object> tab = getTab(tabName); tab.remove(key); }

Target:
this only needs to be package visible
Source:
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getClassLoader().getResource("org/springframework/web/servlet") != null; }

Target:
`context.getClassLoader()` can return null
Source:
public String handledTypeMismatchException() { try { throw new TypeMismatchException("Test", String.class); } catch (TypeMismatchException ex) { bugsnag.notify(ex); } return "The exception was handled"; }

Target:
Are these `return`s used anywhere? If not, might as well make the method `void`. Applies throughout.
Source:
Configuration(String apiKey) { this.apiKey = apiKey; // Add built-in callbacks addCallback(new AppCallback(this)); addCallback(new DeviceCallback()); DeviceCallback.initializeCache(); if (ServletCallback.isAvailable()) { addCallback(new ServletCallback()); } sessionDelivery = new AsyncHttpDelivery(); ((HttpDelivery) sessionDelivery).setEndpoint("https://sessions.bugsnag.com"); }

Target:
Any reason you aren't initializing this at declaration time?
Source:
SessionPayload(Collection<SessionCount> sessionCounts, Configuration configuration) { this.sessionCounts.addAll(sessionCounts); diagnostics = new Diagnostics(configuration); }

Target:
would it be better here to just initialize the `ArrayList` with `sessionCounts` instead of calling `addAll`? Presumably initializing it would result in potentially less array resizing
Source:
public List<Exception> getExceptions() { List<Exception> exceptions = new ArrayList<Exception>(); Throwable currentThrowable = throwable; while (currentThrowable != null) { exceptions.add(new Exception(config, currentThrowable)); currentThrowable = currentThrowable.getCause(); } return exceptions; }

Target:
This either needs to be `protected` or `Exception` needs to be public.
Source:
public List<ThreadState> getThreads() { return config.sendThreads ? ThreadState.getLiveThreads(config) : null; }

Target:
This either needs to be `protected` or `ThreadState` needs to be public.
Source:
public Report(Configuration config, Throwable throwable) { this.config = config; this.throwable = throwable; }

Target:
If the expectation is that this always get built from Bugsnag.buildReport we should remove the `public` here to make this package protected. This will enforce the API usage which will make it easier to maintain and refactor in the future.
Source:
public Table getTable(final String dbName, final String tableName, boolean throwException) throws HiveException { return this.getTable(dbName, tableName, throwException, true); }

Target:
Why is this change? Should not this minimally depend on if this table is transactional or not? What happens if we call it on a non-transactional table?
Source:
public synchronized void addMetric(ReplicationMetric replicationMetric) throws SemanticException { if (metricMap.size() > maxSize) { throw new SemanticException("Metrics are not getting collected. "); } else { if (metricMap.size() > 0.8 * maxSize) { //soft limit LOG.warn("Metrics cache is more than 80 % full. Will start dropping metrics once full. "); } metricMap.put(replicationMetric.getScheduledExecutionId(), replicationMetric); } }

Target:
We fail on addMetric() time only when size (of Concurrent Policies) hit the max. If we have say only 10 policies we are trying to failover we will not hit the max criteria. If sink is broken, addMetric() will never fail and we will not get the required metric for controlled failover ever?
Source:
public List<AtlasObjectId> getItemsToExport(AtlasReplInfo atlasReplInfo, String srcAtlasServerName) { List<AtlasObjectId> atlasObjectIds = new ArrayList<>(); final String qualifiedName = getQualifiedName(srcAtlasServerName, atlasReplInfo.getSrcDB()); atlasObjectIds.add(new AtlasObjectId(ATLAS_TYPE_HIVE_DB, ATTRIBUTE_QUALIFIED_NAME, qualifiedName)); return atlasObjectIds; }

Target:
Do you need all methods to be public
Source:
public void testWithNonZeroFraction() throws SemanticException { if (intType) { testNullCase("100.1"); } }

Target:
nit: in case throwing an exception from a testcase: it's better to throw plain Exception - then we never have to go back there
Source:
DataSketchesFunctions() { this.sketchClasses = new ArrayList<SketchDescriptor>(); this.descriptors = new ArrayList<HiveUDFPlugin.UDFDescriptor>(); registerHll(); registerCpc(); registerKll(); registerTheta(); registerTuple(); registerQuantiles(); registerFrequencies(); buildCalciteFns(); buildDescritors(); }

Target:
`private`?
Source:
private boolean shouldDump(Path previousDumpPath) throws IOException { //If no previous dump means bootstrap. So return true as there was no //previous dump to load if (previousDumpPath == null) { return true; } else { FileSystem fs = previousDumpPath.getFileSystem(conf); if (fs.exists(previousDumpPath)) { FileStatus[] latestUpdateStatuses = fs.listStatus(previousDumpPath); for (FileStatus status : latestUpdateStatuses) { if (status.getPath().getName().equalsIgnoreCase(ReplUtils.LOAD_ACKNOWLEDGEMENT)) { return true; } } } } return false; }

Target:
Should we just use return fs.exists(new Path(previousDumpPath, ReplUtils.LOAD_ACKNOWLEDGEMENT));
Source:
public SCOPE getScope(){ if (isInReplicationScope()){ if (isMetadataOnly() || isMetadataOnlyForExternalTables()){ return SCOPE.MD_ONLY; } else { return SCOPE.REPL; } } else { return SCOPE.NO_REPL; } }

Target:
No need to change this
Source:
public final void unSetClockBit() { long val = state.get(); while (State.isClockBitSet(val) && !state.compareAndSet(val, State.unSetClockBit(val))) { val = state.get(); } }

Target:
There isn't really a need for any unSet as each check against the clockBit (observed) should reset the clock bit.
Source:
public void notifyLock(LlapCacheableBuffer buffer) { // We do not proactively remove locked items from the heap, and opportunistically try to // remove from the list (since eviction is mostly from the list). If eviction stumbles upon // a locked item in either, it will remove it from cache; when we unlock, we are going to // put it back or update it, depending on whether this has happened. This should cause // most of the expensive cache update work to happen in unlock, not blocking processing. if (buffer.cacheAttribute == null || buffer.cacheAttribute.getIndex() != IN_LIST || !listLock.tryLock()) { return; } removeFromListAndUnlock(buffer); }

Target:
Question: what scenario can lead to a null cacheAttribute?
Source:
public String generateInitFileName(String toVersion) throws HiveMetaException { if (toVersion == null) { toVersion = getHiveSchemaVersion(); } String initScriptName = INIT_FILE_PREFIX + toVersion + "." + dbType + SQL_FILE_EXTENSION; // check if the file exists File file = new File(getMetaStoreScriptDir() + File.separatorChar + initScriptName); if (!(file.exists())) { throw new HiveMetaException("Unknown version specified for initialization: " + toVersion, new NoSuchFileException(file.getAbsolutePath())); } return initScriptName; }

Target:
nit. enclosing () for file not needed
Source:
public static void unregisterLoggingContext() { // Remove the keys added, don't use clear, as it may clear all other things which are not intended to be removed. MDC.remove(SESSIONID_LOG_KEY); MDC.remove(QUERYID_LOG_KEY); MDC.remove(OPERATIONLOG_LEVEL_KEY); l4j.info("Unregistered logging context."); if (MDC.get(OPERATIONLOG_LEVEL_KEY) != null) { throw new RuntimeException("Keys removal failed from thread context MDC"); } }

Target:
why do we need this check here ?
Source:
MetaStoreConfigAuthenticationProviderImpl(Configuration conf) throws AuthenticationException { userName = MetastoreConf.getVar(conf, MetastoreConf.ConfVars.THRIFT_AUTH_CONFIG_USERNAME); password = MetastoreConf.getVar(conf, MetastoreConf.ConfVars.THRIFT_AUTH_CONFIG_PASSWORD); if (null == userName || userName.isEmpty()) { throw new AuthenticationException("No username specified in " + MetastoreConf.ConfVars.THRIFT_AUTH_CONFIG_USERNAME); } if (null == password || password.isEmpty()) { throw new AuthenticationException("No password specified in " + MetastoreConf.ConfVars.THRIFT_AUTH_CONFIG_USERNAME); } }

Target:
password can be empty
Source:
public Table get_table(final String dbname, final String name) throws MetaException, NoSuchObjectException { String[] parsedDbName = parseDbName(dbname, conf); return getTableInternal( parsedDbName[CAT_NAME], parsedDbName[DB_NAME], name, null, null, false, null); }

Target:
Should this be null? Does that internally default to "hive" in getTableColumnStatistics()? Or is this safe because we are not getting column stats in this case?
Source:
public LlapManagementProtocolClientImpl create(LlapServiceInstance serviceInstance) { LlapManagementProtocolClientImpl client = new LlapManagementProtocolClientImpl(conf, serviceInstance.getHost(), serviceInstance.getManagementPort(), retryPolicy, socketFactory); return client; }

Target:
Why storing it in client instead of returning it directly (which would be consistent with basicInstance)?
Source:
TimedAverageMetrics(int windowDataSize, long windowTimeSize) { this(windowDataSize, windowTimeSize, System.nanoTime()); }

Target:
Using the current time as default time essentially makes all values valid within the time window. We therefore aggregate just zeros here. Wouldn't it make sense to initialize this with zero to mark all entries "outside of the window" initially?
Source:
public String getQueryId() throws SQLException { if (stmtHandle == null) { return null; } try { return client.GetQueryId(new TGetQueryIdReq(stmtHandle)).getQueryId(); } catch (TException e) { throw new SQLException(e); } }

Target:
what about concurrent closure of statement ?
Source:
ConstraintFileType(String name, String prefix) { this.name = name; this.prefix = prefix; }

Target:
Why do we need this change? I don't see this constructor being used outside this class.
Source:
public TableType tableType() { if (isView()) { return TableType.VIRTUAL_VIEW; } else if (isMaterializedView()) { return TableType.MATERIALIZED_VIEW; } return table.getTableType(); }

Target:
No need to check view type above. table.getTableType() suffice.
Source:
public IMetaStoreClient getMSC() { connectionStats.incrementMetastoreCalls(); return msClient; }

Target:
is this required to be public? exposing the metastore client via streaming connection API seems to be risky as clients can mess with it.
Source:
private void verifyIfCkptSet(Map<String, String> props, String dumpDir) { assertTrue(props.containsKey(ReplUtils.REPL_CHECKPOINT_KEY)); assertTrue(props.get(ReplUtils.REPL_CHECKPOINT_KEY).equalsIgnoreCase(dumpDir)); }

Target:
for some file systems the path is case sensitive.
Source:
public void shouldNotCreateDirectoryForNonNativeTableInDumpDirectory() throws Throwable { String createTableQuery = "CREATE TABLE custom_serdes( serde_id bigint COMMENT 'from deserializer', name string " + "COMMENT 'from deserializer', slib string COMMENT 'from deserializer') " + "ROW FORMAT SERDE 'org.apache.hive.storage.jdbc.JdbcSerDe' " + "STORED BY 'org.apache.hive.storage.jdbc.JdbcStorageHandler' " + "WITH SERDEPROPERTIES ('serialization.format'='1') " + "TBLPROPERTIES ( " + "'hive.sql.database.type'='METASTORE', " + "'hive.sql.query'='SELECT \"SERDE_ID\", \"NAME\", \"SLIB\" FROM \"SERDES\"')"; WarehouseInstance.Tuple bootstrapTuple = primary .run("use " + primaryDbName) .run(createTableQuery).dump(primaryDbName, null); Path cSerdesTableDumpLocation = new Path(bootstrapTuple.dumpLocation + Path.SEPARATOR + primaryDbName + Path.SEPARATOR + "custom_serdes"); FileSystem fs = cSerdesTableDumpLocation.getFileSystem(primary.hiveConf); assertFalse(fs.exists(cSerdesTableDumpLocation)); }

Target:
instead of path separator create new path to make it generic
Source:
protected static void closeStmt(Statement stmt) { try { if (stmt != null && !stmt.isClosed()) { stmt.close(); } } catch (SQLException e) { LOG.warn("Failed to close statement " + e.getMessage()); } }

Target:
Access can be private for both close methods. Also, can we merge them into one method?
Source:
private void verifyResultsInReplica(List<String> selectStmtList, List<String[]> expectedValues) throws Throwable { for (int idx = 0; idx > selectStmtList.size(); idx++) { replica.run("use " + replicatedDbName) .run(selectStmtList.get(idx)) .verifyResults(expectedValues.get(idx)); } }

Target:
This loop will never execute as condition is >.
Source:
public void alterCatalog(String catName, Catalog cat) throws MetaException, InvalidOperationException { rawStore.alterCatalog(catName, cat); catName = catName.toLowerCase(); sharedCache.alterCatalogInCache(StringUtils.normalizeIdentifier(catName), cat); }

Target:
StringUtils.normalizeIdentifier does lowercase as well, so this is not necessary. Same issue is present in getDatabase (but not introduced by your patch).
Source:
public String getReplPolicy() { if (dbName == null) { return null; } else if (tableName == null) { return dbName.toLowerCase() + ".*"; } else { return dbName.toLowerCase() + "." + tableName.toLowerCase(); } }

Target:
Better to check for blank string as well. StringUtils.isEmpty() can be used.
Source:
public ReplTxnWork(String dbName, String tableName, Long txnId, OperationType type) { this.txnIds = Lists.newArrayList(); this.txnIds.add(txnId); this.dbName = dbName; this.tableName = tableName; this.operation = type; }

Target:
Shall initialise using newArrayList(txnId) instead of 2 statements.
Source:
public static ValidWriteIdList getTableValidWriteIdList(Configuration conf, String fullTableName) { String txnString = conf.get(ValidTxnWriteIdList.VALID_TABLES_WRITEIDS_KEY); ValidTxnWriteIdList validTxnList = new ValidTxnWriteIdList(txnString); return validTxnList.getTableWriteIdList(fullTableName); }

Target:
should this do something meaningful if key is not found? Seems like that would be an error condition. This seems like it may mask issues.
Source:
public ConstraintEventsIterator(String dumpDirectory, HiveConf hiveConf) throws IOException { Path path = new Path(dumpDirectory); fs = path.getFileSystem(hiveConf); dbDirs = fs.listStatus(new Path(dumpDirectory), EximUtil.getDirectoryFilter(fs)); currentDbIndex = 0; if (dbDirs.length != 0) { currentConstraintIndex = 0; constraintFiles = listConstraintFilesInDBDir(fs, dbDirs[0].getPath()); } }

Target:
Constraint files listing for 0th Db also can be done inside hasNext to avoid duplicate code here.
Source:
static Path getCMPath(Configuration conf, String checkSum) throws IOException, MetaException { String newFileName = checkSum; int maxLength = conf.getInt(DFSConfigKeys.DFS_NAMENODE_MAX_COMPONENT_LENGTH_KEY, DFSConfigKeys.DFS_NAMENODE_MAX_COMPONENT_LENGTH_DEFAULT); if (newFileName.length() > maxLength) { newFileName = newFileName.substring(0, maxLength-1); } return new Path(cmroot, newFileName); }

Target:
Just noticed that those exceptions are not thrown by this method and as we making changes in this code, thought may be make these changes as well. If you don't want to make those changes part of this path, that's fine as well.
Source:
private static String getMetastoreJdbcPasswd(HiveConf conf) { try { return ShimLoader.getHadoopShims().getPassword(conf, HiveConf.ConfVars.METASTOREPWD.varname); } catch (IOException io) { } return null; }

Target:
shouldn't this be throwing the exception ?
Source:
private void setupHistory() throws IOException { if (this.history != null) { return; } this.history = new FileHistory(new File(getOpts().getHistoryFile())); // add shutdown hook to flush the history to history file and to close all open connections ShutdownHookManager.addShutdownHook(new Runnable() { @Override public void run() { try { history.flush(); } catch (IOException e) { error(e); } finally { close(); } } }); }

Target:
This shutdown hook is being added as part of setupHistory method, using that for close is not very clean. Maybe create a separate function for adding shutdown hook ?
Source:
public TJobExecutionStatus forStatus(String status) { try { TezStatus tezStatus = TezStatus.valueOf(status); switch (tezStatus) { case SUBMITTED: case INITING: case RUNNING: return TJobExecutionStatus.IN_PROGRESS; default: return TJobExecutionStatus.COMPLETE; } } catch (IllegalArgumentException ex) { LOG.debug("Could not understand the status from tez execution engine : " + status); return TJobExecutionStatus.NOT_AVAILABLE; } }

Target:
I think LOG.warn might be more suited for this message. We don't expect this to happen.
Source:
private static GroupType buildProjectedGroupType( GroupType originalType, List<Type> types) { return new GroupType(originalType.getRepetition(), originalType.getName(), types); }

Target:
(minor suggestion) I think this func along with `projectLeafTypes` can be combined into one to make it more clear: `private static GroupType buildProjectedGroupType(GroupType originalType, List<String> groupPaths, String currentPath) { .... } ` Perhaps return null if none of the group fields get included.
Source:
public void write(JsonGenerator generator) throws IOException { generator.writeStartObject(); generator.writeStringField("type", type); switch ("type") { case "NOT": writeField(generator, "field", fields.get(0)); break; default: writeField(generator, "fields", fields); } generator.writeEndObject(); }

Target:
Should be `switch (type)`?
Source:
public static AcidStats parseAcidStats(Reader reader) { if (reader.hasMetadataValue(ACID_STATS)) { String statsSerialized; try { ByteBuffer val = reader.getMetadataValue(ACID_STATS) .duplicate(); statsSerialized = utf8Decoder.decode(val).toString(); } catch (CharacterCodingException e) { throw new IllegalArgumentException("Bad string encoding for " + ACID_STATS, e); } return new AcidStats(statsSerialized); } else { return null; } }

Target:
nit: bad alignment
Source:
public HivePrincipal getHivePrincipal(PrincipalDesc principal) throws HiveException { return AuthorizationUtils.getHivePrincipal(principal); }

Target:
It looks weird. Do we still need `getHivePrincipal` for the `AuthorizationUtils`? We can move the implementation of these three APIs to the translator. And remove that in `AuthorizationUtils`.
Source:
public InstanceOfExpr(final Expression expression, final ReferenceType type) { this(null, expression, type); }

Target:
In all the other nodes, all the constructors call the most specific constructor to avoid constructor spaghetti. That would mean the this-call gets "null" at the end for example.
Source:
public void commentBeforeBlock() { Statement st = StaticJavaParser.parseBlock( "// a comment before parent" + System.lineSeparator() + "{ if (file != null) }"); assertTrue(st.getComment().isPresent()); assertTrue(st.getOrphanComments().isEmpty()); assertEquals(1, st.getAllContainedComments()); }

Target:
Im confused how this works... st.getAllContainedComments() returns a list RIGHT? so how can a list be equal to 1? shouldnt it be : `st.getAllContainedComments.size()`
Source:
void getters() { assertEquals("getValue", getterName(Object.class, "value")); assertEquals("isBlue", getterName(Boolean.TYPE, "isBlue")); assertEquals("isBlue", getterName(Boolean.TYPE, "blue")); assertEquals("getBlue", getterName(Boolean.class, "blue")); assertEquals("getIsBlue", getterName(Boolean.class, "isBlue")); }

Target:
Yeah, I thought the subtle capitalization change might cause misunderstanding ;-) I think it's more expressive because "TYPE" vs "class" is not as direct as `boolean` vs `Boolean`... although you could argue against it because of the subtle caps. Make it as you like.
Source:
default boolean hasParametersOfType(String... paramTypes) { return getParameters().stream() .map(p -> p.getType().asString()) .collect(toList()) .equals(Stream.of(paramTypes).collect(toList())); }

Target:
Arrays,asList prevents a stream/collect
Source:
void noModifiersInForEachBesideFinal() { ParseResult<Statement> result = javaParser.parse(STATEMENT, provider("for(static transient int i : nums){}")); assertProblems(result, "(line 1,col 5) 'static' is not allowed here.", "(line 1,col 5) 'transient' is not allowed here.", "(line 1,col 1) A foreach statement's variable declaration may have at most one 'final' modifier, and no other modifiers. Given: [static , transient ]."); }

Target:
Hmmm, three messages are a little overkill?
Source:
public void parseModuleDeclaration() { JavaParser.getStaticConfiguration().setLanguageLevel(JAVA_9); JavaParser.parseModuleDeclaration("module X {}"); }

Target:
Is it good to change the static configuration in a test?
Source:
public Iterable<Node> treeIterable(TreeTraversal traversal) { return () -> treeIterator(traversal); }

Target:
Wow!
Source:
private static <T extends Node> T simplifiedParse(ParseStart<T> context, Provider provider) { ParseResult<T> result = new JavaParser(staticConfiguration).parse(context, provider); if (result.isSuccessful()) { considerInjectingSymbolResolver(result, staticConfiguration); return result.getResult().get(); } throw new ParseProblemException(result.getProblems()); }

Target:
This is already done in the other method.
Source:
public void arrayType() { Type type = parseType("int[]"); assertTrue(type.isArrayType()); ArrayType arrayType = type.asArrayType(); final ArrayType[] s = new ArrayType[1]; type.ifArrayType(t -> s[0] = (ArrayType)t); assertNotNull(s[0]); }

Target:
Huh? The point is that a cast isn't necessary
Source:
public void ifBlockComment(Consumer<BlockComment> action) { if (isBlockComment()) { action.accept(asBlockComment()); } }

Target:
this one could be empty I guess
Source:
public static boolean isComment(int kind) { return getCategory(kind)== JavaToken.Category.COMMENT; }

Target:
for the other categories you are using just the name (COMMENT instead of JavaToken.Category.COMMENT), also a space before `==`
Source:
public String toText() { StringBuffer sb = new StringBuffer(); elements.forEach(e -> sb.append(e.toText())); return sb.toString(); }

Target:
Replace with StringBuilder here too
Source:
public default <A extends Statement> A addAndGetStatement(A statement) { getStmts().add(statement); statement.setParentNode((Node) this); return statement; }

Target:
Intellij tells me that "public" is not necessary here.
Source:
public VariableDeclarationExpr(final Type type, VariableDeclarator var) { setType(type); List<VariableDeclarator> vars = new ArrayList<>(); vars.add(var); setVars(vars); }

Target:
Why not using Arrays.asList(var) ? or asList(var) with Arrays.asList in a static import
Source:
public Position withColumn(int column) { return new Position(line, column); }

Target:
should we use "this" on line to make more evident what we are doing
Source:
private DB selectDatabase(Mongo mongo) { DB db = mongo.getDB(dbName); // MongoDB defaults are insane, set a reasonable write concern explicitly. MK. // But we would be insane not to override this when writing lock records. LB. db.setWriteConcern(WriteConcern.JOURNALED); if (username != null) { if(authDbName != null) { // authentificating to db which gives access to all other dbs (role - readWriteAnyDatabase) // by default in mongo it should be "admin" DB authDb = mongo.getDB(authDbName) authDb.authenticate(username, password.toCharArray()); } else { db.authenticate(username, password.toCharArray()); } } return db; }

Target:
A missing semicolon [causes the project fail to compile](https://travis-ci.org/michaelklishin/quartz-mongodb/jobs/16463278).
Source:
public synchronized RegisteredService save(final RegisteredService registeredService, final boolean publishEvent) { publishEvent(new CasRegisteredServicePreSaveEvent(this, registeredService)); var r = this.serviceRegistry.save(registeredService); this.services.put(r.getId(), r); saveInternal(registeredService); if (publishEvent) { publishEvent(new CasRegisteredServiceSavedEvent(this, r)); } return r; }

Target:
Is this change needed?
Source:
public ListFactoryBean ldapPasswordSynchronizationAuthenticationPostProcessorListFactoryBean() { val bean = new ListFactoryBean() { @Override protected void destroyInstance(final List list) { list.forEach(Unchecked.consumer(postProcessor -> { ((DisposableBean) postProcessor).destroy(); })); } }; bean.setSourceList(new ArrayList()); return bean; }

Target:
```suggestion bean.setSourceList(new ArrayList<>()); ```
Source:
private void revokeToken(final OAuth20RefreshToken token) { LOGGER.debug("Revoking token [{}]", token); getOAuthConfigurationContext().getTicketRegistry().deleteTicket(token); token.getAccessTokens().forEach(item-> { LOGGER.debug("Revoking Access Token related to Refresh Token [{}]", item, token); getOAuthConfigurationContext().getTicketRegistry().deleteTicket(item); }); }

Target:
Remove log line, Call `revokeToken` instead in a lambda to avoid duplicate code.
Source:
protected boolean clientNeedAuthentication(final HttpServletRequest request, final HttpServletResponse response) { val clientId = OAuth20Utils.getClientIdAndClientSecret(new JEEContext(request, response, sessionStore)).getLeft(); val registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(servicesManager, clientId); if (clientId.isEmpty() || registeredService == null) { return true; } return OAuth20Utils.doesServiceNeedAuthentication(registeredService); }

Target:
If client-id is undefined, return immediately and do not look up the service in registry.
Source:
protected ProxyGrantingTicket produceTicketWithAdequateExpirationPolicy( final RegisteredServiceProxyGrantingTicketExpirationPolicy servicePgtPolicy, final ServiceTicket serviceTicket, final Authentication authentication, final String pgtId) { if (servicePgtPolicy != null) { LOGGER.trace("Overriding proxy-granting ticket policy with the specific policy: [{}]", servicePgtPolicy); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, new HardTimeoutExpirationPolicy(servicePgtPolicy.getMaxTimeToLiveInSeconds())); } else { LOGGER.trace("Using default ticket-granting ticket policy for proxy-granting ticket"); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, this.ticketGrantingTicketExpirationPolicy.buildTicketExpirationPolicy()); } }

Target:
```suggestion } LOGGER.trace("Using default ticket-granting ticket policy for proxy-granting ticket"); return serviceTicket.grantProxyGrantingTicket(pgtId, authentication, this.ticketGrantingTicketExpirationPolicy.buildTicketExpirationPolicy()); ```
Source:
public void onEvent(final CacheEvent<? extends String, ? extends Ticket> event) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Event Type: {}, Ticket Id: {}", event.getType().name(), event.getKey()); } }

Target:
The if condition here should be unnecessary unless `event.getXyz()` calls are expensive?
Source:
void verifyGroovyResourceClasspathExecution() { try { val resource = new ClassPathResource("ScriptingUtilsTestGroovyScript.groovy"); val result = ScriptingUtils.executeGroovyScript(resource, "process", String.class, "casuser"); assertEquals("casuser", result); } catch (final Exception e) { throw new AssertionError(e.getMessage(), e); } }

Target:
`() throws Exception`
Source:
public static RedisConnectionFactory newRedisConnectionFactory(final BaseRedisProperties redis) { LOGGER.debug("Loaded Redis configuration {}", redis); final RedisConfiguration redisConfiguration = redis.getSentinel() == null ? getStandaloneConfig(redis) : getSentinelConfig(redis); val factory = new LettuceConnectionFactory(redisConfiguration, getRedisPoolConfig(redis)); return factory; }

Target:
Use `val` or `var`?
Source:
public void createX509Credential() throws IOException, CertificateException { val request = new MockHttpServletRequest(); try (val inStream = new FileInputStream(new ClassPathResource("ldap-crl.crt").getFile())) { X509Certificate[] certs = {CertUtils.readCertificate(inStream)}; request.setAttribute(REQUEST_ATTRIBUTE_X509_CERTIFICATE, certs); val cred = factory.fromRequest(request, null).iterator().next(); assertTrue(cred instanceof X509CertificateCredential); } }

Target:
val?
Source:
public String decodeSamlAuthnRequest(final String encodedRequestXmlString) { if (StringUtils.isEmpty(encodedRequestXmlString)) { return null; } final byte[] decodedBytes = EncodingUtils.decodeBase64(encodedRequestXmlString); if (decodedBytes == null) { return null; } final String inflated = CompressionUtils.inflate(decodedBytes); if (!StringUtils.isEmpty(inflated)) { return inflated; } else { return new String(decodedBytes, StandardCharsets.UTF_8); } }

Target:
This is fine, but the else clause is redundant here.
Source:
protected void createDefaultEndStates(final Flow flow) { createRedirectUnauthorizedServiceUrlEndState(flow); createServiceErrorEndState(flow); createRedirectEndState(flow); createPostEndState(flow); createInjectHeadersActionState(flow); createGenericLoginSuccessEndState(flow); createServiceWarningViewState(flow); createMfaDeniedViewState(flow); createMfaUnavailableViewState(flow); createEndWebflowEndState(flow); }

Target:
Does this really belong here? I think a better home would perhaps be the thing that configures the mfa flow in general. It would be best to try to keep the flow defn as _pure_ as possible, and only interject when a feature is actually used.
Source:
public static String CreateTmpFile(String fileName) { fileName = isFilenameValid(fileName) ? fileName : KEY_FILENAME; File tempFile = getUniqueFile(fileName); try { tempFile.createNewFile(); } catch (IOException e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(); return ""; } return tempFile.getPath(); }

Target:
don catch exception, better fail than return ""
Source:
public static File getUniqueFile(String fileName) { File tempFile = null; int i = 0; try { do { tempFile = new File(TMP_DIR + DIR_SEPARATOR + fileName + "-" + i + "." + KEY_FILENAME_EXT); i++; } while (tempFile.exists()); } // Catch exception if any catch (Exception e) { System.err.println("Error: " + e.getMessage()); } return tempFile; }

Target:
dont catch, better fail
Source:
public boolean equals(EmbeddedServerInfo info) { if (this.serverName.equals(info.serverName) && this.userDir.getAbsolutePath().equals(info.userDir.getAbsolutePath()) && this.outputDir.getAbsolutePath().equals(info.outputDir.getAbsolutePath())) { return true; } return false; }

Target:
Technically I think you should use the get methods on `info` to access its variables.
Source:
public SRResult similarity(String phrase1, String phrase2, Language language, boolean explanations) throws DaoException { if (phrase1 == null || phrase2 == null) { throw new NullPointerException("Null phrase passed to similarity"); } try { TIntDoubleHashMap scores1 = getConceptVector(phrase1, language); TIntDoubleHashMap scores2 = getConceptVector(phrase2, language); double sim = SimUtils.cosineSimilarity(scores1, scores2); return new SRResult(sim); // TODO: normalize } catch (WikapidiaException e) { throw new DaoException(e); } }

Target:
this should be normalize(new SRResult(sim))
Source:
public Integer getUriOpenedSockets(String uri) { Integer numberOpenedSockets = 0; for (WebSocketDispatcher dispatcher : dispatchers) { numberOpenedSockets += dispatcher.getNumberOpenedSocketsByUri(uri); } return numberOpenedSockets; }

Target:
need to be protected against concurrent accesses
Source:
public Map<String, Integer> getNumberOpenedSockets() { Map<String, Integer> numberOpenedSocketByUri = new LinkedHashMap<>(); for (Map.Entry<String, List<Socket>> socketByUri : socketsByUri.entrySet()) { numberOpenedSocketByUri.put(socketByUri.getKey(), socketByUri.getValue().size()); } return numberOpenedSocketByUri; }

Target:
must be protected against concurrent accesses
Source:
public Integer getNumberOpenedSocketsByUri(String uri) { Integer numberOpenedSocketForUri = 0; if (socketsByUri.containsKey(uri)) { numberOpenedSocketForUri = socketsByUri.get(uri).size(); } return numberOpenedSocketForUri; }

Target:
concurrency issue too
Source:
public static Organization createDtoFromDbo(DBOOrganization dbo) { Organization dto = new Organization(); dto.setCreatedBy("" + dbo.getCreatedBy()); dto.setCreatedOn(dbo.getCreatedOn()); dto.setId(""+dbo.getId()); dto.setName(dbo.getName()); return dto; }

Target:
String.valueOf
Source:
public static String createFlagIssue(JiraClient jiraClient, String principalId, String displayName, String dataObjectId) { Map<String,String> params = new HashMap<String,String>(); params.put(JIRA_PRINCIPAL_ID_ISSUE_FIELD_NAME, principalId); params.put(JIRA_USER_DISPLAY_NAME_ISSUE_FIELD_NAME, displayName); params.put(JIRA_SYNAPSE_ENTITY_ID_FIELD_NAME, dataObjectId); CreatedIssue createdIssue = createIssue(jiraClient, JIRA_FLAG_ISSUE_TYPE_NAME, FLAG_SUMMARY, params); return (String) createdIssue.getKey(); }

Target:
Cast to string can be removed
Source:
public MigratableTableTranslation<DBOVerificationState, DBOVerificationState> getTranslator() { return new BasicMigratableTableTranslation<DBOVerificationState>() { @Override public DBOVerificationState createDatabaseObjectFromBackup(DBOVerificationState backup) { if (backup.getEtag() == null) { backup.setEtag(UUID.randomUUID().toString()); } return backup; } }; }

Target:
remove
Source:
public void deleteVerificationSubmission(long verificationId) { wrapSubmissionNotFound(verificationId, () -> { MapSqlParameterSource param = new MapSqlParameterSource(); param.addValue(COL_VERIFICATION_SUBMISSION_ID.toLowerCase(), verificationId); basicDao.deleteObjectByPrimaryKey(DBOVerificationSubmission.class, param); return false; }); }

Target:
not needed here
Source:
public DLNAThumbnailInputStream getThumbnailInputStream() throws IOException { if (thumbURL != null) { return DLNAThumbnailInputStream.toThumbnailInputStream( FileUtil.isUrl(thumbURL) ? downloadAndSend(thumbURL, true) : new FileInputStream(thumbURL) ); } else { try (DLNAThumbnailInputStream dtis = super.getThumbnailInputStream()) { return dtis; } } }

Target:
I am unsure about this one. Before this, we were returning a live stream, and after this we may be returning a closed stream.
Source:
public static boolean isSupportedMimetype(String mimetype) { boolean supported = true; if ("audio/L24".equalsIgnoreCase(mimetype) || "video/vnd.dlna.mpeg-tts".equalsIgnoreCase(mimetype) || "video/mpeg2".equalsIgnoreCase(mimetype) || "audio/vnd.dlna.adts".equals(mimetype) ) supported = false; return supported; }

Target:
equals ?
Source:
public boolean isADPCM() { return getCodecA() != null && getCodecA().equalsIgnoreCase(FormatConfiguration.ADPCM); }

Target:
If i remember correctly, getCodecA is now set in lower case so `IgnoreCase` is not need anymore.
Source:
public String[] getSupportedExtensions() { return new String[] { "oga", "ogg", "oga", "spx", "opus", }; }

Target:
@Nadahar Isn't "**oga**" already there ?
Source:
public void getCapabilitiesGetRequestWorksWithCORS() throws IOException { String url = wpsUrl + "?Service=WPS&Request=GetCapabilities"; method = new GetMethod(url); method.addRequestHeader("Origin", randomOrigin); int code = client.executeMethod(method); assertThat(code, is(equalTo(200))); Header acaoHeader = method.getResponseHeader("Access-Control-Allow-Origin"); assertThat(acaoHeader.toString(), containsString(randomOrigin.toString())); }

Target:
If CORS is not activated, this throws a NPE. I recommend to add an assertNotNull statement.
Source:
public void describeProcessGetRequestWorksWithCORS() throws IOException { String url = wpsUrl + "?Service=WPS&Request=DescribeProcess&Version=1.0.0&Identifier=" + "org.n52.wps.server.algorithm.test.EchoProcess"; method = new GetMethod(url); method.addRequestHeader("Origin", randomOrigin); int code = client.executeMethod(method); assertThat(code, is(equalTo(200))); Header acaoHeader = method.getResponseHeader("Access-Control-Allow-Origin"); assertThat(acaoHeader.toString(), containsString(randomOrigin.toString())); }

Target:
If CORS is not activated, this throws a NPE. I recommend to add an assertNotNull statement.
Source:
protected String getClassProperty() { return super.getClassProperty() + ' ' + this.getDescriptor().getId() + "message"; }

Target:
The macro might be associated to a specific syntax to it's probably safer to do this.getDescriptor().getId().getId().
Source:
private boolean isMetaDataElement(WikiParameters parameters) { if (parameters.getParameter(CLASS_ATTRIBUTE) != null) { return METADATA_CONTAINER_CLASS.equals(parameters.getParameter(CLASS_ATTRIBUTE).getValue()); } return false; }

Target:
This can be written in a single line: return parameters.getParameter(CLASS_ATTRIBUTE) != null && METADATA_CONTAINER_CLASS.equals(parameters.getParameter(CLASS_ATTRIBUTE).getValue());
Source:
default Type getType() { return new DefaultParameterizedType(null, List.class, Block.class); }

Target:
The default type should be ``String.class`` I think.
Source:
public boolean equals(Object object) { if (object == null && object.getClass() != getClass()) { return false; } if (object == this) { return true; } Syntax rhs = (Syntax) object; return new EqualsBuilder().append(getType(), rhs.getType()).append(getVersion(), rhs.getVersion()) .append(getQualifier(), rhs.getQualifier()).isEquals(); }

Target:
Since Syntax is not really designed to be extended you would replace this whole if by `if (!(object instanceof Syntax))`. Also I would move it after the `if (object == this)`.