auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public <C> List<Validation<E, C>> traverseList(F<T, List<C>> f){ return isSuccess() ? f.f(success()).map(c -> Validation.<E, C>success(c)) : list(Validation.<E, C>fail(e.left().value())); }

Target:
Method reference for success here, e.g. `map(Validation::success)` I tried this and did not need the types. ``` return isSuccess() ? f.f(success()).map(Validation::success) : List.list(Validation.fail(e.left().value())); ```
Source:
public final <A, B> Effect1<B> comap(Effect1<A> e1, final F<B, A> f) { return b -> { e1.f(f.f(b)); }; }

Target:
Is the use of curly brackets here necessary when we are returning a void value?
Source:
public String toString() { //Don't call getCommand and getData since it causes //AuSetDeferredAttribute to evaluate the deferred value final StringBuffer sb = new StringBuffer(60).append("[cmd=").append(_cmd); if (_data != null && _data.length > 0) { sb.append(", {"); for (AuSetAttribute d : (AuSetAttribute[]) _data) { sb.append(d); } sb.append('}'); } return sb.append(']').toString(); }

Target:
StringBuilder
Source:
public void setConstraint(String constr) { if (!isValidConstraint(constr)) throw new WrongValueException("Invalid constraint: " + constr + " (the constraint should be formatted in yyyyMMdd)"); setConstraint(constr != null ? new SimpleDateConstraint(constr) : null); // Bug 2564298 }

Target:
should put in SimpleDateConstraint
Source:
public String getUpload() { Desktop desktop = getDesktop(); String upload = _auxinf != null ? _auxinf.upload : null; if (desktop != null && !Strings.isEmpty(upload) && !upload.contains("maxsize=")) upload = upload.concat(",maxsize=" + desktop.getWebApp().getConfiguration().getMaxUploadSize()); return upload; }

Target:
not good to add sth when calling getter
Source:
public void testDesktopDestroy() { F85_ZK_1148FileDealer.writeMsg("", false); DesktopAgent da = connect(); da.destroy(); Assert.assertEquals("DestroyD is called!DestroyC is called!IncludeVM is called!", F85_ZK_1148FileDealer.readMsg()); F85_ZK_1148FileDealer.close(); }

Target:
https://github.com/zkoss/zk/pull/1185/files#diff-c52ff1da920c31e56cabddf44f726869R34 You forgot the potential issue
Source:
public static List<String> addProperties(String key, List<String> values) { if (key == null) throw new NullPointerException(); if (key.length() == 0) throw new IllegalArgumentException(); List<String> old = _props.get(key); if (old == null) old = new LinkedList<String>(); old.addAll(values); return _props.put(key, old); }

Target:
the `old`(LinkedList) is not thread-safe, multi-thread addAll might be wrong. You should protect it.
Source:
public static List<String> addProperties(String key, List<String> values) { if (key == null) throw new NullPointerException(); if (key.length() == 0) throw new IllegalArgumentException(); List<String> old = _props.get(key); synchronized (_props) { if (old == null) old = new LinkedList<String>(); old.addAll(values); } return _props.put(key, old); }

Target:
It is better to remain the original code. The fetch-create-put action should be atomic. Or every thread will replace others.
Source:
public static List<String> getProperties(String key) { final List<String> v; v = _props.get(key); return v; }

Target:
just `return _props.get(key);` in this method
Source:
private boolean isCheckmarkDeselectOther() { if (_ckDeselectOther == null) //ok to race _ckDeselectOther = Boolean .valueOf("true".equals(Library.getProperty("org.zkoss.zul.tree.checkmarkDeselectOthers"))); return Utils.testAttribute(this, "org.zkoss.zul.listbox.checkmarkDeselectOthers", _ckDeselectOther.booleanValue(), true); }

Target:
listbox?
Source:
public void test() { connect(); click(jq("$listbox1").toWidget().firstChild()); waitResponse(); Assert.assertTrue(jq("@notification").exists()); waitResponse(); click(jq("body")); waitResponse(); click(jq("$listbox2").toWidget().firstChild()); waitResponse(); Assert.assertTrue(jq("@notification").exists()); waitResponse(); }

Target:
The last `waitResponse` is unnecessary
Source:
public void setLocale(Locale locale) { if (!Objects.equals(_locale, locale)) { _locale = locale; if (getFormat() == null) { if ("en_IN".equals(locale.toString())) { setFormat("en-IN"); } else { setFormat(getDefaultFormat()); } } invalidate(); } }

Target:
Hard-coded. What if we add another format in the future?
Source:
private String getName(URL url) { String name = url.getPath(); if (name != null) { { final int j = name.lastIndexOf(File.pathSeparatorChar); if (j >= 0) name = name.substring(j + 1); } if (File.pathSeparatorChar != '/') { final int j = name.lastIndexOf('/'); if (j >= 0) name = name.substring(j + 1); } } return name; }

Target:
extra { ?
Source:
protected void renderProperties(org.zkoss.zk.ui.sys.ContentRenderer renderer) throws java.io.IOException { super.renderProperties(renderer); if (_columns > 0) renderer.render("columns", _columns); if (_columns > 0 && _start > 0) renderer.render("start", _start); //F85-ZK-3525: frozen support smooth mode (ee only) renderer.render("smooth", isSmooth()); }

Target:
How about use `render(renderer, "smooth", isSmooth());` instead? It will not send additional data if smooth is false.
Source:
public boolean onOptionsItemSelected(MenuItem item) { if (!super.onOptionsItemSelected(item)) { if (item.getItemId() == R.id.clear_history_item) { DBWriter.clearDownloadLog(); return true; } return false; } else { return true; } }

Target:
This will cause a merge conflict with #4244. Please do not change this file.
Source:
public void testFeedListDownloadUrls() { List<Feed> feeds = saveFeedlist(10, 0, false); List<String> urls = DBReader.getFeedListDownloadUrls(); assertNotNull(urls); assertEquals(urls.size(), feeds.size()); for (int i = 0; i < urls.size(); i++) { assertEquals(urls.get(i), feeds.get(i).getDownload_url()); } }

Target:
I'm not 100% sure but I think this should be the other way around. `feeds.size()` seems to be the expected value. This problem is also present in other tests. Before, a failing test just showed something about a failed assertion. Now it shows actual value and expected value, so it is misleading if they are exchanged.
Source:
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { Log.w("DBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + "."); DBUpgrader.upgrade(db, oldVersion, newVersion); if (oldVersion == 1090000) { db.execSQL("ALTER TABLE " + TABLE_NAME_FEEDS + " ADD COLUMN " + KEY_FEED_SKIP_INTRO + " INTEGER DEFAULT 0;"); db.execSQL("ALTER TABLE " + TABLE_NAME_FEEDS + " ADD COLUMN " + KEY_FEED_SKIP_ENDING + " INTEGER DEFAULT 0;"); } }

Target:
Please move this to `DBUpgrader`. Also, use `oldVersion < 1090001`. Users might skip AntennaPod versions. When checking for equality, this skips the migration when coming from, say `1080100` instead of exactly `1090000`.
Source:
public void onStart() { super.onStart(); EventBus.getDefault().register(this); autoDownload = prefs.getString(PREF_AUTO_DOWNLOAD,STRING_NO_FILTER); keepUpdated = prefs.getString(PREF_KEEP_UPDATED,STRING_NO_FILTER); autoDelete = prefs.getString(PREF_AUTO_DELETE,STRING_NO_FILTER); loadSubscriptions(); }

Target:
I think those can be loaded when actually filtering the items. That way, the Fragment does not need to keep preferences as member variables and watch out that they are always updated.
Source:
public String getDescription() { return de.danoeh.antennapod.core.util.TextUtils.getNormalizedText(description); }

Target:
Parsing html should be done outside of `Feed.java`. `Feed` is the model that represents the actual feed. How we display the feed afterwards does not belong to the feed itself, in my opinion.
Source:
private static boolean isHtml(String str) { final String HTML_TAG_PATTERN = "<(\"[^\"]*\"|'[^']*'|[^'\">])*>"; Pattern htmlValidator = TextUtils.isEmpty(HTML_TAG_PATTERN) ? null : Pattern.compile(HTML_TAG_PATTERN); boolean isHtml = htmlValidator.matcher(str).find(); return isHtml; }

Target:
You don't need a variable here
Source:
public static String getPlainText(String str) { if (!TextUtils.isEmpty(str) && isHtml(str)) { HtmlToPlainText formatter = new HtmlToPlainText(); Document feedDescription = Jsoup.parse(str); str = StringUtils.trim(formatter.getPlainText(feedDescription)); } return str; }

Target:
I think it is safer to explicitly return an empty string if TextUtils.isEmpty to prevent crashes at the caller when the description is null.
Source:
private void setSortOrder(SortOrder sortOrder) { boolean keepSorted = UserPreferences.isQueueKeepSorted(); if (keepSorted) { UserPreferences.setQueueKeepSortedOrder(sortOrder); } QueueSorter.sort(sortOrder, true); }

Target:
This does not need to be conditional anymore. If the queue just saves the order every time, it would support first sorting and then checking "keep sorted".
Source:
void onPlayPause() { if(controller == null) { return; } controller.init(); controller.playPause(); }

Target:
Init should only be called one single time when constructing the controller. That is done in OnStart. Please add a space between if and (
Source:
public void onResume() { super.onResume(); onPositionObserverUpdate(); new Thread(() -> controller.init()).start(); }

Target:
Do you actually do any heavy lifting here that needs to happen in the background? If so, why do we still do `controller.init()` in `connectToPlaybackService()` which definitely is executed on the UI thread?
Source:
public boolean onStartJob(JobParameters params) { Log.d(TAG, "Job started"); ClientConfig.initialize(getApplicationContext()); new Thread(() -> { FeedUpdateUtils.startAutoUpdate(getApplicationContext(), true); UserPreferences.restartUpdateAlarm(false); jobFinished(params, false); // needsReschedule = false }).start(); return true; }

Target:
The codes here (spawning new thread, using synchronous version of startAutoUpdate(), etc.) are a tad tricky. A way to reduce the complexity could be changing `FeedUpdateUtils.startAutoUpdate()` to accept a `Runnable onCompleteCallback` parameter, so that 1. At `FeedUpdateJobService` level, it simply calls: ```java FeedUpdateUtils.startAutoUpdate(getApplicationContext(), () -> { UserPreferences.restartUpdateAlarm(false); jobFinished(params, false); // needsReschedule = false }); ``` 2. In the underlying DBTasks.refreshAllFeeds(context, feeds), accept the new parameter `Runnable onCompleteCallback`, and invokes the callback upon completion. - `DBTasks` and `FeedUpdateUtils` thus have no need to expose synchronous version of feed updates.
Source:
public static void refreshAllFeeds(final Context context, final List<Feed> feeds) { new Thread(() -> refreshAllFeedsSynchronously(context, feeds)).start(); }

Target:
that doesn't look right... an executor service is a better abstraction
Source:
private static String getWebsiteLinkWithFallback(Playable media) { String link = null; if (media != null) { link = media.getWebsiteLink(); if (link == null) { if (media instanceof FeedMedia) { link = FeedItemUtil.getLinkWithFallback(((FeedMedia)media).getItem()); } // else case not a FeedMedia, return null } } // else no media, return null return link; }

Target:
In my opinion, this function belongs to `FeedItemUtil`
Source:
public static String getLinkWithFallback(FeedItem item) { String link = null; if (item != null) { link = item.getLink(); if (link == null) { Feed feed = item.getFeed(); if (feed != null) { link = feed.getLink(); } } } // else null item, can only return null return link; }

Target:
I think it is easier to read if you don't use nested `if`s. Same for the other method. ``` if (item == null) { return null; } else if (item.getLink() != null) { return item.getLink(); } else if (item.getFeed() != null) { return item.getFeed().getLink(); } return null; ```
Source:
public String writeToString() { String result = this.podcast + "\t" + this.episode + "\t" + this.deviceId + "\t" + this.action + "\t" + this.timestamp.getTime() + "\t" + String.valueOf(this.started) + "\t" + String.valueOf(this.position) + "\t" + String.valueOf(this.total); return result; }

Target:
You can directly return that instead of creating a String first
Source:
private String buildInOperator(int size) { if (size == 1) { return "(?)"; } String builder = "(" + TextUtils.join(",", Collections.nCopies(size, "?")) + ")"; return builder; }

Target:
You can directly return that instead of creating a String first
Source:
public void onActivityResult(int requestCode, int resultCode, Intent resultData) { if (requestCode == REQUEST_CODE_RESTORE && resultCode == RESULT_OK && resultData != null) { Uri uri = resultData.getData(); restoreFrom(uri); } else if (requestCode == REQUEST_CODE_BACKUP_DOCUMENT && resultCode == RESULT_OK && resultData != null) { Uri uri = resultData.getData(); backupToDocument(uri); } }

Target:
guard clause? ``` if(resultCode != RESULT_OK || resultData == null) return; Uri uri = ... if(requestCode == ... ```
Source:
public void testParseDateWithIncorrectWeekday() { GregorianCalendar exp1 = new GregorianCalendar(2014, 9, 8, 9, 00, 00); exp1.setTimeZone(TimeZone.getTimeZone("GMT")); Date expected = new Date(exp1.getTimeInMillis()); Date actual = DateUtils.parse("Thu, 8 Oct 2014 09:00:00 GMT"); // actually a Wednesday assertEquals(expected, actual); }

Target:
Intellij warns that `00` is octal. Shouldn't be a problem but maybe we can avoid the warnings by just writing a single `0`
Source:
public static String getMimeTypeFromUrl(String url) { if (url != null) { String extension = FilenameUtils.getExtension(url); if (extension != null) { return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } } return null; }

Target:
I would change this to `if(url == null) { return null; }` less indentation, code looks a lot cleaner
Source:
static protected TextView getTxtvFFFromActivity(MediaplayerActivity activity) { return activity.txtvFF; }

Target:
can you change this to `protected static`? This order is really unconventional
Source:
private void updatePlaybackSpeedButton() { if(butPlaybackSpeed == null) { return; } // TODO this possibly needs to change if we introduce an alternative button if (controller == null || !(this instanceof AudioplayerActivity)) { butPlaybackSpeed.setVisibility(View.GONE); return; } updatePlaybackSpeedButtonText(); ViewCompat.setAlpha(butPlaybackSpeed, controller.canSetPlaybackSpeed() ? 1.0f : 0.5f); butPlaybackSpeed.setVisibility(View.VISIBLE); }

Target:
shouldn't AudioplayerActivity override this method to support configuring the button? The default implementation can just return without doing anything. I'd imagine that only the AudioplayerActivity would have a butPlaybackSpeed object and others wouldn't.
Source:
public static FlattrService getService(AccessToken token) { if (flattrService == null) { flattrService = FlattrFactory.getInstance().createFlattrService(token); } return flattrService; }

Target:
still needs `synchronized`, doesn't it?
Source:
void updateData(List<Podcast> result) { this.searchResults = result; adapter.clear(); if (result != null && result.size() > 0) { gridView.setVisibility(View.VISIBLE); txtvEmpty.setVisibility(View.GONE); adapter.addAll(result); adapter.notifyDataSetInvalidated(); } else { gridView.setVisibility(View.GONE); txtvEmpty.setVisibility(View.VISIBLE); } }

Target:
Call requires API level 11 (we are on 10)
Source:
public static boolean setLockscreenBackground() { return prefs.getBoolean(PREF_LOCKSCREEN_BACKGROUND, false); }

Target:
I think 'false' needs to get changed to true. For some reason the 'default' in the preferences doesn't work otherwise. It shows up as being checked but doesn't actually work until you uncheck/check it again. I'm not sure why it works this way. :( (Tested on 5.0.0 and 5.1)
Source:
public GuiceBundle<T> build() { return new GuiceBundle<T>(Stage.PRODUCTION, autoConfig, modules, configurationClass); }

Target:
Why not simply call? ``` return build(Stage.PRODUCTION); ```
Source:
public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { TreeNode treeNode = jp.readValueAsTree(); JsonNode oid = ((JsonNode) treeNode).get(MONGO_QUERY_OID); if (oid != null) return oid.asText(); else if(treeNode.isValueNode() && treeNode instanceof TextNode) { return ((JsonNode) treeNode).textValue(); } else return treeNode.toString(); }

Target:
Instead of calling toString() on treeNode what about calling asText() instead. It seems ok and 'else if' condition is no longer needed
Source:
public void setCharset(String charset) { if(charset == null) { throw new UnsupportedCharsetException("provided mediatype does not support setting charset"); } if(StringUtils.isNotEmpty(charset)) { this.charset = Charset.forName(charset); } }

Target:
Hier bedoel je dan denk ik if (this.charset == null)
Source:
public void testAdd() throws ArrayIndexOutOfBoundsException { SizeLimitedVector slv = new SizeLimitedVector(10); slv.add("testString"); assertEquals(slv.getMaxSize(), 10); assertEquals(slv.get(0), "testString"); }

Target:
You dont have to declare this RuntimeException here do you? Non of the functions are throwing any exceptions
Source:
private String determineDestination(ParameterValueList pvl) { if (StringUtils.isNotEmpty(getDestination())) { return getDestination(); } if (pvl!=null && pvl.containsKey(PARAMETER_DESTINATION)) { return pvl.getParameterValue(PARAMETER_DESTINATION).asStringValue(""); } return null; }

Target:
Wat als deze leeg is? Kan je niet beter NULL teruggeven?
Source:
public void testEmptySessionKeyEmptyInput() throws Exception { exception.expect(NullPointerException.class); pipe.setSessionKey(null); session.put("a", "123"); PipeRunResult res = doPipe(pipe, null, session); assertEquals(res.getResult().toString(), "[null]"); }

Target:
Setters cannot be null (they would not be set). They can however be empty `""`
Source:
public Message(Object request) { if (request instanceof Message) { this.request = ((Message)request).asObject(); } else { this.request = request; } }

Target:
Hoe kan hij hier in komen als de input al een Message is?
Source:
private ArrayList<String> getSuperClasses(Class clazz) { ArrayList<String> superClasses = new ArrayList<String>(); int index = 0; while (clazz.getSuperclass() != null) { // Assign a string with a priority number attached to it and add it to the array of superclasses String str = Integer.toString(index); superClasses.add(clazz.getSimpleName() + str); clazz = clazz.getSuperclass(); index++; } return superClasses; }

Target:
Waarom voeg je de index aan de naam toe? De lijst is toch op dezelfde volgorde als de index?
Source:
public void add(String message, Throwable t) { String msgToLog = message; if(t.getMessage() != null) { msgToLog += ": "+t.getMessage(); } add(msgToLog); log.error(msgToLog, t); }

Target:
zou een warning hier niet meer op z'n plaats zijn?
Source:
protected int getNumberOfPages(File file) { int result = 0; if(file != null) { try (InputStream inStream = new FileInputStream(file)){ Document doc = new Document(inStream); result = doc.getPages().size(); System.out.println(" get number of pages has ben executed "+result); } catch (IOException e) { System.out.println(e); } } return result; }

Target:
Code should not contain System.out.println(). Please remove all occurrences, or replace with appropriate logging.
Source:
private CisConversionResult createFailureResult(String filename, ConversionOption conversionOption, MediaType mediaType, String message) { CisConversionResult result; StringBuilder msg = new StringBuilder(); if (filename != null) { msg.append(filename); } msg.append(" " + message); LOGGER.info("Conversion not supported: " + msg.toString()); result = CisConversionResult.createFailureResult(conversionOption, mediaType, filename, msg.toString()); return result; }

Target:
This is warning
Source:
public SameSiteCookieHandler(final HttpHandler next, final String mode) { this(next, mode, null, false); }

Target:
do we want to have a disable client checker with a default value set to false, or do we want to have a enable-client-checker with a default value set to true? I wonder how does this work in the long term pov, do we expect to still have a long list of incompatible user agents in the future?
Source:
public String getLocalName() { String hostName = exchange.getDestinationAddress().getHostName(); if (hostName == null) { //return the IP as string return exchange.getDestinationAddress().getHostString(); } return hostName; }

Target:
Hi @tmiyargi @fl4via and/or @stuartwdouglas will have a final say on this one. I'm just a lurker in this project. Having said that, I think the backward compatiblity of this shouldn't play a role here, because this bug fix is about fixing a wrong value that was being retuned, before this change.
Source:
public Long getContentLength() { try { if (Files.isSymbolicLink(file) && Files.notExists(file)) { return 0L; } return Files.size(file); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
I think this should be null as well
Source:
private SerializedValue getSerializedValue(RestAction<?> action, Object object) throws ActionException { String bodyClass = action.getBodyClass(); if (bodyClass != null) { List<ContentType> contentTypes = action.getClientProducedContentTypes(); Serialization serialization = findSerialization(bodyClass, contentTypes); if (serialization != null) { try { return serialize(serialization, object, bodyClass, contentTypes); } catch (SerializationException e) { throw new ActionSerializationException(e); } } } throw new ActionSerializationException( "Unable to serialize request body. No serializer found."); }

Target:
I think it was more readable with `try-catch` was part of `serialize`
Source:
public void resolve_hasAnnotations_hasNoCookieParams() { // given HasAnnotations hasAnnotations = mock(HasAnnotations.class); // when String value = resolver.resolve(hasAnnotations); // then assertThat(value).isEqualTo(SOME_VALUE); }

Target:
I think the assert should be that `value` is null. It looks like it's your assert that is throwing the NPE
Source:
public ActionBinding generate() throws UnableToCompleteException { String implName = getSuperTypeName() + SUFFIX; PrintWriter printWriter = getGeneratorUtil().tryCreatePrintWriter(getPackage(), implName); if (printWriter != null) { try { doGenerate(implName, printWriter); registerMetadata(); } finally { printWriter.close(); } } else { getLogger().debug("Action already generated. Returning."); } return createActionBinding(implName); }

Target:
It would save a lot of duplication if you move this try finally up into mergeTemplate. The printwriter is never used after it's called anyways.
Source:
public DispatchRequest undo(LogInAction action, LogInResult result, AsyncCallback<Void> callback, UndoCommand<LogInAction, LogInResult> undoCommand) { undoCommand.undo(action, result, callback); return new CompletedDispatchRequest(); }

Target:
`return undoCommand.undo(action, result, callback);`
Source:
public DispatchCall(ExceptionHandler exceptionHandler, SecurityCookieAccessor securityCookieAccessor, A action, AsyncCallback<R> callback) { this.action = action; this.callback = callback; this.exceptionHandler = exceptionHandler; this.securityCookieAccessor = securityCookieAccessor; prepareCall(); }

Target:
This should be done later in the class life cycle (not in the ctor)
Source:
protected <T> GinLinkedBindingBuilder<T> bindAnnotated(Class<T> clazz) { GinAnnotatedBindingBuilder<T> binding = bind(clazz); if (annotationClass != null) { return binding.annotatedWith(annotationClass); } return binding; }

Target:
Revert to private
Source:
protected EventBus getEventBus() { return eventBus; }

Target:
The final was there so that the user can't override the method.
Source:
public Widget asWidget() { return getView() == null ? null : getView().asWidget(); }

Target:
view should never be null. If anything the contract should be enforced in the ctor and the check here removed.
Source:
public void removeFromParentSlot() { assert parent != null : "Tried to remove a presenter that has no parent from its parent"; parent.removeFromSlot(slot, this); }

Target:
Do you think naming it `removeFromParent()` could be enough?
Source:
public LogInHandler(Logger logger, Authenticator authenticator, UserSessionDao loginCookieDao) { super(LogInAction.class); this.logger = logger; this.authenticator = authenticator; this.loginCookieDao = loginCookieDao; }

Target:
rm public
Source:
protected DispatchRequest doExecute() { super.doExecute(); try { RequestBuilder requestBuilder = buildRequest(); return new GwtHttpDispatchRequest(requestBuilder.send()); } catch (RequestException | ActionException e) { onExecuteFailure(e); } return new CompletedDispatchRequest(); }

Target:
Java 7 rocks for that :D
Source:
public void iNavigateTo(String nameToken) { if (nameToken.equals(NameTokens.LOGIN)) { applicationPage.navigateToNotLoggedIn(nameToken); } else { applicationPage.navigateToWithMenu(nameToken); } }

Target:
Do it the other way around, it's safer to do : `NameTokens.LOGIN.equals(nameToken)`
Source:
public ResourceLoader(AppResources resources, WidgetResources widgetResources) { resources.styles().ensureInjected(); widgetResources.header().ensureInjected(); }

Target:
rm public
Source:
protected void onReveal() { ActionBarVisibilityEvent.fire(this, false); if (!Strings.isNullOrEmpty(getLoggedInCookie())) { tryLoggingInWithCookieFirst(); } if (!currentUser.isLoggedIn() && !isOnLoginPage()) { PlaceRequest p = new Builder().nameToken(NameTokens.login).with(REDIRECT_PARAMETER_NAME, getHistoryToken()).build(); placeManager.revealPlace(p); } }

Target:
For better readability, maybe on multiple lines?
Source:
public CrawlFilter(@ServiceUrl String serviceUrl, @ServiceKey String key, Logger log) { this.serviceUrl = serviceUrl; this.key = key; this.log = log; }

Target:
rm public
Source:
public void setUp(HttpRequestBuilderFactory httpRequestBuilderFactory, UrlUtils urlUtils) { requestBuilder = mock(RequestBuilder.class); given(httpRequestBuilderFactory.create(any(Method.class), anyString())).willReturn(requestBuilder); given(urlUtils.encodeQueryString(DECODED_VALUE_1)).willReturn(ENCODED_VALUE_1); given(urlUtils.encodeQueryString(DECODED_VALUE_2)).willReturn(ENCODED_VALUE_2); given(urlUtils.encodeQueryString(DECODED_VALUE_3)).willReturn(ENCODED_VALUE_3); }

Target:
you could `forceMock(RequestBuilder.class` and `@Inject` it as a field of `DefaultRestRequestBuilderFactoryTest`
Source:
GoogleAnalyticsNavigationTracker( @GaAccount String gaAccount, PlaceManager placeManager, EventBus eventBus, GoogleAnalytics analytics) { this.gaAccount = gaAccount; this.placeManager = placeManager; this.eventBus = eventBus; this.analytics = analytics; if (GWT.isScript()) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { init(); } }); } }

Target:
Not needed anymore, they seems to have fixed the bug with "localhost" within ga.js
Source:
public ActionMetadataProviderGenerator( TypeOracle typeOracle, Logger logger, Provider<VelocityContext> velocityContextProvider, VelocityEngine velocityEngine, GeneratorUtil generatorUtil, EventBus eventBus) { super(typeOracle, logger, velocityContextProvider, velocityEngine, generatorUtil); eventBus.register(this); }

Target:
rm public
Source:
public ServiceDefinitions(Logger logger, TypeOracle typeOracle, GeneratorUtil generatorUtil) throws UnableToCompleteException { this.logger = logger; this.typeOracle = typeOracle; this.generatorUtil = generatorUtil; findAllServices(); }

Target:
You can rm public
Source:
public void onFailure(Throwable caught) { if (hasResponse()) { GWT.log("HTTP " + getResponse().getStatusCode() + ": " + getResponse().getStatusText()); } Message message = new Message(translateCauses(caught), MessageStyle.ERROR); DisplayMessageEvent.fire(hasHandlers, message); }

Target:
you should remove this log.
Source:
public void revealDefaultPlace() { revealPlace(new PlaceRequest(NameTokens.getHome())); }

Target:
should add the false parameter so that when first entering the app, we don't end up blocked in the app.
Source:
short getCurrentTimeMillis() { return (short) System.currentTimeMillis(); }

Target:
How about using proper bitmasking to make the usage of the two last timestamp bytes more obvious?
Source:
public void setDynamicMdcFieldType(String fieldPattern, String type) { final Pattern pattern = Pattern.compile(fieldPattern); dynamicMdcFieldTypes.put(pattern, type); }

Target:
Nit: No need for `final`.
Source:
private void setupDynamicMdcFieldTypes(PropertyProvider propertyProvider) { int fieldNumber = 0; while (true) { final String property = propertyProvider.getProperty(PropertyProvider.PROPERTY_DYNAMIC_MDC_FIELD_TYPES + fieldNumber); if (null == property) { break; } final int index = property.indexOf('='); if (-1 != index) { String field = property.substring(0, index); String type = property.substring(index + 1); setDynamicMdcFieldType(field, type); } fieldNumber++; } }

Target:
Nit: No need for `final`.
Source:
private String getMatchingDynamicMdcFieldType(String fieldName) { String fieldType = null; for (final Map.Entry<Pattern, String> entry : dynamicMdcFieldTypes.entrySet()) { if(entry.getKey().matcher(fieldName).matches()) { fieldType = entry.getValue(); break; } } return fieldType; }

Target:
Nit: No need for `final`.
Source:
protected boolean connect() throws IOException { if (isConnected()) { return false; } if (super.connect()) { this.sslEngine = sslContext.createSSLEngine(); this.sslEngine.setUseClientMode(true); this.sslSession = sslEngine.getSession(); // Begin handshake sslEngine.beginHandshake(); doHandshake(channel(), sslEngine, ByteBuffer.allocate(sslSession.getPacketBufferSize()), ByteBuffer.allocate(sslSession.getPacketBufferSize())); } return false; }

Target:
This check is superfluous as `super.connect()` does the same check. We can safely remove this `if` block here.
Source:
public static void checkArgument(boolean expression, String errorMessage, String... args) { if (!expression) { if (args != null && args.length > 0) { String message = String.format("errorMessage", args); throw new IllegalArgumentException(message); } else { throw new IllegalArgumentException(errorMessage); } } }

Target:
`errorMessage` shouldn't be quoted.
Source:
public String toString() { return "BasicDistributionSummary{config=" + config + ", totalAmount=" + totalAmount + ", count=" + count + ", max=" + max + ", min=" + min + ", monitors=" + monitors + '}'; }

Target:
Was it intentional to add the monitors list to the toString output? That seems redundant with the count, min, and max fields already there.
Source:
public int hashCode() { int result = config.hashCode(); result = 31 * result + totalAmount.hashCode(); result = 31 * result + count.hashCode(); result = 31 * result + max.hashCode(); result = 31 * result + min.hashCode(); result = 31 * result + monitors.hashCode(); return result; }

Target:
The monitors list was added to the hash code here, but not for BasicTimer. I don't think it will change the result in this case, but any reason it isn't consistent for both?
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !(obj instanceof MaxGauge)) { return false; } MaxGauge m = (MaxGauge) obj; return config.equals(m.getConfig()); }

Target:
What is the use-case for equality of the gauge being based on the config only? Would it make more sense to just use the default equals/hashCode for the gauge and expect equality checks to use the config directly?
Source:
public <T> String display(Type targetType, T value) throws HTMLDisplayerException { if (targetType == null && value != null) { return getHTMLDisplayer(value.getClass()).display(value); } else { return getHTMLDisplayer(targetType).display(value); } }

Target:
Just a detail: I would have probably created a private (maybe it make sense even in public not sure) getHTMLDisplayer(Type targetType, Object value) to put this logic in a common method.
Source:
public boolean isDeprecated() { return deprecated; }

Target:
missing `this`
Source:
public DatabaseJoinData() { super(); notfound = null; }

Target:
Why are we keeping `notfound = null`? Won't it be `null` without this?
Source:
public void setMaxSize( int maxSize ) { this.maxSize = maxSize; }

Target:
Could this method, and setPurgeTimeout, be package-private? Still testable, and reduces risk of misuse.
Source:
private boolean safeWaitForCompletion( Future future, long timeoutSeconds ) { try { future.get( timeoutSeconds, TimeUnit.SECONDS ); } catch ( TimeoutException te ) { System.out.println( "Thread timed out." ); return false; } catch ( InterruptedException | ExecutionException e ) { fail(); } return true; }

Target:
Replace sysout. Maybe just fail(message)?
Source:
public void init(FMLInitializationEvent evt) { try { Natura.logger.debug("[MFR] Registering Natura trees/plants/crops with MFR Farming Registry."); MRFRegistering.registerWithMFR(); } catch (Throwable t) { Natura.logger.debug("Something went wrong in Natura plugin MineFactoryReloaded.", t); } }

Target:
this should stay in warn
Source:
private static boolean isEjbModule(IModule module) { IModuleType type = module.getModuleType(); return IWTPConstants.FACET_EJB.equals(type.getId()); //$NON-NLS-1$ }

Target:
After some thoughs, shouldn't we check that the module is a Web module instead of excluding EJB modules ?
Source:
public int getUnhealthy() { return unhealthy ? 1 : 0; }

Target:
It's sort of weird that the getter is an int but the setter is a boolean. Can we just make everything an int, including the underlying variable? Also, did you consider making this an error count instead of just 1/0 since that would provide additional information?
Source:
private static int findFreePort() throws IOException { try (ServerSocket socket = new ServerSocket(0);) { return socket.getLocalPort(); } }

Target:
Unnecessary semicolon
Source:
public void testKerberosAuthenticatorExceptionInExecute() throws Exception { String principal = flumePrincipal; String keytab = flumeKeytab.getAbsolutePath(); // Clear the previous statically stored logged in credentials FlumeAuthenticationUtil.clearCredentials(); FlumeAuthenticator authenticator = FlumeAuthenticationUtil.getAuthenticator(principal, keytab); assertTrue(authenticator instanceof KerberosAuthenticator); authenticator.execute(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { throw new IOException(); } }); }

Target:
I think this cleanup should be part of tearDown. (Here and in other tests as well.)
Source:
private FlumeEventAvroEventDeserializer(Context context, ResettableInputStream ris) { this.ris = ris; schemaType = AvroSchemaType.valueOf( context.getString(CONFIG_SCHEMA_TYPE_KEY, AvroSchemaType.HASH.toString()).toUpperCase(Locale.ENGLISH)); if (schemaType == AvroSchemaType.LITERAL) { logger.warn(CONFIG_SCHEMA_TYPE_KEY + " set to " + AvroSchemaType.LITERAL.toString() + ", so storing full Avro " + "schema in the header of each event, which may be inefficient. " + "Consider using the hash of the schema " + "instead of the literal schema."); } }

Target:
This (line 48-57) is a copy-paste from `AvroEventDeserializer`. Could you please simplify it by pushing it (from here and from the `AvroEventDeserializer`) up to the `AbstractAvroEventDeserializer`? If the logic is moved to the parent class then its `schemaType` field can be changed to `private final`.
Source:
public LatestLinkBuilder(File dir) throws IOException { System.out.println(String.format("Writing plugin symlinks and redirects to dir: %s", dir)); index = new IndexHtmlBuilder(dir,"Permalinks to latest files"); htaccess = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir,".htaccess")), "UTF-8")); htaccess.println("# GENERATED. DO NOT MODIFY."); // Redirect directive doesn't let us write redirect rules relative to the directory .htaccess exists, // so we are back to mod_rewrite htaccess.println("RewriteEngine on"); }

Target:
Hasn't the second parameter `true` (for `autoFlush`) been forgotten in the go?
Source:
public String getString(String key, String defaultValue) { Object value = getRawProperty(key); if (value == null) { return notFound(key, defaultValue != null ? interpolator.create(getLookup()).resolve(defaultValue) : null); } if (value instanceof String) { return resolve(value.toString()); } else { return value.toString(); } }

Target:
casting would be faster...
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; throw new ProvisionException("Only one ArchaiusModule may be installed"); }

Target:
Having equals throw to enforce a singleton module policy seems unintuitive. Does this really add much over the normal duplicate binding for Config error?
Source:
public DynamicBooleanProperty(String propName, boolean defaultValue) { super(propName, Boolean.valueOf(defaultValue)); // Set the initial value of the cached primitive value. this.primitiveValue = chooseValue(); // Add a callback to update the cached primitive value when the property is changed. this.prop.addCallback(new Runnable() { @Override public void run() { primitiveValue = chooseValue(); } }); }

Target:
Rather than adding this callback here, you could just override either of the propertyChanged methods and then update the PropertyWrapper class to not add this class to the SUBCLASSES_WITH_NO_CALLBACK map. This would be cleaner and probably result in less overall code.
Source:
public String getValue(ContextKey key) { if (delegate == null) { LOG.debug("Configuration not yet initialized. Returning 'null' for " + key); return null; } return delegate.getValue(key); }

Target:
Just curious, why does this class use logging but StaticAbstractConfiguration is being changed to System.err?
Source:
public void close() { try { Closeables.close(pathChildrenCache, true); } catch (IOException exc) { logger.warn("IOException should not have been thrown.", exc); } }

Target:
If you want to maintain the same behavior as before you should probably log this as ERROR since guava is logging it as SEVERE.
Source:
protected void propertyChanged() { super.propertyChanged(); // derived.set(this.derive(this.get())); deriveAndSet(); }

Target:
what if people override this method and forget to call super.propertyChanged(). Then the derived value will no longer be available. You might want to look at DynamicSetProperty and see if you can use the same trick to avoid that from happening.
Source:
void propertyChangedInternal() { propertyChanged(); deriveAndSet(); }

Target:
I think deriveAndSet() should be called first. Then in propertyChanged(), users can call get to get() the updated derived value.
Source:
private boolean isLogDataValid(long address, ILogData logData, boolean throwException) { if (logData == null || logData.getType() == DataType.EMPTY) { throw new RuntimeException("Unexpected return of empty data at address " + address + " on read"); } if (logData.isTrimmed()) { if (throwException) { throw new TrimmedException(Collections.singletonList(address)); } return false; } return true; }

Target:
Cleaner to push down to the constructor.
Source:
public void start() { // The DISCOVERY_INIT_TOPOLOGY should be the first event to be processed for both ACTIVE and STANDBY sites. this.eventQueue.add(new DiscoveryServiceEvent(DISCOVER_INIT_TOPOLOGY)); this.executorService.submit(this::run); startDiscovery(); }

Target:
wasn't the purpose of DISCOVER_INIT_TOPOLOGY to call startDiscovery from there? DISCOVER_INIT_TOPOLOGY is not a supported event (processEvent)
Source:
LogReplicationEntry generateMessageWithOpaqueEntryList(List<OpaqueEntry> opaqueEntryList, UUID logEntryRequestId) { // Set the last timestamp as the max timestamp currentMsgTs = opaqueEntryList.get(opaqueEntryList.size() - 1).getVersion(); LogReplicationEntry txMessage = new LogReplicationEntry(MSG_TYPE, topologyConfigId, logEntryRequestId, currentMsgTs, preMsgTs, globalBaseSnapshot, sequence, opaqueEntryList); preMsgTs = currentMsgTs; sequence++; log.trace("Generate a log entry message with transactions ", txMessage.getMetadata(), opaqueEntryList.size()); return txMessage; }

Target:
nit - extra newline
Source:
boolean shouldProcess(OpaqueEntry entry) { Set<UUID> tmpUUIDs = entry.getEntries().keySet(); //If the entry's stream set is a subset of interested streams, it is the entry we should process if (streamUUIDs.containsAll(tmpUUIDs)) { return true; } //If the entry's stream set has no overlap with the interested streams, it should be skipped. tmpUUIDs.retainAll(streamUUIDs); if (tmpUUIDs.isEmpty()) { return false; } // If the entry's stream set contains both interested streams and other streams, it is not // the expected behavior log.error("There are noisy streams in the entry, expected streams set {}", entry.getEntries().keySet(), streamUUIDs); hasNoiseData = true; return false; }

Target:
private
Source:
public LogReplicationMetadata.ReplicationStatusVal queryReplicationStatus() { return corfuReplicationDiscoveryService.queryReplicationStatus( topologyConfig.getClusters(0).getId()); }

Target:
It's not guaranteed to always place the local cluster in the 0th index position right? Am I mistaken?
Source:
long query(CorfuStoreMetadata.Timestamp timestamp, LogReplicationMetadataType key) { long val = -1; String str = queryString(timestamp, key); if (str != null) { val = Long.parseLong(str); } return val; }

Target:
Lets add public/private accessor. It should be private right. as we have wrappers for each metadata type.
Source:
long getLastProcessed() { return logReplicationMetadataManager.getLastProcessedLogTimestamp(null); }

Target:
private, public?
Source:
TxBuilder getTxBuilder() { return corfuStore.tx(namespace); }

Target:
private
Source:
public CompletableFuture<LogReplicationEntry> sendWithBuffering(LogReplicationEntry message) { //todo need to be removed. message.getMetadata().setSnapshotSyncSeqNum(maxAckedMsgSeqNum++); pendingMessages.append(message); log.info("Send messsage {}", message.getMetadata()); CompletableFuture<LogReplicationEntry> cf = dataSender.send(message); addCFToAcked(message, cf); return cf; }

Target:
I think we can remove this or downgrade to trace as we already log right before sending.
Source:
private void completeSnapshotApply(LogReplicationEntry inputEntry) { log.debug("Complete of a snapshot apply"); //check if the all the expected message has received rxState = RxState.LOG_ENTRY_SYNC; logReplicationMetadataManager.setSnapshotApplied(inputEntry); logEntrySinkBufferManager = new LogEntrySinkBufferManager(ackCycleTime, ackCycleCnt, bufferSize, logReplicationMetadataManager.getLastProcessedLogTimestamp(), this); log.info("Sink manager completed SNAPSHOT transfer for and has transit to state.", inputEntry, rxState); }

Target:
Do we need a new BufferManager on every snapshotApply? or could we just reset?
Source:
private CompletableFuture<CorfuInterClusterReplicationServerNode> startDiscoveryService(ServerContext serverContext) throws InterruptedException { log.info("Start Discovery Service."); CompletableFuture<CorfuInterClusterReplicationServerNode> discoveryServiceCallback = new CompletableFuture<>(); this.clusterManagerAdapter = buildClusterManagerAdapter(serverContext.getPluginConfigFilePath()); // Start LogReplicationDiscovery Service, responsible for // acquiring lock, retrieving Site Manager Info and processing this info // so this node is initialized as Source (sender) or Sink (receiver) replicationDiscoveryService = new CorfuReplicationDiscoveryService(serverContext, clusterManagerAdapter, discoveryServiceCallback); return discoveryServiceCallback; }

Target:
throws InterruptedException is not used.
Source:
public CompletableFuture<LogReplicationQueryMetadataResponse> sendQueryMetadataRequest() { return null; }

Target:
I think we can return new CompletableFuture<>(); Otherwise, we hit NPE...
Source:
public void cleanShutdown() { log.info("CleanShutdown: Starting Cleanup."); shutdownServer = true; activeServer.close(); replicationDiscoveryService.shutdown(); clusterManagerAdapter.shutdown(); }

Target:
Need to check those variables are initialized or not to avoid NPE.
Source:
public TopologyDescriptor(TopologyConfigurationMsg topologyMessage) { this.topologyConfigId = topologyMessage.getTopologyConfigID(); this.certs = topologyMessage.getCerts(); standbyClusters = new HashMap<>(); for (ClusterConfigurationMsg clusterConfig : topologyMessage.getClustersList()) { ClusterDescriptor siteInfo = new ClusterDescriptor(clusterConfig); if (clusterConfig.getRole() == ClusterRole.ACTIVE) { activeCluster = siteInfo; } else if (clusterConfig.getRole() == ClusterRole.STANDBY) { addStandbySite(siteInfo); } } }

Target:
Do we assume that topologyMessage from the cluster manager is always valid? I mean it always has only one active cluster. If not, we can throw an exception or at least have some debug logs.
Source:
private Layout updateLayoutAndGet() { return getCorfuRuntime() .invalidateLayout() .thenApply(serverContext::saveManagementLayout) .join(); }

Target:
what's the motivation, why you need to update the layout? FD is in charge of doing it, not sure if it safe to update the layout here
Source:
public int getSizeEstimate() { byte[] tempData = data; if (tempData != null) { return tempData.length + metadataMap.size() + DataType.values().length; } else if (lastKnownSize != NOT_KNOWN) { return lastKnownSize; } log.warn("getSizeEstimate: LogData size estimate is defaulting to 1," + " this might cause leaks in the cache!"); return 1; }

Target:
metadataMap.size() is the number of entries, not the size.
Source:
public void AddNodeDuringInvalidateLayoutTest() { workflow(wf -> { wf.setupDocker(fixture -> { fixture.getCluster().numNodes(3); }); wf.deploy(); try { addNodeDuringInvalidateLayout(wf); } catch (Exception e) { Assertions.fail("Test failed: " + e); } } ); }

Target:
it is a 3 node cluster by default, don't need to specify it
Source:
public void channelActive(final ChannelHandlerContext ctx) throws Exception { log.trace("channelActive: Incoming connection established from: Start Read Timeout.", ctx.channel().remoteAddress()); ctx.pipeline().addBefore(ctx.name(), READ_TIMEOUT_HANDLER, new ReadTimeoutHandler(this.timeoutInSeconds)); }

Target:
This log statement I believe is also relevant when we're not sure if the connection from one client to a server is established. It is useful, I think we should leave it as INFO or DEBUG.
Source:
public List<SMREntry> current() { ILogData data = streamView.current(); if (data != null && data.isHole()) { throw new HoleInStreamException(); } if (data == null || data.getType() != DataType.DATA || !(data.getPayload(runtime) instanceof ISMRConsumable)) { return Collections.emptyList(); } return ((ISMRConsumable) data.getPayload(runtime)).getSMRUpdates(streamView.getId()); }

Target:
Rather than signaling this condition via an exception, maybe a better approach would be to have a globally unique instance that signals a hole.
Source:
private void updatePointer(final ILogData data) { // Update the global pointer, if it is non-checkpoint data. if ((data.isData() && !data.hasCheckpointMetadata()) || (data.isHole() && (data.getBackpointerMap().isEmpty() || data.containsStream(getCurrentContext().id))) ) { // Note: here we only set the global pointer and do not validate its position with respect to the trim mark, // as the pointer is expected to be moving step by step (for instance when syncing a stream up to maxGlobal) // The validation is deferred to these methods which call it in advance based on the expected final position // of the pointer. getCurrentContext().setGlobalPointer(data.getGlobalAddress()); } }

Target:
I think we probably don't need to check containsStream here because when we call this method, logdata that does not belong to this stream should already be filtered out, could you double check?
Source:
public void setServer(AbstractServer server) { router.reset(); router.setIgnoreMessageValidation(true); router.addServer(server); }

Target:
Why ignore the epoch/cluster id check?
Source:
default void sendWrongEpochMessage(CorfuMsg msg, ChannelHandlerContext ctx) { sendResponse(ctx, msg, new CorfuPayloadMsg<>(CorfuMsgType.WRONG_EPOCH, getServerEpoch())); log.warn("Incoming message with wrong epoch, got {}, expected {}, message was: {}", msg.getEpoch(), getServerEpoch(), msg); }

Target:
This log line and the the ones in the following methods are trace level in master, why we made it warning level?