auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testInstantiation() throws Exception { maxChunkSize = random.nextInt(1024 * 1024) + 1; blobSize = maxChunkSize * 5; doPut(); String blobIdStr = (new BlobId(mockClusterMap.getWritablePartitionIds().get(0))).getID(); Callback<ReadableStreamChannel> operationCallback = new Callback<ReadableStreamChannel>() { @Override public void onCompletion(ReadableStreamChannel result, Exception exception) { } }; try { new GetBlobOperation(routerConfig, routerMetrics, mockClusterMap, responseHandler, "invalid_id", operationFuture, operationCallback, operationCompleteCallback, time); Assert.fail("Instantiation of GetReadableStreamChannel operation with an invalid blob id must fail"); } catch (RouterException e) { Assert.assertEquals("Unexpected exception received on creating GetBlobOperation", RouterErrorCode.InvalidBlobId, e.getErrorCode()); } GetBlobOperation op = new GetBlobOperation(routerConfig, routerMetrics, mockClusterMap, responseHandler, blobIdStr, operationFuture, operationCallback, operationCompleteCallback, time); Assert.assertEquals("Callbacks must match", operationCallback, op.getCallback()); Assert.assertEquals("Futures must match", operationFuture, op.getFuture()); Assert.assertEquals("Blob ids must match", blobIdStr, op.getBlobIdStr()); }

Target:
public void testInstantiation() throws Exception { Callback<ReadableStreamChannel> operationCallback = new Callback<ReadableStreamChannel>() { @Override public void onCompletion(ReadableStreamChannel result, Exception exception) { } }; try { new GetBlobOperation(routerConfig, routerMetrics, mockClusterMap, responseHandler, "invalid_id", operationFuture, operationCallback, operationCompleteCallback, blobIdFactory, time); Assert.fail("Instantiation of GetBlobOperation with an invalid blob id must fail"); } catch (RouterException e) { Assert.assertEquals("Unexpected exception received on creating GetBlobOperation", RouterErrorCode.InvalidBlobId, e.getErrorCode()); } blobIdStr = new BlobId(mockClusterMap.getWritablePartitionIds().get(0)).getID(); GetBlobOperation op = new GetBlobOperation(routerConfig, routerMetrics, mockClusterMap, responseHandler, blobIdStr, operationFuture, operationCallback, operationCompleteCallback, blobIdFactory, time); Assert.assertEquals("Callbacks must match", operationCallback, op.getCallback()); Assert.assertEquals("Futures must match", operationFuture, op.getFuture()); Assert.assertEquals("Blob ids must match", blobIdStr, op.getBlobIdStr()); }
Source:
private void checkNewNode( boolean client, boolean canWrite, boolean safe ) throws Exception { try { IgniteEx cl = startClientGrid("newNode"); CacheGroupContext grpCtx = cl.context().cache().cacheGroup(CU.cacheId(DEFAULT_CACHE_NAME)); assertTrue(grpCtx.needsRecovery()); verifyCacheOps(canWrite, safe, cl); validateQuery(safe, cl); } finally { stopGrid("newNode", false); } }

Target:
private void checkNewNode( boolean client, boolean canWrite, boolean safe ) throws Exception { try { IgniteEx cl = client ? startClientGrid("newNode") : startGrid("newNode"); CacheGroupContext grpCtx = cl.context().cache().cacheGroup(CU.cacheId(DEFAULT_CACHE_NAME)); assertTrue(grpCtx.needsRecovery()); verifyCacheOps(canWrite, safe, cl); validateQuery(safe, cl); } finally { stopGrid("newNode", false); } }
Source:
private void _checkOldGenUsage() { List<MemoryPoolMXBean> memoryPoolBeans = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean bean : memoryPoolBeans) { if (bean.getType() == MemoryType.HEAP) { String name = bean.getName().toLowerCase(); if (name.contains("old") || name.contains("tenured")) { long oldGenUsed = bean.getUsage().getUsed(); _logger.info("Old Gen Memory = bytes", oldGenUsed); _logger.info("Max JVM Memory = bytes", MAX_MEMORY); if (oldGenUsed > 0.90 * MAX_MEMORY) { _logger.info("JVM heap memory usage has exceeded 90% of the allocated heap memory. Disabling writes to TRIE."); WRITES_TO_TRIE_ENABLED = false; } else if(oldGenUsed < 0.50 * MAX_MEMORY && !WRITES_TO_TRIE_ENABLED) { _logger.info("JVM heap memory usage is below 50% of the allocated heap memory and writes to TRIE is disabled. " + "Enabling writes to TRIE now."); WRITES_TO_TRIE_ENABLED = true; } } } } }

Target:
private void _checkOldGenUsage() { List<MemoryPoolMXBean> memoryPoolBeans = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean bean : memoryPoolBeans) { if (bean.getType() == MemoryType.HEAP) { String name = bean.getName().toLowerCase(); if (name.contains("old") || name.contains("tenured")) { long oldGenUsed = bean.getUsage().getUsed(); _logger.info("Old Gen Memory = bytes", oldGenUsed); _logger.info("Max JVM Memory = bytes", MAX_MEMORY); if (oldGenUsed > 0.90 * MAX_MEMORY) { _logger.info("JVM heap memory usage has exceeded 90% of the allocated heap memory. Disabling writes to TRIE."); _writesToTrieEnabled = false; } else if(oldGenUsed < 0.50 * MAX_MEMORY && !_writesToTrieEnabled) { _logger.info("JVM heap memory usage is below 50% of the allocated heap memory and writes to TRIE is disabled. " + "Enabling writes to TRIE now."); _writesToTrieEnabled = true; } } } } }
Source:
private void parseExcelDocument(File officeFile, String objectID) { String fileType = Files.getFileExtension(officeFile.getAbsolutePath()); Sheet sheet; try { if (fileType.equals(XLSX)) { sheet = new XSSFWorkbook(OPCPackage.open(officeFile.getAbsolutePath())).getSheetAt(0); } else { sheet = new HSSFWorkbook(new FileInputStream(officeFile.getAbsolutePath())).getSheetAt(0); } } catch (OldExcelFormatException e) { showMessage(viewer.getControl().getShell(), SWT.ERROR, "Error", "This version of Excel is not supported."); return; } catch (Exception e) { e.printStackTrace(); showMessage(viewer.getControl().getShell(), SWT.ERROR, "Error", "Couldn't open the file."); return; } DataFormatter formatter = new DataFormatter(); getOpenedView().clearSelection(); if (!objectID.equals(OBJECT_ID_NOT_SPECIFIED)) { Row row = sheet.getRow(Integer.parseInt(objectID)); if (row != null) { CapraExcelRow cRow = new CapraExcelRow(row, officeFile, formatter); if (!cRow.getData().isEmpty()) selection.add(cRow); } } else { for (int i = 0; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row != null) { CapraExcelRow cRow = new CapraExcelRow(row, officeFile, formatter); if (!cRow.getData().isEmpty()) selection.add(cRow); } } } }

Target:
private void parseExcelDocument(File officeFile, String objectID) { String fileType = Files.getFileExtension(officeFile.getAbsolutePath()); Sheet sheet; try { if (fileType.equals(XLSX)) { sheet = new XSSFWorkbook(OPCPackage.open(officeFile)).getSheetAt(0); } else { sheet = new HSSFWorkbook(new FileInputStream(officeFile)).getSheetAt(0); } } catch (OldExcelFormatException e) { showMessage(viewer.getControl().getShell(), SWT.ERROR, "Error", "This version of Excel is not supported."); return; } catch (Exception e) { e.printStackTrace(); showMessage(viewer.getControl().getShell(), SWT.ERROR, "Error", "Couldn't open the file."); return; } DataFormatter formatter = new DataFormatter(); getOpenedView().clearSelection(); if (!objectID.equals(OBJECT_ID_NOT_SPECIFIED)) { Row row = sheet.getRow(Integer.parseInt(objectID)); if (row != null) { CapraExcelRow cRow = new CapraExcelRow(row, officeFile, formatter); if (!cRow.getData().isEmpty()) selection.add(cRow); } } else { for (int i = 0; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row != null) { CapraExcelRow cRow = new CapraExcelRow(row, officeFile, formatter); if (!cRow.getData().isEmpty()) selection.add(cRow); } } } }
Source:
public void onClick(final View v) { ((CoordinatesInputDialog.CalculateState) getActivity()).saveCalculatorState(saveState()); displayToast(R.string.info_calculator_state_saved, true); if (!areCurrentCoordinatesValid(true)) { return; } if (gp != null) { ((CoordinatesInputDialog.CoordinateUpdate) getActivity()).updateCoordinates(gp); } close(); }

Target:
public void onClick(final View v) { final CalcState currentState = getCurrentState(); setSavedState(currentState); ((CoordinatesInputDialog.CalculateState) getActivity()).saveCalculatorState(currentState); displayToast(R.string.info_calculator_state_saved, true); if (!areCurrentCoordinatesValid()) { return; } if (gp != null) { ((CoordinatesInputDialog.CoordinateUpdate) getActivity()).updateCoordinates(gp); } close(); }
Source:
public synchronized MetricsContext beforeSend() { long start = 0; if (this.sendCount.getAndIncrement() % this.sampleSize == 0 && isFullStatsEnabled()) { start = System.nanoTime(); this.sendRate.increment(start); } return new DefaultChannelMetricsContext(start); }

Target:
public synchronized MetricsContext beforeSend() { long count = this.sendCount.getAndIncrement(); if (isFullStatsEnabled() && count % this.sampleSize == 0) { this.start = System.nanoTime(); this.sendRate.increment(start); } return new AggregatingChannelMetricsContext(this.start, count + 1); }
Source:
private Analysis analyzeStatement(Statement statement, Session session, Metadata metadata, AccessControl accessControl, List<Expression> parameters) { Analyzer analyzer = new Analyzer(session, metadata, sqlParser, accessControl, Optional.empty(), parameters, BlackholeWarningSink.getInstance()); return analyzer.analyze(statement); }

Target:
private Analysis analyzeStatement(Statement statement, Session session, Metadata metadata, AccessControl accessControl, List<Expression> parameters) { Analyzer analyzer = new Analyzer(session, metadata, sqlParser, accessControl, Optional.empty(), parameters, BlackholeWarningCollector.getInstance()); return analyzer.analyze(statement); }
Source:
private static Photo toPhoto(Feature feature) { LngLatAlt coordinates = ((Point)feature.getGeometry()).getCoordinates(); GeoPoint geoPoint = new GeoPoint(coordinates.getLatitude(), coordinates.getLongitude()); return new Photo(propertyOrDefault(feature, "id", -1), propertyOrDefault(feature, "categoryId", "Not known"), propertyOrDefault(feature, "metacategoryId", "Not known"), (String)feature.getProperty("caption"), propertyOrDefault(feature, "datetime",-1), (String)feature.getProperty("shortlink"), (String)feature.getProperty("thumbnailUrl"), geoPoint, toVideos(propertyOrDefault(feature, "videoFormats", Collections.<String, Object>emptyMap()))); }

Target:
private static Photo toPhoto(Feature feature) { LngLatAlt coordinates = ((Point)feature.getGeometry()).getCoordinates(); GeoPoint geoPoint = new GeoPoint(coordinates.getLatitude(), coordinates.getLongitude()); return new Photo(propertyOrDefault(feature, "id", -1), propertyOrDefault(feature, "categoryId", "Not known"), propertyOrDefault(feature, "metacategoryId", "Not known"), feature.getProperty("caption"), propertyOrDefault(feature, "datetime",-1), feature.getProperty("shortlink"), feature.getProperty("thumbnailUrl"), geoPoint, toVideos(propertyOrDefault(feature, "videoFormats", Collections.<String, Object>emptyMap()))); }
Source:
public void testGenerateOnlyBreakingCompatibility() throws Exception { final List<String> errors = MainProcess.run( createNotes(createAllNotes(), null, null, null, null), createBaseCliOptions() .setGenerateAll(true).build()); Assert.assertEquals("no errors", 0, errors.size()); assertFile("xdocBreakingCompatibility.txt", MainProcess.XDOC_FILENAME); assertFile("twitterGplusBreakingCompatibility.txt", MainProcess.TWITTER_FILENAME); assertFile("rssMlistBreakingCompatibility.txt", MainProcess.RSS_FILENAME); assertFile("rssMlistBreakingCompatibility.txt", MainProcess.MLIST_FILENAME); }

Target:
public void testGenerateOnlyBreakingCompatibility() throws Exception { final List<String> errors = MainProcess.run( createNotes(createAllNotes(), null, null, null, null), createBaseCliOptions() .setGenerateAll(true).build()); Assert.assertEquals("no errors", 0, errors.size()); assertFile("xdocBreakingCompatibility.txt", MainProcess.XDOC_FILENAME); assertFile("twitterBreakingCompatibility.txt", MainProcess.TWITTER_FILENAME); assertFile("rssMlistBreakingCompatibility.txt", MainProcess.RSS_FILENAME); assertFile("rssMlistBreakingCompatibility.txt", MainProcess.MLIST_FILENAME); }
Source:
public static void main(String... args) throws CheckstyleException, ParseException { final CommandLine commandLine = parseCli(args); if (commandLine.getArgList().size() == 1) { try { writePropertiesFile(commandLine.getArgList().get(0), commandLine.getOptionValue(OPTION_DEST_FILE)); } catch (IOException ex) { throw new CheckstyleException("Failed to write properties file", ex); } } else { printUsage(); } }

Target:
public static void main(String... args) throws CheckstyleException, ParseException { final CommandLine commandLine = parseCli(args); if (commandLine.getArgList().size() == 1) { final File inputFile = new File(commandLine.getArgList().get(0)); final File outputFile = new File(commandLine.getOptionValue(OPTION_DEST_FILE)); writePropertiesFile(inputFile, outputFile); } else { printUsage(); } }
Source:
public static Sla getSLA(Cluster cluster, Process process) { final Sla clusterSla = cluster.getSla(); if (clusterSla != null) { return clusterSla; } final Sla processSla = process.getSla(); return processSla == null ? null : processSla; }

Target:
public static Sla getSLA(Cluster cluster, Process process) { final Sla clusterSla = cluster.getSla(); if (clusterSla != null) { return clusterSla; } return process.getSla(); }
Source:
public void addVertexHopCriteria(SearchResult searchResult, GraphContainer container) { LOG.debug("SearchProvider->addVertexHopCriteria: called with search result: '{}'", searchResult); VertexHopCriteria criterion = LinkdHopCriteria.createCriteria(container.getMetaTopologyId(),searchResult.getId(), searchResult.getLabel()); container.addCriteria(criterion); LOG.debug("SearchProvider->addVertexHop: adding hop criteria {}.", criterion); logCriteriaInContainer(container); }

Target:
public void addVertexHopCriteria(SearchResult searchResult, GraphContainer container) { LOG.debug("SearchProvider->addVertexHopCriteria: called with search result: '{}'", searchResult); VertexHopCriteria criterion = LinkdHopCriteria.createCriteria(searchResult.getNamespace(), searchResult.getId(), searchResult.getLabel()); container.addCriteria(criterion); LOG.debug("SearchProvider->addVertexHop: adding hop criteria {}.", criterion); logCriteriaInContainer(container); }
Source:
public Optional<Object> apply( final Object... args ) { Integer minInt = Integer.MAX_VALUE; Double minDouble = Double.MAX_VALUE; if(args.length == 0) { return Optional.empty(); } for(Object arg: args) { if(arg instanceof Integer) { minInt = java.lang.Math.min( minInt, (Integer) arg ); } else if(arg instanceof Double) { minDouble = java.lang.Math.min( minDouble, (Double) arg ); } } if(minInt == Integer.MAX_VALUE && minDouble == Double.MAX_VALUE) { return Optional.<Object>of( Double.NaN ); } if ( minInt.doubleValue() <= minDouble ) { return Optional.<Object>of(minInt); } else { return Optional.<Object>of(minDouble); } }

Target:
public Optional<Object> apply( final Object... args ) { Integer minInt = Integer.MAX_VALUE; Double minDouble = Double.MAX_VALUE; Long minLong = Long.MAX_VALUE; if(args.length == 0) { return Optional.empty(); } for(Object arg: args) { if(arg instanceof Integer) { minInt = java.lang.Math.min( minInt, (Integer) arg ); } else if(arg instanceof Double) { minDouble = java.lang.Math.min( minDouble, (Double) arg ); } else if(arg instanceof Long) { minLong = java.lang.Math.min( minLong, (Long) arg ); } } if(minInt == Integer.MAX_VALUE && minDouble == Double.MAX_VALUE) { return Optional.empty(); } if(minInt.longValue() <= minDouble.longValue() && minInt.longValue() <= minLong) { return Optional.<Object>of(minInt); } else if(minLong <= minDouble.longValue() && minLong <= minInt.longValue()) { return Optional.<Object>of(minLong); } else { return Optional.<Object>of(minDouble); } }
Source:
public void waitNavigationBar() { new WebDriverWait(seleniumWebDriver, LOAD_PAGE_TIMEOUT_SEC).until(visibilityOf(navigationBar)); }

Target:
public void waitNavigationBar() { seleniumWebDriverHelper.waitVisibility(navigationBar, LOAD_PAGE_TIMEOUT_SEC); }
Source:
public HashMap<String, String> toMap() { ObjectMapper objectMapper = new ObjectMapper(); HashMap<String, String> map = new HashMap<>(); ObjectNode node = objectMapper.convertValue(this, ObjectNode.class); node.fieldNames().forEachRemaining(fieldName -> { map.put(fieldName, node.get(fieldName).asText()); }); return map; }

Target:
public Map<String, String> toMap() { return objectMapper.convertValue(this, new TypeReference<Map<String, String>>() { }); }
Source:
public CompletableFuture<String> generateMap(String version, byte[] optionArray) { ByteBuffer seedBuffer = ByteBuffer.allocate(8); seedBuffer.putLong(seedGenerator.nextLong()); String seedString = Base64.getEncoder().encodeToString(seedBuffer.array()); String optionString = Base64.getEncoder().encodeToString(optionArray); return generateMap(version,seedString+'_'+optionString); }

Target:
public CompletableFuture<String> generateMap(String version, byte[] optionArray) { return generateMap(new ComparableVersion(version), optionArray); }
Source:
public boolean taskFailed(int siteId, long taskId, String lockId, AgentId agentId, Config error) { boolean changed = sm.lockTaskIfExists(taskId, (store, task) -> taskFailed(new TaskControl(store, task), error) ).or(false); if (changed) { try { dispatcher.taskFinished(siteId, lockId, agentId); } catch (TaskNotFoundException ex) { logger.debug("Ignoring missing task entry error", ex); } catch (TaskConflictException ex) { logger.warn("Ignoring preempted task entry error", ex); } } return changed; }

Target:
public boolean taskFailed(int siteId, long taskId, String lockId, AgentId agentId, Config error) { boolean changed = sm.lockTaskIfExists(taskId, (store, task) -> taskFailed(new TaskControl(store, task), error) ).or(false); if (changed) { try { dispatcher.taskFinished(siteId, lockId, agentId); } catch (TaskNotFoundException ex) { logger.warn("Ignoring missing task entry error", ex); } catch (TaskConflictException ex) { logger.warn("Ignoring preempted task entry error", ex); } } return changed; }
Source:
public void setDriverClassName(String driverClassName) { Class<?> driverClass = null; try { driverClass = this.getClass().getClassLoader().loadClass(driverClassName); LOGGER.info("Driver class found in the Hikari classes classloader {}", this.getClass().getClassLoader()); } catch (ClassNotFoundException e) { if (Thread.currentThread().getContextClassLoader() != this.getClass().getClassLoader()) { try { driverClass = Thread.currentThread().getContextClassLoader().loadClass(driverClassName); LOGGER.info("Driver class found in Thread context class loader {}", Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e1) { LOGGER.error("Failed to load class of driverClassName in either of HikariConfig class loader or Thread context classloader {}", driverClassName, this.getClass().getClassLoader(), Thread.currentThread().getContextClassLoader()); } } else { LOGGER.error("Failed to load class of driverClassName in HikariConfig class loader {}", driverClassName, this.getClass().getClassLoader()); } } if (driverClass == null) { throw new RuntimeException("Failed to load class of driverClassName [" + driverClassName + "] in either of HikariConfig class loader or Thread context classloader"); } try { driverClass.newInstance(); this.driverClassName = driverClassName; } catch (Exception e) { throw new RuntimeException("Failed to instantiate class " + driverClassName, e); } }

Target:
public void setDriverClassName(String driverClassName) { Class<?> driverClass = null; try { driverClass = this.getClass().getClassLoader().loadClass(driverClassName); LOGGER.debug("Driver class found in the HikariConfig class classloader {}", this.getClass().getClassLoader()); } catch (ClassNotFoundException e) { ClassLoader threadContextClassLoader = Thread.currentThread().getContextClassLoader(); if (threadContextClassLoader != null && threadContextClassLoader != this.getClass().getClassLoader()) { try { driverClass = threadContextClassLoader.loadClass(driverClassName); LOGGER.debug("Driver class found in Thread context class loader {}", threadContextClassLoader); } catch (ClassNotFoundException e1) { LOGGER.error("Failed to load class of driverClassName in either of HikariConfig class classloader or Thread context classloader {}", driverClassName, this.getClass().getClassLoader(), threadContextClassLoader); } } else { LOGGER.error("Failed to load class of driverClassName in HikariConfig class classloader {}", driverClassName, this.getClass().getClassLoader()); } } if (driverClass == null) { throw new RuntimeException("Failed to load class of driverClassName [" + driverClassName + "] in either of HikariConfig class loader or Thread context classloader"); } try { driverClass.newInstance(); this.driverClassName = driverClassName; } catch (Exception e) { throw new RuntimeException("Failed to instantiate class " + driverClassName, e); } }
Source:
public void compile(final ThemeArchive.ThemeModifier modifier) { try { final LessCompiler lessCompiler = new LessCompiler(); lessCompiler.setEncoding("UTF-8"); File file = modifier.resolve(input); if (!Files.exists(file.toPath())) { LOGGER.warning(format("Trying to compile <%s> but it does not exist.", file)); return; } modifier.add(output, lessCompiler.compile(file).getBytes("UTF-8")); } catch (final LessException | IOException e) { throw new LessCompilationException("Failed to compile " + input, e); } }

Target:
public byte[] compile(final ThemeArchive.ThemeModifier modifier) { final LessCompiler lessCompiler = new LessCompiler(); lessCompiler.setEncoding("UTF-8"); File file = modifier.resolve(input); if (!Files.exists(file.toPath())) { LOGGER.warning(format("Theme compilation failure. File <%s> not found", file)); return new byte[0]; } try { final byte[] compilation = lessCompiler.compile(file).getBytes("UTF-8"); modifier.add(output, compilation); return compilation; } catch (final LessException | IOException e) { throw new LessCompilationException("Failed to compile " + input, e); } }
Source:
protected final void ensureUniqueId(String type, TransactionContext context) { final Timer idGenerationTimer = context.service(Metrics.class).timer("idGeneration"); try { idGenerationTimer.start(); if (getIdGenerationStrategy() instanceof RegisteringIdStrategy) { final String componentId = getIdGenerationStrategy().generate(context); try { checkComponentExists(context, componentId); throw new AlreadyExistsException(type, componentId); } catch (ComponentNotFoundException e) { setIdGenerationStrategy(new ConstantIdStrategy(componentId)); return; } } else if (getIdGenerationStrategy() instanceof ReservingIdStrategy) { String componentId = null; for (int i = 0; i < ID_GENERATION_ATTEMPTS; i++) { componentId = getIdGenerationStrategy().generate(context); try { checkComponentExists(context, componentId); } catch (ComponentNotFoundException e) { setIdGenerationStrategy(new RegisteringIdStrategy(componentId)); return; } } throw new BadRequestException("Couldn't generate unique identifier for %s after %d attempts.", type, ID_GENERATION_ATTEMPTS); } else if (getIdGenerationStrategy() instanceof ConstantIdStrategy) { String componentId = getIdGenerationStrategy().generate(context); try { checkComponentExists(context, componentId); throw new AlreadyExistsException(type, componentId); } catch (ComponentNotFoundException e) { return; } } } finally { idGenerationTimer.stop(); } }

Target:
protected final void ensureUniqueId(String type, TransactionContext context) { final Timer idGenerationTimer = context.service(Metrics.class).timer("idGeneration"); try { idGenerationTimer.start(); if (getIdGenerationStrategy() instanceof RegisteringIdStrategy) { final String componentId = getIdGenerationStrategy().generate(context); try { checkComponentExists(context, componentId); throw new AlreadyExistsException(type, componentId); } catch (ComponentNotFoundException e) { setIdGenerationStrategy(new ConstantIdStrategy(componentId)); return; } } else if (getIdGenerationStrategy() instanceof ReservingIdStrategy) { String componentId = null; for (int i = 0; i < IdRequest.ID_GENERATION_ATTEMPTS; i++) { componentId = getIdGenerationStrategy().generate(context); try { checkComponentExists(context, componentId); } catch (ComponentNotFoundException e) { setIdGenerationStrategy(new RegisteringIdStrategy(componentId)); return; } } throw new BadRequestException("Couldn't generate unique identifier for %s after %d attempts.", type, IdRequest.ID_GENERATION_ATTEMPTS); } else if (getIdGenerationStrategy() instanceof ConstantIdStrategy) { String componentId = getIdGenerationStrategy().generate(context); try { checkComponentExists(context, componentId); throw new AlreadyExistsException(type, componentId); } catch (ComponentNotFoundException e) { return; } } } finally { idGenerationTimer.stop(); } }
Source:
public void setSystemProperty(CoreSession session, List<String> ids, Boolean value) { List<DocumentRef> updatedRefs = new ArrayList<>(ids.size()); String query = String.format(SYSPROP_QUERY_TEMPLATE, value ? "0" : "1", String.join("', '", ids)); try (IterableQueryResult res = session.queryAndFetch(query, NXQL)) { for (Map<String, Serializable> map : res) { DocumentRef ref = new IdRef((String) map.get(ECM_UUID)); try { session.setDocumentSystemProp(ref, "isTrashed", value); String docName = (String) map.get(ECM_NAME); TrashService trashService = Framework.getService(TrashService.class); if (!value && trashService.isMangledName(docName)) { DocumentRef parentRef = new IdRef((String) map.get(ECM_PARENTID)); session.move(ref, parentRef, trashService.unmangleName(session, parentRef, docName)); } updatedRefs.add(ref); } catch (NuxeoException e) { log.warn("Cannot set system property: isTrashed on: " + ref.toString(), e); } } } try { session.save(); if (!updatedRefs.isEmpty()) { fireEvent(session, value ? DOCUMENT_TRASHED : DOCUMENT_UNTRASHED, updatedRefs); } } catch (PropertyException e) { log.warn("Cannot save session", e); } }

Target:
public void setSystemProperty(CoreSession session, List<String> ids, Boolean value) { List<DocumentRef> updatedRefs = new ArrayList<>(ids.size()); String query = String.format(SYSPROP_QUERY_TEMPLATE, value ? "0" : "1", String.join("', '", ids)); try (IterableQueryResult res = session.queryAndFetch(query, NXQL)) { TrashService trashService = Framework.getService(TrashService.class); for (Map<String, Serializable> map : res) { DocumentRef ref = new IdRef((String) map.get(ECM_UUID)); try { session.setDocumentSystemProp(ref, "isTrashed", value); String docName = (String) map.get(ECM_NAME); if (!value && trashService.isMangledName(docName)) { DocumentRef parentRef = new IdRef((String) map.get(ECM_PARENTID)); session.move(ref, parentRef, trashService.unmangleName(session, parentRef, docName)); } updatedRefs.add(ref); } catch (NuxeoException e) { log.warn("Cannot set system property: isTrashed on: " + ref.toString(), e); } } } try { session.save(); if (!updatedRefs.isEmpty()) { fireEvent(session, value ? DOCUMENT_TRASHED : DOCUMENT_UNTRASHED, updatedRefs); } } catch (PropertyException e) { log.warn("Cannot save session", e); } }
Source:
public void onUpdate(IItemRelocator relocator, int side) { ++tick; if (tick == 4) { tick = 0; emitRedstoneSignal = false; markRedstoneUpdate(relocator.getTileEntity()); } }

Target:
public void onUpdate(IItemRelocator relocator, int side) { if (tick >= 0) { --tick; if (tick == 0) { emitRedstoneSignal = false; markRedstoneUpdate(relocator.getTileEntity()); } } }
Source:
public void setUp() throws Exception { perms = new AccessPermissionListMock(); user = SecurityPrincipalMocks.createAdministratorUser(); }

Target:
public void setUp() { perms = new AccessPermissionListMock(); user = SecurityPrincipalMocks.createAdministratorUser(); }
Source:
public void initialize() { playerTextField.textProperty().addListener((observable, oldValue, newValue) -> { playerList.setAll(getPlayerNames()); playersListView.getSelectionModel().selectFirst(); }); filteredPlayerList.predicateProperty().bind(Bindings.createObjectBinding(() -> p -> { if (playerService.getCurrentPlayer().map(Player::getUsername).map(n -> n.equals(p)).orElse(true)) { return false; } if (playerTextField.getText().trim().equals("")) { return playerService.getPlayerForUsername(p).map(player -> player.getSocialStatus() == SocialStatus.FRIEND).orElse(false); } else { return p.toLowerCase().contains(playerTextField.getText().toLowerCase()); } }, playerTextField.textProperty() )); playersListView.setItems(sortedPlayerList); playerTextField.setText(""); playerTextField.requestFocus(); }

Target:
public void initialize() { playerTextField.textProperty().addListener((observable, oldValue, newValue) -> { playersListView.getSelectionModel().selectFirst(); }); playerList.setAll(getPlayerNames()); filteredPlayerList.predicateProperty().bind(Bindings.createObjectBinding(() -> p -> { if (playerService.getCurrentPlayer() .map(Player::getUsername) .map(n -> n.equals(p)) .orElse(true)) { return false; } if (playerTextField.getText().isBlank()) { return playerService.getPlayerForUsername(p) .map(player -> player.getSocialStatus() == SocialStatus.FRIEND) .orElse(false); } else { return p.toLowerCase().contains(playerTextField.getText().toLowerCase()); } }, playerTextField.textProperty() )); playersListView.setItems(sortedPlayerList); playersListView.getSelectionModel().selectFirst(); requestFocus(); }
Source:
protected boolean migrateProperties(int version) { boolean migrated = false; if (version < CONVERT_COLUMNS_AND_TABLE_TO_UPPERCASE_VERSION) { convertColumnsAndTableToUppercase.setValue(false); migrated = true; } if(version < TABLE_ACTION_VERSION) { tableAction.setValue(TableAction.TableActionEnum.NONE); migrated = true; } if (version < CONVERT_EMPTY_STRINGS_TO_NULL_VERSION) { convertEmptyStringsToNull.setValue(true); migrated = true; } if(version < DB_TYPE_SELECTION_VERSION) { usePersonalDBType.setValue(false); migrated = true; } return migrated; }

Target:
protected boolean migrateProperties(int version) { boolean migrated = false; if (version < CONVERT_COLUMNS_AND_TABLE_TO_UPPERCASE_VERSION) { convertColumnsAndTableToUppercase.setValue(false); migrated = true; } if(version < TABLE_ACTION_VERSION) { tableAction.setValue(TableAction.TableActionEnum.NONE); migrated = true; } if (version < CONVERT_EMPTY_STRINGS_TO_NULL_VERSION) { convertEmptyStringsToNull.setValue(true); migrated = true; } return migrated; }
Source:
private void updateMetrics(long beginProcessing, long endProcessing, SamzaSqlRelMsgMetadata metadata) { insertProcessingTime.update(TranslatorUtils.getMicroDurationFromNanoTimes(beginProcessing, endProcessing)); long outputTime = System.nanoTime(); queryOutputEvents.inc(); Validate.isTrue(metadata.hasScanSystemNanoTime()); long scanTime = metadata.getScanSystemNanoTime(); queryLatency.update(TranslatorUtils.getMicroDurationFromNanoTimes(scanTime, outputTime)); if (metadata.hasArrivalSystemNanoTime()) { long arrivalTime = metadata.getArrivalSystemNanoTime(); queueingLatency.update(TranslatorUtils.getMicroDurationFromNanoTimes(arrivalTime, scanTime)); } if (metadata.hasEventTime()) { long eventTime = metadata.getEventTime(); totalLatency.update(Duration.between(Instant.ofEpochMilli(eventTime), Instant.now()).toMillis()); } }

Target:
private void updateMetrics(long beginProcessing, long endProcessing, SamzaSqlRelMsgMetadata metadata) { insertProcessingTime.update(endProcessing - beginProcessing); queryOutputEvents.inc(); Validate.isTrue(metadata.hasScanTime()); queryLatencyNs.update(System.nanoTime() - metadata.getScanTimeNanos()); if (metadata.hasArrivalTime()) { queuingLatencyMS.update(metadata.getScanTimeMillis() - metadata.getArrivalTime()); } if (metadata.hasEventTime()) { totalLatencyMs.update(System.currentTimeMillis() - metadata.getEventTime()); } }
Source:
private ClientConnection createConnection() throws IOException, TechnicalException { final SecurityKey validAuthenticationKey = this.getSecurityKey(SecurityKeyType.E_METER_AUTHENTICATION); final SecurityKey validEncryptionKey = this.getSecurityKey(SecurityKeyType.E_METER_ENCRYPTION); try { final String authenticationKeyValue = validAuthenticationKey.getKey(); final String encryptionKeyValue = validEncryptionKey.getKey(); final byte[] authenticationKey = org.apache.commons.codec.binary.Hex.decodeHex(authenticationKeyValue .toCharArray()); final byte[] encryptionKey = org.apache.commons.codec.binary.Hex .decodeHex(encryptionKeyValue.toCharArray()); final byte[] decryptedAuthentication = RSAEncrypterService.decrypt(authenticationKey, this.devicePrivateKeyPath); final byte[] decryptedEncryption = RSAEncrypterService.decrypt(encryptionKey, this.devicePrivateKeyPath); final TcpConnectionBuilder tcpConnectionBuilder = new TcpConnectionBuilder( InetAddress.getByName(this.device.getIpAddress())) .useGmacAuthentication(decryptedAuthentication, decryptedEncryption) .enableEncryption(decryptedEncryption).responseTimeout(this.responseTimeout) .logicalDeviceAddress(this.logicalDeviceAddress).clientAccessPoint(this.clientAccessPoint); final Integer challengeLength = this.device.getChallengeLength(); if (challengeLength != null) { tcpConnectionBuilder.challengeLength(challengeLength); } return tcpConnectionBuilder.buildLnConnection(); } catch (final DecoderException e) { LOGGER.error("Unexpected exception while readinig RSA key", e); throw new TechnicalException(ComponentType.PROTOCOL_DLMS, "Error while reading RSA key! "); } }

Target:
private ClientConnection createConnection() throws IOException, TechnicalException, RsaEncrypterException { final SecurityKey validAuthenticationKey = this.getSecurityKey(SecurityKeyType.E_METER_AUTHENTICATION); final SecurityKey validEncryptionKey = this.getSecurityKey(SecurityKeyType.E_METER_ENCRYPTION); final byte[] authenticationKey = Hex.decode(validAuthenticationKey.getKey()); final byte[] encryptionKey = Hex.decode(validEncryptionKey.getKey()); final byte[] decryptedAuthentication = RsaEncrypterService .decrypt(authenticationKey, this.devicePrivateKeyPath); final byte[] decryptedEncryption = RsaEncrypterService.decrypt(encryptionKey, this.devicePrivateKeyPath); final TcpConnectionBuilder tcpConnectionBuilder = new TcpConnectionBuilder(InetAddress.getByName(this.device .getIpAddress())).useGmacAuthentication(decryptedAuthentication, decryptedEncryption) .enableEncryption(decryptedEncryption).responseTimeout(this.responseTimeout) .logicalDeviceAddress(this.logicalDeviceAddress).clientAccessPoint(this.clientAccessPoint); final Integer challengeLength = this.device.getChallengeLength(); if (challengeLength != null) { tcpConnectionBuilder.challengeLength(challengeLength); } return tcpConnectionBuilder.buildLnConnection(); }
Source:
public Object combine(Object lhs, Object rhs) { return (((SerializablePair<Long, Double>) lhs).lhs > ((SerializablePair<Long, Double>) rhs).lhs) ? lhs : rhs; }

Target:
public Object combine(Object lhs, Object rhs) { return DoubleFirstAggregatorFactory.TIME_COMPARATOR.compare(lhs, rhs) > 0 ? lhs : rhs; }
Source:
void addUnloadedPlayer(String id, EntityData.PlayerStore unloadedPlayer) { unloadedPlayers.put(id, unloadedPlayer); }

Target:
public void addUnloadedPlayer(String id, EntityData.PlayerStore unloadedPlayer) { unloadedPlayers.put(id, unloadedPlayer); }
Source:
private void linkPointsToStreets(boolean all) { LambdaCounter counter = new LambdaCounter(LOG, pointSet.featureCount(), 10000, "Linked of PointSet points to streets."); IntStream.range(0, pointSet.featureCount()).parallel().forEach(p -> { if (all || streetLayer.edgeStore.temporarilyDeletedEdges != null && streetLayer.edgeStore.temporarilyDeletedEdges.contains(edges[p])) { Split split = streetLayer.findSplit(pointSet.getLat(p), pointSet.getLon(p), MAX_OFFSTREET_WALK_METERS, streetMode); if (split == null) { edges[p] = -1; } else { edges[p] = split.edge; distances0_mm[p] = split.distance0_mm; distances1_mm[p] = split.distance1_mm; } counter.increment(); } }); long unlinked = Arrays.stream(edges).filter(e -> e == -1).count(); counter.done(); LOG.info("{} points are not linked to the street network.", unlinked); }

Target:
private void linkPointsToStreets(boolean all) { LambdaCounter counter = new LambdaCounter(LOG, pointSet.featureCount(), 10000, "Linked of PointSet points to streets."); IntStream.range(0, pointSet.featureCount()).parallel().forEach(p -> { if (all || (streetLayer.edgeStore.temporarilyDeletedEdges != null && streetLayer.edgeStore.temporarilyDeletedEdges.contains(edges[p]))) { Split split = streetLayer.findSplit(pointSet.getLat(p), pointSet.getLon(p), MAX_OFFSTREET_WALK_METERS, streetMode); if (split == null) { edges[p] = -1; } else { edges[p] = split.edge; distances0_mm[p] = split.distance0_mm; distances1_mm[p] = split.distance1_mm; } counter.increment(); } }); long unlinked = Arrays.stream(edges).filter(e -> e == -1).count(); counter.done(); LOG.info("{} points are not linked to the street network.", unlinked); }
Source:
public void testRebuildArtifactsIndexes() throws NoSuchAlgorithmException, XmlPullParserException, IOException, ClassNotFoundException, SchedulerException, InstantiationException, CronTaskException, IllegalAccessException, CronTaskNotFoundException, InterruptedException, ParseException { String jobName = "RebuildIndex-1"; addRebuildCronJobConfig(jobName, "storage0", "releases-one", ARTIFACT_BASE_PATH_STRONGBOX_INDEXES); while (!jobManager.getExecutedJobs().containsKey(jobName)) { Thread.sleep(8000); } System.out.println(jobManager.getExecutedJobs().toString()); SearchRequest request = new SearchRequest("storage0", "releases-one", "+g:org.carlspring.strongbox.indexes +a:strongbox-test-one +v:1.0 +p:jar"); assertTrue(artifactSearchService.contains(request)); deleteRebuildCronJobConfig(jobName); }

Target:
public void testRebuildArtifactsIndexes() throws Exception { String jobName = "RebuildIndex-1"; addRebuildCronJobConfig(jobName, "storage0", "releases-one", ARTIFACT_BASE_PATH_STRONGBOX_INDEXES); while (!jobManager.getExecutedJobs().containsKey(jobName)) { Thread.sleep(8000); } System.out.println(jobManager.getExecutedJobs().toString()); SearchRequest request = new SearchRequest("storage0", "releases-one", "+g:org.carlspring.strongbox.indexes +a:strongbox-test-one +v:1.0 +p:jar"); assertTrue(artifactSearchService.contains(request)); deleteRebuildCronJobConfig(jobName); }
Source:
private boolean isRenameAllowed(String catalogName, String srcDBName, String destDBName) throws MetaException, NoSuchObjectException { RawStore ms = getMS(); if (!srcDBName.equalsIgnoreCase(destDBName)) { Database destDB = ms.getDatabase(catalogName, destDBName); if (destDB == null) { throw new NoSuchObjectException("The destination db " + destDBName + " is not found"); } Database srcDB = ms.getDatabase(catalogName, srcDBName); if (srcDB == null) { throw new NoSuchObjectException("The source db " + srcDBName + " is not found"); } if (ReplChangeManager.isSourceOfReplication(srcDB) || ReplChangeManager.isSourceOfReplication(destDB)) { LOG.info("Cannot rename as either " + srcDBName + " or " + destDBName + " is a source of replication"); return false; } } return true; }

Target:
private boolean isRenameAllowed(String catalogName, String srcDBName, String destDBName) throws MetaException, NoSuchObjectException { RawStore ms = getMS(); if (!srcDBName.equalsIgnoreCase(destDBName)) { Database destDB = ms.getDatabase(catalogName, destDBName); Database srcDB = ms.getDatabase(catalogName, srcDBName); if (ReplChangeManager.isSourceOfReplication(srcDB) || ReplChangeManager.isSourceOfReplication(destDB)) { return false; } } return true; }
Source:
public void testWithEmptySet() { final Set<AlarmNotification> alarmNotificationSet = new TreeSet<AlarmNotification>(); final AlarmNotifications alarmNotifications = new AlarmNotifications(alarmNotificationSet); final AlarmNotificationsDto alarmNotificationsDto = this.configurationMapper.map(alarmNotifications, AlarmNotificationsDto.class); assertNotNull(alarmNotifications); assertNotNull(alarmNotificationsDto); assertNotNull(alarmNotificationSet); assertNotNull(alarmNotificationsDto.getAlarmNotifications()); assertTrue(alarmNotificationSet.isEmpty()); assertTrue(alarmNotificationsDto.getAlarmNotifications().isEmpty()); assertEquals(alarmNotificationSet.isEmpty(), alarmNotificationsDto.getAlarmNotifications().isEmpty()); }

Target:
public void testWithEmptySet() { final Set<AlarmNotification> alarmNotificationSet = new TreeSet<AlarmNotification>(); final AlarmNotifications alarmNotifications = new AlarmNotifications(alarmNotificationSet); final AlarmNotificationsDto alarmNotificationsDto = this.configurationMapper.map(alarmNotifications, AlarmNotificationsDto.class); assertNotNull(alarmNotificationsDto); assertNotNull(alarmNotificationsDto.getAlarmNotificationsSet()); assertTrue(alarmNotificationsDto.getAlarmNotificationsSet().isEmpty()); }
Source:
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { log.debug("Attempting Keycloak authentication"); HttpFacade facade = new SimpleHttpFacade(request, response); KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade); AdapterTokenStore tokenStore = adapterTokenStoreFactory.createAdapterTokenStore(deployment, request); RequestAuthenticator authenticator = new SpringSecurityRequestAuthenticator(facade, request, deployment, tokenStore, -1); AuthOutcome result = authenticator.authenticate(); log.debug("Auth outcome: {}", result); if (AuthOutcome.FAILED.equals(result)) { throw new KeycloakAuthenticationException("Auth outcome: " + result); } else if (AuthOutcome.AUTHENTICATED.equals(result)) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Assert.notNull(authentication, "Authentication SecurityContextHolder was null"); return authenticationManager.authenticate(authentication); } else { AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { challenge.challenge(facade); } return null; } }

Target:
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { log.debug("Attempting Keycloak authentication"); HttpFacade facade = new SimpleHttpFacade(request, response); KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade); deployment.setContainerErrorPage(false); AdapterTokenStore tokenStore = adapterTokenStoreFactory.createAdapterTokenStore(deployment, request); RequestAuthenticator authenticator = new SpringSecurityRequestAuthenticator(facade, request, deployment, tokenStore, -1); AuthOutcome result = authenticator.authenticate(); log.debug("Auth outcome: {}", result); if (AuthOutcome.FAILED.equals(result)) { throw new KeycloakAuthenticationException("Auth outcome: " + result); } else if (AuthOutcome.AUTHENTICATED.equals(result)) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Assert.notNull(authentication, "Authentication SecurityContextHolder was null"); return authenticationManager.authenticate(authentication); } else { AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { challenge.challenge(facade); } return null; } }
Source:
public void run(final ActionContext context) throws Exception { config.validate(); Connection connection = new Connection(config.host); try { connection.connect(); char[] privateKey = new String(context.getSecureData(context.getNamespace(), config.privateKeyFileLookupKey).get()).toCharArray(); String passphrase = Strings.isNullOrEmpty(config.passphrase) ? "" : config.passphrase; if (!connection.authenticateWithPublicKey(config.user, privateKey, passphrase)) { throw new IOException(String.format("SSH authentication error when connecting to %s@%s on port %d", config.user, config.host, config.port)); } LOG.debug("Connection established with the host {}", config.host); Session session = connection.openSession(); session.execCommand(config.command); InputStream stdout = new StreamGobbler(session.getStdout()); BufferedReader outBuffer = new BufferedReader(new InputStreamReader(stdout, Charsets.UTF_8)); InputStream stderr = new StreamGobbler(session.getStderr()); BufferedReader errBuffer = new BufferedReader(new InputStreamReader(stderr, Charsets.UTF_8)); String out = CharStreams.toString(outBuffer); String err = CharStreams.toString(errBuffer); if (out.length() > 0) { LOG.debug("Stdout: {}", out); } if (err.length() > 0) { LOG.error("Stderr: {}", err); } Integer exitCode = session.getExitStatus(); if (exitCode != null && exitCode != 0) { throw new IOException(String.format("Error: command %s running on hostname %s finished with exit code: %d", config.command, config.host, exitCode)); } if (config.output != null) { out = out.endsWith("\n") ? out.substring(0, out.length() - 1) : out; context.getArguments().set(config.output, out); } } finally { connection.close(); } }

Target:
public void run(final ActionContext context) throws Exception { config.validate(); Connection connection = new Connection(config.host); try { connection.connect(); if (!connection.authenticateWithPublicKey(config.user, config.privateKey.toCharArray(), config.passphrase)) { throw new IOException(String.format("SSH authentication error when connecting to %s@%s on port %d", config.user, config.host, config.port)); } LOG.debug("Connection established with the host {}", config.host); Session session = connection.openSession(); session.execCommand(config.command); InputStream stdout = new StreamGobbler(session.getStdout()); BufferedReader outBuffer = new BufferedReader(new InputStreamReader(stdout, Charsets.UTF_8)); InputStream stderr = new StreamGobbler(session.getStderr()); BufferedReader errBuffer = new BufferedReader(new InputStreamReader(stderr, Charsets.UTF_8)); String out = CharStreams.toString(outBuffer); String err = CharStreams.toString(errBuffer); if (out.length() > 0) { LOG.debug("Stdout: {}", out); } if (err.length() > 0) { LOG.error("Stderr: {}", err); } Integer exitCode = session.getExitStatus(); if (exitCode != null && exitCode != 0) { throw new IOException(String.format("Error: command %s running on hostname %s finished with exit code: %d", config.command, config.host, exitCode)); } out = out.endsWith("\n") ? out.substring(0, out.length() - 1) : out; context.getArguments().set(config.outputKey, out); } finally { connection.close(); } }
Source:
public ListenableFuture<?> execute(AlterFunction statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) { Analyzer analyzer = new Analyzer(stateMachine.getSession(), metadata, sqlParser, accessControl, Optional.empty(), parameters, stateMachine.getWarningCollector()); analyzer.analyze(statement); QualifiedFunctionName functionName = QualifiedFunctionName.of(statement.getFunctionName().toString()); AlterRoutineCharacteristics alterRoutineCharacteristics = new AlterRoutineCharacteristics( statement.getCharacteristics().getNullCallClause().map(nullCallClause -> RoutineCharacteristics.NullCallClause.valueOf(nullCallClause.name()))); metadata.getFunctionManager().alterFunction( functionName, statement.getParameterTypes().map(types -> types.stream().map(TypeSignature::parseTypeSignature).collect(toImmutableList())), alterRoutineCharacteristics); return immediateFuture(null); }

Target:
public ListenableFuture<?> execute(AlterFunction statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) { Analyzer analyzer = new Analyzer(stateMachine.getSession(), metadata, sqlParser, accessControl, Optional.empty(), parameters, stateMachine.getWarningCollector()); analyzer.analyze(statement); QualifiedFunctionName functionName = QualifiedFunctionName.of(statement.getFunctionName().toString()); AlterRoutineCharacteristics alterRoutineCharacteristics = new AlterRoutineCharacteristics( statement.getCharacteristics().getNullCallClause() .map(com.facebook.presto.sql.tree.RoutineCharacteristics.NullCallClause::name) .map(NullCallClause::valueOf)); metadata.getFunctionManager().alterFunction( functionName, statement.getParameterTypes().map(types -> types.stream() .map(TypeSignature::parseTypeSignature) .collect(toImmutableList())), alterRoutineCharacteristics); return immediateFuture(null); }