auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private synchronized void terminate() { Log.w(TAG, "termination stack", new Exception()); lockManager.updatePhoneState(LockManager.PhoneState.PROCESSING); NotificationBarManager.setCallEnded(this); incomingRinger.stop(); START if (outgoingRinger.isLooping()) { END outgoingRinger.stop(); } if (currentCallManager != null) { currentCallManager.terminate(); currentCallManager = null; } shutdownAudio(); state = STATE_IDLE; lockManager.updatePhoneState(LockManager.PhoneState.IDLE); } Because we still need to release it, even if we're not stopping it, right?

Target:
private synchronized void terminate() { Log.w(TAG, "termination stack", new Exception()); lockManager.updatePhoneState(LockManager.PhoneState.PROCESSING); NotificationBarManager.setCallEnded(this); incomingRinger.stop(); outgoingRinger.stop(); if (currentCallManager != null) { currentCallManager.terminate(); currentCallManager = null; } shutdownAudio(); state = STATE_IDLE; lockManager.updatePhoneState(LockManager.PhoneState.IDLE); }
Source:
public void stop() { if( mediaPlayer == null ) return; try { START mediaPlayer.release(); END mediaPlayer = null; } catch( IllegalStateException e ) { } currentSoundID = -1; } You can then also remove the `try...catch` for `IllegalStateException`.

Target:
public void stop() { if (mediaPlayer == null) return; mediaPlayer.release(); mediaPlayer = null; currentSoundID = -1; }
Source:
private String getMessageBody(String body) { if (TextSecurePreferences.isUnicodeStrippingEnabled(context)) { return new UnicodeFilter().filter(body); } else { return body; } START } END 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

Target:
private String getMessageBody(String body) { if (TextSecurePreferences.isUnicodeStrippingEnabled(context)) { return UnicodeFilter.filter(body); } else { return body; } }
Source:
private void notifyAllListeners() { List<Listener<T>> localListeners; synchronized (this) { notifyAll(); localListeners = new LinkedList<>(listeners); START } END for (Listener<T> listener : localListeners) { notifyListener(listener); } } It's very unlikely that I will merge changes to SettableFuture

Target:
private void notifyAllListeners() { List<Listener<T>> localListeners; synchronized (this) { localListeners = new LinkedList<>(listeners); } for (Listener<T> listener : localListeners) { notifyListener(listener); } }
Source:
private static String getPlaintextExportDirectoryPath() { File sdDirectory = Environment.getExternalStorageDirectory(); START File signalBackup = new File(sdDirectory.getAbsolutePath() + File.separator, "SignalPlaintextBackup.xml"); END if(signalBackup.exists()) { return sdDirectory.getAbsolutePath() + File.separator + "SignalPlaintextBackup.xml"; } else { return sdDirectory.getAbsolutePath() + File.separator + "TextSecurePlaintextBackup.xml"; } } you don''t need File.separator here

Target:
private static String getPlaintextExportDirectoryPath() { File sdDirectory = Environment.getExternalStorageDirectory(); File signalBackup = new File(sdDirectory.getAbsolutePath(), "SignalPlaintextBackup.xml"); if (signalBackup.exists()) { return sdDirectory.getAbsolutePath() + File.separator + "SignalPlaintextBackup.xml"; } else { return sdDirectory.getAbsolutePath() + File.separator + "TextSecurePlaintextBackup.xml"; } }
Source:
START @Override protected void onDestroy() { END super.onDestroy(); if (recipients != null) recipients.removeListener(this); } @ Override \n

Target:
protected void onDestroy() { super.onDestroy(); if (recipients != null) recipients.removeListener(this); }
Source:
private void onSecurityUpdated() { START initializeDraft(); END updateInviteReminder(); } this would call initializeDraft for every security update broadcast, rather than just once on create

Target:
private void onSecurityUpdated() { updateInviteReminder(); }
Source:
START public static GroupDescription getDescription(@NonNull Context context, @Nullable String encodedGroup) { END 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); } } result is also `@NonNull`

Target:
public static @NonNull 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); } }
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"); START } else if (parts[1].contains("%")){ END return URLDecoder.decode(parts[1]); }else{ return parts[1]; } } 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.

Target:
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 return parts[1]; }
Source:
protected final void onCreate(Bundle savedInstanceState) { onPreCreate(); final MasterSecret masterSecret = KeyCachingService.getMasterSecret(this); routeApplicationState(masterSecret); super.onCreate(savedInstanceState); if (!isFinishing()) { START Glide.get(this).register(Uri.class, InputStream.class, new EncryptedStreamUriLoader.Factory(masterSecret)); END initializeClearKeyReceiver(); onCreate(savedInstanceState, masterSecret); } } this is crazy gross, there's no way to make this explicit at load time?

Target:
protected final void onCreate(Bundle savedInstanceState) { onPreCreate(); final MasterSecret masterSecret = KeyCachingService.getMasterSecret(this); routeApplicationState(masterSecret); super.onCreate(savedInstanceState); if (!isFinishing()) { initializeClearKeyReceiver(); onCreate(savedInstanceState, masterSecret); } }
Source:
START public static Locale getSelectedLocale(Context context) { END 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]); } } return currentLocale instead

Target:
private 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]); } }
Source:
public Locale getCurrentLocale() { START return (currentLocale != null) ? currentLocale : Locale.getDefault(); END } when would you want this to be true?

Target:
public Locale getCurrentLocale() { return currentLocale; }
Source:
public void bindView(View view, Context context, Cursor cursor) { if (masterSecret != null && masterCipher != null) { START ThreadDatabase.Reader reader = threadDatabase.readerFor(cursor, masterSecret, masterCipher); END ThreadRecord record = reader.getCurrent(); ((ConversationListItem)view).set(masterSecret, record, batchSet, clickListener, batchMode); } } intuitively nothing should really need both a mastersecret and a mastercipher, just one or the other

Target:
public void bindView(View view, Context context, Cursor cursor) { if (masterSecret != null) { ThreadDatabase.Reader reader = threadDatabase.readerFor(cursor, masterSecret); ThreadRecord record = reader.getCurrent(); ((ConversationListItem)view).set(record, batchSet, batchMode); } }
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); START return context.getString(passphraseResId, onRes); END } use if else or the ternary

Target:
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); } else { return context.getString(passphraseResId, onRes); } }
Source:
public MessageDetailsRecipientAdapter(Context context, MasterSecret masterSecret, MessageRecord record, Recipients recipients) { START super(); END this.context = context; this.masterSecret = masterSecret; this.record = record; this.recipients = recipients; } unnecessary

Target:
public MessageDetailsRecipientAdapter(Context context, MasterSecret masterSecret, MessageRecord record, Recipients recipients) { this.context = context; this.masterSecret = masterSecret; this.record = record; this.recipients = recipients; }
Source:
START public static Bitmap rotateBitmap(Bitmap bitmap, int angle) { END Matrix matrix = new Matrix(); matrix.postRotate(angle); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } can probably make this `private` since it's not needed outside of this util

Target:
private 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); }
Source:
public static byte[] toByteArray(Bitmap bitmap) { START if (bitmap == null) return null; END ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); return stream.toByteArray(); } why is this necessary?

Target:
public static byte[] toByteArray(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); return stream.toByteArray(); }
Source:
public void afterTextChanged(Editable s) { calculateCharactersRemaining(); START updateSendButtonState(); END } I think we had to take this enabled/disabled functionality out before because it made typing too slow on some devices.

Target:
public void afterTextChanged(Editable s) { calculateCharactersRemaining(); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { START case android.R.id.home: END finish(); break; case R.id.add_menu_item: startContactPicker(); break; } return super.onOptionsItemSelected(item); } If you want this you'll need to explicitly set homeAsUpEnabled in onCreate.

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.add_menu_item: startContactPicker(); break; } return super.onOptionsItemSelected(item); }
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()); START } END else addPreferencesFromResource(R.xml.mms_preferences); } } else {

Target:
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); } }
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); START startService(downloadStalledMmsIntent); END } It seems potentially strange to do this type of scheduling here. In what case is this needed?

Target:
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(); }
Source:
public void onDestroyActionMode(ActionMode mode) { ((ConversationListAdapter)getListAdapter()).initializeBatchMode(false); START if (actionMode != null) { END actionMode = null; batchMode = false; } } what is this if condition for?

Target:
public void onDestroyActionMode(ActionMode mode) { ((ConversationListAdapter)getListAdapter()).initializeBatchMode(false); batchMode = false; }
Source:
private void skipUntil(byte... expected) throws IOException { while (!expect(expected)) { START if (stream.skip(1) == 0) return; END } } 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.

Target:
private void skipUntil(byte... expected) throws IOException { while (!expect(expected)) { if (stream.read() == -1) return; } }
Source:
START public Integer getResolvedCount() { END int resolved = 0; Integer[] partials = { getFailedCount(), getInvalidCount(), getDeliveredCount() }; for (Integer partial : partials) { if (partial != null) { resolved += partial; } } return resolved; } Wouldn't this by grealy simplified by using primitive `int`s?

Target:
public int getResolvedCount() { return getFailedCount() + getInvalidCount() + getDeliveredCount(); }
Source:
public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.convert(TimeUnit.NANOSECONDS)); START hash = LangUtils.hashCode(hash, TimeUnit.NANOSECONDS); END return hash; } @michael-o `hash = LangUtils.hashCode(hash, TimeUnit.NANOSECONDS)` can be dropped as unnecessary.

Target:
public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.convert(TimeUnit.NANOSECONDS)); return hash; }
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 { START return -Integer.MAX_VALUE; END } } 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.

Target:
public int compareTo(final TimeValue other) { final TimeUnit targetTimeUnit = min(other.getTimeUnit()); return Long.compare(convert(targetTimeUnit), other.convert(targetTimeUnit)); }
Source:
START public void addComponent(JComponent component, String orientation){ END workspaceBar.add(component, orientation); } You could make this protected if you want.

Target:
protected void addComponent(JComponent component, String orientation){ workspaceBar.add(component, orientation); }
Source:
public int compare(String integer, String integer2) { START Double i1 = Double.valueOf(integer != null ? integer : ""); END Double i2 = Double.valueOf(integer2 != null ? integer2 : ""); return i1.compareTo(i2); } I'm not sure off the top of my head what the value of `Double.valueOf("")` is.

Target:
public int compare(String integer, String integer2) { Double i1 = Double.valueOf(integer); Double i2 = Double.valueOf(integer2); return i1.compareTo(i2); }
Source:
private void initButtons(){ START bGrad = new JRadioButton(I18N.tr("")); END 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(); } Never set empty string to I18N. Gathering strings in source code will fail.

Target:
private void initButtons(){ bGrad = new JRadioButton(""); 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(); }
Source:
START CRSConstraint() { END } Empty constructor, but no public modifier ?

Target:
public CRSConstraint() { }
Source:
public FunctionSignature[] getFunctionSignatures() { return new FunctionSignature[]{ START new BasicFunctionSignature(getType(null), ScalarArgument.GEOMETRY, END ScalarArgument.INT), new BasicFunctionSignature(getType(null), ScalarArgument.GEOMETRY, ScalarArgument.STRING)}; } Again, strange getType(null) calls.

Target:
public FunctionSignature[] getFunctionSignatures() { return new FunctionSignature[]{ new BasicFunctionSignature(Type.GEOMETRY, ScalarArgument.GEOMETRY, ScalarArgument.INT), new BasicFunctionSignature(Type.GEOMETRY, ScalarArgument.GEOMETRY, ScalarArgument.STRING)}; }
Source:
public boolean verify(JComponent jComponent) { if(jComponent instanceof JTextComponent) { START String value = ((JTextField) jComponent).getText(); END 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"); } } If jComponent is an instance of JEditorPane, we obtain a ClassCastException here. Moreover, getText() seems to be valid even on JTextComponent.

Target:
public boolean verify(JComponent jComponent) { if(jComponent instanceof JTextComponent) { String value = ((JTextComponent) 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"); } }
Source:
public ReadMapContextJob(MapElement editableMap) { this.editableMap = editableMap; START Services.registerService(MapElement.class, END I18N.tr("Access to the MapElement"), editableMap); } Map element is not a service. You must create another instance to use it.

Target:
public ReadMapContextJob(MapElement editableMap) { this.editableMap = editableMap; }
Source:
public void saveWMSServerFile() { try { START CoreWorkspace ws = (CoreWorkspace) Services.getService(CoreWorkspace.class); END 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")); } } useless cast

Target:
public void saveWMSServerFile() { try { CoreWorkspace ws = 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")); } }
Source:
public Type getColumnType(int col) { try { START return getMetadata().getFieldType(col); END } catch (DriverException e) { return null; } } Looks like a DriverException is being hidden behing a NullPointerException.

Target:
public Type getColumnType(int col) { try { return getMetadata().getFieldType(col); } catch (DriverException e) { throw new IllegalStateException(e); } }
Source:
private void setRowSelection(IntegerUnion modelSelection) { IntegerUnion newSelection; if(tableSorter.isFiltered() || !tableSorter.getSortKeys().isEmpty()) { START IntegerUnion viewSelection = new IntegerUnion(); END for(Integer modelId : modelSelection) { int viewRowId = table.convertRowIndexToView(modelId); if(viewRowId!=-1) { viewSelection.add(viewRowId); } } newSelection = viewSelection; } else { newSelection = modelSelection; } setViewRowSelection(newSelection); } This intermediate variable is not necessary

Target:
private void setRowSelection(IntegerUnion modelSelection) { IntegerUnion newSelection; if(tableSorter.isFiltered() || !tableSorter.getSortKeys().isEmpty()) { newSelection = new IntegerUnion(); for(Integer modelId : modelSelection) { int viewRowId = table.convertRowIndexToView(modelId); if(viewRowId!=-1) { newSelection.add(viewRowId); } } } else { newSelection = modelSelection; } setViewRowSelection(newSelection); }
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; } START throw new IllegalArgumentException("Can't recognize "+tc+" as a geometry type"); END } what about putting this in the `default:` case of the switch (switches without default, you know...)

Target:
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; default: throw new IllegalArgumentException("Can't recognize " + tc + " as a geometry type"); } }
Source:
private void loadDBProperties() { START CoreWorkspace ws = (CoreWorkspace) Services.getService(CoreWorkspace.class); END try { File propertiesFile = new File(ws.getWorkspaceFolder() + File.separator + dbPropertiesFile); if (propertiesFile.exists()) { dbProperties.load(new FileInputStream(propertiesFile)); } } catch (IOException e) { LOGGER.error(e); } } useless cast again. Same below.

Target:
private void loadDBProperties() { CoreWorkspace ws = 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); } }
Source:
private DataManager getDataManager() { START return (DataManager)Services.getService(DataManager.class); END } The cast is not necessary, we are not using generics for nothing ;-)

Target:
private DataManager getDataManager() { return Services.getService(DataManager.class); }
Source:
public double getClassNumber(int elem) { START return (double) (1 + (3.3 * Math.log10(elem))); END } This cast here is useless, `Math.log10` returns a double already.

Target:
public double getClassNumber(int elem) { return 1 + (3.3 * Math.log10(elem)); }
Source:
public double getClassNumber(int elem) { START return (double) (2.5f * Math.pow(elem, 0.25)); END } Useless cast as well, `Math.pow` returns double.

Target:
public double getClassNumber(int elem) { return 2.5f * Math.pow(elem, 0.25); }
Source:
protected String getNumberVersion(String firstV) { String res = firstV; START if (!firstV.matches("[0-9.]+") && firstV.contains("-")) { END String[] splittedVersion = firstV.split("-"); if(splittedVersion.length > 1) { res = splittedVersion[1]; } } return res; } can you pls also remove number regexp matching here since it will never match if there is a '-' in the input string anyway?

Target:
protected String getNumberVersion(String firstV) { String res = firstV; if (firstV.contains("-")) { String[] splittedVersion = firstV.split("-"); if(splittedVersion.length > 1) { res = splittedVersion[1]; } } return res; }
Source:
private PromiseHttpAsyncClient getPromiseHttpAsyncClient(Request request) { START log.info( "Creating new HttpAsyncClient" ); END 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); } Shouldn't this be `log.trace`?

Target:
private PromiseHttpAsyncClient getPromiseHttpAsyncClient(Request request) { log.trace( "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); }
Source:
protected void appendChangeTimestampToDescription(StringBuilder description, JiraSite site, long timestamp) { DateFormat df = null; START if (!StringUtils.isBlank(site.getDateTimePattern())) { END 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); } nit: invert the statement while you are here - positive conditions are easier to understand

Target:
protected void appendChangeTimestampToDescription(StringBuilder description, JiraSite site, long timestamp) { DateFormat df = null; if (StringUtils.isBlank(site.getDateTimePattern())) { // default format for current locale df = new SimpleDateFormat("d/M/yy hh:mm a", Locale.getDefault()); } else { df = new SimpleDateFormat(site.getDateTimePattern()); } Date changeDate = new Date(timestamp); String dateTimeString = df.format(changeDate); description.append(dateTimeString); }
Source:
public void setUserPattern(String userPattern) { this.userPattern = Util.fixEmptyAndTrim(userPattern); START if (this.userPattern != null) { END this.userPat = Pattern.compile(this.userPattern); } else { this.userPat = null; } } using positive conditions and 'fail fast' approach improves code readability, e.g. ``` if (this.userPattern == null) { return null; } return Pattern.compile(this.userPattern); ```

Target:
public void setUserPattern(String userPattern) { this.userPattern = Util.fixEmptyAndTrim(userPattern); if (this.userPattern == null) { this.userPat = null; } else { this.userPat = 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) { START LOGGER.warning("issueType: " + issue.getName() + " "+ issue.getId()); END if(issue.getName().equalsIgnoreCase(issueTypeName)) { issueTypeId = issue.getId(); break; } } return issueTypeId; } This logging will cause pretty bad spam..

Target:
public Long getIssueTypeId(String issueTypeName) { List<IssueType> issueTypeList = new ArrayList<IssueType>(); Long issueTypeId = 10004L; issueTypeList = this.getIssueTypes(); for(IssueType issue : issueTypeList) { if(issue.getName().equalsIgnoreCase(issueTypeName)) { issueTypeId = issue.getId(); break; } } return issueTypeId; }
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()); START assertEquals(new GregorianCalendar(1969, Calendar.JANUARY, 10).getTime(), date ); END } You are comparing `java.sql.Date` and `java.util.Date` here. What does it mean?

Target:
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().getTime(), date.getTime() ); }
Source:
START public synchronized int read() throws IOException { END if (ensureBytes(1)) { return buffer[index++] & 0xFF; } return -1; } Should probably remove all synchronization from this class.

Target:
public int read() throws IOException { if (ensureBytes(1)) { return buffer[index++] & 0xFF; } return -1; }
Source:
public int getPortNumber() { START return portNumbers[0]; END } This assumes `portNumbers` is not null but other parts of the code do that check prior to use.

Target:
public int getPortNumber() { if (portNumbers == null || portNumbers.length == 0) { return 0; } return portNumbers[0]; }
Source:
private void releaseSavePoint(boolean autosave, int flags) throws SQLException { if (autosave START && (flags & QueryExecutor.QUERY_SUPPRESS_BEGIN) == 1 END && 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); } } } After changing the check for the QUERY_SUPPRESS_BEGIN to 0 the changes fix the issue. Otherwise the savepoint is never released

Target:
private void releaseSavePoint(boolean autosave, int flags) throws SQLException { if ( autosave && 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); } } }
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); START fis.close(); END } catch (FileNotFoundException ex) { } return crl; } this close should be in a finally block.

Target:
private X509CRL loadRevokedCertificates(CertificateFactory cf, String crlFile) throws IOException, CRLException { // load the CRL X509CRL crl = null; FileInputStream fis = null; try { new FileInputStream(crlFile); crl = (X509CRL) cf.generateCRL(fis); fis.close(); } catch (FileNotFoundException ex) { } finally { if ( fis != null ) { fis.close(); } } return crl; }
Source:
START public void set(long oid, long rows) { END this.oid = oid; this.rows = rows; } Does this need to be public?

Target:
void set(long oid, long rows) { this.oid = oid; this.rows = rows; }
Source:
public void tearDown() throws SQLException { START TimeZone.setDefault(saveTZ); END TestUtil.dropTable(con, "table1"); TestUtil.closeDB(con); } If the dedicated `java.time` methods from `TimestampUtils` are used this should no longer be necessary.

Target:
public void tearDown() throws SQLException { TestUtil.dropTable(con, "table1"); TestUtil.closeDB(con); }
Source:
START private Set<Integer> getOidSet(String oidList) throws PSQLException { END 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; } consider making this static

Target:
private static 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; }
Source:
public synchronized String toString(LocalTime localTime) { sbuf.setLength(0); START if (localTime == LocalTime.MAX) { END return "24:00:00"; } appendTime(sbuf, localTime); return sbuf.toString(); } @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.

Target:
public synchronized String toString(LocalTime localTime) { sbuf.setLength(0); if (localTime.equals( LocalTime.MAX )) { return "24:00:00"; } appendTime(sbuf, localTime); return sbuf.toString(); }
Source:
public long[] getLargeUpdateCount() { long[] copyCount = uncompressLongUpdateCount(); START return Arrays.copyOf(copyCount, copyCount.length); END } Is copy required here?

Target:
public long[] getLargeUpdateCount() { return uncompressLongUpdateCount(); }
Source:
public int getSQLType(int oid) throws SQLException { if (oid == Oid.UNSPECIFIED) { return Types.OTHER; } START Integer sqlType = _oidToSQLType.get(oid); END if (sqlType != null) { return sqlType; } PgType pgType = fetchPgType(oid); if (pgType == null) { return Types.OTHER; } return pgType.sqlType(); } this access needs to be synchronized

Target:
public synchronized 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(); }
Source:
public void testGetNumericWithoutArg() throws SQLException { START assumeCallableStatementsSupported(); END try (CallableStatement call = con.prepareCall(func + pkgName + "getNumericWithoutArg () }")) { call.registerOutParameter(1, Types.NUMERIC); call.execute(); assertEquals(new BigDecimal(42), call.getObject(1, BigDecimal.class)); } } This can be placed in a `setUp` method.

Target:
public void testGetNumericWithoutArg() throws SQLException { try (CallableStatement call = con.prepareCall(func + pkgName + "getNumericWithoutArg () }")) { call.registerOutParameter(1, Types.NUMERIC); call.execute(); assertEquals(new BigDecimal(42), call.getObject(1, BigDecimal.class)); } }
Source:
public String get(Properties properties) { START return new org.postgresql.util.ExpressionProperties(properties).getProperty(_name, _defaultValue); END } This would have an unexpected consequence if someone has `dfwe${...}asdfa` pattern right inside a password property.

Target:
public String get(Properties properties) { return properties.getProperty(_name, _defaultValue); }
Source:
public void setEncoding(Encoding encoding) throws IOException { // Close down any old writer. START if (encodingWriter != null) { END 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); } 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.

Target:
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) { public void flush() throws IOException { } public void close() throws IOException { super.flush(); } }; encodingWriter = encoding.getEncodingWriter(interceptor); }
Source:
public void getLatestDisplay_CurrentIsNull_DisplayUnchanged() { DisplaySafe safe = new DisplaySafe(null); DisplaySafe safeSpy = spy(safe); when(safeSpy.getCurrent()).thenReturn(null); START boolean nullDisplayExceptionThrown = false; END try { safeSpy.getLatestDisplay(); } catch (DisplaySafe.NullDisplayException nde) { nullDisplayExceptionThrown = true; } assertTrue(nullDisplayExceptionThrown); } 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.

Target:
public void getLatestDisplay_CurrentIsNull_DisplayUnchanged() throws DisplaySafe.NullDisplayException { DisplaySafe safe = new DisplaySafe(null); DisplaySafe safeSpy = spy(safe); when(safeSpy.getCurrent()).thenReturn(null); safeSpy.getLatestDisplay(); }
Source:
public static void setup() throws IOException { FileUtils.deleteDirectory(new File(ODO_CACHE_DIR)); START UsageReportPreferences.setEnabled(false); END UsageReportPreferences.setAskUser(false); } Not needed, there is an env variable wich is set by our jobs.

Target:
public static void setup() throws IOException { FileUtils.deleteDirectory(new File(ODO_CACHE_DIR)); }
Source:
public void publishFinish(IProgressMonitor monitor) throws CoreException { super.publishFinish(monitor); final File localFolder = getDeploymentsRootFolder(); START syncPodsToDirectory(localFolder, monitor); END deleteOldDeployments(getServer()); syncDirectoryToPods(localFolder, monitor); final IResource resource = OpenShiftServerUtils.getResource(getServer(), monitor); loadPodPathIfEmpty(resource, monitor); } 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.

Target:
public void publishFinish(IProgressMonitor monitor) throws CoreException { super.publishFinish(monitor); final File localFolder = getDeploymentsRootFolder(); syncDirectoryToPods(localFolder, monitor); final IResource resource = OpenShiftServerUtils.getResource(getServer(), monitor); loadPodPathIfEmpty(resource, monitor); }
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. START setRule(ResourcesPlugin.getWorkspace().getRuleFactory().createRule(ResourcesPlugin.getWorkspace().getRoot())); END } 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());

Target:
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().getRoot()); }
Source:
private File folderWhiteListBin(File folder) { String[] children = folder.list(); START children = (children == null ? new String[0] : children); END 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; } why wouldn't you simply return null if children is null? Using a 0-length string has the same effect but is less visible.

Target:
private File folderWhiteListBin(File folder) { String[] children = folder.list(); if( children == null ) return null; 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; }
Source:
public static String getProjectAbsolutePath(String... path) { // Construct path StringBuilder builder = new StringBuilder(); for (String fragment : path) { builder.append("/" + fragment); } String filePath = ""; START filePath = System.getProperty("user.dir"); END 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(); } why declare and initialise with an empty string that immediately gets overwritten by the system property?

Target:
public static String getProjectAbsolutePath(String... path) { // Construct path StringBuilder builder = new StringBuilder(); for (String fragment : path) { builder.append("/" + fragment); } String 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(); }
Source:
private void validateOCLocation() { if( selectedConnection != null ) { String ocValString = OCBinary.getInstance().getLocation(selectedConnection); START if( ocValString == null || ocValString.isEmpty()) { END 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(); } } } more expressive would be ```if (StringUtils.isEmpty())```

Target:
private void validateOCLocation() { if (selectedConnection != null) { String ocValString = OCBinary.getInstance().getLocation(selectedConnection); if (StringUtils.isEmpty(ocValString)) { 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(); } } }
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(); START preText = devmodeKeyText.getText(); END this.toggleListener = toggleListener; this.textListener = textListener; } preText? not the most speaking variable name imho

Target:
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; this.preSelected = !useImageDevmodeKeyButton.getSelection(); this.preText = devmodeKeyText.getText(); this.toggleListener = toggleListener; this.textListener = textListener; }
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(); START if (initialDelay >= INITIAL_DELAY) { END OpenShiftServerUtils.setLivenessProbeInitialDelay(initialDelay, context.getServer()); return false; } probe.setInitialDelaySeconds(INITIAL_DELAY); return true; } 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 ?

Target:
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) { return false; } OpenShiftServerUtils.setLivenessProbeInitialDelay(initialDelay, context.getServer()); probe.setInitialDelaySeconds(INITIAL_DELAY); return true; }
Source:
public static String getCurrentBranch(IProject project) throws CoreException { if (project == null) { return null; } START Repository repo = EGitUtils.getRepository(project); END if (repo == null) { return null; } String currentBranch = EGitUtils.getCurrentBranch(repo); repo.close(); return currentBranch; } 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); }

Target:
public static String getCurrentBranch(IProject project) throws CoreException { if (project == null) { return null; } 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))) START .count() > 0; END } 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.

Target:
public static boolean areRelated(final IService service, final IDeploymentConfig dc) { return service.getProject().getResources(ResourceKind.POD).stream() .filter(pod -> dc.getName().equals(pod.getAnnotation(OpenShiftAPIAnnotations.DEPLOYMENT_CONFIG_NAME))) .filter(pod -> containsAll(service.getSelector(), pod.getLabels())) .count() > 0; }