auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<Object[]> getDvObjectInfoForMyData(List<Long> dvObjectIdList){ //msgt("getAssigneeAndRoleIdListFor"); String dvObjectClause = getDvObjectIdListClause(dvObjectIdList); if (dvObjectClause==null){ return null; } String qstr = "SELECT dv.id, dv.dtype, dv.owner_id"; // dv.modificationtime, qstr += " FROM dvobject dv"; qstr += " WHERE dv.id IN " + dvObjectClause; qstr += ";"; START return em.createNativeQuery(qstr, Object[].class).getResultList(); END } Isn't this the default return type?

Target:
public List<Object[]> getDvObjectInfoForMyData(List<Long> dvObjectIdList){ //msgt("getAssigneeAndRoleIdListFor"); String dvObjectClause = getDvObjectIdListClause(dvObjectIdList); if (dvObjectClause==null){ return null; } String qstr = "SELECT dv.id, dv.dtype, dv.owner_id"; // dv.modificationtime, qstr += " FROM dvobject dv"; qstr += " WHERE dv.id IN " + dvObjectClause; qstr += ";"; return em.createNativeQuery(qstr).getResultList(); }
Source:
public String init() { START System.out.println("_YE_OLDE_QUERY_COUNTER_"); // for debug purposes END if ((session.getUser() != null) && (session.getUser().isAuthenticated()) && (session.getUser().isSuperuser())) { authUser = (AuthenticatedUser) session.getUser(); userListMaker = new UserListMaker(userService); runUserSearch(); } else { return permissionsWrapper.notAuthorized(); // redirect to login OR give some type ‘you must be logged in message' } return null; } cruft removed

Target:
public String init() { if ((session.getUser() != null) && (session.getUser().isAuthenticated()) && (session.getUser().isSuperuser())) { authUser = (AuthenticatedUser) session.getUser(); userListMaker = new UserListMaker(userService); runUserSearch(); } else { return permissionsWrapper.notAuthorized(); // redirect to login OR give some type ‘you must be logged in message' } return null; }
Source:
public Long getTotalUserCount(){ return getUserCount(null); START } END As getUserCount immediate checks for null and changes it, why not pass an empty string instead?

Target:
public Long getTotalUserCount(){ return getUserCount(""); }
Source:
void idIsGeneratedUUID() { class Entity { @GeneratedValue(strategy = GenerationStrategy.UNIQUE) @Id UUID id; } Entity entity = new Entity(); CouchbaseDocument converted = new CouchbaseDocument(); converter.write(entity, converted); assertThat(converted.getId()).isEqualTo(entity.id.toString()); START System.out.println(entity.id); END } Looks like there are leftover printlns in addition to the assertions?

Target:
void idIsGeneratedUUID() { class Entity { @GeneratedValue(strategy = GenerationStrategy.UNIQUE) @Id UUID id; } Entity entity = new Entity(); CouchbaseDocument converted = new CouchbaseDocument(); converter.write(entity, converted); assertThat(converted.getId()).isEqualTo(entity.id.toString()); }
Source:
public T one(final String id) { try { return reactiveSupport.one(id).block(); } catch(DocumentNotFoundException dnfe){ START dnfe.printStackTrace(); END return null; } } this is a leftover I assume?

Target:
public T one(final String id) { return reactiveSupport.one(id).block(); }
Source:
public JsonValue getParameters() { START return parameters; END } I think it could be benefitial to have two overloads (jsonObject, jsonarray), very similar to what the sdk has

Target:
JsonValue getParameters() { return parameters; }
Source:
private Boolean executeRequest(URIBuilder builder) throws Exception { try { HttpGet request = new HttpGet(builder.build()); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); START if (status < 200 || status > 300) { END return false; } return true; } catch (Exception ex) { Thread.sleep(1000); throw ex; } } What if status is 300? Should the check be`status >= 300` ?

Target:
private Boolean executeRequest(URIBuilder builder) throws Exception { try { HttpGet request = new HttpGet(builder.build()); HttpClient client = HttpClientBuilder.create().build(); HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status < 200 || status >= 300) { return false; } return true; } catch (Exception ex) { Thread.sleep(1000); throw ex; } }
Source:
START public KeySettings delimiter(String delimiter) { END this.delimiter = delimiter; return this; } should probably test for `null` delimiter and either ignore or preferably interpret null as "no delimiter" (the empty `String`)

Target:
public KeySettings delimiter(String delimiter) { if (delimiter == null) { return this; } this.delimiter = delimiter; return this; }
Source:
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf payloadAndCrc = (ByteBuf) super.decode(ctx, in); assert header != null; if (payloadAndCrc == null) { START return null; END } else { Segment segment = segmentCodec.decode(header, payloadAndCrc); header = null; return segment; } } ```suggestion header = null; return null; ``` I think you need to also null out the header here in cases where the input buffer doesn't have enough readable bytes to decode the full payload. As it is, the next time `super.decode` is called it hits the assertion in `getUnadjustedFrameLength`

Target:
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { try { ByteBuf payloadAndCrc = (ByteBuf) super.decode(ctx, in); if (payloadAndCrc == null) { return null; } else { assert header != null; Segment segment = segmentCodec.decode(header, payloadAndCrc); header = null; return segment; } } catch (Exception e) { // Don't hold on to a stale header if we failed to decode the rest of the segment header = null; throw e; } }
Source:
private Optional<Long> gettimeofdayImpl(POSIX posix) { Timeval tv = posix.allocateTimeval(); int rv = posix.gettimeofday(tv); if (rv != 0) { START LOG.info("Expected 0 return value from gettimeofday(), observed " + rv); END return Optional.empty(); } return Optional.of(tv.sec() * 1_000_000 + tv.usec()); } `Log.debug` maybe?

Target:
private Optional<Long> gettimeofdayImpl(POSIX posix) { Timeval tv = posix.allocateTimeval(); int rv = posix.gettimeofday(tv); if (rv != 0) { LOG.debug("Expected 0 return value from gettimeofday(), observed " + rv); return Optional.empty(); } return Optional.of(tv.sec() * 1_000_000 + tv.usec()); }
Source:
START public static String getCpu() { END return CPU.name().toLowerCase(LOCALE); } Since this is class is becoming a shell that delegates all of its operations to a `NativeImpl` instance, wouldn't it be a better design to also include `getCpu()` in `NativeImpl`?

Target:
public static String getCpu() { return CPU.toString(); }
Source:
public boolean equals(Object o) { START if (this == o) return true; END if (!(o instanceof ReplicationFactor)) return false; ReplicationFactor that = (ReplicationFactor) o; return allReplicas == that.allReplicas && fullReplicas == that.fullReplicas; } missing braces

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ReplicationFactor)) { return false; } ReplicationFactor that = (ReplicationFactor) o; return allReplicas == that.allReplicas && fullReplicas == that.fullReplicas; }
Source:
public MappingCodec( @NonNull TypeCodec<InnerT> innerCodec, @NonNull GenericType<OuterT> outerJavaType) { START this.innerCodec = Objects.requireNonNull(innerCodec, "innerCodec cannot be null"); END this.outerJavaType = Objects.requireNonNull(outerJavaType, "outerJavaType cannot be null"); } nit: maybe make this constructor protected (although I don't see any real issue with it being public)

Target:
protected MappingCodec( @NonNull TypeCodec<InnerT> innerCodec, @NonNull GenericType<OuterT> outerJavaType) { this.innerCodec = Objects.requireNonNull(innerCodec, "innerCodec cannot be null"); this.outerJavaType = Objects.requireNonNull(outerJavaType, "outerJavaType cannot be null"); }
Source:
START public static void maybeCreateSchema(CqlSession session) throws Exception { END session.execute( SimpleStatement.newInstance( "CREATE KEYSPACE IF NOT EXISTS killrvideo WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}") .setExecutionProfileName("slow")); session.execute("USE killrvideo"); for (String statement : getStatements("killrvideo_schema.cql")) { session.execute(SimpleStatement.newInstance(statement).setExecutionProfileName("slow")); } } Can be private

Target:
private static void maybeCreateSchema(CqlSession session) throws Exception { session.execute( SimpleStatement.newInstance( "CREATE KEYSPACE IF NOT EXISTS killrvideo WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}") .setExecutionProfileName("slow")); session.execute("USE killrvideo"); for (String statement : getStatements("killrvideo_schema.cql")) { session.execute(SimpleStatement.newInstance(statement).setExecutionProfileName("slow")); } }
Source:
START boolean nullSavingStrategyExplicitlySet(Element methodElement, Class<?> javaClass) { END Optional<AnnotationMirror> annotationMirrorForJavaClass = getAnnotationMirrorForJavaClass(methodElement, javaClass); // Find out if NullSavingStrategy was set explicitly if (annotationMirrorForJavaClass.isPresent()) { for (ExecutableElement executableElement : annotationMirrorForJavaClass.get().getElementValues().keySet()) { if (executableElement.getSimpleName().contentEquals("nullSavingStrategy")) { return true; } } } return false; } If we were to remove `default NullSavingStrategy.DO_NOT_SET` from all annotations so they are null instead couldn't this be more effective as all you would have to do is null check?

Target:
private boolean nullSavingStrategyExplicitlySet(Element methodElement, Class<?> javaClass) { Optional<AnnotationMirror> annotationMirrorForJavaClass = getAnnotationMirrorForJavaClass(methodElement, javaClass); // Find out if NullSavingStrategy was set explicitly if (annotationMirrorForJavaClass.isPresent()) { for (ExecutableElement executableElement : annotationMirrorForJavaClass.get().getElementValues().keySet()) { if (executableElement.getSimpleName().contentEquals("nullSavingStrategy")) { return true; } } } return false; }
Source:
public static void setValue( CodeBlock cqlName, PropertyType type, CodeBlock valueExtractor, String targetName, MethodSpec.Builder methodBuilder, BindableHandlingSharedCode enclosingClass) { // invoke with SET_TO_NULL to preserve default behaviour when retrieving an entity setValue( cqlName, type, valueExtractor, targetName, methodBuilder, enclosingClass, START CodeBlock.of("$T.$L", NullSavingStrategy.class, NullSavingStrategy.SET_TO_NULL)); END } Its an interesting decision point because it's possible that fields may be initialized with some non-null value in their default constructors. However, conceptually, I think what you are doing is the right thing here. If the value is unset in C*, it should be effectively null in the entity itself.

Target:
public static void setValue( CodeBlock cqlName, PropertyType type, CodeBlock valueExtractor, String targetName, MethodSpec.Builder methodBuilder, BindableHandlingSharedCode enclosingClass) { setValue(cqlName, type, valueExtractor, targetName, methodBuilder, enclosingClass, false); }
Source:
public String addQueryProvider( ExecutableElement methodElement, TypeMirror providerClass, List<ClassName> entityHelperTypes) { // Invokers are not shared between methods, so always generate a new name START String fieldName = nameIndex.uniqueField(methodElement.getSimpleName().toString() + "Invoker"); END List<String> entityHelperNames = new ArrayList<>(); for (ClassName type : entityHelperTypes) { entityHelperNames.add(addEntityHelperField(type)); } queryProviders.add( new GeneratedQueryProvider(methodElement, fieldName, providerClass, entityHelperNames)); return fieldName; } Nice, i was wondering if this would work for overloaded methods and it appears it does (i.e. `findSliceInvoker1` is defined if a previous `findSliceInvoker` exists.

Target:
public String addQueryProvider( ExecutableElement methodElement, TypeMirror providerClass, List<ClassName> entityHelperTypes) { // Invokers are not shared between methods, so always generate a new name String fieldName = nameIndex.uniqueField(methodElement.getSimpleName().toString() + "Invoker"); List<String> entityHelperNames = new ArrayList<>(); for (ClassName type : entityHelperTypes) { entityHelperNames.add(addEntityHelperField(type)); } queryProviders.add(new GeneratedQueryProvider(fieldName, providerClass, entityHelperNames)); return fieldName; }
Source:
private CqlNameGenerator(NamingConvention namingConvention, TypeMirror converterClassMirror) { START Preconditions.checkArgument(namingConvention == null ^ converterClassMirror == null); END this.namingConvention = namingConvention; this.converterClassMirror = converterClassMirror; } If this check fails will it be converted to easy to read the message? I am assuming that not every client will know the meaning of using `^` in this part of the code and if this will propagate to exception message he maybe confused

Target:
private CqlNameGenerator(NamingConvention namingConvention, TypeMirror converterClassMirror) { assert namingConvention == null ^ converterClassMirror == null; this.namingConvention = namingConvention; this.converterClassMirror = converterClassMirror; }
Source:
public SimpleStatementBuilder builder() { START return SimpleStatement.builder(asCql()).setIdempotence(IS_IDEMPOTENT); END } Please don't use a constant here. `setIdempotence(true)` is perfectly clear, and it's not like we might decide to use "false" to mean "idempotent" at any point in the future.

Target:
public SimpleStatementBuilder builder() { return SimpleStatement.builder(asCql()).setIdempotence(true); }
Source:
public ByteBuffer encode(@Nullable T value, @NonNull ProtocolVersion protocolVersion) { if (value == null) return null; try { return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value)); } catch (JsonProcessingException e) { START throw new InvalidTypeException(e.getMessage(), e); END } } As I said in #1208 : In driver 4.0 we don't have any specific exception for codecs except `CodecNotFoundException`. When a codec cannot serialize or deserialize something, we use `IllegalArgumentException`. I don't think you need to introduce a special exception in these examples.

Target:
public ByteBuffer encode(@Nullable T value, @NonNull ProtocolVersion protocolVersion) { if (value == null) { return null; } try { return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value)); } catch (JsonProcessingException e) { throw new IllegalArgumentException(e.getMessage(), e); } }
Source:
public T parse(String value) { START if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) return null; END if (!Strings.isQuoted(value)) throw new IllegalArgumentException("JSON strings must be enclosed by single quotes"); String json = Strings.unquote(value); try { return (T) objectMapper.readValue(json, toJacksonJavaType()); } catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); } } In driver 4 the contribution guidelines mandate that if/for/while blocks must be enclosed with braces. Same thing for the line below.

Target:
public T parse(String value) { if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL")) { return null; } if (!Strings.isQuoted(value)) { throw new IllegalArgumentException("JSON strings must be enclosed by single quotes"); } String json = Strings.unquote(value); try { return (T) objectMapper.readValue(json, toJacksonJavaType()); } catch (IOException e) { throw new IllegalArgumentException(e.getMessage(), e); } }
Source:
private boolean isAuthFailure(Throwable error) { boolean authFailure = true; if (error instanceof AllNodesFailedException) { START Collection<Throwable> errors = ((AllNodesFailedException) error).getErrors().values(); END for (Throwable nodeError : errors) { if (!(nodeError instanceof AuthenticationException)) { authFailure = false; break; } } } return authFailure; } if `getErrors()` will return empty connection we will treat it as the `AuthFailure`. Is it ok for us? Is it possible?

Target:
private boolean isAuthFailure(Throwable error) { boolean authFailure = true; if (error instanceof AllNodesFailedException) { Collection<Throwable> errors = ((AllNodesFailedException) error).getErrors().values(); if (errors.size() == 0) { return false; } for (Throwable nodeError : errors) { if (!(nodeError instanceof AuthenticationException)) { authFailure = false; break; } } } return authFailure; }
Source:
private boolean isFullyFetched() { START return currentPage.hasMorePages(); END } Should be `!currentPage.hasMorePages()`.

Target:
private boolean isFullyFetched() { return !currentPage.hasMorePages(); }
Source:
public BatchStatement build() { return new DefaultBatchStatement( batchType, statementsBuilder.build(), executionProfileName, executionProfile, keyspace, routingKeyspace, routingKey, routingToken, buildCustomPayload(), idempotent, tracing, timestamp, pagingState, pageSize, consistencyLevel, serialConsistencyLevel, timeout, START null); END } The last argument should be `node` (inherited from the parent builder) instead of `null`.

Target:
public BatchStatement build() { return new DefaultBatchStatement( batchType, statementsBuilder.build(), executionProfileName, executionProfile, keyspace, routingKeyspace, routingKey, routingToken, buildCustomPayload(), idempotent, tracing, timestamp, pagingState, pageSize, consistencyLevel, serialConsistencyLevel, timeout, node); }
Source:
private Builder() { try { this.configDirectory = Files.createTempDirectory("ccm"); } catch (IOException e) { // change to unchecked for now. throw new RuntimeException(e); } // disable auto_snapshot by default to reduce disk usage when destroying schema. withCassandraConfiguration("auto_snapshot", "false"); // mark the ccm temp directories for deletion when the JVM exits if (this.configDirectory != null) { START this.configDirectory.toFile().deleteOnExit(); END } } Are we sure this directory will be empty? If not, I suggest doing the following instead: ``` Runtime.getRuntime() .addShutdownHook( new Thread( () -> { try (Stream<Path> walk = Files.walk(configDirectory)) { walk.sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } catch (IOException e) { logger.error("Could not walk " + configDirectory, e); } })); ```

Target:
private Builder() { try { this.configDirectory = Files.createTempDirectory("ccm"); // mark the ccm temp directories for deletion when the JVM exits this.configDirectory.toFile().deleteOnExit(); } catch (IOException e) { // change to unchecked for now. throw new RuntimeException(e); } // disable auto_snapshot by default to reduce disk usage when destroying schema. withCassandraConfiguration("auto_snapshot", "false"); }
Source:
private static File createTempStore(String storePath) { File f = null; try (OutputStream os = new FileOutputStream(f = File.createTempFile("server", ".store"))) { Resources.copy(CcmBridge.class.getResource(storePath), os); } catch (IOException e) { logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e); START } finally { END // ensure the temp store files are deleted when the JVM exits if (f != null) { f.deleteOnExit(); } } return f; } Imo this could be simplified to just `f.deleteOnExit();` placed right after the try block start, since `f` cannot be null at that point. But this way is OK too.

Target:
private static File createTempStore(String storePath) { File f = null; try (OutputStream os = new FileOutputStream(f = File.createTempFile("server", ".store"))) { f.deleteOnExit(); Resources.copy(CcmBridge.class.getResource(storePath), os); } catch (IOException e) { logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e); } return f; }
Source:
public static <T> void shuffleHead(@NonNull T[] elements, int n) { START shuffleHead(elements, n, ThreadLocalRandom.current()::nextInt); END } There's probably a small overhead to translate the method reference on each call. I'm not sure if it's significant or not, but we can avoid it altogether by passing the `ThreadLocalRandom` itself instead of the method. Then you can mock it in the test: ```java ThreadLocalRandom random = Mockito.mock(ThreadLocalRandom.class); Mockito.when(random.nextInt(Mockito.anyInt())).thenAnswer((invocation) -> { int i = invocation.getArgument(0); return i - 2; }); ```

Target:
public static <T> void shuffleHead(@NonNull T[] elements, int n) { shuffleHead(elements, n, ThreadLocalRandom.current()); }
Source:
boolean errorDuringInit() { if (isInit && initException != null) { return true; } START return false; END } This can be simplified as `return (isInit && initException != null);`

Target:
boolean errorDuringInit() { return (isInit && initException != null); }
Source:
KeyspaceMetadata(String name, boolean durableWrites, Map<String, String> replication) { this.name = name; this.durableWrites = durableWrites; this.replication = replication; this.strategy = ReplicationStrategy.create(replication); START this.isVirtual=false; END } Would be preferable for this constructor should reuse the new one (i.e. `this(name, durableWrites, replication, false)`). Should also mark this constructor as deprecated as it looks like existing uses of it were updated to use the new one.

Target:
KeyspaceMetadata(String name, boolean durableWrites, Map<String, String> replication) { this(name, durableWrites, replication, false); }
Source:
START public Class<?> getRawType() { END return token.getRawType(); } Shouldn't this be `<? super T>`?

Target:
public Class<? super T> getRawType() { return token.getRawType(); }
Source:
public DefaultNode(InetSocketAddress connectAddress, InternalDriverContext context) { this.connectAddress = connectAddress; // We leak a reference to a partially constructed object (this), but in practice this won't be a // problem because the node updater only needs the connect address to initialize. START this.metricUpdater = context.metricUpdaterFactory().newNodeUpdater(this); END this.state = NodeState.UNKNOWN; this.distance = NodeDistance.IGNORED; this.rawTokens = Collections.emptySet(); this.extras = Collections.emptyMap(); } it seems a little worse than that, I see that the constructor of `DefaultNodeUpdater` also tries to do the following: ``` ChannelPool pool = context.poolManager().getPools().get(node); ```

Target:
public DefaultNode(InetSocketAddress connectAddress, InternalDriverContext context) { this.connectAddress = connectAddress; this.state = NodeState.UNKNOWN; this.distance = NodeDistance.IGNORED; this.rawTokens = Collections.emptySet(); this.extras = Collections.emptyMap(); // We leak a reference to a partially constructed object (this), but in practice this won't be a // problem because the node updater only needs the connect address to initialize. this.metricUpdater = context.metricUpdaterFactory().newNodeUpdater(this); }
Source:
void validate(QueryType qt, MappingManager manager) { START checkArgument(qt == QueryType.SAVE || qt == QueryType.DEL || qt == QueryType.GET, END "Consistency level option is only allowed in save, delete and get queries"); } Just noticed: this check is useless, these is no other `QueryType` at this moment.

Target:
void validate(QueryType qt, MappingManager manager) { }
Source:
public void should_hash_consistently() { ByteBuffer byteBuffer = Bytes.fromHexString("0xCAFEBABE"); Token tokenA = factory.hash(byteBuffer); Token tokenB = factory.hash(byteBuffer); assertThat(tokenA).isEqualTo(factory.fromString("59959303159920881837560881824507314222")); START assertThat(tokenA).isEqualTo(tokenB); END } Trivial: you could have chained the `isEqualTo` calls.

Target:
public void should_hash_consistently() { ByteBuffer byteBuffer = Bytes.fromHexString("0xCAFEBABE"); Token tokenA = factory.hash(byteBuffer); Token tokenB = factory.hash(byteBuffer); assertThat(tokenA) .isEqualTo(factory.fromString("59959303159920881837560881824507314222")) .isEqualTo(tokenB); }
Source:
public PreparedStatement addPrepared(PreparedStatement stmt) { PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().boundValuesMetadata.id, stmt); if (previous != null) { logger.warn("Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. " + "Consider preparing the statement only once. Query='{}'", stmt.getQueryString()); // The one object in the cache will get GCed once it's not referenced by the client anymore since we use a weak reference. // So we need to make sure that the instance we do return to the user is the one that is in the cache. if (com.google.common.base.Objects.equal(previous.getPreparedId().resultSetMetadata.id, stmt.getPreparedId().resultSetMetadata.id)) START return previous; END } return stmt; } I don't think it's the right way to fix the issue you described. We're returning the correct PreparedStatement to the caller of this method, but leaving the cached instance with the old result metadata. Rather it should be: ```java previous.getPreparedId().resultSetMetadata = stmt.getPreparedId().resultSetMetadata; return previous; ```

Target:
public PreparedStatement addPrepared(PreparedStatement stmt) { PreparedStatement previous = preparedQueries.putIfAbsent(stmt.getPreparedId().boundValuesMetadata.id, stmt); if (previous != null) { logger.warn("Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. " + "Consider preparing the statement only once. Query='{}'", stmt.getQueryString()); // The one object in the cache will get GCed once it's not referenced by the client anymore since we use a weak reference. // So we need to make sure that the instance we do return to the user is the one that is in the cache. // However if the result metadata changed since the last PREPARE call, this also needs to be updated. previous.getPreparedId().resultSetMetadata = stmt.getPreparedId().resultSetMetadata; return previous; } return stmt; }
Source:
String keyspace() { SetKeyspaceAttempt currentAttempt = targetKeyspace.get(); START return currentAttempt == null ? null : currentAttempt.keyspace; END } targetKeyspace gets set to null if the future fails, should it not do that? The reason it does it is if set keyspace fails, we want to provide another opportunity to set the same keyspace.

Target:
String keyspace() { return targetKeyspace.get().keyspace; }
Source:
public void getMessage_should_return_message_if_address_is_null() { START assertEquals("[null] Test message", new ConnectionException(null, "Test message").getMessage()); END } We might as well remove `[null]` altogether in that case, that is have the message `"Test message"`.

Target:
public void getMessage_should_return_message_if_address_is_null() { assertEquals(new ConnectionException(null, "Test message").getMessage(), "Test message"); }
Source:
static <T extends Annotation> T getTypeAnnotation(Class<T> annotation, Class<?> annotatedClass) { T instance = annotatedClass.getAnnotation(annotation); if (instance == null) START throw new IllegalStateException(String.format("@%s annotation was not found on %s", END annotation.getSimpleName(), annotatedClass)); // Check that no other mapping annotations are present validateAnnotations(annotatedClass, annotation); return instance; } Admittedly `IllegalArgumentException` isn't the most appropriate type for mapper annotation misuse, but `IllegalStateException` isn't either: - `IllegalArgumentException`: _Thrown to indicate that a method has been passed an illegal or inappropriate argument_ - `IllegalStateException`: _Signals that a method has been invoked at an illegal or inappropriate time_ Between the two, I'd rather keep IAE for the sake of backward compatibility.

Target:
static <T extends Annotation> T getTypeAnnotation(Class<T> annotation, Class<?> annotatedClass) { T instance = annotatedClass.getAnnotation(annotation); if (instance == null) throw new IllegalArgumentException(String.format("@%s annotation was not found on %s", annotation.getSimpleName(), annotatedClass)); // Check that no other mapping annotations are present validateAnnotations(annotatedClass, annotation); return instance; }
Source:
private String joinJvmArgs() { StringBuilder allJvmArgs = new StringBuilder(""); for (String jvmArg : jvmArgs) { // Windows requires jvm arguments to be quoted, while *nix requires unquoted. START String quote = isWindows() ? "\"" : ""; END allJvmArgs.append(" "); allJvmArgs.append(quote); allJvmArgs.append("--jvm_arg="); allJvmArgs.append(randomizePorts(jvmArg)); allJvmArgs.append(quote); } return allJvmArgs.toString(); } This could be moved outside the for loop.

Target:
private String joinJvmArgs() { StringBuilder allJvmArgs = new StringBuilder(""); String quote = isWindows() ? "\"" : ""; for (String jvmArg : jvmArgs) { // Windows requires jvm arguments to be quoted, while *nix requires unquoted. allJvmArgs.append(" "); allJvmArgs.append(quote); allJvmArgs.append("--jvm_arg="); allJvmArgs.append(randomizePorts(jvmArg)); allJvmArgs.append(quote); } return allJvmArgs.toString(); }
Source:
private <V> V as(TypeToken<V> javaType) { START if (OBJECT_TYPE.equals(javaType)) { // we're handling a getObject() call END @SuppressWarnings("unchecked") V v = (V)asObject(); // Since V is Object, this is a safe cast return v; } else { // we're handling a typed getter call assert javaType != null; return with(codecFor(javaType)); } } That's a good point, but my plan was to move OBJECT_TYPE to TypeTokens and make it public, which in theory allows users to pass it to get(). So it might be better to use `null` to indicate getObject (as you initially did).

Target:
private <V> V as(TypeToken<V> javaType) { return with(codecFor(javaType)); }
Source:
public void indexerTest() throws Exception { // add triples sparqlIndexer.update(uri, createDefaultModel().read( new StringReader(fooRDF), "", "N3")); waitForTriples(3); // triples should be present in the triplestore assertEquals("Triples should be present!", 3, countDescribeTriples(uri)); // SPARQL search should work final String sparqlQuery = "PREFIX fcrepo: <http://fedora.info/definitions/v4/repository#> \n" + "SELECT ?p \n" + "WHERE \n" + "{ ?p fcrepo:hasParent ?c }"; START assertEquals("Triple should return from search!", 3, countQueryTriples(sparqlQuery)); END // remove object sparqlIndexer.remove(uri); waitForTriples(0); // triples should not be present in the triplestore assertTrue("Triples should not be present!", countDescribeTriples(uri) == 0); } This update causes my build to fail.

Target:
public void indexerTest() throws Exception { // add triples sparqlIndexer.update(uri, createDefaultModel().read( new StringReader(fooRDF), "", "N3")); waitForTriples(3); // triples should be present in the triplestore assertEquals("Triples should be present!", 3, countDescribeTriples(uri)); // SPARQL search should work final String sparqlQuery = "PREFIX fcrepo: <http://fedora.info/definitions/v4/repository#> \n" + "SELECT ?p \n" + "WHERE \n" + "{ ?p fcrepo:hasParent ?c }"; assertTrue("Triple should return from search!", countQueryTriples(sparqlQuery) > 0 ); // remove object sparqlIndexer.remove(uri); waitForTriples(0); // triples should not be present in the triplestore assertTrue("Triples should not be present!", countDescribeTriples(uri) == 0); }
Source:
public void bitwise() { counter trueCount = new Counter(true); START counter falseCount = new Counter(false); END String x = "Hai"; if (trueCount.count() | falseCount.count()) { x = "kthxbai"; } assertEquals(x, __); assertEquals(trueCount.count, __); assertEquals(falseCount.count, __); } Shouldn't the `Counter `class contain a suitable constructor to initialize the `returnValue `attribute? ` public Counter(boolean b) { this.returnValue = b; }`

Target:
public void bitwise() { Counter trueCount = new Counter(true); Counter falseCount = new Counter(false); String x = "Hai"; if (trueCount.count() | falseCount.count()) { x = "kthxbai"; } assertEquals(x, __); assertEquals(trueCount.count, __); assertEquals(falseCount.count, __); }
Source:
public static boolean isTransientError(int code) { // Note: Status.NOT_ACCEPTABLE = 406, Status.REQUEST_TIMEOUT = 408 START return code == 406 || code == 408 || code == 500 || code == 502 || code == 503 || code == 504; END } In general a transient error means that it's temporary and recoverable. For 406 with CouchDB, is it recoverable?

Target:
public static boolean isTransientError(int code) { // Note: Status.REQUEST_TIMEOUT = 408 return code == 408 || code == 500 || code == 502 || code == 503 || code == 504; }
Source:
public boolean isOpen() { START return (open.get() && !closing.get()) || opening.get(); END } If opening is true, doesn't it mean it's still opening but not done opening yet?

Target:
public boolean isOpen() { return (open.get() && !closing.get()); }
Source:
public CustomFuture submit(boolean gzip) { START com.couchbase.lite.replicator.RemoteRequest request = generateRemoteRequest(); END if (gzip) request.setCompressedRequest(true); synchronized (requestExecutor) { if (!requestExecutor.isShutdown()) { Future future = requestExecutor.submit(request); pendingRequests.add(future); runnables.put(future, request); } } return this; } Can't we just have `RemoteRequest`?

Target:
public CustomFuture submit(boolean gzip) { RemoteRequest request = generateRemoteRequest(); if (gzip) request.setCompressedRequest(true); synchronized (requestExecutor) { if (!requestExecutor.isShutdown()) { Future future = requestExecutor.submit(request); pendingRequests.add(future); runnables.put(future, request); } } return this; }
Source:
private void pruneFailedDownload(String docId) { START Log.e(TAG, "pruneFailedDownload: " + docId); END try { getLocalDatabase().deleteLocalDocument(docId); } catch (CouchbaseLiteException e) { Log.w(TAG, "Failed to delete local document: " + docId, e); } } Shouldn't be Log.e.

Target:
private void pruneFailedDownload(String docId) { try { getLocalDatabase().deleteLocalDocument(docId); } catch (CouchbaseLiteException e) { Log.w(TAG, "Failed to delete local document: " + docId, e); } }
Source:
protected void setError(Throwable throwable) { // TODO - needs to port //if (error.code == NSURLErrorCancelled && $equal(error.domain, NSURLErrorDomain)) // return; if (throwable != this.error) { Log.e(Log.TAG_SYNC, "%s: Progress: set error = %s", this, throwable); parentReplication.setLastError(throwable); this.error = throwable; // if permanent error, stop immediately if(Utils.isPermanentError(this.error)) { stop(); } // iOS version sends notification from stop() method, but java version does not. // following codes are always executed. START { END Replication.ChangeEvent changeEvent = new Replication.ChangeEvent(this); changeEvent.setError(this.error); notifyChangeListeners(changeEvent); } } } { here is not necessary.

Target:
protected void setError(Throwable throwable) { // TODO - needs to port //if (error.code == NSURLErrorCancelled && $equal(error.domain, NSURLErrorDomain)) // return; if (throwable != this.error) { Log.e(Log.TAG_SYNC, "%s: Progress: set error = %s", this, throwable); parentReplication.setLastError(throwable); this.error = throwable; // if permanent error, stop immediately if(Utils.isPermanentError(this.error)) { stop(); } // iOS version sends notification from stop() method, but java version does not. // following codes are always executed. Replication.ChangeEvent changeEvent = new Replication.ChangeEvent(this); changeEvent.setError(this.error); notifyChangeListeners(changeEvent); } }
Source:
protected void stop() { if (!isRunning()) return; // clear batcher batcher.clear(); // set non-continuous setLifecycle(Replication.Lifecycle.ONESHOT); // cancel if middle of retry cancelRetryFuture(); // cancel all pending future tasks. while (!pendingFutures.isEmpty()) { Future future = pendingFutures.poll(); START if (future != null && !future.isCancelled() && future.isDone()) { END future.cancel(true); } } } should it be `!future.isDone()`?

Target:
protected void stop() { if (!isRunning()) return; // clear batcher batcher.clear(); // set non-continuous setLifecycle(Replication.Lifecycle.ONESHOT); // cancel if middle of retry cancelRetryFuture(); // cancel all pending future tasks. while (!pendingFutures.isEmpty()) { Future future = pendingFutures.poll(); if (future != null && !future.isCancelled() && !future.isDone()) { future.cancel(true); } } }
Source:
public E take() throws InterruptedException { E e = super.take(); START if(listener != null) listener.changed(BlockingQueueListener.EventType.TAKE, e, this); END return e; } Can you wrap this in curly braces? ``` if(listener != null) { listener.changed(BlockingQueueListener.EventType.TAKE, e, this); } ```

Target:
public E take() throws InterruptedException { E e = super.take(); if(listener != null) { listener.changed(BlockingQueueListener.EventType.TAKE, e, this); } return e; }
Source:
public T convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException { for (T t : type_.getEnumConstants()) { if (t.toString().equals(value)) { return t; } } String choices = TextHelper.concat(type_.getEnumConstants(), 0, ",", "{", "}"); throw new ArgumentParserException(String.format( TextHelper.LOCALE_ROOT, "could not convert '%s' (choose from %s)", value, choices), START null, parser, arg); END } We can omit null here, since we have that overload.

Target:
public T convert(ArgumentParser parser, Argument arg, String value) throws ArgumentParserException { for (T t : type_.getEnumConstants()) { if (t.toString().equals(value)) { return t; } } String choices = TextHelper.concat(type_.getEnumConstants(), 0, ",", "{", "}"); throw new ArgumentParserException(String.format( TextHelper.LOCALE_ROOT, "could not convert '%s' (choose from %s)", value, choices), parser, arg); }
Source:
START private static final IModelAccessFacade getModelAccess() { END return Utils.getComponent(IModelAccessFacade.class); } why needs this method to be static?

Target:
private final IModelAccessFacade getModelAccess() { return Utils.getComponent(IModelAccessFacade.class); }
Source:
START private static final XWikiContext getContext() { END return getModelContext().getXWikiContext(); } why needs this method to be static?

Target:
private final XWikiContext getContext() { return getModelContext().getXWikiContext(); }
Source:
public void setValue(String content) { START this.content = Optional.fromNullable(content); END } Optional should be used in interfaces. Use `null` as internal value.

Target:
public void setValue(String content) { this.content = content; }
Source:
public String getValue() { START return content.orNull(); END } why not returning a Optional<String>?

Target:
public String getValue() { return content; }
Source:
public @NotNull MetaTag getCharsetMetaTag(@NotNull String charsetStr) { START ECharset charset = ECharset.getCharset(charsetStr).get(); END if (charset != null) { return new MetaTag(charset); } return new MetaTag(ECharset.ATTRIB_NAME, charsetStr, null); } This could cause a NPE, instead resolve Optionals by checking present() first

Target:
public @NotNull MetaTag getCharsetMetaTag(@NotNull String charsetStr) { Optional<ECharset> charset = ECharset.getCharset(charsetStr); if (charset.isPresent()) { return new MetaTag(charset.get()); } return new MetaTag(ECharset.ATTRIB_NAME, charsetStr, null); }
Source:
public @NotNull MetaTag getCharsetMetaTag(@NotNull String charsetStr) { if (ECharset.getCharset(charsetStr).isPresent()) { ECharset charset = ECharset.getCharset(charsetStr).get(); START if (charset != null) { END return new MetaTag(charset); } } return new MetaTag(ECharset.ATTRIB_NAME, charsetStr, null); } null check unnecessary

Target:
public @NotNull MetaTag getCharsetMetaTag(@NotNull String charsetStr) { Optional<ECharset> charset = ECharset.getCharset(charsetStr); if (charset.isPresent()) { return new MetaTag(charset.get()); } return new MetaTag(ECharset.ATTRIB_NAME, charsetStr, null); }
Source:
public Optional<BaseObject> getXObject(XWikiDocument doc, DocumentReference classRef, int objectNumber) { BaseObject bObj = null; List<BaseObject> objs = getXObjects(doc, classRef); for (BaseObject baseObject : objs) { if (baseObject.getNumber() == objectNumber) { START bObj = baseObject; END } } return Optional.fromNullable(bObj); } add break statement

Target:
public Optional<BaseObject> getXObject(XWikiDocument doc, DocumentReference classRef, int objectNumber) { BaseObject bObj = null; List<BaseObject> objs = getXObjects(doc, classRef); for (BaseObject baseObject : objs) { if (baseObject.getNumber() == objectNumber) { bObj = baseObject; break; } } return Optional.fromNullable(bObj); }
Source:
public Optional<IPageTypeCategoryRole> getTypeCategoryForCatName(String categoryName) { START loadTypeNameToCategoryMap(); END return Optional.fromNullable(getTypeNameToCategoryMapIncludeDeprecated().get(categoryName)); } additional loadTypeNameToCategoryMap not needed.

Target:
public Optional<IPageTypeCategoryRole> getTypeCategoryForCatName(String categoryName) { return Optional.fromNullable(getTypeNameToCategoryMapIncludeDeprecated().get(categoryName)); }
Source:
void checkNotTranslation(XWikiDocument doc) { START String msg = "Trying to access XObjects on translation ''{0}'' of doc ''{1}''"; END checkState(!isTranslation(doc), MessageFormat.format(msg, doc.getLanguage(), doc.getDocumentReference())); } please extract to constant

Target:
void checkNotTranslation(XWikiDocument doc) { checkState(!isTranslation(doc), MessageFormat.format( "Trying to access XObjects on translation ''{0}'' of doc ''{1}''", doc.getLanguage(), doc.getDocumentReference())); }
Source:
private DocumentReference createDocRef(DocumentReference baseDocRef, long num) { START String name = baseDocRef.getName() + num; END SpaceReference parent = References.extractRef(baseDocRef, SpaceReference.class).get(); return References.create(DocumentReference.class, name, parent); } Please use StringBuilder

Target:
private DocumentReference createDocRef(DocumentReference baseDocRef, long num) { String name = new StringBuilder(baseDocRef.getName()).append(num).toString(); SpaceReference parent = References.extractRef(baseDocRef, SpaceReference.class).get(); return References.create(DocumentReference.class, name, parent); }
Source:
public String getLayoutType(SpaceReference layoutSpaceRef) { BaseObject layoutPropertyObj = getLayoutPropertyObj(layoutSpaceRef); if ((layoutPropertyObj != null) && (layoutPropertyObj.getStringValue( ICellsClassConfig.LAYOUT_TYPE_FIELD) != null)) { START return layoutPropertyObj.getStringValue(ICellsClassConfig.LAYOUT_TYPE_FIELD); END } return ICellsClassConfig.PAGE_LAYOUT_VALUE; } afaik `com.xpn.xwiki.objects.BaseCollection.getStringValue(String)` never returns null

Target:
public String getLayoutType(SpaceReference layoutSpaceRef) { BaseObject layoutPropertyObj = getLayoutPropertyObj(layoutSpaceRef); if (layoutPropertyObj != null) { return layoutPropertyObj.getStringValue(ICellsClassConfig.LAYOUT_TYPE_FIELD); } return ICellsClassConfig.PAGE_LAYOUT_VALUE; }
Source:
public boolean isActivated(String name) { for (IClassCollectionRole classCollection : classCollections) { if (classCollection.getConfigName().equals(name)) { return classCollection.isActivated(); } } START try { END return Utils.getComponentManager().lookup(ClassPackage.class, name).isActivated(); } catch (ComponentLookupException exc) { LOGGER.debug("ClassDefinitionPackage '{}' doesn't exist", name); return false; } } please move "lookup" before the for loop

Target:
public boolean isActivated(String name) { try { return Utils.getComponentManager().lookup(ClassPackage.class, name).isActivated(); } catch (ComponentLookupException exc) { LOGGER.debug("ClassDefinitionPackage '{}' doesn't exist", name); } for (IClassCollectionRole classCollection : classCollections) { if (classCollection.getConfigName().equals(name)) { return classCollection.isActivated(); } } return false; }
Source:
public boolean sameObject(DocFormRequestKey other) { System.out.println("compare " + this); START System.out.println("with " + other); END return (this.classRef != null) && (this.objNb != null) && (this.objNb >= 0) && ObjectUtils.equals(this.classRef, other.classRef) && ObjectUtils.equals(this.objNb, other.objNb); } Please change to log or remove.

Target:
public boolean sameObject(DocFormRequestKey other) { return (this.classRef != null) && (this.objNb != null) && (this.objNb >= 0) && ObjectUtils.equals(this.classRef, other.classRef) && ObjectUtils.equals(this.objNb, other.objNb); }
Source:
public ZonedDateTime parse(String string) throws Exception { ZonedDateTime date; DateTimeFormatter df = this.getDateFormat(); ObjectHelper.notNull(this.pattern, "pattern"); START date = ZonedDateTime.parse(string, df); END return date; } I'd change this to initialize `date` directly unless there was another reason perhaps?: ```suggestion ZonedDateTime date = ZonedDateTime.parse(string, df); ```

Target:
public ZonedDateTime parse(String string) throws Exception { DateTimeFormatter df = this.getDateFormat(); ObjectHelper.notNull(this.pattern, "pattern"); return ZonedDateTime.parse(string, df); }
Source:
private Map<String, Float> classify(Model model, Translator translator, File input) throws Exception { try { return classify(model, translator, ImageIO.read(input)); } catch (IOException e) { LOG.error("Couldn't transform input into a BufferedImage"); START throw new Exception("Couldn't transform input into a BufferedImage", e); END } } I'd favour to narrow down the exception being thrown here, `Exception` is too generic. Perhaps anything that inherits or it is `RuntimeExceptioon`.

Target:
private Map<String, Float> classify(Model model, Translator translator, File input) throws Exception { try { return classify(model, translator, ImageIO.read(input)); } catch (IOException e) { LOG.error("Couldn't transform input into a BufferedImage"); throw new RuntimeException("Couldn't transform input into a BufferedImage", e); } }
Source:
public UndertowSecurityProvider getSecurityProvider() { START if (this.securityProvider == null) { END return getComponent().getSecurityProvider(); } return this.securityProvider; } getter/setters should be plain, not these tricks. Instead when creating the endpoint in the component, then set the security provider on the endpoint correctly

Target:
public UndertowSecurityProvider getSecurityProvider() { return this.securityProvider; }
Source:
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { WorkdayConfiguration workdayConfiguration = new WorkdayConfiguration(); START setProperties(workdayConfiguration, parameters); END this.httpClient = createHttpClient(workdayConfiguration); this.workdayConfiguration = workdayConfiguration; Endpoint endpoint = new WorkdayEndpoint(uri, this); setProperties(endpoint, parameters); return endpoint; } This shouldn't be done, we just need to setProperties on the endpoint, so the second one should be sufficient, take a look at the other components.

Target:
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { WorkdayEndpoint endpoint = new WorkdayEndpoint(uri, this); setProperties(endpoint, parameters); return endpoint; }
Source:
protected String getEndpointId(Endpoint ep) { String answer = doGetEndpointId(ep); boolean sanitize = camelContext != null && camelContext.getManagementStrategy().getManagementAgent().getMask(); START if (sanitize != null && sanitize) { END // use xxxxxx as replacements as * has to be quoted for MBean names answer = URISupport.sanitizeUri(answer); } return answer; } primitive boolean cannot be compared with null.

Target:
protected String getEndpointId(Endpoint ep) { String answer = doGetEndpointId(ep); boolean sanitize = camelContext != null && camelContext.getManagementStrategy().getManagementAgent().getMask(); if (sanitize) { // use xxxxxx as replacements as * has to be quoted for MBean names answer = URISupport.sanitizeUri(answer); } return answer; }