auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void resolveReference(String field) { if ((flags & ALL_RESOLVED_FLAG) != 0) { return; } synchronized (this) { <START> try { <END> if ((flags & ALL_RESOLVED_FLAG) != 0) { return; } if (linkedObjects.isEmpty()) { return; } boolean hasPotentialRefs = false; Collection<Object> rawValuesValues = rawValues.values(); for (Object rawValue : rawValuesValues) { if (rawValue instanceof Map && ((Map<?, ?>) rawValue).containsKey(StateSerializer.REFERENCE_KEY)) { hasPotentialRefs = true; break; } } if (!hasPotentialRefs) { return; } Profiler.Static.startThreadEvent(RESOLVE_REFERENCE_PROFILER_EVENT, this); try { Object object = linkedObjects.values().iterator().next(); Map<UUID, Object> references = StateValueUtils.resolveReferences(getDatabase(), object, rawValuesValues, field); Map<String, Object> resolved = new HashMap<>(); resolveMetricReferences(resolved); for (Map.Entry<? extends String, ?> e : rawValues.entrySet()) { UUID id = StateValueUtils.toIdIfReference(e.getValue()); if (id != null) { resolved.put(e.getKey(), references.get(id)); } } for (Map.Entry<String, Object> e : resolved.entrySet()) { put(e.getKey(), e.getValue()); } } finally { Profiler.Static.stopThreadEvent(); } } finally { flags |= ALL_RESOLVED_FLAG; } } }</code><technical_language>a try/finally block, want flag set if error resolve</technical_language>

Target:
public void resolveReference(String field) { if ((flags & ALL_RESOLVED_FLAG) != 0) { return; } synchronized (this) { if ((flags & ALL_RESOLVED_FLAG) != 0) { return; } if (linkedObjects.isEmpty()) { flags |= ALL_RESOLVED_FLAG; return; } boolean hasPotentialRefs = false; Collection<Object> rawValuesValues = rawValues.values(); for (Object rawValue : rawValuesValues) { if (rawValue instanceof Map && ((Map<?, ?>) rawValue).containsKey(StateSerializer.REFERENCE_KEY)) { hasPotentialRefs = true; break; } } if (!hasPotentialRefs) { flags |= ALL_RESOLVED_FLAG; return; } Profiler.Static.startThreadEvent(RESOLVE_REFERENCE_PROFILER_EVENT, this); try { Object object = linkedObjects.values().iterator().next(); Map<UUID, Object> references = StateValueUtils.resolveReferences(getDatabase(), object, rawValuesValues, field); Map<String, Object> resolved = new HashMap<>(); resolveMetricReferences(resolved); for (Map.Entry<? extends String, ?> e : rawValues.entrySet()) { UUID id = StateValueUtils.toIdIfReference(e.getValue()); if (id != null) { resolved.put(e.getKey(), references.get(id)); } } for (Map.Entry<String, Object> e : resolved.entrySet()) { put(e.getKey(), e.getValue()); } flags |= ALL_RESOLVED_FLAG; } finally { Profiler.Static.stopThreadEvent(); } } }
Source:
<code>public Set<Attribute<T, ?>> describe() { return Collections.singleton( <START> new MultivaluedAttribute<T, String>("grantedPermissions", String.class) <END> .getter(MatrixAuthorizationStrategyConfigurator::getGrantedPermissions) .setter(MatrixAuthorizationStrategyConfigurator::setGrantedPermissions) ); }</code><technical_language>suggestion new MultivaluedAttribute<T, String>("permissions", String.class) done for NodeProperty, here</technical_language>

Target:
public Set<Attribute<T, ?>> describe() { return new HashSet<>(Arrays.asList( new MultivaluedAttribute<T, String>("permissions", String.class) .getter(MatrixAuthorizationStrategyConfigurator::getPermissions) .setter(MatrixAuthorizationStrategyConfigurator::setPermissions), new MultivaluedAttribute<T, String>("grantedPermissions", String.class) .getter(unused -> null) .setter(MatrixAuthorizationStrategyConfigurator::setPermissionsDeprecated) )); }
Source:
<code>public PlanNode visitLateralJoin(LateralJoinNode lateral, RewriteContext<PlanNode> context) { LateralJoinNode rewrittenLateral = (LateralJoinNode) context.defaultRewrite(lateral, context.get()); <START> if (!rewrittenLateral.getCorrelation().isEmpty()) { <END> Optional<ValuesNode> values = searchFrom(lateral.getSubquery()) .skipOnlyWhen(ProjectNode.class::isInstance) .where(ValuesNode.class::isInstance) .findSingle(); if (values.isPresent() && isSingleRowValuesWithNoColumns(values.get())) { List<ProjectNode> subqueryProjections = searchFrom(lateral.getSubquery()) .where(ProjectNode.class::isInstance) .findAll(); if (subqueryProjections.size() == 0) { return rewrittenLateral.getInput(); } else if (subqueryProjections.size() == 1) { Assignments assignments = Assignments.builder() .putIdentities(rewrittenLateral.getInput().getOutputSymbols()) .putAll(subqueryProjections.get(0).getAssignments()) .build(); return projectNode(rewrittenLateral.getInput(), assignments); } } } return rewrittenLateral; }</code><technical_language>restructure this a sequence of checks short-circuit transformation instead of a bunch of nested ifs easier follow: java if (rewrittenLateral.getCorrelation().isEmpty()) { return rewrittenLateral; } Optional<ValuesNode> values = ... if (!values.isPresent() || !isSingleRowValuesWithNoColumns(values.get()) { return rewrittenLateral; } List<ProjectNode> subqueryProjections = ... if (subqueryProjections.size() == 0) { ... } else if (...) { ... } ..</technical_language>

Target:
public PlanNode visitLateralJoin(LateralJoinNode lateral, RewriteContext<PlanNode> context) { LateralJoinNode rewrittenLateral = (LateralJoinNode) context.defaultRewrite(lateral, context.get()); if (rewrittenLateral.getCorrelation().isEmpty()) { return rewrittenLateral; } Optional<ValuesNode> values = searchFrom(lateral.getSubquery()) .skipOnlyWhen(ProjectNode.class::isInstance) .where(ValuesNode.class::isInstance) .findSingle(); if (!values.isPresent() || !isSingleRowValuesWithNoColumns(values.get())) { return rewrittenLateral; } List<ProjectNode> subqueryProjections = searchFrom(lateral.getSubquery()) .where(ProjectNode.class::isInstance) .findAll(); if (subqueryProjections.size() == 0) { return rewrittenLateral.getInput(); } else if (subqueryProjections.size() == 1) { Assignments assignments = Assignments.builder() .putIdentities(rewrittenLateral.getInput().getOutputSymbols()) .putAll(subqueryProjections.get(0).getAssignments()) .build(); return projectNode(rewrittenLateral.getInput(), assignments); } return rewrittenLateral; }
Source:
<code>public static @Nullable Long getThreadPrio(KernelAnalysis module, Integer threadId, long ts) { Long execPrio = null; ITmfStateSystem ss = module.getStateSystem(); if (ss == null) { return execPrio; } Integer execPrioQuark; try { execPrioQuark = ss.getQuarkAbsolute(Attributes.THREADS, threadId.toString(), Attributes.PRIO); ITmfStateInterval interval = ss.querySingleState(ts, execPrioQuark); ITmfStateValue prioValue = interval.getStateValue(); switch (prioValue.getType()) { case LONG: <START> execPrio = prioValue.unboxLong(); <END> break; case STRING: case DOUBLE: case NULL: case INTEGER: default: break; } } catch (AttributeNotFoundException | StateSystemDisposedException | TimeRangeException e) { } return execPrio; }</code><technical_language>if .newIntValue() is in provider, Type = Integer .unboxInt() here. In fact, control is put attribute, skip switch do prioValue.unboxInt(). .getType() is more more for want query state system/attributes do about</technical_language>

Target:
public static @Nullable Integer getThreadPrio(KernelAnalysis module, Integer threadId, long ts) { Integer execPrio = null; ITmfStateSystem ss = module.getStateSystem(); if (ss == null) { return execPrio; } try { Integer execPrioQuark = ss.getQuarkAbsolute(Attributes.THREADS, threadId.toString(), Attributes.PRIO); ITmfStateInterval interval = ss.querySingleState(ts, execPrioQuark); ITmfStateValue prioValue = interval.getStateValue(); execPrio = prioValue.unboxInt(); } catch (AttributeNotFoundException | StateSystemDisposedException | TimeRangeException e) { } return execPrio; }
Source:
<code>protected void reflectedUpdateFile(Path outputPath, byte[] data) throws InvocationTargetException, IllegalAccessException { <START> if (cachedUpdateFileMethod == null) { <END> getCachedUpdateFileMethod(); } Class parameters = cachedUpdateFileMethod.getParameterTypes(); if (parameters.length == 2 && parameters[0].equals(Path.class) && parameters[1].isArray()) { cachedUpdateFileMethod.invoke(outputPath, data); } else if (parameters.length == 3 && parameters[0].equals(Path.class) && parameters[1].isArray() && parameters[2].isPrimitive()) { cachedUpdateFileMethod.invoke(outputPath, data, true); } else { throw new RuntimeException("updateFile Method has unexpected parameters"); } }</code><technical_language>do need check for null - do getCachedUpdateFileMethod() method</technical_language>

Target:
protected void reflectedUpdateFile(Path outputPath, byte[] data) throws InvocationTargetException, IllegalAccessException { Class parameters = updateFileMethod.getParameterTypes(); if (parameters.length == 2 && parameters[0].equals(Path.class) && parameters[1].isArray()) { updateFileMethod.invoke(this, outputPath, data); } else if (parameters.length == 3 && parameters[0].equals(Path.class) && parameters[1].isArray() && parameters[2].isPrimitive()) { updateFileMethod.invoke(this, outputPath, data, true); } else { throw new RuntimeException("updateFile Method has unexpected parameters"); } }
Source:
<code>public void testRemove() throws Exception { setUpGetConnection(2); setUpGetEntityExpectations(GUIDS[0], 2, getEntity(0)); setUriInfo(setUpActionExpectations(VdcActionType.DetachStorageDomainFromPool, DetachStorageDomainFromPoolParameters.class, new String[] { "StorageDomainId", "StoragePoolId" }, new Object[] { GUIDS[0], GUIDS[NAMES.length-1] }, true, true)); <START> collection.remove(GUIDS[0].toString()); <END> }</code><technical_language>please verify response remove()</technical_language>

Target:
public void testRemove() throws Exception { setUpGetConnection(2); setUpGetEntityExpectations(GUIDS[0], 2, getEntity(0)); setUriInfo(setUpActionExpectations(VdcActionType.DetachStorageDomainFromPool, DetachStorageDomainFromPoolParameters.class, new String[] { "StorageDomainId", "StoragePoolId" }, new Object[] { GUIDS[0], GUIDS[NAMES.length-1] }, true, true)); verifyRemove(collection.remove(GUIDS[0].toString())); }
Source:
<code>public void doPolling(Guid cmdId, List<Guid> childCmdIds) { boolean anyFailed = false; for (Guid childCmdId : childCmdIds) { switch (CommandCoordinatorUtil.getCommandStatus(childCmdId)) { case ACTIVE: log.info("Waiting on CloneCinderDisksCommandCallback child commands to complete"); return; case FAILED: case FAILED_RESTARTED: case UNKNOWN: <START> anyFailed = true; <END> break; default: break; } } T command = getCommand(cmdId); command.getParameters().setTaskGroupSuccess(!anyFailed); command.setCommandStatus(anyFailed ? CommandStatus.FAILED : CommandStatus.SUCCEEDED); log.info("All CloneCinderDisksCommandCallback commands have completed, status '{}'", command.getCommandStatus()); }</code><technical_language>Please a a warn log here, a failure for specific child command command status</technical_language>

Target:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { boolean anyFailed = false; for (Guid childCmdId : childCmdIds) { CommandStatus commandStatus = CommandCoordinatorUtil.getCommandStatus(childCmdId); switch (commandStatus) { case ACTIVE: log.info("Waiting on CloneCinderDisksCommandCallback child commands to complete"); return; case FAILED: case FAILED_RESTARTED: case UNKNOWN: anyFailed = true; break; default: log.error("Invalid command status: '{}", commandStatus); break; } } T command = getCommand(cmdId); command.getParameters().setTaskGroupSuccess(!anyFailed); command.setCommandStatus(anyFailed ? CommandStatus.FAILED : CommandStatus.SUCCEEDED); log.info("All CloneCinderDisksCommandCallback commands have completed, status '{}'", command.getCommandStatus()); }
Source:
<code>protected Sequence<T> mergeCachedAndUncachedSequences( List<Pair<Interval, Sequence<T>>> sequencesByInterval, QueryToolChest<T, Query<T>> toolChest ) { if (sequencesByInterval.isEmpty()) { return Sequences.empty(); } <START> return toolChest.mergeSequencesUnordered(Sequences.simple(Lists.transform( <END> sequencesByInterval, new Function<Pair<Interval, Sequence<T>>, Sequence<T>>() { @Nullable @Override public Sequence<T> apply(Pair<Interval, Sequence<T>> input) { return input.rhs; } } ))); }</code><technical_language>break lines formatting a bit nicer, long lines below</technical_language>

Target:
protected Sequence<T> mergeCachedAndUncachedSequences( List<Pair<Interval, Sequence<T>>> sequencesByInterval, QueryToolChest<T, Query<T>> toolChest ) { if (sequencesByInterval.isEmpty()) { return Sequences.empty(); } return toolChest.mergeSequencesUnordered( Sequences.simple( Lists.transform( sequencesByInterval, new Function<Pair<Interval, Sequence<T>>, Sequence<T>>() { @Override public Sequence<T> apply(Pair<Interval, Sequence<T>> input) { return input.rhs; } } ) ) ); }
Source:
<code>public void run() { List<byte[]> args = command.getProcessedCommand(); byte[] channelName = args.get(1); byte[] message = args.get(2); try { long publishCount = context.getPubSub() .publish(context.getRegionProvider().getDataRegion(), channelName, message); <START> ByteBuf response = Coder.getIntegerResponse(context.getByteBufAllocator(), publishCount); <END> context.endAsyncCommandExecution(command, response); } catch (Throwable ex) { context.endAsyncCommandExecution(command, ex); } }</code><technical_language>prefer create a RedisResponse netty specifics out of executors</technical_language>

Target:
public void run() { List<byte[]> args = command.getProcessedCommand(); byte[] channelName = args.get(1); byte[] message = args.get(2); try { long publishCount = context.getPubSub() .publish(context.getRegionProvider().getDataRegion(), channelName, message); RedisResponse response = RedisResponse.integer(publishCount); context.endAsyncCommandExecution(command, response); } catch (Throwable ex) { context.endAsyncCommandExecution(command, ex); } }
Source:
<code>public void reportIssue(JavaCheck javaCheck, Tree tree, String message) { <START> throwIfEndOfAnalysisCheck(javaCheck); <END> reportIssue(javaCheck, tree, message, ImmutableList.of(), null); }</code><technical_language>this method overloading</technical_language>

Target:
public void reportIssue(JavaCheck javaCheck, Tree tree, String message) { reportIssue(javaCheck, tree, message, ImmutableList.of(), null); }
Source:
<code>void followLeader() throws InterruptedException { self.end_fle = Time.currentElapsedTime(); long electionTimeTaken = self.end_fle - self.start_fle; self.setElectionTimeTaken(electionTimeTaken); LOG.info("FOLLOWING - LEADER ELECTION TOOK - {}", electionTimeTaken, QuorumPeer.FLE_TIME_UNIT); self.start_fle = 0; self.end_fle = 0; fzk.registerJMX(new FollowerBean(this, zk), self.jmxLocalPeerBean); try { <START> InetSocketAddress addr = findLeader(); <END> try { connectToLeader(addr); long newEpochZxid = registerWithLeader(Leader.FOLLOWERINFO); if (self.isReconfigStateChange()) throw new Exception("learned about role change"); long newEpoch = ZxidUtils.getEpochFromZxid(newEpochZxid); if (newEpoch < self.getAcceptedEpoch()) { LOG.error("Proposed leader epoch " + ZxidUtils.zxidToString(newEpochZxid) + " is less than our accepted epoch " + ZxidUtils.zxidToString(self.getAcceptedEpoch())); throw new IOException("Error: Epoch of leader is lower"); } syncWithLeader(newEpochZxid); QuorumPacket qp = new QuorumPacket(); while (this.isRunning()) { readPacket(qp); processPacket(qp); } } catch (Exception e) { LOG.warn("Exception when following the leader", e); try { sock.close(); } catch (IOException e1) { e1.printStackTrace(); } pendingRevalidations.clear(); } } finally { zk.unregisterJMX((Learner)this); } }</code><technical_language>Unnecessary change - this file removed change list</technical_language>

Target:
void followLeader() throws InterruptedException { self.end_fle = Time.currentElapsedTime(); long electionTimeTaken = self.end_fle - self.start_fle; self.setElectionTimeTaken(electionTimeTaken); LOG.info("FOLLOWING - LEADER ELECTION TOOK - {}", electionTimeTaken, QuorumPeer.FLE_TIME_UNIT); self.start_fle = 0; self.end_fle = 0; fzk.registerJMX(new FollowerBean(this, zk), self.jmxLocalPeerBean); try { QuorumServer leaderServer = findLeader(); try { connectToLeader(leaderServer.addr, leaderServer.hostname); long newEpochZxid = registerWithLeader(Leader.FOLLOWERINFO); if (self.isReconfigStateChange()) throw new Exception("learned about role change"); long newEpoch = ZxidUtils.getEpochFromZxid(newEpochZxid); if (newEpoch < self.getAcceptedEpoch()) { LOG.error("Proposed leader epoch " + ZxidUtils.zxidToString(newEpochZxid) + " is less than our accepted epoch " + ZxidUtils.zxidToString(self.getAcceptedEpoch())); throw new IOException("Error: Epoch of leader is lower"); } syncWithLeader(newEpochZxid); QuorumPacket qp = new QuorumPacket(); while (this.isRunning()) { readPacket(qp); processPacket(qp); } } catch (Exception e) { LOG.warn("Exception when following the leader", e); try { sock.close(); } catch (IOException e1) { e1.printStackTrace(); } pendingRevalidations.clear(); } } finally { zk.unregisterJMX((Learner)this); } }
Source:
<code>public F next() throws NoSuchElementException { if(next==null&&this.hasNext()==false) { <START> throw new NoSuchElementException(); <END> } F f = next; next = null; return f; }</code><technical_language>minor suggestions: please, check formatting (need some whitespaces). I personally !this.hasNext() instead of explicit check false. if (next == null && !this.hasNext()) {</technical_language>

Target:
public F next() throws NoSuchElementException { if(next==null && !this.hasNext()) { throw new NoSuchElementException(); } F f = next; next = null; return f; }
Source:
<code>S3SelectPushdown(HiveClientConfig hiveClientConfig) { <START> this.hiveClientConfig = hiveClientConfig; <END> }</code><technical_language>Add requireNonNull</technical_language>

Target:
S3SelectPushdown(HiveClientConfig hiveClientConfig) { this.hiveClientConfig = requireNonNull(hiveClientConfig); }
Source:
<code><START> public FastClass(Class<?> hostClass) { <END> super(hostClass, FASTCLASS_BY_GUICE_MARKER); hostIsInterface = hostClass.isInterface(); }</code><technical_language>nit, need public</technical_language>

Target:
FastClass(Class<?> hostClass) { super(hostClass, FASTCLASS_BY_GUICE_MARKER); hostIsInterface = hostClass.isInterface(); }
Source:
<code>private GHResponse runMoscow(GraphHopper hopper, String edgeBasedParam, boolean ch) { GHRequest req = new GHRequest(55.813357, 37.5958585, 55.811042, 37.594689); if (edgeBasedParam.equals("true") || edgeBasedParam.equals("false")) { <START> req.getHints().putObject(Routing.EDGE_BASED, edgeBasedParam); <END> } else { req.getHints().remove(Routing.EDGE_BASED); } req.putHint(CH.DISABLE, !ch); req.setVehicle("car"); req.setWeighting("fastest"); return hopper.route(req); }</code><technical_language>I need putObject(Routing.EDGE_BASED, Helper.toObject(edgeBasedParam)) (previously this code relied string converted boolean... This is a bit ugly code, in #1958 :)</technical_language>

Target:
private GHResponse runMoscow(GraphHopper hopper, String edgeBasedParam, boolean ch) { GHRequest req = new GHRequest(55.813357, 37.5958585, 55.811042, 37.594689); if (edgeBasedParam.equals("true") || edgeBasedParam.equals("false")) { req.getHints().putObject(Routing.EDGE_BASED, Helper.toObject(edgeBasedParam)); } else { req.getHints().remove(Routing.EDGE_BASED); } req.putHint(CH.DISABLE, !ch); req.setVehicle("car"); req.setWeighting("fastest"); return hopper.route(req); }
Source:
<code>public void reset(ResetRequest request) throws GitException { try { ResetCommand resetCommand = getGit().reset(); resetCommand.setRef(request.getCommit()); <START> int filePatternsAmount = request.getFilePattern().size(); <END> for (int i = 0; i < filePatternsAmount; i++) { resetCommand.addPath(request.getFilePattern().get(i)); } if (request.getType() != null && filePatternsAmount == 0) { if (request.getType().equals(ResetRequest.ResetType.HARD)) { resetCommand.setMode(ResetCommand.ResetType.HARD); } else if (request.getType().equals(ResetRequest.ResetType.KEEP)) { resetCommand.setMode(ResetCommand.ResetType.KEEP); } else if (request.getType().equals(ResetRequest.ResetType.MERGE)) { resetCommand.setMode(ResetCommand.ResetType.MERGE); } else if (request.getType().equals(ResetRequest.ResetType.MIXED)) { resetCommand.setMode(ResetCommand.ResetType.MIXED); } else if (request.getType().equals(ResetRequest.ResetType.SOFT)) { resetCommand.setMode(ResetCommand.ResetType.SOFT); } } resetCommand.call(); } catch (GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } }</code><technical_language>request.getFilePattern() .stream() .forEach(resetCommand::addPath);</technical_language>

Target:
public void reset(ResetRequest request) throws GitException { try { ResetCommand resetCommand = getGit().reset(); resetCommand.setRef(request.getCommit()); List<String> patterns = request.getFilePattern(); patterns.stream().forEach(resetCommand::addPath); if (request.getType() != null && patterns.isEmpty()) { switch (request.getType()) { case HARD: resetCommand.setMode(ResetType.HARD); break; case KEEP: resetCommand.setMode(ResetType.KEEP); break; case MERGE: resetCommand.setMode(ResetType.MERGE); break; case MIXED: resetCommand.setMode(ResetType.MIXED); break; case SOFT: resetCommand.setMode(ResetType.SOFT); break; } } resetCommand.call(); } catch (GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } }
Source:
<code>public void testAPIUsage() { final KieServices ks = KieServices.Factory.get(); final KieContainer kieContainer = DMNRuntimeUtil.getKieContainerIgnoringErrors(ks.newReleaseId("org.kie", "dmn-test-" + UUID.randomUUID(), "1.0"), ks.getResources().newClassPathResource("incomplete_expression.dmn", this.getClass()), ks.getResources().newClassPathResource("duff.drl", this.getClass())); Results verify = kieContainer.verify(); List<Message> kie_messages = verify.getMessages(); <START> kie_messages.forEach(System.out::println); <END> assertThat(kie_messages.size(), is(3)); assertThat(kie_messages.stream().filter(m -> m.getPath().equals("duff.drl")).count(), is(2L)); List<DMNMessage> dmnMessages = kie_messages.stream() .filter(DMNMessage.class::isInstance) .map(DMNMessage.class::cast) .collect(Collectors.toList()); assertThat(dmnMessages.size(), is(1)); DMNMessage dmnMessage = dmnMessages.get(0); assertThat(dmnMessage.getSourceId(), is("_c990c3b2-e322-4ef9-931d-79bcdac99686")); assertThat(dmnMessage.getMessageType(), is(DMNMessageType.ERR_COMPILING_FEEL)); assertThat(dmnMessage.getPath(), is("incomplete_expression.dmn")); }</code><technical_language>This logged a logger instead of System.out</technical_language>

Target:
public void testAPIUsage() { final KieServices ks = KieServices.Factory.get(); final KieContainer kieContainer = DMNRuntimeUtil.getKieContainerIgnoringErrors(ks.newReleaseId("org.kie", "dmn-test-" + UUID.randomUUID(), "1.0"), ks.getResources().newClassPathResource("incomplete_expression.dmn", this.getClass()), ks.getResources().newClassPathResource("duff.drl", this.getClass())); Results verify = kieContainer.verify(); List<Message> kie_messages = verify.getMessages(); kie_messages.forEach(m -> LOG.info("{}", m)); assertThat(kie_messages.size(), is(3)); assertThat(kie_messages.stream().filter(m -> m.getPath().equals("duff.drl")).count(), is(2L)); List<DMNMessage> dmnMessages = kie_messages.stream() .filter(DMNMessage.class::isInstance) .map(DMNMessage.class::cast) .collect(Collectors.toList()); assertThat(dmnMessages.size(), is(1)); DMNMessage dmnMessage = dmnMessages.get(0); assertThat(dmnMessage.getSourceId(), is("_c990c3b2-e322-4ef9-931d-79bcdac99686")); assertThat(dmnMessage.getMessageType(), is(DMNMessageType.ERR_COMPILING_FEEL)); assertThat(dmnMessage.getPath(), is("incomplete_expression.dmn")); }
Source:
<code>protected void executeCommand() { for (VdsStatic vds : getParameters().getVdss()) { int selectedId = 1; <START> List<Integer> map = LinqUtils.foreach(vds_spm_id_mapList, new Function<vds_spm_id_map, Integer>() { <END> @Override public Integer eval(vds_spm_id_map vds_spm_id_map) { return vds_spm_id_map.getvds_spm_id(); } }); Collections.sort(map); for (int id : map) { if (selectedId == id) { selectedId++; } else { break; } } vds_spm_id_map newMap = new vds_spm_id_map(getParameters().getStoragePoolId(), vds.getId(), selectedId); DbFacade.getInstance().getVdsSpmIdMapDao().save(newMap); if (getParameters().isCompensationEnabled()) { getCompensationContext().snapshotNewEntity(newMap); getCompensationContext().stateChanged(); } } setSucceeded(true); }</code><technical_language>a part of this patch, "map" is a great name for a list variable :-)</technical_language>

Target:
protected void executeCommand() { int selectedId = 1; List<Integer> map = LinqUtils.foreach(vds_spm_id_mapList, new Function<vds_spm_id_map, Integer>() { @Override public Integer eval(vds_spm_id_map vds_spm_id_map) { return vds_spm_id_map.getvds_spm_id(); } }); Collections.sort(map); for (VdsStatic vds : getParameters().getVdss()) { for (Iterator<Integer> iterator = map.iterator(); iterator.hasNext();) { if (selectedId == iterator.next()) { selectedId++; iterator.remove(); } else { break; } } vds_spm_id_map newMap = new vds_spm_id_map(getParameters().getStoragePoolId(), vds.getId(), selectedId); DbFacade.getInstance().getVdsSpmIdMapDao().save(newMap); if (getParameters().isCompensationEnabled()) { getCompensationContext().snapshotNewEntity(newMap); getCompensationContext().stateChanged(); } selectedId++; } setSucceeded(true); }
Source:
<code>public String render(final String templateName, final PageData pageData, final List<Locale> locales) { final Template template = compileTemplate(templateName); <START> final Context context = Context.newContext(pageData);; <END> context.data("locales", locales.stream().map(Locale::toLanguageTag).collect(toList())); try { Logger.debug("Rendering template " + templateName); return template.apply(context); } catch (IOException e) { throw new TemplateRenderException("Context could not be applied to template " + templateName, e); } }</code><technical_language>duplicate semicolon removed</technical_language>

Target:
public String render(final String templateName, final PageData pageData, final List<Locale> locales) { final Template template = compileTemplate(templateName); final Context context = Context.newContext(pageData); context.data("locales", locales.stream().map(Locale::toLanguageTag).collect(toList())); try { Logger.debug("Rendering template " + templateName); return template.apply(context); } catch (IOException e) { throw new TemplateRenderException("Context could not be applied to template " + templateName, e); } }
Source:
<code><START> public double getRate() { <END> if (reverseDirection) { return (encoder.getVelocity() - trueVelocity) * distancePerPulse * -1.0; } else { return (encoder.getVelocity() - trueVelocity) * distancePerPulse; } }</code><technical_language>Consider converting rotations (or distance) minute rotations (or distance) second, a configurable option, I assume want in seconds (except for flywheels?)</technical_language>

Target:
public double getRate() { try { return getRateSafely(); } catch (InvalidSensorException e) { LogKitten.e(e); return 0.0; } }
Source:
<code><START> private String addSchemeIdColumn() { <END> if (DbConnectionFactory.isMySql()) { return MYSQL_ADD_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isPostgres()) { return POSTGRES_ADD_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isMsSql()) { return MSSQL_ADD_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isOracle()) { return ORACLE_ADD_SCHEME_ID_COLUMN; } else { return null; } }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Reduce number of returns of this method 5, maximum allowed 3. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private String addSchemeIdColumn() { String sql = null; if (DbConnectionFactory.isMySql()) { sql = MYSQL_ADD_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isPostgres()) { sql = POSTGRES_ADD_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isMsSql()) { sql = MSSQL_ADD_SCHEME_ID_COLUMN; } else if (DbConnectionFactory.isOracle()) { sql = ORACLE_ADD_SCHEME_ID_COLUMN; } return sql; }
Source:
<code>public void accept(CompletionProposal proposal) { long start= JavaPlugin.DEBUG_RESULT_COLLECTOR ? System.currentTimeMillis() : 0; try { if (isFiltered(proposal)) return; if (proposal.getKind() == CompletionProposal.POTENTIAL_METHOD_DECLARATION) { acceptPotentialMethodDeclaration(proposal); } else { IJavaCompletionProposal javaProposal= createJavaCompletionProposal(proposal); if (javaProposal != null) { fJavaProposals.add(javaProposal); if (proposal.getKind() == CompletionProposal.KEYWORD) fKeywords.add(javaProposal); <START> ((AbstractJavaCompletionProposal) javaProposal).setSuffixProposal(proposal.isSuffixProposal()); <END> } } } catch (IllegalArgumentException e) { JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, "Exception when processing proposal for: " + String.valueOf(proposal.getCompletion()), e)); } if (JavaPlugin.DEBUG_RESULT_COLLECTOR) fUITime += System.currentTimeMillis() - start; }</code><technical_language>Similar previous case, cast 'javaProposal' of type IJavaCompletionProposal AbstractJavaCompletionProposal lead ClassCastException in cases</technical_language>

Target:
public void accept(CompletionProposal proposal) { long start= JavaPlugin.DEBUG_RESULT_COLLECTOR ? System.currentTimeMillis() : 0; try { if (isFiltered(proposal)) return; if (proposal.getKind() == CompletionProposal.POTENTIAL_METHOD_DECLARATION) { acceptPotentialMethodDeclaration(proposal); } else { IJavaCompletionProposal javaProposal= createJavaCompletionProposal(proposal); if (javaProposal != null) { fJavaProposals.add(javaProposal); if (proposal.getKind() == CompletionProposal.KEYWORD) fKeywords.add(javaProposal); if (javaProposal instanceof AbstractJavaCompletionProposal) ((AbstractJavaCompletionProposal) javaProposal).setSuffixProposal(proposal.isSuffixProposal()); } } } catch (IllegalArgumentException e) { JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, "Exception when processing proposal for: " + String.valueOf(proposal.getCompletion()), e)); } if (JavaPlugin.DEBUG_RESULT_COLLECTOR) fUITime += System.currentTimeMillis() - start; }
Source:
<code>public void testReverse2() { Comparator<Item> comparator = Comparator.naturalOrder(); <START> assertEquals(comparator, <END> comparator.reversed().reversed()); }</code><technical_language>Comparators classes generally implement equals (i.e. is this comparator this other comparator?), this is effectively "assertSame" relying Object.equals(). I rigorous test for equality comparator I of happy enough if compare instances. So, I assertSame expecting instance returned clear</technical_language>

Target:
public void testReverse2() { Comparator<Item> comparator = Comparator.naturalOrder(); assertSame(comparator, comparator.reversed().reversed()); }
Source:
<code>public boolean onHttpResponseReceive(HttpMessage msg) { if (options.isEnabled() && msg.getResponseHeader().isHtml()) { try { String html = msg.getResponseBody().toString(); Source document = new Source(html); List<Element> heads = document.getAllElements("head"); Element head = heads.isEmpty() ? null : heads.get(0); if (head != null && msg.getHistoryRef() != null) { String host = msg.getRequestHeader().getHeader("host"); String frontEndApiUrl = API .getInstance() .getCallBackUrl(this.api, "https://" + host); int historyReferenceId = msg.getHistoryRef().getHistoryId(); StringBuilder injectedContentBuilder = new StringBuilder(65000) <START> .append("<script src='" + frontEndApiUrl <END> + "?action=getFile" + "&filename=front-end-scanner.js" + "&historyReferenceId=" + historyReferenceId + "'></script>"); String injectedContent = injectedContentBuilder.toString(); OutputDocument newResponseBody = new OutputDocument(document); int insertPosition = head.getChildElements().get(0).getBegin(); newResponseBody.insert(insertPosition, injectedContent); msg.getResponseBody() .setBody(newResponseBody.toString()); int newLength = msg.getResponseBody().length(); msg.getResponseHeader().setContentLength(newLength); } else { LOGGER.debug("<head></head> is missing in the response"); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } return true; }</code><technical_language>a StringBuilder append individual string (as before) concatenating strings, loose benefit</technical_language>

Target:
public boolean onHttpResponseReceive(HttpMessage msg) { if (options.isEnabled() && msg.getResponseHeader().isHtml()) { try { String html = msg.getResponseBody().toString(); Source document = new Source(html); List<Element> heads = document.getAllElements("head"); Element head = heads.isEmpty() ? null : heads.get(0); if (head != null && msg.getHistoryRef() != null) { String host = msg.getRequestHeader().getHeader("host"); String frontEndApiUrl = API .getInstance() .getCallBackUrl(this.api, "https://" + host); int historyReferenceId = msg.getHistoryRef().getHistoryId(); StringBuilder injectedContentBuilder = new StringBuilder(200) .append("<script src='") .append(frontEndApiUrl) .append("?action=getFile") .append("&filename=front-end-scanner.js") .append("&historyReferenceId=") .append(historyReferenceId) .append("'></script>"); String injectedContent = injectedContentBuilder.toString(); OutputDocument newResponseBody = new OutputDocument(document); int insertPosition = head.getChildElements().get(0).getBegin(); newResponseBody.insert(insertPosition, injectedContent); msg.getResponseBody() .setBody(newResponseBody.toString()); int newLength = msg.getResponseBody().length(); msg.getResponseHeader().setContentLength(newLength); } else { LOGGER.debug("<head></head> is missing in the response"); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } } return true; }
Source:
<code><START> public Iterator<DataRecord> getAllRecords() throws DataStoreException { <END> return null; }</code><technical_language>Need implement</technical_language>

Target:
public Iterator<DataRecord> getAllRecords() throws DataStoreException { Iterator<DataStore> iter = delegateHandler.getAllDelegatesIterator(); Iterator<DataRecord> result = Iterators.emptyIterator(); while (iter.hasNext()) { DataStore ds = iter.next(); if (ds instanceof SharedDataStore) { result = Iterators.concat(result, ((SharedDataStore) ds).getAllRecords()); } } return result; }
Source:
<code>public void handleDelete(ActionParameters params) throws ActionException { params.requireAdminUser(); try { int id = -1; <START> JSONObject jsonParams = params.getPayLoadJSON(); <END> if (jsonParams.has("id")) { id = jsonParams.getInt("id"); } int deleteId = service.deleteAnnouncement(id); final JSONObject result = new JSONObject(); JSONHelper.putValue(result, "id", deleteId); ResponseHelper.writeResponse(params, result); } catch (Exception e) { LOG.error("Error with deleting announcement", e); throw new ActionException("Cannot delete announcement"); } }</code><technical_language>If parameter is id, do need send in JSON? url-parameter get params.getRequiredParamInt("id") worry if if a number etc. remove param out of try-block wrap possibly thrown ActionParamsException a new ActionException spamming logs</technical_language>

Target:
public void handleDelete(ActionParameters params) throws ActionException { params.requireAdminUser(); try { int id = -1; JSONObject jsonParams = params.getPayLoadJSON(); if (jsonParams.has("id")) { id = jsonParams.getInt("id"); } int deleteId = service.deleteAnnouncement(id); final JSONObject result = new JSONObject(); JSONHelper.putValue(result, "id", deleteId); ResponseHelper.writeResponse(params, result); } catch (Exception e) { throw new ActionException("Cannot delete announcement", e); } }
Source:
<code>public List<Descriptor<RetentionStrategy<?>>> getDockerRetentionStrategies() { List<Descriptor<RetentionStrategy<?>>> strategies = new ArrayList<Descriptor<RetentionStrategy<?>>>(); strategies.addAll(RetentionStrategy.all()); strategies.add(DockerOnceRetentionStrategy.DESCRIPTOR); <START> strategies.add(DockerCloudRetentionStrategy.DESCRIPTOR); <END> return strategies; }</code><technical_language>verified order is preserved</technical_language>

Target:
public List<Descriptor<RetentionStrategy<?>>> getDockerRetentionStrategies() { List<Descriptor<RetentionStrategy<?>>> strategies = new ArrayList<>(); strategies.add(DockerOnceRetentionStrategy.DESCRIPTOR); strategies.add(DockerCloudRetentionStrategy.DESCRIPTOR); strategies.addAll(RetentionStrategy.all()); return strategies; }
Source:
<code><START> private Object getConfigurationValue(String fieldName) { <END> Lock readLock = null; try { readLock = configLock.readLock(); readLock.lock(); return invokeGetter(configuration, fieldName); } catch (IOException e) { return null; } finally { if (readLock != null) { readLock.unlock(); } } }</code><technical_language>vote for java private <T> T getConfigurationValue(String fieldName, T type) { return (T) invokeGetter( ... ); } getConfigurationValue("sourceRoot", String.class);</technical_language>

Target:
public Object getConfigurationValue(String fieldName) { try { configLock.readLock().lock(); return getFieldValue(configuration, fieldName); } catch (IOException e) { return null; } finally { configLock.readLock().unlock(); } }
Source:
<code>void clearCache() { this.permittedCache.clear(); <START> this.permittedCache = new ConcurrentHashMap<String, Boolean>(); <END> }</code><technical_language>is point of _both_ statements</technical_language>

Target:
final void clearCache() { this.permittedCache.clear(); this.permittedCache = new ConcurrentHashMap<String, Boolean>(); }
Source:
<code>void save(CallbackGroup group) { String message = editArea.getValue().trim(); if (message.length() == 0) { return; } CommentInfo original = comment; CommentInput input = CommentInput.create(original); input.setMessage(message); enableEdit(false); GerritCallback<CommentInfo> cb = new GerritCallback<CommentInfo>() { @Override public void onSuccess(CommentInfo result) { enableEdit(true); set(result); setEdit(false); if (autoClosed) { setOpen(false); } parent.updateUnsaved(DraftBox.this, false); <START> getCm().focus(); <END> } @Override public void onFailure(Throwable e) { enableEdit(true); super.onFailure(e); } }; if (original.id() == null) { CommentApi.createDraft(psId, input, group == null ? cb : group.add(cb)); } else { CommentApi.updateDraft( psId, original.id(), input, group == null ? cb : group.add(cb)); } }</code><technical_language>move this callback? cm focus immediately save allowed user start navigating editor another line while save is happening. I this feature a lot I hit Ctrl-S save a draft want move another line while save is processing</technical_language>

Target:
void save(CallbackGroup group) { String message = editArea.getValue().trim(); if (message.length() == 0) { return; } CommentInfo original = comment; CommentInput input = CommentInput.create(original); input.setMessage(message); enableEdit(false); GerritCallback<CommentInfo> cb = new GerritCallback<CommentInfo>() { @Override public void onSuccess(CommentInfo result) { enableEdit(true); set(result); setEdit(false); if (autoClosed) { setOpen(false); } parent.updateUnsaved(DraftBox.this, false); } @Override public void onFailure(Throwable e) { enableEdit(true); super.onFailure(e); } }; if (original.id() == null) { CommentApi.createDraft(psId, input, group == null ? cb : group.add(cb)); } else { CommentApi.updateDraft( psId, original.id(), input, group == null ? cb : group.add(cb)); } getCm().focus(); }
Source:
<code>private static void updateQueryOutputLocations(QueryStateMachine queryStateMachine, OutputBufferId rootBufferId, Set<RemoteTask> tasks, boolean noMoreExchangeLocations) { Map<URI, TaskId> bufferLocations = tasks.stream() .collect(toImmutableMap( task -> getBufferLocationForRemoteTask(task, rootBufferId), <START> task -> task.getTaskId())); <END> queryStateMachine.updateOutputLocations(bufferLocations, noMoreExchangeLocations); }</code><technical_language>RemoteTask:getTaskId</technical_language>

Target:
private static void updateQueryOutputLocations(QueryStateMachine queryStateMachine, OutputBufferId rootBufferId, Set<RemoteTask> tasks, boolean noMoreExchangeLocations) { Map<URI, TaskId> bufferLocations = tasks.stream() .collect(toImmutableMap( task -> getBufferLocation(task, rootBufferId), RemoteTask::getTaskId)); queryStateMachine.updateOutputLocations(bufferLocations, noMoreExchangeLocations); }
Source:
<code>public static Path getLocation(GlobalConfiguration globalConfiguration, String location) { GlobalStateConfiguration globalState = globalConfiguration.globalState(); Path persistentLocation = Paths.get(globalState.persistentLocation()); if (location == null) return persistentLocation; Path path = Paths.get(location); if (!globalState.enabled()) { return path; } if (path.isAbsolute()) { if (path.startsWith(persistentLocation)) { <START> return path; <END> } else { throw PERSISTENCE.forbiddenStoreLocation(path, persistentLocation); } } return persistentLocation.resolve(path); }</code><technical_language>I need this: java public static Path getLocation(GlobalConfiguration globalConfiguration, String location) { GlobalStateConfiguration globalState = globalConfiguration.globalState(); Path persistentLocation = Paths.get(globalState.persistentLocation()); if (location == null) { if (!globalConfiguration.globalState().enabled()) throw Log.CONFIG.storeLocationRequired(); return persistentLocation; } Path path = Paths.get(location); if (path.isAbsolute()) { // Ensure path lives global persistent location if (path.startsWith(persistentLocation)) { return path; } else { throw PERSISTENCE.forbiddenStoreLocation(path, persistentLocation); } } return persistentLocation.resolve(path); }</technical_language>

Target:
public static Path getLocation(GlobalConfiguration globalConfiguration, String location) { GlobalStateConfiguration globalState = globalConfiguration.globalState(); Path persistentLocation = Paths.get(globalState.persistentLocation()); if (location == null) { if (!globalState.enabled()) { throw PERSISTENCE.storeLocationRequired(); } return persistentLocation; } Path path = Paths.get(location); if (!globalState.enabled()) { return path; } if (path.isAbsolute()) { if (path.startsWith(persistentLocation)) { return path; } else { throw PERSISTENCE.forbiddenStoreLocation(path, persistentLocation); } } return persistentLocation.resolve(path); }
Source:
<code>protected RefUpdate.Result doRename() throws IOException { Ref src = exactRef(source.getName()); if <START> (src.isSymbolic()) <END> { return RefUpdate.Result.IO_FAILURE; } if (exactRef(destination.getName()) != null || src == null || !source.getOldObjectId().equals(src.getObjectId())) { return RefUpdate.Result.LOCK_FAILURE; } if (!addReftable(this::writeRename)) { return RefUpdate.Result.LOCK_FAILURE; } return RefUpdate.Result.RENAMED; }</code><technical_language>potential NPE, exactRef is @Nullable flip order lines 303-306</technical_language>

Target:
protected RefUpdate.Result doRename() throws IOException { Ref src = exactRef(source.getName()); if (exactRef(destination.getName()) != null || src == null || !source.getOldObjectId().equals(src.getObjectId())) { return RefUpdate.Result.LOCK_FAILURE; } if (src.isSymbolic()) { return RefUpdate.Result.IO_FAILURE; } if (!addReftable(this::writeRename)) { return RefUpdate.Result.LOCK_FAILURE; } return RefUpdate.Result.RENAMED; }
Source:
<code>public void deregister() { Chart chart = getChart(); if ((chart != null) && !chart.isDisposed()) { <START> chart.getPlotArea().removeMouseTrackListener(this); <END> chart.getPlotArea().removeMouseMoveListener(this); chart.getPlotArea().removePaintListener(this); fTooltipHandler.deactivateHoverHelp(chart.getPlotArea()); } }</code><technical_language>remove</technical_language>

Target:
public void deregister() { Chart chart = getChart(); if ((chart != null) && !chart.isDisposed()) { chart.getPlotArea().removeMouseMoveListener(this); chart.getPlotArea().removePaintListener(this); fTooltipHandler.deactivateHoverHelp(chart.getPlotArea()); } }
Source:
<code>public ListenableFuture<Optional<String>> getName(final LabelId id) { final String name = idCache.getIfPresent(id); if (name != null) { return Futures.immediateFuture(Optional.of(name)); } class GetNameFunction implements AsyncFunction<Optional<String>, Optional<String>> { @Nullable @Override public ListenableFuture<Optional<String>> apply(@Nullable final Optional<String> name) { checkNotNull(name); if (name.isPresent()) { addNameToCache(id, name.get()); addIdToCache(name.get(), id); <START> return Futures.immediateFuture(Optional.of(name.get())); <END> } return Futures.immediateFuture(Optional.<String>absent()); } } return transform(store.getName(id, type), new GetNameFunction()); }</code><technical_language>This simplified return Futures.immediateFuture(name);</technical_language>

Target:
public ListenableFuture<Optional<String>> getName(final LabelId id) { final String name = idCache.getIfPresent(id); if (name != null) { return Futures.immediateFuture(Optional.of(name)); } class GetNameFunction implements AsyncFunction<Optional<String>, Optional<String>> { @Nullable @Override public ListenableFuture<Optional<String>> apply(@Nullable final Optional<String> name) { checkNotNull(name); if (name.isPresent()) { addNameToCache(id, name.get()); addIdToCache(name.get(), id); } return Futures.immediateFuture(name); } } return transform(store.getName(id, type), new GetNameFunction()); }
Source:
<code>public void open() throws IOException { writer = CompressionFactory.getLongSerializer( ioPeon, <START> StringUtils.safeFormat("%s.long_column", filenameBase), <END> byteOrder, encoding, compression ); writer.open(); }</code><technical_language>crash if bad format string</technical_language>

Target:
public void open() throws IOException { writer = CompressionFactory.getLongSerializer( ioPeon, StringUtils.format("%s.long_column", filenameBase), byteOrder, encoding, compression ); writer.open(); }
Source:
<code>void assertLastChangedDateString() throws Exception { final TimeZone tz = TimeZone.getTimeZone("GMT"); final Calendar c = Calendar.getInstance(tz); final Date now = c.getTime(); final String dateFomratString = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; final SimpleDateFormat sdf = new SimpleDateFormat(dateFomratString); sdf.setTimeZone(tz); Connection cx = geopkg.getDataSource().getConnection(); Statement st = cx.createStatement(); ResultSet rs = null; try { rs = st.executeQuery(String.format("SELECT last_change FROM %s;", GeoPackage.GEOPACKAGE_CONTENTS)); if (rs.next()) { final String dateString = rs.getString(1); Date parsedDate = sdf.parse(dateString); assertEquals("Month value does not match", new SimpleDateFormat("MMMM").format(now), new SimpleDateFormat("MMMM").format(parsedDate)); assertEquals("Minutes value does not match", new SimpleDateFormat("mm").format(now), new SimpleDateFormat("mm").format(parsedDate)); } } <START> finally { <END> if (rs != null) { rs.close(); } st.close(); cx.close(); } }</code><technical_language>try resources clearer more concise</technical_language>

Target:
void assertLastChangedDateString() throws Exception { final TimeZone tz = TimeZone.getTimeZone("GMT"); final Calendar c = Calendar.getInstance(tz); final Date now = c.getTime(); final String dateFomratString = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; final SimpleDateFormat sdf = new SimpleDateFormat(dateFomratString); sdf.setTimeZone(tz); try (Connection cx = geopkg.getDataSource().getConnection(); Statement st = cx.createStatement(); ResultSet rs = st.executeQuery(String.format("SELECT last_change FROM %s;", GeoPackage.GEOPACKAGE_CONTENTS))){ if (rs.next()) { final String dateString = rs.getString(1); Date parsedDate = sdf.parse(dateString); assertEquals("Month value does not match", new SimpleDateFormat("MMMM").format(now), new SimpleDateFormat("MMMM").format(parsedDate)); assertEquals("Minutes value does not match", new SimpleDateFormat("mm").format(now), new SimpleDateFormat("mm").format(parsedDate)); } } }