id
stringlengths
23
26
content
stringlengths
182
2.49k
codereview_java_data_5949
String v1name = name(); Vertex v1 = p.dag.newVertex(v1name, metaSupplierFn.apply(eventTimePolicy)) .localParallelism(localParallelism()); - int localParallelism = localParallelism() != LOCAL_PARALLELISM_USE_DEFAULT - ? localParallelism() - : v1.determineLocalParallelism(LOCAL_PARALLELISM_USE_DEFAULT); PlannerVertex pv2 = p.addVertex( this, v1name + "-add-timestamps", localParallelism, insertWatermarksP(eventTimePolicy) ); can be simplified as `int localParallelism = v1.determineLocalParallelism(localParallelism());` String v1name = name(); Vertex v1 = p.dag.newVertex(v1name, metaSupplierFn.apply(eventTimePolicy)) .localParallelism(localParallelism()); + int localParallelism = v1.determineLocalParallelism(localParallelism()); PlannerVertex pv2 = p.addVertex( this, v1name + "-add-timestamps", localParallelism, insertWatermarksP(eventTimePolicy) );
codereview_java_data_5954
import static net.consensys.pantheon.ethereum.p2p.config.DiscoveryConfiguration.MAINNET_BOOTSTRAP_NODES; import static net.consensys.pantheon.ethereum.p2p.config.DiscoveryConfiguration.RINKEBY_BOOTSTRAP_NODES; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.Objects; -import com.google.common.io.Resources; - public class EthNetworkConfig { private static final String MAINNET_GENESIS = "mainnet.json"; private static final String RINKEBY_GENESIS = "rinkeby.json"; should there be some validation here to make sure an invalid eth network can't be constructed? I.e. no networkID? import static net.consensys.pantheon.ethereum.p2p.config.DiscoveryConfiguration.MAINNET_BOOTSTRAP_NODES; import static net.consensys.pantheon.ethereum.p2p.config.DiscoveryConfiguration.RINKEBY_BOOTSTRAP_NODES; +import com.google.common.base.Preconditions; +import com.google.common.io.Resources; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.Objects; public class EthNetworkConfig { private static final String MAINNET_GENESIS = "mainnet.json"; private static final String RINKEBY_GENESIS = "rinkeby.json";
codereview_java_data_5966
OutputFileFactory fileFactory = new OutputFileFactory( spec, format, locations, io.value(), encryptionManager.value(), partitionId, taskId); - final TaskWriter<InternalRow> writer; if (spec.isUnpartitioned()) { writer = new UnpartitionedWriter<>(spec, format, appenderFactory, fileFactory, io.value(), Long.MAX_VALUE); Iceberg doesn't use `final` because it is unlikely that this actually helps. In Java 8, final detection is quite good, which is why non-final variables can be used in closures and lambdas. And final doesn't produce different byte code so it can't do much to help at runtime. OutputFileFactory fileFactory = new OutputFileFactory( spec, format, locations, io.value(), encryptionManager.value(), partitionId, taskId); + TaskWriter<InternalRow> writer; if (spec.isUnpartitioned()) { writer = new UnpartitionedWriter<>(spec, format, appenderFactory, fileFactory, io.value(), Long.MAX_VALUE);
codereview_java_data_5979
package tech.pegasys.pantheon.consensus.ibftlegacy; import static java.util.Collections.singletonList; -import static org.assertj.core.api.Java6Assertions.assertThat; import tech.pegasys.pantheon.consensus.common.CastVote; -import tech.pegasys.pantheon.consensus.common.ValidatorVotePolarity; import tech.pegasys.pantheon.crypto.SECP256K1.KeyPair; import tech.pegasys.pantheon.ethereum.core.Address; import tech.pegasys.pantheon.ethereum.core.AddressHelpers; Same suggestions as for `CliqueVoteBlockInterfaceTest`. package tech.pegasys.pantheon.consensus.ibftlegacy; import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static tech.pegasys.pantheon.consensus.common.ValidatorVotePolarity.ADD; +import static tech.pegasys.pantheon.consensus.common.ValidatorVotePolarity.DROP; +import java.util.List; +import java.util.Optional; +import org.junit.Before; +import org.junit.Test; import tech.pegasys.pantheon.consensus.common.CastVote; import tech.pegasys.pantheon.crypto.SECP256K1.KeyPair; import tech.pegasys.pantheon.ethereum.core.Address; import tech.pegasys.pantheon.ethereum.core.AddressHelpers;
codereview_java_data_5987
return instanceNamePath; } - private String getRootUserName(SiteConfiguration siteConfig, Opts opts) throws IOException { final String keytab = siteConfig.get(Property.GENERAL_KERBEROS_KEYTAB); if (keytab.equals(Property.GENERAL_KERBEROS_KEYTAB.getDefaultValue()) || !siteConfig.getBoolean(Property.INSTANCE_RPC_SASL_ENABLED)) { return DEFAULT_ROOT_USER; } - Console c = System.console(); System.out.println("Running against secured HDFS"); if (opts.rootUser != null) { ```suggestion ``` Can drop this and instead do ``` System.console().readLine("Principal (user) to grant administrative privileges to : "); ``` below where c is used (it is used only once). return instanceNamePath; } + private String getRootUserName(SiteConfiguration siteConfig, Opts opts) { final String keytab = siteConfig.get(Property.GENERAL_KERBEROS_KEYTAB); if (keytab.equals(Property.GENERAL_KERBEROS_KEYTAB.getDefaultValue()) || !siteConfig.getBoolean(Property.INSTANCE_RPC_SASL_ENABLED)) { return DEFAULT_ROOT_USER; } System.out.println("Running against secured HDFS"); if (opts.rootUser != null) {
codereview_java_data_5995
parse(in, false); } - public final void parse(InputStream in, boolean recurse) throws IOException, MessagingException { MimeConfig parserConfig = new MimeConfig(); parserConfig.setMaxHeaderLen(-1); // The default is a mere 10k parserConfig.setMaxLineLen(-1); // The default is 1000 characters. Some MUAs generate If we move `MessageTest` to the internet package (and rename it to `MimeMessageTest`, which is what it is), these can be package-local. Also please annotate `@VisibleForTesting` parse(in, false); } + private void parse(InputStream in, boolean recurse) throws IOException, MessagingException { MimeConfig parserConfig = new MimeConfig(); parserConfig.setMaxHeaderLen(-1); // The default is a mere 10k parserConfig.setMaxLineLen(-1); // The default is 1000 characters. Some MUAs generate
codereview_java_data_5996
// Default should be FAST for the next release // but we use FULL for the moment as Fast is still in progress SyncMode DEFAULT_SYNC_MODE = SyncMode.FULL; - int DEFAULT_FAST_SYNC_MAX_WAIT_TIME = 0; - int DEFAULT_FAST_SYNC_MIN_PEER_COUNT = 5; int DEFAULT_MAX_PEERS = 25; static Path getDefaultPantheonDataPath(final Object command) { I know not all the constants in this file are named correctly but we should try to avoid having "DEFAULT" in the constant name as it's clear given the class we are in. // Default should be FAST for the next release // but we use FULL for the moment as Fast is still in progress SyncMode DEFAULT_SYNC_MODE = SyncMode.FULL; + int FAST_SYNC_MAX_WAIT_TIME = 0; + int FAST_SYNC_MIN_PEER_COUNT = 5; int DEFAULT_MAX_PEERS = 25; static Path getDefaultPantheonDataPath(final Object command) {
codereview_java_data_6007
public void tlsTimeoutConfigured_shouldHonor() { Duration connectTimeout = Duration.ofSeconds(1); Duration tlsTimeout = Duration.ofSeconds(3); try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() .connectionTimeout(connectTimeout) .tlsNegotiationTimeout(tlsTimeout) What happens if you set `tlsNegotiationTimeout` first and `connectionTimeout` second? Looking at the code, I'm worried it will overwrite the explicit `tlsNegotiationTimeout`. public void tlsTimeoutConfigured_shouldHonor() { Duration connectTimeout = Duration.ofSeconds(1); Duration tlsTimeout = Duration.ofSeconds(3); + try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() + .tlsNegotiationTimeout(tlsTimeout) + .connectionTimeout(connectTimeout) + .build()) { + assertThat(client.configuration().tlsHandshakeTimeout()).isEqualTo(tlsTimeout); + } + try (NettyNioAsyncHttpClient client = (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder() .connectionTimeout(connectTimeout) .tlsNegotiationTimeout(tlsTimeout)
codereview_java_data_6008
int ver = props.getDataVersion(); - var createdTs = props.getTimestamp(); byte[] bytes = props.toBytes(); Might be clearer this way. ```suggestion Instant createdTs = props.getTimestamp(); ``` int ver = props.getDataVersion(); + Instant createdTs = props.getTimestamp(); byte[] bytes = props.toBytes();
codereview_java_data_6021
for (int i = 1; i <= THREAD_COUNT; i++) { final int threadId = i - 1; - Assertions.assertTimeout(TIMEOUT, () -> { try { futures.get(threadId).get(); } catch (final InterruptedException | ExecutionException e) { This must be a preemptive timeout because this test tests a possible classloader deadlock. for (int i = 1; i <= THREAD_COUNT; i++) { final int threadId = i - 1; + assertTimeoutPreemptively(TIMEOUT, () -> { try { futures.get(threadId).get(); } catch (final InterruptedException | ExecutionException e) {
codereview_java_data_6022
switch (nodesWhitelistResult.result()) { case SUCCESS: return new JsonRpcSuccessResponse(req.getId(), true); - case ADD_ERROR_EXISTING_ENTRY: return new JsonRpcErrorResponse(req.getId(), JsonRpcError.NODE_WHITELIST_EXISTING_ENTRY); case ERROR_DUPLICATED_ENTRY: return new JsonRpcErrorResponse( s/ADD_ERROR_EXISTING_ENTRY/ERROR_EXISTING_ENTRY I realise this wasn't part of your PR - but it would be good to have consistency between PermAddNodesToWhitelist and PermAddAccountsToWhitelist. switch (nodesWhitelistResult.result()) { case SUCCESS: return new JsonRpcSuccessResponse(req.getId(), true); + case ERROR_EXISTING_ENTRY: return new JsonRpcErrorResponse(req.getId(), JsonRpcError.NODE_WHITELIST_EXISTING_ENTRY); case ERROR_DUPLICATED_ENTRY: return new JsonRpcErrorResponse(
codereview_java_data_6030
} } - // determine exact local parallelism of the transforms - for (Transform transform : adjacencyMap.keySet()) { - transform.determineLocalParallelism(ctx); - } - // fuse subsequent map/filter/flatMap transforms into one Map<Transform, List<Transform>> originalParents = new HashMap<>(); List<Transform> transforms = new ArrayList<>(adjacencyMap.keySet()); Here we mutate the pipeline. The following code will have unexpected behavior. ```java Pipeline p = ... DAG dagWithLp1 = p.toDag(() -> 1); DAG dagWithLp2 = p.toDag(() -> 2); ``` Both DAGs will use LP=1 where default LP was used. I also don't see a reason why do we need this. Can't we have the vertices with LP=1 and rely on the logic in `Vertex` class? } } // fuse subsequent map/filter/flatMap transforms into one Map<Transform, List<Transform>> originalParents = new HashMap<>(); List<Transform> transforms = new ArrayList<>(adjacencyMap.keySet());
codereview_java_data_6033
break; } } - } catch (MessagingException | IOException e) { /* * Let the user continue composing their message even if we have a problem processing * the source message. Log it as an error, though. this seems like a bad idea, I'd rather wrap the IOException into a MessagingException further down the stack where it's still visible why IOExceptions can happen and why they are handled this way. break; } } + } catch (MessagingException e) { /* * Let the user continue composing their message even if we have a problem processing * the source message. Log it as an error, though.
codereview_java_data_6035
mFileRegistry.deleteTopicPartition(topicPartition); mZookeeperConnector.setCommittedOffsetCount(topicPartition, lastSeenOffset + 1); mOffsetTracker.setCommittedOffsetCount(topicPartition, lastSeenOffset + 1); - if (mConfig.getOffsetsStorage().equals("kafka")) { mMessageReader.commit(); } mMetricCollector.increment("uploader.file_uploads.count", paths.size(), topicPartition.getTopic()); Can this constant "kafka" defined in a a central place, e.g. SecorConfig.java? And should it be 'equals' or 'equalsIgnoreCase'? mFileRegistry.deleteTopicPartition(topicPartition); mZookeeperConnector.setCommittedOffsetCount(topicPartition, lastSeenOffset + 1); mOffsetTracker.setCommittedOffsetCount(topicPartition, lastSeenOffset + 1); + if (isOffsetsStorageKafka) { mMessageReader.commit(); } mMetricCollector.increment("uploader.file_uploads.count", paths.size(), topicPartition.getTopic());
codereview_java_data_6037
.getBoolean("com.alibaba.nacos.client.naming.tls.enable"); private static final int MAX_REDIRECTS = 5; - private static final HttpClientFactory HTTP_CLIENT_FACTORY = new NamingHttpClientConfig(); public static String getPrefix() { if (ENABLE_HTTPS) { `NamingHttpClientFactory` will be better. `NamingHttpClientConfig` make other think it is a config pojo. .getBoolean("com.alibaba.nacos.client.naming.tls.enable"); private static final int MAX_REDIRECTS = 5; + private static final HttpClientFactory HTTP_CLIENT_FACTORY = new NamingHttpClientFactory(); public static String getPrefix() { if (ENABLE_HTTPS) {
codereview_java_data_6038
private static final Place PLACE = new Place("name", Place.Label.AIRPORT, "desc", null, new LatLng(38.6270, -90.1994, 0), null); private static final Place UNKNOWN_PLACE = new Place("name", Place.Label.UNKNOWN, -<<<<<<< HEAD -======= -<<<<<<< 27ac8ae0d72011bc651affecf7b1da2100ec927e - "?", null, new LatLng(39.7392, -104.9903, 0), null); - // ^ "?" is a special value for unknown class names from Wikidata query results -======= ->>>>>>> directNearbyUploadsNewLocal "desc", null, new LatLng(39.7392, -104.9903, 0), null); ->>>>>>> Rename Description to Label to prevent misunderstandings private Place clickedPlace; @Test Some conflicts still remain. :) private static final Place PLACE = new Place("name", Place.Label.AIRPORT, "desc", null, new LatLng(38.6270, -90.1994, 0), null); private static final Place UNKNOWN_PLACE = new Place("name", Place.Label.UNKNOWN, "desc", null, new LatLng(39.7392, -104.9903, 0), null); + private Place clickedPlace; @Test
codereview_java_data_6053
import org.junit.jupiter.api.Disabled; import org.kie.kogito.testcontainers.quarkus.InfinispanQuarkusTestResource; -@Disabled("Currently not working in native mode") @NativeImageTest @QuarkusTestResource(InfinispanQuarkusTestResource.Conditional.class) class NativeJavaFNctxIT extends JavaFNctxTest { ```suggestion @Disabled("[KOGITO-TICKETID] Currently not working in native mode (Quarkus 1.8 CR1 + GraalVM 20.2)") ``` import org.junit.jupiter.api.Disabled; import org.kie.kogito.testcontainers.quarkus.InfinispanQuarkusTestResource; +@Disabled("KOGITO-3269 NativeJavaFNctxIT not working in native mode (Quarkus 1.8 CR1 + GraalVM 20.2)") @NativeImageTest @QuarkusTestResource(InfinispanQuarkusTestResource.Conditional.class) class NativeJavaFNctxIT extends JavaFNctxTest {
codereview_java_data_6067
Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper, BiFunction<? super V, ? super V, ? extends V> merge) { - return LinkedHashMap.ofEntries(toMap(keyMapper, valueMapper, merge)); } /** I think we do not maintain key order here, which is iteration order of the elements of this Traversable. The result of `toMap` does not guarantee any specific key order. So we need to do some extra work to order the keys of the LinkedHashMap: ```java default <K extends Comparable<? super K>, V> Map<K, V> toLinkedMap( Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper, BiFunction<? super V, ? super V, ? extends V> merge) { final Map<K, V> map = toMap(keyMapper, valueMapper, merge); final Iterator<K, V> entries = iterator().map(t -> { K key = keyMapper.apply(t); V value = map.getOrElse(key, null); // the default value will not be used return Tuple.of(key, value); }); return LinkedHashMap.ofEntries(entries); } ``` Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends V> valueMapper, BiFunction<? super V, ? super V, ? extends V> merge) { + final Map<K, V> map = toMap(keyMapper, valueMapper, merge); + final Iterator<Tuple2<K, V>> entries = iterator() + .map(keyMapper) + .distinct() + .map(key -> { + V value = map.getOrElse(key, null); // the default value will not be used + return Tuple.of(key, value); + }); + return LinkedHashMap.ofEntries(entries); } /**
codereview_java_data_6068
.map(AccountManagerFuture::getResult) .doOnEvent((bundle, throwable) -> { if (bundle.containsKey(AccountManager.KEY_ACCOUNT_NAME)) { - throw new RuntimeException(); } }) .map(bundle -> bundle.getString(AccountManager.KEY_ACCOUNT_NAME)) Doesnt this do the reverse of what we want? If the bundle contains an account name it should be a success & not an exception, surely? .map(AccountManagerFuture::getResult) .doOnEvent((bundle, throwable) -> { if (bundle.containsKey(AccountManager.KEY_ACCOUNT_NAME)) { + throw new RuntimeException("Bundle doesn't contain account-name key: " + + AccountManager.KEY_ACCOUNT_NAME); } }) .map(bundle -> bundle.getString(AccountManager.KEY_ACCOUNT_NAME))
codereview_java_data_6069
MetricsConfiguration metricsConfiguration() { final MetricsConfiguration metricsConfiguration = createDefault(); metricsConfiguration.setEnabled(isMetricsEnabled); - metricsConfiguration.setMode(metricsMode); metricsConfiguration.setHost(metricsHost.toString()); metricsConfiguration.setPort(metricsPort); metricsConfiguration.setPushHost(metricsPushHost.toString()); metricsConfiguration.setPushPort(metricsPushPort); metricsConfiguration.setPushInterval(metricsPushInterval); Is there a way to throw an error if the user configures a set of host / port values that don't correspond to the chosen mode? MetricsConfiguration metricsConfiguration() { final MetricsConfiguration metricsConfiguration = createDefault(); metricsConfiguration.setEnabled(isMetricsEnabled); metricsConfiguration.setHost(metricsHost.toString()); metricsConfiguration.setPort(metricsPort); + metricsConfiguration.setPushEnabled(isMetricsPushEnabled); metricsConfiguration.setPushHost(metricsPushHost.toString()); metricsConfiguration.setPushPort(metricsPushPort); metricsConfiguration.setPushInterval(metricsPushInterval);
codereview_java_data_6085
} private static File newStagingFile(String ossStagingDirectory) { - Preconditions.checkArgument(ossStagingDirectory != null, "Invalid staging directory: null"); try { File stagingFile = File.createTempFile("oss-file-io-", ".tmp", new File(ossStagingDirectory)); stagingFile.deleteOnExit(); Minor: should this be moved into the config class so it is validated when properties are parsed instead of each time you get a new staging file? } private static File newStagingFile(String ossStagingDirectory) { try { File stagingFile = File.createTempFile("oss-file-io-", ".tmp", new File(ossStagingDirectory)); stagingFile.deleteOnExit();
codereview_java_data_6086
int packetType = s.startsWith("M-SEARCH") ? M_SEARCH : s.startsWith("NOTIFY") ? NOTIFY : 0; boolean redundant = address.equals(lastAddress) && packetType == lastPacketType; - if (packetType == M_SEARCH || packetType == NOTIFY) { if (configuration.getIpFiltering().allowed(address)) { String remoteAddr = address.getHostAddress(); int remotePort = receivePacket.getPort(); Why would you use both `+ type +` and `{}` in the same log entry? It means that two `StringBuilder`s have to be created when running this one line in trace mode, and one when not in trace. int packetType = s.startsWith("M-SEARCH") ? M_SEARCH : s.startsWith("NOTIFY") ? NOTIFY : 0; boolean redundant = address.equals(lastAddress) && packetType == lastPacketType; + // Is the request from our own server, i.e. self-originating? + boolean isSelf = address.getHostAddress().equals(PMS.get().getServer().getHost()) && + s.contains("UMS/"); + if (!isSelf && (packetType == M_SEARCH || packetType == NOTIFY)) { if (configuration.getIpFiltering().allowed(address)) { String remoteAddr = address.getHostAddress(); int remotePort = receivePacket.getPort();
codereview_java_data_6093
assertEquals(3, state.getActiveAgents()); } - - @Test - public void testScheduledTasksInfoEndpoint(SingularityClient singularityClient) { - final SingularityScheduledTasksInfo scheduledTasksInfo = singularityClient.getScheduledTasksInfo(); - // TODO: assertion - } } We don't actually have any real unit tests set up for the SingularityClient at the moment (yes... shame on us...). If you are trying to fit unit tests in for this PR, better bet would be to write one for the `stateManager.getScheduledTasksInfo();` method. The SingularityClient methods you'll likely end up testing in our staging environment instead assertEquals(3, state.getActiveAgents()); } }
codereview_java_data_6096
intersectMap.put(instance.toString(), 1); } } - - instancesMap.put(instance.toString(), instance); } Do not change the Indentation. intersectMap.put(instance.toString(), 1); } } + + newInstancesMap.put(instance.toString(), instance); }
codereview_java_data_6097
import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; -import org.junit.internal.ExactComparisonCriteria; import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.METASTOREURIS; Is it normal to use this class that's got `internal` in the package name? Do we have to worry about behavioral changes if we upgrade JUnit? import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.METASTOREURIS;
codereview_java_data_6108
} catch (Exception ex) { if (lock != null || asyncLock != null) { lockWatcher.unableToMonitorLockNode(ex); - log.error("Error resetting watch on ZooLock " + lock + " " + event, ex); } } This is a different log message than before if lock == null; it never logs the asyncLock info in that case. How about: ```suggestion log.error("Error resetting watch on ZooLock {} {}", lock != null ? lock : asyncLock, event, ex); ``` } catch (Exception ex) { if (lock != null || asyncLock != null) { lockWatcher.unableToMonitorLockNode(ex); + log.error("Error resetting watch on ZooLock {} {}", lock != null ? lock : asyncLock, + event, ex); } }
codereview_java_data_6111
private void checkExplain(Statement stat, String sql, String expected) throws SQLException { ResultSet rs = stat.executeQuery(sql); - rs.next(); assertEquals(expected, rs.getString(1)); } Do we have any `EXPLAIN ANALYZE` tests? I do not see any. private void checkExplain(Statement stat, String sql, String expected) throws SQLException { ResultSet rs = stat.executeQuery(sql); + assertTrue(rs.next()); assertEquals(expected, rs.getString(1)); }
codereview_java_data_6116
* @param mapper A {@code Function} * @throws NullPointerException if {@code mapper} is null */ - default <W> Map<K, W> mapValues(Function<V, ? extends W> mapper) { - Objects.requireNonNull(mapper, "mapper is null"); - return map((k, v) -> Tuple.of(k, mapper.apply(v))); - } Map<K, V> put(K key, V value); This needs to be an abstract method, also in `SortedMap`. We need to implement it with appropriate return type in `HashMap`, `LinkedHashMap` and `TreeMap`. * @param mapper A {@code Function} * @throws NullPointerException if {@code mapper} is null */ + <W> Map<K, W> mapValues(Function<V, ? extends W> mapper); Map<K, V> put(K key, V value);
codereview_java_data_6118
} public String getUploaderRetries() { - return getString("secor.upload.retries", "5"); } public String getUploadManagerClass() { Can you add this property in secor.common.properties with default value. We prefer setting the default value in properties file instead of java class. Is default value 3 better than 5? } public String getUploaderRetries() { + return getString("secor.upload.retries"); + } + + public String getUploaderRetryBackoffMillis() { + return getString("secor.upload.retry.backoff"); } public String getUploadManagerClass() {
codereview_java_data_6119
* * @param tag the tag of the associated input stream * @param accumulateFn the {@code accumulate} primitive. It must be - * stateless and {@linkplain Processor#isCooperative() cooperative} * @param <T> the expected type of input item * @return this */ ```suggestion * stateless and {@linkplain Processor#isCooperative() cooperative}. ``` * * @param tag the tag of the associated input stream * @param accumulateFn the {@code accumulate} primitive. It must be + * stateless and {@linkplain Processor#isCooperative() cooperative}. * @param <T> the expected type of input item * @return this */
codereview_java_data_6121
case KeyEvent.KEYCODE_DPAD_LEFT: //Go Back onRewind(); break; case KeyEvent.KEYCODE_DPAD_RIGHT: //Go Forward onFastForward(); break; case KeyEvent.KEYCODE_M: //Mute/Unmute For double-tapping forward and backward, we already have a nice little animation. Could you try to add it here, too? case KeyEvent.KEYCODE_DPAD_LEFT: //Go Back onRewind(); + showSkipAnimation(false); break; case KeyEvent.KEYCODE_DPAD_RIGHT: //Go Forward onFastForward(); + showSkipAnimation(true); break; case KeyEvent.KEYCODE_M: //Mute/Unmute
codereview_java_data_6132
} @Test - public void testUseUserAccessTokenFromCTRProps() { ComposedTaskRunnerConfigurationProperties composedTaskRunnerConfigurationProperties = new ComposedTaskRunnerConfigurationProperties(); composedTaskRunnerConfigurationProperties.setUseUserAccessToken(true); We should also have a test that test if the user sets access token to false. i.e. composedTaskRunnerConfigurationProperties.setUseUserAccessToken(false); } @Test + public void testUseUserAccessTokenFromCTRPropsEnabled() { ComposedTaskRunnerConfigurationProperties composedTaskRunnerConfigurationProperties = new ComposedTaskRunnerConfigurationProperties(); composedTaskRunnerConfigurationProperties.setUseUserAccessToken(true);
codereview_java_data_6140
import javax.annotation.Resource; import javax.enterprise.context.SessionScoped; -import javax.faces.component.UIComponent; -import javax.faces.context.FacesContext; import javax.inject.Named; import javax.mail.Address; import javax.mail.Message; I know it seems silly for such a trivial example, but you might want to use a Resources class like: ``` public class Resources { @Produces @Resource (mappedName="java:jboss/mail/Default") private Session mySession; } ``` As then you can just @Inject the Session wherever you want. import javax.annotation.Resource; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import javax.mail.Address; import javax.mail.Message;
codereview_java_data_6142
throw new UnsupportedOperationException("Cannot rename Hadoop tables"); } - private static final PathFilter TABLE_FILTER = path -> path.getName().endsWith(TABLE_METADATA_FILE_EXTENSION); - @Override public void close() throws IOException { } Should this class variable move to the top of the class? throw new UnsupportedOperationException("Cannot rename Hadoop tables"); } @Override public void close() throws IOException { }
codereview_java_data_6153
/** * Get the tablet metadata for the given extents. This will find tablets based on end row, so - * its possible the prev rows could differ for the tablets returned. If this matters then it * must be checked. */ Options forTablets(Collection<KeyExtent> extents); "its" -> "it's" ("it is") ```suggestion * it's possible the prev rows could differ for the tablets returned. If this matters, then it ``` /** * Get the tablet metadata for the given extents. This will find tablets based on end row, so + * it's possible the prev rows could differ for the tablets returned. If this matters, then it * must be checked. */ Options forTablets(Collection<KeyExtent> extents);
codereview_java_data_6154
V value = this.zkValues.get().get(key); if (value == null) { - LOG.debug("ApiCache returned null for {}", key); } return value; for this and the debug statement above, maybe these are more like TRACE level lines? Would get pretty noisy given that we could acall these multiple times a second V value = this.zkValues.get().get(key); if (value == null) { + LOG.trace("ApiCache returned null for {}", key); } return value;
codereview_java_data_6160
private static final int MESSAGE_TYPE_THUMBNAIL_INCOMING = 6; private static final int MESSAGE_TYPE_DOCUMENT_OUTGOING = 7; private static final int MESSAGE_TYPE_DOCUMENT_INCOMING = 8; - private static final int MESSAGE_TYPE_INCOMING_MULTIPART = 9; private final Set<MessageRecord> batchSelected = Collections.synchronizedSet(new HashSet<MessageRecord>()); Shouldn't this be "MESSAGE_TYPE_MULTIPART_INCOMING" (and possibly "=10" since outgoing is listed before incoming) to keep with the above established naming convention? private static final int MESSAGE_TYPE_THUMBNAIL_INCOMING = 6; private static final int MESSAGE_TYPE_DOCUMENT_OUTGOING = 7; private static final int MESSAGE_TYPE_DOCUMENT_INCOMING = 8; + private static final int MESSAGE_TYPE_MULTIPART_INCOMING = 9; private final Set<MessageRecord> batchSelected = Collections.synchronizedSet(new HashSet<MessageRecord>());
codereview_java_data_6162
// rule // #Ceil(MapItem(K1, K2, ..., Kn) Rest:Map) // => - // {(@K1 in_keys(@Rest)) #Equals false} #And ... #And #Ceil(@Kn) - // Note: The {_ in_Keys(_) #Equals false} condition implies // #Ceil(@K1) and #Ceil(@Rest). // [anywhere, simplification] I agree with you that the `in_keys` condition would require the variables to be defined anyway. Why then keep the definedness conditions? // rule // #Ceil(MapItem(K1, K2, ..., Kn) Rest:Map) // => + // {(@K1 in_keys(@Rest)) #Equals false} #And #Ceil(@K2) #And ... #And #Ceil(@Kn) + // Note: The {_ in_keys(_) #Equals false} condition implies // #Ceil(@K1) and #Ceil(@Rest). // [anywhere, simplification]
codereview_java_data_6172
* location. * * @param schema iceberg schema used to create the table - * @param spec partition specification - * @param properties properties of the table to be created * @param location a path URI (e.g. hdfs:///warehouse/my_table) * @return newly created table implementation */ Can you note that null is accepted? Also, should we do something similar for spec? If spec is null, we could use `PartitionSpec.unpartitioned()`. * location. * * @param schema iceberg schema used to create the table + * @param spec partition specification. It can be null in case of unpartitioned table + * @param properties properties of the table to be created, it can be null * @param location a path URI (e.g. hdfs:///warehouse/my_table) * @return newly created table implementation */
codereview_java_data_6173
private final Collection<Path> classesPaths = new ArrayList<>(); private final boolean isJar; - private final String resourcesPath; public static AppPaths fromProjectDir(Path projectDir) { return new AppPaths(Collections.singleton(projectDir), Collections.emptyList(), false, BuildTool.MAVEN); I think in the future we might consider to support `Gradle` also via `kogito-maven-plugin` (so also for Springboot). Wdyt? What about a ticket for that? private final Collection<Path> classesPaths = new ArrayList<>(); private final boolean isJar; + private final Path resourcesPath; public static AppPaths fromProjectDir(Path projectDir) { return new AppPaths(Collections.singleton(projectDir), Collections.emptyList(), false, BuildTool.MAVEN);
codereview_java_data_6175
*/ package tech.pegasys.pantheon.ethereum.eth.sync.fastsync; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; (optional) Might also be good to have a test that imports a sequence of blocks and fails early in that sequence. Then we can check that `fastImportBlock` doesn't get called for the blocks after the failure. */ package tech.pegasys.pantheon.ethereum.eth.sync.fastsync; +import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when;
codereview_java_data_6176
DialogUtil.showAlertDialog(getActivity(), getString(R.string.upload_problem_image), errorMessageForResult, - getString(R.string.cancel), getString(R.string.upload), () -> { uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); onNextButtonClicked(); buttons are in wrong positions, Proceed on the right, Cancel on the left DialogUtil.showAlertDialog(getActivity(), getString(R.string.upload_problem_image), errorMessageForResult, getString(R.string.upload), + getString(R.string.cancel), () -> { uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); onNextButtonClicked();
codereview_java_data_6179
cleanImmediately = false; { - String storePaths; - if (DefaultMessageStore.this.getMessageStoreConfig().isMultiCommitLogPathEnable()) { - storePaths = DefaultMessageStore.this.getMessageStoreConfig().getCommitLogStorePaths(); - } else { - storePaths = DefaultMessageStore.this.getMessageStoreConfig().getStorePathCommitLog(); - } - double physicRatio = UtilAll.getDiskPartitionSpaceUsedPercent(storePaths); if (physicRatio > diskSpaceWarningLevelRatio) { boolean diskok = DefaultMessageStore.this.runningFlags.getAndMakeDiskFull(); Any update? what's the meaning of the diskok? cleanImmediately = false; { + String storePaths = DefaultMessageStore.this.getMessageStoreConfig().getStorePathCommitLog(); double physicRatio = UtilAll.getDiskPartitionSpaceUsedPercent(storePaths); if (physicRatio > diskSpaceWarningLevelRatio) { boolean diskok = DefaultMessageStore.this.runningFlags.getAndMakeDiskFull();
codereview_java_data_6188
import tech.pegasys.pantheon.ethereum.mainnet.HeaderValidationMode; public interface ValidationPolicy { HeaderValidationMode getValidationModeForNextBlock(); Might be worth adding `@FunctionalInterface` here import tech.pegasys.pantheon.ethereum.mainnet.HeaderValidationMode; +@FunctionalInterface public interface ValidationPolicy { HeaderValidationMode getValidationModeForNextBlock();
codereview_java_data_6190
if (resumeRes != null && resumeRes.media != null) { resumeRes.media.setThumbready(false); resumeRes.media.setMimeType(HTTPResource.VIDEO_TRANSCODE); - resumeRes.media.setThumbready(false); } /** @SubJunk Why set "thumbready" twice? if (resumeRes != null && resumeRes.media != null) { resumeRes.media.setThumbready(false); resumeRes.media.setMimeType(HTTPResource.VIDEO_TRANSCODE); } /**
codereview_java_data_6192
@FunctionalInterface public interface MessageCallback { - MessageCallback NOOP = (final Capability capability, final Message message) -> {}; - void onMessage(final Capability capability, final Message message); } (Discussion) What are those NOOPs Callback used for ? Is it only for testing purpose and are they really used in the code ? @FunctionalInterface public interface MessageCallback { void onMessage(final Capability capability, final Message message); }
codereview_java_data_6195
public void onReceive(Context context, Intent intent) { if (NetworkUtils.isInternetConnectionEstablished(NearbyActivity.this)) { refreshView(LOCATION_SIGNIFICANTLY_CHANGED); } else { - Snackbar.make(transparentView , R.string.no_internet, Snackbar.LENGTH_INDEFINITE).show(); } } }; Probably want to remove the snackbar here? public void onReceive(Context context, Intent intent) { if (NetworkUtils.isInternetConnectionEstablished(NearbyActivity.this)) { refreshView(LOCATION_SIGNIFICANTLY_CHANGED); + snackbar.dismiss(); } else { + snackbar.show(); } } };
codereview_java_data_6203
} @Override - void load(List<TabletMetadata> tablets, Files files) throws Exception { byte[] fam = TextUtil.getBytes(DataFileColumnFamily.NAME); for (TabletMetadata tablet : tablets) { scanTime can be negative because `System.currentTimeMillis` are used instead of `System.nanoTime`; that could cause some unexpected behavior here. Probably unlikely, though... and worst case seems to just use wait longer than necessary. } @Override + void load(List<TabletMetadata> tablets, Files files) throws MutationsRejectedException { byte[] fam = TextUtil.getBytes(DataFileColumnFamily.NAME); for (TabletMetadata tablet : tablets) {
codereview_java_data_6214
Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); Double MaxIOBallowed = constraintChecker.getMaxIOBAllowed().value(); String APSmode = sp.getString(R.string.key_aps_mode, "open"); - Double LGSthreshold = 0d; PumpInterface pump = activePlugin.getActivePump(); boolean isLGS = false; if (!isSuspended() && !pump.isSuspended()) if (closedLoopEnabled.value()) - if ((MaxIOBallowed.equals(LGSthreshold)) || (APSmode.equals("lgs"))) isLGS = true; return isLGS; Shouldn't this come from the `HardLimits.kt` constants? Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); Double MaxIOBallowed = constraintChecker.getMaxIOBAllowed().value(); String APSmode = sp.getString(R.string.key_aps_mode, "open"); PumpInterface pump = activePlugin.getActivePump(); boolean isLGS = false; + if (!isSuspended() && !pump.isSuspended()) if (closedLoopEnabled.value()) + if ((MaxIOBallowed.equals(hardLimits.getMAXIOB_LGS())) || (APSmode.equals("lgs"))) isLGS = true; return isLGS;
codereview_java_data_6215
out = resizeApplicationBuffer(out);// guarantees enough room for unwrap // Record a hex dump of the buffer, but only when logging on level 'debug'. String hexDump = null; if ( Log.isDebugEnabled() ) { If debug is enabled, hexDump is calculated - but only ever used if the exception occurs. Is it worth moving this section to the exception handler? out = resizeApplicationBuffer(out);// guarantees enough room for unwrap // Record a hex dump of the buffer, but only when logging on level 'debug'. + // Create the dump before the buffer is being passed to tlsEngine, to ensure + // that the original content of the buffer is logged. String hexDump = null; if ( Log.isDebugEnabled() ) {
codereview_java_data_6219
import java.util.List; import java.util.stream.Collectors; -import com.github.javaparser.StaticJavaParser; -import com.github.javaparser.ast.CompilationUnit; -import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; -import com.github.javaparser.ast.stmt.ReturnStmt; import org.drools.compiler.compiler.DecisionTableFactory; import org.drools.compiler.compiler.DecisionTableProvider; import org.junit.jupiter.api.Assertions; This is probably the main reason of the code formatting problem import java.util.List; import java.util.stream.Collectors; import org.drools.compiler.compiler.DecisionTableFactory; import org.drools.compiler.compiler.DecisionTableProvider; import org.junit.jupiter.api.Assertions;
codereview_java_data_6230
@Override public Set<StoredTabletFile> getCandidates(Set<StoredTabletFile> currFiles, CompactionKind kind) { - Set<StoredTabletFile> candidates = new HashSet<>(currFiles); - candidates.removeAll(allCompactingFiles); - return Collections.unmodifiableSet(candidates); } } ```suggestion return Collections.unmodifiableSet(Sets.difference(currFiles, allCompactingFiles)); ``` This might be a nice change. @Override public Set<StoredTabletFile> getCandidates(Set<StoredTabletFile> currFiles, CompactionKind kind) { + return Collections.unmodifiableSet(Sets.difference(currFiles, allCompactingFiles)); } }
codereview_java_data_6231
.isIn("UP", "DOWN", "UNKNOWN"); assertThat(readString(json, "$.zipkin.status")) .isIn("UP", "DOWN", "UNKNOWN"); - assertThat(readString(json, "$.diskSpace.status")) - .isIn("UP", "DOWN", "UNKNOWN"); } @Test public void writesSpans_readMetricsFormat() throws Exception { we don't need this one .isIn("UP", "DOWN", "UNKNOWN"); assertThat(readString(json, "$.zipkin.status")) .isIn("UP", "DOWN", "UNKNOWN"); } @Test public void writesSpans_readMetricsFormat() throws Exception {
codereview_java_data_6233
*/ public static final String ZDELEGATION_TOKEN_KEYS = "/delegation_token_keys"; - /** - * Initial tablet directory name for the default tablet in all tables - */ - public static final String DEFAULT_TABLET_DIR_NAME = "default_tablet"; - public static final String ZTABLE_LOCKS = "/table_locks"; public static final String BULK_PREFIX = "b-"; Been trying to phase out these global constants anyway. Is there a more appropriate location for this new constant? */ public static final String ZDELEGATION_TOKEN_KEYS = "/delegation_token_keys"; public static final String ZTABLE_LOCKS = "/table_locks"; public static final String BULK_PREFIX = "b-";
codereview_java_data_6238
long executionId, SnapshotContext snapshotContext, ConcurrentHashMap<String, File> tempDirectories, - InternalSerializationService serializationService) { this.nodeEngine = (NodeEngineImpl) nodeEngine; this.executionId = executionId; - initProcSuppliers(jobId, executionId, tempDirectories, serializationService); - initDag(serializationService); this.ptionArrgmt = new PartitionArrangement(partitionOwners, nodeEngine.getThisAddress()); JetInstance instance = getJetInstance(nodeEngine); this should be called `jobSerializationService` long executionId, SnapshotContext snapshotContext, ConcurrentHashMap<String, File> tempDirectories, + InternalSerializationService jobSerializationService) { this.nodeEngine = (NodeEngineImpl) nodeEngine; this.executionId = executionId; + initProcSuppliers(jobId, executionId, tempDirectories, jobSerializationService); + initDag(jobSerializationService); this.ptionArrgmt = new PartitionArrangement(partitionOwners, nodeEngine.getThisAddress()); JetInstance instance = getJetInstance(nodeEngine);
codereview_java_data_6250
* cluster topology change (triggering data migration), the source may * miss and/or duplicate some entries. * <p> - * Default local parallelism for this processor is 2 (or less if less CPUs - * are available). */ @Nonnull public static <K, V> Source<Map.Entry<K, V>> cache(@Nonnull String cacheName) { "or less if less CPUs are available" sounds contrived given that there is only one choice. "Or 1 if there's just one CPU available" sounds more natural. * cluster topology change (triggering data migration), the source may * miss and/or duplicate some entries. * <p> + * The default local parallelism for this processor is 2 (or 1 if just 1 + * CPU is available). */ @Nonnull public static <K, V> Source<Map.Entry<K, V>> cache(@Nonnull String cacheName) {
codereview_java_data_6259
} /** - * Wither of the 1st element of this tuple. - * - * Note: The wither is NOT named {@code _1} due to possible ambiguity when using method reference (Tuple3::_1). * * @return a copy of this tuple with a new value for the 1st element of this Tuple. */ - public Tuple3<T1, T2, T3> w1(T1 t1) { - return new Tuple3<>(t1, _2, _3); } /** I don't like these abbreviations, why not `with1`, `with2` ... `with3` instead? } /** + * Sets the 1st element of this tuple to the given {@code value}. * * @return a copy of this tuple with a new value for the 1st element of this Tuple. */ + public Tuple3<T1, T2, T3> update1(T1 value) { + return new Tuple3<>(value, _2, _3); } /**
codereview_java_data_6287
startActivityForResult(intent, EDIT_REQUEST_CODE); } // Implements CustomTabActivityHelper.ConnectionCallback @Override public void onCustomTabsConnected() { Unsure what this is for, this request code isn't used. startActivityForResult(intent, EDIT_REQUEST_CODE); } + @OnClick(R.id.compare_product_button) + public void onCompareProductButtonClick() { + Intent intent = new Intent(getContext(), ProductComparisonActivity.class); + intent.putExtra("product_found", true); + ArrayList<Product> productsToCompare = new ArrayList<>(); + productsToCompare.add(product); + intent.putExtra("products_to_compare", productsToCompare); + startActivity(intent); + } + // Implements CustomTabActivityHelper.ConnectionCallback @Override public void onCustomTabsConnected() {
codereview_java_data_6291
} } } finally { - lockForErrorHandle.lock(); - sendFinishedFlag = true; - sendFinished.signalAll(); - lockForErrorHandle.unlock(); } } try lock finally unlock } } } finally { + try { + lockForErrorHandle.lock(); + sendFinishedFlag = true; + sendFinished.signalAll(); + }finally { + lockForErrorHandle.unlock(); + } } }
codereview_java_data_6295
if (tableRef instanceof SqlBasicCall && ((SqlBasicCall) tableRef).getOperator() instanceof SqlAsOperator) { SqlBasicCall basicCall = (SqlBasicCall) tableRef; - SqlAsOperator operator = (SqlAsOperator) ((SqlBasicCall) tableRef).getOperator(); - operator.unparse( - writer, basicCall, 0, 0, ignore -> writeKeywordAndPeriod(writer, snapshot)); } else { tableRef.unparse(writer, 0, 0); writeKeywordAndPeriod(writer, snapshot); There is no need to use the `SqlAsOperator#unparse`, just append the `AS table alias` in the last of the statement. if (tableRef instanceof SqlBasicCall && ((SqlBasicCall) tableRef).getOperator() instanceof SqlAsOperator) { SqlBasicCall basicCall = (SqlBasicCall) tableRef; + basicCall.operand(0).unparse(writer, 0, 0); + writer.setNeedWhitespace(true); + writeKeywordAndPeriod(writer, snapshot); + writer.keyword("AS"); + basicCall.operand(1).unparse(writer, 0, 0); } else { tableRef.unparse(writer, 0, 0); writeKeywordAndPeriod(writer, snapshot);
codereview_java_data_6299
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout; import com.wdullaer.materialdatetimepicker.time.TimePickerDialog; -import org.apache.commons.lang3.ObjectUtils; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; Where is this import needed? import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout; import com.wdullaer.materialdatetimepicker.time.TimePickerDialog; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger;
codereview_java_data_6303
return super.dispatchTouchEvent(event); } - private class GestureDetectorListener implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.d(TAG, "GestureDetecorListener:onFling() fired"); why not extend GestureDetector.SimpleOnGestureListener instead if you're only overriding a few methods? return super.dispatchTouchEvent(event); } + private class GestureDetectorListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.d(TAG, "GestureDetecorListener:onFling() fired");
codereview_java_data_6309
private static final String PANTHEON_PREFIX = "pantheon_"; private final Map<MetricCategory, Collection<Collector>> collectors = new ConcurrentHashMap<>(); - private static final Supplier<MetricsSystem> INSTANCE = - Suppliers.memoize(PrometheusMetricsSystem::init); - PrometheusMetricsSystem() {} - public static MetricsSystem instance() { - return INSTANCE.get(); - } - - private static MetricsSystem init() { final PrometheusMetricsSystem metricsSystem = new PrometheusMetricsSystem(); metricsSystem.collectors.put(MetricCategory.PROCESS, singleton(new StandardExports())); metricsSystem.collectors.put( I think this is wrong as it makes the metrics system JVM-wide whereas we want to be able to run two separate Pantheon instances in the same JVM and have them entirely isolated. private static final String PANTHEON_PREFIX = "pantheon_"; private final Map<MetricCategory, Collection<Collector>> collectors = new ConcurrentHashMap<>(); PrometheusMetricsSystem() {} + public static MetricsSystem init() { final PrometheusMetricsSystem metricsSystem = new PrometheusMetricsSystem(); metricsSystem.collectors.put(MetricCategory.PROCESS, singleton(new StandardExports())); metricsSystem.collectors.put(
codereview_java_data_6320
* @return an optional containing the instance of the registered factory, or empty if the factory * hasn't been registered. */ - Optional<KeyValueStorageFactory> getByName(final String name); } `final` modifier not needed on an interface * @return an optional containing the instance of the registered factory, or empty if the factory * hasn't been registered. */ + Optional<KeyValueStorageFactory> getByName(String name); }
codereview_java_data_6324
import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.name.Named; -import com.hubspot.singularity.SingularityTaskRequest; public class SingularityMesosModule extends AbstractModule { Are these unused imports? import com.google.inject.Scopes; import com.google.inject.Singleton; import com.google.inject.name.Named; public class SingularityMesosModule extends AbstractModule {
codereview_java_data_6326
} } - private void initializeRingtoneSummary(AdvancedRingtonePreference pref) { RingtoneSummaryListener listener = (RingtoneSummaryListener) pref.getOnPreferenceChangeListener(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); also i might be missing something, but do we need to typecast these to AdvancedRingtonePreference instead of leaving it as is? Seems like we don't need to modify this file. } } + private void initializeRingtoneSummary(RingtonePreference pref) { RingtoneSummaryListener listener = (RingtoneSummaryListener) pref.getOnPreferenceChangeListener(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
codereview_java_data_6332
try { listTable(Ample.DataLevel.ROOT, context); } catch (UnsupportedOperationException ex) { - // print nothing if no table name exists } System.out.println(); listTable(Ample.DataLevel.METADATA, context); Why are you suppressing the error here? You could just let the error be thrown, like the other calls to ```listTable``` try { listTable(Ample.DataLevel.ROOT, context); } catch (UnsupportedOperationException ex) { + System.out.println("\tNo volumes present"); } System.out.println(); listTable(Ample.DataLevel.METADATA, context);
codereview_java_data_6334
TSERV_SUMMARY_RETRIEVAL_THREADS("tserver.summary.retrieval.threads", "10", PropertyType.COUNT, "The number of threads on each tablet server available to retrieve" + " summary data, that is not currently in cache, from RFiles."), - TSERV_LASTLOCATION_UPDATE_TIME("tserver.lastlocation.update.time", "1000000", PropertyType.COUNT, - "The time in between tservers update last location of tablets."), - TSERV_LASTLOCATION_UPDATE_DELAY("tserver.lastlocation.update.delay", "30s", - PropertyType.TIMEDURATION, - "Time a tablet server will sleep between checking which tablets need an update for Last Location."), // accumulo garbage collector properties GC_PREFIX("gc.", null, PropertyType.PREFIX, Without looking at the code (and not being familiar with the particulars) - I find this description / value confusing. The property is named TIME, but you are using a PropertyType.COUNT. At first, I wondered why you didn't specify the time as 15m or 900s, or whatever human readable value. TSERV_SUMMARY_RETRIEVAL_THREADS("tserver.summary.retrieval.threads", "10", PropertyType.COUNT, "The number of threads on each tablet server available to retrieve" + " summary data, that is not currently in cache, from RFiles."), // accumulo garbage collector properties GC_PREFIX("gc.", null, PropertyType.PREFIX,
codereview_java_data_6349
/** * @return {@code true} if we should show remaining time or the duration */ - public static boolean getShowRemainTimeSetting() { return prefs.getBoolean(PREF_SHOW_TIME_LEFT, false); } UserPreferences currently does not send events. Could you please send it in the preferences fragment instead? /** * @return {@code true} if we should show remaining time or the duration */ + public static boolean shouldShowRemainingTime() { return prefs.getBoolean(PREF_SHOW_TIME_LEFT, false); }
codereview_java_data_6351
/** * ConfigInfo. * - * @author boyan - * @date 2010-5-4 */ public class ConfigInfo { Is this file copied from others? /** * ConfigInfo. * + * @author Nacos */ public class ConfigInfo {
codereview_java_data_6356
sb.append(", TVEPISODENUMBER VARCHAR2(").append(SIZE_TVEPISODENUMBER).append(')'); sb.append(", TVEPISODENAME VARCHAR2(").append(SIZE_MAX).append(')'); sb.append(", ISTVEPISODE BOOLEAN"); - sb.append(", EXTRAINFORMATION VARCHAR2(").append(SIZE_MAX).append("))"); sb.append(", actors VARCHAR2(").append(SIZE_MAX).append(')'); sb.append(", awards VARCHAR2(").append(SIZE_MAX).append(')'); @SubJunk one problem could be here. It closes the SQL request. sb.append(", TVEPISODENUMBER VARCHAR2(").append(SIZE_TVEPISODENUMBER).append(')'); sb.append(", TVEPISODENAME VARCHAR2(").append(SIZE_MAX).append(')'); sb.append(", ISTVEPISODE BOOLEAN"); + sb.append(", EXTRAINFORMATION VARCHAR2(").append(SIZE_MAX).append(")"); sb.append(", actors VARCHAR2(").append(SIZE_MAX).append(')'); sb.append(", awards VARCHAR2(").append(SIZE_MAX).append(')');
codereview_java_data_6366
import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; -import software.amazon.awssdk.transfer.s3.S3CrtResponseHandlerAdapter; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.http.SdkHttpUtils; nit: could just return the values instead of assigning import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.http.SdkHttpUtils;
codereview_java_data_6370
public static final AwsAdvancedClientOption<Boolean> ENABLE_DEFAULT_REGION_DETECTION = new AwsAdvancedClientOption<>(Boolean.class); - public static final AwsAdvancedClientOption<String> SIGNING_NAME = new AwsAdvancedClientOption<>(String.class); protected AwsAdvancedClientOption(Class<T> valueClass) { super(valueClass); Is there a more verbose name for this? SERVICE_SIGNING_NAME? public static final AwsAdvancedClientOption<Boolean> ENABLE_DEFAULT_REGION_DETECTION = new AwsAdvancedClientOption<>(Boolean.class); + public static final AwsAdvancedClientOption<String> SERVICE_SIGNING_NAME = new AwsAdvancedClientOption<>(String.class); protected AwsAdvancedClientOption(Class<T> valueClass) { super(valueClass);
codereview_java_data_6373
} if (requestsCache.isEnabled()) { - List<SingularityRequestWithState> requests = requestsCache.get("all"); - if (requests != null) { return requests; } } I wonder if we should just not use the web cache here if this is the case. Seems overkill to have the leaderCache -> web cache -> zk cache all here. Lots of duplicate memory usage to store it all 3 times } if (requestsCache.isEnabled()) { + List<SingularityRequestWithState> requests = new ArrayList<>( + (requestsCache.getAll()).values() + ); + if (requests.isEmpty()) { return requests; } }
codereview_java_data_6386
this.id = id; } else { // otherwise assign the remote host as id. - this.id = id = "http://" + remoteHost.getHost() + ":" + remoteHost.getPort(); } maxConcurrentSession = getConfigInteger(RegistrationRequest.MAX_SESSION); any reason you're assigning to the local variable 'id' too? this.id = id; } else { // otherwise assign the remote host as id. + this.id = "http://" + remoteHost.getHost() + ":" + remoteHost.getPort(); } maxConcurrentSession = getConfigInteger(RegistrationRequest.MAX_SESSION);
codereview_java_data_6391
} else { editor.putInt(Prefs.UPLOADS_SHOWING, value); editor.putBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED,true); - uploadLimit.setSummary(newValue.toString()); } editor.apply(); return true; While user sets upload limit to empty string, this patch set it to default value which is 100. However summary of uploadLimit field remains empty (users expectation is to see value 100 there). There should be an if-else condition to write 100 while newValue is non-number string. } else { editor.putInt(Prefs.UPLOADS_SHOWING, value); editor.putBoolean(Prefs.IS_CONTRIBUTION_COUNT_CHANGED,true); + uploadLimit.setSummary(String.valueOf(value)); } editor.apply(); return true;
codereview_java_data_6406
import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; -import org.openqa.selenium.SessionNotCreatedException; import org.openqa.selenium.grid.distributor.Distributor; -import org.openqa.selenium.grid.sessionmap.SessionMap; import org.openqa.selenium.internal.Require; import java.net.URI; You can safely revert changes to this file. import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; import org.openqa.selenium.grid.distributor.Distributor; import org.openqa.selenium.internal.Require; import java.net.URI;
codereview_java_data_6418
@ApiOperation("Retrieve the list of logs stored in S3 for a specific task.") public List<SingularityS3Log> getS3LogsForTask( @ApiParam("The task ID to search for") @PathParam("taskId") String taskId, - @ApiParam("Start timestamp (millis, 13 digit)") @QueryParam("start") long start, - @ApiParam("End timestamp (mills, 13 digit)") @QueryParam("end") long end) throws Exception { checkS3(); SingularityTaskId taskIdObject = getTaskIdObject(taskId); Can they not be optional in here? @ApiOperation("Retrieve the list of logs stored in S3 for a specific task.") public List<SingularityS3Log> getS3LogsForTask( @ApiParam("The task ID to search for") @PathParam("taskId") String taskId, + @ApiParam("Start timestamp (millis, 13 digit)") @QueryParam("start") Optional<Long> start, + @ApiParam("End timestamp (mills, 13 digit)") @QueryParam("end") Optional<Long> end) throws Exception { checkS3(); SingularityTaskId taskIdObject = getTaskIdObject(taskId);
codereview_java_data_6429
} @Override - public void peerAdded(final PeerConnection newConnection) { final Address peerAddress = newConnection.getPeer().getAddress(); peerConnections.put(peerAddress, newConnection); } @Override - public void peerRemoved(final PeerConnection removedConnection) { final Address peerAddress = removedConnection.getPeer().getAddress(); peerConnections.remove(peerAddress); } I like the rename to `blacklist` } @Override + public void add(final PeerConnection newConnection) { final Address peerAddress = newConnection.getPeer().getAddress(); peerConnections.put(peerAddress, newConnection); } @Override + public void remove(final PeerConnection removedConnection) { final Address peerAddress = removedConnection.getPeer().getAddress(); peerConnections.remove(peerAddress); }
codereview_java_data_6430
Field[] fields = proxyIn.getDeclaredFields(); for (Field field : fields) { int modifiers = field.getModifiers(); - if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers)) continue; Object value = decorator.decorate(page.getClass().getClassLoader(), field); if (value != null) { curly brackets would be good here as well Field[] fields = proxyIn.getDeclaredFields(); for (Field field : fields) { int modifiers = field.getModifiers(); + if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers)) { continue; + } Object value = decorator.decorate(page.getClass().getClassLoader(), field); if (value != null) {
codereview_java_data_6434
domainTemplate.setTemplateNames(domainTemplateListMap.get(domainName)); //Passing null context since it is an internal call during app start up //executePutDomainTemplate can bulk apply templates given a domain hence sending domainName and templatelist - this.executePutDomainTemplate(null, domainName, domainTemplate, auditRef, caller); } return domainTemplateListMap; } this call should be protected such that if any exception is thrown, we don't stop the process but rather just swallow it and let it continue with the rest of domains. domainTemplate.setTemplateNames(domainTemplateListMap.get(domainName)); //Passing null context since it is an internal call during app start up //executePutDomainTemplate can bulk apply templates given a domain hence sending domainName and templatelist + try { + this.executePutDomainTemplate(null, domainName, domainTemplate, auditRef, caller); + } catch (Exception ex) { + LOG.error("unable to apply template for domain {} and template {} error: {}", domainName, domainTemplate, ex.getMessage()); + continue; + } } return domainTemplateListMap; }
codereview_java_data_6439
// Overrides the table's read.split.open-file-cost public static final String FILE_OPEN_COST = "file-open-cost"; } There are also more read options. Why not include all of them? // Overrides the table's read.split.open-file-cost public static final String FILE_OPEN_COST = "file-open-cost"; + + // Overrides the table's read.split.open-file-cost + public static final String VECTORIZATION_ENABLED = "vectorization-enabled"; + + // Overrides the table's read.parquet.vectorization.batch-size + public static final String VECTORIZATION_BATCH_SIZE = "batch-size"; }
codereview_java_data_6447
static abstract class Factory extends DeduplicatingVoidCallFactory<Input> { final Session session; - // Shared across all threads as updates can come from any thread. - final Map<Entry<String, Long>, Pair> sharedState; final String table; final int bucketCount; final PreparedStatement preparedStatement; in reality this might not be possible to merge, as the data is used for different purposes. For example, here it is used to determine if an existing range will be extended.. not if an exact call was made prior. As the main next goal is getting rid of guava, the follow-up PR may not actually merge these features into DelayLimiter, rather make a similar bounded expire-after-write map. static abstract class Factory extends DeduplicatingVoidCallFactory<Input> { final Session session; + /** + * This ensures we only attempt to write rows that would extend the timestamp range of a trace + * index query. This is shared singleton as inserts can come from any thread. + */ + final Map<Entry<String, Long>, Pair> partitionKeyAndTraceIdToTimestampRange; final String table; final int bucketCount; final PreparedStatement preparedStatement;
codereview_java_data_6450
List<String> types= new ArrayList<>(); types.add(Proxy.Type.DIRECT.name()); types.add(Proxy.Type.HTTP.name()); - - if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ types.add(Proxy.Type.SOCKS.name()); } - ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, types); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Please add a space between `)` and `{` List<String> types= new ArrayList<>(); types.add(Proxy.Type.DIRECT.name()); types.add(Proxy.Type.HTTP.name()); + if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { types.add(Proxy.Type.SOCKS.name()); } ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, types); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
codereview_java_data_6464
protected static final String ICEBERG_METADATA_FOLDER = "metadata"; protected static final List<String> EXCLUDED_PROPERTIES = ImmutableList.of("path", "transient_lastDdlTime", "serialization.format"); - private AtomicInteger counter = new AtomicInteger(); private final SparkSession spark; nit: This seems redundant. protected static final String ICEBERG_METADATA_FOLDER = "metadata"; protected static final List<String> EXCLUDED_PROPERTIES = ImmutableList.of("path", "transient_lastDdlTime", "serialization.format"); private final SparkSession spark;
codereview_java_data_6465
return nameAllocator; } - public synchronized CryptoService getCryptoService() { if (cryptoService == null) { throw new CryptoService.CryptoException("Crypto service not initialized."); } not sure if this needs to be synchronized return nameAllocator; } + public CryptoService getCryptoService() { if (cryptoService == null) { throw new CryptoService.CryptoException("Crypto service not initialized."); }
codereview_java_data_6483
OutputFile encryptingOutputFile(); /** - * Metadata about the encryption keys and other crypto parameters used to encrypt the associated * {@link #encryptingOutputFile()}. */ EncryptionKeyMetadata keyMetadata(); - - /** - * Parameters of native encryption (if used for this file) - */ - default NativeFileCryptoParameters nativeEncryptionParameters() { - return null; - } } Can we reuse `keyMetadata ` instead of introducing `nativeEncryptionParameters `? Here are reasons: 1. Both `keyMetadata` and `nativeEncryptionParameters` are used for keys and crypto parameters. 2. Each file will have either one, not both. It depends whether streaming encryption or native encryption is used for this file. NativeFileCryptoParameters can implement interface `EncryptionKeyMetadata` in that sense. OutputFile encryptingOutputFile(); /** + * Metadata about the encryption key that is being used to encrypt the associated * {@link #encryptingOutputFile()}. */ EncryptionKeyMetadata keyMetadata(); }
codereview_java_data_6484
sendResponse(null); } } else { - LogUtil.CLIENT_LOG.warn("client subsciber's relations delete fail."); } } catch (Throwable t) { LogUtil.DEFAULT_LOG.error("long polling error:" + t.getMessage(), t.getCause()); add this log to default log sendResponse(null); } } else { + LogUtil.DEFAULT_LOG.warn("client subsciber's relations delete fail."); } } catch (Throwable t) { LogUtil.DEFAULT_LOG.error("long polling error:" + t.getMessage(), t.getCause());
codereview_java_data_6485
@Override public void execute(final String[] args) throws Exception { - System.out.println("WARNING: External compaction processes are experimental"); CompactionCoordinator.main(args); } System.err or using the logger might be better for these. @Override public void execute(final String[] args) throws Exception { + System.err.println("WARNING: External compaction processes are experimental"); CompactionCoordinator.main(args); }
codereview_java_data_6487
public static final String STRING = "STRING"; public static final String SUBSTITUTION = "SUBSTITUTION"; public static final String UNIFICATION = "UNIFICATION"; - public static final String JSON = "JSON"; - public static final Set<String> namespaces = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(ARRAY, BOOL, BUFFER, BYTES, FFI, FLOAT, INT, IO, KEQUAL, KREFLECTION, LIST, MAP, MINT, SET, STRING, SUBSTITUTION, UNIFICATION, JSON))); } This PR doesn't seem to add anything for JSON parsing handling, should we wait for the JSON module to add this? public static final String STRING = "STRING"; public static final String SUBSTITUTION = "SUBSTITUTION"; public static final String UNIFICATION = "UNIFICATION"; + public static final Set<String> namespaces = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(ARRAY, BOOL, BUFFER, BYTES, FFI, FLOAT, INT, IO, KEQUAL, KREFLECTION, LIST, MAP, MINT, SET, STRING, SUBSTITUTION, UNIFICATION))); }
codereview_java_data_6495
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Arrays; -import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; Would a Map<Integer,StorageProviderFunction> work better in the event that version numbers are non-consecutive? For example if we drop support for a specific experimental version? import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Map; +import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
codereview_java_data_6500
@Override public NacosAsyncRestTemplate createNacosAsyncRestTemplate() { final HttpClientConfig originalRequestConfig = buildHttpClientConfig(); - final RequestConfig requestConfig = getRequestConfig(); - final IOReactorConfig ioReactorConfig = getIoReactorConfig(); return new NacosAsyncRestTemplate(assignLogger(), new DefaultAsyncHttpClientRequest( HttpAsyncClients.custom() .addInterceptorLast(new RequestContent(true)) - .setDefaultIOReactorConfig(ioReactorConfig) - .setDefaultRequestConfig(requestConfig) .setMaxConnTotal(originalRequestConfig.getMaxConnTotal()) .setMaxConnPerRoute(originalRequestConfig.getMaxConnPerRoute()) .setUserAgent(originalRequestConfig.getUserAgent()).build())); use getIoReactorConfig directly, no need to use attribute. @Override public NacosAsyncRestTemplate createNacosAsyncRestTemplate() { final HttpClientConfig originalRequestConfig = buildHttpClientConfig(); return new NacosAsyncRestTemplate(assignLogger(), new DefaultAsyncHttpClientRequest( HttpAsyncClients.custom() .addInterceptorLast(new RequestContent(true)) + .setDefaultIOReactorConfig(getIoReactorConfig()) + .setDefaultRequestConfig(getRequestConfig()) .setMaxConnTotal(originalRequestConfig.getMaxConnTotal()) .setMaxConnPerRoute(originalRequestConfig.getMaxConnPerRoute()) .setUserAgent(originalRequestConfig.getUserAgent()).build()));
codereview_java_data_6503
fileStatuses = fs.listStatus(metadataLocation, path -> path.getName().endsWith(TableMetadataParser.fileSuffix())); } catch (IOException e) { - LOG.warn("Unable to list table metadata files", e); - return ImmutableList.of(); } return Stream.of(fileStatuses) .map(FileStatus::getPath) .map(path -> new BaseTableMetadataFile( io().newInputFile(path.toString()), parseVersion(path))) - .filter(file -> file.version() != -1) .collect(Collectors.toList()); } nit: I realize that this is only for cleanup but does it make sense that we throw a runtimeIO exception here and let callers handle it on their own? fileStatuses = fs.listStatus(metadataLocation, path -> path.getName().endsWith(TableMetadataParser.fileSuffix())); } catch (IOException e) { + throw new RuntimeIOException("Unable to list table metadata files", e); } return Stream.of(fileStatuses) .map(FileStatus::getPath) .map(path -> new BaseTableMetadataFile( io().newInputFile(path.toString()), parseVersion(path))) .collect(Collectors.toList()); }
codereview_java_data_6509
.deleteFile(FILE_DAY_2) .addFile(FILE_DAY_2_MODIFIED) .validateFromSnapshot(baseSnapshot.snapshotId()) - .validateNoConflictingAppends(EXPRESSION_DAY_2) .commit(); validateTableFiles(table, FILE_DAY_1, FILE_DAY_2_MODIFIED); I think `validateNoConflictingAppends` has been deprecated as well. We should use `conflictDetectionFilter` and `validateNoConflictingData`. .deleteFile(FILE_DAY_2) .addFile(FILE_DAY_2_MODIFIED) .validateFromSnapshot(baseSnapshot.snapshotId()) + .conflictDetectionFilter(EXPRESSION_DAY_2) + .validateNoConflictingData() .commit(); validateTableFiles(table, FILE_DAY_1, FILE_DAY_2_MODIFIED);
codereview_java_data_6510
+ expr.getExpressionString() + "'", e); } } - - public static Mono<Boolean> evaluateAsMonoBoolean(Expression expr, EvaluationContext ctx) { - try { - return (Mono<Boolean>) expr.getValue(ctx, Mono.class); - } - catch (EvaluationException e) { - throw new IllegalArgumentException("Failed to evaluate expression '" - + expr.getExpressionString() + "'", e); - } - } } Adding a Reactive return type to a class used by non-reactive applications can potentially break non-reactive applications since depending on the JDK it may load all method definitions as it loads the class. In general, optional dependencies must be placed in distinct classes. + expr.getExpressionString() + "'", e); } } }
codereview_java_data_6514
@Override public synchronized void provideDynamicMetrics(MetricDescriptor descriptor, MetricsCollectionContext context) { - if (bytes > 0) { - context.collect(descriptor, SNAPSHOT_BYTES, ProbeLevel.INFO, ProbeUnit.COUNT, bytes); - context.collect(descriptor, SNAPSHOT_KEYS, ProbeLevel.INFO, ProbeUnit.COUNT, keys); - } } } I don't think we need the conditional logic here. It'll be confusing if metric is sometimes missing and sometimes not. @Override public synchronized void provideDynamicMetrics(MetricDescriptor descriptor, MetricsCollectionContext context) { + context.collect(descriptor, SNAPSHOT_BYTES, ProbeLevel.INFO, ProbeUnit.COUNT, bytes); + context.collect(descriptor, SNAPSHOT_KEYS, ProbeLevel.INFO, ProbeUnit.COUNT, keys); } }
codereview_java_data_6515
import org.apache.accumulo.shell.Shell; import org.apache.accumulo.shell.Shell.Command; import org.apache.commons.cli.CommandLine; public class ImportDirectoryCommand extends Command { I think `OptUtil.getTableOpt()` is supposed to do most of this logic. As in: ```java String tableName = OptUtil.getTableOpt(cl, shellState); ``` Either way, you also need to declare it as an option in the `getOptions` method, something like: ```java @Override public Options getOptions() { Options o = new Options(); o.addOption(OptUtil.tableOpt("name of the table to import files into")); return o; } ``` import org.apache.accumulo.shell.Shell; import org.apache.accumulo.shell.Shell.Command; import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.Options; public class ImportDirectoryCommand extends Command {
codereview_java_data_6521
* @return <tt>true</tt>, if one address belongs to a contact. * <tt>false</tt>, otherwise. */ - public boolean containsContact(final Address[] addresses) { if (addresses == null) { return false; } This does almost exactly the same as `isInContacts`, I would suggest a more similar name like `isAnyInContacts`. Could also make it a single method using a variadic signature. Furthermore, this is quite the expensive method - it's one contacts provider query per email address. This could be collapsed into a single query, and even then it might be a good idea to add an @WorkerThread annotation to discourage its use on the ui thread in the future. * @return <tt>true</tt>, if one address belongs to a contact. * <tt>false</tt>, otherwise. */ + public boolean isAnyInContacts(final Address[] addresses) { if (addresses == null) { return false; }
codereview_java_data_6522
throw new UnknownFormatException("Unable to read image format", e); } - if (inputResult.bufferedImage == null) { // ImageIO doesn't support the image format throw new UnknownFormatException("Failed to transform image because the source format is unknown"); } Why don't we need to check for that? throw new UnknownFormatException("Unable to read image format", e); } + if (inputResult.bufferedImage == null || inputResult.imageFormat == null) { // ImageIO doesn't support the image format throw new UnknownFormatException("Failed to transform image because the source format is unknown"); }
codereview_java_data_6525
} @Test - public void setNodeWhiteListPassingNull() { final PermissioningConfiguration configuration = PermissioningConfiguration.createDefault(); configuration.setNodeWhitelist(null); assertThat(configuration.getNodeWhitelist()).isEmpty(); Should we be more descriptive in the test name? } @Test + public void setNodeWhiteListPassingNullShouldNotChangeWhitelistSetFlag() { final PermissioningConfiguration configuration = PermissioningConfiguration.createDefault(); configuration.setNodeWhitelist(null); assertThat(configuration.getNodeWhitelist()).isEmpty();