id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_9543
private Date lastSeen; private String barcode; - public HistoryProduct() {} - public HistoryProduct(String title, String brands, String url, String barcode) { this.title = title; this.brands = brands; you could remove the default constructor right ? private Date lastSeen; private String barcode; public HistoryProduct(String title, String brands, String url, String barcode) { this.title = title; this.brands = brands;
codereview_java_data_9549
*/ public void setCurrentGroupExprData(Expression expr, Object obj) { if (cachedLookup == expr) { - assert currentGroupByExprData[cachedLookupIndex] != null; currentGroupByExprData[cachedLookupIndex] = obj; } Integer index = exprToIndexInGroupByData.get(expr); if (index != null) { - assert currentGroupByExprData[index] != null; currentGroupByExprData[index] = obj; return; } I got an assertion error here in the original test case. */ public void setCurrentGroupExprData(Expression expr, Object obj) { if (cachedLookup == expr) { + assert currentGroupByExprData[cachedLookupIndex] == null; currentGroupByExprData[cachedLookupIndex] = obj; } Integer index = exprToIndexInGroupByData.get(expr); if (index != null) { + assert currentGroupByExprData[index] == null; currentGroupByExprData[index] = obj; return; }
codereview_java_data_9557
import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.KeeperException.NotEmptyException; public class ZooQueueLock implements QueueLock { - private static final String PREFIX = "zlock#" + UUID.randomUUID() + "#"; private ZooReaderWriter zoo; private String path; If it is required that this PREFIX here and the ZLOCK_PREFIX in ZooLock match, then maybe the definition should be placed in Constants and shared. (Not saying that the should be the same, that's a different discussion) import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.KeeperException.NotEmptyException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ZooQueueLock implements QueueLock { + private static final Logger log = LoggerFactory.getLogger(ZooQueueLock.class); + private static final String PREFIX = "lock-"; private ZooReaderWriter zoo; private String path;
codereview_java_data_9568
public ApplicationGenerator withAddons(AddonsConfig addonsConfig) { if (addonsConfig.useMonitoring()) { - this.labelers.add(new PrometheusLabeler()); } return this; } Side note because it is not related to this PR. This code is quite error prone, if `withAddons` is invoked multiple times, multiple `PrometheusLabeler`s are created public ApplicationGenerator withAddons(AddonsConfig addonsConfig) { if (addonsConfig.useMonitoring()) { + this.labelers.put(PrometheusLabeler.class, new PrometheusLabeler()); } return this; }
codereview_java_data_9570
* populated list of locks held by transaction - or an empty map if none. * @return current fate and lock status */ - public FateStatus getTransactionStatus(ReadOnlyTStore<T> zs, Set<Long> filterTxid, EnumSet<TStatus> filterStatus, Map<Long,List<String>> heldLocks, Map<Long,List<String>> waitingLocks) { Seems like it may make sense to make this private and have something like the following two public methods that call it. ```java public FateStatus getStatus(ReadOnlyTStore<T> zs, IZooReader zk, String lockPath, Set<Long> filterTxid, EnumSet<TStatus> filterStatus) public List<TransactionStatus> getTransactionStatus(ReadOnlyTStore<T> zs, IZooReader zk, Set<Long> filterTxid, EnumSet<TStatus> filterStatus) ``` * populated list of locks held by transaction - or an empty map if none. * @return current fate and lock status */ + private FateStatus getTransactionStatus(ReadOnlyTStore<T> zs, Set<Long> filterTxid, EnumSet<TStatus> filterStatus, Map<Long,List<String>> heldLocks, Map<Long,List<String>> waitingLocks) {
codereview_java_data_9572
Package timePackage = pkg.getDependencies().get(0); assertThat(timePackage).isNotNull(); - assertThat(timePackage.getConfigValues().getRaw()).contains("\"foo.expression\": \"\\\\\\\\d\""); assertThat(timePackage.getConfigValues().getRaw()).contains("\"bar\": \"\\\\d\""); - assertThat(timePackage.getConfigValues().getRaw()).contains("\"complex.expression\": \"#jsonPath(payload,'$.name') matches '\\\\\\\\d*'\""); - assertThat(timePackage.getConfigValues().getRaw()).contains("\"bar.expression\": \"\\\\\\\\d \\\\\\\\ \\\\0 \\\\a \\\\b \\\\t \\\\n \\\\v \\\\f \\\\r \\\\e \\\\N \\\\_ \\\\L\\\n" - + " \\ \\\\P \\\\\\\\\""); } @Test what is going on here? Package timePackage = pkg.getDependencies().get(0); assertThat(timePackage).isNotNull(); + assertThat(timePackage.getConfigValues().getRaw()).contains("\"foo.expression\": \"\\\\d\""); assertThat(timePackage.getConfigValues().getRaw()).contains("\"bar\": \"\\\\d\""); + assertThat(timePackage.getConfigValues().getRaw()).contains("\"complex.expression\": \"#jsonPath(payload,'$.name') matches '\\\\d*'\""); + assertThat(timePackage.getConfigValues().getRaw()).contains("\"bar.expression\": \"\\\\d \\\\\\\\ \\\\0 \\\\a \\\\b \\\\t \\\\n \\\\v \\\\f \\\\r \\\\e \\\\N \\\\_ \\\\L \\\\P \\\\\""); } @Test
codereview_java_data_9574
"ArrayEquals", "MissingOverride", "UnnecessaryParentheses", - "PreferJavaTimeOverload", - "UnnecessaryLambda"); private final ListProperty<String> patchChecks; I recall this creating code that didn't compile, might want to test it on something large and internal (or atlas) first "ArrayEquals", "MissingOverride", "UnnecessaryParentheses", + "PreferJavaTimeOverload"); private final ListProperty<String> patchChecks;
codereview_java_data_9578
@Override public void handleRoundChangePayload(final RoundChange message) { final ConsensusRoundIdentifier targetRound = message.getRoundIdentifier(); - LOG.trace("Received a RoundChange Payload for {}", targetRound.toString()); final MessageAge messageAge = determineAgeOfPayload(message.getRoundIdentifier().getRoundNumber()); no need to do toString on targetRound @Override public void handleRoundChangePayload(final RoundChange message) { final ConsensusRoundIdentifier targetRound = message.getRoundIdentifier(); + LOG.trace("Received a RoundChange Payload for {}", targetRound); final MessageAge messageAge = determineAgeOfPayload(message.getRoundIdentifier().getRoundNumber());
codereview_java_data_9581
link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks", linkType = LinkType.CUSTOM, severity = SeverityLevel.SUGGESTION, - summary = "Avoid default cases in switch statements to correctly handle new enum variants") public final class SwitchStatementDefaultCase extends BugChecker implements BugChecker.SwitchTreeMatcher { @Override Could you add a sentence or two to the README to flesh out the reasoning behind this a bit more (i.e. recommending to throw an unreachable exception)? link = "https://github.com/palantir/gradle-baseline#baseline-error-prone-checks", linkType = LinkType.CUSTOM, severity = SeverityLevel.SUGGESTION, + summary = "Avoid default cases in switch statements to correctly handle new enum values") public final class SwitchStatementDefaultCase extends BugChecker implements BugChecker.SwitchTreeMatcher { @Override
codereview_java_data_9585
*/ @Nonnull public static <K, V> ServiceFactory<?, ReplicatedMap<K, V>> replicatedMapService(@Nonnull String mapName) { - return ServiceFactory.withCreateContainerFn(ctx -> ctx.jetInstance().<K, V>getReplicatedMap(mapName)) .withCreateServiceFn((ctx, map) -> map); } Can use `perInstanceService` here */ @Nonnull public static <K, V> ServiceFactory<?, ReplicatedMap<K, V>> replicatedMapService(@Nonnull String mapName) { + return ServiceFactory.withCreateContextFn(ctx -> ctx.jetInstance().<K, V>getReplicatedMap(mapName)) .withCreateServiceFn((ctx, map) -> map); }
codereview_java_data_9591
private UploadContract.View view = DUMMY; private CompositeDisposable compositeDisposable; - public static final String COUNTER_OF_NO_LOCATION - = "how_many_consecutive_uploads_have_no_coordinates"; @Inject @misaochan Do we have a convention for these store key values? I think there was an issue about that, but can't find it. private UploadContract.View view = DUMMY; private CompositeDisposable compositeDisposable; + public static final String COUNTER_OF_CONSECUTIVE_UPLOADS_WITHOUT_COORDINATES + = "number_of_consecutive_uploads_without_coordinates"; @Inject
codereview_java_data_9595
} private T getSessionCatalog() { - Preconditions.checkNotNull(sessionCatalog, "Delegated SessionCatalog is not provided by Spark. " + - "Please make sure you are replacing Spark's default catalog."); return sessionCatalog; } } How about adding the name of the session catalog, like this: "Please make sure your are replacing Spark's default catalog, named 'spark_catalog'". Also, the first line makes it sound like Spark did something wrong when this is probably a misconfiguration. For that, what about changing it to "Delegated SessionCatalog is missing" rather that "not provided by Spark"? } private T getSessionCatalog() { + Preconditions.checkNotNull(sessionCatalog, "Delegated SessionCatalog is missing. " + + "Please make sure your are replacing Spark's default catalog, named 'spark_catalog'."); return sessionCatalog; } }
codereview_java_data_9603
public class CompactorInfo { // Variable names become JSON keys - public long lastContact; - public String server; - public String queueName; public CompactorInfo(long fetchedTimeMillis, String queue, String hostAndPort) { lastContact = System.currentTimeMillis() - fetchedTimeMillis; Should these public variables be final? public class CompactorInfo { // Variable names become JSON keys + public final long lastContact; + public final String server; + public final String queueName; public CompactorInfo(long fetchedTimeMillis, String queue, String hostAndPort) { lastContact = System.currentTimeMillis() - fetchedTimeMillis;
codereview_java_data_9621
} private void validatePercentileFunctions(SqlCall call) { - // Percentile functions must have a single argument in the order by clause if (call.getOperandList().size() == 2) { SqlBasicCall sqlBasicCall = null; SqlNodeList list = null; Is it necessary to hard-code the SqlKind values here? Operators should validate based on their properties (e.g. {{SqlAggFunction.requiresOrder}}). Let's discuss in JIRA. } private void validatePercentileFunctions(SqlCall call) { if (call.getOperandList().size() == 2) { SqlBasicCall sqlBasicCall = null; SqlNodeList list = null;
codereview_java_data_9622
package org.apache.rocketmq.common.protocol.body; -import org.apache.rocketmq.common.protocol.body.QueryCorrectionOffsetBody; import org.apache.rocketmq.remoting.protocol.RemotingSerializable; import org.junit.Test; you'd better remove some unnecessary imports, use hot key 'Ctrl+Shift+o' for intelij idea import org.apache.rocketmq.common.protocol.body.QueryCorrectionOffsetBody; package org.apache.rocketmq.common.protocol.body; import org.apache.rocketmq.remoting.protocol.RemotingSerializable; import org.junit.Test;
codereview_java_data_9631
nodeNameToXPaths.clear(); addQueryToNode(originalXPath, AST_ROOT); if (LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "Unable to use RuleChain for for XPath: " + xpath); } } Duplicate "for" in the message nodeNameToXPaths.clear(); addQueryToNode(originalXPath, AST_ROOT); if (LOG.isLoggable(Level.FINE)) { + LOG.log(Level.FINE, "Unable to use RuleChain for XPath: " + xpath); } }
codereview_java_data_9654
// Combined with criteria TokenQuery query = idmIdentityService.createTokenQuery().userAgentLike("%firefox%").orderByTokenDate().asc(); List<Token> tokens = query.list(); - assertThat(tokens).hasSize(2); - assertThat(tokens.get(0).getUserAgent()).isEqualTo("firefox"); - assertThat(tokens.get(1).getUserAgent()).isEqualTo("firefox2"); } @Test Here we can use a construct like: ``` assertThat(tokens) .extracting(Token::getUserAgent) .containsExactly("firefox", "firefox2"); ``` // Combined with criteria TokenQuery query = idmIdentityService.createTokenQuery().userAgentLike("%firefox%").orderByTokenDate().asc(); List<Token> tokens = query.list(); + assertThat(tokens) + .extracting(Token::getUserAgent) + .containsExactly("firefox", "firefox2"); } @Test
codereview_java_data_9656
this.sw = sw; if (kompileOptions.backend.equals("ocaml")) { - kem.registerCriticalWarning(ExceptionType.DEPRECATED_BACKEND, "The OCaml backend is in the process of being deprecated (final date May 31, 2020). Please switch to the LLVM backend."); } } Is there much use in distinguishing `DEPRECATED_BACKEND` from `FUTURE_ERROR`? Seems to me that `DEPRECATED_BACKEND` will only be used twice, and equally well could be just thrown into "these are features that we will not support in the future. this.sw = sw; if (kompileOptions.backend.equals("ocaml")) { + kem.registerCriticalWarning(ExceptionType.FUTURE_ERROR, "The OCaml backend is in the process of being deprecated (final date May 31, 2020). Please switch to the LLVM backend."); } }
codereview_java_data_9664
stream(modules).forEach(m -> stream(m.localSentences()).forEach(new CheckHOLE(errors, m)::check)); - stream(modules).forEach(m -> stream(m.localSentences()).forEach(new CheckTokens(errors, m, isSymbolic && isKast)::check)); stream(modules).forEach(m -> stream(m.localSentences()).forEach(new CheckK(errors)::check)); I think this check `isSymbolic && isKast` can be done before even entering this line. So we would avoid this entire step instead of looking at each sentence and decide if we need to do something. stream(modules).forEach(m -> stream(m.localSentences()).forEach(new CheckHOLE(errors, m)::check)); + if (!(isSymbolic && isKast)) { + stream(modules).forEach(m -> stream(m.localSentences()).forEach(new CheckTokens(errors, m)::check)); + } stream(modules).forEach(m -> stream(m.localSentences()).forEach(new CheckK(errors)::check));
codereview_java_data_9665
legacyIndex.contentType(MediaType.HTML_UTF_8).cacheControl(maxAgeMinute); lensIndex.contentType(MediaType.HTML_UTF_8).cacheControl(maxAgeMinute); return new IndexSwitchingService( legacyIndex.build().asService(), lensIndex.build().asService()); } Our JS/CSS bundles get a hash appended right? legacyIndex.contentType(MediaType.HTML_UTF_8).cacheControl(maxAgeMinute); lensIndex.contentType(MediaType.HTML_UTF_8).cacheControl(maxAgeMinute); + // In both our old and new UI, assets have hashes in the filenames (generated by webpack). + // This allows us to host both simultaneously without conflict as long as we change the index + // file to point to the correct files. return new IndexSwitchingService( legacyIndex.build().asService(), lensIndex.build().asService()); }
codereview_java_data_9667
Service singleton = ServiceManager.getInstance().getSingleton(service); Client client = clientManager.getClient(clientId); if (null == client || !client.isEphemeral()) { return; } InstancePublishInfo instanceInfo = getPublishInfo(instance); abstract a method named `validateClient`? And print an warn log, I think better. Service singleton = ServiceManager.getInstance().getSingleton(service); Client client = clientManager.getClient(clientId); if (null == client || !client.isEphemeral()) { + Loggers.SRV_LOG.warn("Client connection {} already disconnect", clientId); return; } InstancePublishInfo instanceInfo = getPublishInfo(instance);
codereview_java_data_9675
final boolean devMode, final Function<Collection<PantheonNode>, Optional<String>> genesisConfig) throws IOException { - final Path homeDirectory = Files.createTempDirectory("acctest"); this.name = name; - this.homeDirectory = homeDirectory; this.keyPair = KeyPairUtil.loadKeyPair(homeDirectory); this.p2pPort = p2pPort; this.miningParameters = miningParameters; I'd inline the local `homeDirectory` variable again. final boolean devMode, final Function<Collection<PantheonNode>, Optional<String>> genesisConfig) throws IOException { this.name = name; + this.homeDirectory = Files.createTempDirectory("acctest"); this.keyPair = KeyPairUtil.loadKeyPair(homeDirectory); this.p2pPort = p2pPort; this.miningParameters = miningParameters;
codereview_java_data_9683
} // DEV-NOTE: Use this method for non-infinite and direct-access collection only // see https://github.com/vavr-io/vavr/issues/2007 @SuppressWarnings("unchecked") static <T, S extends IndexedSeq<T>> S dropRightUntil(S seq, Predicate<? super T> predicate) { Could you rather add a little explanation why one should not use this method when using infinite collections? I think this is more convinient than referring to a github issue which might get lost over the time. } // DEV-NOTE: Use this method for non-infinite and direct-access collection only + // because of O(N) complexity of get() and infinite loop in size() // see https://github.com/vavr-io/vavr/issues/2007 @SuppressWarnings("unchecked") static <T, S extends IndexedSeq<T>> S dropRightUntil(S seq, Predicate<? super T> predicate) {
codereview_java_data_9685
Cursor cursor = DatabaseFactory.getImageDatabase(c).getImagesForThread(threadId); List<SaveAttachmentTask.Attachment> attachments = new ArrayList<>(cursor.getCount()); - cursor.moveToFirst(); - do { ImageRecord record = ImageRecord.from(cursor); attachments.add(new SaveAttachmentTask.Attachment(record.getAttachment().getDataUri(), record.getContentType(), record.getDate())); - } while (cursor.moveToNext()); return attachments; } while (cursor != null && cursor.moveToNext()) { Cursor cursor = DatabaseFactory.getImageDatabase(c).getImagesForThread(threadId); List<SaveAttachmentTask.Attachment> attachments = new ArrayList<>(cursor.getCount()); + while (cursor != null && cursor.moveToNext()) { ImageRecord record = ImageRecord.from(cursor); attachments.add(new SaveAttachmentTask.Attachment(record.getAttachment().getDataUri(), record.getContentType(), record.getDate())); + } return attachments; }
codereview_java_data_9688
return findRecursive(first, last); } setupQueryParameters(session, first, last, intersection); - query.setNeverLazy(true); ResultInterface result = query.query(0); return new ViewCursor(this, result, first, last); } All the subqueries will become never-lazy now. Does not look like a correct fix. return findRecursive(first, last); } setupQueryParameters(session, first, last, intersection); ResultInterface result = query.query(0); return new ViewCursor(this, result, first, last); }
codereview_java_data_9689
maxValue >= value && maxValue > minValue && increment != 0 && - // Math.abs(increment) < maxValue - minValue // Can use Long.compareUnsigned() on Java 8 - Math.abs(increment) + Long.MIN_VALUE < maxValue - minValue + Long.MIN_VALUE; } private static long getDefaultMinValue(Long startValue, long increment) { if maxValue is near Long.MAX_VALUE (i.e. 2^63-1) and minValue is near Long.MIN_VALUE (i.e. -2^63), then maxValue - minValue is going to overflow maxValue >= value && maxValue > minValue && increment != 0 && + // Math.abs(increment) <= maxValue - minValue // Can use Long.compareUnsigned() on Java 8 + Math.abs(increment) + Long.MIN_VALUE <= maxValue - minValue + Long.MIN_VALUE; } private static long getDefaultMinValue(Long startValue, long increment) {
codereview_java_data_9694
private void reportUnnecessaryModifiers(Object data, Node node, Modifier unnecessaryModifier, String explanation) { - reportUnnecessaryModifiers(data, node, Collections.singletonList(unnecessaryModifier), explanation); } private void reportUnnecessaryModifiers(Object data, Node node, - List<Modifier> unnecessaryModifiers, String explanation) { if (unnecessaryModifiers.isEmpty()) { return; } I'd explode this into if statements as we do in `getPrintableNodeKind`... may be longer, but will enhance readability private void reportUnnecessaryModifiers(Object data, Node node, Modifier unnecessaryModifier, String explanation) { + reportUnnecessaryModifiers(data, node, EnumSet.of(unnecessaryModifier), explanation); } private void reportUnnecessaryModifiers(Object data, Node node, + Set<Modifier> unnecessaryModifiers, String explanation) { if (unnecessaryModifiers.isEmpty()) { return; }
codereview_java_data_9701
private static final String SQL_LAST_INSERT_ID = "SELECT LAST_INSERT_ID();"; private static final String SQL_INSERT_ROLE_MEMBER = "INSERT INTO role_member (role_id, principal_id, expiration, active) VALUES (?,?,?,?);"; private static final String SQL_DELETE_ROLE_MEMBER = "DELETE FROM role_member WHERE role_id=? AND principal_id=?;"; - private static final String SQL_DELETE_INACTIVE_ROLE_MEMBER = "DELETE FROM role_member WHERE role_id=? AND principal_id=? AND active=FALSE;"; private static final String SQL_UPDATE_ROLE_MEMBER = "UPDATE role_member SET expiration=? WHERE role_id=? AND principal_id=?;"; - private static final String SQL_APPROVE_ROLE_MEMBER = "UPDATE role_member SET expiration=?,active=? WHERE role_id=? AND principal_id=?;"; private static final String SQL_INSERT_ROLE_AUDIT_LOG = "INSERT INTO role_audit_log " + "(role_id, admin, member, action, audit_ref) VALUES (?,?,?,?,?);"; private static final String SQL_LIST_ROLE_AUDIT_LOGS = "SELECT * FROM role_audit_log WHERE role_id=?;"; we should be consistent and use false since we've used lowercase everywhere else private static final String SQL_LAST_INSERT_ID = "SELECT LAST_INSERT_ID();"; private static final String SQL_INSERT_ROLE_MEMBER = "INSERT INTO role_member (role_id, principal_id, expiration, active) VALUES (?,?,?,?);"; private static final String SQL_DELETE_ROLE_MEMBER = "DELETE FROM role_member WHERE role_id=? AND principal_id=?;"; + private static final String SQL_DELETE_INACTIVE_ROLE_MEMBER = "DELETE FROM role_member WHERE role_id=? AND principal_id=? AND active=false;"; private static final String SQL_UPDATE_ROLE_MEMBER = "UPDATE role_member SET expiration=? WHERE role_id=? AND principal_id=?;"; + private static final String SQL_APPROVE_ROLE_MEMBER = "UPDATE role_member SET expiration=?,active=true WHERE role_id=? AND principal_id=?;"; private static final String SQL_INSERT_ROLE_AUDIT_LOG = "INSERT INTO role_audit_log " + "(role_id, admin, member, action, audit_ref) VALUES (?,?,?,?,?);"; private static final String SQL_LIST_ROLE_AUDIT_LOGS = "SELECT * FROM role_audit_log WHERE role_id=?;";
codereview_java_data_9703
public void remoteConnectionsPercentageWithInvalidFormatMustFail() { parseCommand( - "--remote-connections-limit-enabled", - "--remote-connections-percentage", - "not-a-percentage"); verifyZeroInteractions(mockRunnerBuilder); assertThat(commandOutput.toString()).isEmpty(); assertThat(commandErrorOutput.toString()) .contains( - "Invalid value for option '--remote-connections-percentage': cannot convert 'not-a-percentage' to Percentage"); } @Test Question - where does this phrase "cannot convert 'not-a-percentage'" come from? Is that generated internally by PicoCLI? If we add a custom error message to the exception that's thrown can we get a better error message? public void remoteConnectionsPercentageWithInvalidFormatMustFail() { parseCommand( + "--remote-connections-limit-enabled", "--remote-connections-percentage", "invalid"); verifyZeroInteractions(mockRunnerBuilder); assertThat(commandOutput.toString()).isEmpty(); assertThat(commandErrorOutput.toString()) .contains( + "Invalid value for option '--remote-connections-percentage'", + "should be a number between 0 and 100 inclusive"); } @Test
codereview_java_data_9729
// set manual x bounds to have nice steps graphData.formatAxis(fromTime, endTime); - // insulin activity - graphData.addActivity(fromTime, endTime, graphData.maxY); // Treatments graphData.addTreatments(fromTime, endTime); make it conditional like `if (SP.getBoolean("showactivity", false)) .....` // set manual x bounds to have nice steps graphData.formatAxis(fromTime, endTime); + if(SP.getBoolean("showactivity", true)) { + graphData.addActivity(fromTime, endTime, graphData.maxY); + } // Treatments graphData.addTreatments(fromTime, endTime);
codereview_java_data_9730
import ws.com.google.android.mms.pdu.PduPart; public class AttachmentDownloadJob extends MasterSecretJob implements InjectableType { - - private static final String TAG = AttachmentDownloadJob.class.getSimpleName(); @Inject transient TextSecureMessageReceiver messageReceiver; If you have to do this, you have to include a serialVersionUID. It will break every existing attachmentdownloadjob, so you also have to handle rescheduling the existing ones. import ws.com.google.android.mms.pdu.PduPart; public class AttachmentDownloadJob extends MasterSecretJob implements InjectableType { + private static final long serialVersionUID = 1L; + private static final String TAG = AttachmentDownloadJob.class.getSimpleName(); @Inject transient TextSecureMessageReceiver messageReceiver;
codereview_java_data_9733
"\" with \"" + definitionFileName.substring(0, definitionFileName.length() - 2) + ".md\".", di); } - ArrayList<File> allLookupDirectoris = new ArrayList<>(lookupDirectories); - allLookupDirectoris.add(1, currentDirectory); - Optional<File> definitionFile = allLookupDirectoris.stream() .map(lookupDirectory -> { if (new File(definitionFileName).isAbsolute()) { return new File(definitionFileName); 1. This looks like a typo in the name of this variable `allLookupDirectoris => allLookupDirectories` 2. What is this change? The `0 => 1`. "\" with \"" + definitionFileName.substring(0, definitionFileName.length() - 2) + ".md\".", di); } + ArrayList<File> allLookupDirectories = new ArrayList<>(lookupDirectories); + allLookupDirectories.add(1, currentDirectory); //after builtin directory but before anything else + Optional<File> definitionFile = allLookupDirectories.stream() .map(lookupDirectory -> { if (new File(definitionFileName).isAbsolute()) { return new File(definitionFileName);
codereview_java_data_9740
private CharSeqComparator() { } - private boolean isCharInUTF16HighSurrogateRange(char c1) { - if (c1 >= '\uD800' && c1 <= '\uDBFF') { // High surrogate pair range is U+D800—U+DBFF - return true; - } - return false; - } - /** * Java character supports only upto 3 byte UTF-8 characters. 4 byte UTF-8 character is represented using two Java * characters (using UTF-16 surrogate pairs). Character by character comparison may yield incorrect results Here's an example, I think this was removed in a later version. Similarly, the extra newline on line 201 was fixed in another version. private CharSeqComparator() { } /** * Java character supports only upto 3 byte UTF-8 characters. 4 byte UTF-8 character is represented using two Java * characters (using UTF-16 surrogate pairs). Character by character comparison may yield incorrect results
codereview_java_data_9741
import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - public abstract class NodeDataRequest { - private static final Logger LOG = LogManager.getLogger(); private final RequestType requestType; private final Hash hash; private BytesValue data; I don't see LOG used, can this file be taken out of the PR? import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; public abstract class NodeDataRequest { private final RequestType requestType; private final Hash hash; private BytesValue data;
codereview_java_data_9743
*/ public class SourceEditorController implements Initializable, SettingsOwner { - private final DesignerApp designerApp; private final MainDesignerController parent; @FXML I see no reason to even think about disabling syntax highlighting. */ public class SourceEditorController implements Initializable, SettingsOwner { + private final DesignerRoot designerRoot; private final MainDesignerController parent; @FXML
codereview_java_data_9750
* @return {@code true} if notifications are persistent, {@code false} otherwise */ public static boolean setLockscreenBackground() { - return prefs.getBoolean(PREF_LOCKSCREEN_BACKGROUND, false); } /** 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) * @return {@code true} if notifications are persistent, {@code false} otherwise */ public static boolean setLockscreenBackground() { + return prefs.getBoolean(PREF_LOCKSCREEN_BACKGROUND, true); } /**
codereview_java_data_9751
createAndInitSourceTable(sourceName); append(targetName, new Employee(1, "emp-id-one"), new Employee(6, "emp-id-6")); append(sourceName, new Employee(2, "emp-id-2"), new Employee(1, "emp-id-1"), new Employee(6, "emp-id-6")); - String sqlText = "MERGE INTO " + targetName + " AS target \n" + - "USING " + sourceName + " AS source \n" + "ON target.id = source.id \n" + "WHEN MATCHED AND target.id = 1 THEN UPDATE SET * \n" + "WHEN MATCHED AND target.id = 6 THEN DELETE \n" + "WHEN NOT MATCHED AND source.id = 2 THEN INSERT * "; - sql(sqlText, ""); assertEquals("Should have expected rows", ImmutableList.of(row(1, "emp-id-1"), row(2, "emp-id-2")), sql("SELECT * FROM %s ORDER BY id ASC NULLS LAST", targetName)); Nit: use of "" instead of filling in table names in this test as well. createAndInitSourceTable(sourceName); append(targetName, new Employee(1, "emp-id-one"), new Employee(6, "emp-id-6")); append(sourceName, new Employee(2, "emp-id-2"), new Employee(1, "emp-id-1"), new Employee(6, "emp-id-6")); + String sqlText = "MERGE INTO %s AS target \n" + + "USING %s AS source \n" + "ON target.id = source.id \n" + "WHEN MATCHED AND target.id = 1 THEN UPDATE SET * \n" + "WHEN MATCHED AND target.id = 6 THEN DELETE \n" + "WHEN NOT MATCHED AND source.id = 2 THEN INSERT * "; + sql(sqlText, targetName, sourceName); assertEquals("Should have expected rows", ImmutableList.of(row(1, "emp-id-1"), row(2, "emp-id-2")), sql("SELECT * FROM %s ORDER BY id ASC NULLS LAST", targetName));
codereview_java_data_9760
"session closed"); } Command command; - if (queryCache != null) { - synchronized (queryCache) { long newModificationMetaID = database.getModificationMetaId(); if (newModificationMetaID != modificationMetaID) { queryCache.clear(); why do you need to synchronize here? Surely at this point we either hold the Database object or the Session object locked already? "session closed"); } Command command; + if (queryCacheSize > 0) { + if (queryCache == null) { + queryCache = SmallLRUCache.newInstance(queryCacheSize); + modificationMetaID = database.getModificationMetaId(); + } else { long newModificationMetaID = database.getModificationMetaId(); if (newModificationMetaID != modificationMetaID) { queryCache.clear();
codereview_java_data_9763
} public static TomlParseResult loadConfiguration(final String toml) { - TomlParseResult result; - result = Toml.parse(toml); if (result.hasErrors()) { final String errors = Any reason this wasn't a single line? } public static TomlParseResult loadConfiguration(final String toml) { + TomlParseResult result = Toml.parse(toml); if (result.hasErrors()) { final String errors =
codereview_java_data_9764
return command; } - void releaseDatabaseObjectId(int id) { idsToRelease.set(id); } this method has a verb form i.e. "do it now", perhaps a better name, something like "markDatabaseObjectIdForDelayedRelease" or something else equally obvious return command; } + /** + * Arranges for the specified database object id to be released + * at the end of the current transaction. + * @param id to be scheduled + */ + void scheduleDatabaseObjectIdForRelease(int id) { + if (idsToRelease == null) { + idsToRelease = new BitSet(); + } idsToRelease.set(id); }
codereview_java_data_9770
try { remembered.shutdown(); } catch (Throwable t) { - System.err.println("Client shutdown failed with:"); t.printStackTrace(); } } Shouldn't we use the `LOGGER` that's in the class? try { remembered.shutdown(); } catch (Throwable t) { + System.err.println("Shutdown failed with:"); t.printStackTrace(); } }
codereview_java_data_9781
import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; -import javax.inject.Inject; import javax.xml.transform.TransformerException; import org.gradle.api.DefaultTask; import org.gradle.api.Project; It's probably fine to use this method, but Gradle regards these `G` prefixed classes as internal (despite not being in the `.internal` package - `GFileUtils` is another example) and regularly breaks/removes methods from them in point releases import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; import javax.xml.transform.TransformerException; import org.gradle.api.DefaultTask; import org.gradle.api.Project;
codereview_java_data_9798
Pattern jpegPattern = Pattern.compile("\\.jpeg$", Pattern.CASE_INSENSITIVE); // People are used to ".jpg" more than ".jpeg" which the system gives us. - if (extension != null && extension.toLowerCase(Locale.US).equals("jpeg")) { extension = "jpg"; } title = jpegPattern.matcher(title).replaceFirst(".jpg"); - if (extension != null && !title.toLowerCase(Locale.US).endsWith("." + extension.toLowerCase(Locale.US))) { title += "." + extension; } return title; title can be non-English (US English or anything else) on Wikimedia Commons, so it seems to be better to stick with the default locale. extension here should be ASCII only, so using Locale.US here might make sense. (But I don't think default would do harm. Also, did you also consider using Locale.ROOT?) Pattern jpegPattern = Pattern.compile("\\.jpeg$", Pattern.CASE_INSENSITIVE); // People are used to ".jpg" more than ".jpeg" which the system gives us. + if (extension != null && extension.toLowerCase(Locale.ENGLISH).equals("jpeg")) { extension = "jpg"; } title = jpegPattern.matcher(title).replaceFirst(".jpg"); + if (extension != null && !title.toLowerCase(Locale.getDefault()).endsWith("." + extension.toLowerCase(Locale.ENGLISH))) { title += "." + extension; } return title;
codereview_java_data_9801
public static ProcessorMetaSupplier writeObservableSupplier(@Nonnull String name) { return new ProcessorMetaSupplier() { - private final Map<Object, Object> tags = Collections.singletonMap( ObservableUtil.OWNED_OBSERVABLE, name ); @Nonnull @Override - public Map<Object, Object> getTags() { return tags; } We don't need the buffer when we add items one by one. Btw, couldn't we use the same `addAllAsync` here? public static ProcessorMetaSupplier writeObservableSupplier(@Nonnull String name) { return new ProcessorMetaSupplier() { + private final Map<String, String> tags = Collections.singletonMap( ObservableUtil.OWNED_OBSERVABLE, name ); @Nonnull @Override + public Map<String, String> getTags() { return tags; }
codereview_java_data_9804
@Override protected void onResume() { - dynamicTheme.onCreate(this); super.onResume(); } I haven't actually tested the code... but: 1. should use `onResume` here? 2. in `RegistrationActivity` there is no call to `dynamicTheme.onResume` @Override protected void onResume() { + dynamicTheme.onResume(this); super.onResume(); }
codereview_java_data_9807
// Create a test table with multiple versions TableIdentifier tableId = TableIdentifier.of("tbl"); Table table = catalog.createTable(tableId, SCHEMA, PartitionSpec.unpartitioned()); DataFile dataFile1 = DataFiles.builder(SPEC) .withPath("/a.parquet") I don't think this is correct. If the hint file is missing, the table should still be readable. // Create a test table with multiple versions TableIdentifier tableId = TableIdentifier.of("tbl"); Table table = catalog.createTable(tableId, SCHEMA, PartitionSpec.unpartitioned()); + HadoopTableOperations tableOperations = (HadoopTableOperations) catalog.newTableOps(tableId); DataFile dataFile1 = DataFiles.builder(SPEC) .withPath("/a.parquet")
codereview_java_data_9819
* Demonstrates the usage of observable results on client side in their * {@link CompletableFuture} form (applicable only to batch jobs). * <p> - * The concrete job we are observing the results of is a simple Word Count. * It inserts the text of The Complete Works of William Shakespeare into a * Hazelcast IMap, then lets Jet count the words in it. * <p> lower case "word count" * Demonstrates the usage of observable results on client side in their * {@link CompletableFuture} form (applicable only to batch jobs). * <p> + * The concrete job we are observing the results of is a simple word count. * It inserts the text of The Complete Works of William Shakespeare into a * Hazelcast IMap, then lets Jet count the words in it. * <p>
codereview_java_data_9826
return websocket -> { final SocketAddress socketAddress = websocket.remoteAddress(); final String connectionId = websocket.textHandlerID(); - String token = getToken(websocket); - LOG.trace("token {}", token); LOG.debug("Websocket Connected ({})", socketAddressAsString(socketAddress)); Maybe we should add a bit more of context in this trace msg. Also, what happens when the token doesn't exist? return websocket -> { final SocketAddress socketAddress = websocket.remoteAddress(); final String connectionId = websocket.textHandlerID(); + final String token = getAuthToken(websocket); + LOG.trace("Authentication token {}", token); LOG.debug("Websocket Connected ({})", socketAddressAsString(socketAddress));
codereview_java_data_9827
return saslSupplier.get(); } - public synchronized static BatchWriterConfig getBatchWriterConfig(Properties props) { BatchWriterConfig batchWriterConfig = new BatchWriterConfig(); Long maxMemory = ClientProperty.BATCH_WRITER_MEMORY_MAX.getBytes(props); Synchronized should go with the instance method and not the static method. return saslSupplier.get(); } + public static BatchWriterConfig getBatchWriterConfig(Properties props) { BatchWriterConfig batchWriterConfig = new BatchWriterConfig(); Long maxMemory = ClientProperty.BATCH_WRITER_MEMORY_MAX.getBytes(props);
codereview_java_data_9834
if (statement instanceof MySqlPrepareStatement) { String simpleName = ((MySqlPrepareStatement) statement).getName().getSimpleName(); nameSet.add(simpleName); - rwSplitService.setTxStart(true); } if (statement instanceof MysqlDeallocatePrepareStatement) { String simpleName = ((MysqlDeallocatePrepareStatement) statement).getStatementName().getSimpleName(); nameSet.remove(simpleName); if (nameSet.isEmpty()) { - rwSplitService.setTxStart(false); } } } catch (SQLSyntaxErrorException throwables) { application point? prepare has no practical relationship with tx; (doing so may lead to other aspects of influence) If it's for some purpose, try something else. if (statement instanceof MySqlPrepareStatement) { String simpleName = ((MySqlPrepareStatement) statement).getName().getSimpleName(); nameSet.add(simpleName); + rwSplitService.setInPrepare(true); } if (statement instanceof MysqlDeallocatePrepareStatement) { String simpleName = ((MysqlDeallocatePrepareStatement) statement).getStatementName().getSimpleName(); nameSet.remove(simpleName); if (nameSet.isEmpty()) { + rwSplitService.setInPrepare(false); } } } catch (SQLSyntaxErrorException throwables) {
codereview_java_data_9856
package com.hazelcast.jet.core; import com.hazelcast.jet.JetInstance; -import com.hazelcast.jet.JetTestInstanceFactory; import com.hazelcast.jet.Job; import com.hazelcast.jet.Observable; import com.hazelcast.jet.function.Observer; why not use `JetTestSupport` ? package com.hazelcast.jet.core; import com.hazelcast.jet.JetInstance; import com.hazelcast.jet.Job; import com.hazelcast.jet.Observable; import com.hazelcast.jet.function.Observer;
codereview_java_data_9869
String ELEMENT_SCROLL_BEHAVIOR = "elementScrollBehavior"; String HAS_TOUCHSCREEN = "hasTouchScreen"; String OVERLAPPING_CHECK_DISABLED = "overlappingCheckDisabled"; - String ENABLE_DOWNLOADING = "chromium:enableDownloading"; String LOGGING_PREFS = "loggingPrefs"; The name `enableDownloading` implies this is a boolean capability. How about `downloadDir`? String ELEMENT_SCROLL_BEHAVIOR = "elementScrollBehavior"; String HAS_TOUCHSCREEN = "hasTouchScreen"; String OVERLAPPING_CHECK_DISABLED = "overlappingCheckDisabled"; + String ENABLE_DOWNLOAD_TO = "chromium:enableDownloadTo"; String LOGGING_PREFS = "loggingPrefs";
codereview_java_data_9879
Optional<BytesValue> getNodeData(Hash hash); - // TODO: look into optimizing this call in implementing classes default boolean contains(final Hash hash) { return getNodeData(hash).isPresent(); } Jira subtask to track this todo? That said, it looks like the optimisation potential is fairly limited with RocksDB - it has a `keyMayExist` which will tell you if it's definitely not there, but you have use `get` to be sure it's there. Other backends would likely benefit a lot more though. Optional<BytesValue> getNodeData(Hash hash); default boolean contains(final Hash hash) { return getNodeData(hash).isPresent(); }
codereview_java_data_9888
/** Executes the task while timed by a timer. */ public void executeTaskTimed() { final OperationTimer.TimingContext timingContext = taskTimer.startTimer(); - executeTask(); - taskTimeInSec = timingContext.stopTimer(); } public double getTaskTimeInSec() { We should probably use the `try (final OperationTimer.TimingContext timingContext = taskTimer.startTimer())` or an explicit `final` block here to ensure the timer completes even if the task fails. /** Executes the task while timed by a timer. */ public void executeTaskTimed() { final OperationTimer.TimingContext timingContext = taskTimer.startTimer(); + try { + executeTask(); + } finally { + taskTimeInSec = timingContext.stopTimer(); + } } public double getTaskTimeInSec() {
codereview_java_data_9891
} public void setParameters(List<Parameter> parameters) { this.parameters = parameters; - setAsParentNodeOf(this.parameters); } public Statement getBody() { What happens if parameters is null? } public void setParameters(List<Parameter> parameters) { + setAsParentNodeOf(parameters); this.parameters = parameters; } public Statement getBody() {
codereview_java_data_9895
stream(modules).forEach(m -> stream(m.localSentences()).forEach(new CheckHOLE(errors, m)::check)); - if (!(isSymbolic && isKast)) { stream(modules).forEach(m -> stream(m.localSentences()).forEach(new CheckTokens(errors, m)::check)); } ```suggestion if (!(isSymbolic && isKast)) { // if it's not the java backend ``` stream(modules).forEach(m -> stream(m.localSentences()).forEach(new CheckHOLE(errors, m)::check)); + if (!(isSymbolic && isKast)) { // if it's not the java backend stream(modules).forEach(m -> stream(m.localSentences()).forEach(new CheckTokens(errors, m)::check)); }
codereview_java_data_9896
package org.thoughtcrime.securesms.color; import org.thoughtcrime.securesms.util.Util; import java.util.Map; seems like we can avoid this whole ThemeType thing all together by having a `<attr name="materialWeight" format="string|reference" />` or something that is "900" or "500" per theme and resolving it just like any other theme attribute. package org.thoughtcrime.securesms.color; +import android.content.Context; +import android.support.annotation.NonNull; +import android.util.Log; +import android.util.TypedValue; + +import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.util.Util; import java.util.Map;
codereview_java_data_9899
import java.util.List; import java.util.Optional; import javax.lang.model.element.Modifier; -import software.amazon.awssdk.awscore.protocol.query.AwsQueryProtocolFactory; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.core.Request; import software.amazon.awssdk.core.http.HttpMethodName; -import software.amazon.awssdk.core.protocol.OperationInfo; -import software.amazon.awssdk.core.protocol.ProtocolMarshaller; import software.amazon.awssdk.utils.StringUtils; public class QueryMarshallerSpec implements MarshallerProtocolSpec { Can we move the apiVersion and serviceName outside this `if block`. We need service name always to create the Default request. import java.util.List; import java.util.Optional; import javax.lang.model.element.Modifier; import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel; import software.amazon.awssdk.codegen.model.intermediate.Metadata; import software.amazon.awssdk.codegen.model.intermediate.ShapeModel; import software.amazon.awssdk.core.Request; import software.amazon.awssdk.core.http.HttpMethodName; +import software.amazon.awssdk.protocols.core.OperationInfo; +import software.amazon.awssdk.protocols.core.ProtocolMarshaller; +import software.amazon.awssdk.protocols.query.AwsQueryProtocolFactory; import software.amazon.awssdk.utils.StringUtils; public class QueryMarshallerSpec implements MarshallerProtocolSpec {
codereview_java_data_9901
signupButton.setOnClickListener(view -> signUp()); if(BuildConfig.FLAVOR == "beta"){ - loginCredentials.setText("Use Commons Beta Credentials"); } else { loginCredentials.setVisibility(View.GONE); } Can you please move this into strings.xml, so that we can get translations. Besides instead of imperative sentence, Isn't it better an informing sentence as "You are using Commons Beta Credentials" ? By the way I am not an English expert definitely, what do you think @misaochan ? signupButton.setOnClickListener(view -> signUp()); if(BuildConfig.FLAVOR == "beta"){ + loginCredentials.setText(getString(R.string.login_credentials)); } else { loginCredentials.setVisibility(View.GONE); }
codereview_java_data_9903
import org.flowable.common.engine.impl.util.CollectionUtil; import org.flowable.engine.ProcessEngineConfiguration; import org.flowable.engine.history.HistoricActivityInstance; -import org.flowable.engine.repository.MergeMode; import org.flowable.engine.impl.test.HistoryTestHelper; import org.flowable.engine.impl.test.PluggableFlowableTestCase; import org.flowable.engine.repository.Deployment; import org.flowable.engine.repository.Model; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.runtime.ProcessInstance; Not alphabetic order here too. import org.flowable.common.engine.impl.util.CollectionUtil; import org.flowable.engine.ProcessEngineConfiguration; import org.flowable.engine.history.HistoricActivityInstance; import org.flowable.engine.impl.test.HistoryTestHelper; import org.flowable.engine.impl.test.PluggableFlowableTestCase; import org.flowable.engine.repository.Deployment; +import org.flowable.engine.repository.MergeMode; import org.flowable.engine.repository.Model; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.engine.runtime.ProcessInstance;
codereview_java_data_9906
} default String getNameAsString(){ - return getName().getId(); } } Good :D I wanted to suggest this one and I forgot } default String getNameAsString(){ + return getName().getIdentifier(); } }
codereview_java_data_9909
return getName().hashCode(); } - ImapStore getStore() { return store; } protected String getLogId() { String id = store.getStoreConfig().toString() + ":" + getName() + "/" + Thread.currentThread().getName(); if (connection != null) { Why is this necessary? return getName().hashCode(); } + private ImapStore getStore() { return store; } + Set<Flag> getPermanentFlags() { + return getStore().getPermanentFlagsIndex(); + } + protected String getLogId() { String id = store.getStoreConfig().toString() + ":" + getName() + "/" + Thread.currentThread().getName(); if (connection != null) {
codereview_java_data_9917
* @param place place which is bookmarked * @param isBookmarked true is bookmarked, false if bookmark removed */ public static void updateMarkerLabelListBookmark(Place place, boolean isBookmarked) { for (ListIterator<MarkerPlaceGroup> iter = markerLabelList.listIterator(); iter.hasNext();) { MarkerPlaceGroup markerPlaceGroup = iter.next(); agh static lists! I would be very concerned about ConcurrentModification, this is not thread safe for ArrayList. Maybe a CopyOnWriteArrayList would be best here? I am really not sure without diving deeper * @param place place which is bookmarked * @param isBookmarked true is bookmarked, false if bookmark removed */ + @MainThread public static void updateMarkerLabelListBookmark(Place place, boolean isBookmarked) { for (ListIterator<MarkerPlaceGroup> iter = markerLabelList.listIterator(); iter.hasNext();) { MarkerPlaceGroup markerPlaceGroup = iter.next();
codereview_java_data_9918
set("parquet.avro.write-old-list-structure", "false"); MessageType type = ParquetSchemaUtil.convert(schema, name); - // Check that our metrics make sense - metricsConfig.validateProperties(schema); - if (createWriterFunc != null) { Preconditions.checkArgument(writeSupport == null, "Cannot write with both write support and Parquet value writer"); Is this the right place to do the validation? If a user adds a bad property or performs some schema update that causes a validation error, that would break all writes to the table. To me, it doesn't seem like we are catching the problem early enough and possibly allowing a typo to break scheduled jobs. What do you think about adding this validation when altering the table? `UpdateProperties` could check whether any properties starting with `write.metadata.metrics` were modified and run this. Similarly, `UpdateSchema` could run this as well, although I think that we should probably modify `UpdateSchema` to simply update the properties for column renames (if that's easily done). set("parquet.avro.write-old-list-structure", "false"); MessageType type = ParquetSchemaUtil.convert(schema, name); if (createWriterFunc != null) { Preconditions.checkArgument(writeSupport == null, "Cannot write with both write support and Parquet value writer");
codereview_java_data_9922
try (JarFile jarFile = new JarFile(jar)) { if (StringUtil.isNullOrEmpty(mainClass)) { if (jarFile.getManifest() == null) { - error("No manifest file in " + jar); } mainClass = jarFile.getManifest().getMainAttributes().getValue("Main-Class"); if (mainClass == null) { - error("No Main-Class found in manifest"); } } We can hint here that one can use `-c` option. Also on line 126. try (JarFile jarFile = new JarFile(jar)) { if (StringUtil.isNullOrEmpty(mainClass)) { if (jarFile.getManifest() == null) { + error("No manifest file in " + jar + ". The -c option can be used to provide a main class."); } mainClass = jarFile.getManifest().getMainAttributes().getValue("Main-Class"); if (mainClass == null) { + error("No Main-Class found in manifest. The -c option can be used to provide a main class."); } }
codereview_java_data_9927
return logger.getName(); } - // FIXME: 2018/3/2 @Override public boolean isEnabled(InternalLogLevel internalLogLevel) { return nettyLogLevel.ordinal() <= internalLogLevel.ordinal(); How to fix this issue? return logger.getName(); } @Override public boolean isEnabled(InternalLogLevel internalLogLevel) { return nettyLogLevel.ordinal() <= internalLogLevel.ordinal();
codereview_java_data_9935
*/ private final ReentrantLock l; - /* - * Used as null value for ConcurrentSkipListSet - */ - private final Entry<V> ENTRY_NULL = new Entry<>(); - /** * Create a new cache segment. * @param maxMemory the maximum memory to use I think it would be better to convert `misses` to `AtomicLong` and avoid a lock for a `null` value completely. In that case this dummy value and related tricks will not be required. */ private final ReentrantLock l; /** * Create a new cache segment. * @param maxMemory the maximum memory to use
codereview_java_data_9948
*/ package tech.pegasys.pantheon.ethereum.jsonrpc.internal.results.tracing; -public interface Trace { - @FunctionalInterface - interface ResultWriter { - void write(Trace trace); - } -} Style: why an interface in an interface? I would expect just one interface `TraceResultWriter` */ package tech.pegasys.pantheon.ethereum.jsonrpc.internal.results.tracing; +public interface Trace {}
codereview_java_data_9952
} } - if (request.getIncludeProcessVariables() != null) { - if (request.getIncludeProcessVariables()) { - taskQuery.includeProcessVariables(); } } I think `request` should be `queryRequest` instead. } } + if (queryRequest.getIncludeProcessVariables() != null) { + if (queryRequest.getIncludeProcessVariables()) { + query.includeProcessVariables(); } }
codereview_java_data_9953
} public static Option startRowOpt() { - final Option o = new Option(START_ROW_OPT, "begin-row", true, "begin row (NOT) inclusive"); o.setArgName("begin-row"); return o; } Parens should go around "(NOT inclusive)" instead of just "(NOT)". Personally, I prefer "(exclusive)". } public static Option startRowOpt() { + final Option o = new Option(START_ROW_OPT, "begin-row", true, "begin row (exclusive)"); o.setArgName("begin-row"); return o; }
codereview_java_data_9961
@Override public int hashCode() { - if (LoadDataBatch.getInstance().isEnableBatchLoadData() && !Objects.isNull(loadData) && !Strings.isNullOrEmpty(loadData.getFileName())) { - return loadData.getFileName().hashCode(); - } return name.hashCode(); } maybe cause problems in some hashmap. for example, two object A and B, which A equals B, but A.hashCode() not equals B.hashCode(). @Override public int hashCode() { return name.hashCode(); }
codereview_java_data_9969
setContentView(getContentViewResourceId()); sbPosition = findViewById(R.id.sbPosition); txtvPosition = findViewById(R.id.txtvPosition); - seekDisplay = findViewById(R.id.seek_display); SharedPreferences prefs = getSharedPreferences(PREFS, MODE_PRIVATE); showTimeLeft = prefs.getBoolean(PREF_SHOW_TIME_LEFT, false); Have you checked a video podcast? I think this line will crash because you only added the view to the layout of the audio player. Would be good to also add it to the video player layout. setContentView(getContentViewResourceId()); sbPosition = findViewById(R.id.sbPosition); txtvPosition = findViewById(R.id.txtvPosition); SharedPreferences prefs = getSharedPreferences(PREFS, MODE_PRIVATE); showTimeLeft = prefs.getBoolean(PREF_SHOW_TIME_LEFT, false);
codereview_java_data_9976
} } - public void onDataSetInvalidated() { - //Doing nothing as of now - } - public interface MediaDetailProvider { Media getMediaAtPosition(int i); Removing these unused methods from the interface is a good idea. } } public interface MediaDetailProvider { Media getMediaAtPosition(int i);
codereview_java_data_9982
try (AccumuloClient c = Accumulo.newClient().from(getClientProperties()).build()) { String tableName = getUniqueNames(1)[0]; c.instanceOperations().setProperty(Property.TABLE_DURABILITY.getKey(), "none"); - Map<String,String> props = c.tableOperations().getPropertiesMap(MetadataTable.NAME); assertEquals("sync", props.get(Property.TABLE_DURABILITY.getKey())); c.tableOperations().create(tableName); - props = c.tableOperations().getPropertiesMap(tableName); assertEquals("none", props.get(Property.TABLE_DURABILITY.getKey())); restartTServer(); assertTrue(c.tableOperations().exists(tableName)); Not sure if the map method is still needed after this change. If it isn't needed, it should be deleted. try (AccumuloClient c = Accumulo.newClient().from(getClientProperties()).build()) { String tableName = getUniqueNames(1)[0]; c.instanceOperations().setProperty(Property.TABLE_DURABILITY.getKey(), "none"); + Map<String,String> props = c.tableOperations().getConfiguration(MetadataTable.NAME); assertEquals("sync", props.get(Property.TABLE_DURABILITY.getKey())); c.tableOperations().create(tableName); + props = c.tableOperations().getConfiguration(tableName); assertEquals("none", props.get(Property.TABLE_DURABILITY.getKey())); restartTServer(); assertTrue(c.tableOperations().exists(tableName));
codereview_java_data_9987
return secretKeyBytes; } - public IdentifyPositionTypes getAuthorizationLocation() { - authorizationLocation = IdentifyPositionTypes.valueOf(EnvUtil.getProperty("nacos.core.auth.authorizationLocation", "")); - return authorizationLocation; } public String[] getAuthorityKey() { - authorityKey = EnvUtil.getProperty("nacos.core.auth.authorityKey", "").split(","); return authorityKey; } Why get value from config file every time? return secretKeyBytes; } + public IdentifyPositionTypes getIdentifyPositionTypes() { + return identifyPosition; } public String[] getAuthorityKey() { return authorityKey; }
codereview_java_data_9990
if (undoLog != null) { MVMap.RootReference rootReference = undoLog.flushAppendBuffer(); undoLogRootReferences[i] = rootReference; - undoLogSize += rootReference.root.getTotalCount() + rootReference.appendCounter; } } } while(committingTransactions != store.committingTransactions.get() || May be some similar change is needed in `sizeAsLongMax()` which should return an upper limit of size? if (undoLog != null) { MVMap.RootReference rootReference = undoLog.flushAppendBuffer(); undoLogRootReferences[i] = rootReference; + undoLogSize += rootReference.root.getTotalCount() + rootReference.getAppendCounter(); } } } while(committingTransactions != store.committingTransactions.get() ||
codereview_java_data_9996
return new RelFieldCollation(field, direction, nullDirection); } public RelDistribution toDistribution(Object o) { final Map map = (Map) o; final RelDistribution.Type type = RelEnumTypes.toEnum((String) map.get("type")); Is there a need to check if Object is a Map? return new RelFieldCollation(field, direction, nullDirection); } + /** + * When serialized to json string, a {@link RelDistribution} object will serialized to + * a map, see {@link #toJson(RelDistribution)} + */ public RelDistribution toDistribution(Object o) { final Map map = (Map) o; final RelDistribution.Type type = RelEnumTypes.toEnum((String) map.get("type"));
codereview_java_data_10004
propertyMap.put(ID, loan.getId().toString()); propertyMap.put(OFFICE_NAME, loan.getOffice().getName()); propertyMap.put(LOAN_PRODUCT_SHORT_NAME, loan.loanProduct().getShortName()); - propertyMap.put(OFFICE_AND_LOAD_PRODUCT_NAME, loan.getOffice().getName()+ loan.loanProduct().getShortName()); return generateAccountNumber(propertyMap, accountNumberFormat); } - public String generate(SavingsAccount savingsAccount, AccountNumberFormat accountNumberFormat) { Map<String, String> propertyMap = new HashMap<>(); propertyMap.put(ID, savingsAccount.getId().toString()); This property is never read again... looks unnecessary propertyMap.put(ID, loan.getId().toString()); propertyMap.put(OFFICE_NAME, loan.getOffice().getName()); propertyMap.put(LOAN_PRODUCT_SHORT_NAME, loan.loanProduct().getShortName()); + propertyMap.put(OFFICE_AND_LOAN_PRODUCT_NAME, getFirstLetters(loan.getOffice().getName()).concat(loan.loanProduct().getShortName())); return generateAccountNumber(propertyMap, accountNumberFormat); } + public String generate(SavingsAccount savingsAccount, AccountNumberFormat accountNumberFormat) { Map<String, String> propertyMap = new HashMap<>(); propertyMap.put(ID, savingsAccount.getId().toString());
codereview_java_data_10005
break; } final List<RexNode> reducedValues = new ArrayList<>(); - RexNode simplifiedExpr = rexBuilder.makeCast(e.getType(), operand); executor.reduce(rexBuilder, ImmutableList.of(simplifiedExpr), reducedValues); return Objects.requireNonNull( Iterables.getOnlyElement(reducedValues)); Makes the `simplifiedExpr ` final. break; } final List<RexNode> reducedValues = new ArrayList<>(); + final RexNode simplifiedExpr = rexBuilder.makeCast(e.getType(), operand); executor.reduce(rexBuilder, ImmutableList.of(simplifiedExpr), reducedValues); return Objects.requireNonNull( Iterables.getOnlyElement(reducedValues));
codereview_java_data_10009
CompactionConfigurer configurer = CompactableUtils.newInstance(tablet.getTableConfiguration(), cfg.getClassName(), CompactionConfigurer.class); - configurer.init(new CompactionConfigurer.InitParamaters() { - - private final ServiceEnvironment senv = new ServiceEnvironmentImpl(tablet.getContext()); @Override public Map<String,String> getOptions() { return cfg.getOptions(); This is created twice in the createCompactionConfiguration method, once for the anonymous InitParamaters (which I just noticed is misspelled; should be InitParameters) and once for the anonymous InputParameters below. This could be created once in the method as a final local variable, and referenced in each anonymous inner class instance's getEnvironment method. CompactionConfigurer configurer = CompactableUtils.newInstance(tablet.getTableConfiguration(), cfg.getClassName(), CompactionConfigurer.class); + final ServiceEnvironment senv = new ServiceEnvironmentImpl(tablet.getContext()); + configurer.init(new CompactionConfigurer.InitParameters() { @Override public Map<String,String> getOptions() { return cfg.getOptions();
codereview_java_data_10011
switch (from.typeId()) { case INTEGER: - return to.equals(Types.LongType.get()); case FLOAT: - return to.equals(Types.DoubleType.get()); case DECIMAL: Types.DecimalType fromDecimal = (Types.DecimalType) from; why is this change necessary? switch (from.typeId()) { case INTEGER: + return to == Types.LongType.get(); case FLOAT: + return to == Types.DoubleType.get(); case DECIMAL: Types.DecimalType fromDecimal = (Types.DecimalType) from;
codereview_java_data_10021
// If the HighlyAvailableService is not initialized or it's not the active service, throw an exception // to prevent processing of the servlet. if (null == Monitor.HA_SERVICE_INSTANCE || !Monitor.HA_SERVICE_INSTANCE.isActiveService()) { - throw new IOException("This is not the active Monitor", new NotActiveServiceException()); } } It'd probably be better to return an explicit 503 on the response, rather than throw an IOException here. We could also try to discern the active monitor (if there is one), and return a 307 redirect. Or, we could have partial functionality (personally, I'm not a fan of the monitor using this locking mechanism... I'd rather support running multiple monitors). // If the HighlyAvailableService is not initialized or it's not the active service, throw an exception // to prevent processing of the servlet. if (null == Monitor.HA_SERVICE_INSTANCE || !Monitor.HA_SERVICE_INSTANCE.isActiveService()) { + throw new IOException(STANDBY_MONITOR_MESSAGE, new NotActiveServiceException()); } }
codereview_java_data_10023
terminal.close(); reader = null; } catch (IOException e) { - e.printStackTrace(); } } if (accumuloClient != null) { I suggest adding a log.warn or log.error here to capture the exception within the logs. terminal.close(); reader = null; } catch (IOException e) { + printException(e); } } if (accumuloClient != null) {
codereview_java_data_10025
* if the user does not have permission * @throws NamespaceNotFoundException * if the specified namespace doesn't exist - * @deprecated since 2.1.0; use {@link #getPropertiesMap(String)} instead. */ @Deprecated(since = "2.1.0") Iterable<Entry<String,String>> getProperties(String namespace) I am wondering if we _need_ to mark this method deprecated. I can't think of a risky/harmful reason why a user shouldn't use this method. Yes, a map is more convenient, which makes the new method nice but I don't know if we need to mark this as deprecated. If a user is using it today there is no reason why they should change their code unless they want to. * if the user does not have permission * @throws NamespaceNotFoundException * if the specified namespace doesn't exist + * @since 1.6.0 + * @deprecated since 2.1.0; use {@link #getConfiguration(String)} (String)} instead. */ @Deprecated(since = "2.1.0") Iterable<Entry<String,String>> getProperties(String namespace)
codereview_java_data_10027
* @param beginLine the linenumber, 1-based. */ public TokenEntry(String image, String tokenSrcID, int beginLine) { - setImage(image); - this.tokenSrcID = tokenSrcID; - this.beginLine = beginLine; - this.beginColumn = -1; - this.endColumn = -1; - this.index = TOKEN_COUNT.get().getAndIncrement(); } /** Please call here the other constructor via `this(image, tokenSrcID, beginLine, -1, -1)`. That way, we don't need to duplicate the logic... * @param beginLine the linenumber, 1-based. */ public TokenEntry(String image, String tokenSrcID, int beginLine) { + this(image, tokenSrcID, beginLine, -1, -1); } /**
codereview_java_data_10030
private static final long serialVersionUID = 1L; - private final Seq<? extends E> errors; /** * Construct an {@code Invalid} I think it can be `Seq<E> errors`. Maybe it needs to be casted when assigned/at creation time in one of our factory methods. private static final long serialVersionUID = 1L; + private final Seq<E> errors; /** * Construct an {@code Invalid}
codereview_java_data_10034
String image = deploy.getContainerInfo().get().getDocker().get().getImage(); checkBadRequest( validDockerRegistries.contains(URI.create(image).getHost()), - String.format("%s does not point to an allowed docker registry", image) ); } } Maybe include the allowed registries in the error message to make this obvious? String image = deploy.getContainerInfo().get().getDocker().get().getImage(); checkBadRequest( validDockerRegistries.contains(URI.create(image).getHost()), + String.format( + "%s does not point to an allowed docker registry. Must be one of: %s", + image, + validDockerRegistries + ) ); } }
codereview_java_data_10038
if (result.hasErrors()) { final String errors = result.errors().stream().map(TomlParseError::toString).collect(Collectors.joining("\n")); - throw new Exception("Invalid TOML configuration : \n" + errors); } return checkConfigurationValidity(result, toml); spurious space between configuration and : if (result.hasErrors()) { final String errors = result.errors().stream().map(TomlParseError::toString).collect(Collectors.joining("\n")); + throw new Exception("Invalid TOML configuration: \n" + errors); } return checkConfigurationValidity(result, toml);
codereview_java_data_10039
super.snapshotState(context); long checkpointId = context.getCheckpointId(); LOG.info("Start to flush snapshot state to state backend, table: {}, checkpointId: {}", table, checkpointId); - long current = System.currentTimeMillis(); - if (checkNeedCommit(current)) { - // Update the checkpoint state. - dataFilesPerCheckpoint.put(checkpointId, writeToManifest(checkpointId)); - lastCheckTime = current; - } // Reset the snapshot state to the latest state. checkpointsState.clear(); checkpointsState.add(dataFilesPerCheckpoint); If the `maxCommitIdleTimeMs` set to be 6min, and the checkpoints produces such `WriteResult`: ``` ckpt1: {data-file1, data-file2}, ckpt2: {}, ckpt3: {data-file3, data-fille4}, ckpt4: {}, ``` If the checkpoint interval is set to be 3min, then for every 6 min, we will still commit a dummy txn which has no data files in iceberg table ? I mean currently we will periodily check whether the `WriteResult` is empty or not, if true then we will commit a dummy iceberg txn to refresh the latest max-committed-txn-id. In fact when there're some txn that has committed few files into iceberg in a `maxCommitIdleTimeMs` interval, then we don't have to commit those empty txn to iceberg, right ? super.snapshotState(context); long checkpointId = context.getCheckpointId(); LOG.info("Start to flush snapshot state to state backend, table: {}, checkpointId: {}", table, checkpointId); + // Update the checkpoint state. + dataFilesPerCheckpoint.put(checkpointId, writeToManifest(checkpointId)); // Reset the snapshot state to the latest state. checkpointsState.clear(); checkpointsState.add(dataFilesPerCheckpoint);
codereview_java_data_10047
requestsDropped.increment(); delegate.onDropped(); } }; } Maybe want to override toString requestsDropped.increment(); delegate.onDropped(); } + + @Override public String toString() { + return "LimiterMetrics{" + delegate + "}"; + } }; }
codereview_java_data_10048
* creation (usually close to execution order) without step execution data filtered by job * names matching query string. * - * @param queryString search query string to filter job names * @param start the index of the first execution to return * @param count the maximum number of executions * @return a collection of {@link JobExecutionWithStepCount} */ - Collection<JobExecutionWithStepCount> listFilteredJobExecutionsWithStepCount(String queryString, int start, int count); } I concerned that there maybe a case for sql injection here. * creation (usually close to execution order) without step execution data filtered by job * names matching query string. * + * @param jobName search query string to filter job names * @param start the index of the first execution to return * @param count the maximum number of executions * @return a collection of {@link JobExecutionWithStepCount} */ + Collection<JobExecutionWithStepCount> listFilteredJobExecutionsWithStepCount(String jobName, int start, int count); }
codereview_java_data_10050
} catch (TableNotFoundException ex) {} try { client.createConditionalWriter(creds, doesNotExist, new ConditionalWriterOptions()); } catch (TableNotFoundException ex) {} } If this thrift call does not throw a NNFE, it seems like the test will still pass? If this is the case, could place an Assert.fail() after each thrift call thats supposed to throw. } catch (TableNotFoundException ex) {} try { client.createConditionalWriter(creds, doesNotExist, new ConditionalWriterOptions()); + fail("exception not thrown"); } catch (TableNotFoundException ex) {} }
codereview_java_data_10051
for (final SingularityEventSender eventListener : eventListeners) { builder.add( listenerExecutorService.submit( - new Callable<Void>() { - - @Override - public Void call() { - eventListener.elevatedAccessEvent(elevatedAccessEvent); - return null; - } } ) ); feel free to change any of these to lambdas too. Much of this is pre-java8 code which is why there are callables/runnables all over for (final SingularityEventSender eventListener : eventListeners) { builder.add( listenerExecutorService.submit( + () -> { + eventListener.elevatedAccessEvent(elevatedAccessEvent); + return null; } ) );
codereview_java_data_10052
*/ @Nonnull public static <T> ProcessorMetaSupplier writeJmsTopicP( @Nonnull SupplierEx<? extends Connection> newConnectionFn, - @Nonnull BiFunctionEx<? super Session, ? super T, ? extends Message> messageFn, - @Nonnull String name ) { - return WriteJmsP.supplier(newConnectionFn, messageFn, name, true); } /** should we still expose `Session` here? */ @Nonnull public static <T> ProcessorMetaSupplier writeJmsTopicP( + @Nonnull String topicName, @Nonnull SupplierEx<? extends Connection> newConnectionFn, + @Nonnull BiFunctionEx<? super Session, ? super T, ? extends Message> messageFn ) { + return WriteJmsP.supplier(topicName, newConnectionFn, messageFn, true); } /**
codereview_java_data_10055
-package main.java.com.getcapacitor.util; import android.graphics.Color; Shouldn't this be `com.getcapacitor.util`? +package com.getcapacitor.util; import android.graphics.Color;
codereview_java_data_10056
storage.put(key, value); } catch (Exception e) { throw new KvStorageException(ErrorCode.KVStorageWriteError.getCode(), - "Put data failed, key: " + new String(key) + ",detail: " + e.getMessage(), e); } // after actual storage put success, put it in memory, memory put should success all the time super.put(key, value); There should be a space between `,` and `detail`. Not only `put` operation, `get`, `delete` also need this enhancement. storage.put(key, value); } catch (Exception e) { throw new KvStorageException(ErrorCode.KVStorageWriteError.getCode(), + "Put data failed, key: " + new String(key) + ", detail: " + e.getMessage(), e); } // after actual storage put success, put it in memory, memory put should success all the time super.put(key, value);
codereview_java_data_10062
else selectFiles(); - tablet.updateTimer(MAJOR, queuedTime, startTime, stats.getEntriesRead(), failed); } } Could shorten the code a bit by removing failed boolean. Please ignore this suggestion if it does not suit you. Just something I thought of when I looked at the code. ```suggestion tablet.updateTimer(MAJOR, queuedTime, startTime, stats.getEntriesRead(), metaFile == null); ``` else selectFiles(); + tablet.updateTimer(MAJOR, queuedTime, startTime, stats.getEntriesRead(), metaFile == null); } }
codereview_java_data_10071
} mRvAllergens = (RecyclerView) view.findViewById(R.id.alergens_recycle); - mAllergens = Utils.getAppDaoSession(this.getActivity()).getAllergenDao().queryBuilder().where(AllergenDao.Properties.Enable.eq("true")).list(); - mAdapter = new AllergensAdapter(mAllergens, getActivity()); mRvAllergens.setAdapter(mAdapter); mRvAllergens.setLayoutManager(new LinearLayoutManager(view.getContext())); mRvAllergens.setHasFixedSize(true); are you sure that's a good idea to require the dao each time we need it in the same class ? instead of create a class field and intialize in the constructor or create method } mRvAllergens = (RecyclerView) view.findViewById(R.id.alergens_recycle); + mAllergensEnabled = Utils.getAppDaoSession(this.getActivity()).getAllergenDao().queryBuilder().where(AllergenDao.Properties.Enable.eq("true")).list(); + mAdapter = new AllergensAdapter(mAllergensEnabled, getActivity()); mRvAllergens.setAdapter(mAdapter); mRvAllergens.setLayoutManager(new LinearLayoutManager(view.getContext())); mRvAllergens.setHasFixedSize(true);
codereview_java_data_10073
boolean actionMessage = false; boolean mediaMessage = false; for (MessageRecord messageRecord : messageRecords) { if (messageRecord.isGroupAction() || messageRecord.isCallLog() || messageRecord.isJoined() || messageRecord.isExpirationTimerUpdate() || Why remove this? boolean actionMessage = false; boolean mediaMessage = false; + if (actionMode != null && messageRecords.size() == 0) { + actionMode.finish(); + return; + } + for (MessageRecord messageRecord : messageRecords) { if (messageRecord.isGroupAction() || messageRecord.isCallLog() || messageRecord.isJoined() || messageRecord.isExpirationTimerUpdate() ||
codereview_java_data_10075
throw new IllegalArgumentException( "Unsupported write ahead log version " + new String(magicBuffer)); } - } catch (Exception e) { - log.warn("Got EOFException trying to read WAL header information," + " assuming the rest of the file has no data."); // A TabletServer might have died before the (complete) header was written throw new LogHeaderIncompleteException(e); This will catch immediately in the catch block below, and print the incorrect message about getting an EOFException (which isn't true in this case). This is probably doing the right thing, but the catch block should be corrected to match. throw new IllegalArgumentException( "Unsupported write ahead log version " + new String(magicBuffer)); } + } catch (EOFException e) { + // Explicitly catch any exceptions that should be converted to LogHeaderIncompleteException + log.info("Got " + e.getClass().getSimpleName() + " trying to read WAL header information," + " assuming the rest of the file has no data."); // A TabletServer might have died before the (complete) header was written throw new LogHeaderIncompleteException(e);