auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void checkCompatibility() throws ServerException { try { Version versionInfo = dockerConnector.getVersion(); if (!supportedVersions.contains(versionInfo.getVersion())) { throw new ServerException("Unsupported docker version " + versionInfo.getVersion()); } } catch (IOException e) { throw new ServerException("Impossible to get docker version", e); } }

Target:
void checkCompatibility() throws ServerException { try { Version versionInfo = dockerConnector.getVersion(); if (!supportedVersions.contains(versionInfo.getVersion())) { throw new ServerException("Unsupported docker version " + versionInfo.getVersion()); } } catch (IOException e) { throw new ServerException("Impossible to get docker version", e); } }
Source:
private void createRepository() { if (pool.isCreateMissingRepos()) { try { final Ref head = git.getRef(Constants.HEAD); NewProjectCreatedListener.Event event = new NewProjectCreatedListener.Event() { @Override public String getProjectName() { return projectName.get(); } @Override public String getHeadName() { return head != null ? head.getName() : null; } }; if (replicationQueue.onNewProjectCreated(event)) { repLog.warn("Missing repository created; retry replication to " + uri); pool.reschedule(this, Destination.RetryReason.REPOSITORY_MISSING); } else { repLog.warn("Missing repository could not be created when replicating " + uri + ". You can only create missing repositories locally, over SSH or when " + "using adminUrl in replication.config. See documentation for more information."); } } catch (IOException ioe) { stateLog.error("Cannot replicate to " + uri + "; failed to create missing repository", ioe, getStatesAsArray()); } } else { stateLog.error("Cannot replicate to " + uri + "; repository not found", getStatesAsArray()); } }

Target:
private void createRepository() { if (pool.isCreateMissingRepos()) { try { final Ref head = git.getRef(Constants.HEAD); if (replicationQueue.createProject(projectName, head != null ? head.getName() : null)) { repLog.warn("Missing repository created; retry replication to " + uri); pool.reschedule(this, Destination.RetryReason.REPOSITORY_MISSING); } else { repLog.warn("Missing repository could not be created when replicating " + uri + ". You can only create missing repositories locally, over SSH or when " + "using adminUrl in replication.config. See documentation for more information."); } } catch (IOException ioe) { stateLog.error("Cannot replicate to " + uri + "; failed to create missing repository", ioe, getStatesAsArray()); } } else { stateLog.error("Cannot replicate to " + uri + "; repository not found", getStatesAsArray()); } }
Source:
private void close(SelectionKey key) { Transmission transmission = getTransmission(key); if (transmission != null) { logger.debug("Closing connection from {}", transmission.getConnectionId()); this.disconnected.add(transmission.getConnectionId()); this.keyMap.remove(transmission.getConnectionId()); activeConnections.set(this.keyMap.size()); try { transmission.clearReceive(); transmission.clearSend(); transmission.close(); } catch (IOException e) { logger.error("IOException thrown during closing of transmission with connectionId :", transmission.getConnectionId(), e); } } else { key.attach(null); key.cancel(); SocketAddress address = null; try { SocketChannel socketChannel = channel(key); address = socketChannel.socket().getRemoteSocketAddress(); socketChannel.socket().close(); socketChannel.close(); } catch (IOException e) { metrics.selectorCloseSocketErrorCount.inc(); logger.error("Exception closing connection to remote host :", address, e); } } this.metrics.selectorConnectionClosed.inc(); }

Target:
private void close(SelectionKey key) { Transmission transmission = getTransmission(key); if (transmission != null) { logger.debug("Closing connection from {}", transmission.getConnectionId()); this.disconnected.add(transmission.getConnectionId()); this.keyMap.remove(transmission.getConnectionId()); activeConnections.set(this.keyMap.size()); try { transmission.close(); } catch (IOException e) { logger.error("IOException thrown during closing of transmission with connectionId :", transmission.getConnectionId(), e); } } else { key.attach(null); key.cancel(); SocketAddress address = null; try { SocketChannel socketChannel = channel(key); address = socketChannel.socket().getRemoteSocketAddress(); socketChannel.socket().close(); socketChannel.close(); } catch (IOException e) { metrics.selectorCloseSocketErrorCount.inc(); logger.error("Exception closing connection to remote host :", address, e); } } this.metrics.selectorConnectionClosed.inc(); }
Source:
private static void executeDeleteQuery(Connection conn, String query, int tenantId) throws SQLException { try (PreparedStatement ps = conn.prepareStatement(query)) { ps.setInt(1, tenantId); ps.executeUpdate(); } catch (SQLException e) { String errMsg = "Error executing query " + query + " for tenant: " + tenantId; throw new SQLException(errMsg, e); } }

Target:
private static void executeDeleteQuery(Connection conn, String query, int tenantId) throws SQLException { try (PreparedStatement ps = conn.prepareStatement(query)) { ps.setInt(1, tenantId); ps.executeUpdate(); if (log.isDebugEnabled()) { log.debug("Deletion query : " + query + "executed for tenant :" + tenantId); } } catch (SQLException e) { String errMsg = "Error executing query " + query + " for tenant: " + tenantId; throw new SQLException(errMsg, e); } }
Source:
protected Collection<TaskAttribute> getAttributes() { Map<String, TaskAttribute> allAttributes = getTaskData().getRoot().getAttributes(); List<TaskAttribute> attributes = new ArrayList<TaskAttribute>(allAttributes.size()); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED)); attributes.add(getTaskData().getRoot() .getMappedAttribute(BugzillaRestTaskSchema.getDefault().RESET_ASSIGNED_TO.getKey())); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_REPORTER)); if (!getTaskData().isNew()) { addSelfToCC(attributes); } attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_CC)); for (TaskAttribute attribute : allAttributes.values()) { TaskAttributeMetaData properties = attribute.getMetaData(); if (TaskAttribute.KIND_PEOPLE.equals(properties.getKind())) { if (!attributes.contains(attribute)) { attributes.add(attribute); } } } return attributes; }

Target:
protected Collection<TaskAttribute> getAttributes() { Map<String, TaskAttribute> allAttributes = getTaskData().getRoot().getAttributes(); List<TaskAttribute> attributes = new ArrayList<TaskAttribute>(allAttributes.size()); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED)); attributes.add(getTaskData().getRoot() .getMappedAttribute(BugzillaRestTaskSchema.getDefault().RESET_ASSIGNED_TO.getKey())); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_REPORTER)); addSelfToCC(attributes); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_CC)); for (TaskAttribute attribute : allAttributes.values()) { TaskAttributeMetaData properties = attribute.getMetaData(); if (TaskAttribute.KIND_PEOPLE.equals(properties.getKind())) { if (!attributes.contains(attribute)) { attributes.add(attribute); } } } return attributes; }
Source:
public void testRestartFailedTask() throws Exception { int numTasks = 1; Map<String, String> connectorProps = new HashMap<>(); connectorProps.put(CONNECTOR_CLASS_CONFIG, MonitorableSourceConnector.class.getName()); connectorProps.put(TASKS_MAX_CONFIG, Objects.toString(numTasks)); connectorProps.put(CONNECTOR_CLIENT_PRODUCER_OVERRIDES_PREFIX + BOOTSTRAP_SERVERS_CONFIG, "nobrokerrunningatthisaddress"); waitForCondition(() -> assertWorkersUp(NUM_WORKERS).orElse(false), WORKER_SETUP_DURATION_MS, "Initial group of workers di not start in time."); connect.configureConnector(CONNECTOR_NAME, connectorProps); waitForCondition(() -> assertConnectorTasksFailed(CONNECTOR_NAME, numTasks).orElse(false), CONNECTOR_SETUP_DURATION_MS, "Connector tasks did not fail in time"); connectorProps.remove(CONNECTOR_CLIENT_PRODUCER_OVERRIDES_PREFIX + BOOTSTRAP_SERVERS_CONFIG); connect.configureConnector(CONNECTOR_NAME, connectorProps); String taskRestartEndpoint = connect.endpointForResource( String.format("connectors/%s/tasks/0/restart", CONNECTOR_NAME)); connect.executePost(taskRestartEndpoint, "", Collections.emptyMap()); waitForCondition(() -> assertConnectorAndTasksRunning(CONNECTOR_NAME, numTasks).orElse(false), CONNECTOR_SETUP_DURATION_MS, "Connector tasks are not all in running state."); }

Target:
public void testRestartFailedTask() throws Exception { int numTasks = 1; Map<String, String> connectorProps = new HashMap<>(); connectorProps.put(CONNECTOR_CLASS_CONFIG, MonitorableSourceConnector.class.getName()); connectorProps.put(TASKS_MAX_CONFIG, Objects.toString(numTasks)); connectorProps.put(CONNECTOR_CLIENT_PRODUCER_OVERRIDES_PREFIX + BOOTSTRAP_SERVERS_CONFIG, "nobrokerrunningatthisaddress"); waitForCondition(() -> assertWorkersUp(NUM_WORKERS).orElse(false), WORKER_SETUP_DURATION_MS, "Initial group of workers did not start in time."); connect.configureConnector(CONNECTOR_NAME, connectorProps); waitForCondition(() -> assertConnectorTasksFailed(CONNECTOR_NAME, numTasks).orElse(false), CONNECTOR_SETUP_DURATION_MS, "Connector tasks did not fail in time"); connectorProps.remove(CONNECTOR_CLIENT_PRODUCER_OVERRIDES_PREFIX + BOOTSTRAP_SERVERS_CONFIG); connect.configureConnector(CONNECTOR_NAME, connectorProps); String taskRestartEndpoint = connect.endpointForResource( String.format("connectors/%s/tasks/0/restart", CONNECTOR_NAME)); connect.executePost(taskRestartEndpoint, "", Collections.emptyMap()); waitForCondition(() -> assertConnectorAndTasksRunning(CONNECTOR_NAME, numTasks).orElse(false), CONNECTOR_SETUP_DURATION_MS, "Connector tasks are not all in running state."); }
Source:
public void testStaffOnly() throws Exception { Map<String, String> depositStatus = new HashMap<>(); depositStatus.put(DepositField.staffOnly.name(), "true"); when(depositStatusFactory.get(eq(depositUUID))).thenReturn(depositStatus); PID objPid = makePid(); Bag objBag = model.createBag(objPid.getRepositoryPath()); objBag.addProperty(RDF.type, Cdr.Folder); Resource fileResc = addFileObject(objBag, FILE_CONTENT1); objBag.addProperty(Cdr.primaryObject, fileResc); objBag.addProperty(RDF.type, Cdr.FileObject); depBag.add(objBag); job.closeModel(); job.run(); model = job.getReadOnlyModel(); Resource roles = model.getResource(objPid.getRepositoryPath()); assertTrue(roles.hasProperty(none.getProperty(), AUTHENTICATED_PRINC)); assertTrue(roles.hasProperty(none.getProperty(), PUBLIC_PRINC)); assertFalse(fileResc.hasProperty(none.getProperty())); }

Target:
public void testStaffOnly() throws Exception { Map<String, String> depositStatus = new HashMap<>(); depositStatus.put(DepositField.staffOnly.name(), "true"); when(depositStatusFactory.get(eq(depositUUID))).thenReturn(depositStatus); PID objPid = makePid(); Bag objBag = model.createBag(objPid.getRepositoryPath()); objBag.addProperty(RDF.type, Cdr.Work); Resource fileResc = addFileObject(objBag); objBag.addProperty(Cdr.primaryObject, fileResc); depBag.add(objBag); job.closeModel(); job.run(); model = job.getReadOnlyModel(); Resource roles = model.getResource(objPid.getRepositoryPath()); assertTrue(roles.hasProperty(none.getProperty(), AUTHENTICATED_PRINC)); assertTrue(roles.hasProperty(none.getProperty(), PUBLIC_PRINC)); assertFalse(fileResc.hasProperty(none.getProperty())); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Long.valueOf(timeOut).hashCode(); return result; }

Target:
public int hashCode() { return 31 * super.hashCode() + Long.valueOf(timeOut).hashCode(); }
Source:
private void validateFields(final String projectName, final String projectDescription, final Command successCallback) { if (projectName == null || projectName.trim().isEmpty()) { hideLoadingBox(); notificationEvent.fire(new NotificationEvent(view.getEmptyNameMessage(), NotificationEvent.NotificationType.ERROR)); return; } validationService.call((Boolean isValid) -> { if (Boolean.TRUE.equals(isValid)) { if (successCallback != null) { successCallback.execute(); } } else { hideLoadingBox(); notificationEvent.fire(new NotificationEvent(view.getInvalidNameMessage(), NotificationEvent.NotificationType.ERROR)); } }).validateArtifactId(projectName); }

Target:
private void validateFields(final String projectName, final String projectDescription, final Command successCallback) { if (projectName == null || projectName.trim().isEmpty()) { hideLoadingBox(); notificationEvent.fire(new NotificationEvent(view.getEmptyNameMessage(), NotificationEvent.NotificationType.ERROR)); return; } validationService.call((Boolean isValid) -> { final String sanitizeProjectName = NewProjectUtils.sanitizeProjectName(projectName); if (Boolean.TRUE.equals(isValid) && !sanitizeProjectName.isEmpty()) { if (successCallback != null) { successCallback.execute(); } } else { hideLoadingBox(); notificationEvent.fire(new NotificationEvent(view.getInvalidNameMessage(), NotificationEvent.NotificationType.ERROR)); } }).isProjectNameValid(projectName); }
Source:
public static <T> T loadFirst(Class<T> spi) { ServiceLoader<T> serviceLoader = ServiceLoader.load(spi); if (serviceLoader.iterator().hasNext()) { return serviceLoader.iterator().next(); } else { throw new UnavailableImplementationException(spi); } }

Target:
public static <T> T loadFirst(Class<T> spi) { Assert.notNull(spi, "Parameter 'spi' must not be null."); ServiceLoader<T> serviceLoader = ServiceLoader.load(spi); if (serviceLoader.iterator().hasNext()) { return serviceLoader.iterator().next(); } else { throw new UnavailableImplementationException(spi); } }
Source:
protected TokenManager getLexerForSource(SourceCode sourceCode) { return new JspTokenManager(new CharSequenceReader(sourceCode.getCodeBuffer())); }

Target:
protected TokenManager getLexerForSource(SourceCode sourceCode) { return new JspTokenManager(IOUtil.skipBOM(new CharSequenceReader(sourceCode.getCodeBuffer()))); }
Source:
public ParsingHybridProperty( Parser<? extends ModelT> parser, PrettyPrinter<? super ModelT> printer, ObservableList<Token> tokens, ParsingContextFactory parsingContextFactory) { myParser = parser; myPrinter = printer; mySourceTokens = tokens; myParsingContextFactory = parsingContextFactory; initUpdate(); myValue = parse(); update(); mySourceTokens.addListener(new CollectionListener<Token>() { @Override public void onItemAdded(final CollectionItemEvent<? extends Token> event) { if (event.getNewItem() instanceof CommentToken) { executeInUpdate(new Runnable() { @Override public void run() { myPrettyTokens.add(event.getIndex(), event.getNewItem()); } }); } else { update(); } } @Override public void onItemSet(final CollectionItemEvent<? extends Token> event) { if (event.getNewItem() instanceof CommentToken) { executeInUpdate(new Runnable() { @Override public void run() { myPrettyTokens.set(event.getIndex(), event.getNewItem()); } }); if (!(event.getOldItem() instanceof CommentToken)) { update(); } } else if (event.getOldItem() instanceof CommentToken) { myPrettyTokens.set(event.getIndex(), event.getNewItem()); update(); } else { update(); } } @Override public void onItemRemoved(final CollectionItemEvent<? extends Token> event) { if (event.getOldItem() instanceof CommentToken) { executeInUpdate(new Runnable() { @Override public void run() { myPrettyTokens.remove(event.getIndex()); } }); } else { update(); } } }); }

Target:
public ParsingHybridProperty( Parser<? extends ModelT> parser, PrettyPrinter<? super ModelT> printer, ObservableList<Token> tokens, ParsingContextFactory parsingContextFactory) { myParser = parser; myPrinter = printer; mySourceTokens = tokens; myParsingContextFactory = parsingContextFactory; initUpdate(); myValue = parse(); update(); mySourceTokens.addListener(new CollectionListener<Token>() { @Override public void onItemAdded(final CollectionItemEvent<? extends Token> event) { if (event.getNewItem() instanceof CommentToken) { executeInUpdate(new Runnable() { @Override public void run() { myPrettyTokens.add(event.getIndex(), event.getNewItem()); } }); } else { update(); } } @Override public void onItemSet(final CollectionItemEvent<? extends Token> event) { if (event.getNewItem() instanceof CommentToken) { executeInUpdate(new Runnable() { @Override public void run() { myPrettyTokens.set(event.getIndex(), event.getNewItem()); } }); if (!(event.getOldItem() instanceof CommentToken)) { update(); } } else if (event.getOldItem() instanceof CommentToken) { executeInUpdate(new Runnable() { @Override public void run() { myPrettyTokens.set(event.getIndex(), event.getNewItem()); } }); update(); } else { update(); } } @Override public void onItemRemoved(final CollectionItemEvent<? extends Token> event) { if (event.getOldItem() instanceof CommentToken) { executeInUpdate(new Runnable() { @Override public void run() { myPrettyTokens.remove(event.getIndex()); } }); } else { update(); } } }); }
Source:
public boolean test(BlockVector3 vector) { Map<String, Object> existingStates = getExtent().getBlock(vector).getStates().entrySet().stream() .collect(Collectors.toMap(p -> p.getKey().getName(), Entry::getValue)); return states.entrySet().stream().allMatch(matchState -> existingStates.containsKey(matchState.getKey()) && existingStates.get(matchState.getKey()).toString().equals(matchState.getValue())); }

Target:
public boolean test(BlockVector3 vector) { BlockState block = getExtent().getBlock(vector); final Map<Property<Object>, Object> checkProps = cache .computeIfAbsent(block.getBlockType(), (b -> Blocks.resolveProperties(states, b))); if (strict && checkProps.isEmpty()) { return false; } return checkProps.entrySet().stream() .allMatch(entry -> block.getState(entry.getKey()) == entry.getValue()); }
Source:
public static boolean isDiskInterfaceSupportedByOs (DiskInterface diskInterface, int osId, Version version) { List<DiskInterface> supportedDiskInterfaces = getSupportedDiskInterfaces(osId, version); if (!supportedDiskInterfaces.contains(diskInterface)) { return false; } return true; }

Target:
public static boolean isDiskInterfaceSupportedByOs(DiskInterface diskInterface, int osId, Version version) { return getOsRepository().getDiskInterfaces(osId, version).contains(diskInterface.name()); }
Source:
private void restartRoom() { fireEvent(new ControllerEvent(this, ControllerEvent.RESTARTROOM, "Room restarted")); Model.restartRoom(); ArrayList<PowerUp> powers = Model.getPowerUps(); for(int i = 0; i < powers.size(); i++) { powers.get(i).reset(); } Model.clearPowerUps(); Model.clearShortPower(); getTimers().restartTimer(); collisionHandler.addCollidable(Model.getCurrentRoom().getCollidables()); }

Target:
private void restartRoom() { fireEvent(new ControllerEvent(this, ControllerEvent.RESTARTROOM, "Room restarted")); Model.restartRoom(); ArrayList<PowerUp> powers = Model.getPowerUps(); for(PowerUp power: powers) { power.reset(); } Model.clearPowerUps(); Model.clearShortPower(); getTimers().restartTimer(); collisionHandler.addCollidable(Model.getCurrentRoom().getCollidables()); }
Source:
public Promise<String> getValue() { final Resource[] resources = appContext.getResources(); if (resources == null || resources.length != 1) { return promises.resolve(""); } final Resource resource = resources[0]; final Optional<Project> project = resource.getRelatedProject(); if (!JavaUtil.isJavaProject(project.get())) { return promises.resolve(""); } final String projectPath = project.get().getLocation().toString(); return classpathContainer.getClasspathEntries(projectPath).then(new Function<List<ClasspathEntryDto>, String>() { @Override public String apply(List<ClasspathEntryDto> arg) throws FunctionException { classpathResolver.resolveClasspathEntries(arg); Set<String> libs = classpathResolver.getLibs(); StringBuilder classpath = new StringBuilder(""); for (String lib : libs) { classpath.append(lib).append(':'); } if (classpath.toString().isEmpty()) { classpath.append(appContext.getProjectsRoot().toString()).append(projectPath).append(':'); } return classpath.toString(); } }); }

Target:
public Promise<String> getValue() { final Resource[] resources = appContext.getResources(); if (resources == null || resources.length != 1) { return promises.resolve(""); } final Resource resource = resources[0]; final Optional<Project> project = resource.getRelatedProject(); if (!JavaUtil.isJavaProject(project.get())) { return promises.resolve(""); } final String projectPath = project.get().getLocation().toString(); return classpathContainer.getClasspathEntries(projectPath).then(new Function<List<ClasspathEntryDto>, String>() { @Override public String apply(List<ClasspathEntryDto> arg) throws FunctionException { classpathResolver.resolveClasspathEntries(arg); Set<String> libs = classpathResolver.getLibs(); StringBuilder classpath = new StringBuilder(); for (String lib : libs) { classpath.append(lib).append(':'); } if (classpath.toString().isEmpty()) { classpath.append(appContext.getProjectsRoot().toString()).append(projectPath).append(':'); } return classpath.toString(); } }); }
Source:
private Decrypt decryptor() { final String host = System.getProperty(HOST_KEY, ""); Decrypt result; if (host.isEmpty()) { result = new Decrypt(this.profile); } else { final String port = System.getProperty(PORT_KEY, ""); int portValue = DEFAULT_PORT; if (!port.isEmpty()) { try { portValue = Integer.parseInt(port); } catch (final NumberFormatException exception) { throw new IllegalStateException( Joiner.on(' ').join( "Can't parse proxy port", port ), exception ); } } result = new Decrypt(this.profile, host, portValue); } return result; }

Target:
private Decrypt decryptor() { return new Decrypt( this.profile, System.getProperty(HOST_KEY, ""), Integer.parseInt(System.getProperty(PORT_KEY, DEFAULT_PORT)) ); }
Source:
public Mono<ResponseEntity<?>> cleanupWorkflows( @RequestBody @ApiParam(value = "Parameters for the maintenance process", required = true) MaintenanceRequest request) { return handleExceptions(() -> { MaintenanceConfiguration configuration = converter.convert(request); MaintenanceResults results = maintenanceService.cleanupWorkflows(configuration); return scheduler.wrapBlocking(() -> ok(converter.convert(results))); }); }

Target:
public Mono<ResponseEntity<?>> cleanupWorkflows( @RequestBody @ApiParam(value = "Parameters for the maintenance process", required = true) MaintenanceRequest request) { return handleExceptions(() -> wrapBlocking(() -> { MaintenanceConfiguration configuration = converter.convert(request); MaintenanceResults results = maintenanceService.cleanupWorkflows(configuration); return ok(converter.convert(results)); })); }
Source:
public void maybeUpdateGCGraceSeconds() { logger.info("Checking tables in " + keyspace + " to see if gc_grace_seconds needs to be updated"); Stopwatch stopwatch = Stopwatch.createStarted(); Map<String, String> replication = session.getCluster().getMetadata().getKeyspace(keyspace).getReplication(); String replicationFactor = replication.get("replication_factor"); Completable check; if (getClusterSize() == 1 || replicationFactor.equals("1")) { check = updateAllGCGraceSeconds(0); } else { check = Completable.merge(configurationService.load("org.hawkular.metrics").map(config -> { int gcGraceSeconds = Integer.parseInt(config.get("gcGraceSeconds", Integer.toString( DEFAULT_GC_GRACE_SECONDS))); return updateAllGCGraceSeconds(gcGraceSeconds); })); } check.subscribe( () -> { stopwatch.stop(); logger.info("Finished gc_grace_seconds updates in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms"); updatesFinished.ifPresent(subject -> subject.onNext(null)); }, t -> { logger.warn("There was an error checking and updating gc_grace_seconds"); updatesFinished.ifPresent(subject -> subject.onNext(t)); } ); }

Target:
public void maybeUpdateGCGraceSeconds() { logger.info("Checking tables in " + keyspace + " to see if gc_grace_seconds needs to be updated"); Stopwatch stopwatch = Stopwatch.createStarted(); Map<String, String> replication = session.getCluster().getMetadata().getKeyspace(keyspace).getReplication(); String replicationFactor = replication.get("replication_factor"); Completable check; if (getClusterSize() == 1 || replicationFactor.equals("1")) { check = updateAllGCGraceSeconds(0); } else { check = Completable.merge(configurationService.load("org.hawkular.metrics", "gcGraceSeconds") .switchIfEmpty(Observable.just(Integer.toString(DEFAULT_GC_GRACE_SECONDS))) .map(property -> { int gcGraceSeconds = Integer.parseInt(property); return updateAllGCGraceSeconds(gcGraceSeconds); })); } check.subscribe( () -> { stopwatch.stop(); logger.info("Finished gc_grace_seconds updates in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms"); updatesFinished.ifPresent(subject -> subject.onNext(null)); }, t -> { logger.warn("There was an error checking and updating gc_grace_seconds"); updatesFinished.ifPresent(subject -> subject.onNext(t)); } ); }
Source:
void testDescribeSnapshotsWithFilterInvalid() { String region = defaultRegion; SortedSet<Snapshot> allResults = Sets.newTreeSet(client.describeSnapshotsInRegion(region)); assertNotNull(allResults); if (allResults.size() >= 1) { Snapshot snapshot = allResults.last(); Snapshot result = Iterables.getOnlyElement(client.describeSnapshotsInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("invalid-filter", snapshot.getId()).build())); } }

Target:
void testDescribeSnapshotsWithFilterInvalid() { String region = defaultRegion; SortedSet<Snapshot> allResults = Sets.newTreeSet(client.describeSnapshotsInRegion(region)); assertNotNull(allResults); if (!allResults.isEmpty()) { Snapshot snapshot = allResults.last(); Snapshot result = Iterables.getOnlyElement(client.describeSnapshotsInRegionWithFilter(region, ImmutableMultimap.<String, String>builder() .put("invalid-filter", snapshot.getId()).build())); } }
Source:
public void testClusterRestartWithPersistence() throws Exception { persistence = true; startGrids(2); grid(0).cluster().state(ClusterState.ACTIVE); startCollectStatistics(); stopAllGrids(false); startGrids(2); grid(0).cluster().state(ClusterState.ACTIVE); waitForStatisticsEnabled(true); }

Target:
public void testClusterRestartWithPersistence() throws Exception { startGrids(2); if (persistence) grid(0).cluster().state(ClusterState.ACTIVE); startCollectStatistics(); stopAllGrids(false); startGrids(2); if (persistence) grid(0).cluster().state(ClusterState.ACTIVE); waitForStatisticsEnabled(persistence); }
Source:
public Table listStepExecutions( @CliOption(mandatory = true, key = { "", "id" }, help = "the id of the job execution") long jobExecutionId) { final List<StepExecutionInfoResource> stepExecutions = jobOperations().listStepExecutions(jobExecutionId); final Table table = new Table(); table.addHeader(1, new TableHeader("Id")) .addHeader(2, new TableHeader("Step Name")) .addHeader(3, new TableHeader("Job Exec ID")) .addHeader(4, new TableHeader("Start Time (UTC)")) .addHeader(5, new TableHeader("End Time (UTC)")) .addHeader(6, new TableHeader("Status")); for (StepExecutionInfoResource stepExecutionInfoResource : stepExecutions) { final String utcStartTime = CommonUtils.getUtcTime(stepExecutionInfoResource.getStepExecution().getStartTime()); String utcEndTime = ""; if (stepExecutionInfoResource.getStepExecution().getEndTime() != null) { CommonUtils.getUtcTime(stepExecutionInfoResource.getStepExecution().getEndTime()); } final TableRow row = new TableRow(); row.addValue(1, String.valueOf(stepExecutionInfoResource.getStepExecution().getId())) .addValue(2, stepExecutionInfoResource.getStepExecution().getStepName()) .addValue(3, String.valueOf(stepExecutionInfoResource.getJobExecutionId())) .addValue(4, utcStartTime) .addValue(5, utcEndTime) .addValue(6, stepExecutionInfoResource.getStepExecution().getStatus().name()); table.getRows().add(row); } return table; }

Target:
public Table listStepExecutions( @CliOption(mandatory = true, key = { "", "id" }, help = "the id of the job execution") long jobExecutionId) { final List<StepExecutionInfoResource> stepExecutions = jobOperations().listStepExecutions(jobExecutionId); final Table table = new Table(); table.addHeader(1, new TableHeader("Id")) .addHeader(2, new TableHeader("Step Name")) .addHeader(3, new TableHeader("Job Exec ID")) .addHeader(4, new TableHeader("Start Time (UTC)")) .addHeader(5, new TableHeader("End Time (UTC)")) .addHeader(6, new TableHeader("Status")); for (StepExecutionInfoResource stepExecutionInfoResource : stepExecutions) { final String utcStartTime = CommonUtils.getUtcTime(stepExecutionInfoResource.getStepExecution().getStartTime()); final Date endTimeDate = stepExecutionInfoResource.getStepExecution().getEndTime(); final String utcEndTime = (endTimeDate == null) ? "" : CommonUtils.getUtcTime(endTimeDate); final TableRow row = new TableRow(); row.addValue(1, String.valueOf(stepExecutionInfoResource.getStepExecution().getId())) .addValue(2, stepExecutionInfoResource.getStepExecution().getStepName()) .addValue(3, String.valueOf(stepExecutionInfoResource.getJobExecutionId())) .addValue(4, utcStartTime) .addValue(5, utcEndTime) .addValue(6, stepExecutionInfoResource.getStepExecution().getStatus().name()); table.getRows().add(row); } return table; }
Source:
JavaType getReturnType(@Nullable JavaType returnType, JavaType defSite, JavaType callSite, TypeSubstitution substitution, JavaSymbol.MethodJavaSymbol method) { JavaType resultType = returnType; if (method.isConstructor()) { if (constructParametrizedTypeWithoutSubstitution(method, defSite)) { resultType = applySubstitution(defSite, substitution); } else { return defSite; } } if(defSite == symbols.objectType && "getClass".equals(method.name())) { TypeJavaSymbol classSymbol = symbols.classType.symbol; resultType = parametrizedTypeCache.getParametrizedTypeType(classSymbol, new TypeSubstitution().add(classSymbol.typeVariableTypes.get(0), callSite.erasure())); } resultType = applySiteSubstitution(resultType, defSite); if (callSite != defSite) { resultType = applySiteSubstitution(resultType, callSite); } resultType = applySubstitution(resultType, substitution); if (!isReturnTypeCompletelySubstituted(resultType, method.typeVariableTypes) || (method.isConstructor() && !isReturnTypeCompletelySubstituted(resultType, defSite.symbol.typeVariableTypes))) { resultType = symbols.deferedType(resultType); } return resultType; }

Target:
JavaType getReturnType(@Nullable JavaType returnType, JavaType defSite, JavaType callSite, TypeSubstitution substitution, JavaSymbol.MethodJavaSymbol method) { JavaType resultType = returnType; if (method.isConstructor()) { if (constructParametrizedTypeWithoutSubstitution(method, defSite)) { resultType = applySubstitution(defSite, substitution); } else { return defSite; } } if(defSite == symbols.objectType && "getClass".equals(method.name())) { TypeJavaSymbol classSymbol = symbols.classType.symbol; JavaType wildcardType = parametrizedTypeCache.getWildcardType(callSite.erasure(), WildCardType.BoundType.EXTENDS); resultType = parametrizedTypeCache.getParametrizedTypeType(classSymbol, new TypeSubstitution().add(classSymbol.typeVariableTypes.get(0), wildcardType)); } resultType = applySiteSubstitution(resultType, defSite); if (callSite != defSite) { resultType = applySiteSubstitution(resultType, callSite); } resultType = applySubstitution(resultType, substitution); if (!isReturnTypeCompletelySubstituted(resultType, method.typeVariableTypes) || (method.isConstructor() && !isReturnTypeCompletelySubstituted(resultType, defSite.symbol.typeVariableTypes))) { resultType = symbols.deferedType(resultType); } return resultType; }
Source:
private void validateFilter() { String filter = getProperty(NotificationProperties.FILTER, true); if (filter != null) FirstMatchSimpleFilter.parse(filter); }

Target:
private void validateFilter() { String filter = getProperty(NotificationProperties.FILTER, true); if (filter != null) { FirstMatchSimpleFilter.parse(filter); } }
Source:
public ObjectMapper getObjectMapper() { return objectMapper; }

Target:
public ObjectMapper getObjectMapper() { return this.objectMapper; }
Source:
public <K, V> BasicCache<K, V> getCache(String cacheName) { return remoteCacheManager.getCache(cacheName); }

Target:
public <K, V> RemoteCache<K, V> getCache(String cacheName) { return this.remoteCacheManager.getCache(cacheName); }
Source:
public MemoryAddressHash(int pointers) { this.pointerCount = nextPowerOfTwo(pointers); long bytes = ((long) pointerCount) << 3; memory = OffHeapMemory.allocate(bytes); UNSAFE.setMemory(memory, bytes, (byte) 0); }

Target:
public MemoryAddressHash(int pointers) { this.pointerCount = nextPowerOfTwo(pointers); long bytes = ((long) pointerCount) << 3; memory = MEMORY.allocate(bytes); UNSAFE.setMemory(memory, bytes, (byte) 0); }
Source:
public void testTranslateServiceWithManagementStatisticsUnspecifiedAndNoCaches() { Jsr107ServiceConfigurationParser configTranslator = new Jsr107ServiceConfigurationParser(); boolean jsr107CompliantAtomics = false; Map<String, String> templateMap = new ConcurrentHashMap<>(); Jsr107Configuration serviceCreationConfiguration = new Jsr107Configuration("tiny-template", templateMap, jsr107CompliantAtomics, ConfigurationElementState.UNSPECIFIED, ConfigurationElementState.UNSPECIFIED); Node retElement = configTranslator.unparseServiceCreationConfiguration(serviceCreationConfiguration); assertThat(retElement, is(notNullValue())); assertAttributeItemsWithManagementStatisticsUnspecifiedAndNoCaches(retElement); assertThat(retElement.getNodeName(), is("jsr107:defaults")); assertThat(retElement.getFirstChild(), is(nullValue())); }

Target:
public void testTranslateServiceWithManagementStatisticsUnspecifiedAndNoCaches() { Jsr107ServiceConfigurationParser configTranslator = new Jsr107ServiceConfigurationParser(); boolean jsr107CompliantAtomics = false; Map<String, String> templateMap = new HashMap<>(); Jsr107Configuration serviceCreationConfiguration = new Jsr107Configuration("tiny-template", templateMap, jsr107CompliantAtomics, ConfigurationElementState.UNSPECIFIED, ConfigurationElementState.UNSPECIFIED); Node retElement = configTranslator.unparseServiceCreationConfiguration(serviceCreationConfiguration); assertThat(retElement, is(notNullValue())); assertAttributeItemsWithManagementStatisticsUnspecifiedAndNoCaches(retElement); assertThat(retElement.getNodeName(), is("jsr107:defaults")); assertThat(retElement.getFirstChild(), is(nullValue())); }
Source:
private void fireNewSessionEvents() { if (!isManagingZkConnection()) { return; } final String sessionId = getHexSessionId(); for (final IZkStateListener stateListener : _stateListener) { _eventThread .send(new ZkEventThread.ZkEvent("New session event sent to " + stateListener, sessionId) { @Override public void run() throws Exception { if (_syncOnNewSession) { LOG.info("syncOnNewSession with sessionId {}", sessionId); final ZkConnection zkConnection = (ZkConnection) getConnection(); if (zkConnection == null || zkConnection.getZookeeper() == null) { throw new IllegalStateException( "ZkConnection is in invalid state! Please close this ZkClient and create new client."); } final String syncPath = new String("/"); zkConnection.getZookeeper().sync(syncPath, new AsyncCallback.VoidCallback() { @Override public void processResult(int rt, String s, Object ctx) { LOG.info("sycnOnNewSession with sessionID async return code: {}", sessionId, rt); } }, syncPath); } stateListener.handleNewSession(sessionId); } }); } }

Target:
private void fireNewSessionEvents() { if (!isManagingZkConnection()) { return; } final String sessionId = getHexSessionId(); if (SYNC_ON_SESSION) { final ZooKeeper zk = ((ZkConnection) getConnection()).getZookeeper(); _eventThread.send(new ZkEventThread.ZkEvent("Sync call before new session event of session " + sessionId, sessionId) { @Override public void run() throws Exception { if (issueSync(zk) == false) { LOG.warn("\"Failed to call sync() on new session {}", sessionId); } } }); } for (final IZkStateListener stateListener : _stateListener) { _eventThread .send(new ZkEventThread.ZkEvent("New session event sent to " + stateListener, sessionId) { @Override public void run() throws Exception { stateListener.handleNewSession(sessionId); } }); } }
Source:
private void addCapabilities(List<?> result, Schema s) { if (s == null) { return; } Map<String, Action> actions = s.getResourceActions(); if (actions == null || actions.size() == 0) { return; } boolean addCapability = false; for (Map.Entry<String, Action> entry : actions.entrySet()) { Map<String, Object> attributes = entry.getValue().getAttributes(); if (attributes == null || attributes.size() == 0) { continue; } String capability = ObjectUtils.toString(attributes.get(ObjectMetaDataManager.CAPABILITY), null); if (ObjectMetaDataManager.MODIFY_INFRA_CAPABILITY.equals(capability)) { addCapability = true; break; } } if (addCapability && infraAccess.canModifyInfrastructure((Policy) ApiContext.getContext().getPolicy())) { for (Object r : result) { ApiContext.getContext().addCapability(r, ObjectMetaDataManager.MODIFY_INFRA_CAPABILITY); } } }

Target:
private void addCapabilities(List<?> result, Schema s) { if (s == null) { return; } Map<String, Action> actions = s.getResourceActions(); if (actions == null || actions.size() == 0) { return; } if (!infraAccess.canModifyInfrastructure((Policy) ApiContext.getContext().getPolicy())) { return; } boolean addCapability = false; for (Map.Entry<String, Action> entry : actions.entrySet()) { Map<String, Object> attributes = entry.getValue().getAttributes(); if (attributes == null || attributes.size() == 0) { continue; } String capability = ObjectUtils.toString(attributes.get(ObjectMetaDataManager.CAPABILITY), null); if (ObjectMetaDataManager.MODIFY_INFRA_CAPABILITY.equals(capability)) { addCapability = true; break; } } if (addCapability) { for (Object r : result) { ApiContext.getContext().addCapability(r, ObjectMetaDataManager.MODIFY_INFRA_CAPABILITY); } } }
Source:
public boolean containsFrom(final ActivationState state) { return transitions.stream().anyMatch(tr -> Objects.equals(tr.from, state)); }

Target:
public boolean containsFrom(final ActivationState state) { return transitionMap.containsKey(state) && !transitionMap.get(state).isEmpty(); }
Source:
public Map<String, String> getOptions() { Map<String, String> convertedMap = new HashMap(); Set<QName> keys = options.keySet(); for (QName key : keys) { convertedMap.put(key.getNamespaceURI(), options.get(key)); } return convertedMap; }

Target:
public Map<String, String> getOptions() { Map<String, String> convertedMap = new HashMap<>(); Set<QName> keys = options.keySet(); for (QName key : keys) { convertedMap.put(key.getNamespaceURI(), options.get(key)); } return convertedMap; }
Source:
private RollingUpdateOp rollingUpdateDeploy(final ZooKeeperClient client, final RollingUpdateOpFactory opFactory, final DeploymentGroup deploymentGroup, final String host) { final List<ZooKeeperOperation> operations = Lists.newArrayList(); final Deployment deployment = Deployment.of(deploymentGroup.getJobId(), Goal.START, Deployment.EMTPY_DEPLOYER_USER, this.name, deploymentGroup.getName()); try { operations.addAll(getDeployOperations(client, host, deployment, Job.EMPTY_TOKEN)); } catch (JobDoesNotExistException | TokenVerificationException | HostNotFoundException | JobPortAllocationConflictException e) { return opFactory.taskError(e, host); } catch (JobAlreadyDeployedException e) { } return opFactory.nextTask(operations); }

Target:
private RollingUpdateOp rollingUpdateDeploy(final ZooKeeperClient client, final RollingUpdateOpFactory opFactory, final DeploymentGroup deploymentGroup, final String host) { final Deployment deployment = Deployment.of(deploymentGroup.getJobId(), Goal.START, Deployment.EMTPY_DEPLOYER_USER, this.name, deploymentGroup.getName()); try { return opFactory.nextTask(getDeployOperations(client, host, deployment, Job.EMPTY_TOKEN)); } catch (JobDoesNotExistException e) { return opFactory.taskError(e, host, RollingUpdateError.JOB_NOT_FOUND); } catch (TokenVerificationException e) { return opFactory.taskError(e, host, RollingUpdateError.TOKEN_VERIFICATION_ERROR); } catch (HostNotFoundException e) { return opFactory.taskError(e, host, RollingUpdateError.HOST_NOT_FOUND); } catch (JobPortAllocationConflictException e) { return opFactory.taskError(e, host, RollingUpdateError.PORT_CONFLICT); } catch (JobAlreadyDeployedException e) { return opFactory.nextTask(); } }
Source:
public PayaraNotification build() { return notification; }

Target:
public PayaraNotification build() { return new PayaraNotification(eventType, serverName, hostName, domainName, instanceName, subject, message, data, notifierWhitelist, notifierBlacklist); }
Source:
private void checkAndNotify( final AsyncFileEntry parent, final List<AsyncFileEntry> previous, @Nullable final File[] files, final AsyncFileAlterationListener listenerCopy) { if (files == null) { return; } int c = 0; for (final AsyncFileEntry entry : previous) { while (c < files.length && failedAndNotUpdated(files[c])) { c++; } if (c < files.length && !failedAndNotUpdated(files[c])) { while (c < files.length && entry.compareToFile(files[c]) > 0) { doCreate(new AsyncFileEntry(parent, files[c]), listenerCopy); c++; } } if (c < files.length && entry.compareToFile(files[c]) == 0) { doMatch(entry, listenerCopy); checkAndNotify(entry, entry.getChildren(), listFiles(files[c]), listenerCopy); c++; } else { if (!entry.checkNetwork()) { return; } checkAndNotify(entry, entry.getChildren(), FileUtils.EMPTY_FILE_ARRAY, listenerCopy); doDelete(entry, listenerCopy); } } for (; c < files.length; c++) { if (!failedAndNotUpdated(files[c])) { doCreate(new AsyncFileEntry(parent, files[c]), listenerCopy); } } }

Target:
private void checkAndNotify( final AsyncFileEntry parent, final List<AsyncFileEntry> previous, @Nullable final File[] files, final AsyncFileAlterationListener listenerCopy) { if (files == null) { return; } int c = 0; for (final AsyncFileEntry entry : previous) { while (c < files.length && entry.compareToFile(files[c]) > 0) { doCreate(new AsyncFileEntry(parent, files[c]), listenerCopy); c++; } if (c < files.length && entry.compareToFile(files[c]) == 0) { doMatch(entry, listenerCopy); checkAndNotify(entry, entry.getChildren(), listFiles(files[c]), listenerCopy); c++; } else { if (!entry.checkNetwork()) { return; } checkAndNotify(entry, entry.getChildren(), FileUtils.EMPTY_FILE_ARRAY, listenerCopy); doDelete(entry, listenerCopy); } } for (; c < files.length; c++) { doCreate(new AsyncFileEntry(parent, files[c]), listenerCopy); } }
Source:
public void closeIdleConnectionsWhenServerIsStoppedWhileThereIsAnInflightRequest() throws IOException, MuleException, InterruptedException { Thread stopper = new MuleContextStopper(); try (Socket idlePersistentConnection = generateIdlePersistentConnection()) { try (Socket slowRequestConnection = new Socket("localhost", dynamicPort.getNumber())) { sendRequest(slowRequestConnection, "/slow"); sleep(100); stopper.start(); new PollingProber(300, 50).check(new ConnectionClosedProbe(idlePersistentConnection)); } } finally { stopper.join(); } }

Target:
public void closeIdleConnectionsWhenServerIsStoppedWhileThereIsAnInflightRequest() throws IOException, MuleException, InterruptedException { Thread stopper = new MuleContextStopper(); try (Socket idlePersistentConnection = generateIdlePersistentConnection()) { try (Socket slowRequestConnection = new Socket("localhost", dynamicPort.getNumber())) { sendRequest(slowRequestConnection, SLOW_PROCESSING_ENDPOINT); sleep(100); stopper.start(); new PollingProber(POLL_TIMEOUT_MILLIS, POLL_DELAY_MILLIS).check(new ConnectionClosedProbe(idlePersistentConnection)); } } finally { stopper.join(); } }
Source:
public BithumbResponse( @JsonProperty("status") String status, @JsonProperty("message") String message, @JsonProperty("data") D data) { this.status = status; this.message = message; this.data = data; }

Target:
public BithumbResponse( @JsonProperty("status") String status, @JsonProperty("message") String message, @JsonProperty("data") D data) { if (!StringUtils.equals(status, "0000")) { throw new ExceptionalReturnContentException(message); } this.status = status; this.message = message; this.data = data; }
Source:
public void verifyTableRemoved() { waitForElementNotPresent(articleTableBy); PageObjectLogging.log(commentAuthorLink, commentAuthorLink, true); }

Target:
public void verifyTableRemoved() { waitForElementNotPresent(articleTableBy); PageObjectLogging.log("verifyTableRemoved", "table was removedcd", true); }
Source:
void setWappalyzer(boolean enabled) { if (this.enabled == enabled) { return; } this.enabled = enabled; wappalyzerParam.setEnabled(enabled); getPassiveScanner().setEnabled(enabled); try { wappalyzerParam.getConfig().save(); } catch (ConfigurationException e) { logger.error(e.getMessage(), e); } getTechPanel().getEnableToggleButton().setSelected(enabled); }

Target:
void setWappalyzer(boolean enabled) { if (this.enabled == enabled) { return; } this.enabled = enabled; wappalyzerParam.setEnabled(enabled); getPassiveScanner().setEnabled(enabled); if (View.isInitialised()) { getTechPanel().getEnableToggleButton().setSelected(enabled); } }
Source:
protected byte[] toBytes(BulkRequest request) { BytesStreamOutput out = new BytesStreamOutput(); try { request.writeTo(out); ByteArrayOutputStream out2 = new ByteArrayOutputStream(); out.bytes().writeTo(out2); return out2.toByteArray(); } catch (IOException e) { throw new NuxeoException("Cannot write elasticsearch bulk request " + request, e); } }

Target:
protected byte[] toBytes(BulkRequest request) { BytesStreamOutput out = new BytesStreamOutput(); try { request.writeTo(out); return BytesReference.toBytes(out.bytes()); } catch (IOException e) { throw new NuxeoException("Cannot write elasticsearch bulk request " + request, e); } }
Source:
private void handleConstructor(NewClassTree tree) { if (PASSWORD_AUTHENTICATION_CONSTRUCTOR.matches(tree)) { ExpressionTree secondArg = tree.arguments().get(1); if (secondArg.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) secondArg; if (isCallOnStringLiteral(mit.methodSelect()) && STRING_TO_CHAR_ARRAY.matches(mit)) { reportIssue(secondArg); } } } }

Target:
private void handleConstructor(NewClassTree tree) { if (!PASSWORD_AUTHENTICATION_CONSTRUCTOR.matches(tree)) { return; } ExpressionTree secondArg = tree.arguments().get(1); if (secondArg.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) secondArg; if (isCallOnStringLiteral(mit.methodSelect()) && STRING_TO_CHAR_ARRAY.matches(mit)) { reportIssue(secondArg); } } }