auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public JSONInvoiceInfoResponse getInvoiceInfo(@NonNull final InvoiceId invoiceId, final String ad_language) { final JSONInvoiceInfoResponse.JSONInvoiceInfoResponseBuilder result = JSONInvoiceInfoResponse.builder(); final I_C_Invoice invoice = invoiceDAO.getByIdInTrx(invoiceId); final CurrencyCode currency = Services.get(ICurrencyDAO.class).getCurrencyCodeById(CurrencyId.ofRepoId(invoice.getC_Currency_ID())); final List<I_C_InvoiceLine> lines = invoiceDAO.retrieveLines(invoiceId); for (final I_C_InvoiceLine line : lines) { final String productName = productBL.getProductNameTrl(ProductId.ofRepoId(line.getM_Product_ID())).translate(ad_language); final BigDecimal taxRate = taxDAO.getRateById(TaxId.ofRepoId(line.getC_Tax_ID())).orElse(BigDecimal.ZERO); result.lineInfo(JSONInvoiceLineInfo.builder() .line_number(line.getLine()) .product_name(productName) .qty_invoiced(line.getQtyEntered()) .price(line.getPriceEntered()) .tax_rate(taxRate) .line_net_amt(line.getLineNetAmt()) .currency(currency) .build()); } return result.build(); }

Target:
public JSONInvoiceInfoResponse getInvoiceInfo(@NonNull final InvoiceId invoiceId, final String ad_language) { final JSONInvoiceInfoResponse.JSONInvoiceInfoResponseBuilder result = JSONInvoiceInfoResponse.builder(); final I_C_Invoice invoice = invoiceDAO.getByIdInTrx(invoiceId); final CurrencyCode currency = currencyDAO.getCurrencyCodeById(CurrencyId.ofRepoId(invoice.getC_Currency_ID())); final List<I_C_InvoiceLine> lines = invoiceDAO.retrieveLines(invoiceId); for (final I_C_InvoiceLine line : lines) { final String productName = productBL.getProductNameTrl(ProductId.ofRepoId(line.getM_Product_ID())).translate(ad_language); final Percent taxRate = taxDAO.getRateById(TaxId.ofRepoId(line.getC_Tax_ID())); result.lineInfo(JSONInvoiceLineInfo.builder() .lineNumber(line.getLine()) .productName(productName) .qtyInvoiced(line.getQtyEntered()) .price(line.getPriceEntered()) .taxRate(taxRate) .lineNetAmt(line.getLineNetAmt()) .currency(currency) .build()); } return result.build(); }
Source:
private EventResult runConnectHostToPoolEvent(final Guid storagePoolId, final VDS vds) { EventResult result = new EventResult(true, EventType.VDSCONNECTTOPOOL); storage_pool storagePool = getStoragePoolDAO().get(storagePoolId); StorageDomain masterDomain = getStorageDomainDAO().getMasterStorageDomainForPool(storagePoolId); boolean isMasterDomainInactiveOrUnknown = (masterDomain.getStatus() == StorageDomainStatus.InActive || masterDomain.getStatus() == StorageDomainStatus.Unknown); try { runVdsCommand(VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(vds.getId(), storagePoolId, vds.getVdsSpmId(), masterDomain.getId(), storagePool.getmaster_domain_version())).getSucceeded(); } catch (VDSNetworkException | VdcBLLException e) { if (isMasterDomainInactiveOrUnknown) { result.setSuccess(true); } else { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } } catch (RuntimeException exp) { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } if (result.isSuccess() && !isMasterDomainInactiveOrUnknown) { result.setSuccess(proceedVdsStats()); if (!result.isSuccess()) { AuditLogDirector.log(new AuditLogableBase(getVdsId()), AuditLogType.VDS_STORAGE_VDS_STATS_FAILED); } } return result; }

Target:
private EventResult runConnectHostToPoolEvent(final Guid storagePoolId, final VDS vds) { EventResult result = new EventResult(true, EventType.VDSCONNECTTOPOOL); storage_pool storagePool = getStoragePoolDAO().get(storagePoolId); StorageDomain masterDomain = getStorageDomainDAO().getStorageDomainForPoolByType(storagePoolId, StorageDomainType.Master); boolean shouldProceedVdsStats = true; try { runVdsCommand(VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(vds.getId(), storagePoolId, vds.getVdsSpmId(), masterDomain.getId(), storagePool.getmaster_domain_version())).getSucceeded(); } catch (VdcBLLException e) { boolean isMasterDomainInactiveOrUnknown = (masterDomain.getStatus() == StorageDomainStatus.InActive || masterDomain.getStatus() == StorageDomainStatus.Unknown); if (e.getErrorCode() != VdcBllErrors.VDS_NETWORK_ERROR && isMasterDomainInactiveOrUnknown) { shouldProceedVdsStats = false; result.setSuccess(true); } else { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } } catch (RuntimeException exp) { log.errorFormat("Could not connect host {0} to pool {1}", vds.getName(), storagePool .getname()); result.setSuccess(false); } if (result.isSuccess() && shouldProceedVdsStats) { result.setSuccess(proceedVdsStats()); if (!result.isSuccess()) { AuditLogDirector.log(new AuditLogableBase(getVdsId()), AuditLogType.VDS_STORAGE_VDS_STATS_FAILED); } } return result; }
Source:
public void onStart() { super.onStart(); EventBus.getDefault().register(this); autoDownload = prefs.getString(PREF_AUTO_DOWNLOAD,STRING_NO_FILTER); keepUpdated = prefs.getString(PREF_KEEP_UPDATED,STRING_NO_FILTER); autoDelete = prefs.getString(PREF_AUTO_DELETE,STRING_NO_FILTER); loadSubscriptions(); }

Target:
public void onStart() { super.onStart(); EventBus.getDefault().register(this); loadSubscriptions(); }
Source:
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 at least one requested element: "+unavailable); } return newlyClaimed; } }

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:
public CompletableFuture<LedgerEntries> readAsync(long firstEntry, long lastEntry) { CompletableFuture<LedgerEntries> promise = new CompletableFuture<>(); if (bk.isStopped()) { promise.completeExceptionally(BKException.create(-1)); 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; }

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:
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)); return a.countEntries(); } } private static final long serialVersionUID = 1L; }); }

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:
public ObjectInspector getObjectInspector() throws SerDeException { if (LOG.isDebugEnabled()) SpliceLogUtils.trace(LOG, "getObjectInspector"); return rowOI; }

Target:
public ObjectInspector getObjectInspector() throws SerDeException { if (LOG.isTraceEnabled()) SpliceLogUtils.trace(LOG, "getObjectInspector"); return rowOI; }
Source:
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( publishInputMap.mput(Logger.InvokeKeys.LOG_RECORD, record), publishOutputMap); } catch(Exception ex) } }

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:
protected static ImmutableList<Ds3Request> convertRequests( final ImmutableList<Ds3Request> requests, final NameMapper nameMapper) { if (requests == null || requests.isEmpty()) { 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(); }

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:
public void dosCborObject() throws Throwable { byte[] raw = ArrayOps.hexToBytes("5b0004000000000000"); try { CborObject.fromByteArray(raw); throw new Throwable("Should have failed!"); } catch (RuntimeException e) }

Target:
public void dosCborObject() throws Throwable { byte[] raw = ArrayOps.hexToBytes("5b0004000000000000"); try { CborObject.fromByteArray(raw); Assert.fail("Should have failed!"); } catch (RuntimeException e) }
Source:
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) { continue; } 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); }

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:
private static void notNull(Object value, String message) { if (value == null) throw new IllegalArgumentException(message); }

Target:
private static void notNull(Object value, String message) { if (value == null) { throw new NullPointerException(message); } }
Source:
public String[] getSourceNames() { return this.sourcesByName.keySet().toArray(new String[this.sourcesByName.size()]); }

Target:
public String[] getSourceNames() { return this.sourcesByName.keySet().toArray(new String[0]); }
Source:
public String toString(){ String json = JSONObject.toJSONString(webrequestMap); return "{\"webrequest\":" +json + "}"; }

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:
public String starlarkStrictDeps() { switch (strictProtoDeps()) { case OFF: return "OFF"; case WARN: return "WARN"; case ERROR: case STRICT: case DEFAULT: return "ERROR"; } Preconditions.checkState(false, "NOTREACHED"); return null; }

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:
public void getReport(HttpServletRequest request, HttpServletResponse response) throws IOException, BadRequestException, UnauthorizedException { Session session = serviceServiceSupplier.getService().get(request); HSSFWorkbook workbook = createWorkbook(session); 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()); }

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:
private static SummaryStatistics[] getStats(final ArrayOfDoublesSketch sketch) { final SummaryStatistics[] stats = new SummaryStatistics[sketch.getNumValues()]; for (int i = 0; i < stats.length; i++) { 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; }

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:
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) { return retriesSupported && clusterService.state().nodes().nodeExists(targetNode) && retryableException(e); } }; onGoingRetryableActions.put(key, retryableAction); retryableAction.run(); if (isCancelled) { retryableAction.cancel(new CancellableThreads.ExecutionCancelledException("recovery was cancelled")); } }

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:
private static Set<Diff> removePseudoConflicts(Set<Diff> diffs) { Set<Diff> resultSet = new LinkedHashSet<Diff>(); for (Diff diff : diffs) { if (diff.getConflict() != null && diff.getConflict().getKind() == PSEUDO) { } else { resultSet.add(diff); } } return resultSet; }

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:
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 { Locale.setDefault(Locale.ENGLISH); 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); } }

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:
protected void validateSession( final IOSession ioSession, final Callback<Boolean> callback) { final TimeValue timeValue = validateAfterInactivity; if (TimeValue.ZERO_MILLISECONDS.equals(timeValue) || TimeValue.isPositive(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); }

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:
public String docs() { return "mixed {Locationarray} Returns the list regions at the location." + " If region is found, an array of region names are returned, else an empty is returned"; }

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:
public static void cleanup() throws Exception { SecurityTestUtil.cleanup(); stopAllServers(); }

Target:
public static void cleanup() throws Exception { stopAllServers(); }
Source:
public List<VocabularyExtension> getExtensions() { return this.extensions.get(); }

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:
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.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; }

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:
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)); return (svgFile != null); }

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:
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 (Throwable t) { LOG.warn(desc.getName() + " does not support Tablespace::getTableVolume()"); desc.getStats().setNumBytes(-1); } } }

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:
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(); InputStream inputStream = new FileInputStream(new File(getClass().getResource("/root.crl").getPath())); demEncodedCrl = new byte[inputStream.available()]; inputStream.read(demEncodedCrl); }

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:
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); String redirect = cr.getHeaders().get("Location").get(0); assertTrue(redirect.contains("error=access_denied")); Set<String> keys = store.keySet(); assertFalse(keys.contains(key)); }

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:
public static void refreshResolve() { try { if(hostname == null || hostname.isEmpty()) { hostname = java.net.InetAddress.getLocalHost().getHostName(); if (hostname == null) { hostname = "localhost"; } lastUpdate = System.currentTimeMillis(); } } catch (UnknownHostException e) { } }

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:
public RecentChangesPoller(WikibaseRepository wikibase, Date firstStartTime, int batchSize, Map<Long, Boolean> seenIDs, int tailSeconds) { this.wikibase = wikibase; this.firstStartTime = firstStartTime != null ? new Date(firstStartTime.getTime()) : null; this.batchSize = batchSize; this.seenIDs = seenIDs; this.tailSeconds = tailSeconds; }

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:
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(); } MuleContentGenerator.createClassLoaderModelJsonFile(new NotParameterizedClassLoaderModel(mulePluginClassLoaderModel), artifactFolderDestination); }); }

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:
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 { ServletHelper.respondAsJsonWithHttpStatus(resp, new JsonResponse().setFailed(), HttpServletResponse.SC_FORBIDDEN); } LOGGER.exiting(); }

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:
public boolean send(Slice f) { if (sendQueue.offer(f)) { try { lock.lock(); if (!isWriteEnabled) { resumeWriteIfSuspended(); isWriteEnabled = true; } } finally { lock.unlock(); } return true; } return false; }

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:
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(); it.forEach(element -> { 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; }

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:
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); config.setCannedAcl(CannedAccessControlList.valueOf(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; }

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:
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(mapName -> officialMapsPath.resolve(mapName)) .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; } }); }

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:
public CrossSiteOriginFilter(final DolphinPlatformConfiguration configuration){ this.configuration = configuration; }

Target:
public CrossSiteOriginFilter(final DolphinPlatformConfiguration configuration){ this.configuration = Assert.requireNonNull(configuration, "configuration"); }
Source:
protected void saveMetadata() { Path metadata = getMetadataPath(); StringBuilder builder = new StringBuilder(); builder.append( String.format("# Log created %s%n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date()))); 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")); } }

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:
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()) { Entry<String, JoinEmailData> email = emailIterator.next(); 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(); }

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:
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"); assertSent(server, "POST", "/networks/1/connect"); } finally { server.shutdown(); } }

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:
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); System.out.println(result); id = getIdFromJSONObject(result); assertEquals("Incorrect result - id has another value than null!", Integer.valueOf(0), id); }

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); }