auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
StreamSession deriveSession(StreamMessage message) { // StreamInitMessage starts a new channel, and IncomingStreamMessage potentially, as well. // IncomingStreamMessage needs a session to be established a priori, though StreamSession streamSession = message.getOrCreateSession(channel); if (streamSession == null) throw new IllegalStateException(createLogTag(null, channel) + " no session found for message " + message); // Attach this channel to the session: this only happens upon receiving the first init message as a follower; // in all other cases, no new control channel will be added, as the proper control channel will be already attached. streamSession.attachInbound(channel, message instanceof StreamInitMessage); return streamSession; }

Target:
Based on my understanding, calling `getOrCreateSession` on `StreamInitMessage` or `IncomingStreamMessage` is guaranty to return a `StreamSession` and calling `getOrCreateSession` on another type of message would throw an `UnsupportedOperationException`. By consequence, it seems that this null check is useless. Am I missing something?
Source:
private void onChannelClose(Channel channel) { if (channels.remove(channel.id()) != null && channels.isEmpty()) messageSender.close(); }

Target:
This is called from different channels, so possibly from different event loop threads, so shouldn't it be synchronized?
Source:
public static void applyPartitioner() { /* Hashing strategy */ if (conf.partitioner == null) { throw new ConfigurationException("Missing directive: partitioner", false); } String partitionerName = conf.partitioner; try { partitionerName = System.getProperty(Config.PROPERTY_PREFIX + "partitioner", conf.partitioner); partitioner = FBUtilities.newPartitioner(partitionerName); } catch (Exception e) { throw new ConfigurationException("Invalid partitioner class " + partitionerName, e); } paritionerName = partitioner.getClass().getCanonicalName(); }

Target:
The change allows to 1. Set the correct `partitionerName` in the exception message. Previously, the message just include the partitioner set in the conf and it could be wrong when system property is present. 2. Add the stack trace to the exception and enable logging.
Source:
public static void before() { // This only works because the way CI works // In CI a new JVM is spun up for each test file, so this doesn't have to worry about another test file // getting this set first System.setProperty("cassandra.nodetool.jmx_notification_poll_interval_seconds", "1"); DatabaseDescriptor.clientInitialization(); }

Target:
I'm curious why we need to initialize client here. Usually we need to do this in Cassandra instance itself, but not on the test class. Do we need it for JMX to work?
Source:
public InternalNodeProbe(boolean withNotifications) throws IOException { super("", 0); this.withNotifications = withNotifications; connect(); // need to double "connect" since constructor calls connect; withNotifications isn't visable the first time }

Target:
how about adding a new `NodeProble` constructor with param `boolean connect`, so we don't have to connect twice...
Source:
public boolean permit(int from, int to, IMessage msg) { for (Filter filter : filters) { if (filter.matches(from, to, msg)) return filter.permitIfMatched; } return true; }

Target:
this feels weird to me; if I have the following ``` filter(verb).pass(); filter(verb).drop(); ``` what happens? It looks like the drop will be skipped in favor of pass. Don't see a test for this since each test calls `filters.reset();` before adding the second filter. The pass/drop stuff already exists so nothing for this PR, but I feel that `pass()` should be removed (should file jira for this)
Source:
public NodeProbe create(String host, int port, String username, String password) throws IOException { return new InternalNodeProbe(host, port, username, password); }

Target:
personal preference (aka your call) ``` return new InternalNodeProbe(); ``` Rather than have the dumby constructors in `InternalNodeProbe`
Source:
private static int roundKey(int point, int roundSeconds) { int d = point % roundSeconds; if (d > 0) { point += roundSeconds - d; if (point == Cell.MAX_DELETION_TIME) // the rounding should not be a reason to mark point as unexpirable point = Cell.MAX_DELETION_TIME; else if (point < 0) // math overflow happen because of point was close to max possible value return Cell.MAX_DELETION_TIME; return point; } else return point; }

Target:
why assign `point =` here, but `return` below?
Source:
public void add(Replica replica) { // can only add to full array - if we have sliced it, we must be a snapshot assert begin == 0; if (size == contents.length) { int newSize; if (size < 3) newSize = 3; else if (size < 9) newSize = 9; else newSize = size * 2; contents = Arrays.copyOf(contents, newSize); } contents[size++] = replica; }

Target:
Shouldn't be possible to disable this check.
Source:
static final ReplicaMap<InetAddressAndPort> endpointMap(ReplicaList list) { return new ReplicaMap<>(list, Replica::endpoint); }

Target:
This is a method, we can skip `final` here
Source:
public Iterator<Replica> iterator() { return new Iterator<Replica>() { final int end = begin + size; int i = begin; @Override public boolean hasNext() { return i < end; } @Override public Replica next() { return contents[i++]; } }; }

Target:
You can also use `Iterators#fromArray`.
Source:
public static boolean isDummyList(RangesAtEndpoint ranges) { return all(ranges, Replica::isLocal) || all(ranges, range -> range.endpoint().getHostAddress(true).equals("0.0.0.0:0")); }

Target:
How does all replicas being local mean it's a dummy list? Only the 2nd half of this predicate is dummy list related.
Source:
public static <E extends Endpoints<E>> E resolveWriteConflictsInPending(E natural, E pending) { return pending.without(natural.endpoints()); }

Target:
Not anymore
Source:
public Iterator<ResultHandler.ComparableRow> iterator() { if (wasFailed()) return Collections.emptyListIterator(); return new AbstractIterator<ResultHandler.ComparableRow>() { Iterator<Row> iter = resultSet.iterator(); protected ResultHandler.ComparableRow computeNext() { if (iter.hasNext()) { return new DriverRow(iter.next()); } return endOfData(); } }; }

Target:
Unnecessary braces for single statement block (there are bunch of these in this file).
Source:
public String toString() { StringBuilder sb = new StringBuilder("batch: ").append(batchType).append('\n'); for (Single q : queries) { sb.append(q.toString()).append('\n'); } sb.append("end batch"); return sb.toString(); }

Target:
Redundant braces for a single statement block.
Source:
private String columnDefinitionsString(ResultHandler.ComparableColumnDefinitions cd) { StringBuilder sb = new StringBuilder(); if (cd == null) { sb.append("NULL"); } else if (cd.wasFailed()) { sb.append("FAILED"); } else { for (ResultHandler.ComparableDefinition def : cd) { sb.append(def.toString()); } } return sb.toString(); }

Target:
Redundant braces
Source:
private Object getParameter(ParameterType type) { for (int ii = 0; ii < parameters.size(); ii += PARAMETER_TUPLE_SIZE) { if (((ParameterType)parameters.get(ii + PARAMETER_TUPLE_TYPE_OFFSET)).equals(type)) { return parameters.get(ii + PARAMETER_TUPLE_PARAMETER_OFFSET); } } return null; }

Target:
Don't need the typecast to `ParameterType`
Source:
public int hashCode() { return Objects.hash(replicaList); }

Target:
replicaList is not null so I would have just used replicaList.hashCode(). This might allocate a wrapper array for varargs. Objects.hashCode() is the single arg version that won't allocate.
Source:
public void executeAsync() { Replicas.checkFull(targetReplicas); makeDataRequests(targetReplicas.subList(0, targetReplicas.size() > 1 ? 2 : 1).asEndpoints()); if (targetReplicas.size() > 2) makeDigestRequests(targetReplicas.subList(2, targetReplicas.size()).asEndpoints()); cfs.metric.speculativeRetries.inc(); }

Target:
Same thing with these two, can you avoid creating the extra intermediate list.
Source:
public static StartupClusterConnectivityChecker create(long timeoutSecs, boolean blockForRemoteDcs) { if (timeoutSecs < 0) logger.warn("skipping block-for-peers due to negative timeout. You may encounter errors or timeouts on" + " the first user query"); if (timeoutSecs > 100) logger.warn("setting the block-for-peers timeout (in seconds) to might be a bit excessive, but using it nonetheless", timeoutSecs); long timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSecs); return new StartupClusterConnectivityChecker(timeoutNanos, blockForRemoteDcs); }

Target:
Should this be a warning? They have pretty clearly asked for it?
Source:
private static String readFile(File file) throws IOException { Reader in = new BufferedReader(new FileReader(file)); StringBuilder sb = new StringBuilder(); char[] chars = new char[1 << 16]; int length; while ((length = in.read(chars)) > 0) sb.append(chars, 0, length); in.close(); return sb.toString(); }

Target:
We should probably do this in a finally block.
Source:
@NotNull private Cache makeCache() throws IOException { File cacheDir = File.createTempFile("cache-", ".dir"); cacheDir.delete(); return new Cache(cacheDir, 1024 * 1024); }

Target:
no `@NotNull` in OkHttp code. https://developer.squareup.com/blog/non-null-is-the-default/
Source:
protected void attachCVterms(SqwFile file, String ontID, String commaSepTerms) { System.err.println("Use of attachCVTerms is deprecated. Please use attachCVlabels"); attachCVlabels(file, ontID, commaSepTerms); }

Target:
This should be a call to the logger and not to System.err (throughout this class).
Source:
public Map<String, ?> getRawCapabilities() { DesiredCapabilities headlessChrome = DesiredCapabilities.chrome(); headlessChrome.setBrowserName("chromeHeadless"); return headlessChrome.asMap(); }

Target:
Do we really want to set the `browserName` property to `chromeHeadless`? chromeHeadless is our internal feature - Selenium or the webdrivers doesn't know anything about it...
Source:
public GitHubSource(String organization, String project, HttpClient httpClient, GitHubLastUpdateCache gitHubLastUpdateCache) { this.httpClient = httpClient; this.projectUrl = String.format("https://api.github.com/repos/%s/%s", organization, project); this.uniqueKey = organization + "@" + project; this.gson = new Gson(); // TODO think if that should be really a field this.cache = gitHubLastUpdateCache; }

Target:
> TODO think if that should be really a field Yeah, I was asking myself the same thing. But technically, there should be nothing wrong with it. But some investigation would be good - if multiple creations of new instances of Gson has some performance impact or not... Another question is if Gson instance itself is anyhow changed when the method `fromJson` is called.
Source:
private void cleanUpStreams() { System.setOut(null); }

Target:
I think that this is not a clear way to reset values to default - I think, that there should be something like: `System.setOut(System.out);`
Source:
private void checkCompletedSubgoals(State state) { int len = this.recipeSubgoals.size(); for (int i = 0; i < len; i++) { if (this.recipeSubgoals.get(i).goalCompleted(state)) { this.completedSubgoals[i] = true; } } }

Target:
instead of if, you could just do this.completedSubgoals[i] |= this.recipeSubgoals.get(i).goalCompleted(state);
Source:
public AllowUsingTool(String name, Domain domain, IngredientRecipe ingredient) { super(name, domain, new String[] {AgentFactory.ClassName, ToolFactory.ClassName, ContainerFactory.ClassName} ,ingredient); this.recipe = null; }

Target:
Don't need to set objects explicitly to null.
Source:
public void onStart(@NonNull LifecycleOwner owner) { isAppVisible = true; android.util.Log.i(TAG, "App is now visible."); executePendingContactSync(); }

Target:
why util?
Source:
public void onStop(@NonNull LifecycleOwner owner) { isAppVisible = false; android.util.Log.i(TAG, "App is no longer visible."); }

Target:
why util?
Source:
protected final void onSend(MasterSecret masterSecret) throws Exception { if (TextSecurePreferences.getSignedPreKeyFailureCount(context) > 5) { ApplicationContext.getInstance(context) .getJobManager() .add(new RotateSignedPreKeyJob(context)); throw new TextSecureExpiredException("Too many signed prekey rotation failures"); } try { onPushSend(); TextSecurePreferences.setNeedsOutageCheck(context, false); } catch (Exception e) { TextSecurePreferences.setNeedsOutageCheck(context, true); throw e; } }

Target:
In general, please try to avoid catching and rethrowing unwrapped exceptions. You can set this value in onCancelled() rather than catching anything here.
Source:
private static File getPlaintextExportFile() throws NoExternalStorageException { File backup = PlaintextBackupExporter.getPlaintextExportFile(); File oldBackup = new File(Environment.getExternalStorageDirectory(), "TextSecurePlaintextBackup.xml"); if (!backup.exists() && oldBackup.exists()) { return oldBackup; } return backup; }

Target:
From here to the end of this method, IMO, could be rewritten as: ```java return !backup.exists() && oldBackup.exists() ? oldBackup : backup ; ```
Source:
public static File getSignalStorageDir() throws NoExternalStorageException { final File storage = Environment.getExternalStorageDirectory(); if (!storage.canWrite()) throw new NoExternalStorageException(); return storage; }

Target:
braces please
Source:
int getWidthAdjustment() { int width = recordButtonFab.getWidth() / 4; return ViewCompat.getLayoutDirection(recordButtonFab) == LAYOUT_DIRECTION_LTR ? -width : width; }

Target:
can these be private?
Source:
public static void setRegistered(Context context, boolean registered) { setBooleanPreference(context, REGISTERED_PREF, registered); if (isGooglePlayServicesAvailable(context)) { setPushRegistered(context, registered); } }

Target:
No side effects please
Source:
public void setLed() { String ledColor = TextSecurePreferences.getNotificationLedColor(context); String ledBlinkPattern = TextSecurePreferences.getNotificationLedPattern(context); String ledBlinkPatternCustom = TextSecurePreferences.getNotificationLedPatternCustom(context); if (!ledColor.equals("none")) { String[] blinkPatternArray = parseBlinkPattern(ledBlinkPattern, ledBlinkPatternCustom); setLights(Color.parseColor(ledColor), Integer.parseInt(blinkPatternArray[0]), Integer.parseInt(blinkPatternArray[1])); } }

Target:
why is this public?
Source:
protected void onResume() { dynamicTheme.onCreate(this); super.onResume(); }

Target:
I haven't actually tested the code... but: 1. should use `onResume` here? 2. in `RegistrationActivity` there is no call to `dynamicTheme.onResume`
Source:
private synchronized void terminate() { Log.w(TAG, "termination stack", new Exception()); lockManager.updatePhoneState(LockManager.PhoneState.PROCESSING); NotificationBarManager.setCallEnded(this); incomingRinger.stop(); if (outgoingRinger.isLooping()) { outgoingRinger.stop(); } if (currentCallManager != null) { currentCallManager.terminate(); currentCallManager = null; } shutdownAudio(); state = STATE_IDLE; lockManager.updatePhoneState(LockManager.PhoneState.IDLE); }

Target:
Because we still need to release it, even if we're not stopping it, right?
Source:
public void stop() { if( mediaPlayer == null ) return; try { mediaPlayer.release(); mediaPlayer = null; } catch( IllegalStateException e ) { } currentSoundID = -1; }

Target:
You can then also remove the `try...catch` for `IllegalStateException`.
Source:
private String getMessageBody(String body) { if (TextSecurePreferences.isUnicodeStrippingEnabled(context)) { return new UnicodeFilter().filter(body); } else { return body; } }

Target:
sadly this class doesn't have a serialization version id, and i'm not willing to break pending jobs for this change, so please make the change such that it doesn't break the current serialization signature
Source:
private void notifyAllListeners() { List<Listener<T>> localListeners; synchronized (this) { notifyAll(); localListeners = new LinkedList<>(listeners); } for (Listener<T> listener : localListeners) { notifyListener(listener); } }

Target:
It's very unlikely that I will merge changes to SettableFuture
Source:
private static String getPlaintextExportDirectoryPath() { File sdDirectory = Environment.getExternalStorageDirectory(); File signalBackup = new File(sdDirectory.getAbsolutePath() + File.separator, "SignalPlaintextBackup.xml"); if(signalBackup.exists()) { return sdDirectory.getAbsolutePath() + File.separator + "SignalPlaintextBackup.xml"; } else { return sdDirectory.getAbsolutePath() + File.separator + "TextSecurePlaintextBackup.xml"; } }

Target:
you don''t need File.separator here
Source:
@Override protected void onDestroy() { super.onDestroy(); if (recipients != null) recipients.removeListener(this); }

Target:
@ Override \n
Source:
private void onSecurityUpdated() { initializeDraft(); updateInviteReminder(); }

Target:
this would call initializeDraft for every security update broadcast, rather than just once on create
Source:
public static GroupDescription getDescription(@NonNull Context context, @Nullable String encodedGroup) { if (encodedGroup == null) { return new GroupDescription(context, null); } try { GroupContext groupContext = GroupContext.parseFrom(Base64.decode(encodedGroup)); return new GroupDescription(context, groupContext); } catch (IOException e) { Log.w(TAG, e); return new GroupDescription(context, null); } }

Target:
result is also `@NonNull`
Source:
private String parsePath() throws URISyntaxException { String[] parts = uri.split("\\?")[0].split(":", 2); if (parts.length < 2 || parts[1].isEmpty()){ throw new URISyntaxException(uri, "invalid path"); } else if (parts[1].contains("%")){ return URLDecoder.decode(parts[1]); }else{ return parts[1]; } }

Target:
Putting this into the URI class seems kinda gross to me. This class should either decode or not decode, not base decisions around whether there's a "%" character present. I assume that always decoding won't work, since it would interpret an unencoded "+" as a space. So this class probably shouldn't decode, and the caller should be responsible.
Source:
protected final void onCreate(Bundle savedInstanceState) { onPreCreate(); final MasterSecret masterSecret = KeyCachingService.getMasterSecret(this); routeApplicationState(masterSecret); super.onCreate(savedInstanceState); if (!isFinishing()) { Glide.get(this).register(Uri.class, InputStream.class, new EncryptedStreamUriLoader.Factory(masterSecret)); initializeClearKeyReceiver(); onCreate(savedInstanceState, masterSecret); } }

Target:
this is crazy gross, there's no way to make this explicit at load time?
Source:
public static Locale getSelectedLocale(Context context) { String language[] = TextUtils.split(TextSecurePreferences.getLanguage(context), "_"); if (language[0].equals(DEFAULT)) { return Locale.getDefault(); } else if (language.length == 2) { return new Locale(language[0], language[1]); } else { return new Locale(language[0]); } }

Target:
return currentLocale instead
Source:
public Locale getCurrentLocale() { return (currentLocale != null) ? currentLocale : Locale.getDefault(); }

Target:
when would you want this to be true?
Source:
public void bindView(View view, Context context, Cursor cursor) { if (masterSecret != null && masterCipher != null) { ThreadDatabase.Reader reader = threadDatabase.readerFor(cursor, masterSecret, masterCipher); ThreadRecord record = reader.getCurrent(); ((ConversationListItem)view).set(masterSecret, record, batchSet, clickListener, batchMode); } }

Target:
intuitively nothing should really need both a mastersecret and a mastercipher, just one or the other
Source:
private static CharSequence getPassphraseSummary(Context context) { final int passphraseResId = R.string.preferences__passphrase_summary; final String onRes = context.getString(R.string.ApplicationPreferencesActivity_on); final String offRes = context.getString(R.string.ApplicationPreferencesActivity_off); if (TextSecurePreferences.isPasswordDisabled(context)) return context.getString(passphraseResId, offRes); return context.getString(passphraseResId, onRes); }

Target:
use if else or the ternary
Source:
public MessageDetailsRecipientAdapter(Context context, MasterSecret masterSecret, MessageRecord record, Recipients recipients) { super(); this.context = context; this.masterSecret = masterSecret; this.record = record; this.recipients = recipients; }

Target:
unnecessary
Source:
public static Bitmap rotateBitmap(Bitmap bitmap, int angle) { Matrix matrix = new Matrix(); matrix.postRotate(angle); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); }

Target:
can probably make this `private` since it's not needed outside of this util
Source:
public static byte[] toByteArray(Bitmap bitmap) { if (bitmap == null) return null; ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); return stream.toByteArray(); }

Target:
why is this necessary?
Source:
public void afterTextChanged(Editable s) { calculateCharactersRemaining(); updateSendButtonState(); }

Target:
I think we had to take this enabled/disabled functionality out before because it made typing too slow on some devices.
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.add_menu_item: startContactPicker(); break; } return super.onOptionsItemSelected(item); }

Target:
If you want this you'll need to explicitly set homeAsUpEnabled in onCreate.
Source:
private void initializePreferences() { if (!MmsDownloadHelper.isMmsConnectionParametersAvailable(this, null, false)) { PreferenceManager.getDefaultSharedPreferences(this).edit() .putBoolean(ApplicationPreferencesActivity.ENABLE_MANUAL_MMS_PREF, true).commit(); addPreferencesFromResource(R.xml.mms_preferences); this.findPreference(ApplicationPreferencesActivity.ENABLE_MANUAL_MMS_PREF).setOnPreferenceChangeListener(new OverrideMmsChangeListener()); } else addPreferencesFromResource(R.xml.mms_preferences); }

Target:
} else {
Source:
private void initializeMmsEnabledCheck() { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { return MmsSendHelper.hasNecessaryApnDetails(ConversationActivity.this); } @Override protected void onPostExecute(Boolean isMmsEnabled) { ConversationActivity.this.isMmsEnabled = isMmsEnabled; } }.execute(); Intent downloadStalledMmsIntent = new Intent(SendReceiveService.DOWNLOAD_STALLED_MMS_ACTION, null, this, SendReceiveService.class); startService(downloadStalledMmsIntent); }

Target:
It seems potentially strange to do this type of scheduling here. In what case is this needed?
Source:
public void onDestroyActionMode(ActionMode mode) { ((ConversationListAdapter)getListAdapter()).initializeBatchMode(false); if (actionMode != null) { actionMode = null; batchMode = false; } }

Target:
what is this if condition for?
Source:
private void skipUntil(byte... expected) throws IOException { while (!expect(expected)) { if (stream.skip(1) == 0) return; } }

Target:
Depending on the stream type, you can't actually rely on the return value of `skip`. I've learned the hard way to follow commons-io's `skipFully` and use `read` instead.
Source:
public Integer getResolvedCount() { int resolved = 0; Integer[] partials = { getFailedCount(), getInvalidCount(), getDeliveredCount() }; for (Integer partial : partials) { if (partial != null) { resolved += partial; } } return resolved; }

Target:
Wouldn't this by grealy simplified by using primitive `int`s?
Source:
public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.convert(TimeUnit.NANOSECONDS)); hash = LangUtils.hashCode(hash, TimeUnit.NANOSECONDS); return hash; }

Target:
@michael-o `hash = LangUtils.hashCode(hash, TimeUnit.NANOSECONDS)` can be dropped as unnecessary.
Source:
public int compareTo(final TimeValue other) { if (other != null) { final TimeUnit targetTimeUnit = min(other.getTimeUnit()); return Long.compare(convert(targetTimeUnit), other.convert(targetTimeUnit)); } else { return -Integer.MAX_VALUE; } }

Target:
This likely violates: The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.
Source:
public void addComponent(JComponent component, String orientation){ workspaceBar.add(component, orientation); }

Target:
You could make this protected if you want.
Source:
public int compare(String integer, String integer2) { Double i1 = Double.valueOf(integer != null ? integer : ""); Double i2 = Double.valueOf(integer2 != null ? integer2 : ""); return i1.compareTo(i2); }

Target:
I'm not sure off the top of my head what the value of `Double.valueOf("")` is.
Source:
private void initButtons(){ bGrad = new JRadioButton(I18N.tr("")); bPal = new JRadioButton(""); bGrad.addActionListener( EventHandler.create(ActionListener.class, this, "onClickGrad")); bPal.addActionListener( EventHandler.create(ActionListener.class, this, "onClickPal")); bPal.setSelected(true); ButtonGroup bg = new ButtonGroup(); bg.add(bGrad); bg.add(bPal); onClickPal(); }

Target:
Never set empty string to I18N. Gathering strings in source code will fail.
Source:
CRSConstraint() { }

Target:
Empty constructor, but no public modifier ?
Source:
public FunctionSignature[] getFunctionSignatures() { return new FunctionSignature[]{ new BasicFunctionSignature(getType(null), ScalarArgument.GEOMETRY, ScalarArgument.INT), new BasicFunctionSignature(getType(null), ScalarArgument.GEOMETRY, ScalarArgument.STRING)}; }

Target:
Again, strange getType(null) calls.
Source:
public boolean verify(JComponent jComponent) { if(jComponent instanceof JTextComponent) { String value = ((JTextField) jComponent).getText(); try { getValue(value); return true; } catch (ParseException ex) { LOGGER.error(I18N.tr("The entered value cannot be parsed"),ex); return false; } catch (Exception ex) { LOGGER.error(ex.getLocalizedMessage(),ex); return false; } } else { throw new IllegalArgumentException("This verifier is only valid on Text field component"); } }

Target:
If jComponent is an instance of JEditorPane, we obtain a ClassCastException here. Moreover, getText() seems to be valid even on JTextComponent.
Source:
public ReadMapContextJob(MapElement editableMap) { this.editableMap = editableMap; Services.registerService(MapElement.class, I18N.tr("Access to the MapElement"), editableMap); }

Target:
Map element is not a service. You must create another instance to use it.
Source:
public void saveWMSServerFile() { try { CoreWorkspace ws = (CoreWorkspace) Services.getService(CoreWorkspace.class); File file = new File(ws.getWorkspaceFolder() + File.separator + WMSServerFile); PrintWriter pw = new PrintWriter(file); for (String server : serverswms) { pw.println(server); } pw.close(); } catch (FileNotFoundException e) { LOGGER.error(I18N.tr("Cannot save the list of WMS url")); } }

Target:
useless cast
Source:
public Type getColumnType(int col) { try { return getMetadata().getFieldType(col); } catch (DriverException e) { return null; } }

Target:
Looks like a DriverException is being hidden behing a NullPointerException.
Source:
private void setRowSelection(IntegerUnion modelSelection) { IntegerUnion newSelection; if(tableSorter.isFiltered() || !tableSorter.getSortKeys().isEmpty()) { IntegerUnion viewSelection = new IntegerUnion(); for(Integer modelId : modelSelection) { int viewRowId = table.convertRowIndexToView(modelId); if(viewRowId!=-1) { viewSelection.add(viewRowId); } } newSelection = viewSelection; } else { newSelection = modelSelection; } setViewRowSelection(newSelection); }

Target:
This intermediate variable is not necessary
Source:
public static int getSimpleType(Type type){ int tc = type.getTypeCode(); switch(tc){ case Type.POINT: case Type.MULTIPOINT: return POINT; case Type.LINESTRING: case Type.MULTILINESTRING: return LINE; case Type.POLYGON: case Type.MULTIPOLYGON: return POLYGON; case Type.GEOMETRYCOLLECTION: case Type.GEOMETRY: return ALL; } throw new IllegalArgumentException("Can't recognize "+tc+" as a geometry type"); }

Target:
what about putting this in the `default:` case of the switch (switches without default, you know...)
Source:
private void loadDBProperties() { CoreWorkspace ws = (CoreWorkspace) Services.getService(CoreWorkspace.class); try { File propertiesFile = new File(ws.getWorkspaceFolder() + File.separator + dbPropertiesFile); if (propertiesFile.exists()) { dbProperties.load(new FileInputStream(propertiesFile)); } } catch (IOException e) { LOGGER.error(e); } }

Target:
useless cast again. Same below.
Source:
private DataManager getDataManager() { return (DataManager)Services.getService(DataManager.class); }

Target:
The cast is not necessary, we are not using generics for nothing ;-)
Source:
public double getClassNumber(int elem) { return (double) (1 + (3.3 * Math.log10(elem))); }

Target:
This cast here is useless, `Math.log10` returns a double already.
Source:
public double getClassNumber(int elem) { return (double) (2.5f * Math.pow(elem, 0.25)); }

Target:
Useless cast as well, `Math.pow` returns double.
Source:
protected String getNumberVersion(String firstV) { String res = firstV; if (!firstV.matches("[0-9.]+") && firstV.contains("-")) { String[] splittedVersion = firstV.split("-"); if(splittedVersion.length > 1) { res = splittedVersion[1]; } } return res; }

Target:
can you pls also remove number regexp matching here since it will never match if there is a '-' in the input string anyway?
Source:
private PromiseHttpAsyncClient getPromiseHttpAsyncClient(Request request) { log.info( "Creating new HttpAsyncClient" ); final CloseableHttpAsyncClient nonCachingHttpClient; try { final HttpAsyncClientBuilder clientBuilder = createClientBuilder(); nonCachingHttpClient = clientBuilder.build(); nonCachingHttpClient.start(); } catch ( IOReactorException e ) { throw new RuntimeException( "Reactor " + httpClientOptions.getThreadPrefix() + "not set up correctly" , e ); } return new SettableFuturePromiseHttpPromiseAsyncClient<C>(nonCachingHttpClient, threadLocalContextManager, callbackExecutor); }

Target:
Shouldn't this be `log.trace`?
Source:
protected void appendChangeTimestampToDescription(StringBuilder description, JiraSite site, long timestamp) { DateFormat df = null; if (!StringUtils.isBlank(site.getDateTimePattern())) { df = new SimpleDateFormat(site.getDateTimePattern()); } else { // default format for current locale df = new SimpleDateFormat("d/M/yy hh:mm a", Locale.getDefault()); } Date changeDate = new Date(timestamp); String dateTimeString = df.format(changeDate); description.append(dateTimeString); }

Target:
nit: invert the statement while you are here - positive conditions are easier to understand
Source:
public void setUserPattern(String userPattern) { this.userPattern = Util.fixEmptyAndTrim(userPattern); if (this.userPattern != null) { this.userPat = Pattern.compile(this.userPattern); } else { this.userPat = null; } }

Target:
using positive conditions and 'fail fast' approach improves code readability, e.g. ``` if (this.userPattern == null) { return null; } return Pattern.compile(this.userPattern); ```
Source:
public Long getIssueTypeId(String issueTypeName) { List<IssueType> issueTypeList = new ArrayList<IssueType>(); Long issueTypeId = 10004L; issueTypeList = this.getIssueTypes(); for(IssueType issue : issueTypeList) { LOGGER.warning("issueType: " + issue.getName() + " "+ issue.getId()); if(issue.getName().equalsIgnoreCase(issueTypeName)) { issueTypeId = issue.getId(); break; } } return issueTypeId; }

Target:
This logging will cause pretty bad spam..
Source:
public void TestTimeStampBefore1970() { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); TimestampUtils tsu = ((BaseConnection) con).getTimestampUtils(); Date date = tsu.convertToDate(Timestamp.valueOf("1969-01-10 12:00:00").getTime(), TimeZone.getDefault()); assertEquals(new GregorianCalendar(1969, Calendar.JANUARY, 10).getTime(), date ); }

Target:
You are comparing `java.sql.Date` and `java.util.Date` here. What does it mean?
Source:
public synchronized int read() throws IOException { if (ensureBytes(1)) { return buffer[index++] & 0xFF; } return -1; }

Target:
Should probably remove all synchronization from this class.
Source:
public int getPortNumber() { return portNumbers[0]; }

Target:
This assumes `portNumbers` is not null but other parts of the code do that check prior to use.
Source:
private void releaseSavePoint(boolean autosave, int flags) throws SQLException { if (autosave && (flags & QueryExecutor.QUERY_SUPPRESS_BEGIN) == 1 && getAutoSave() == AutoSave.ALWAYS && getTransactionState() == TransactionState.OPEN) { try { sendOneQuery(releaseAutoSave, SimpleQuery.NO_PARAMETERS, 1, 0, QUERY_NO_RESULTS | QUERY_NO_METADATA | QUERY_EXECUTE_AS_SIMPLE); } catch (IOException ex) { throw new PSQLException(GT.tr("Error releasing savepoint"), PSQLState.IO_ERROR); } } }

Target:
After changing the check for the QUERY_SUPPRESS_BEGIN to 0 the changes fix the issue. Otherwise the savepoint is never released
Source:
private X509CRL loadRevokedCertificates(CertificateFactory cf, String crlFile) throws IOException, CRLException { // load the CRL X509CRL crl = null; try { FileInputStream fis = new FileInputStream(crlFile); crl = (X509CRL) cf.generateCRL(fis); fis.close(); } catch (FileNotFoundException ex) { } return crl; }

Target:
this close should be in a finally block.
Source:
public void set(long oid, long rows) { this.oid = oid; this.rows = rows; }

Target:
Does this need to be public?
Source:
public void tearDown() throws SQLException { TimeZone.setDefault(saveTZ); TestUtil.dropTable(con, "table1"); TestUtil.closeDB(con); }

Target:
If the dedicated `java.time` methods from `TimestampUtils` are used this should no longer be necessary.
Source:
private Set<Integer> getOidSet(String oidList) throws PSQLException { Set<Integer> oids = new HashSet<Integer>(); StringTokenizer tokenizer = new StringTokenizer(oidList, ","); while (tokenizer.hasMoreTokens()) { String oid = tokenizer.nextToken(); oids.add(Oid.valueOf(oid)); } return oids; }

Target:
consider making this static
Source:
public synchronized String toString(LocalTime localTime) { sbuf.setLength(0); if (localTime == LocalTime.MAX) { return "24:00:00"; } appendTime(sbuf, localTime); return sbuf.toString(); }

Target:
@davecramer Would it be better to do `LocalTime.MAX.equals(localTime)` here, instead of using the reference equality? Otherwise there will be a difference in write behavior between a LocalTime that has a value of `23:59:59.999999999` and when using `LocalTime.MAX`, even though they are value-equal.
Source:
public long[] getLargeUpdateCount() { long[] copyCount = uncompressLongUpdateCount(); return Arrays.copyOf(copyCount, copyCount.length); }

Target:
Is copy required here?
Source:
public int getSQLType(int oid) throws SQLException { if (oid == Oid.UNSPECIFIED) { return Types.OTHER; } Integer sqlType = _oidToSQLType.get(oid); if (sqlType != null) { return sqlType; } PgType pgType = fetchPgType(oid); if (pgType == null) { return Types.OTHER; } return pgType.sqlType(); }

Target:
this access needs to be synchronized
Source:
public void testGetNumericWithoutArg() throws SQLException { assumeCallableStatementsSupported(); try (CallableStatement call = con.prepareCall(func + pkgName + "getNumericWithoutArg () }")) { call.registerOutParameter(1, Types.NUMERIC); call.execute(); assertEquals(new BigDecimal(42), call.getObject(1, BigDecimal.class)); } }

Target:
This can be placed in a `setUp` method.
Source:
public String get(Properties properties) { return new org.postgresql.util.ExpressionProperties(properties).getProperty(_name, _defaultValue); }

Target:
This would have an unexpected consequence if someone has `dfwe${...}asdfa` pattern right inside a password property.
Source:
public void setEncoding(Encoding encoding) throws IOException { // Close down any old writer. if (encodingWriter != null) { encodingWriter.close(); } this.encoding = encoding; // Intercept flush() downcalls from the writer; our caller // will call PGStream.flush() as needed. OutputStream interceptor = new FilterOutputStream(pg_output) { @Override public void flush() throws IOException { } @Override public void close() throws IOException { super.flush(); } }; encodingWriter = encoding.getEncodingWriter(interceptor); }

Target:
If you want to correct style, can you please send another PR for that? It is very hard to identify changes required for unixsocket support.
Source:
public void getLatestDisplay_CurrentIsNull_DisplayUnchanged() { DisplaySafe safe = new DisplaySafe(null); DisplaySafe safeSpy = spy(safe); when(safeSpy.getCurrent()).thenReturn(null); boolean nullDisplayExceptionThrown = false; try { safeSpy.getLatestDisplay(); } catch (DisplaySafe.NullDisplayException nde) { nullDisplayExceptionThrown = true; } assertTrue(nullDisplayExceptionThrown); }

Target:
Instead of a boolean, you can use ``` @Test(expected = DisplaySafe.NullDisplayException.class) ``` that's a more universally accepted way of testing that an exception is thrown.
Source:
public static void setup() throws IOException { FileUtils.deleteDirectory(new File(ODO_CACHE_DIR)); UsageReportPreferences.setEnabled(false); UsageReportPreferences.setAskUser(false); }

Target:
Not needed, there is an env variable wich is set by our jobs.
Source:
public void publishFinish(IProgressMonitor monitor) throws CoreException { super.publishFinish(monitor); final File localFolder = getDeploymentsRootFolder(); syncPodsToDirectory(localFolder, monitor); deleteOldDeployments(getServer()); syncDirectoryToPods(localFolder, monitor); final IResource resource = OpenShiftServerUtils.getResource(getServer(), monitor); loadPodPathIfEmpty(resource, monitor); }

Target:
Why is syncPodsToDirectory being done during publishFinish? Shouldn't that be done at the start of the publish operation, like publishStart or something? My concern is if this is done after publish, it may be buggy. For example: User changes Sample.war. publishStart() is called, publishModule(etc) is called. You copy in the new changes of Sample.war, then you syncPodsToDirectory and end up overwriting your changes? Not sure if this is correct but its my current concern.
Source:
public ActivateMavenProfileJob(Action action, IProject project) { super(NLS.bind("{0} maven profile \"openshift\" for project {1}", action == Action.ACTIVATE? "Activating" : "Deactivating", project.getName())); this.action = action; this.project = project; // need to lock the whole workspace to prevent dead locks with other, concurrent // jobs that escalate to the workspace lock. setRule(ResourcesPlugin.getWorkspace().getRuleFactory().createRule(ResourcesPlugin.getWorkspace().getRoot())); }

Target:
IWorkspaceRoot and IContainer both implement ISchedulingRule so odds are you can replace setRule(ResourcesPlugin.getWorkspace().getRuleFactory().createRule(ResourcesPlugin.getWorkspace().getRoot())); with setRule(ResourcesPlugin.getWorkspace().getRoot());
Source:
private File folderWhiteListBin(File folder) { String[] children = folder.list(); children = (children == null ? new String[0] : children); for( int i = 0; i < children.length; i++ ) { Matcher m = WHITELIST_PATTERN.matcher(children[i]); if( m.matches()) { return new File(folder, children[i]); } } return null; }

Target:
why wouldn't you simply return null if children is null? Using a 0-length string has the same effect but is less visible.
Source:
public static String getProjectAbsolutePath(String... path) { // Construct path StringBuilder builder = new StringBuilder(); for (String fragment : path) { builder.append("/" + fragment); } String filePath = ""; filePath = System.getProperty("user.dir"); File file = new File(filePath + builder.toString()); if (!file.exists()) { throw new RedDeerException("Resource file does not exists within project path " + filePath + builder.toString()); } return file.getAbsolutePath(); }

Target:
why declare and initialise with an empty string that immediately gets overwritten by the system property?
Source:
private void validateOCLocation() { if( selectedConnection != null ) { String ocValString = OCBinary.getInstance().getLocation(selectedConnection); if( ocValString == null || ocValString.isEmpty()) { ocLocationDecorator.show(); ocLocationDecorator.setImage(FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_WARNING).getImage()); ocLocationDecorator.setDescriptionText("The selected connection does not have an 'oc' command associated with it. Please edit the connection or modify your workspace settings to add one."); } else { ocLocationDecorator.hide(); } } }

Target:
more expressive would be ```if (StringUtils.isEmpty())```
Source:
public ToggleDebuggingCommand(IServerWorkingCopy server, Button useImageDevmodeKeyButton, Text devmodeKeyText, SelectionListener toggleListener, ModifyListener textListener) { super(server, "Enable Debugging"); this.wc = server; this.useImageDevmodeKeyButton = useImageDevmodeKeyButton; this.devmodeKeyText = devmodeKeyText; preSelected = !useImageDevmodeKeyButton.getSelection(); preText = devmodeKeyText.getText(); this.toggleListener = toggleListener; this.textListener = textListener; }

Target:
preText? not the most speaking variable name imho
Source:
public boolean setInitialDelay(DebugContext context, IProgressMonitor monitor) throws CoreException { monitor.subTask(NLS.bind("Setting liveness probe initial delay to {0}", INITIAL_DELAY)); IProbe probe = getLivenessProbe(dc); if (probe == null) { return false; } int initialDelay = probe.getInitialDelaySeconds(); if (initialDelay >= INITIAL_DELAY) { OpenShiftServerUtils.setLivenessProbeInitialDelay(initialDelay, context.getServer()); return false; } probe.setInitialDelaySeconds(INITIAL_DELAY); return true; }

Target:
I don't understand the rationale for this case and why don't you save the original value as an annotation in the deployment config ?
Source:
public static String getCurrentBranch(IProject project) throws CoreException { if (project == null) { return null; } Repository repo = EGitUtils.getRepository(project); if (repo == null) { return null; } String currentBranch = EGitUtils.getCurrentBranch(repo); repo.close(); return currentBranch; }

Target:
I think it's better to use try-with-resources here, it will also fix Sonar complaining about it. I mean it should be smth like: ````java try (Repository repo = EGitUtils.getRepository(project)) { if (repo == null) { return null; } return EGitUtils.getCurrentBranch(repo); }
Source:
public static boolean areRelated(final IService service, final IDeploymentConfig dc) { return service.getProject().getResources(ResourceKind.POD).stream() .filter(pod -> containsAll(service.getSelector(), pod.getLabels())) .filter(pod -> dc.getName().equals(pod.getAnnotation(OpenShiftAPIAnnotations.DEPLOYMENT_CONFIG_NAME))) .count() > 0; }

Target:
nitpicking I think that the first filter is longer running than the second - so it's better to rearrange them for performance, so that currently first filter would work on less number of pods.
Source:
public static String getKind(String uniqueId) { if (StringUtils.isEmpty(uniqueId)) { return null; } String[] comps = uniqueId.split(String.valueOf(UNIQUE_ID_PROJECT_NAME_DELIMITER)); if (comps.length == 2) { return ResourceKind.SERVICE; } else { return comps[1]; } }

Target:
this should only be performed once we checked that there are actually >= 2 elements in comps. We otherwise potentially run into an ArrayIndexOutOfBoundsException.
Source:
private void stopWatchSafe(IProject project, IOpenShiftConnection connection, String... kinds) { for (String kind : KINDS) { AtomicReference<IWatcher> watcherRef = watches.remove(new WatchKey(connection, project, kind)); if((watcherRef != null) && (watcherRef.get() != null)) { watcherRef.get().stop(); } } }

Target:
Should not 'kinds' be used here instead of 'KINDS' as in startWatchSafe(), or it is left intentionally to make sure that all watches are removed?
Source:
public OpenShiftExplorerContentProvider() { listener = new IElementListener() { @Override public void elementChanged(IOpenshiftUIElement<?, ?> element) { if (element instanceof OpenshiftUIModel) { refreshViewer(ConnectionsRegistrySingleton.getInstance()); } else { refreshViewer(element); } if (element.getWrapped() instanceof IRoute) { viewer.update(element.getParent(), null); } } }; model.addListener(listener); }

Target:
keeping that constructor makes it more testable as you could inject a mock OpenshiftUIModel
Source:
private String getLabel(String mode) { String label = OpenShiftCoreMessages.RunOnOpenshift; if (ILaunchManager.PROFILE_MODE.equals(mode)) { label = OpenShiftCoreMessages.ProfileOnOpenshift; } else if (ILaunchManager.DEBUG_MODE.equals(mode)) { label = OpenShiftCoreMessages.DebugOnOpenshift; } return label; }

Target:
just a niggle: i think `switch-case` with "RunOnOpenshift" as the default would be more readable here
Source:
public static com.openshift.restclient.model.IProject getProject(IResource resource) { IProject project = null; if (resource instanceof IProject) { project = (IProject) resource; } else if (resource != null) { project = resource.getProject(); } return project; }

Target:
just a niggle : what's the point of using full class name (including package)?
Source:
public IConnection update(IConnection conn) { Assert.isLegal(conn instanceof Connection); final Connection connection = (Connection) conn; // might be called from job, switch to display thread to access observables Display.getDefault().syncExec(new Runnable() { @Override public void run() { connection.setAuthScheme(IAuthorizationContext.AUTHSCHEME_OAUTH); connection.setToken((String) tokenObservable.getValue()); connection.setRememberToken((boolean) rememberTokenObservable.getValue()); } }); return connection; }

Target:
Since definition of rememberTokenObservable and tokenObservable now has type parameter, the casting may be not needed at all.
Source:
private LoadingStub makeStub(Object parentElement) { LoadingStub stub = stubs.get(parentElement); if (stub == null) { stub= new LoadingStub(); stubs.put(parentElement, stub); } return stub; }

Target:
Any chance of a race condition here where concurrent threads try to add entries and one ends up replacing the other?
Source:
Job createJob(final String name, final JobCounter jc) { return new Job("Job 1") { @Override protected IStatus run(IProgressMonitor monitor) { jc.jobDone(getName()); return Status.OK_STATUS; } }; }

Target:
return new Job(name)
Source:
private IConnectionWrapper createConnection(IServer server) throws MalformedURLException { ConnectorProviderRegistry connectorProviders = OpenShiftCoreActivator.getDefault().getConnectorProviders(); VersionKey version = new VersionDetector(server).guess(); if (version != null) { JMXConnectorProvider provider = connectorProviders.getProvider(version); return new OpenshiftConnectionWrapper(this, server, provider); } return null; }

Target:
what if provider == null?
Source:
public void dispose() { super.dispose(); DockerConnectionManager.getInstance().removeConnectionManagerListener(this); ((EnvironmentVariablesPageModel)envModel).dispose(); connection = null; project = null; dockerConnection = null; projects.clear(); volumes.clear(); portSpecs.clear(); if(imagePorts != null) { imagePorts.clear(); } }

Target:
set the reference to imagePorts to null (to be consistent)? `imagePorts = null`
Source:
public void restart(String launchMode) throws CoreException { putSharedData(CURRENTLY_RESTARTING, true); }

Target:
``` @Override public void restart(String launchMode) throws CoreException { putSharedData(CURRENTLY_RESTARTING, true); super.restart(launchMode); } ```
Source:
protected boolean isEapProfile() { // quick and dirty String profile = ServerProfileModel.getProfile(getServer()); if( "openshift3.eap".equals(profile)) { return false; } return true; }

Target:
nope, return true
Source:
default public boolean isRememberChoice() { return false; }

Target:
I have no issues correcting the other method signatures either. It would be obvious from the diff what is happening and that no code is being changed.
Source:
public void startWatch(final IProject project) { ConcurrentMap<String, IWatcher> kindMap = new ConcurrentHashMap<>(); if(watches.putIfAbsent(project, kindMap) == null){ final Connection conn = ConnectionsRegistryUtil.getConnectionFor(project); for (String kind: KINDS) { WatchListener listener = new WatchListener(project, conn, kind, 0, 0); startWatch(project, 0, 0, listener); } } }

Target:
can't conn be null at that point?