auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void testAccessControl_instructorSubmitStudentResponseNoPermission_inaccessible() { <START> ______TS("Student intends to access own response, but logged in as instructor without permission, " <END> + "should be inaccessible"); InstructorAttributes helperOfCourse1 = typicalBundle.instructors.get("helperOfCourse1"); loginAsInstructor(helperOfCourse1.getGoogleId()); assertEquals(student1InCourse1.getEmail(), student1ResponseToStudent1.getGiver()); FeedbackResponseUpdateRequest updateRequest = getUpdateRequest(student1ResponseToStudent1.getRecipient()); String[] studentAccessOwnPersonParams = new String[] { Const.ParamsNames.INTENT, Intent.STUDENT_SUBMISSION.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_ID, student1ResponseToStudent1.getId(), Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON, student1InCourse1.getEmail(), }; verifyCannotAccess(updateRequest, studentAccessOwnPersonParams); }</code><technical_language>suggestion ______TS("Instructor attempts edit student's response, permission, "</technical_language>

Target:
protected void testAccessControl_instructorSubmitStudentResponseNoPermission_inaccessible() { ______TS("Instructor attempts to edit student's response, but without appropriate permission, " + "should be inaccessible"); InstructorAttributes helperOfCourse1 = typicalBundle.instructors.get("helperOfCourse1"); loginAsInstructor(helperOfCourse1.getGoogleId()); assertEquals(student1InCourse1.getEmail(), student1ResponseToStudent1.getGiver()); FeedbackResponseUpdateRequest updateRequest = getUpdateRequest(student1ResponseToStudent1.getRecipient()); String[] studentAccessOwnPersonParams = new String[] { Const.ParamsNames.INTENT, Intent.STUDENT_SUBMISSION.toString(), Const.ParamsNames.FEEDBACK_RESPONSE_ID, student1ResponseToStudent1.getId(), Const.ParamsNames.FEEDBACK_SESSION_MODERATED_PERSON, student1InCourse1.getEmail(), }; verifyCannotAccess(updateRequest, studentAccessOwnPersonParams); }
Source:
<code>private Map<String, CacheNode> addDuplicateOfOutdatedDescendents(@Nonnull final String key, @Nonnull final Map<String, CacheNode> updatedNodesMap) { <START> for (final String child : cgs.getAllDescendentsMap().get(key)) { <END> CacheNode oldChild = nodesMap.get(child); updatedNodesMap.put(child, ((ComputableCacheNode)oldChild).duplicateWithUpdatedCacheStatus(false)); } return updatedNodesMap; }</code><technical_language>child -> descendant for clarity</technical_language>

Target:
private Map<String, CacheNode> addDuplicateOfOutdatedDescendents(@Nonnull final String key, @Nonnull final Map<String, CacheNode> updatedNodesMap) { for (final String descendant : cgs.getAllDescendents(key)) { CacheNode oldDescendant = nodesMap.get(descendant); updatedNodesMap.put(descendant, ((ComputableCacheNode)oldDescendant).duplicateWithOutdatedCacheStatus()); } return updatedNodesMap; }
Source:
<code><START> private void makeRequestAndVerify(String headerName, String headerValue, String username) { <END> WebRequest req = new WebRequest(new URL(j.getURL(),"test")); req.setEncodingType(null); if (headerValue!=null) req.setAdditionalHeader(headerName, headerValue); Page p = wc.getPage(req); assertEquals(username, p.getWebResponse().getContentAsString().trim()); }</code><technical_language>needs declare IOException, MalformedURLException (PR build failure)</technical_language>

Target:
private void makeRequestAndVerify(String headerName, String headerValue, String username) throws IOException, SAXException { WebRequest req = new WebRequest(new URL(j.getURL(),"test")); req.setEncodingType(null); if (headerValue!=null) req.setAdditionalHeader(headerName, headerValue); Page p = wc.getPage(req); assertEquals(username, p.getWebResponse().getContentAsString().trim()); }
Source:
<code>public byte[] getCacheKey() { if (cacheKey == null) { <START> final boolean hasNull = values.stream().anyMatch(Objects::isNull); <END> final List<String> sortedValues = new ArrayList<>(values); Collections.sort(sortedValues); final Hasher hasher = Hashing.sha256().newHasher(); sortedValues.forEach(v -> { if (v == null) { hasher.putInt(0); } else { hasher.putString(v, StandardCharsets.UTF_8); } }); cacheKey = new CacheKeyBuilder(DimFilterUtils.IN_CACHE_ID) .appendString(dimension) .appendByte(DimFilterUtils.STRING_SEPARATOR) .appendByteArray(extractionFn == null ? new byte[0] : extractionFn.getCacheKey()) .appendByte(DimFilterUtils.STRING_SEPARATOR) .appendByte(hasNull ? NullHandling.IS_NULL_BYTE : NullHandling.IS_NOT_NULL_BYTE) .appendByte(DimFilterUtils.STRING_SEPARATOR) .appendByteArray(hasher.hash().asBytes()) .build(); } return cacheKey; }</code><technical_language>If values is a set, I determine hasNull if scanned values for empty/nulls, avoid scanning</technical_language>

Target:
public byte[] getCacheKey() { if (cacheKey == null) { final List<String> sortedValues = new ArrayList<>(values); sortedValues.sort(Comparator.nullsFirst(Ordering.natural())); final Hasher hasher = Hashing.sha256().newHasher(); for (String v : sortedValues) { if (v == null) { hasher.putInt(0); } else { hasher.putString(v, StandardCharsets.UTF_8); } } cacheKey = new CacheKeyBuilder(DimFilterUtils.IN_CACHE_ID) .appendString(dimension) .appendByte(DimFilterUtils.STRING_SEPARATOR) .appendByteArray(extractionFn == null ? new byte[0] : extractionFn.getCacheKey()) .appendByte(DimFilterUtils.STRING_SEPARATOR) .appendByteArray(hasher.hash().asBytes()) .build(); } return cacheKey; }
Source:
<code>public File getIndexingTmpDir() { <START> return new File(taskWorkDir, "firehose"); <END> }</code><technical_language>rename temporary directory</technical_language>

Target:
public File getIndexingTmpDir() { return new File(taskWorkDir, "indexing-tmp"); }
Source:
<code>public Collection<? extends Action> getProjectActions() { <START> return this.projectActions; <END> }</code><technical_language>wrapped Collections.unmodifyableList(). FindBugs start grumbling if set a threshold</technical_language>

Target:
public Collection<? extends Action> getProjectActions() { buildProjectActions(); return Collections.unmodifiableList(this.projectActions); }
Source:
<code>public final String readUTF() throws IOException { int numberOfBytes = readInt(); if (numberOfBytes == NULL_ARRAY_LENGTH) { return null; } <START> checkAvailable(pos, numberOfBytes); <END> String result = new String(data, pos, numberOfBytes, UTF_8); pos += numberOfBytes; return result; }</code><technical_language>bounds check is done String constructor. check if this line is necessary</technical_language>

Target:
public final String readUTF() throws IOException { int numberOfBytes = readInt(); if (numberOfBytes == NULL_ARRAY_LENGTH) { return null; } String result = new String(data, pos, numberOfBytes, UTF_8); pos += numberOfBytes; return result; }
Source:
<code>protected RowExpression visitInPredicate(InPredicate node, Void context) { ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder(); <START> RowExpression lhs = process(node.getValue(), context); <END> InListExpression values = (InListExpression) node.getValueList(); if (values.getValues().size() == 1) { return buildEquals(lhs, process(values.getValues().get(0), context)); } arguments.add(lhs); for (Expression value : values.getValues()) { arguments.add(process(value, context)); } return specialForm(IN, BOOLEAN, arguments.build()); }</code><technical_language>lhs -></technical_language>

Target:
protected RowExpression visitInPredicate(InPredicate node, Void context) { ImmutableList.Builder<RowExpression> arguments = ImmutableList.builder(); RowExpression value = process(node.getValue(), context); InListExpression values = (InListExpression) node.getValueList(); if (values.getValues().size() == 1) { return buildEquals(value, process(values.getValues().get(0), context)); } arguments.add(value); for (Expression inValue : values.getValues()) { arguments.add(process(inValue, context)); } return specialForm(IN, BOOLEAN, arguments.build()); }
Source:
<code>protected void loadBlocksToOutputStream(Transaction t, Long streamId, long firstBlock, long numBlocks, OutputStream os) { try { BiMap<SnapshotsStreamValueTable.SnapshotsStreamValueRow, Long> blockRows = KeyedStream.of( LongStream.rangeClosed(firstBlock, firstBlock + numBlocks).boxed()) .mapKeys(blockId -> SnapshotsStreamValueTable.SnapshotsStreamValueRow.of(streamId, blockId)) .collectTo(HashBiMap::create); Map<SnapshotsStreamValueTable.SnapshotsStreamValueRow, byte[]> blocks = getBlocks(t, blockRows.keySet()); for (long i = 0; i < numBlocks; i++) { <START> os.write(blocks.get(blockRows.inverse().get(firstBlock + 1))); <END> } } catch (RuntimeException e) { log.error("Error loading blocks for stream", SafeArg.of("firstBlock", firstBlock), SafeArg.of("numBlocks", numBlocks), SafeArg.of("streamId", streamId), e); throw e; } catch (IOException e) { log.error("Error writing blocks to output stream", SafeArg.of("firstBlock", firstBlock), SafeArg.of("numBlocks", numBlocks), SafeArg.of("streamId", streamId), e); throw Throwables.rewrapAndThrowUncheckedException("Error writing blocks to output stream.", e); } }</code><technical_language>Uhh, this wrong - this firstBlock + i rest?</technical_language>

Target:
protected void loadBlocksToOutputStream(Transaction t, Long streamId, long firstBlock, long numBlocks, OutputStream os) { try { BiMap<SnapshotsStreamValueTable.SnapshotsStreamValueRow, Long> blockRows = KeyedStream.of( LongStream.range(firstBlock, firstBlock + numBlocks).boxed()) .mapKeys(blockId -> SnapshotsStreamValueTable.SnapshotsStreamValueRow.of(streamId, blockId)) .collectTo(HashBiMap::create); Map<SnapshotsStreamValueTable.SnapshotsStreamValueRow, byte[]> blocks = getBlocks(t, blockRows.keySet()); for (long i = 0; i < numBlocks; i++) { os.write(blocks.get(blockRows.inverse().get(firstBlock + i))); } } catch (RuntimeException e) { log.error("Error loading blocks for stream", SafeArg.of("firstBlock", firstBlock), SafeArg.of("numBlocks", numBlocks), SafeArg.of("streamId", streamId), e); throw e; } catch (IOException e) { log.error("Error writing blocks to output stream", SafeArg.of("firstBlock", firstBlock), SafeArg.of("numBlocks", numBlocks), SafeArg.of("streamId", streamId), e); throw Throwables.rewrapAndThrowUncheckedException("Error writing blocks to output stream.", e); } }
Source:
<code>private void processCommandLine() throws ParseException, BadArgumentException { parseCommandLine(true); if (cmd.hasOption(TRACE.getLongOpt())) { setConsoleLogLevel(Level.TRACE); } else if (cmd.hasOption(DEBUG.getLongOpt())) { setConsoleLogLevel(Level.DEBUG); } else if (cmd.hasOption(VERBOSE.getLongOpt())) { setConsoleLogLevel(Level.INFO); } else { setConsoleLogLevel(Level.OFF); } if (cmd.hasOption(LOG_TRACE.getLongOpt())) { setFileLogLevel(Level.TRACE); } else if (cmd.hasOption(LOG_DEBUG.getLongOpt())) { setFileLogLevel(Level.DEBUG); } else if (cmd.hasOption(LOG_VERBOSE.getLongOpt())) { setFileLogLevel(Level.INFO); } else { setFileLogLevel(Level.OFF); } <START> if (cmd.hasOption(PRINT_HELP.getOpt())) { <END> this.printHelp(); System.exit(0); } if (cmd.hasOption(COMMAND_HELP.getLongOpt())) { setHelp(true); try { if (getHelp() == null) { this.printHelp(); System.exit(0); } return; } catch (final IllegalArgumentException e) { throw new BadArgumentException("Unknown command: " + getHelp() + "; use --help list_commands to get available commands.", e); } } if (cmd.hasOption(PRINT_VERSION.getLongOpt())) { this.printVersion(); System.exit(0); } try { if (getCommand() == null) { if (!isHelp()) { throw new MissingOptionException(COMMAND.getOpt()); } } } catch (final IllegalArgumentException e) { throw new BadArgumentException("Unknown command", e); } }</code><technical_language>pull cli behavior out of parsing, caller</technical_language>

Target:
private void processCommandLine() throws ParseException, BadArgumentException { parseRootCommands(); if (cmd.hasOption(TRACE.getLongOpt())) { setConsoleLogLevel(Level.TRACE); } else if (cmd.hasOption(DEBUG.getLongOpt())) { setConsoleLogLevel(Level.DEBUG); } else if (cmd.hasOption(VERBOSE.getLongOpt())) { setConsoleLogLevel(Level.INFO); } else { setConsoleLogLevel(Level.OFF); } if (cmd.hasOption(LOG_TRACE.getLongOpt())) { setFileLogLevel(Level.TRACE); } else if (cmd.hasOption(LOG_DEBUG.getLongOpt())) { setFileLogLevel(Level.DEBUG); } else if (cmd.hasOption(LOG_VERBOSE.getLongOpt())) { setFileLogLevel(Level.INFO); } else { setFileLogLevel(Level.OFF); } }
Source:
<code>public void validateOffsetsIfNeeded() { RuntimeException exception = cachedOffsetForLeaderException.getAndSet(null); if (exception != null) throw exception; int newMetadataUpdateVersion = metadata.updateVersion(); <START> if (metadataUpdateVersion.getAndSet(newMetadataUpdateVersion) != newMetadataUpdateVersion) { <END> subscriptions.forEachAssignedPartition(topicPartition -> { ConsumerMetadata.LeaderAndEpoch leaderAndEpoch = metadata.leaderAndEpoch(topicPartition); subscriptions.maybeValidatePositionForCurrentLeader(topicPartition, leaderAndEpoch); }); } Map<TopicPartition, SubscriptionState.FetchPosition> partitionsToValidate = subscriptions .partitionsNeedingValidation(time.milliseconds()) .stream() .collect(Collectors.toMap(Function.identity(), subscriptions::position)); validateOffsetsAsync(partitionsToValidate); }</code><technical_language>logic in places, sense a method</technical_language>

Target:
public void validateOffsetsIfNeeded() { RuntimeException exception = cachedOffsetForLeaderException.getAndSet(null); if (exception != null) throw exception; maybeValidateAssignments(); Map<TopicPartition, SubscriptionState.FetchPosition> partitionsToValidate = subscriptions .partitionsNeedingValidation(time.milliseconds()) .stream() .collect(Collectors.toMap(Function.identity(), subscriptions::position)); validateOffsetsAsync(partitionsToValidate); }
Source:
<code>public static Results analyze(final WebDriver webDriver, final WebElement context) throws IOException, OperationNotSupportedException { if (webDriver == null) { throw new NullPointerException("the webDriver is null"); } if (context == null) { <START> throw new NullPointerException("the webDriver is null"); <END> } AxeBuilder axeBuilder = new AxeBuilder(); return axeBuilder.analyze(webDriver, context); }</code><technical_language>suggestion throw new NullPointerException("the context is null");</technical_language>

Target:
public static Results analyze(final WebDriver webDriver, final WebElement context) throws IOException, OperationNotSupportedException { if (webDriver == null) { throw new NullPointerException("the webDriver is null"); } if (context == null) { throw new NullPointerException("the context is null"); } AxeBuilder axeBuilder = new AxeBuilder(); return axeBuilder.analyze(webDriver, context); }
Source:
<code>private ColumnChunkPageReader readChunk(SeekableInputStream f, ChunkDescriptor descriptor) throws IOException { f.seek(descriptor.fileOffset); int fullAllocations = descriptor.size / options.getMaxAllocationSize(); int lastAllocationSize = descriptor.size % options.getMaxAllocationSize(); int numAllocations = fullAllocations + (lastAllocationSize > 0 ? 1 : 0); List<ByteBuffer> buffers = new ArrayList<>(numAllocations); <START> for (int i = 0; i < fullAllocations; i += 1) { <END> buffers.add(options.getAllocator().allocate(options.getMaxAllocationSize())); } if (lastAllocationSize > 0) { buffers.add(options.getAllocator().allocate(lastAllocationSize)); } for (ByteBuffer buffer : buffers) { f.readFully(buffer); buffer.flip(); } ByteBufferInputStream stream = ByteBufferInputStream.wrap(buffers); Chunk chunk = new WorkaroundChunk(descriptor, stream.sliceBuffers(descriptor.size), f); return chunk.readAllPages(); }</code><technical_language>i++</technical_language>

Target:
private ColumnChunkPageReader readChunk(SeekableInputStream f, ChunkDescriptor descriptor) { try { List<ByteBuffer> buffers = readBlocks(f, descriptor.fileOffset, descriptor.size); ByteBufferInputStream stream = ByteBufferInputStream.wrap(buffers); Chunk chunk = new WorkaroundChunk(descriptor, stream.sliceBuffers(descriptor.size), f); return chunk.readAllPages(); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>public static @Nullable List<Long> extractTimeRequested(Map<String, Object> parameters) { Object timeRequestedObject = parameters.get(TIME_REQUESTED_KEY); if (timeRequestedObject instanceof List<?>) { List<Long> timeRequested = new ArrayList<>(); List<?> timeRequestedList = (List<?>) timeRequestedObject; <START> if (!timeRequestedList.isEmpty()) { if (timeRequestedList.get(0) instanceof Long) { timeRequested = (List<Long>) timeRequestedList; } else if (timeRequestedList.get(0) instanceof Integer) { for (Integer time : (List<Integer>) timeRequestedList) { timeRequested.add(time.longValue()); } } else { return null; } } <END> return timeRequested; } return null; }</code><technical_language>change to: if (!timeRequestedList.isEmpty()) { timeRequested = timeRequestedList.stream().filter(o -> o instanceof Integer || o instanceof Long).map(o -> (Long) o).collect(Collectors.toList()); if (timeRequested.isEmpty()) { return null; } }</technical_language>

Target:
public static @Nullable List<Long> extractTimeRequested(Map<String, Object> parameters) { Object timeRequestedObject = parameters.get(TIME_REQUESTED_KEY); if (timeRequestedObject instanceof List<?>) { return transformToLongList((List<?>) timeRequestedObject); } return null; }
Source:
<code>public void configure() { from("direct:start") .log("Querying dbpedia:Ecuador ") .to("<LINK_3>") .unmarshal() .any23(BASEURI) .process(new Processor() { public void process(Exchange exchange) throws Exception { ValueFactory vf = SimpleValueFactory.getInstance(); Model model = (Model) exchange.getIn().getBody(); IRI propertyLeader = vf.createIRI("<LINK_1>"); Set<Value> leadersResources = model.filter(null, propertyLeader, null).objects(); List<String> leadersList = new ArrayList<>(); for (Value leader : leadersResources) { String aLeader = leader.stringValue().replace("resource", "page"); leadersList.add(aLeader); } exchange.getIn().setBody(leadersList); } }) .log(" Content: ${body} ") .split(simple("${body}")) .to("direct:extractMoreData"); from("direct:extractMoreData") .log("Split ${body}") .convertBodyTo(String.class) .toD("${body}") .unmarshal() .any23(BASEURI, Any23Type.JSONLD) .log(" Result : ${body} ") <START> .to("mock:result"); <END> }</code><technical_language>mock endpoint is useless here. log:result better</technical_language>

Target:
public void configure() { from("direct:start") .log("Querying dbpedia:Ecuador ") .to("<LINK_3>") .unmarshal() .any23(BASEURI) .process(new Processor() { public void process(Exchange exchange) throws Exception { ValueFactory vf = SimpleValueFactory.getInstance(); Model model = exchange.getIn().getBody(Model.class); IRI propertyLeader = vf.createIRI("<LINK_1>"); Set<Value> leadersResources = model.filter(null, propertyLeader, null).objects(); List<String> leadersList = new ArrayList<>(); for (Value leader : leadersResources) { String aLeader = leader.stringValue().replace("resource", "page"); leadersList.add(aLeader); } exchange.getIn().setBody(leadersList); } }) .log(" Content: ${body} ") .split(simple("${body}")) .to("direct:extractMoreData"); from("direct:extractMoreData") .log("Split ${body}") .toD("${body}") .unmarshal() .any23(BASEURI, Any23Type.JSONLD) .log(" Result : ${body} ") .to("log:result"); }
Source:
<code><START> protected List<String> expectedContent(final Class<?> clazz) throws Exception { <END> List<String> expectedContentList = new ArrayList<>(); final TypeElement typeElement = compilationRule.getElements().getTypeElement(clazz.getCanonicalName()); final List<TypeSpec> typeSpecs = generator.generateTypes(typeElement); typeSpecs.forEach(typeSpec -> { final String typeName = typeSpec.name; final String fixtureFile = typeName + ".java.expected"; InputStream resourceAsStream = clazz.getResourceAsStream(fixtureFile); try { expectedContentList.add(IOUtils.toString(resourceAsStream, Charsets.UTF_8)); } catch (IOException e) { throw new IllegalStateException("Fixture file '" + fixtureFile + "' not found.", e); } }); return expectedContentList; }</code><technical_language>good idea return a list of expected content nicer if add a method AbstractMultipleGenerator returns ClassNames generate for a TypeElement. This avoid generate actual TypeSpecs here</technical_language>

Target:
protected List<String> expectedContent(final Class<?> clazz) throws Exception { List<String> expectedContentList = new ArrayList<>(); final TypeElement typeElement = compilationRule.getElements().getTypeElement(clazz.getCanonicalName()); final List<String> classNames = generator.expectedClassNames(typeElement); classNames.forEach(className -> { final String fixtureFile = className + ".java.expected"; InputStream resourceAsStream = clazz.getResourceAsStream(fixtureFile); try { expectedContentList.add(IOUtils.toString(resourceAsStream, Charsets.UTF_8)); } catch (IOException e) { throw new IllegalStateException("Fixture file '" + fixtureFile + "' not found.", e); } }); return expectedContentList; }
Source:
<code>public String getStringValue(int offset) { if (value == null || offset > value.length) { return null; } byte[] strBytes = new byte[value.length - offset]; <START> for (int i = 0; i != (value.length - offset); ++i) { <END> strBytes[i] = (byte) value[offset + i]; } return new String(strBytes); }</code><technical_language>i < ... is widely accepted way. happen exceed maximum, know..</technical_language>

Target:
public String getStringValue(int offset) { if (value == null || offset > value.length) { return null; } byte[] strBytes = new byte[value.length - offset]; for (int i = 0; i < (value.length - offset); ++i) { strBytes[i] = (byte) value[offset + i]; } return new String(strBytes, StandardCharsets.UTF_8); }
Source:
<code>public VdsNotRespondingTreatmentCommand(T parameters) { super(parameters); <START> mVmList.addAll(getVmDAO().getAllMigratingToHost(getVdsId())); <END> }</code><technical_language>is option move this ctor other place? execute? a feels related ctor</technical_language>

Target:
public VdsNotRespondingTreatmentCommand(T parameters) { super(parameters); }
Source:
<code>public void onBackPressed() { <START> retrieveLoginNavFragment().goBack(); <END> super.onBackPressed(); }</code><technical_language>retrieveLoginNavFragment return null, this throw NPE</technical_language>

Target:
public void onBackPressed() { getLoginNavFragmentOrThrow().goBack(); super.onBackPressed(); }
Source:
<code>private void initializeSession() { <START> mSession = (new Session.Builder(this, mApiKey, mSessionId).build()); <END> mSession.setSessionListener(this); mSession.connect(mToken); }</code><technical_language>I remove a pair of parens: mSession = new Session.Builder(this, mApiKey, mSessionId).build();</technical_language>

Target:
private void initializeSession() { mSession = new Session.Builder(this, mApiKey, mSessionId).build(); mSession.setSessionListener(this); mSession.connect(mToken); }
Source:
<code>private PushOneCommit.Result createChangeWithTopic(String topic) throws GitAPIException, IOException { PushOneCommit push = pushFactory.create(db, admin.getIdent()); <START> assertThat(!topic.isEmpty()); <END> return push.to(git, "refs/for/master/" + topic); }</code><technical_language>assertThat(topic).isNotEmpty();</technical_language>

Target:
private PushOneCommit.Result createChangeWithTopic(String topic) throws GitAPIException, IOException { PushOneCommit push = pushFactory.create(db, admin.getIdent()); assertThat(topic).isNotEmpty(); return push.to(git, "refs/for/master/" + topic); }
Source:
<code>public static String getCurrentURI(final HttpServletRequest request) { try { return URLDecoder.decode((request.getAttribute(Constants.CMS_FILTER_URI_OVERRIDE) != null) ? (String) request.getAttribute(Constants.CMS_FILTER_URI_OVERRIDE) : request.getRequestURI(), "UTF-8"); } catch (UnsupportedEncodingException e) { <START> throw new DotRuntimeException(e); <END> } }</code><technical_language>is worth add a Log.debug ? warning</technical_language>

Target:
public static String getCurrentURI(final HttpServletRequest request) { try { return URLDecoder.decode((request.getAttribute(CMS_FILTER_URI_OVERRIDE) != null) ? (String) request.getAttribute(CMS_FILTER_URI_OVERRIDE) : request.getRequestURI(), "UTF-8"); } catch (UnsupportedEncodingException e) { Logger.debug(CMSUrlUtil.class, e.getMessage(), e); throw new DotRuntimeException(e); } }
Source:
<code>private boolean isRunningFromCommandLine() { boolean runningFromCommandLine = false; Collection<? extends OptionProcessor> optionProcessors = Lookup.getDefault().lookupAll(OptionProcessor.class); Iterator<? extends OptionProcessor> optionsIterator = optionProcessors.iterator(); while (optionsIterator.hasNext()) { OptionProcessor processor = optionsIterator.next(); if (!(processor instanceof CommandLineOptionProcessor)) { continue; } runningFromCommandLine = ((CommandLineOptionProcessor) processor).isRunFromCommandLine(); return runningFromCommandLine; } return false; <START> } <END></code><technical_language>Codacy flagged this method for "Avoid a branching statement in a loop." I is a reasonable call Codacy code easier read if runningFromCommandLine set true in loop, a break, a single method return of runningFromCommandLine is currently line 136. Alternatively, do runningFromCommandLine a return true statement in loop, I alternative a easier read Codacy content</technical_language>

Target:
private boolean isRunningFromCommandLine() { Collection<? extends OptionProcessor> optionProcessors = Lookup.getDefault().lookupAll(OptionProcessor.class); Iterator<? extends OptionProcessor> optionsIterator = optionProcessors.iterator(); while (optionsIterator.hasNext()) { OptionProcessor processor = optionsIterator.next(); if ((processor instanceof CommandLineOptionProcessor)) { return ((CommandLineOptionProcessor) processor).isRunFromCommandLine(); } } return false; }
Source:
<code>public void readMarshallable(WireIn wireIn) throws IORuntimeException { String type = wireIn.read("type").text(); int protocolVersion = wireIn.read("protocol-version").int32(); QueryOptions queryOptions = QueryOptions.codec.decode(Unpooled.wrappedBuffer(wireIn.read("query-options").bytes()), ProtocolVersion.decode(protocolVersion)); long queryTime = wireIn.read("query-time").int64(); String keyspace = legacyFiles ? null : wireIn.read("keyspace").text(); switch (type) { case "single": String queryString = wireIn.read("query").text(); query = new FQLQuery.Single(keyspace, protocolVersion, queryOptions, queryTime, queryString, queryOptions.getValues()); break; case "batch": BatchStatement.Type batchType = BatchStatement.Type.valueOf(wireIn.read("batch-type").text()); ValueIn in = wireIn.read("queries"); int queryCount = in.int32(); List<String> queries = new ArrayList<>(queryCount); for (int i = 0; i < queryCount; i++) queries.add(in.text()); in = wireIn.read("values"); int valueCount = in.int32(); List<List<ByteBuffer>> values = new ArrayList<>(valueCount); for (int ii = 0; ii < valueCount; ii++) { List<ByteBuffer> subValues = new ArrayList<>(); values.add(subValues); int numSubValues = in.int32(); for (int zz = 0; zz < numSubValues; zz++) <START> { <END> subValues.add(ByteBuffer.wrap(in.bytes())); } } query = new FQLQuery.Batch(keyspace, protocolVersion, queryOptions, queryTime, batchType, queries, values); break; default: throw new RuntimeException("Unknown type: " + type); } }</code><technical_language>Redundant braces</technical_language>

Target:
public void readMarshallable(WireIn wireIn) throws IORuntimeException { String type = wireIn.read("type").text(); int protocolVersion = wireIn.read("protocol-version").int32(); QueryOptions queryOptions = QueryOptions.codec.decode(Unpooled.wrappedBuffer(wireIn.read("query-options").bytes()), ProtocolVersion.decode(protocolVersion)); long queryTime = wireIn.read("query-time").int64(); String keyspace = wireIn.read("keyspace").text(); switch (type) { case "single": String queryString = wireIn.read("query").text(); query = new FQLQuery.Single(keyspace, protocolVersion, queryOptions, queryTime, queryString, queryOptions.getValues()); break; case "batch": BatchStatement.Type batchType = BatchStatement.Type.valueOf(wireIn.read("batch-type").text()); ValueIn in = wireIn.read("queries"); int queryCount = in.int32(); List<String> queries = new ArrayList<>(queryCount); for (int i = 0; i < queryCount; i++) queries.add(in.text()); in = wireIn.read("values"); int valueCount = in.int32(); List<List<ByteBuffer>> values = new ArrayList<>(valueCount); for (int ii = 0; ii < valueCount; ii++) { List<ByteBuffer> subValues = new ArrayList<>(); values.add(subValues); int numSubValues = in.int32(); for (int zz = 0; zz < numSubValues; zz++) subValues.add(ByteBuffer.wrap(in.bytes())); } query = new FQLQuery.Batch(keyspace, protocolVersion, queryOptions, queryTime, batchType, queries, values); break; default: throw new RuntimeException("Unknown type: " + type); } }
Source:
<code>private void poll1(Cursor c) { final Uri alertUri = ObaContract.TripAlerts.buildUri(c.getInt(COL_ID)); final int state = c.getInt(COL_STATE); if (state == ObaContract.TripAlerts.STATE_CANCELLED) { return; } long now = System.currentTimeMillis(); final long startTime = c.getLong(COL_START_TIME); if (startTime < (now - ONE_MINUTE * 30)) { ContentValues values = new ContentValues(); values.put(ObaContract.TripAlerts.STATE, ObaContract.TripAlerts.STATE_CANCELLED); mCR.update(alertUri, values, null, null); TripService.scheduleAll(mContext); return; } TripService.pollTrip(mContext, alertUri, now + ONE_MINUTE); if (state == ObaContract.TripAlerts.STATE_SCHEDULED) { ObaContract.TripAlerts .setState(mContext, alertUri, ObaContract.TripAlerts.STATE_POLLING); } final String tripId = c.getString(COL_TRIP_ID); final String stopId = c.getString(COL_STOP_ID); final long reminderMS = getReminderMS(tripId, stopId); ObaArrivalInfoResponse response = ObaArrivalInfoRequest .newRequest(mContext, stopId).call(); <START> Pair<Long, Boolean> depart = null; <END> if (response.getCode() == ObaApi.OBA_OK) { depart = checkArrivals(response, c); } if (depart != null) { final long diffTime = depart.first - System.currentTimeMillis(); if (diffTime <= reminderMS) { TripService.notifyTrip(mContext, mUri, diffTime, depart.second); } } }</code><technical_language>change name of depart, longer a departure. eta? implies arrival. welcome other naming ideas</technical_language>

Target:
private void poll1(Cursor c) { final Uri alertUri = ObaContract.TripAlerts.buildUri(c.getInt(COL_ID)); final int state = c.getInt(COL_STATE); if (state == ObaContract.TripAlerts.STATE_CANCELLED) { return; } long now = System.currentTimeMillis(); final long startTime = c.getLong(COL_START_TIME); if (startTime < (now - ONE_MINUTE * 30)) { ContentValues values = new ContentValues(); values.put(ObaContract.TripAlerts.STATE, ObaContract.TripAlerts.STATE_CANCELLED); mCR.update(alertUri, values, null, null); TripService.scheduleAll(mContext); return; } TripService.pollTrip(mContext, alertUri, now + ONE_MINUTE); if (state == ObaContract.TripAlerts.STATE_SCHEDULED) { ObaContract.TripAlerts .setState(mContext, alertUri, ObaContract.TripAlerts.STATE_POLLING); } final String tripId = c.getString(COL_TRIP_ID); final String stopId = c.getString(COL_STOP_ID); final long reminderMS = getReminderMS(tripId, stopId); ObaArrivalInfoResponse response = ObaArrivalInfoRequest .newRequest(mContext, stopId).call(); Long departMS = null; if (response.getCode() == ObaApi.OBA_OK) { departMS = checkArrivals(response, c); } if (departMS != null) { final long diffTime = departMS - System.currentTimeMillis(); if (diffTime <= reminderMS) { TripService.notifyTrip(mContext, mUri, diffTime); } } }
Source:
<code>public void openImagePicker() { waitForElementByElement(bgImage); <START> scrollAndClick(bgImage); <END> waitForElementByElement(bgImagePicker); PageObjectLogging.log("openImagePicker", "image picker opened", true, driver); }</code><technical_language>if scrolling if necessary, change .click(), if yes, leave is</technical_language>

Target:
public void openImagePicker() { waitForElementByElement(bgImage); bgImage.click(); waitForElementByElement(bgImagePicker); PageObjectLogging.log("openImagePicker", "image picker opened", true, driver); }
Source:
<code>private SortedIterator(IHistoryTree tree, TimeRangeCondition times, IntegerRangeCondition quarks, Comparator<ITmfStateInterval> comparator) { fTree = tree; fTimes = times; fQuarks = quarks; fComparator = comparator; queue = new PriorityQueue<>(tree.getNodeCount(), Comparator.comparing(ParentNode.Tuple::getInterval, fComparator)); queue.add(new ParentNode.Tuple(new HTInterval(0, 1, 0, null), tree.getRootNode().getSequenceNumber())); <START> intersecting = new PriorityQueue<>(10000, fComparator); <END> }</code><technical_language>9000</technical_language>

Target:
private SortedIterator(IHistoryTree tree, TimeRangeCondition times, IntegerRangeCondition quarks, Comparator<ITmfStateInterval> comparator) { fTree = tree; fTimes = times; fQuarks = quarks; fComparator = comparator; fNodeQueue = new PriorityQueue<>(tree.getNodeCount(), Comparator.comparing(ParentNode.Tuple::getInterval, fComparator)); fNodeQueue.add(new ParentNode.Tuple(new HTInterval(0, 1, 0, null), tree.getRootNode().getSequenceNumber())); fIntersectingIntervals = new PriorityQueue<>(INITIAL_INTERVAL_QUEUE_CAPACITY, fComparator); }
Source:
<code>public Guid schedule(VDSGroup cluster, VM vm, List<Guid> hostBlackList, List<Guid> hostWhiteList, Guid destHostId, List<String> messages, VdsFreeMemoryChecker memoryChecker) { clusterLockMap.putIfAbsent(cluster.getId(), new Object()); synchronized (clusterLockMap.get(cluster.getId())) { List<VDS> vdsList = getVdsDAO() .getAllForVdsGroupWithStatus(cluster.getId(), VDSStatus.Up); updateInitialHostList(vdsList, hostBlackList, true); updateInitialHostList(vdsList, hostWhiteList, false); ClusterPolicy policy = policyMap.get(cluster.getClusterPolicyId()); Map<String, String> parameters = createClusterPolicyParameters(cluster); vdsList = runFilters(policy.getFilters(), vdsList, vm, parameters, policy.getFilterPositionMap(), messages, memoryChecker); if (vdsList == null || vdsList.size() == 0) { return null; } if (vdsList != null) { for (VDS vds: vdsList) { if (vds.getId().equals(destHostId)) { return destHostId; } } } if (vdsList != null && vdsList.contains(destHostId)) { return destHostId; <START> } <END> if (policy.getFunctions() == null || policy.getFunctions().isEmpty()) { return vdsList.get(0).getId(); } Guid bestHost = runFunctions(policy.getFunctions(), vdsList, vm, parameters); if (bestHost != null) { getVdsDynamicDao().updatePartialVdsDynamicCalc( bestHost, 1, vm.getNumOfCpus(), vm.getMinAllocatedMem(), vm.getVmMemSizeMb(), vm.getNumOfCpus()); } return bestHost; } }</code><technical_language>plz remove this if condition</technical_language>

Target:
public Guid schedule(VDSGroup cluster, VM vm, List<Guid> hostBlackList, List<Guid> hostWhiteList, Guid destHostId, List<String> messages, VdsFreeMemoryChecker memoryChecker) { clusterLockMap.putIfAbsent(cluster.getId(), new Object()); synchronized (clusterLockMap.get(cluster.getId())) { List<VDS> vdsList = getVdsDAO() .getAllForVdsGroupWithStatus(cluster.getId(), VDSStatus.Up); updateInitialHostList(vdsList, hostBlackList, true); updateInitialHostList(vdsList, hostWhiteList, false); ClusterPolicy policy = policyMap.get(cluster.getClusterPolicyId()); Map<String, String> parameters = createClusterPolicyParameters(cluster); vdsList = runFilters(policy.getFilters(), vdsList, vm, parameters, policy.getFilterPositionMap(), messages, memoryChecker); if (vdsList == null || vdsList.size() == 0) { return null; } if (vdsList != null) { for (VDS vds: vdsList) { if (vds.getId().equals(destHostId)) { return destHostId; } } } if (policy.getFunctions() == null || policy.getFunctions().isEmpty()) { return vdsList.get(0).getId(); } Guid bestHost = runFunctions(policy.getFunctions(), vdsList, vm, parameters); if (bestHost != null) { getVdsDynamicDao().updatePartialVdsDynamicCalc( bestHost, 1, vm.getNumOfCpus(), vm.getMinAllocatedMem(), vm.getVmMemSizeMb(), vm.getNumOfCpus()); } return bestHost; } }
Source:
<code>public void testConnectionOnAfterGetConnectionAfterGettingFromPooledConnectionWithThrowingSQLException() throws SQLException { SQLException sqle = new SQLException(); when(mockedPooledConnection.getConnection()).thenThrow(sqle); try { wrappedPooledConnection.getConnection(); <START> } catch (SQLException expected) { <END> } verify(mockedJdbcListener).onAfterGetConnection(connectionInformationWithoutConnection(), eq(sqle)); }</code><technical_language>ditto (Assert.fail())</technical_language>

Target:
public void testConnectionOnAfterGetConnectionAfterGettingFromPooledConnectionWithThrowingSQLException() throws SQLException { SQLException sqle = new SQLException(); when(mockedPooledConnection.getConnection()).thenThrow(sqle); try { wrappedPooledConnection.getConnection(); Assert.fail("exception should be thrown"); } catch (SQLException expected) { } verify(mockedJdbcListener).onAfterGetConnection(connectionInformationWithoutConnection(), eq(sqle)); }
Source:
<code>void checkSupportedCipherSuites() { if (getSupportedCipherSuites() == null) { setSupportedCipherSuites(ImmutableList.of(HTTP2_DEFAULT_CIPHER)); } else if (!getSupportedCipherSuites().contains(HTTP2_DEFAULT_CIPHER)) { <START> throw new IllegalArgumentException("h2 server configuration must include cipher: " + HTTP2_DEFAULT_CIPHER); <END> } }</code><technical_language>leave it: Mild preference for "HTTP/2" in error message</technical_language>

Target:
void checkSupportedCipherSuites() { if (getSupportedCipherSuites() == null) { setSupportedCipherSuites(ImmutableList.of(HTTP2_DEFAULT_CIPHER)); } else if (!getSupportedCipherSuites().contains(HTTP2_DEFAULT_CIPHER)) { throw new IllegalArgumentException("HTTP/2 server configuration must include cipher: " + HTTP2_DEFAULT_CIPHER); } }
Source:
<code><START> protected <T> QueryResponse<T> setErrorQueryResponse(String message) { <END> QueryResponse<T> queryResponse = new QueryResponse<>(); endTime = System.currentTimeMillis(); queryResponse.setApiVersion(version); queryResponse.setQueryOptions(queryOptions); queryResponse.setTime(new Long(endTime - startTime).intValue()); queryResponse.setResponse(Collections.EMPTY_LIST); queryResponse.setError(message); return queryResponse; }</code><technical_language>This method previous similar, common code extracted a private method: time, API version, queryOptions</technical_language>

Target:
protected <T> QueryResponse<T> setErrorQueryResponse(String message) { QueryResponse<T> queryResponse = buildQueryResponse(); queryResponse.setResponse(Collections.EMPTY_LIST); queryResponse.setError(message); return queryResponse; }
Source:
<code>private void updateUi() { setTitle(MessageFormat.format(UIText.CommitSelectionDialog_DialogTitle, Integer.valueOf(allCommits.size()), GitLabels.getPlainShortLabel(repository))); setMessage(UIText.CommitSelectionDialog_DialogMessage); table.setInput(highlightFlag, allCommits, allCommits .toArray(new SWTCommit[0]), null, true); searchBar.setInput(new ICommitsProvider() { @Override public Object getSearchContext() { return null; } @Override public SWTCommit[] getCommits() { return <START> allCommits.toArray(new SWTCommit[0]); <END> } @Override public RevFlag getHighlight() { return highlightFlag; } }); }</code><technical_language>Avoid duplicating this array; large. Create table.setInput(), pass here</technical_language>

Target:
private void updateUi() { setTitle(MessageFormat.format(UIText.CommitSelectionDialog_DialogTitle, Integer.valueOf(allCommits.size()), GitLabels.getPlainShortLabel(repository))); setMessage(UIText.CommitSelectionDialog_DialogMessage); SWTCommit[] allCommitsArray = allCommits.toArray(new SWTCommit[0]); table.setInput(highlightFlag, allCommits, allCommitsArray, null, true); searchBar.setInput(new ICommitsProvider() { @Override public Object getSearchContext() { return null; } @Override public SWTCommit[] getCommits() { return allCommitsArray; } @Override public RevFlag getHighlight() { return highlightFlag; } }); }
Source:
<code>public static String createAllResponseResultGetters(final ImmutableList<Ds3ResponseCode> responseCodes) { if (isEmpty(responseCodes)) { return ""; } final ImmutableMap<String, Ds3ResponseType> map = createUniqueDs3ResponseTypesMap(responseCodes); final ImmutableList.Builder<String> builder = ImmutableList.builder(); <START> for (Map.Entry<String, Ds3ResponseType> entry : map.entrySet()) { <END> builder.add(createResponseResultGetter(entry.getKey(), entry.getValue())); } return builder.build() .stream() .map(i -> i) .collect(Collectors.joining("\n")); }</code><technical_language>Missing final</technical_language>

Target:
public static String createAllResponseResultGetters(final ImmutableList<Ds3ResponseCode> responseCodes) { if (isEmpty(responseCodes)) { return ""; } final ImmutableMap<String, Ds3ResponseType> map = createUniqueDs3ResponseTypesMap(responseCodes); final ImmutableList.Builder<String> builder = ImmutableList.builder(); for (final Map.Entry<String, Ds3ResponseType> entry : map.entrySet()) { builder.add(createResponseResultGetter(entry.getKey(), entry.getValue())); } return builder.build() .stream() .map(i -> i) .collect(Collectors.joining("\n")); }
Source:
<code><START> public Object getNodeMBeanHistory(@HeaderParam("sessionid") String sessionId, <END> @QueryParam("nodejmxurl") String nodeJmxUrl, @QueryParam("objectname") String objectName, @QueryParam("attrs") List<String> attrs, @QueryParam("range") String range) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException, NotConnectedException, MalformedObjectNameException, NullPointerException, MBeanException { RMProxyUserInterface rmProxy = checkAccess(sessionId); return rmProxy.getNodeMBeanHistory(nodeJmxUrl, objectName, attrs, range); }</code><technical_language>change String object</technical_language>

Target:
public String getNodeMBeanHistory(@HeaderParam("sessionid") String sessionId, @QueryParam("nodejmxurl") String nodeJmxUrl, @QueryParam("objectname") String objectName, @QueryParam("attrs") List<String> attrs, @QueryParam("range") String range) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException, NotConnectedException, MalformedObjectNameException, NullPointerException, MBeanException { RMProxyUserInterface rmProxy = checkAccess(sessionId); return rmProxy.getNodeMBeanHistory(nodeJmxUrl, objectName, attrs, range); }
Source:
<code>public boolean addValue(Data dataKey, MultiMapRecord value, int index) { MultiMapValue multiMapValue = getOrCreateMultiMapValue(dataKey); <START> boolean added; <END> if (index < 0) { added = multiMapValue.getCollection(false).add(value); } else { ((List<MultiMapRecord>) multiMapValue.getCollection(false)).add(index, value); added = true; } if (added) { incSize(1); } return added; }</code><technical_language>nitpicking personal taste, I find difficult follow boolean changes in code, more error prone. removing it, multiple method-exit points (return). eg. return multiMapValue.getCollection(false).add(value);</technical_language>

Target:
public boolean addValue(Data dataKey, MultiMapRecord value, int index) { MultiMapValue multiMapValue = getOrCreateMultiMapValue(dataKey); if (index < 0) { boolean added = multiMapValue.getCollection(false).add(value); if (added) { incSize(1); } return added; } else { ((List<MultiMapRecord>) multiMapValue.getCollection(false)).add(index, value); incSize(1); return true; } }
Source:
<code>public PartialUpdate<T> del(String path) { Assert.hasText(path, "Path to remove must not be null or empty!"); <START> propertyUpdates.add(new PropertyUpdate(UpdateCommand.DEL, path)); <END> return new PartialUpdate<T>(this.id, this.target, this.value, this.refreshTtl, this.propertyUpdates); }</code><technical_language>PartialUpdate changes state creates a new instance</technical_language>

Target:
public PartialUpdate<T> del(String path) { Assert.hasText(path, "Path to remove must not be null or empty!"); PartialUpdate<T> update = new PartialUpdate<T>(this.id, this.target, this.value, this.refreshTtl, this.propertyUpdates); update.propertyUpdates.add(new PropertyUpdate(UpdateCommand.DEL, path)); return update; }
Source:
<code>public QueueConsumers<T> reset() { if (changedIterator != null) { <START> currentIterator = changedIterator; <END> changedIteratorFieldUpdater.compareAndSet(this, changedIterator, null); } else { currentIterator.reset(); } return this; }</code><technical_language>I save changedIterator perform a logic a local instead of volatile load</technical_language>

Target:
public void reset() { iterator.reset(); }
Source:
<code>public ActionResponse execute() throws QueryStoreException { <START> if (!validate()) { <END> throw new QueryStoreException(QueryStoreException.ErrorCode.INVALID_REQUEST, "Request validation failed" + ""); } final String cacheKeyValue = cacheKey(); if (isCacheable()) { if (cache.has(cacheKeyValue)) { logger.info("Cache hit for key: " + cacheKeyValue); return cache.get(cacheKey()); } } logger.info("Cache miss for key: " + cacheKeyValue); parameter.setFilters(checkAndAddTemporalBoundary(parameter.getFilters())); ActionResponse result = execute(parameter); if (isCacheable()) { logger.info("Cache load for key: " + cacheKeyValue); return cache.put(cacheKey(), result); } return result; }</code><technical_language>validate throw exception instead of throwing ErrorCode for validation failures</technical_language>

Target:
public ActionResponse execute() throws QueryStoreException { validate(); final String cacheKeyValue = cacheKey(); if (isCacheable()) { if (cache.has(cacheKeyValue)) { logger.info("Cache hit for key: " + cacheKeyValue); return cache.get(cacheKey()); } } logger.info("Cache miss for key: " + cacheKeyValue); parameter.setFilters(checkAndAddTemporalBoundary(parameter.getFilters())); ActionResponse result = execute(parameter); if (isCacheable()) { logger.info("Cache load for key: " + cacheKeyValue); return cache.put(cacheKey(), result); } return result; }
Source:
<code>public int size() { if (countQuery == null) { return UNKNOWN_SIZE; } try (Connection connection = createConnection()) { Statement st = connection.createStatement(); ResultSet res = st.executeQuery(countQuery); int count = 0; if (res.next()) { count = res.getInt(1); } return count; } catch (SQLException e) { log.warn("Could not determine query size by count query"); try (Connection connection = createConnection()) { Statement st = connection.createStatement(); ResultSet res = st.executeQuery(sqlQuery); <START> int count = 0; <END> while (res.next()) { count++; } return count; } catch (SQLException e2) { log.warn("Could not determine query size by counting query result", e2); return UNKNOWN_SIZE; } } }</code><technical_language>For example so: if (!res.next()) { return 0; } else { return UNKNOWN_SIZE; }</technical_language>

Target:
public int size() { if (countQuery == null) { return UNKNOWN_SIZE; } try (Connection connection = createConnection()) { Statement st = connection.createStatement(); ResultSet res = st.executeQuery(countQuery); int count = 0; if (res.next()) { count = res.getInt(1); } return count; } catch (SQLException e) { log.warn("Could not determine query size by count query"); try (Connection connection = createConnection()) { Statement st = connection.createStatement(); st.setMaxRows(1); ResultSet res = st.executeQuery(sqlQuery); if (res.next()) { return UNKNOWN_SIZE; } else { return 0; } } catch (SQLException e2) { log.warn("Could not determine query size by counting query result", e2); return UNKNOWN_SIZE; } } }