auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean classOrModelClassExists(String className) { Elements elementUtils = processingEnv.getElementUtils(); if (className.endsWith(ModelConstants.generationSuffix())) { className = className.substring(0, className.length() - 1); } return elementUtils.getTypeElement(className) != null; }

Target:
private boolean classOrModelClassExists(String className) { Elements elementUtils = processingEnv.getElementUtils(); if (className.endsWith(classSuffix())) { className = className.substring(0, className.length() - classSuffix().length()); } return elementUtils.getTypeElement(className) != null; }
Source:
static boolean isBug(Throwable error) { if (error instanceof OnErrorNotImplementedException) { return true; } if (error instanceof MissingBackpressureException) { return true; } if (error instanceof IllegalStateException) { return true; } if (error instanceof NullPointerException) { return true; } if (error instanceof IllegalArgumentException) { return true; } return false; }

Target:
static boolean isBug(Throwable error) { if (error instanceof OnErrorNotImplementedException) { return true; } if (error instanceof MissingBackpressureException) { return true; } if (error instanceof IllegalStateException) { return true; } if (error instanceof NullPointerException) { return true; } if (error instanceof IllegalArgumentException) { return true; } if (error instanceof CompositeException) { return true; } return false; }
Source:
public void testIncIteration() { Assertions.assertThrows( UnsupportedOperationException.class, unmodifiables::incIteration ); }

Target:
public void testIncIteration() { assertThrowsUnsupportedOperation(unmodifiables::incIteration); }
Source:
private boolean testDatabase(Instance instance) throws TimeoutException { System.out.println("Connect to database"); Connection conn = null; try { String connString = "jdbc:mysql://" + getVirtualIPv4(getLb().getVirtualIPs()) + "/" + Constants.NAME + "?user=" + Constants.NAME + "&password=" + Constants.PASSWORD; System.out.println("Connecting to " + connString); conn = DriverManager.getConnection(connString); Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT 3+5"); rs.first(); System.out.println("3+5 is " + rs.getInt(1)); } catch (SQLException ex){ System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); return false; } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { } rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { } stmt = null; } } } catch (SQLException ex) { System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); return false; } return true; }

Target:
private boolean testDatabase(Instance instance) throws TimeoutException { System.out.println("Connect to database"); Connection conn = null; try { StringBuilder connString = new StringBuilder(); connString.append( "jdbc:mysql://" ); connString.append( getVirtualIPv4(getLb().getVirtualIPs()) ); connString.append("/"); connString.append(Constants.NAME); connString.append("?user="); connString.append(Constants.NAME); connString.append("&password="); connString.append(Constants.PASSWORD); System.out.println("Connecting to " + connString); conn = DriverManager.getConnection(connString.toString()); Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT 3+5"); rs.first(); System.out.println("3+5 is " + rs.getInt(1)); } catch (SQLException e){ System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); e.printStackTrace(); return false; } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { } rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { } stmt = null; } if(conn != null) try { conn.close(); } catch (SQLException sqlEx) { } } } catch (SQLException e) { System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); e.printStackTrace(); return false; } return true; }
Source:
protected String getChangePasswordMsg(CLIParser parser) throws ManageDomainsResult, UnsupportedEncodingException { if (!changePasswordMsg) { return null; } String changePasswordMsgStr = readInteractively("Please enter message or URL to appear when user tries to login with an expired password.\n", false); if (changePasswordMsgStr.indexOf("http") == 0 || changePasswordMsgStr.indexOf("https") == 0) { try { URL url = new URL(changePasswordMsgStr); log.debug("Validated that " + url + " is in correct format"); } catch (MalformedURLException ex) { throw new ManageDomainsResult(ManageDomainsResultEnum.INVALID_ARGUMENT_FOR_COMMAND, "The provided value begins with a URL prefix of either http or https. However this is not a valid URL"); } } return URLEncoder.encode(changePasswordMsgStr, "UTF-8"); }

Target:
protected String getChangePasswordMsg(CLIParser parser) throws ManageDomainsResult, UnsupportedEncodingException { if (!changePasswordMsg) { return null; } String changePasswordMsgStr = readInteractively("Please enter message or URL to appear when user tries to login with an expired password: ", false); if (changePasswordMsgStr.indexOf("http") == 0 || changePasswordMsgStr.indexOf("https") == 0) { try { URL url = new URL(changePasswordMsgStr); log.debug("Validated that " + url + " is in correct format"); } catch (MalformedURLException ex) { throw new ManageDomainsResult(ManageDomainsResultEnum.INVALID_ARGUMENT_FOR_COMMAND, "The provided value begins with a URL prefix of either http or https. However this is not a valid URL"); } } return URLEncoder.encode(changePasswordMsgStr, "UTF-8"); }
Source:
public void onCompletion(String result, Exception exception) { callbackTracker.markOperationEnd(); ReadableStreamChannel response = null; if (result == null && exception == null) { throw new IllegalStateException("Both result and exception cannot be null"); } else if (exception == null) { try { RestMethod restMethod = restRequest.getRestMethod(); logger.trace("Forwarding of to the router", restMethod, result); switch (restMethod) { case GET: RestUtils.SubResource subresource = RestUtils.getBlobSubResource(restRequest); if (subresource == null || subresource.equals(RestUtils.SubResource.BlobInfo) || subresource.equals( RestUtils.SubResource.UserMetadata)) { getCallback.markStartTime(); router.getBlob(result, getCallback.options, getCallback); } else { switch (subresource) { case Replicas: response = getReplicasHandler.getReplicas(result, restResponseChannel); break; } } break; case HEAD: GetOption getOption = RestUtils.getGetOption(restRequest); headCallback.markStartTime(); router.getBlob(result, new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.BlobInfo) .getOption(getOption) .build(), headCallback); break; case DELETE: deleteCallback.markStartTime(); router.deleteBlob(result, RestUtils.getServiceId(restRequest), deleteCallback); break; default: exception = new IllegalStateException("Unrecognized RestMethod: " + restMethod); } } catch (Exception e) { exception = e; } } if (response != null || exception != null) { submitResponse(restRequest, restResponseChannel, response, exception); } callbackTracker.markCallbackProcessingEnd(); }

Target:
public void onCompletion(String result, Exception exception) { callbackTracker.markOperationEnd(); ReadableStreamChannel response = null; if (result == null && exception == null) { throw new IllegalStateException("Both result and exception cannot be null"); } else if (exception == null) { try { RestMethod restMethod = restRequest.getRestMethod(); logger.trace("Handling of {}", restMethod, result); switch (restMethod) { case GET: RestUtils.SubResource subresource = RestUtils.getBlobSubResource(restRequest); if (subresource == null) { getCallback.markStartTime(); router.getBlob(result, getCallback.options, getCallback); } else { switch (subresource) { case BlobInfo: case UserMetadata: getCallback.markStartTime(); router.getBlob(result, getCallback.options, getCallback); break; case Replicas: response = getReplicasHandler.getReplicas(result, restResponseChannel); break; } } break; case HEAD: GetOption getOption = RestUtils.getGetOption(restRequest); headCallback.markStartTime(); router.getBlob(result, new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.BlobInfo) .getOption(getOption) .build(), headCallback); break; case DELETE: deleteCallback.markStartTime(); router.deleteBlob(result, RestUtils.getServiceId(restRequest), deleteCallback); break; default: exception = new IllegalStateException("Unrecognized RestMethod: " + restMethod); } } catch (Exception e) { exception = e; } } if (response != null || exception != null) { submitResponse(restRequest, restResponseChannel, response, exception); } callbackTracker.markCallbackProcessingEnd(); }
Source:
public List<Pair<Guid, Integer>> score(Cluster cluster, List<VDS> hosts, VM vm, Map<String, String> parameters) { List<VDS> acceptableHostsList = vmToHostAffinityFilterPolicyUnit.getAcceptableHosts(false, hosts, vm, new PerHostMessages(), getPendingResourceManager()); Map<Guid, VDS> acceptableHostsMap = new HashMap<>(); if (acceptableHostsList != null) { acceptableHostsMap = acceptableHostsList.stream().collect(Collectors.toMap(VDS::getId, h -> h)); } List<Pair<Guid, Integer>> retList = new ArrayList<>(); int score; for (VDS host : hosts) { score = DEFAULT_SCORE; if (!acceptableHostsMap.containsKey(host.getId())) { score = MaxSchedulerWeight; } retList.add(new Pair<>(host.getId(), score)); } return retList; }

Target:
public List<Pair<Guid, Integer>> score(Cluster cluster, List<VDS> hosts, VM vm, Map<String, String> parameters) { List<VDS> acceptableHostsList = vmToHostAffinityFilterPolicyUnit.get().getAcceptableHosts(false, hosts, vm, new PerHostMessages(), getPendingResourceManager()); Map<Guid, VDS> acceptableHostsMap = new HashMap<>(); if (acceptableHostsList != null) { acceptableHostsMap = acceptableHostsList.stream().collect(Collectors.toMap(VDS::getId, h -> h)); } List<Pair<Guid, Integer>> retList = new ArrayList<>(); int score; for (VDS host : hosts) { score = DEFAULT_SCORE; if (!acceptableHostsMap.containsKey(host.getId())) { score = MaxSchedulerWeight; } retList.add(new Pair<>(host.getId(), score)); } return retList; }
Source:
private void updateRegionCache(String bucketName) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { if (bucketName != null && this.accessKey != null && this.secretKey != null && !BucketRegionCache.INSTANCE.exists(bucketName)) { String region; if (!this.region.equals("")) { region = this.region; } else { Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put("location", null); HttpResponse response = execute(Method.GET, US_EAST_1, bucketName, null, null, queryParamMap, null, 0); XmlPullParser xpp = xmlPullParserFactory.newPullParser(); String location = null; xpp.setInput(response.body().charStream()); while (xpp.getEventType() != xpp.END_DOCUMENT) { if (xpp.getEventType() == xpp.START_TAG && xpp.getName() == "LocationConstraint") { xpp.next(); location = getText(xpp, location); break; } xpp.next(); } response.body().close(); if (location == null) { region = US_EAST_1; } else { if ("EU".equals(location)) { region = "eu-west-1"; } else { region = location; } } } BucketRegionCache.INSTANCE.set(bucketName, region); } }

Target:
private void updateRegionCache(String bucketName) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException { if (bucketName != null && this.accessKey != null && this.secretKey != null && !BucketRegionCache.INSTANCE.exists(bucketName)) { Map<String,String> queryParamMap = new HashMap<>(); queryParamMap.put("location", null); HttpResponse response = execute(Method.GET, US_EAST_1, bucketName, null, null, queryParamMap, null, 0); XmlPullParser xpp = xmlPullParserFactory.newPullParser(); String location = null; xpp.setInput(response.body().charStream()); while (xpp.getEventType() != xpp.END_DOCUMENT) { if (xpp.getEventType() == xpp.START_TAG && xpp.getName() == "LocationConstraint") { xpp.next(); location = getText(xpp, location); break; } xpp.next(); } response.body().close(); String region; if (location == null) { region = US_EAST_1; } else { if ("EU".equals(location)) { region = "eu-west-1"; } else { region = location; } } BucketRegionCache.INSTANCE.set(bucketName, region); } }
Source:
public void recover(Message message, Throwable cause) { Map<String, Object> headers = message.getMessageProperties().getHeaders(); headers.put("x-exception-stacktrace", getStackTraceAsString(cause)); headers.put("x-exception-message", cause.getCause() != null ? cause.getCause().getMessage() : cause.getMessage()); headers.put("x-original-exchange", message.getMessageProperties().getReceivedExchange()); headers.put("x-original-routingKey", message.getMessageProperties().getReceivedRoutingKey()); if (null != errorExchangeName) { String routingKey = errorRoutingKey != null ? errorRoutingKey : message.getMessageProperties().getReceivedRoutingKey(); this.errorTemplate.send(errorExchangeName, routingKey, message); if (logger.isWarnEnabled()) { logger.warn("Republishing failed message to exchange " + errorExchangeName); } } else { final String routingKey = "error." + message.getMessageProperties().getReceivedRoutingKey(); this.errorTemplate.send(routingKey, message); if (logger.isWarnEnabled()) { logger.warn("Republishing failed message to the template's default exchange with routing key " + routingKey); } } }

Target:
public void recover(Message message, Throwable cause) { Map<String, Object> headers = message.getMessageProperties().getHeaders(); headers.put("x-exception-stacktrace", getStackTraceAsString(cause)); headers.put("x-exception-message", cause.getCause() != null ? cause.getCause().getMessage() : cause.getMessage()); headers.put("x-original-exchange", message.getMessageProperties().getReceivedExchange()); headers.put("x-original-routingKey", message.getMessageProperties().getReceivedRoutingKey()); if (null != errorExchangeName) { String routingKey = errorRoutingKey != null ? errorRoutingKey : this.prefixedOriginalRoutingKey(message); this.errorTemplate.send(errorExchangeName, routingKey, message); if (logger.isWarnEnabled()) { logger.warn("Republishing failed message to exchange " + errorExchangeName); } } else { final String routingKey = this.prefixedOriginalRoutingKey(message); this.errorTemplate.send(routingKey, message); if (logger.isWarnEnabled()) { logger.warn("Republishing failed message to the template's default exchange with routing key " + routingKey); } } }
Source:
public void testPutSynonymCatalogFile() throws Exception { final File file = new File("src/test/resources/testsynonymcatalog"); final MockMultipartFile multipartFile = new MockMultipartFile("file", "testsynonymcatalog", "text/plain", new FileInputStream(file)); final MvcResult mvcResult = _mockMvc.perform( fileUpload("/test/referencedata/synonymCatalog/testCatalog").file(multipartFile).with(withPut()) .contentType(MediaType.MULTIPART_FORM_DATA).param("casesensitive", "false")).andExpect(status().isCreated()).andExpect( header().string("Location", is("http://localhost/test/referencedata/synonymCatalog/testCatalog"))) .andReturn(); final String location = mvcResult.getResponse().getHeader("Location"); _mockMvc.perform(get(location)).andExpect(status().isOk()).andExpect(jsonPath("$.name", is("testCatalog"))) .andExpect(jsonPath("$.entries", hasSize(1))).andExpect(jsonPath("$.entries[0].masterTerm", is("foo"))) .andExpect(jsonPath("$.entries[0].synonyms", hasSize(2))) .andExpect(jsonPath("$.entries[0].synonyms[1]", is("baz"))) .andExpect(jsonPath("$.caseSensitive", is(false))); }

Target:
public void testPutSynonymCatalogFile() throws Exception { final byte[] bytes = Files.readAllBytes(Paths.get("src/test/resources/testsynonymcatalog")); final MvcResult mvcResult = _mockMvc.perform( put("/test/referencedata/synonymCatalog/testCatalog").content(bytes).param("casesensitive", "false")) .andExpect(status().isCreated()).andExpect(header().string("Location", is("http://localhost/test/referencedata/synonymCatalog/testCatalog"))).andReturn(); final String location = mvcResult.getResponse().getHeader("Location"); _mockMvc.perform(get(location)).andExpect(status().isOk()).andExpect(jsonPath("$.name", is("testCatalog"))) .andExpect(jsonPath("$.entries", hasSize(1))).andExpect(jsonPath("$.entries[0].masterTerm", is("foo"))) .andExpect(jsonPath("$.entries[0].synonyms", hasSize(2))) .andExpect(jsonPath("$.entries[0].synonyms[1]", is("baz"))) .andExpect(jsonPath("$.caseSensitive", is(false))); }
Source:
public static String[] getIndices(final String table, final ActionRequest request) throws Exception { final Interval interval = new PeriodSelector(request.getFilters()).analyze(); DateTime start = interval.getStart().toLocalDate().toDateTimeAtStartOfDay(); if(start.getYear() == 1970) { logger.warn("Request of type running on all indices", request.getClass().getSimpleName()); return getIndices(table); } DateTime end = interval.getEnd().plusDays(1).toLocalDate().toDateTimeAtStartOfDay(); List<String> indices = Lists.newArrayList(); String lastIndex = ""; String index = ""; while (true) { index = String.format("%s-%s-%s-%s", ElasticsearchUtils.TABLENAME_PREFIX, table, ElasticsearchUtils.TABLENAME_POSTFIX, String.format("%02d-%d-%4d", start.dayOfMonth().get(), start.monthOfYear().get(), start.year().get())); if(index.equals(lastIndex)) { break; } if(new Duration(start, end).getStandardSeconds() < 86400) { break; } indices.add(index); lastIndex = index; start = start.plusDays(1); } logger.info("Request of type on indices: {}", request.getClass().getSimpleName(), indices); return indices.toArray(new String[indices.size()]); }

Target:
public static String[] getIndices(final String table, final ActionRequest request) throws Exception { return getIndices(table, request, new PeriodSelector(request.getFilters()).analyze()); }
Source:
public void deployService() throws Exception { super.init(); loadESBConfigurationFromClasspath("/artifacts/ESB/mediatorconfig/clone/cloneMediatorHandleException.xml"); logViewerClient = new LogViewerClient(contextUrls.getBackEndUrl(), getSessionCookie()); }

Target:
public void deployService() throws Exception { super.init(); loadESBConfigurationFromClasspath("/artifacts/ESB/mediatorconfig/clone/cloneMediatorHandleException.xml"); logViewerClient = new LogViewerClient(contextUrls.getBackEndUrl(), getSessionCookie()); logViewerClient.clearLogs(); }
Source:
private void setFinalResult( Result resultMessage, Frame responseFrame, boolean schemaInAgreement, NodeResponseCallback callback) { try { ExecutionInfo executionInfo = buildExecutionInfo(callback, resultMessage, responseFrame, schemaInAgreement); AsyncResultSet resultSet = Conversions.toResultSet(resultMessage, executionInfo, session, context); if (result.complete(resultSet)) { cancelScheduledTasks(); throttler.signalSuccess(this); long completionTimeNanos = -1, totalLatencyNanos = -1; if (!(requestTracker instanceof NoopRequestTracker)) { completionTimeNanos = System.nanoTime(); totalLatencyNanos = completionTimeNanos - startTimeNanos; long nodeLatencyNanos = completionTimeNanos - callback.nodeStartTimeNanos; requestTracker.onNodeSuccess( statement, nodeLatencyNanos, executionProfile, callback.node); requestTracker.onSuccess(statement, totalLatencyNanos, executionProfile, callback.node); } if (sessionMetricUpdater.isEnabled( DefaultSessionMetric.CQL_REQUESTS, executionProfile.getName())) { if (completionTimeNanos < 0) { completionTimeNanos = System.nanoTime(); totalLatencyNanos = completionTimeNanos - startTimeNanos; } sessionMetricUpdater.updateTimer( DefaultSessionMetric.CQL_REQUESTS, executionProfile.getName(), totalLatencyNanos, TimeUnit.NANOSECONDS); } } } catch (Throwable error) { setFinalError(error, callback.node, -1); } }

Target:
private void setFinalResult( Result resultMessage, Frame responseFrame, boolean schemaInAgreement, NodeResponseCallback callback) { try { ExecutionInfo executionInfo = buildExecutionInfo(callback, resultMessage, responseFrame, schemaInAgreement); AsyncResultSet resultSet = Conversions.toResultSet(resultMessage, executionInfo, session, context); if (result.complete(resultSet)) { cancelScheduledTasks(); throttler.signalSuccess(this); long completionTimeNanos = NANOTIME_NOT_MEASURED_YET, totalLatencyNanos = NANOTIME_NOT_MEASURED_YET; if (!(requestTracker instanceof NoopRequestTracker)) { completionTimeNanos = System.nanoTime(); totalLatencyNanos = completionTimeNanos - startTimeNanos; long nodeLatencyNanos = completionTimeNanos - callback.nodeStartTimeNanos; requestTracker.onNodeSuccess( statement, nodeLatencyNanos, executionProfile, callback.node); requestTracker.onSuccess(statement, totalLatencyNanos, executionProfile, callback.node); } if (sessionMetricUpdater.isEnabled( DefaultSessionMetric.CQL_REQUESTS, executionProfile.getName())) { if (completionTimeNanos == NANOTIME_NOT_MEASURED_YET) { completionTimeNanos = System.nanoTime(); totalLatencyNanos = completionTimeNanos - startTimeNanos; } sessionMetricUpdater.updateTimer( DefaultSessionMetric.CQL_REQUESTS, executionProfile.getName(), totalLatencyNanos, TimeUnit.NANOSECONDS); } } } catch (Throwable error) { setFinalError(error, callback.node, -1); } }
Source:
public EnumTypeAdapter(Class<T> classOfT) { try { for (Field field : classOfT.getDeclaredFields()) { if (!field.isEnumConstant()) { continue; } field.setAccessible(true); T constant = (T)(field.get(null)); String name = constant.name(); SerializedName annotation = field.getAnnotation(SerializedName.class); if (annotation != null) { name = annotation.value(); for (String alternate : annotation.alternate()) { nameToConstant.put(alternate, constant); } } nameToConstant.put(name, constant); constantToName.put(constant, name); } } catch (IllegalAccessException e) { throw new AssertionError(e); } catch (NullPointerException e) { throw new AssertionError(e); } catch (ExceptionInInitializerError e) { throw new AssertionError(e); } }

Target:
public EnumTypeAdapter(Class<T> classOfT) { try { for (Field field : classOfT.getDeclaredFields()) { if (!field.isEnumConstant()) { continue; } field.setAccessible(true); @SuppressWarnings("unchecked") T constant = (T)(field.get(null)); String name = constant.name(); SerializedName annotation = field.getAnnotation(SerializedName.class); if (annotation != null) { name = annotation.value(); for (String alternate : annotation.alternate()) { nameToConstant.put(alternate, constant); } } nameToConstant.put(name, constant); constantToName.put(constant, name); } } catch (IllegalAccessException e) { throw new AssertionError(e); } }
Source:
public boolean isEmergencyOnly() { return (mServiceState != null && mServiceState.getNetworkRegistrationInfoList().stream() .filter(NetworkRegistrationInfo::isInService) .allMatch(NetworkRegistrationInfo::isEmergencyEnabled)); }

Target:
public boolean isEmergencyOnly() { return (mServiceState != null && mServiceState.getNetworkRegistrationInfoList().stream() .filter(NetworkRegistrationInfo::isRegistered) .allMatch(NetworkRegistrationInfo::isEmergencyEnabled)); }
Source:
public static void main(String[] args) { Options options = getRequiredOptions(); CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args); String folderPath = executeDownloader(cmd); System.out.println("The download completed successfully and the zip folder is located : " + FolderCompressor.compress(folderPath)); } catch (ParseException exp) { System.out.println(exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Migrator", options); } catch (RepresentationNotExistsException ex) { System.out.println(ex.getMessage()); } catch (MimeTypeException e) { System.out.println("The downloaded records have unrecognised mimeType"); } catch (ZipException e) { System.out.println("Exception happened during zipping the folder" + e.getMessage()); } catch (MCSException | DriverException e) { System.out.println("An exception happened while communicating with mcs" + e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } }

Target:
public static void main(String[] args) { Options options = getOptions(); CommandLineParser parser = new DefaultParser(); String zipFolderPath = FileUtil.createZipFolderPath(new Date()); CommandLine cmd = null; try { cmd = parser.parse(options, args); String folderPath = executeDownloader(cmd); FolderCompressor.compress(folderPath, zipFolderPath); System.out.println("The download completed successfully and the zip folder is located : " + zipFolderPath); } catch (ParseException exp) { System.out.println(exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Records downloader ", options); } catch (RepresentationNotFoundException ex) { System.out.println(ex.getMessage()); } catch (MimeTypeException e) { System.out.println("The downloaded records have unrecognised mimeType"); } catch (ZipException e) { System.out.println("Exception happened during zipping the folder " + e.getMessage()); try { if (zipFolderPath != null) FileUtils.forceDelete(new File(zipFolderPath)); } catch (IOException io) { System.out.println("An Exception happened while deleting folder " + zipFolderPath); } } catch (NumberFormatException e) { System.out.println("Threads count should be integer"); } catch (DriverException e) { System.out.println("An exception happened during communicating with MCS: " + cmd.getOptionValue(MCS_URL) + " caused by " + e.getMessage()); } catch (InterruptedException | ExecutionException e) { System.out.println("An exception happened during downloading the files caused by: " + e.getMessage()); } catch (Exception e) { System.out.println("An exception happened caused by: " + e.getMessage()); } }
Source:
public void trade() { HashMap<String, Stock> stockList = m.getStockList(); Set<String> stk = stockList.keySet(); String[] stocks = stk.toArray(new String[stk.size()]); for (String sym : stocks) { ArrayList<Order> supply = sellOrders.get(sym); ArrayList<Order> demand = buyOrders.get(sym); if(supply != null && demand != null && supply.size() > 0 && demand.size() > 0) { sortByPrice(supply); sortByPrice(demand); Collections.reverse(supply); int cumSupplySize = 0; int cumDemandSize = 0; HashMap<Double, Integer> minSizeSupply = new HashMap<Double, Integer>(); HashMap<Double, Integer> minSizeDemand = new HashMap<Double, Integer>(); ArrayList<Double> prices = new ArrayList<Double>(); int d = genMinShare(supply, cumSupplySize, minSizeSupply, prices); getMinShare(demand, cumDemandSize, minSizeDemand, prices, d); int i; double marketPrice = highestMinShare(minSizeSupply, minSizeDemand, prices); updateStockPriceAfterTrade(sym, marketPrice); if (marketPrice == 0.0) marketPrice = calculateAverageMarketPrice(prices); matchingPrice(supply, marketPrice); sellOrders.put(sym, supply); i = 0; while (i < demand.size()) { Order potentialOrder = demand.get(i); if (potentialOrder.getPrice() >= marketPrice) { try { (potentialOrder.getTrader()).tradePerformed(potentialOrder, marketPrice); } catch (StockMarketExpection e) { e.printStackTrace(); } demand.remove(i); } i++; } buyOrders.put(sym, demand); } } }

Target:
public void trade() { HashMap<String, Stock> stockList = m.getStockList(); Set<String> stk = stockList.keySet(); String[] stocks = stockListKeys.toArray(new String[stk.size()]); for (String sym : stocks) { ArrayList<Order> supply = sellOrders.get(sym); ArrayList<Order> demand = buyOrders.get(sym); if(supply != null && demand != null && supply.size() > 0 && demand.size() > 0) { sortByPrice(supply); sortByPrice(demand); Collections.reverse(supply); int cumSupplySize = 0; int cumDemandSize = 0; HashMap<Double, Integer> minSizeSupply = new HashMap<Double, Integer>(); HashMap<Double, Integer> minSizeDemand = new HashMap<Double, Integer>(); ArrayList<Double> prices = new ArrayList<Double>(); int d = genMinShare(supply, cumSupplySize, minSizeSupply, prices); getMinShare(demand, cumDemandSize, minSizeDemand, prices, d); int i; double marketPrice = highestMinShare(minSizeSupply, minSizeDemand, prices); updateStockPriceAfterTrade(sym, marketPrice); if (marketPrice == 0.0) marketPrice = calculateAverageMarketPrice(prices); matchingPrice(supply, marketPrice); sellOrders.put(sym, supply); i = 0; while (i < demand.size()) { Order potentialOrder = demand.get(i); if (potentialOrder.getPrice() >= marketPrice) { try { (potentialOrder.getTrader()).tradePerformed(potentialOrder, marketPrice); } catch (StockMarketExpection e) { e.printStackTrace(); } demand.remove(i); } i++; } buyOrders.put(sym, demand); } } }
Source:
public static void reset(boolean retainBookmarkedPosts) { SQLiteDatabase db = getWritableDb(); if (retainBookmarkedPosts && ReaderPostTable.hasBookmarkedPosts()) { ReaderTagList tags = ReaderTagTable.getBookmarkTags(); if (!tags.isEmpty()) { ReaderPostList bookmarkedPosts = ReaderPostTable.getPostsWithTag(tags.get(0), 0, true); db.beginTransaction(); try { getDatabase().reset(db); ReaderPostTable.addOrUpdatePosts(tags.get(0), bookmarkedPosts); db.setTransactionSuccessful(); } finally { db.endTransaction(); } return; } } getDatabase().reset(db); }

Target:
public static void reset(boolean retainBookmarkedPosts) { SQLiteDatabase db = getWritableDb(); if (retainBookmarkedPosts && ReaderPostTable.hasBookmarkedPosts()) { ReaderTagList tags = ReaderTagTable.getBookmarkTags(); if (!tags.isEmpty()) { ReaderPostList bookmarkedPosts = ReaderPostTable.getPostsWithTag(tags.get(0), 0, false); db.beginTransaction(); try { getDatabase().reset(db); ReaderPostTable.addOrUpdatePosts(tags.get(0), bookmarkedPosts); db.setTransactionSuccessful(); } finally { db.endTransaction(); } return; } } getDatabase().reset(db); }
Source:
static public String encode(final byte[] bytes) { return BaseEncoding.base32().encode(bytes); }

Target:
static public String encode(final byte[] bytes) { return BaseEncoding.base32() .omitPadding() .lowerCase() .encode(bytes) .toUpperCase(); }
Source:
public void setStyle(S style) { this.style = style; }

Target:
public StyledText<S> setStyle(S style) { return new StyledText<>(text, style); }
Source:
public boolean canConfigure(IProject project, Set<IPath> ignoredDirectories, IProgressMonitor monitor) { IFile featureFile = project.getFile("feature.xml"); if (featureFile.exists()) { WorkspaceFeatureModel workspaceFeatureModel = new WorkspaceFeatureModel(featureFile); workspaceFeatureModel.load(); return workspaceFeatureModel.isLoaded(); } return featureFile.exists(); }

Target:
public boolean canConfigure(IProject project, Set<IPath> ignoredDirectories, IProgressMonitor monitor) { IFile featureFile = project.getFile(ICoreConstants.FEATURE_FILENAME_DESCRIPTOR); if (featureFile.exists()) { WorkspaceFeatureModel workspaceFeatureModel = new WorkspaceFeatureModel(featureFile); workspaceFeatureModel.load(); return workspaceFeatureModel.isLoaded(); } return featureFile.exists(); }
Source:
public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final RelNode input = aggregate.getInput(); final RelMetadataQuery mq = call.getMetadataQuery(); if (!SqlFunctions.isTrue(mq.areColumnsUnique(input, aggregate.getGroupSet()))) { return; } final RelBuilder relBuilder = call.builder(); final RexBuilder rexBuilder = relBuilder.getRexBuilder(); final List<RexNode> projects = new ArrayList<>(); for (AggregateCall aggCall : aggregate.getAggCallList()) { final SqlAggFunction aggregation = aggCall.getAggregation(); if (aggregation.getKind() == SqlKind.SUM0) { return; } final SqlSplittableAggFunction splitter = Objects.requireNonNull( aggregation.unwrap(SqlSplittableAggFunction.class)); final RexNode singleton = splitter.singleton( rexBuilder, input.getRowType(), aggCall); projects.add(singleton); } final RelNode newInput = convert(input, aggregate.getTraitSet().simplify()); relBuilder.push(newInput); if (!projects.isEmpty()) { projects.addAll(0, relBuilder.fields(aggregate.getGroupSet())); relBuilder.project(projects); } else if (newInput.getRowType().getFieldCount() > aggregate.getRowType().getFieldCount()) { relBuilder.project(relBuilder.fields(aggregate.getGroupSet())); } call.getPlanner().setImportance(aggregate, 0d); call.transformTo(relBuilder.build()); }

Target:
public void onMatch(RelOptRuleCall call) { final Aggregate aggregate = call.rel(0); final RelNode input = aggregate.getInput(); final RelMetadataQuery mq = call.getMetadataQuery(); if (!SqlFunctions.isTrue(mq.areColumnsUnique(input, aggregate.getGroupSet()))) { return; } final RelBuilder relBuilder = call.builder(); final RexBuilder rexBuilder = relBuilder.getRexBuilder(); final List<RexNode> projects = new ArrayList<>(); for (AggregateCall aggCall : aggregate.getAggCallList()) { final SqlAggFunction aggregation = aggCall.getAggregation(); if (aggregation.getKind() == SqlKind.SUM0) { return; } final SqlSplittableAggFunction splitter = Objects.requireNonNull( aggregation.unwrap(SqlSplittableAggFunction.class)); final RexNode singleton = splitter.singleton( rexBuilder, input.getRowType(), aggCall); projects.add(singleton); } final RelNode newInput = convert(input, aggregate.getTraitSet().simplify()); relBuilder.push(newInput); if (!projects.isEmpty()) { projects.addAll(0, relBuilder.fields(aggregate.getGroupSet())); relBuilder.project(projects); } else if (newInput.getRowType().getFieldCount() > aggregate.getRowType().getFieldCount()) { relBuilder.project(relBuilder.fields(aggregate.getGroupSet())); } call.transformTo(relBuilder.build()); }
Source:
public boolean hasNext() { final boolean first = this.left.hasNext(); final boolean second = this.right.hasNext(); return first || second; }

Target:
public boolean hasNext() { return this.left.hasNext() || this.right.hasNext(); }
Source:
public void configureChannels() throws OwException { Thing thing = callback.getThing(); OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider = callback .getDynamicStateDescriptionProvider(); for (Integer i = 0; i < ioConfig.size(); i++) { String channelId = ioConfig.get(i).getChannelId(); Channel channel = thing.getChannel(channelId); if (channel != null) { Configuration channelConfig = channel.getConfiguration(); try { if (channelConfig.get(CONFIG_DIGITAL_MODE) != null) { ioConfig.get(i).setIoMode((String) channelConfig.get(CONFIG_DIGITAL_MODE)); } if (channelConfig.get(CONFIG_DIGITAL_LOGIC) != null) { ioConfig.get(i).setIoLogic((String) channelConfig.get(CONFIG_DIGITAL_LOGIC)); } } catch (IllegalArgumentException e) { throw new OwException(channelId + " has invalid configuration"); } if (dynamicStateDescriptionProvider != null) { dynamicStateDescriptionProvider.setDescription(ioConfig.get(i).getChannelUID(), new StateDescription(null, null, null, null, ioConfig.get(i).isInput(), null)); } else { logger.info( "state description may be inaccurate, state description provider not available in thing {}", thing.getUID()); } logger.debug("configured channel {}: {}", thing.getUID(), i, ioConfig.get(i)); } else { throw new OwException(channelId + " not found"); } } isConfigured = true; }

Target:
public void configureChannels() throws OwException { Thing thing = callback.getThing(); OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider = callback .getDynamicStateDescriptionProvider(); for (Integer i = 0; i < ioConfig.size(); i++) { String channelId = ioConfig.get(i).getChannelId(); Channel channel = thing.getChannel(channelId); if (channel != null) { Configuration channelConfig = channel.getConfiguration(); try { if (channelConfig.get(CONFIG_DIGITAL_MODE) != null) { ioConfig.get(i).setIoMode((String) channelConfig.get(CONFIG_DIGITAL_MODE)); } if (channelConfig.get(CONFIG_DIGITAL_LOGIC) != null) { ioConfig.get(i).setIoLogic((String) channelConfig.get(CONFIG_DIGITAL_LOGIC)); } } catch (IllegalArgumentException e) { throw new OwException(channelId + " has invalid configuration"); } if (dynamicStateDescriptionProvider != null) { dynamicStateDescriptionProvider.setDescription(ioConfig.get(i).getChannelUID(), new StateDescription(null, null, null, null, ioConfig.get(i).isInput(), null)); } else { logger.debug( "state description may be inaccurate, state description provider not available in thing {}", thing.getUID()); } logger.debug("configured channel {}: {}", thing.getUID(), i, ioConfig.get(i)); } else { throw new OwException(channelId + " not found"); } } isConfigured = true; }
Source:
public HttpCacheEntry getEntry(String key) throws IOException { searcherManager.maybeReopen(); IndexSearcher searcher = searcherManager.acquire(); try { Query query = new TermQuery(new Term(KEY_FIELD_NAME, key)); TopDocs topDocs = searcher.search(query, 1); if (topDocs.totalHits > 1) { System.err.println("topDocs.totalHits > 1"); throw new IOException("Corrupt index (cache key is not unique)"); } ScoreDoc[] scoreDocs = topDocs.scoreDocs; if (scoreDocs.length > 0) { ScoreDoc scoreDoc = scoreDocs[0]; Document document = searcher.doc(scoreDoc.doc); return fromLuceneFields(document.getFields()); } else { return null; } } finally { searcherManager.release(searcher); } }

Target:
public HttpCacheEntry getEntry(String key) throws IOException { searcherManager.maybeReopen(); IndexSearcher searcher = searcherManager.acquire(); try { Query query = new TermQuery(new Term(KEY_FIELD_NAME, key)); TopDocs topDocs = searcher.search(query, 1); if (topDocs.totalHits > 1) { throw new IOException("Corrupt index (cache key is not unique)"); } ScoreDoc[] scoreDocs = topDocs.scoreDocs; if (scoreDocs.length > 0) { ScoreDoc scoreDoc = scoreDocs[0]; Document document = searcher.doc(scoreDoc.doc); return fromLuceneFields(document.getFields()); } else { return null; } } finally { searcherManager.release(searcher); } }
Source:
public ResultSet runQuery(String queryStr) throws TskCoreException { ResultSet resultSet = null; try { resultSet = statement.executeQuery(queryStr); } catch (SQLException ex) { throw new TskCoreException("Error running app SQLite query. " + ex.getMessage(), ex); } return resultSet; }

Target:
public ResultSet runQuery(String queryStr) throws SQLException { ResultSet resultSet = null; if (null != queryStr) { resultSet = statement.executeQuery(queryStr); } return resultSet; }
Source:
public void testTranslateServiceCreationConfiguration() { Jsr107ServiceConfigurationParser configTranslator = new Jsr107ServiceConfigurationParser(); Map<String, String> templateMap = new ConcurrentHashMap<>(); templateMap.put("testCache", "simpleCacheTemplate"); templateMap.put("testCache1", "simpleCacheTemplate1"); boolean jsr107CompliantAtomics = true; Jsr107Configuration serviceCreationConfiguration = new Jsr107Configuration("tiny-template", templateMap, jsr107CompliantAtomics, ConfigurationElementState.ENABLED, ConfigurationElementState.DISABLED); Node retElement = configTranslator.unparseServiceCreationConfiguration(serviceCreationConfiguration); assertThat(retElement, is(notNullValue())); checkAttributeItems(retElement); assertThat(retElement.getNodeName(), is("jsr107:defaults")); assertThat(retElement.getFirstChild(), is(notNullValue())); checkCaches(retElement.getFirstChild()); assertThat(retElement.getLastChild(), is(notNullValue())); checkCaches(retElement.getLastChild()); }

Target:
public void testTranslateServiceCreationConfiguration() { Jsr107ServiceConfigurationParser configTranslator = new Jsr107ServiceConfigurationParser(); Map<String, String> templateMap = new HashMap<>(); templateMap.put("testCache", "simpleCacheTemplate"); templateMap.put("testCache1", "simpleCacheTemplate1"); boolean jsr107CompliantAtomics = true; Jsr107Configuration serviceCreationConfiguration = new Jsr107Configuration("tiny-template", templateMap, jsr107CompliantAtomics, ConfigurationElementState.ENABLED, ConfigurationElementState.DISABLED); Node retElement = configTranslator.unparseServiceCreationConfiguration(serviceCreationConfiguration); assertThat(retElement, is(notNullValue())); assertAttributeItems(retElement); assertThat(retElement.getNodeName(), is("jsr107:defaults")); assertThat(retElement.getFirstChild(), is(notNullValue())); assertCaches(retElement.getFirstChild()); assertThat(retElement.getLastChild(), is(notNullValue())); assertCaches(retElement.getLastChild()); }
Source:
private void checkErrorLimit(double errorRateLimit) { if (errorRateLimit < errPct * 100) { double exceededErrorRate = errPct * 100 - errorRateLimit; resultsErrorMessage += "Error rate is " + String.format("%.2f", exceededErrorRate) + "percent higher than the threshold."; } }

Target:
private void checkErrorLimit(double errorRateLimit) { if (errorRateLimit < errorPct) { double exceededErrorRate = errorPct - errorRateLimit; resultsErrorMessage += "Error rate is " + String.format("%.2f", exceededErrorRate) + "% higher than the specified threshold. "; } }
Source:
public BytesReference source(DocumentModel doc) throws IOException { BytesStreamOutput out = new BytesStreamOutput(); try(JsonGenerator jsonGen = jsonFactory.createGenerator(out)) { jsonESDocumentWriter.writeESDocument(jsonGen, doc, null, null); return out.bytes(); } }

Target:
public BytesReference source(DocumentModel doc) throws IOException { BytesStreamOutput out = new BytesStreamOutput(); try (JsonGenerator jsonGen = JSON_FACTORY.createGenerator(out)) { jsonESDocumentWriter.writeESDocument(jsonGen, doc, null, null); return out.bytes(); } }
Source:
public void testFindWorkingVersionFile() throws Exception{ String folderName = "/testOldFile"+UUIDGenerator.generateUuid(); Folder ff = APILocator.getFolderAPI().createFolders(folderName, host, user, false); java.io.File tmp=new java.io.File(APILocator.getFileAPI().getRealAssetPathTmpBinary()+java.io.File.separator+"testOldFile"); if(!tmp.exists()) tmp.mkdirs(); java.io.File data=new java.io.File(tmp, "test-"+UUIDGenerator.generateUuid()+".txt"); FileWriter fw=new FileWriter(data,true); fw.write("file content"); fw.close(); File file = new File(); file.setFileName("legacy.txt"); file.setFriendlyName("legacy.txt"); file.setMimeType("text/plain"); file.setTitle("legacy.txt"); file.setSize((int)data.length()); file.setModUser(user.getUserId()); file.setModDate(Calendar.getInstance().getTime()); file = APILocator.getFileAPI().saveFile(file, data, ff, user, false); Versionable verAPI = APILocator.getVersionableAPI().findWorkingVersion(file.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),file.getTitle()); assertEquals(verAPI.getInode(),file.getInode()); APILocator.getFileAPI().delete(file, user, false); APILocator.getFolderAPI().delete(ff, user, false); }

Target:
public void testFindWorkingVersionFile() throws Exception{ File file = createLegacyFile(); Versionable verAPI = APILocator.getVersionableAPI().findWorkingVersion(file.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),file.getTitle()); assertEquals(verAPI.getInode(),file.getInode()); Folder folder = APILocator.getFileAPI().getFileFolder(file, host, user, false); APILocator.getFileAPI().delete(file, user, false); APILocator.getFolderAPI().delete(folder, user, false); }
Source:
private List<Medication> mergeMedications( @Nonnull final List<Medication> storedMeds, @Nonnull final List<Medication> newMeds) { return storedMeds.get(0).getName() == null ? Stream.of(storedMeds, newMeds).flatMap(Collection::stream).collect(Collectors.toList()) : newMeds; }

Target:
private List<Medication> mergeMedications( @Nonnull final List<Medication> storedMeds, @Nonnull final List<Medication> newMeds) { if (storedMeds.get(0).getName() == null) { final List<Medication> mergedMeds = new ArrayList<>(storedMeds); mergedMeds.addAll(newMeds); return mergedMeds; } else { return newMeds; } }
Source:
public PluginClassLoader pluginClassLoader(String name) { if (PluginUtils.shouldLoadInIsolation(name)) { SortedMap<PluginDesc<?>, ClassLoader> inner = pluginLoaders.get(name); if (inner != null) { ClassLoader pluginLoader = inner.get(inner.lastKey()); if (pluginLoader instanceof PluginClassLoader) { return (PluginClassLoader) pluginLoader; } } } return null; }

Target:
public PluginClassLoader pluginClassLoader(String name) { if (!PluginUtils.shouldLoadInIsolation(name)) { return null; } SortedMap<PluginDesc<?>, ClassLoader> inner = pluginLoaders.get(name); if (inner == null) { return null; } ClassLoader pluginLoader = inner.get(inner.lastKey()); return pluginLoader instanceof PluginClassLoader ? (PluginClassLoader) pluginLoader : null; }
Source:
private void onBlockMovedMsg(final MigrationMsg msg) { final String operationId = msg.getOperationId().toString(); final BlockMovedMsg blockMovedMsg = msg.getBlockMovedMsg(); final int blockId = blockMovedMsg.getBlockId(); Span detached = null; try (final TraceScope onBlockMovedMsgScope = Trace.startSpan( String.format("on_block_moved_msg. blockId: %d", blockId), HTraceUtils.fromAvro(msg.getTraceInfo()))) { final boolean ownershipMsgArrivedFirst; synchronized (this) { ownershipMsgArrivedFirst = ownershipAckMsgArrivedBlockIds.contains(blockId); if (!ownershipMsgArrivedFirst) { detached = onBlockMovedMsgScope.detach(); blockMovedMsgArrivedBlockIds.put(blockId, Optional.ofNullable(TraceInfo.fromSpan(detached))); } else { ownershipAckMsgArrivedBlockIds.remove(blockId); } } if (ownershipMsgArrivedFirst) { handleBlockMovedMsg(operationId, blockId, TraceInfo.fromSpan(onBlockMovedMsgScope.getSpan())); } } finally { Trace.continueSpan(detached).close(); } }

Target:
private void onBlockMovedMsg(final MigrationMsg msg) { final String operationId = msg.getOperationId().toString(); final BlockMovedMsg blockMovedMsg = msg.getBlockMovedMsg(); final int blockId = blockMovedMsg.getBlockId(); Span detached = null; try (final TraceScope onBlockMovedMsgScope = Trace.startSpan( String.format("on_block_moved_msg. blockId: %d", blockId), HTraceUtils.fromAvro(msg.getTraceInfo()))) { final boolean ownershipMsgArrivedFirst; synchronized (this) { ownershipMsgArrivedFirst = ownershipAckMsgArrivedBlockIds.contains(blockId); if (ownershipMsgArrivedFirst) { ownershipAckMsgArrivedBlockIds.remove(blockId); } else { detached = onBlockMovedMsgScope.detach(); blockMovedMsgArrivedBlockIds.put(blockId, Optional.ofNullable(TraceInfo.fromSpan(detached))); } } if (ownershipMsgArrivedFirst) { processBlockMovedMsg(operationId, blockId, TraceInfo.fromSpan(onBlockMovedMsgScope.getSpan())); } } finally { Trace.continueSpan(detached).close(); } }
Source:
protected static long copy(final InputStream input, final OutputStream output) throws IOException { final byte[] buffer = new byte[8024]; long count = 0; int n; while ((n = input.read(buffer)) != -1) { output.write(buffer, 0, n); count += n; } return count; }

Target:
protected static long copy(final InputStream input, final OutputStream output) throws IOException { final byte[] buffer = new byte[8*1024]; long count = 0; int n; while ((n = input.read(buffer)) != -1) { output.write(buffer, 0, n); count += n; } return count; }
Source:
static Request fieldCaps(FieldCapabilitiesRequest fieldCapabilitiesRequest) throws IOException { String methodName = fieldCapabilitiesRequest.indexFilter() != null ? HttpPut.METHOD_NAME : HttpGet.METHOD_NAME; Request request = new Request(methodName, endpoint(fieldCapabilitiesRequest.indices(), "_field_caps")); Params params = new Params(); params.withFields(fieldCapabilitiesRequest.fields()); params.withIndicesOptions(fieldCapabilitiesRequest.indicesOptions()); request.addParameters(params.asMap()); if (fieldCapabilitiesRequest.indexFilter() != null) { request.setEntity(createEntity(fieldCapabilitiesRequest, REQUEST_BODY_CONTENT_TYPE)); } return request; }

Target:
static Request fieldCaps(FieldCapabilitiesRequest fieldCapabilitiesRequest) throws IOException { String methodName = fieldCapabilitiesRequest.indexFilter() != null ? HttpPost.METHOD_NAME : HttpGet.METHOD_NAME; Request request = new Request(methodName, endpoint(fieldCapabilitiesRequest.indices(), "_field_caps")); Params params = new Params(); params.withFields(fieldCapabilitiesRequest.fields()); params.withIndicesOptions(fieldCapabilitiesRequest.indicesOptions()); request.addParameters(params.asMap()); if (fieldCapabilitiesRequest.indexFilter() != null) { request.setEntity(createEntity(fieldCapabilitiesRequest, REQUEST_BODY_CONTENT_TYPE)); } return request; }