auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void delete() { this.open(); clickLink("Delete Project"); <START> elasticSleep(500); <END> confirmAlert(); }</code><technical_language>alert [throws](<LINK_0> exception if alert, for a "wait until" (with timeout) kind of waiting</technical_language>

Target:
public void delete() { this.open(); clickLink("Delete Project"); confirmAlert(2); }
Source:
<code>protected void onHandleIntent(Intent intent) { Log.d(TAG, "onHandleIntent()"); if(false == NetworkUtils.networkAvailable(this)) { return; } List<FeedMedia> list = DBReader.getFeedMediaUnknownSize(this); for (FeedMedia media : list) { if(false == NetworkUtils.networkAvailable(this)) { return; } long size = Integer.MIN_VALUE; Log.d(TAG, media.getDownload_url()); try { URL url = new URL(media.getDownload_url()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty( "Accept-Encoding", "" ); conn.setRequestMethod("HEAD"); size = conn.getContentLength(); <START> conn.disconnect(); <END> } catch (IOException e) { Log.d(TAG, media.getDownload_url()); e.printStackTrace(); } media.setSize(size); DBWriter.setFeedMedia(this, media); EventBus.getDefault().post(FeedMediaEvent.update(media)); } }</code><technical_language>big of a deal this is, throw exception crash app, put conn.disconnect() in a 'finally' block closed (assuming non-null)</technical_language>

Target:
protected void onHandleIntent(Intent intent) { Log.d(TAG, "onHandleIntent()"); if(false == NetworkUtils.networkAvailable(this)) { return; } List<FeedMedia> list = DBReader.getFeedMediaUnknownSize(this); for (FeedMedia media : list) { if(false == NetworkUtils.networkAvailable(this)) { return; } long size = Integer.MIN_VALUE; if(media.isDownloaded()) { File mediaFile = new File(media.getLocalMediaUrl()); if(mediaFile.exists()) { size = mediaFile.length(); } } else { HttpURLConnection conn = null; try { URL url = new URL(media.getDownload_url()); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Accept-Encoding", ""); conn.setRequestMethod("HEAD"); size = conn.getContentLength(); conn.disconnect(); } catch (IOException e) { Log.d(TAG, media.getDownload_url()); e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } } media.setSize(size); DBWriter.setFeedMedia(this, media); EventBus.getDefault().post(FeedMediaEvent.update(media)); } }
Source:
<code>public void testGenerateXpathSuppressionOptionEmptyConfig() throws Exception { final String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE suppressions PUBLIC\n" <START> + " \"- END> + " \"<LINK_0>" + "suppressions_1_2_xpath_experimental.dtd\">\n" + "<suppressions>\n" + "</suppressions>\n"; exit.checkAssertionAfterwards(() -> { assertEquals("Unexpected output log", expected, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-c", getPath("InputMainConfig-empty.xml"), "--generate-xpath-suppression", getPath("InputMainComplexityOverflow.java")); }</code><technical_language>fix name</technical_language>

Target:
public void testGenerateXpathSuppressionOptionEmptyConfig() throws Exception { final String expected = ""; exit.checkAssertionAfterwards(() -> { assertEquals("Unexpected output log", expected, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-c", getPath("InputMainConfig-empty.xml"), "--generate-xpath-suppression", getPath("InputMainComplexityOverflow.java")); }
Source:
<code>public EventReceiverFirehoseTestClient( String host, String chatID, ObjectMapper jsonMapper, @TestClient HttpClient httpClient, ObjectMapper smileMapper ) { this.host = host; this.jsonMapper = jsonMapper; <START> this.responseHandler = StatusResponseHandler.getInstance(); <END> this.httpClient = httpClient; this.chatID = chatID; this.smileMapper = smileMapper; }</code><technical_language>Please remove this field</technical_language>

Target:
public EventReceiverFirehoseTestClient( String host, String chatID, ObjectMapper jsonMapper, @TestClient HttpClient httpClient, ObjectMapper smileMapper ) { this.host = host; this.jsonMapper = jsonMapper; this.httpClient = httpClient; this.chatID = chatID; this.smileMapper = smileMapper; }
Source:
<code>public void testExport() throws IOException { <START> setup(); <END> SWTBotEditor editorBot = fEditorBot; assertNotNull(editorBot); final SWTBotTable tableBot = editorBot.bot().table(); tableBot.getTableItem(1).contextMenu(EXPORT_TO_TSV).click(); File file = new File(fAbsolutePath); fBot.waitUntil(new FileLargerThanZeroCondition(file)); try (BufferedReader br = new BufferedReader(new FileReader(file))) { long lines = br.lines().count(); assertEquals("Line count", 23, lines); } finally { new File(fAbsolutePath).delete(); } }</code><technical_language>Is test fail call this</technical_language>

Target:
public void testExport() throws IOException { SWTBotEditor editorBot = fEditorBot; assertNotNull(editorBot); final SWTBotTable tableBot = editorBot.bot().table(); tableBot.getTableItem(1).contextMenu(EXPORT_TO_TSV).click(); File file = new File(fAbsolutePath); fBot.waitUntil(new FileLargerThanZeroCondition(file)); try (BufferedReader br = new BufferedReader(new FileReader(file))) { long lines = br.lines().count(); assertEquals("Line count", 23, lines); } finally { new File(fAbsolutePath).delete(); } }
Source:
<code>private void handleDatastreamAddOrDelete() { leaderDoAssignmentScheduled.set(false); List<Datastream> newDatastreams = _adapter.getAllDatastreams(); if (newDatastreams.isEmpty()) { _log.warn("Received a new datastream event, but there were no datastreams"); return; } try { _destinationManager.populateDatastreamDestination(newDatastreams); for (Datastream stream : newDatastreams) { if (stream.hasDestination() && !_adapter.updateDatastream(stream)) { <START> _dynamicMetricsManager.createOrUpdateCounter(this.getClass(), "handleDatastreamAddOrDelete", NUM_ERRORS, 1); <END> _log.error(String.format("Failed to update datastream destination for datastream %s, " + "This datastream will not be scheduled for producing events ", stream.getName())); } } _eventQueue.put(CoordinatorEvent.createLeaderDoAssignmentEvent()); } catch (Exception e) { _log.error("Failed to update the destination of new datastreams.", e); _dynamicMetricsManager.createOrUpdateCounter(this.getClass(), "handleDatastreamAddOrDelete", NUM_ERRORS, 1); if (leaderDoAssignmentScheduled.compareAndSet(false, true)) { _log.warn("Schedule retry for handling new datastream"); _executor.schedule(() -> _eventQueue.put(CoordinatorEvent.createHandleDatastreamAddOrDeleteEvent()), _config.getRetryIntervalMS(), TimeUnit.MILLISECONDS); } } }</code><technical_language>a change throw DatastreamException this AddDatastream is retried? remove counter increment do that</technical_language>

Target:
private void handleDatastreamAddOrDelete() { leaderDoAssignmentScheduled.set(false); List<Datastream> newDatastreams = _adapter.getAllDatastreams(); if (newDatastreams.isEmpty()) { _log.warn("Received a new datastream event, but there were no datastreams"); return; } try { _destinationManager.populateDatastreamDestination(newDatastreams); for (Datastream stream : newDatastreams) { if (stream.hasDestination() && !_adapter.updateDatastream(stream)) { _log.error(String.format("Failed to update datastream destination for datastream %s, " + "This datastream will not be scheduled for producing events ", stream.getName())); throw new DatastreamException("Failed to update datastream destination for datastream" + stream.getName()); } } _eventQueue.put(CoordinatorEvent.createLeaderDoAssignmentEvent()); } catch (Exception e) { _log.error("Failed to update the destination of new datastreams.", e); _dynamicMetricsManager.createOrUpdateCounter(this.getClass(), "handleDatastreamAddOrDelete", NUM_RETRIES, 1); if (leaderDoAssignmentScheduled.compareAndSet(false, true)) { _log.warn("Schedule retry for handling new datastream"); _executor.schedule(() -> _eventQueue.put(CoordinatorEvent.createHandleDatastreamAddOrDeleteEvent()), _config.getRetryIntervalMS(), TimeUnit.MILLISECONDS); } } }
Source:
<code>public void testBlockQuote() { builder.beginDocument(); <START> builder.beginBlock(BlockType.QUOTE, new Attributes()); <END> builder.beginBlock(BlockType.PARAGRAPH, new Attributes()); builder.characters("First paragraph."); builder.endBlock(); builder.beginBlock(BlockType.PARAGRAPH, new Attributes()); builder.characters("Second paragraph."); builder.endBlock(); builder.endBlock(); builder.endDocument(); assertMarkup("> First paragraph.\n\n> Second paragraph.\n\n"); }</code><technical_language>intentional nest paragraphs quote here? If test method name test is about. a test for block QUOTE nested paragraphs (that's a more common scenario)</technical_language>

Target:
public void testBlockQuote() { builder.beginDocument(); builder.beginBlock(BlockType.QUOTE, new Attributes()); builder.characters("A quote by someone important."); builder.endBlock(); builder.endDocument(); assertMarkup("> A quote by someone important.\n\n"); }
Source:
<code>public void init(final VM vm, final CloudInitParameters ciParams) { getHostnameEnabled().setEntity(Boolean.FALSE); getHostname().setEntity(vm.getName()); getAuthorizedKeysEnabled().setEntity(Boolean.FALSE); getRegenerateKeysEnabled().setEntity(Boolean.FALSE); getTimeZoneEnabled().setEntity(Boolean.FALSE); getRootPasswordEnabled().setEntity(Boolean.FALSE); getNetworkEnabled().setEntity(Boolean.FALSE); <START> getAttachmentEnabled().setEntity(Boolean.FALSE); <END> AsyncDataProvider.getTimeZoneList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { @SuppressWarnings("unchecked") Map<String, String> timezones = (Map<String, String>) returnValue; getTimeZoneList().setItems(timezones.entrySet()); getTimeZoneList().setSelectedItem(Linq.firstOrDefault(timezones.entrySet(), new IPredicate<Map.Entry<String, String>>() { @Override public boolean match(Map.Entry<String, String> item) { return item.getValue().startsWith("(GMT) Greenwich"); } })); } }), TimeZoneType.GENERAL_TIMEZONE); getAttachmentType().setItems(attachmentTypes.entrySet()); getAttachmentType().setSelectedItem(Linq.firstOrDefault(attachmentTypes.entrySet())); }</code><technical_language>primitive false thanx autoboxing</technical_language>

Target:
public void init(final VM vm, final CloudInitParameters ciParams) { getHostnameEnabled().setEntity(false); getHostname().setEntity(vm.getName()); getAuthorizedKeysEnabled().setEntity(false); getRegenerateKeysEnabled().setEntity(false); getTimeZoneEnabled().setEntity(false); getRootPasswordEnabled().setEntity(false); getNetworkEnabled().setEntity(false); getAttachmentEnabled().setEntity(false); AsyncDataProvider.getTimeZoneList(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { @SuppressWarnings("unchecked") Map<String, String> timezones = (Map<String, String>) returnValue; getTimeZoneList().setItems(timezones.entrySet()); getTimeZoneList().setSelectedItem(Linq.firstOrDefault(timezones.entrySet(), new IPredicate<Map.Entry<String, String>>() { @Override public boolean match(Map.Entry<String, String> item) { return item.getValue().startsWith("(GMT) Greenwich"); } })); } }), TimeZoneType.GENERAL_TIMEZONE); getAttachmentType().setItems(attachmentTypes.entrySet()); getAttachmentType().setSelectedItem(Linq.firstOrDefault(attachmentTypes.entrySet())); }
Source:
<code>private List<CloudIdAndTimestampResponse> intersectCloudIdAndTimestampResponsesBasedOnCloudId(List<CloudIdAndTimestampResponse> dereferenceCloudIdAndTimestampResponseList, List<CloudIdAndTimestampResponse> publishedCloudIdAndTimestampResponseList) { List<CloudIdAndTimestampResponse> intesectCloudIds = new ArrayList<>(); for (CloudIdAndTimestampResponse dereferenceCloudIdAndTimestamp : dereferenceCloudIdAndTimestampResponseList) { String dereferenceCloudId = dereferenceCloudIdAndTimestamp.getCloudId(); for (CloudIdAndTimestampResponse publishedCloudIdAndTimestamp : publishedCloudIdAndTimestampResponseList) { <START> String publishCloudId = publishedCloudIdAndTimestamp.getCloudId(); <END> if (dereferenceCloudId.equals(publishCloudId)) { intesectCloudIds.add(dereferenceCloudIdAndTimestamp); } } } return intesectCloudIds; }</code><technical_language>need create a variable once</technical_language>

Target:
private List<CloudIdAndTimestampResponse> intersectCloudIdAndTimestampResponsesBasedOnCloudId(List<CloudIdAndTimestampResponse> dereferenceCloudIdAndTimestampResponseList, List<CloudIdAndTimestampResponse> publishedCloudIdAndTimestampResponseList) { List<CloudIdAndTimestampResponse> intesectCloudIds = new ArrayList<>(); for (CloudIdAndTimestampResponse dereferenceCloudIdAndTimestamp : dereferenceCloudIdAndTimestampResponseList) { String dereferenceCloudId = dereferenceCloudIdAndTimestamp.getCloudId(); for (CloudIdAndTimestampResponse publishedCloudIdAndTimestamp : publishedCloudIdAndTimestampResponseList) { if (dereferenceCloudId.equals(publishedCloudIdAndTimestamp.getCloudId())) { intesectCloudIds.add(dereferenceCloudIdAndTimestamp); } } } return intesectCloudIds; }
Source:
<code>public void testCompressNullTransformerId() throws Exception { <START> Map<String, Serializable> arguments = new HashMap<>(); <END> arguments.put("transformerId", null); zipCompression.transform(SINGLE_RESULT_SOURCE_RESPONSE, arguments); }</code><technical_language>nit: Map<String, Serializable> arguments = Collections.singletonMap("stuff", null);</technical_language>

Target:
public void testCompressNullTransformerId() throws Exception { Map<String, Serializable> arguments = Collections.singletonMap("transformerId", null); zipCompression.transform(SINGLE_RESULT_SOURCE_RESPONSE, arguments); }
Source:
<code>public int allowedValueForRef(Set<AccountGroup.Id> groups) { int val = Integer.MIN_VALUE; for (RefRight right : rights) { if (groups.contains(right.getAccountGroupId())) { <START> if ((val < 0 && right.getMaxValue() > 0)) { <END> val = Math.max(right.getMaxValue(), val); } } } return val; }</code><technical_language>Drop this if entirely. if-else block right simplified val = Math.max(...) expression</technical_language>

Target:
public int allowedValueForRef(Set<AccountGroup.Id> groups) { int val = Integer.MIN_VALUE; for (RefRight right : rights) { if (groups.contains(right.getAccountGroupId())) { val = Math.max(right.getMaxValue(), val); } } return val; }
Source:
<code>public void shouldGetErrorWhenUsingCreateUniqueWhenCypherVersionIs3_3() { thrown.expect( QueryExecutionException.class ); thrown.expectMessage( "CREATE UNIQUE is no longer supported. You can achieve the same result using MERGE"); <START> Result result = db().execute( "CYPHER 3.3 MATCH (b) WITH b LIMIT 1 CREATE UNIQUE (b)-[:REL]->()" ); <END> }</code><technical_language>result anymore call db().execute( "CYPHER 3.3 MATCH (b) b LIMIT 1 CREATE UNIQUE (b)-[:REL]->()" ); storing result in a variable</technical_language>

Target:
public void shouldGetErrorWhenUsingCreateUniqueWhenCypherVersionIs3_3() { thrown.expect( QueryExecutionException.class ); thrown.expectMessage( "CREATE UNIQUE is no longer supported. You can achieve the same result using MERGE"); db().execute( "CYPHER 3.3 MATCH (b) WITH b LIMIT 1 CREATE UNIQUE (b)-[:REL]->()" ); }
Source:
<code>public static Object structAccess(Object structObject, int index, String fieldName) { if (structObject == null) { return null; } if (structObject instanceof Object[]) { return ((Object[]) structObject)[index]; } else if (structObject instanceof List) { return ((List) structObject).get(index); } else if (structObject instanceof Row) { return ((Row) structObject).getObject(index); } else { Class<?> beanClass = structObject.getClass(); try { Field structField = beanClass.getDeclaredField(fieldName); return structField.get(structObject); } catch (NoSuchFieldException | IllegalAccessException ex) { <START> throw new IllegalStateException(ex); <END> } } }</code><technical_language>please add relevant exception message? is fieldName/index triggered failure</technical_language>

Target:
public static Object structAccess(Object structObject, int index, String fieldName) { if (structObject == null) { return null; } if (structObject instanceof Object[]) { return ((Object[]) structObject)[index]; } else if (structObject instanceof List) { return ((List) structObject).get(index); } else if (structObject instanceof Row) { return ((Row) structObject).getObject(index); } else { Class<?> beanClass = structObject.getClass(); try { Field structField = beanClass.getDeclaredField(fieldName); return structField.get(structObject); } catch (NoSuchFieldException | IllegalAccessException ex) { throw new IllegalStateException("Failed to access field '" + fieldName + "' of object of type " + beanClass.getName(), ex); } } }
Source:
<code><START> public Library save(Library library) throws IOException { <END> library.setLastModifier(authorizationManager.getCurrentUser()); try { Long newId = libraryDao.save(library); Library managed = libraryDao.get(newId); boolean needsUpdate = false; if (hasTemporaryName(library)) { managed.setName(namingScheme.generateNameFor(managed)); validateNameOrThrow(managed, namingScheme); if (autoGenerateIdBarcodes && isStringEmptyOrNull(managed.getIdentificationBarcode())) generateAndSetIdBarcode(managed); needsUpdate = true; } if (needsUpdate) libraryDao.save(managed); return managed; } catch (MisoNamingException e) { throw new IllegalArgumentException("Name generator failed to generate valid name for library"); } catch (ConstraintViolationException e) { throw new ConstraintViolationException(e.getMessage() + " " + ExceptionUtils.getRootCauseMessage(e), e.getSQLException(), e.getConstraintName()); } }</code><technical_language>dilution service - this private</technical_language>

Target:
private Library save(Library library) throws IOException { try { Long newId = libraryDao.save(library); Library managed = libraryDao.get(newId); boolean needsUpdate = false; if (hasTemporaryName(library)) { managed.setName(namingScheme.generateNameFor(managed)); validateNameOrThrow(managed, namingScheme); needsUpdate = true; } if (autoGenerateIdBarcodes && isStringEmptyOrNull(managed.getIdentificationBarcode())) { generateAndSetIdBarcode(managed); needsUpdate = true; } if (needsUpdate) libraryDao.save(managed); return managed; } catch (MisoNamingException e) { throw new IllegalArgumentException("Name generator failed to generate valid name for library"); } catch (ConstraintViolationException e) { throw new ConstraintViolationException(e.getMessage() + " " + ExceptionUtils.getRootCauseMessage(e), e.getSQLException(), e.getConstraintName()); } }
Source:
<code>private static String readSchema(String dataSchemaLocation) { try { <START> InputStream inputStream = isURL(dataSchemaLocation.trim().toLowerCase(Locale.ENGLISH)) ? new URL(dataSchemaLocation).openStream() : new FileInputStream(new File(dataSchemaLocation)); <END> return CharStreams.toString(new InputStreamReader(inputStream, UTF_8)); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Could not parse the AVRO schema at: " + dataSchemaLocation); } }</code><technical_language>close inputStream, I closed now</technical_language>

Target:
private static String readSchema(String dataSchemaLocation) { InputStream inputStream = null; try { if (isURI(dataSchemaLocation.trim().toLowerCase(ENGLISH))) { try { inputStream = new URL(dataSchemaLocation).openStream(); } catch (MalformedURLException e) { inputStream = new FileInputStream(dataSchemaLocation); } } else { inputStream = new FileInputStream(dataSchemaLocation); } return CharStreams.toString(new InputStreamReader(inputStream, UTF_8)); } catch (IOException e) { throw new PrestoException(GENERIC_INTERNAL_ERROR, "Could not parse the AVRO schema at: " + dataSchemaLocation, e); } finally { closeQuietly(inputStream); } }
Source:
<code><START> public void setTabIndex(int index) { <END> }</code><technical_language>please store tab index return getter</technical_language>

Target:
public void setTabIndex(int index) { this.tabIndex = index; }
Source:
<code>public String decodeSamlAuthnRequest(final String encodedRequestXmlString) { if (StringUtils.isEmpty(encodedRequestXmlString)) { return null; } final byte[] decodedBytes = EncodingUtils.decodeBase64(encodedRequestXmlString); if (decodedBytes == null) { return null; } final String inflated = CompressionUtils.inflate(decodedBytes); if (!StringUtils.isEmpty(inflated)) { return inflated; <START> } else { <END> return new String(decodedBytes, StandardCharsets.UTF_8); } }</code><technical_language>This is fine, else clause is redundant here</technical_language>

Target:
public String decodeSamlAuthnRequest(final String encodedRequestXmlString) { if (StringUtils.isEmpty(encodedRequestXmlString)) { return null; } final byte[] decodedBytes = EncodingUtils.decodeBase64(encodedRequestXmlString); if (decodedBytes == null) { return null; } final String inflated = CompressionUtils.inflate(decodedBytes); if (!StringUtils.isEmpty(inflated)) { return inflated; } return new String(decodedBytes, StandardCharsets.UTF_8); }
Source:
<code>public void whenPOSTInvalidEventTypeThenUnprocessableEntity() { Map body = buildEventTypeBody(null); final Response response = given().body(body).post("http://localhost:8080/event_types"); response.then().body(equalTo( <START> "{\"detail\":\"#/event-type/name: expected type: String, found: Null\",\"title\":\"Invalid EventType object\",\"status\":422,\"type\":\"<LINK_1>\"}")); <END> response.then().statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY); }</code><technical_language>a JsonMatcher well: :) <LINK_0></technical_language>

Target:
public void whenPOSTInvalidEventTypeThenUnprocessableEntity() throws JsonProcessingException { EventType eventType = buildEventTypeBody(); eventType.setName(""); eventType.setCategory(""); eventType.getEventTypeSchema().setType(null); eventType.getEventTypeSchema().setSchema(null); String body = mapper.writer().writeValueAsString(eventType); given(). body(body). header("accept", "application/json"). contentType(JSON). when(). post(ENDPOINT). then(). body("detail", containsString("Field \"name\" may not be empty")). body("detail", containsString("Field \"category\" may not be empty")). body("detail", containsString("Field \"event_type_schema.type\" may not be null")). body("detail", containsString("Field \"event_type_schema.schema\" may not be null")). body("title", equalTo("Invalid event type")). body("status", equalTo("UNPROCESSABLE_ENTITY")). body("type", equalTo("<LINK_1>")). statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY); }
Source:
<code>public UICommandEntry() { subscribe(new CursorUpdateEventListener() { @Override public void onCursorUpdated(int oldPosition, int newPosition) { <START> if(tabCompletionEngine == null) <END> return; tabCompletionEngine.reset(); } }); }</code><technical_language>Need some braces here. :)</technical_language>

Target:
public UICommandEntry() { subscribe(new CursorUpdateEventListener() { @Override public void onCursorUpdated(int oldPosition, int newPosition) { if (tabCompletionEngine == null) { return; } tabCompletionEngine.reset(); } }); }
Source:
<code>public <T extends DataAccessObject> void persist(T dao) throws IOException { File objectPath = getDaoPersistencePath(dao); FileOutputStream fileStream = new FileOutputStream(objectPath); <START> ObjectOutputStream oos = new ObjectOutputStream(fileStream); <END> try { oos.writeObject(dao.list()); } finally { oos.close(); } }</code><technical_language>"Out of School"</technical_language>

Target:
public <T extends DataAccessObject> void persist(T dao) throws IOException { File objectPath = getDaoPersistencePath(dao); FileOutputStream fileStream = new FileOutputStream(objectPath); ObjectOutputStream serializer = new ObjectOutputStream(fileStream); try { serializer.writeObject(dao.list()); } finally { serializer.close(); } }
Source:
<code>public TypeMatcher(Assignability assignability) { <START> super( Boolean.TRUE ); END> this.assignability = assignability; }</code><technical_language>@agudian: Wondering default false? WDYT</technical_language>

Target:
public TypeMatcher(Assignability assignability) { super( Boolean.FALSE ); this.assignability = assignability; }
Source:
<code>public Timeline getFakeTimeline(final EventType eventType) { try { final Storage storage = storageDbRepository.getStorage(DEFAULT_STORAGE) <START> .orElseThrow(() -> new UnableProcessException("No default storage defined")); <END> return Timeline.createFakeTimeline(eventType, storage); } catch (InternalNakadiException ex) { throw new IllegalStateException("Default storage is not defined"); } }</code><technical_language>I agreed method define exceptions throws. Also, if UnableProcessException is a right exception throw here, for more InconsistentStateException find default storage there</technical_language>

Target:
public Timeline getFakeTimeline(final EventType eventType) { return Timeline.createFakeTimeline(eventType, defaultStorage); }
Source:
<code>public void headerValuesWithSameNameOnlyVaryingInCaseAreMerged() { Map<String, Collection<String>> headersMap = new LinkedHashMap<>(); headersMap.put("Set-Cookie", Lists.newArrayList("Cookie-A=Value", "Cookie-B=Value")); headersMap.put("set-cookie", Lists.newArrayList("Cookie-C=Value")); Response response = Response.create(200, null, headersMap, new byte[0]); List<String> expectedHeaderValue = Lists.newArrayList("Cookie-A=Value", "Cookie-B=Value", "Cookie-C=Value"); <START> assertThat(response.headers().get("set-cookie")).isEqualTo(expectedHeaderValue); <END> }</code><technical_language>assertj map assertions! able do java assertThat(response.headers()).containsOnly( entry("set-cookie", asList("Cookie-A=Value", "Cookie-B=Value", "Cookie-C=Value") )</technical_language>

Target:
public void headerValuesWithSameNameOnlyVaryingInCaseAreMerged() { Map<String, Collection<String>> headersMap = new LinkedHashMap<>(); headersMap.put("Set-Cookie", Arrays.asList("Cookie-A=Value", "Cookie-B=Value")); headersMap.put("set-cookie", Arrays.asList("Cookie-C=Value")); Response response = Response.create(200, null, headersMap, new byte[0]); List<String> expectedHeaderValue = Arrays.asList("Cookie-A=Value", "Cookie-B=Value", "Cookie-C=Value"); assertThat(response.headers()).containsOnly(entry(("set-cookie"), expectedHeaderValue)); }
Source:
<code>private InputStream setupInputStream(URL url, Map<String, String> headers) throws IOException { HttpClient client = new HttpClient(); String uri = url.toExternalForm(); <START> uri = uri.replaceAll("\\{Time\\}", "20140101"); <END> LOGGER.log(Level.FINE, "URL is "+ uri); HttpMethod get = new GetMethod(uri); if(MapUtils.isNotEmpty(headers)) { for (String headerName : headers.keySet()) { if(LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Adding header " + headerName +" = " + headers.get(headerName)); } get.addRequestHeader(headerName, headers.get(headerName)); } } int code = client.executeMethod(get); if(code != 200) { throw new IOException("Connection returned code " + code); } return get.getResponseBodyAsStream(); }</code><technical_language>this static time replacement</technical_language>

Target:
private InputStream setupInputStream(URL url, Map<String, String> headers) throws IOException { HttpClient client = new HttpClient(); String uri = url.toExternalForm(); if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, "URL is " + uri); HttpMethod get = new GetMethod(uri); if (MapUtils.isNotEmpty(headers)) { for (String headerName : headers.keySet()) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Adding header " + headerName + " = " + headers.get(headerName)); } get.addRequestHeader(headerName, headers.get(headerName)); } } int code = client.executeMethod(get); if (code != 200) { throw new IOException("Connection returned code " + code); } return get.getResponseBodyAsStream(); }
Source:
<code>private NoarkMetadataFraAvleverendeSakssystem metaDataFrom(MeldingType meldingType) { NoarkMetadataFraAvleverendeSakssystem.Builder<Void> metadata = NoarkMetadataFraAvleverendeSakssystem.builder(); metadata.withSakssekvensnummer(Integer.valueOf(meldingType.getNoarksak().getSaSeknr())); metadata.withSaksaar(Integer.valueOf(meldingType.getNoarksak().getSaSaar())); metadata.withJournalaar(Integer.valueOf(meldingType.getJournpost().getJpJaar())); metadata.withJournalsekvensnummer(Integer.valueOf(meldingType.getJournpost().getJpSeknr())); metadata.withJournalpostnummer(Integer.valueOf(meldingType.getJournpost().getJpJpostnr())); metadata.withJournalposttype(meldingType.getJournpost().getJpNdoktype()); metadata.withJournalstatus(meldingType.getJournpost().getJpStatus()); metadata.withJournaldato(journalDatoFrom(meldingType.getJournpost().getJpDokdato())); metadata.withTittel(meldingType.getJournpost().getJpOffinnhold()); <START> String avsendernavn = getAvsnederNavn(meldingType); <END> if(avsendernavn != null) { metadata.withSaksbehandler(avsendernavn); } return metadata.build(); }</code><technical_language>Gitt optional: getAvsnederNavn(meldingType).ifPresent(n -> metadata.withSaksbehandler(n));</technical_language>

Target:
private NoarkMetadataFraAvleverendeSakssystem metaDataFrom(MeldingType meldingType) { NoarkMetadataFraAvleverendeSakssystem.Builder<Void> metadata = NoarkMetadataFraAvleverendeSakssystem.builder(); metadata.withSakssekvensnummer(Integer.valueOf(meldingType.getNoarksak().getSaSeknr())); metadata.withSaksaar(Integer.valueOf(meldingType.getNoarksak().getSaSaar())); metadata.withJournalaar(Integer.valueOf(meldingType.getJournpost().getJpJaar())); metadata.withJournalsekvensnummer(Integer.valueOf(meldingType.getJournpost().getJpSeknr())); metadata.withJournalpostnummer(Integer.valueOf(meldingType.getJournpost().getJpJpostnr())); metadata.withJournalposttype(meldingType.getJournpost().getJpNdoktype()); metadata.withJournalstatus(meldingType.getJournpost().getJpStatus()); metadata.withJournaldato(journalDatoFrom(meldingType.getJournpost().getJpJdato())); metadata.withDokumentetsDato(journalDatoFrom(meldingType.getJournpost().getJpDokdato())); metadata.withTittel(meldingType.getJournpost().getJpOffinnhold()); Optional<AvsmotType> avsender = getAvsender(meldingType); avsender.map(a -> a.getAmNavn()).ifPresent(metadata::withSaksbehandler); return metadata.build(); }
Source:
<code>public static String fingerprint( X509Certificate cert ) throws CertificateException { try { <START> MessageDigest md = MessageDigest.getInstance( "SHA-1" ); <END> md.update( cert.getEncoded() ); return BytePrinter.compactHex( md.digest() ); } catch( NoSuchAlgorithmException e ) { throw new CertificateException( "Cannot use TLS on this platform, because SHA-1 message digest algorithm is not available: " + e.getMessage(), e ); } }</code><technical_language>move SHA-2 SHA-1 reverted nowadays</technical_language>

Target:
public static String fingerprint( X509Certificate cert ) throws CertificateException { try { MessageDigest md = MessageDigest.getInstance( "SHA-512" ); md.update( cert.getEncoded() ); return BytePrinter.compactHex( md.digest() ); } catch( NoSuchAlgorithmException e ) { throw new CertificateException( "Cannot use TLS on this platform, because SHA-512 message digest algorithm is not available: " + e.getMessage(), e ); } }
Source:
<code>private void notifyPacketReceived(final XBeePacket packet) { <START> logger.debug("New packet received: \n{}", packet.toPrettyString()); <END> try { synchronized (packetReceiveListeners) { final ArrayList<IPacketReceiveListener> removeListeners = new ArrayList<IPacketReceiveListener>(); ScheduledExecutorService executor = Executors.newScheduledThreadPool(Math.min(MAXIMUM_PARALLEL_LISTENER_THREADS, packetReceiveListeners.size())); for (final IPacketReceiveListener listener:packetReceiveListeners.keySet()) { executor.execute(new Runnable() { public void run() { if (packetReceiveListeners.get(listener) == ALL_FRAME_IDS) listener.packetReceived(packet); else if (((XBeeAPIPacket)packet).needsAPIFrameID() && ((XBeeAPIPacket)packet).getFrameID() == packetReceiveListeners.get(listener)) { listener.packetReceived(packet); removeListeners.add(listener); } } }); } executor.shutdown(); for (IPacketReceiveListener listener:removeListeners) packetReceiveListeners.remove(listener); } } catch (Exception e) { logger.error(e.getMessage(), e); } }</code><technical_language>I remove 'New', leave 'Packet received: [...]'</technical_language>

Target:
private void notifyPacketReceived(final XBeePacket packet) { logger.debug(connectionInterface.toString() + "Packet received: \n{}", packet.toPrettyString()); try { synchronized (packetReceiveListeners) { final ArrayList<IPacketReceiveListener> removeListeners = new ArrayList<IPacketReceiveListener>(); ScheduledExecutorService executor = Executors.newScheduledThreadPool(Math.min(MAXIMUM_PARALLEL_LISTENER_THREADS, packetReceiveListeners.size())); for (final IPacketReceiveListener listener:packetReceiveListeners.keySet()) { executor.execute(new Runnable() { public void run() { if (packetReceiveListeners.get(listener) == ALL_FRAME_IDS) listener.packetReceived(packet); else if (((XBeeAPIPacket)packet).needsAPIFrameID() && ((XBeeAPIPacket)packet).getFrameID() == packetReceiveListeners.get(listener)) { listener.packetReceived(packet); removeListeners.add(listener); } } }); } executor.shutdown(); for (IPacketReceiveListener listener:removeListeners) packetReceiveListeners.remove(listener); } } catch (Exception e) { logger.error(e.getMessage(), e); } }
Source:
<code>private void releaseLock(final KeyType key, final Jedis jedis) { <START> jedis.del(redisLockKey(generateRedisKey(key))); <END> }</code><technical_language>if a redis connection failure here</technical_language>

Target:
private void releaseLock(final KeyType key, final Jedis jedis) { for(int i = 0; i < lockReleaseRetries; i++) { try { jedis.del(redisLockKey(generateRedisKey(key))); return; } catch (Exception ex) { log.warn("{}: exception releasing lock, will retry", getCacheName(), ex); try { Thread.sleep(lockReleaseRetryWaitMillis); } catch (InterruptedException e) { log.debug("{}, interrupted retrying lock release", getCacheName(), e); } } } }
Source:
<code>void gatherHeaders(int maxPos) throws IOException { try { while(this.bufferPosition < maxPos) { int possible = maxPos - this.bufferPosition; int want = msgHeaders.length - msgHeadersPosition; if (want > 0 && want <= possible) { System.arraycopy(this.buffer, this.bufferPosition, this.msgHeaders, this.msgHeadersPosition, want); msgHeadersPosition += want; this.bufferPosition += want; continue; } else if (want > 0) { System.arraycopy(this.buffer, this.bufferPosition, this.msgHeaders, this.msgHeadersPosition, possible); msgHeadersPosition += possible; this.bufferPosition += possible; continue; } if (msgHeadersPosition == msgHeaders.length) { incoming.setHeaders(msgHeaders); msgHeaders = null; msgHeadersPosition = -1; this.mode = Mode.GATHER_DATA; break; } else { <START> throw new IllegalStateException("Bad socket data, headers do not match excpected length"); <END> } } } catch (IllegalStateException | NullPointerException ex) { this.encounteredProtocolError(ex); } }</code><technical_language>typo</technical_language>

Target:
void gatherHeaders(int maxPos) throws IOException { try { while(this.bufferPosition < maxPos) { int possible = maxPos - this.bufferPosition; int want = msgHeaders.length - msgHeadersPosition; if (want > 0 && want <= possible) { System.arraycopy(this.buffer, this.bufferPosition, this.msgHeaders, this.msgHeadersPosition, want); msgHeadersPosition += want; this.bufferPosition += want; continue; } else if (want > 0) { System.arraycopy(this.buffer, this.bufferPosition, this.msgHeaders, this.msgHeadersPosition, possible); msgHeadersPosition += possible; this.bufferPosition += possible; continue; } if (msgHeadersPosition == msgHeaders.length) { incoming.setHeaders(new IncomingHeadersProcessor(msgHeaders)); msgHeaders = null; msgHeadersPosition = -1; this.mode = Mode.GATHER_DATA; break; } else { throw new IllegalStateException("Bad socket data, headers do not match expected length"); } } } catch (IllegalStateException | NullPointerException ex) { this.encounteredProtocolError(ex); } }
Source:
<code>private List<TaskResult> loadTaskResultAllAttempts(Session session, TaskId taskId) { DBTaskId dbTaskId = taskId(taskId); TaskData task = session.load(TaskData.class, dbTaskId); Query query = session.getNamedQuery("loadTasksResultByTaskAsc").setParameter("task", task); List<TaskResultData> resultsData = (List<TaskResultData>) query.list(); List<TaskResult> results = new ArrayList<>(resultsData.size()); for (TaskResultData resultData : resultsData) { results.add(resultData.toTaskResult(taskId)); <START> } <END> return results; }</code><technical_language>Myabe: return ((List<TaskResultData>) query.list()).stream().map(resultData -> resultData.toTaskResult(taskId)).collect(Collectors.toList());</technical_language>

Target:
private List<TaskResult> loadTaskResultAllAttempts(Session session, TaskId taskId) { DBTaskId dbTaskId = taskId(taskId); TaskData task = session.load(TaskData.class, dbTaskId); Query query = session.getNamedQuery("loadTasksResultByTaskAsc").setParameter("task", task); return ((List<TaskResultData>) query.list()).stream() .map(resultData -> resultData.toTaskResult(taskId)) .collect(Collectors.toList()); }
Source:
<code>public synchronized void setAutoCommit(boolean enable) throws SQLException { if (activeConnection != null && activeConnection.isValid(5)) { activeConnection.setAutoCommit(enable); } else { <START> logger.debug("Connection to MySql DB is not available"); <END> } }</code><technical_language>This method is called step in a transaction. I expect establish a connection if exist</technical_language>

Target:
public synchronized void setAutoCommit(boolean enable) throws SQLException { activeConnection.setAutoCommit(enable); }
Source:
<code>public Collection<UUID> nodeIds() { <START> return nodeIds == null ? null : new HashSet<>(nodeIds); <END> }</code><technical_language>result if unmodifiable</technical_language>

Target:
public Collection<UUID> nodeIds() { return nodeIds == null ? null : Collections.unmodifiableCollection(nodeIds); }
Source:
<code>protected void drawGuiContainerBackgroundLayer(float par1, int mouseX, int mouseY) { <START> GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); <END> bindGuiTexture(); int sx = (width - xSize) / 2; int sy = (height - ySize) / 2; drawTexturedModalRect(sx, sy, 0, 0, xSize, ySize); renderCustomOptions(getGuiTop() + 13, par1, mouseX, mouseY); super.drawGuiContainerBackgroundLayer(par1, mouseX, mouseY); }</code><technical_language>GlStateManager.color()</technical_language>

Target:
protected void drawGuiContainerBackgroundLayer(float par1, int mouseX, int mouseY) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); bindGuiTexture(); int sx = (width - xSize) / 2; int sy = (height - ySize) / 2; drawTexturedModalRect(sx, sy, 0, 0, xSize, ySize); renderCustomOptions(getGuiTop() + 13, par1, mouseX, mouseY); super.drawGuiContainerBackgroundLayer(par1, mouseX, mouseY); }
Source:
<code><START> protected AtlasDbRuntimeConfig getAtlasDbRuntimeConfig() throws JsonProcessingException { <END> if (runtimeConfig == null) { if (runtimeConfigFile != null) { runtimeConfig = parseAtlasDbConfig(runtimeConfigFile, AtlasDbRuntimeConfig.class, runtimeConfigRoot); } else { runtimeConfig = AtlasDbRuntimeConfig.defaultRuntimeConfig(); } } return runtimeConfig; }</code><technical_language>JsonProcessingException is thrown in method (parseAtlasDbConfig... throws a RuntimeException if underlying file is malformed I think)</technical_language>

Target:
protected AtlasDbRuntimeConfig getAtlasDbRuntimeConfig() { if (runtimeConfig == null) { if (runtimeConfigFile != null) { runtimeConfig = parseAtlasDbConfig(runtimeConfigFile, AtlasDbRuntimeConfig.class, runtimeConfigRoot); } else { runtimeConfig = AtlasDbRuntimeConfig.defaultRuntimeConfig(); } } return runtimeConfig; }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) { streamBatchConfig.validate(); pipelineConfigurer.addStream(new Stream(streamBatchConfig.name)); if (streamBatchConfig.format == null) { pipelineConfigurer.getStageConfigurer().setOutputSchema(DEFAULT_SCHEMA); <START> } <END> }</code><technical_language>formats allow require a schema, set outputschema. streamBatchConfig.getFormatSpec(), if spec's format is non-null, set output schema accordingly. is a tricky is spec's schema is schema of body, add ts headers fields setting output schema</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { streamBatchConfig.validate(); pipelineConfigurer.addStream(new Stream(streamBatchConfig.name)); if (streamBatchConfig.format == null) { pipelineConfigurer.getStageConfigurer().setOutputSchema(DEFAULT_SCHEMA); } else if (streamBatchConfig.getFormatSpec() != null) { List<Schema.Field> fields = Lists.newArrayList(); fields.add(Schema.Field.of("ts", Schema.of(Schema.Type.LONG))); fields.add(Schema.Field.of("headers", Schema.mapOf(Schema.of(Schema.Type.STRING), Schema.of(Schema.Type.STRING)))); fields.addAll(streamBatchConfig.getFormatSpec().getSchema().getFields()); pipelineConfigurer.getStageConfigurer().setOutputSchema(Schema.recordOf("event", fields)); } }
Source:
<code>private List<PartETag> collectPartETags() { <START> final List<PartETag> partETags = new ArrayList<PartETag>(eTagsBeforeResume.size()); <END> partETags.addAll(eTagsBeforeResume); int index = 0; try { for (; index < futures.size(); index++) { partETags.add(futures.get(index).get()); } } catch (Exception e) { for (; index < futures.size(); index++) { futures.get(index).cancel(true); } throw new SdkClientException( "Unable to complete multi-part upload. Individual part upload failed : " + e.getCause().getMessage(), e.getCause()); } return partETags; }</code><technical_language>do about, suggestion final List<PartETag> partETags = new ArrayList<PartETag>(eTagsBeforeResume.size() + futures.size());</technical_language>

Target:
private List<PartETag> collectPartETags() { final List<PartETag> partETags = new ArrayList<PartETag>(eTagsBeforeResume.size() + futures.size()); partETags.addAll(eTagsBeforeResume); int index = 0; try { for (; index < futures.size(); index++) { partETags.add(futures.get(index).get()); } } catch (Exception e) { for (; index < futures.size(); index++) { futures.get(index).cancel(true); } throw new SdkClientException( "Unable to complete multi-part upload. Individual part upload failed : " + e.getCause().getMessage(), e.getCause()); } return partETags; }
Source:
<code>private void saveStateParamForIdpToRequestSession(String state, String idpOriginKey, HttpServletRequest request) { if (request != null) { request.getSession().setAttribute("xoauth-state-" + idpOriginKey, state); <START> } <END> }</code><technical_language>Is this null check? if is null, this operation sense if access session</technical_language>

Target:
private void saveStateParamForIdpToRequestSession(String state, String idpOriginKey, HttpServletRequest request) { request.getSession().setAttribute("xoauth-state-" + idpOriginKey, state); }
Source:
<code>public ApiClient(ApiClientConfiguration config) { Proxy proxy = ProxySelector.getDefault().select(URI.create(config.getBaseUrl())).iterator().next(); <START> URI proxyUri = URI.create(proxy.type() + "://" + proxy.address()); <END> HttpRoutePlanner routePlanner; if (Proxy.Type.HTTP.equals(proxy.type())) { HttpHost proxyHost = new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme()); routePlanner = new DefaultProxyRoutePlanner(proxyHost); } else { routePlanner = new DefaultRoutePlanner(null); } StandardHttpRequestRetryHandler requestRetryHandler = new StandardHttpRequestRetryHandler(RETRY_COUNT, true); HttpClient client = HttpClientBuilder.create().setRetryHandler(requestRetryHandler) .setUserAgent("OktaSDKJava_v" + Utils.getSdkVersion()).disableCookieManagement() .setRoutePlanner(routePlanner) .build(); this.httpClient = client; this.baseUrl = config.getBaseUrl(); this.apiVersion = config.getApiVersion(); this.configuration = config; this.token = config.getApiToken(); initMarshaller(); }</code><technical_language>if is proxy is configured, proxy is null</technical_language>

Target:
public ApiClient(ApiClientConfiguration config) { Proxy proxy = ProxySelector.getDefault().select(URI.create(config.getBaseUrl())).iterator().next(); HttpRoutePlanner routePlanner; if (Proxy.Type.HTTP.equals(proxy.type())) { URI proxyUri = URI.create(proxy.type() + "://" + proxy.address()); HttpHost proxyHost = new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme()); routePlanner = new DefaultProxyRoutePlanner(proxyHost); } else { routePlanner = new DefaultRoutePlanner(null); } StandardHttpRequestRetryHandler requestRetryHandler = new StandardHttpRequestRetryHandler(RETRY_COUNT, true); HttpClient client = HttpClientBuilder.create().setRetryHandler(requestRetryHandler) .setUserAgent("OktaSDKJava_v" + Utils.getSdkVersion()).disableCookieManagement() .setRoutePlanner(routePlanner) .build(); this.httpClient = client; this.baseUrl = config.getBaseUrl(); this.apiVersion = config.getApiVersion(); this.configuration = config; this.token = config.getApiToken(); initMarshaller(); }
Source:
<code>public CandidateDTO getCandidateByApplicationID(Long applicationID) { Assert.notNull(applicationID); ApplicationEntity applicationEntity = applicationsRepository.findOne(applicationID); CandidateEntity candidateEntity = (applicationEntity != null ? applicationEntity.getCandidateEntity() : null); <START> return converterService.convert(candidateEntity, CandidateDTO.class); <END> }</code><technical_language>converter accept null candidateEntity</technical_language>

Target:
public CandidateDTO getCandidateByApplicationID(Long applicationID) { Assert.notNull(applicationID); ApplicationEntity applicationEntity = applicationsRepository.findOne(applicationID); CandidateDTO candidateDTO = (applicationEntity != null ? converterService .convert(applicationEntity.getCandidateEntity(), CandidateDTO.class) : null); return candidateDTO; }
Source:
<code>private void testQueryCancel(int keyCnt, int valSize, String sql, int timeoutUnits, TimeUnit timeUnit, boolean timeout, boolean checkCanceled) throws Exception { try (Ignite client = startGrid("client")) { IgniteCache<Object, Object> cache = client.cache(DEFAULT_CACHE_NAME); assertEquals(0, cache.localSize()); int p = 1; for (int i = 1; i <= keyCnt; i++) { char[] tmp = new char[valSize]; Arrays.fill(tmp, ' '); cache.put(i, new String(tmp)); if (i/(float)keyCnt >= p/10f) { log().info("Loaded " + i + " of " + keyCnt); p++; } } assertEquals(0, cache.localSize()); SqlFieldsQuery qry = new SqlFieldsQuery(sql); final QueryCursor<List<?>> cursor; if (timeout) { qry.setTimeout(timeoutUnits, timeUnit); cursor = cache.query(qry); } else { cursor = cache.query(qry); client.scheduler().runLocal(new Runnable() { @Override public void run() { cursor.close(); } }, timeoutUnits, timeUnit); } try (QueryCursor<List<?>> ignored = cursor) { cursor.getAll(); if (checkCanceled) fail("Query not canceled"); } catch (CacheException ex) { <START> log().error("Got expected exception", ex); <END> assertNotNull("Must throw correct exception", X.cause(ex, QueryCancelledException.class)); } Thread.sleep(TimeUnit.MILLISECONDS.convert(timeoutUnits, timeUnit) + 3_000); checkCleanState(); } }</code><technical_language>error(...)</technical_language>

Target:
private void testQueryCancel(int keyCnt, int valSize, String sql, int timeoutUnits, TimeUnit timeUnit, boolean timeout, boolean checkCanceled) throws Exception { try (Ignite client = startGrid("client")) { IgniteCache<Object, Object> cache = client.cache(DEFAULT_CACHE_NAME); assertEquals(0, cache.localSize()); int p = 1; for (int i = 1; i <= keyCnt; i++) { char[] tmp = new char[valSize]; Arrays.fill(tmp, ' '); cache.put(i, new String(tmp)); if (i/(float)keyCnt >= p/10f) { log().info("Loaded " + i + " of " + keyCnt); p++; } } assertEquals(0, cache.localSize()); SqlFieldsQuery qry = new SqlFieldsQuery(sql); final QueryCursor<List<?>> cursor; if (timeout) { qry.setTimeout(timeoutUnits, timeUnit); cursor = cache.query(qry); } else { cursor = cache.query(qry); client.scheduler().runLocal(new Runnable() { @Override public void run() { cursor.close(); } }, timeoutUnits, timeUnit); } try (QueryCursor<List<?>> ignored = cursor) { cursor.getAll(); if (checkCanceled) fail("Query not canceled"); } catch (CacheException ex) { error("Got expected exception", ex); assertNotNull("Must throw correct exception", X.cause(ex, QueryCancelledException.class)); } Thread.sleep(TimeUnit.MILLISECONDS.convert(timeoutUnits, timeUnit) + 3_000); checkCleanState(); } }