auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public MachineSet claim(MachineSet set) { <START> init(); <END> synchronized (this) { MachineSet originalClaimed = claimedMachines; claimedMachines = claimedMachines.added(set); MachineSet newlyClaimed = claimedMachines.removed(originalClaimed); if (newlyClaimed.size() != set.size()) { claimedMachines = originalClaimed; MachineSet unavailable = set.removed(newlyClaimed); throw new IllegalArgumentException("Could not claim at least one requested element: "+unavailable); } return newlyClaimed; } }</code><technical_language>Do want ensure of machines (e.g. check if in detected, add that)? is safe add nodes passed in</technical_language>

Target:
public MachineSet claim(MachineSet set) { init(); synchronized (this) { MachineSet originalClaimed = claimedMachines; claimedMachines = claimedMachines.added(set); MachineSet newlyClaimed = claimedMachines.removed(originalClaimed); if (newlyClaimed.size() != set.size()) { claimedMachines = originalClaimed; MachineSet unavailable = set.removed(newlyClaimed); throw new IllegalArgumentException("Could not claim all requested machines; failed to claim "+unavailable); } return newlyClaimed; } }
Source:
<code>public CompletableFuture<LedgerEntries> readAsync(long firstEntry, long lastEntry) { CompletableFuture<LedgerEntries> promise = new CompletableFuture<>(); if (bk.isStopped()) { <START> promise.completeExceptionally(BKException.create(-1)); <END> return promise; } bk.executor.execute(() -> { if (bk.getProgrammedFailStatus()) { promise.completeExceptionally(BKException.create(bk.failReturnCode)); return; } else if (bk.isStopped()) { promise.completeExceptionally(BKException.create(-1)); return; } log.debug("readEntries: first={} last={} total={}", firstEntry, lastEntry, entries.size()); List<LedgerEntry> seq = new ArrayList<>(); long entryId = firstEntry; while (entryId <= lastEntry && entryId < entries.size()) { seq.add(entries.get((int) entryId++).duplicate()); } log.debug("Entries read: {}", seq); promise.complete(LedgerEntriesImpl.create(seq)); }); return promise; }</code><technical_language>Code. ReadException for -1</technical_language>

Target:
public CompletableFuture<LedgerEntries> readAsync(long firstEntry, long lastEntry) { CompletableFuture<LedgerEntries> promise = new CompletableFuture<>(); if (bk.isStopped()) { promise.completeExceptionally(new BKException.BKClientClosedException()); return promise; } bk.executor.execute(() -> { if (bk.getProgrammedFailStatus()) { promise.completeExceptionally(BKException.create(bk.failReturnCode)); return; } else if (bk.isStopped()) { promise.completeExceptionally(new BKException.BKClientClosedException()); return; } log.debug("readEntries: first={} last={} total={}", firstEntry, lastEntry, entries.size()); List<LedgerEntry> seq = new ArrayList<>(); long entryId = firstEntry; while (entryId <= lastEntry && entryId < entries.size()) { seq.add(entries.get((int) entryId++).duplicate()); } log.debug("Entries read: {}", seq); promise.complete(LedgerEntriesImpl.create(seq)); }); return promise; }
Source:
<code>public int archive(final ArchiverFactory factory, OutputStream os, final DirScanner scanner) throws IOException, InterruptedException { final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os; return act(new SecureFileCallable<Integer>() { public Integer invoke(File f, VirtualChannel channel) throws IOException { try (Archiver a = factory.create(out)) { scanner.scan(f,reading(a)); <START> return a.countEntries(); <END> } } private static final long serialVersionUID = 1L; }); }</code><technical_language>moved try block? count (potentially long) closing archiver</technical_language>

Target:
public int archive(final ArchiverFactory factory, OutputStream os, final DirScanner scanner) throws IOException, InterruptedException { final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os; return act(new SecureFileCallable<Integer>() { public Integer invoke(File f, VirtualChannel channel) throws IOException { Archiver a = factory.create(out); try { scanner.scan(f,reading(a)); } finally { a.close(); } return a.countEntries(); } private static final long serialVersionUID = 1L; }); }
Source:
<code>public ObjectInspector getObjectInspector() throws SerDeException { <START> if (LOG.isDebugEnabled()) <END> SpliceLogUtils.trace(LOG, "getObjectInspector"); return rowOI; }</code><technical_language>isTraceEnabled() debug()</technical_language>

Target:
public ObjectInspector getObjectInspector() throws SerDeException { if (LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG, "getObjectInspector"); return rowOI; }
Source:
<code>public void publish(LogRecord record) { initRefreshThread(); ExtMap publishInputMap = new ExtMap() .mput(Base.InvokeKeys.COMMAND, Logger.InvokeCommands.PUBLISH); ExtMap publishOutputMap = new ExtMap(); for (ExtensionProxy extension : getExtensions()) { try { extension.invoke( <START> publishInputMap.mput(Logger.InvokeKeys.LOG_RECORD, record), <END> publishOutputMap); } catch(Exception ex) } }</code><technical_language>please put record well</technical_language>

Target:
public void publish(LogRecord record) { initRefreshThread(); ExtMap publishInputMap = new ExtMap() .mput(Base.InvokeKeys.COMMAND, Logger.InvokeCommands.PUBLISH) .mput(Logger.InvokeKeys.LOG_RECORD, record); ExtMap publishOutputMap = new ExtMap(); for (ExtensionProxy extension : getExtensions()) { try { extension.invoke( publishInputMap, publishOutputMap); } catch(Exception ex) } }
Source:
<code>protected static ImmutableList<Ds3Request> convertRequests( final ImmutableList<Ds3Request> requests, final NameMapper nameMapper) { <START> if (requests == null || requests.isEmpty()) { <END> return ImmutableList.of(); } final ImmutableList.Builder<Ds3Request> builder = ImmutableList.builder(); for (final Ds3Request request : requests) { final Ds3Request convertedRequest = new Ds3Request( request.getName(), request.getHttpVerb(), request.getClassification(), request.getBucketRequirement(), request.getObjectRequirement(), request.getAction(), request.getResource(), request.getResourceType(), request.getOperation(), convertAllResponseCodes(request.getDs3ResponseCodes(), nameMapper), convertAllParams(request.getOptionalQueryParams(), nameMapper), convertAllParams(request.getRequiredQueryParams(), nameMapper)); builder.add(convertedRequest); } return builder.build(); }</code><technical_language>This new isEmpty method</technical_language>

Target:
protected static ImmutableList<Ds3Request> convertRequests( final ImmutableList<Ds3Request> requests, final NameMapper nameMapper) { if (isEmpty(requests)) { return ImmutableList.of(); } final ImmutableList.Builder<Ds3Request> builder = ImmutableList.builder(); for (final Ds3Request request : requests) { final Ds3Request convertedRequest = new Ds3Request( request.getName(), request.getHttpVerb(), request.getClassification(), request.getBucketRequirement(), request.getObjectRequirement(), request.getAction(), request.getResource(), request.getResourceType(), request.getOperation(), convertAllResponseCodes(request.getDs3ResponseCodes(), nameMapper), convertAllParams(request.getOptionalQueryParams(), nameMapper), convertAllParams(request.getRequiredQueryParams(), nameMapper)); builder.add(convertedRequest); } return builder.build(); }
Source:
<code>public void dosCborObject() throws Throwable { byte[] raw = ArrayOps.hexToBytes("5b0004000000000000"); try { CborObject.fromByteArray(raw); <START> throw new Throwable("Should have failed!"); <END> } catch (RuntimeException e) }</code><technical_language><LINK_0></technical_language>

Target:
public void dosCborObject() throws Throwable { byte[] raw = ArrayOps.hexToBytes("5b0004000000000000"); try { CborObject.fromByteArray(raw); Assert.fail("Should have failed!"); } catch (RuntimeException e) }
Source:
<code>private static void initializeApp(Context context) { if (!FirebaseApp.getApps(context).isEmpty()) { return; } for (Field field : FirebaseApp.class.getDeclaredFields()) { field.setAccessible(true); Object o; try { o = field.get(null); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (NullPointerException e) { <START> continue; END> } Type genericType = field.getGenericType(); if (o instanceof Map && genericType instanceof ParameterizedType) { Type[] parameterTypes = ((ParameterizedType) genericType).getActualTypeArguments(); if (parameterTypes.length != 2 || parameterTypes[0] != String.class || parameterTypes[1] != FirebaseApp.class) { continue; } Map<String, FirebaseApp> instances = (Map<String, FirebaseApp>) o; instances.put(FirebaseApp.DEFAULT_APP_NAME, mock(FirebaseApp.class)); break; } } FirebaseApp app = FirebaseApp.getInstance(); when(app.get(eq(FirebaseAuth.class))).thenReturn(mock(FirebaseAuth.class)); when(app.getApplicationContext()).thenReturn(context); when(app.getName()).thenReturn(FirebaseApp.DEFAULT_APP_NAME); }</code><technical_language>hack is ;-)</technical_language>

Target:
private static void initializeApp(Context context) { if (!FirebaseApp.getApps(context).isEmpty()) return; FirebaseApp.initializeApp(context, new FirebaseOptions.Builder() .setApiKey("fake") .setApplicationId("fake") .build()); }
Source:
<code>private static void notNull(Object value, String message) { if (value == null) <START> throw new IllegalArgumentException(message); <END> }</code><technical_language>Please throw NullPointerException instead (also, braces for if statement)</technical_language>

Target:
private static void notNull(Object value, String message) { if (value == null) { throw new NullPointerException(message); } }
Source:
<code>public String[] getSourceNames() { <START> return this.sourcesByName.keySet().toArray(new String[this.sourcesByName.size()]); <END> }</code><technical_language>Please, fix kind of smells explicit array size. Thanks</technical_language>

Target:
public String[] getSourceNames() { return this.sourcesByName.keySet().toArray(new String[0]); }
Source:
<code>public String <START> toString(){ <END> String json = JSONObject.toJSONString(webrequestMap); return "{\"webrequest\":" +json + "}"; }</code><technical_language>Is this a method in production? is more for developing/debugging purposes? If latter, create webrequestMap HashMap this method instead making a field in object. slower for tests recreate print, a lot lighter for production (I guess heap garbage collector feel it, create a WebrequestData object for web request). Also, for webrequest do 1 print, right? In case, speed same. Also, annoying :P, I agree do need {"webrequest": <json>} wrapper, json object fine, no</technical_language>

Target:
public String toString(){ Map webrequestMap = new HashMap<String, String>(); webrequestMap.put("uriHost", this.uriHost); webrequestMap.put("uriPath", this.uriPath); webrequestMap.put("uriQuery", this.uriQuery); webrequestMap.put("httpStatus", this.httpStatus); webrequestMap.put("contentType", this.contentType); webrequestMap.put("userAgent", this.userAgent); webrequestMap.put("X-Analytics", this.rawXAnalyticsHeader); return JSONObject.toJSONString(webrequestMap); }
Source:
<code>public String starlarkStrictDeps() { switch (strictProtoDeps()) { case OFF: return "OFF"; case WARN: <START> return "WARN"; <END> case ERROR: case STRICT: case DEFAULT: return "ERROR"; } Preconditions.checkState(false, "NOTREACHED"); return null; }</code><technical_language>Do "WARN"? AFAIU for Java sandwich, passed in Starlark. if not, a Boolean</technical_language>

Target:
public String starlarkStrictDeps() { switch (strictProtoDeps()) { case OFF: case DEFAULT: return "OFF"; case WARN: return "WARN"; case ERROR: case STRICT: return "ERROR"; } throw new IllegalStateException(); }
Source:
<code>public void getReport(HttpServletRequest request, HttpServletResponse response) throws IOException, BadRequestException, UnauthorizedException { Session session = serviceServiceSupplier.getService().get(request); <START> HSSFWorkbook workbook = createWorkbook(session); <END> response.setContentType(APPLICATION_OCTET_STREAM_VALUE); response.setHeader(CONTENT_DISPOSITION_HEADER, format(CONTENT_DISPOSITION_VALUE, getDateString())); response.setStatus(HttpStatus.OK.value()); workbook.write(response.getOutputStream()); }</code><technical_language>wrap HSSFworkbook a try-catch resources</technical_language>

Target:
public void getReport(HttpServletRequest request, HttpServletResponse response) throws IOException, BadRequestException, UnauthorizedException { Session session = serviceServiceSupplier.getService().get(request); response.setContentType(APPLICATION_OCTET_STREAM_VALUE); response.setHeader(CONTENT_DISPOSITION_HEADER, format(CONTENT_DISPOSITION_VALUE, getDateString())); response.setStatus(HttpStatus.OK.value()); createWorkbook(session, response); }
Source:
<code>private static SummaryStatistics[] getStats(final ArrayOfDoublesSketch sketch) { final SummaryStatistics[] stats = new SummaryStatistics[sketch.getNumValues()]; for (int i = 0; i < stats.length; i++) { <START> stats[i] = new SummaryStatistics(); <END> } final ArrayOfDoublesSketchIterator it = sketch.iterator(); while (it.next()) { final double[] values = it.getValues(); for (int i = 0; i < values.length; i++) { stats[i].addValue(values[i]); } } return stats; }</code><technical_language>Arrays.setAll() is cleaner</technical_language>

Target:
private static SummaryStatistics[] getStats(final ArrayOfDoublesSketch sketch) { final SummaryStatistics[] stats = new SummaryStatistics[sketch.getNumValues()]; Arrays.setAll(stats, i -> new SummaryStatistics()); final ArrayOfDoublesSketchIterator it = sketch.iterator(); while (it.next()) { final double[] values = it.getValues(); for (int i = 0; i < values.length; i++) { stats[i].addValue(values[i]); } } return stats; }
Source:
<code>private <T extends TransportResponse> void executeRetryableAction(String action, RecoveryTransportRequest request, TransportRequestOptions options, ActionListener<T> actionListener, Writeable.Reader<T> reader) { final Object key = new Object(); final ActionListener<T> removeListener = ActionListener.runBefore(actionListener, () -> onGoingRetryableActions.remove(key)); final TimeValue initialDelay = TimeValue.timeValueMillis(200); final TimeValue timeout = recoverySettings.internalActionRetryTimeout(); final RetryableAction<T> retryableAction = new RetryableAction<>(logger, threadPool, initialDelay, timeout, removeListener, ThreadPool.Names.GENERIC) { @Override public void tryAction(ActionListener<T> listener) { transportService.sendRequest(targetNode, action, request, options, new ActionListenerResponseHandler<>(listener, reader, ThreadPool.Names.GENERIC)); } @Override public boolean shouldRetry(Exception e) { <START> return retriesSupported && clusterService.state().nodes().nodeExists(targetNode) && retryableException(e); <END> } }; onGoingRetryableActions.put(key, retryableAction); retryableAction.run(); if (isCancelled) { retryableAction.cancel(new CancellableThreads.ExecutionCancelledException("recovery was cancelled")); } }</code><technical_language>ClusterStateObserver is magical here. registered schedule a retry, early cancel a scheduled retry target node drops cluster</technical_language>

Target:
private <T extends TransportResponse> void executeRetryableAction(String action, RecoveryTransportRequest request, TransportRequestOptions options, ActionListener<T> actionListener, Writeable.Reader<T> reader) { final Object key = new Object(); final ActionListener<T> removeListener = ActionListener.runBefore(actionListener, () -> onGoingRetryableActions.remove(key)); final TimeValue initialDelay = TimeValue.timeValueMillis(200); final TimeValue timeout = recoverySettings.internalActionRetryTimeout(); final RetryableAction<T> retryableAction = new RetryableAction<>(logger, threadPool, initialDelay, timeout, removeListener) { @Override public void tryAction(ActionListener<T> listener) { transportService.sendRequest(targetNode, action, request, options, new ActionListenerResponseHandler<>(listener, reader, ThreadPool.Names.GENERIC)); } @Override public boolean shouldRetry(Exception e) { return retriesSupported && retryableException(e); } }; onGoingRetryableActions.put(key, retryableAction); retryableAction.run(); if (isCancelled) { retryableAction.cancel(new CancellableThreads.ExecutionCancelledException("recovery was cancelled")); } }
Source:
<code><START> private static Set<Diff> removePseudoConflicts(Set<Diff> diffs) { <END> Set<Diff> resultSet = new LinkedHashSet<Diff>(); for (Diff diff : diffs) { if (diff.getConflict() != null && diff.getConflict().getKind() == PSEUDO) { } else { resultSet.add(diff); } } return resultSet; }</code><technical_language>Please check filter set creating a new copy, this improve performance</technical_language>

Target:
private static Set<Diff> removePseudoConflicts(Set<Diff> diffs) { Predicate<Diff> isInConflict = new Predicate<Diff>() { public boolean apply(Diff input) { return input != null && input.getConflict() != null; } }; Set<Diff> resultSet = Sets.filter(diffs, or(not(isInConflict), hasConflict(REAL))); return resultSet; }
Source:
<code>public void testVisitTokenSwitchReflection() { final DetailAST astImport = mockAST(TokenTypes.IMPORT, "import", "mockfile", 0, 0); final DetailAST astIdent = mockAST(TokenTypes.IDENT, "myTestImport", "mockfile", 0, 0); astImport.addChild(astIdent); final DetailAST astSemi = mockAST(TokenTypes.SEMI, ";", "mockfile", 0, 0); astIdent.addNextSibling(astSemi); final Locale defaultLocale = Locale.getDefault(); try { <START> Locale.setDefault(Locale.ENGLISH); <END> final ImportOrderCheck mock = new ImportOrderCheck(); final ImportOrderOption importOrderOptionMock = PowerMockito .mock(ImportOrderOption.class); Whitebox.setInternalState(importOrderOptionMock, "name", "NEW_OPTION_FOR_UT"); Whitebox.setInternalState(importOrderOptionMock, "ordinal", 5); Whitebox.setInternalState(mock, "option", importOrderOptionMock); try { mock.visitToken(astImport); fail("exception expected"); } catch (IllegalStateException ex) { assertEquals("Unexpected option for static imports: importOrderOption", ex.getMessage()); } } finally { Locale.setDefault(defaultLocale); } }</code><technical_language>I do this fix .... please put a CS suppression this method restore it. I review this case in separate PR, other changes applied master</technical_language>

Target:
public void testVisitTokenSwitchReflection() { final DetailAST astImport = mockAST(TokenTypes.IMPORT, "import", "mockfile", 0, 0); final DetailAST astIdent = mockAST(TokenTypes.IDENT, "myTestImport", "mockfile", 0, 0); astImport.addChild(astIdent); final DetailAST astSemi = mockAST(TokenTypes.SEMI, ";", "mockfile", 0, 0); astIdent.addNextSibling(astSemi); final ImportOrderCheck mock = new ImportOrderCheck(); final ImportOrderOption importOrderOptionMock = PowerMockito.mock(ImportOrderOption.class); Whitebox.setInternalState(importOrderOptionMock, "name", "NEW_OPTION_FOR_UT"); Whitebox.setInternalState(importOrderOptionMock, "ordinal", 5); Whitebox.setInternalState(mock, "option", importOrderOptionMock); mock.visitToken(astImport); }
Source:
<code>protected void validateSession( final IOSession ioSession, final Callback<Boolean> callback) { final TimeValue timeValue = validateAfterInactivity; <START> if (TimeValue.ZERO_MILLISECONDS.equals(timeValue) || TimeValue.isPositive(timeValue)) { <END> final long lastAccessTime = Math.min(ioSession.getLastReadTime(), ioSession.getLastWriteTime()); final long deadline = lastAccessTime + timeValue.toMilliseconds(); if (deadline <= System.currentTimeMillis()) { final Timeout socketTimeoutMillis = ioSession.getSocketTimeout(); ioSession.enqueue(new PingCommand(new BasicPingHandler(new Callback<Boolean>() { @Override public void execute(final Boolean result) { ioSession.setSocketTimeout(socketTimeoutMillis); callback.execute(result); } })), Command.Priority.NORMAL); return; } } callback.execute(true); }</code><technical_language>@pfrank13 reason for TimeValue#compareTo here</technical_language>

Target:
protected void validateSession( final IOSession ioSession, final Callback<Boolean> callback) { final TimeValue timeValue = validateAfterInactivity; if (TimeValue.isNonNegative(timeValue)) { final long lastAccessTime = Math.min(ioSession.getLastReadTime(), ioSession.getLastWriteTime()); final long deadline = lastAccessTime + timeValue.toMilliseconds(); if (deadline <= System.currentTimeMillis()) { final Timeout socketTimeoutMillis = ioSession.getSocketTimeout(); ioSession.enqueue(new PingCommand(new BasicPingHandler(new Callback<Boolean>() { @Override public void execute(final Boolean result) { ioSession.setSocketTimeout(socketTimeoutMillis); callback.execute(result); } })), Command.Priority.NORMAL); return; } } callback.execute(true); }
Source:
<code>public String docs() { return "mixed {Locationarray} Returns the list regions at the location." <START> + " If region is found, an array of region names are returned, else an empty is returned"; <END> }</code><technical_language>Grammar Nazi: "Returns a list of regions location. If regions found, array of region names returned, otherwise, empty array is returned."</technical_language>

Target:
public String docs() { return "mixed {Locationarray} Returns a list of regions at the specified location. " + "If regions are found, an array of region names are returned, otherwise, an empty array is returned."; }
Source:
<code>public static void cleanup() throws Exception { <START> SecurityTestUtil.cleanup(); <END> stopAllServers(); }</code><technical_language>This method is removed in latest codebase</technical_language>

Target:
public static void cleanup() throws Exception { stopAllServers(); }
Source:
<code>public List<VocabularyExtension> getExtensions() { <START> return this.extensions.get(); <END> }</code><technical_language>this return extensions, valid for this vocabulary? latter</technical_language>

Target:
public List<VocabularyExtension> getExtensions() { List<VocabularyExtension> result = new LinkedList<>(); for (VocabularyExtension extension : this.extensions.get()) { if (extension.isVocabularySupported(this)) { result.add(extension); } } return result; }
Source:
<code>static public ServiceType getMetaData() { ServiceType meta = new ServiceType(ProgramAB.class); meta.addDescription("AIML 2.0 Reference interpreter based on Program AB"); meta.addCategory("ai"); meta.addPeer("search", "GoogleSearch", "replacement for handling pannous sriax requests"); <START> meta.addDependency("program-ab", "program-ab-data", null, "zip"); <END> meta.addDependency("program-ab", "program-ab-kw", "0.0.8.5"); meta.addDependency("org.json", "json", "20090211"); meta.addDependency("commons-io", "commons-io", "2.5"); meta.addDependency("org.apache.lucene", "lucene-analyzers-common", "8.4.1"); meta.addDependency("org.apache.lucene", "lucene-analyzers-kuromoji", "8.4.1"); meta.addCategory("ai", "control"); return meta; }</code><technical_language>including program-ab-data a dependency, removed pom.xml ..</technical_language>

Target:
static public ServiceType getMetaData() { ServiceType meta = new ServiceType(ProgramAB.class); meta.addDescription("AIML 2.0 Reference interpreter based on Program AB"); meta.addCategory("ai"); meta.addPeer("search", "GoogleSearch", "replacement for handling pannous sriax requests"); meta.addDependency("program-ab", "program-ab-data", null, "zip"); meta.addDependency("program-ab", "program-ab-kw", "0.0.8.6"); meta.addDependency("org.json", "json", "20090211"); meta.addDependency("commons-io", "commons-io", "2.5"); meta.addDependency("org.apache.lucene", "lucene-analyzers-common", "8.4.1"); meta.addDependency("org.apache.lucene", "lucene-analyzers-kuromoji", "8.4.1"); meta.addCategory("ai", "control"); return meta; }
Source:
<code>public boolean providesShapes(EObject view) { if (!(view instanceof View)) { return false; } View v = (View) view; if (!isShapeStyleEnable(v)) { return false; } <START> String svgFile = extract((StringValueStyle) v.getNamedStyle(NotationPackage.eINSTANCE.getStringValueStyle(), STYLE_PROPERTY)); <END> return (svgFile != null); }</code><technical_language>issue if do account new property</technical_language>

Target:
public boolean providesShapes(EObject view) { if (!(view instanceof View)) { return false; } View v = (View) view; if (!isShapeStyleEnable(v)) { return false; } String svgFile = extract((StringValueStyle) v.getNamedStyle(NotationPackage.eINSTANCE.getStringValueStyle(), STYLE_PROPERTY)); String imagePath = NotationUtils.getStringValue(v, IMAGE_PATH_PROPERTY, null); return (svgFile != null || imagePath != null); }
Source:
<code>private void updatePhysicalInfo(TableDesc desc) { if (!desc.getMeta().getStoreType().equals("SYSTEM") && !desc.getMeta().getStoreType().equals("FAKEFILE")) { try { if (desc.getStats() != null) { desc.getStats().setNumBytes(storage.getTableVolumn(desc.getUri())); } <START> } catch (Throwable t) { <END> LOG.warn(desc.getName() + " does not support Tablespace::getTableVolume()"); desc.getStats().setNumBytes(-1); } } }</code><technical_language>This line changed catch UnsupportedException</technical_language>

Target:
private void updatePhysicalInfo(TableDesc desc) { if (!desc.getMeta().getStoreType().equals("SYSTEM") && !desc.getMeta().getStoreType().equals("FAKEFILE")) { try { if (desc.getStats() != null) { desc.getStats().setNumBytes(storage.getTableVolumn(desc.getUri())); } } catch (UnsupportedException t) { LOG.warn(desc.getName() + " does not support Tablespace::getTableVolume()"); desc.getStats().setNumBytes(-1); } } }
Source:
<code>public void setup() throws Exception { CrlGenerator.issuerEncryptionPropertiesLocation = getClass().getResource("/issuer/encryption.properties").getPath(); CrlGenerator.issuerSignaturePropertiesLocation = getClass().getResource("/issuer/signature.properties").getPath(); CrlGenerator.serverEncryptionPropertiesLocation = getClass().getResource("/server/encryption.properties").getPath(); CrlGenerator.serverSignaturePropertiesLocation = getClass().getResource("/server/signature.properties").getPath(); CrlGenerator.crlFileLocation = temporaryFolder.getRoot().toString(); <START> InputStream inputStream = <END> new FileInputStream(new File(getClass().getResource("/root.crl").getPath())); demEncodedCrl = new byte[inputStream.available()]; inputStream.read(demEncodedCrl); }</code><technical_language>unit test code, try-with-resources ensure streams closed</technical_language>

Target:
public void setup() throws Exception { CrlGenerator.issuerEncryptionPropertiesLocation = getClass().getResource("/issuer/encryption.properties").getPath(); CrlGenerator.issuerSignaturePropertiesLocation = getClass().getResource("/issuer/signature.properties").getPath(); CrlGenerator.serverEncryptionPropertiesLocation = getClass().getResource("/server/encryption.properties").getPath(); CrlGenerator.serverSignaturePropertiesLocation = getClass().getResource("/server/signature.properties").getPath(); CrlGenerator.crlFileLocation = temporaryFolder.getRoot().toString(); try (InputStream inputStream = new FileInputStream(new File(getClass().getResource("/root.crl").getPath()))) { demEncodedCrl = new byte[inputStream.available()]; inputStream.read(demEncodedCrl); } }
Source:
<code>public void shouldDenyAccess() { AuthorizationRequest authorizationRequest = initAuthorizationRequestCall(CLIENT_ID, REDIRECT_URI); String key = authorizationRequest.getAuthorizationKey(); Map<String, String> params = new HashMap<>(); params.put(REDIRECT_URI_PARAM, REDIRECT_URI); params.put(CLIENT_ID_PARAM, CLIENT_ID); params.put(STATE_PARAM, STATE); params.put(NuxeoOAuth2Servlet.AUTHORIZATION_KEY, key); ClientResponse cr = responseFromPostAuthorizationWith(params); <START> String redirect = cr.getHeaders().get("Location").get(0); <END> assertTrue(redirect.contains("error=access_denied")); Set<String> keys = store.keySet(); assertFalse(keys.contains(key)); }</code><technical_language>add assertEquals(302, cr.getStatus());</technical_language>

Target:
public void shouldDenyAccess() { AuthorizationRequest authorizationRequest = initAuthorizationRequestCall(CLIENT_ID, REDIRECT_URI); String key = authorizationRequest.getAuthorizationKey(); Map<String, String> params = new HashMap<>(); params.put(REDIRECT_URI_PARAM, REDIRECT_URI); params.put(CLIENT_ID_PARAM, CLIENT_ID); params.put(STATE_PARAM, STATE); params.put(NuxeoOAuth2Servlet.AUTHORIZATION_KEY, key); ClientResponse cr = responseFromPostAuthorizationWith(params); assertEquals(302, cr.getStatus()); String redirect = cr.getHeaders().get("Location").get(0); assertTrue(redirect.contains("error=access_denied")); Set<String> keys = store.keySet(); assertFalse(keys.contains(key)); }
Source:
<code><START> public static void refreshResolve() { <END> try { if(hostname == null || hostname.isEmpty()) { hostname = java.net.InetAddress.getLocalHost().getHostName(); if (hostname == null) { hostname = "localhost"; } lastUpdate = System.currentTimeMillis(); } } catch (UnknownHostException e) { } }</code><technical_language>want mutex this a ton of threads performing refresh simultaneously</technical_language>

Target:
public static void refreshResolve() { try { if(envHostname == null || envHostname.isEmpty()) { hostname = java.net.InetAddress.getLocalHost().getHostName(); if (hostname == null) { hostname = "localhost"; } lastUpdate = System.currentTimeMillis(); } } catch (UnknownHostException e) { } }
Source:
<code>public RecentChangesPoller(WikibaseRepository wikibase, Date firstStartTime, int batchSize, Map<Long, Boolean> seenIDs, int tailSeconds) { this.wikibase = wikibase; <START> this.firstStartTime = firstStartTime != null ? new Date(firstStartTime.getTime()) : null; <END> this.batchSize = batchSize; this.seenIDs = seenIDs; this.tailSeconds = tailSeconds; }</code><technical_language>dates - move immutable ones</technical_language>

Target:
public RecentChangesPoller(WikibaseRepository wikibase, Date firstStartTime, int batchSize, Map<Long, Boolean> seenIDs, int tailSeconds) { this.wikibase = wikibase; this.firstStartTime = firstStartTime; this.batchSize = batchSize; this.seenIDs = seenIDs; this.tailSeconds = tailSeconds; }
Source:
<code>private void generateClassLoaderModelRepositoryFiles(ApplicationClassloaderModel appModel) { appModel.getMulePluginsClassloaderModels().stream().forEach(mulePluginClassLoaderModel -> { Artifact artifact = appModel.getArtifacts().stream() .filter(possibleArtifact -> possibleArtifact.getArtifactCoordinates() .equals(mulePluginClassLoaderModel.getArtifactCoordinates())) .findFirst() .orElseThrow(() -> new RuntimeException(format("Cannot resolve artifact folder for class loader model: [%s]", mulePluginClassLoaderModel.getArtifactCoordinates()))); File artifactFolderDestination = artifact.getFormattedMavenDirectory(outputDirectory.toPath().resolve(META_INF.value()) .resolve(MULE_ARTIFACT.value()).toFile()); if (!artifactFolderDestination.exists()) { artifactFolderDestination.mkdirs(); } <START> MuleContentGenerator.createClassLoaderModelJsonFile(new NotParameterizedClassLoaderModel(mulePluginClassLoaderModel), <END> artifactFolderDestination); }); }</code><technical_language>static import</technical_language>

Target:
private void generateClassLoaderModelRepositoryFiles(ApplicationClassloaderModel appModel) { appModel.getMulePluginsClassloaderModels().stream().forEach(mulePluginClassLoaderModel -> { Artifact artifact = appModel.getArtifacts().stream() .filter(possibleArtifact -> possibleArtifact.getArtifactCoordinates() .equals(mulePluginClassLoaderModel.getArtifactCoordinates())) .findFirst() .orElseThrow(() -> new RuntimeException(format("Cannot resolve artifact folder for class loader model: [%s]", mulePluginClassLoaderModel.getArtifactCoordinates()))); File artifactFolderDestination = artifact.getFormattedMavenDirectory(outputDirectory.toPath().resolve(META_INF.value()) .resolve(MULE_ARTIFACT.value()).toFile()); if (!artifactFolderDestination.exists()) { artifactFolderDestination.mkdirs(); } createClassLoaderModelJsonFile(new NotParameterizedClassLoaderModel(mulePluginClassLoaderModel), artifactFolderDestination); }); }
Source:
<code>protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { LOGGER.entering(); Map<String, String> requestParams = ServletHelper.getParameters(req); if (requestParams.get(GridAutoUpgradeDelegateServlet.PARAM_JSON) == null) { ServletHelper.respondAsJsonWithHttpStatus(resp, new JsonResponse().setFailed(), HttpServletResponse.SC_BAD_REQUEST); LOGGER.exiting(); return; } if (CONFIGURED_TOKEN_VALUE.equals(requestParams.get(TOKEN_PARAMETER))) { try { String json = requestParams.get(GridAutoUpgradeDelegateServlet.PARAM_JSON); FileUtils.writeStringToFile(new File(SeLionGridConstants.DOWNLOAD_JSON_FILE), json); ServletHelper.respondAsJsonWithHttpStatus(resp, new JsonResponse().setSuccess(), HttpServletResponse.SC_OK); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); JsonResponse exceptionResponse = new JsonResponse(); exceptionResponse.setResult(e.getLocalizedMessage()); ServletHelper.respondAsJsonWithHttpStatus(resp, exceptionResponse, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { <START> ServletHelper.respondAsJsonWithHttpStatus(resp, new JsonResponse().setFailed(), <END> HttpServletResponse.SC_FORBIDDEN); } LOGGER.exiting(); }</code><technical_language>I reverse this if handle this error condition first</technical_language>

Target:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { LOGGER.entering(); Map<String, String> requestParams = ServletHelper.getParameters(req); if (requestParams.get(GridAutoUpgradeDelegateServlet.PARAM_JSON) == null) { ServletHelper.respondAsJsonWithHttpStatus(resp, new NodeResponseBody().setFailed(), HttpServletResponse.SC_BAD_REQUEST); LOGGER.exiting(); return; } if (!CONFIGURED_TOKEN_VALUE.equals(requestParams.get(TOKEN_PARAMETER))) { ServletHelper.respondAsJsonWithHttpStatus(resp, new NodeResponseBody().setFailed(), HttpServletResponse.SC_FORBIDDEN); LOGGER.exiting(); return; } try { String json = requestParams.get(GridAutoUpgradeDelegateServlet.PARAM_JSON); FileUtils.writeStringToFile(new File(SeLionGridConstants.DOWNLOAD_JSON_FILE), json); ServletHelper.respondAsJsonWithHttpStatus(resp, new NodeResponseBody().setSuccess(), HttpServletResponse.SC_OK); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); NodeResponseBody exceptionResponse = new NodeResponseBody(e.getLocalizedMessage()); ServletHelper.respondAsJsonWithHttpStatus(resp, exceptionResponse, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } LOGGER.exiting(); }
Source:
<code>public boolean send(Slice f) { if (sendQueue.offer(f)) { try { <START> lock.lock(); <END> if (!isWriteEnabled) { resumeWriteIfSuspended(); isWriteEnabled = true; } } finally { lock.unlock(); } return true; } return false; }</code><technical_language>For optimization check !isWriteEnabled lock well</technical_language>

Target:
public boolean send(Slice f) { final NetletThrowable throwable = throwables.poll(); if (throwable != null) { NetletThrowable.Util.throwRuntime(throwable); } if (sendQueue.offer(f)) { try { lock.lock(); if (!isWriteEnabled) { resumeWriteIfSuspended(); isWriteEnabled = true; } } finally { lock.unlock(); } return true; } return false; }
Source:
<code>private Collection<String> findCurrentErrorRefs() { Diagram diagram = sessionManager.getCurrentSession().getCanvasHandler().getDiagram(); final Set<String> errorRefs = new HashSet<>(); @SuppressWarnings("unchecked") final Iterable<Element> it = diagram.getGraph().nodes(); <START> it.forEach(element -> { <END> if (element.getContent() instanceof View) { Object definition = ((View) element.getContent()).getDefinition(); ErrorRef errorRef = null; if (definition instanceof EndErrorEvent) { errorRef = ((EndErrorEvent) definition).getExecutionSet().getErrorRef(); } if (errorRef != null && errorRef.getValue() != null && !errorRef.getValue().isEmpty()) { errorRefs.add(errorRef.getValue()); } } }); return errorRefs; }</code><technical_language>a big fan of functional programming possible, this code a good candidate for, it? In addition of streams intermediate operations results in a performance... infinite stream apply some intermediate filter / map operations achieve results, for example: return StreamSupport.stream(it.spliterator(), false) .filter(e -> e.getContent() instanceof View) .filter(e -> ((View) e.getContent()).getDefinition() instanceof EndErrorEvent) .map(e -> ((View) e.getContent()).getDefinition()) .map(e -> ((EndErrorEvent)e).getExecutionSet().getErrorRef()) .filter(errorRef -> errorRef != null && errorRef.getValue() != null && !errorRef.getValue().isEmpty()) .map(ErrorRef::getValue) .collect(Collectors.toSet()); map result a Map<Object, String> caller for this method expects, you. WDYT</technical_language>

Target:
private Collection<String> findCurrentErrorRefs() { Diagram diagram = sessionManager.getCurrentSession().getCanvasHandler().getDiagram(); @SuppressWarnings("unchecked") Iterable<Node> it = diagram.getGraph().nodes(); return StreamSupport.stream(it.spliterator(), false) .filter(e -> e.getContent() instanceof View) .filter(e -> ((View) e.getContent()).getDefinition() instanceof EndErrorEvent) .map(e -> (EndErrorEvent) ((View) e.getContent()).getDefinition()) .map(e -> e.getExecutionSet().getErrorRef()) .filter(errorRef -> errorRef != null && errorRef.getValue() != null && !errorRef.getValue().isEmpty()) .map(ErrorRef::getValue) .collect(Collectors.toSet()); }
Source:
<code>Optional<S3Configuration> getS3ConfigIfEnabled() { Optional<S3Configuration> s3Config = Optional.empty(); if (StringUtils.isTruthy(s3Bucket)) { S3Configuration config = new S3Configuration(); config.setBucket(s3Bucket); config.setPath(s3Path); config.setRegion(s3Region); config.setAccessKey(s3AwsKey); config.setSecretKey(s3AwsSecret); config.setSessionToken(s3AwsSessionToken); config.setServiceEndpoint(s3ServiceEndpoint); config.setSigningRegion(s3SigningRegion); <START> config.setCannedAcl(CannedAccessControlList.valueOf(s3CannedAcl)); <END> S3Configuration.S3SSEConfiguration sseConfig = null; if (s3SseKeyType != null) { sseConfig = new S3Configuration.S3SSEConfiguration( S3Configuration.SSEType.valueOf(s3SseKeyType), null ); } config.setSseConfiguration(sseConfig); s3Config = Optional.of(config); } return s3Config; }</code><technical_language>try { config.setCannedAclFromValue(s3CannedAcl); } catch (IllegalArgumentException ex) { System.err.println(String.format("Ignoring unrecognized canned ACL %s", s3CannedAcl)); }</technical_language>

Target:
Optional<S3Configuration> getS3ConfigIfEnabled() { Optional<S3Configuration> s3Config = Optional.empty(); if (StringUtils.isTruthy(s3Bucket)) { S3Configuration config = new S3Configuration(); config.setBucket(s3Bucket); config.setPath(s3Path); config.setRegion(s3Region); config.setAccessKey(s3AwsKey); config.setSecretKey(s3AwsSecret); config.setSessionToken(s3AwsSessionToken); config.setServiceEndpoint(s3ServiceEndpoint); config.setSigningRegion(s3SigningRegion); try { config.setCannedAclFromValue(s3CannedAcl); } catch (IllegalArgumentException ex) { System.err.println(String.format("Ignoring unrecognized canned ACL value %s", s3CannedAcl)); } S3Configuration.S3SSEConfiguration sseConfig = null; if (s3SseKeyType != null) { sseConfig = new S3Configuration.S3SSEConfiguration( S3Configuration.SSEType.valueOf(s3SseKeyType), null ); } config.setSseConfiguration(sseConfig); s3Config = Optional.of(config); } return s3Config; }
Source:
<code>private void loadInstalledMaps() { taskService.submitTask(new CompletableTask<Void>(Priority.LOW) { protected Void call() { updateTitle(i18n.get("mapVault.loadingMaps")); Path officialMapsPath = forgedAlliancePreferences.getPath().resolve("maps"); try (Stream<Path> customMapsDirectoryStream = list(customMapsDirectory)) { List<Path> mapPaths = new ArrayList<>(); customMapsDirectoryStream.collect(toCollection(() -> mapPaths)); officialMaps.stream() <START> .map(mapName -> officialMapsPath.resolve(mapName)) <END> .collect(toCollection(() -> mapPaths)); long totalMaps = mapPaths.size(); long mapsRead = 0; for (Path mapPath : mapPaths) { updateProgress(++mapsRead, totalMaps); addSkirmishMap(mapPath); } } catch (IOException e) { logger.warn("Maps could not be read from: " + customMapsDirectory, e); } return null; } }); }</code><technical_language>This a function reference</technical_language>

Target:
private void loadInstalledMaps() { taskService.submitTask(new CompletableTask<Void>(Priority.LOW) { protected Void call() { updateTitle(i18n.get("mapVault.loadingMaps")); Path officialMapsPath = forgedAlliancePreferences.getPath().resolve("maps"); try (Stream<Path> customMapsDirectoryStream = list(customMapsDirectory)) { List<Path> mapPaths = new ArrayList<>(); customMapsDirectoryStream.collect(toCollection(() -> mapPaths)); officialMaps.stream() .map(officialMapsPath::resolve) .collect(toCollection(() -> mapPaths)); long totalMaps = mapPaths.size(); long mapsRead = 0; for (Path mapPath : mapPaths) { updateProgress(++mapsRead, totalMaps); addSkirmishMap(mapPath); } } catch (IOException e) { logger.warn("Maps could not be read from: " + customMapsDirectory, e); } return null; } }); }
Source:
<code>public CrossSiteOriginFilter(final DolphinPlatformConfiguration configuration){ <START> this.configuration = configuration; <END> }</code><technical_language>this.configuration = Assert.requireNonNull(this.configuration, "this.configuration"); this pattern for final param is created constructor. exceptions in case of a null thrown early</technical_language>

Target:
public CrossSiteOriginFilter(final DolphinPlatformConfiguration configuration){ this.configuration = Assert.requireNonNull(configuration, "configuration"); }
Source:
<code>protected void saveMetadata() { Path metadata = getMetadataPath(); StringBuilder builder = new StringBuilder(); builder.append( <START> String.format("# Log created %s%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date()))); <END> builder.append(String.format("%s=%d%n", PARTITIONS_KEY, nbPartitions)); builder.append(String.format("%s=%s%n", RETENTION_KEY, retention)); builder.append(String.format("%s=%d%n", BLOCK_SIZE_KEY, blockSize)); try { Files.write(metadata, builder.toString().getBytes(), StandardOpenOption.CREATE_NEW); } catch (IOException e) { throw new IllegalArgumentException("Unable to create metadata file: " + metadata, e); } if (log.isDebugEnabled()) { log.debug(String.format("Created Log: %s%n%s", name, builder.toString()), new Throwable("here")); } }</code><technical_language>If exact format matter, Instant.now().toString() is simpler</technical_language>

Target:
protected void saveMetadata() { Path metadata = getMetadataPath(); StringBuilder builder = new StringBuilder(); builder.append(String.format("# Log created %s%n", Instant.now().toString())); builder.append(String.format("%s=%d%n", PARTITIONS_KEY, nbPartitions)); builder.append(String.format("%s=%s%n", RETENTION_KEY, retention)); builder.append(String.format("%s=%d%n", BLOCK_SIZE_KEY, blockSize)); try { Files.write(metadata, builder.toString().getBytes(), StandardOpenOption.CREATE_NEW); } catch (IOException e) { throw new IllegalArgumentException("Unable to create metadata file: " + metadata, e); } if (log.isDebugEnabled()) { log.debug(String.format("Created Log: %s%n%s", name, builder.toString()), new Throwable("here")); } }
Source:
<code>private String generateStatusToAdmin(Map<String, JoinEmailData> emailDataMap, String courseId) { StringBuilder statusToAdmin = new StringBuilder(200); statusToAdmin.append("Registration Key sent to the following users in Course <span class=\"bold\">[") .append(courseId) .append("]</span>:<br>"); Iterator<Entry<String, JoinEmailData>> emailIterator = emailDataMap.entrySet().iterator(); while (emailIterator.hasNext()) { <START> Entry<String, JoinEmailData> email = emailIterator.next(); <END> String userEmail = email.getKey(); JoinEmailData joinEmailData = email.getValue(); statusToAdmin.append(joinEmailData.userName).append("<span class=\"bold\"> (").append(userEmail) .append(")</span>.<br>").append(joinEmailData.regKey).append("<br>"); } return statusToAdmin.toString(); }</code><technical_language>Is enhanced for loop for iteration</technical_language>

Target:
private String generateStatusToAdmin(Map<String, JoinEmailData> emailDataMap, String courseId) { StringBuilder statusToAdmin = new StringBuilder(200); statusToAdmin.append("Registration Key sent to the following users in Course <span class=\"bold\">[") .append(courseId) .append("]</span>:<br>"); Set<Entry<String, JoinEmailData>> entries = emailDataMap.entrySet(); for (Entry<String, JoinEmailData> entry : entries) { String userEmail = entry.getKey(); JoinEmailData joinEmailData = entry.getValue(); statusToAdmin.append(joinEmailData.userName) .append("<span class=\"bold\"> (").append(userEmail).append(")</span>.<br>") .append(joinEmailData.regKey).append("<br>"); } return statusToAdmin.toString(); }
Source:
<code>public void testConnectContainerToNetwork() throws Exception { MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200)); NetworkApi api = api(DockerApi.class, server.getUrl("/").toString()).getNetworkApi(); try { api.connectContainerToNetwork("1", "containerName"); <START> assertSent(server, "POST", "/networks/1/connect"); <END> } finally { server.shutdown(); } }</code><technical_language>I mean, is call generates a body; a requestLine. assertSent verify is sending right payload. example [GCE mock tests](<LINK_0> This applied mock test classes, fix network mock in this PR</technical_language>

Target:
public void testConnectContainerToNetwork() throws Exception { MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200)); NetworkApi api = api(DockerApi.class, server.getUrl("/").toString()).getNetworkApi(); try { api.connectContainerToNetwork("123456789", "containerName"); assertSent(server, "POST", "/networks/123456789/connect", "{ \"Container\": \"containerName\" }"); } finally { server.shutdown(); } }
Source:
<code>public void shouldFindDocumentByQuery() throws Exception { Thread.sleep(2000); Searcher searcher = new Searcher("testsearch"); String query = "{\n\"match_all\" : {}\n}"; JsonObject result = searcher.findDocument(query); JsonObject jsonObject = result.getJsonObject("_source"); Integer id = getIdFromJSONObject(result); assertEquals("Incorrect result - id doesn't match to given number!", 1, id.intValue()); String title = jsonObject.getString("title"); assertEquals("Incorrect result - title doesn't match to given plain text!", "Batch1", title); query = "{\n\"match\" : {\n\"title\" : \"Batch1\"}\n}"; result = searcher.findDocument(query); jsonObject = result.getJsonObject("_source"); id = getIdFromJSONObject(result); assertEquals("Incorrect result - id doesn't match to given plain text!", 1, id.intValue()); title = jsonObject.getString("title"); assertEquals("Incorrect result - title doesn't match to given plain text!", "Batch1", title); query = "{\n\"match\" : {\n\"title\" : \"Nonexistent\"}\n}"; result = searcher.findDocument(query); <START> System.out.println(result); <END> id = getIdFromJSONObject(result); assertEquals("Incorrect result - id has another value than null!", Integer.valueOf(0), id); }</code><technical_language>Is this System.out.println() call needed? a logger call</technical_language>

Target:
public void shouldFindDocumentByQuery() throws Exception { Thread.sleep(2000); Searcher searcher = new Searcher("testsearch"); String query = "{\n\"match_all\" : {}\n}"; JsonObject result = searcher.findDocument(query); JsonObject jsonObject = result.getJsonObject("_source"); Integer id = getIdFromJSONObject(result); assertEquals("Incorrect result - id doesn't match to given number!", 1, id.intValue()); String title = jsonObject.getString("title"); assertEquals("Incorrect result - title doesn't match to given plain text!", "Batch1", title); query = "{\n\"match\" : {\n\"title\" : \"Batch1\"}\n}"; result = searcher.findDocument(query); jsonObject = result.getJsonObject("_source"); id = getIdFromJSONObject(result); assertEquals("Incorrect result - id doesn't match to given plain text!", 1, id.intValue()); title = jsonObject.getString("title"); assertEquals("Incorrect result - title doesn't match to given plain text!", "Batch1", title); query = "{\n\"match\" : {\n\"title\" : \"Nonexistent\"}\n}"; result = searcher.findDocument(query); id = getIdFromJSONObject(result); assertEquals("Incorrect result - id has another value than null!", Integer.valueOf(0), id); }