auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public FileSystemModelInputProvider( Configuration configuration, FileSystem fileSystem, Iterable<Path> paths, Class<T> dataModelClass) throws IOException { if (configuration == null) { throw new IllegalArgumentException("configuration must not be null"); } if (fileSystem == null) { throw new IllegalArgumentException("fileSystem must not be null"); } if (paths == null) { throw new IllegalArgumentException("paths must not be null"); } if (dataModelClass == null) { throw new IllegalArgumentException("dataModelClass must not be null"); } this.fileSystem = fileSystem; this.queue = new SynchronousQueue<>(); this.executor = Executors.newFixedThreadPool(1, r -> { Thread t = new Thread(r, "HadoopFileCollector"); t.setDaemon(true); return t; }); this.fetcher = this.executor.submit(() -> { for (Path path : paths) { WGLOG.info("I09001", fileSystem.getUri(), paths); FileStatus[] statusList = fileSystem.globStatus(path); if (statusList == null || statusList.length == 0) { WGLOG.warn("W09001", fileSystem.getUri(), paths); continue; } for (FileStatus status : statusList) { WGLOG.info("I09002", fileSystem.getUri(), status.getPath(), status.getLen()); ModelInput<T> input = TemporaryStorage.openInput( configuration, dataModelClass, status.getPath()); boolean succeed = false; try { queue.put(new Entry<>(status, input)); succeed = true; } finally { if (succeed == false) { input.close(); } } } } queue.put(Entry.eof()); return null; }); }

Target:
public FileSystemModelInputProvider( Configuration configuration, FileSystem fileSystem, Iterable<Path> paths, Class<T> dataModelClass) throws IOException { if (configuration == null) { throw new IllegalArgumentException("configuration must not be null"); } if (fileSystem == null) { throw new IllegalArgumentException("fileSystem must not be null"); } if (paths == null) { throw new IllegalArgumentException("paths must not be null"); } if (dataModelClass == null) { throw new IllegalArgumentException("dataModelClass must not be null"); } this.fileSystem = fileSystem; this.queue = new SynchronousQueue<>(); this.executor = Executors.newFixedThreadPool(1, r -> { Thread t = new Thread(r, "HadoopFileCollector"); t.setDaemon(true); return t; }); this.fetcher = this.executor.submit(() -> { for (Path path : paths) { WGLOG.info("I09001", fileSystem.getUri(), paths); FileStatus[] statusList = fileSystem.globStatus(path); if (statusList == null || statusList.length == 0) { WGLOG.warn("W09002", fileSystem.getUri(), paths); continue; } for (FileStatus status : statusList) { WGLOG.info("I09002", fileSystem.getUri(), status.getPath(), status.getLen()); ModelInput<T> input = TemporaryStorage.openInput( configuration, dataModelClass, status.getPath()); boolean succeed = false; try { queue.put(new Entry<>(status, input)); succeed = true; } finally { if (succeed == false) { input.close(); } } } } queue.put(Entry.eof()); return null; }); }
Source:
public InfluxdbHttp(String host, int port, String database, String username, String password, TimeUnit timePrecision, String version) throws Exception { if("0.9".equals(version)){ this.url = new URL("http", host, port, "/write?u=" + username + "&p=" + password); this.jsonBuilder = new JsonBuilderV9(database, toTimePrecision(timePrecision)); } else { this.url = new URL("http", host, port, "/db/" + database + "/series?u=" + URLEncoder.encode(username, UTF_8.name()) + "&p=" + password + "&time_precision=" + toTimePrecision(timePrecision) ); } }

Target:
public InfluxdbHttp(String host, int port, String database, String username, String password, TimeUnit timePrecision, String version) throws Exception { if("0.9".equals(version)){ this.url = new URL("http", host, port, "/write?u=" + username + "&p=" + password); this.jsonBuilder = new JsonBuilderV9(database, toTimePrecision(timePrecision)); } else { throw new IllegalArgumentException("Unsupported InfluxDb version."); } }
Source:
public PerspectiveCamera(WorldProvider worldProvider, RenderingConfig renderingConfig, DisplayDevice displayDevice) { super(worldProvider, renderingConfig); this.cameraSettings = renderingConfig.getCameraSettings(); displayDevice.subscribe(this); }

Target:
public PerspectiveCamera(WorldProvider worldProvider, RenderingConfig renderingConfig, DisplayDevice displayDevice) { super(worldProvider, renderingConfig); this.cameraSettings = renderingConfig.getCameraSettings(); displayDevice.subscribe(DISPLAY_RESOLUTION_CHANGE, this); }
Source:
public static double sensitivityAtConstantDepth(final int depth, final double[] qualityDistribution, final double logOddsThreshold, final int sampleSize, final double alleleFraction, final int randomSeed) { final RouletteWheel qualityRW = new RouletteWheel(trimDistribution(qualityDistribution)); final Random uniformRNG = new Random(randomSeed); int altDepth = 0; int calledVariants = 0; for (int k = 0; k < sampleSize; k++) { altDepth = binomialDraw(depth, alleleFraction, uniformRNG); int sumOfQualities = 0; for (int i = 0; i < altDepth; i++) { sumOfQualities += qualityRW.draw(); } if (isCalled(depth, altDepth, (double) sumOfQualities / (double) altDepth, alleleFraction, logOddsThreshold)) { calledVariants++; } } return (double) calledVariants / sampleSize; }

Target:
public static double sensitivityAtConstantDepth(final int depth, final double[] qualityDistribution, final double logOddsThreshold, final int sampleSize, final double alleleFraction, final int randomSeed) { final RouletteWheel qualityRW = new RouletteWheel(trimDistribution(qualityDistribution)); final Random uniformRNG = new Random(randomSeed); int calledVariants = 0; for (int k = 0; k < sampleSize; k++) { final int altDepth = binomialDraw(depth, alleleFraction, uniformRNG); final int sumOfQualities = IntStream.range(0, altDepth).map(n -> qualityRW.draw()).sum(); if (isCalled(depth, altDepth, (double) sumOfQualities, alleleFraction, logOddsThreshold)) { calledVariants++; } } return (double) calledVariants / sampleSize; }
Source:
private ImageIcon getScriptPassiveScanIcon() { if (scriptPassiveScanIcon == null) { scriptPassiveScanIcon = new ImageIcon(Exception.class.getResource( "/resource/icon/fugue/plug-connect.png")); } return scriptPassiveScanIcon; }

Target:
private ImageIcon getScriptPassiveScanIcon() { if (scriptPassiveScanIcon == null) { scriptPassiveScanIcon = new ImageIcon( ExtensionWebSocket.class.getResource( "/org/zaproxy/zap/extension/websocket/resources/icons/plug--passive.png")); } return scriptPassiveScanIcon; }
Source:
public int hashCode() { return HashUtil.combineHashCodes(super.hashCode(), executionSet.hashCode(), processData.hashCode(), labels.hashCode()); }

Target:
public int hashCode() { return HashUtil.combineHashCodes(super.hashCode(), Objects.hashCode(executionSet), Objects.hashCode(processData), Objects.hashCode(labels)); }
Source:
public static Type valueOfIgnoreCase(String name) { for (Type type : values()) { if (name.equalsIgnoreCase(type.name())) { return type; } } throw new IllegalArgumentException("No such argument type exists " + name); }

Target:
public static Type valueOfIgnoreCase(String name) { if(name != null) { return valueOf(name.toUpperCase()); } throw new IllegalArgumentException("Invalid value null"); }
Source:
public ActionResult execute() { InstructorCoursesPageData data = new InstructorCoursesPageData(account, sessionToken); List<InstructorAttributes> instructorList = logic.getInstructorsForGoogleId(data.account.googleId); for (InstructorAttributes instructor : instructorList) { List<FeedbackSessionAttributes> feedbackSessionList = logic.getRecoveryFeedbackSessionsListForInstructor(instructor); for (FeedbackSessionAttributes feedbackSession : feedbackSessionList) { gateKeeper.verifyAccessible(instructor, feedbackSession, false, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); } } try { logic.deleteAllFeedbackSessions(instructorList); String statusMessage = Const.StatusMessages.FEEDBACK_SESSION_ALL_DELETED; statusToUser.add(new StatusMessage(statusMessage, StatusMessageColor.SUCCESS)); statusToAdmin = "All sessions deleted"; } catch (Exception e) { setStatusForException(e); } return createRedirectResult(Const.ActionURIs.INSTRUCTOR_FEEDBACK_SESSIONS_PAGE); }

Target:
public ActionResult execute() { InstructorCoursesPageData data = new InstructorCoursesPageData(account, sessionToken); List<InstructorAttributes> instructorList = logic.getInstructorsForGoogleId(data.account.googleId); for (InstructorAttributes instructor : instructorList) { List<FeedbackSessionAttributes> feedbackSessionList = logic.getRecoveryFeedbackSessionsListForInstructor(instructor); for (FeedbackSessionAttributes feedbackSession : feedbackSessionList) { gateKeeper.verifyAccessible(instructor, feedbackSession, false, Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION); } } try { logic.deleteAllFeedbackSessions(instructorList); String statusMessage = Const.StatusMessages.FEEDBACK_SESSION_ALL_DELETED; statusToUser.add(new StatusMessage(statusMessage, StatusMessageColor.SUCCESS)); statusToAdmin = "All sessions in Recycle Bin deleted"; } catch (Exception e) { setStatusForException(e); } return createRedirectResult(Const.ActionURIs.INSTRUCTOR_FEEDBACK_SESSIONS_PAGE); }
Source:
public final Status create( @NotNull(message = "status can't be NULL") final Status status ) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add(STATE, status.state().name()) .add(TARGET_URL, status.targetUrl()) .add(DESCRIPTION, status.description()) .add(CONTEXT, status.context()) .build(); final JsonObject jsonObject = this.request.method(Request.POST) .body().set(json).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject(); return new RtStatus( Status.State.valueOf(jsonObject.getString(STATE)), jsonObject.getString(TARGET_URL), jsonObject.getString(DESCRIPTION), jsonObject.getString(CONTEXT) ); }

Target:
public final Status create( @NotNull(message = "status can't be NULL") final Status status ) throws IOException { final JsonStructure json = Json.createObjectBuilder() .add("state", status.state().name()) .add("target_url", status.targetUrl()) .add("description", status.description()) .add("context", status.context()) .build(); final JsonObject response = this.request.method(Request.POST) .body().set(json).back() .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_CREATED) .as(JsonResponse.class) .json().readObject(); return new RtStatus( Status.State.forValue(response.getString("state")), response.getString("target_url"), response.getString("description"), response.getString("context") ); }
Source:
private long getTableVolume(TableDesc table, Optional<EvalNode> filter) { try { if (table.getStats() != null) { return storage.getTableVolumn(table.getUri(), filter); } } catch (UnsupportedException t) { LOG.warn(table.getName() + " does not support Tablespace::getTableVolume()"); } return StorageUnit.GB; }

Target:
private long getTableVolume(TableDesc table, Optional<EvalNode> filter) { try { if (table.getStats() != null) { return storage.getTableVolumn(table.getUri(), filter); } } catch (UnsupportedException t) { LOG.warn(table.getName() + " does not support Tablespace::getTableVolume()"); } return -1; }
Source:
public void process() throws AmbariException { LOG.info("Updating existing repo versions with service repos."); try { List<ClusterEntity> clusters = clusterDao.findAll(); for (ClusterEntity cluster: clusters) { for (ClusterServiceEntity service : cluster.getClusterServiceEntities()) { RepositoryVersionEntity repositoryVersion = service.getServiceDesiredStateEntity().getDesiredRepositoryVersion(); StackId stackId = repositoryVersion.getStackId(); StackInfo stack = stackManager.getStack(stackId.getStackName(), stackId.getStackVersion()); if(stack !=null) { if (updateRepoVersion(stack, repositoryVersion)) { repositoryVersionDao.merge(repositoryVersion); } } else { LOG.error(String.format("Check if Stack %s version %s is present in file system", stackId.getStackName(), stackId.getStackVersion())); } } } } catch(Exception ex) { throw new AmbariException( "An error occured during updating current repository versions with stack repositories.", ex); } }

Target:
public void process() throws AmbariException { LOG.info("Updating existing repo versions with service repos."); try { List<ClusterEntity> clusters = clusterDao.findAll(); for (ClusterEntity cluster: clusters) { for (ClusterServiceEntity service : cluster.getClusterServiceEntities()) { RepositoryVersionEntity repositoryVersion = service.getServiceDesiredStateEntity().getDesiredRepositoryVersion(); StackId stackId = repositoryVersion.getStackId(); StackInfo stack = stackManager.getStack(stackId.getStackName(), stackId.getStackVersion()); if (stack !=null) { if (updateRepoVersion(stack, repositoryVersion)) { repositoryVersionDao.merge(repositoryVersion); } } else { throw new AmbariException(String.format("Stack %s %s was not found on the file system. In the event that it was removed, " + "please ensure that it exists before starting Ambari Server.", stackId.getStackName(), stackId.getStackVersion())); } } } } catch(Exception ex) { throw new AmbariException( "An error occured during updating current repository versions with stack repositories.", ex); } }
Source:
public String createCluster( @NotNull(message = "No cluster entered. Unable to create.") @Valid final Cluster cluster ) throws GenieException { log.debug("Called to create cluster {}", cluster); final Optional<String> clusterId = cluster.getId(); if (clusterId.isPresent() && this.clusterRepository.existsByUniqueId(clusterId.get())) { throw new GenieConflictException("A cluster with id " + clusterId.get() + " already exists"); } final ClusterEntity clusterEntity = new ClusterEntity(); clusterEntity.setUniqueId(cluster.getId().orElse(UUID.randomUUID().toString())); this.updateEntityWithDtoContents(clusterEntity, cluster); this.clusterRepository.save(clusterEntity); return clusterEntity.getUniqueId(); }

Target:
public String createCluster( @NotNull(message = "No cluster entered. Unable to create.") @Valid final Cluster cluster ) throws GenieException { log.debug("Called to create cluster {}", cluster); final ClusterEntity clusterEntity = new ClusterEntity(); clusterEntity.setUniqueId(cluster.getId().orElse(UUID.randomUUID().toString())); this.updateEntityWithDtoContents(clusterEntity, cluster); try { this.clusterRepository.save(clusterEntity); } catch (final DataIntegrityViolationException e) { throw new GenieConflictException( "A cluster with id " + clusterEntity.getUniqueId() + " already exists", e ); } return clusterEntity.getUniqueId(); }
Source:
protected DataSource retrieve( String dsName ) throws DBDatasourceServiceException { DataSource ds = null; requestedDatasourceName = dsName; try { IDatasourceMgmtService datasourceMgmtSvc = getDatasourceMgmtService(); IDatabaseConnection databaseConnection = datasourceMgmtSvc.getDatasourceByName( dsName ); if ( databaseConnection != null && !databaseConnection.getAccessType().equals( DatabaseAccessType.JNDI ) ) { ds = resolveDatabaseConnection( databaseConnection ); } else { ds = getJndiDataSource( dsName ); } if ( ds != null ) { cacheManager.putInRegionCache( IDBDatasourceService.JDBC_DATASOURCE, dsName, ds ); } } catch ( DatasourceMgmtServiceException daoe ) { log.debug( Messages.getInstance().getErrorString( "DatasourceService.DEBUG_0001_UNABLE_TO_FIND_DATASOURCE_IN_REPOSITORY", daoe.getLocalizedMessage() ), daoe ); try { return getJndiDataSource( dsName ); } catch ( DBDatasourceServiceException dse ) { throw new DBDatasourceServiceException( Messages.getInstance().getErrorString( "DatasourceService.ERROR_0003_UNABLE_TO_GET_JNDI_DATASOURCE" ), dse ); } } return ds; }

Target:
protected DataSource retrieve( String dsName ) throws DBDatasourceServiceException { DataSource ds = null; requestedDatasourceName = dsName; try { IDatasourceMgmtService datasourceMgmtSvc = getDatasourceMgmtService(); IDatabaseConnection databaseConnection = datasourceMgmtSvc.getDatasourceByName( dsName ); if ( databaseConnection != null && !databaseConnection.getAccessType().equals( DatabaseAccessType.JNDI ) ) { ds = resolveDatabaseConnection( databaseConnection ); } else { ds = getJndiDataSource( dsName ); } if ( ds == null && databaseConnection != null ) { ds = getJndiDataSource( databaseConnection.getDatabaseName() ); } if ( ds != null ) { cacheManager.putInRegionCache( IDBDatasourceService.JDBC_DATASOURCE, dsName, ds ); } } catch ( DatasourceMgmtServiceException daoe ) { log.debug( Messages.getInstance().getErrorString( "DatasourceService.DEBUG_0001_UNABLE_TO_FIND_DATASOURCE_IN_REPOSITORY", daoe.getLocalizedMessage() ), daoe ); try { return getJndiDataSource( dsName ); } catch ( DBDatasourceServiceException dse ) { throw new DBDatasourceServiceException( Messages.getInstance().getErrorString( "DatasourceService.ERROR_0003_UNABLE_TO_GET_JNDI_DATASOURCE" ), dse ); } } return ds; }
Source:
public static int computeExitCode(TestExecutionSummary summary, CommandLineOptions options) { if (options.isFailIfNoTests() && summary.getTestsFoundCount() == 0) { return FAILED; } return summary.getTotalFailureCount() == 0 ? SUCCESS : TEST_FAILED; }

Target:
public static int computeExitCode(TestExecutionSummary summary, CommandLineOptions options) { if (options.isFailIfNoTests() && summary.getTestsFoundCount() == 0) { return NO_TESTS_FOUND; } return summary.getTotalFailureCount() == 0 ? SUCCESS : TEST_FAILED; }
Source:
public Image wreckMarkerFor(Entity entity, int secondaryPos) { EntityImage entityImage = getFromCache(entity, secondaryPos); if (entityImage == null) { System.out.println("Unable to load wreckMarker image for entity: " + entity.getShortNameRaw()); return getGenericImage(entity, -1, wreckTileset); } return entityImage.getWreckFacing(entity.getFacing()); }

Target:
public Image wreckMarkerFor(Entity entity, int secondaryPos) { EntityImage entityImage = getFromCache(entity, secondaryPos); if (entityImage == null) { DefaultMmLogger.getInstance().error(getClass(), "wreckMarkerFor()", "Unable to load wreck image for entity: " + entity.getShortNameRaw()); return getGenericImage(entity, -1, wreckTileset); } return entityImage.getWreckFacing(entity.getFacing()); }
Source:
public String toString() { return "ValuesCommand{" + "values=" + cache.size() + " elements" + '}'; }

Target:
public String toString() { return "ValuesCommand{" + "cache=" + cache.getName() + '}'; }
Source:
public static boolean isVersionSupported(final Ds3Client client, final String minVersion) throws CommandException { try { final String buildInfo = client.getSystemInformationSpectraS3(new GetSystemInformationSpectraS3Request()).getSystemInformationResult().getBuildInformation().getVersion(); final String[] buildInfoArr = buildInfo.split(QUOTE); final String[] versionInfo = minVersion.split(QUOTE); if (versionInfo.length > 3) { throw new IllegalArgumentException("The version string can have 3 numbers"); } for (int i = 0; i < versionInfo.length && i < buildInfoArr.length; i++) { final int i1 = Integer.parseInt(buildInfoArr[i]); final int i2 = Integer.parseInt(versionInfo[i]); if (i1 > i2) return true; if (i1 < i2) return false; } return true; } catch (IOException e) { throw CommandExceptionFactory.getResponseExcepion("GetSystemInformation", e); } }

Target:
public static boolean isVersionSupported(final Ds3Client client, final String minVersion) throws IOException { final String buildInfo = client.getSystemInformationSpectraS3(new GetSystemInformationSpectraS3Request()).getSystemInformationResult().getBuildInformation().getVersion(); final String[] buildInfoArr = buildInfo.split(QUOTE); final String[] versionInfo = minVersion.split(QUOTE); if (versionInfo.length > 3) { throw new IllegalArgumentException("The version string can have 3 numbers"); } for (int i = 0; i < versionInfo.length && i < buildInfoArr.length; i++) { final int i1 = Integer.parseInt(buildInfoArr[i]); final int i2 = Integer.parseInt(versionInfo[i]); if (i1 > i2) return true; if (i1 < i2) return false; } return true; }
Source:
public String toString() { long columnCount = getColumnCount(); StringBuilder stringBuilder = new StringBuilder("The TableView "); stringBuilder.append("contains "); stringBuilder.append(columnCount); stringBuilder.append(" columns: "); for (int i = 0; i < columnCount; i++) { if (i != 0) { stringBuilder.append(", "); } stringBuilder.append(getColumnName(i)); } stringBuilder.append("."); stringBuilder.append(" And "); stringBuilder.append(size()); stringBuilder.append(" rows."); return stringBuilder.toString(); }

Target:
public String toString() { long columnCount = getColumnCount(); StringBuilder stringBuilder = new StringBuilder("The TableView contains "); stringBuilder.append(columnCount); stringBuilder.append(" columns: "); for (int i = 0; i < columnCount; i++) { if (i != 0) { stringBuilder.append(", "); } stringBuilder.append(getColumnName(i)); } stringBuilder.append("."); stringBuilder.append(" And "); stringBuilder.append(size()); stringBuilder.append(" rows."); return stringBuilder.toString(); }
Source:
public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); Log_OC.d(TAG, "onSaveInstanceState()"); savedInstanceState.putInt(KEY_SAVED_LIST_POSITION, getReferencePosition()); savedInstanceState.putIntegerArrayList(KEY_INDEXES, mIndexes); savedInstanceState.putIntegerArrayList(KEY_FIRST_POSITIONS, mFirstPositions); savedInstanceState.putIntegerArrayList(KEY_TOPS, mTops); savedInstanceState.putInt(KEY_HEIGHT_CELL, mHeightCell); savedInstanceState.putString(KEY_EMPTY_LIST_MESSAGE, getEmptyViewText()); SharedPreferences appPreferences = PreferenceManager .getDefaultSharedPreferences(MainApp.getAppContext()); SharedPreferences.Editor editor = appPreferences.edit(); editor.putFloat(GRID_COLUMNS, scale); editor.apply(); }

Target:
public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); Log_OC.d(TAG, "onSaveInstanceState()"); savedInstanceState.putInt(KEY_SAVED_LIST_POSITION, getReferencePosition()); savedInstanceState.putIntegerArrayList(KEY_INDEXES, mIndexes); savedInstanceState.putIntegerArrayList(KEY_FIRST_POSITIONS, mFirstPositions); savedInstanceState.putIntegerArrayList(KEY_TOPS, mTops); savedInstanceState.putInt(KEY_HEIGHT_CELL, mHeightCell); savedInstanceState.putString(KEY_EMPTY_LIST_MESSAGE, getEmptyViewText()); SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(getContext()).edit(); editor.putFloat(GRID_COLUMNS, mScale).apply(); }
Source:
private void goBack() { if (changesMadeSinceLastSave && draftIsNotEmpty()) { if (!account.hasDraftsFolder()) { showDialog(DIALOG_CONFIRM_DISCARD_ON_BACK); } else { showDialog(DIALOG_SAVE_OR_DISCARD_DRAFT_MESSAGE); } } else { if (draftId == INVALID_DRAFT_ID) { onDiscard(); } else { String inbox = account.getInboxFolderName(); LocalSearch localSearch = new LocalSearch(inbox); MessageList.actionDisplaySearch(this, localSearch, false, false); } } }

Target:
private void goBack() { if (changesMadeSinceLastSave && draftIsNotEmpty()) { showDialogDraft(); } else { onDiscardChanges(); String inbox = account.getInboxFolderName(); LocalSearch localSearch = new LocalSearch(inbox); localSearch.addAccountUuid(account.getUuid()); localSearch.addAllowedFolder(inbox); MessageList.actionDisplaySearch(this, localSearch, false, false); } }
Source:
public static @Nullable VirtualTableQueryFilter createVirtualTableQueryFilter(Map<String, Object> parameters) { Object columnRequestedObject = parameters.get("columnId"); if (!(columnRequestedObject instanceof List<?>)) { return null; } Object indexObject = parameters.get("index"); if (!(indexObject instanceof Long) && !(indexObject instanceof Integer)) { return null; } Object countObject = parameters.get("count"); if (!(countObject instanceof Integer)) { return null; } return new VirtualTableQueryFilter((List<Long>) columnRequestedObject, (long) indexObject, (int) countObject); }

Target:
public static @Nullable VirtualTableQueryFilter createVirtualTableQueryFilter(Map<String, Object> parameters) { Object columnRequestedObject = parameters.get(COLUMN_ID_KEY); if (!(columnRequestedObject instanceof List<?>)) { return null; } List<Long> columnRequested = transformToLongList((List<?>) columnRequestedObject); if(columnRequested == null) { return null; } Object indexObject = parameters.get(TABLE_INDEX); if (!(indexObject instanceof Long) && !(indexObject instanceof Integer)) { return null; } long index = indexObject instanceof Long ? (long) indexObject : ((Integer) indexObject).longValue(); Object countObject = parameters.get(TABLE_COUNT); if (!(countObject instanceof Integer)) { return null; } return new VirtualTableQueryFilter(columnRequested, index, (int) countObject); }
Source:
private void inUIThread(Runnable r) { if (Display.getCurrent() == getDisplay()) { r.run(); } else { getDisplay().asyncExec(r); } }

Target:
private void inUIThread(Runnable r) { if (Display.getCurrent() != null) { r.run(); } else { getDisplay().asyncExec(() -> { if (!isDisposed()) { r.run(); } }); } }
Source:
protected void toEnd(LogManager manager, String group, String name) { try (LogTailer<Record> tailer = manager.createTailer(group, name)) { tailer.toEnd(); } System.out.println(String.format("# Set log %s, group: %s, to the end", name, group)); }

Target:
protected void toEnd(LogManager manager, String group, String name) { LogLag lag = manager.getLag(name, group); try (LogTailer<Record> tailer = manager.createTailer(group, name)) { tailer.toEnd(); } System.out.println(String.format("# Moved log %s, group: %s, from: %s to %s", name, group, lag.lag(), lag.upper())); }
Source:
public void canDoActionMaxBlockDiskSizeCheckFails() { Guid storageId = Guid.NewGuid(); AddDiskParameters parameters = createParameters(); parameters.setDiskInfo(createDiskImage(16384)); initializeCommand(storageId, parameters); mockVm(); mockStorageDomain(storageId, StorageType.ISCSI); mockStoragePoolIsoMap(); assertFalse(command.canDoAction()); assertTrue(command.getReturnValue() .getCanDoActionMessages() .contains(VdcBllMessages.ACTION_TYPE_FAILED_DISK_MAX_SIZE_EXCEEDED.toString())); }

Target:
public void canDoActionMaxBlockDiskSizeCheckFails() { Guid storageId = Guid.NewGuid(); AddDiskParameters parameters = createParameters(); parameters.setDiskInfo(createDiskImage(MAX_BLOCK_SIZE * 2)); initializeCommand(storageId, parameters); mockVm(); mockStorageDomain(storageId, StorageType.ISCSI); mockStoragePoolIsoMap(); assertFalse(command.canDoAction()); assertTrue(command.getReturnValue() .getCanDoActionMessages() .contains(VdcBllMessages.ACTION_TYPE_FAILED_DISK_MAX_SIZE_EXCEEDED.toString())); }
Source:
public void postProcessAdminNoOptionsFailedStatus() throws Exception { LinkedList<DSpaceCommandLineParameter> parameters = new LinkedList<>(); parameters.add(new DSpaceCommandLineParameter("-z", "test")); parameters.add(new DSpaceCommandLineParameter("-q", null)); List<ParameterValueRest> list = parameters.stream() .map(dSpaceCommandLineParameter -> dSpaceRunnableParameterConverter .convert(dSpaceCommandLineParameter, Projection.DEFAULT)) .collect(Collectors.toList()); String token = getAuthToken(admin.getEmail(), password); MvcResult mvcResult = getClient(token) .perform(post("/api/system/scripts/mock-script/processes").contentType("multipart/form-data") .param("properties", new Gson().toJson(list))) .andExpect(status().isAccepted()) .andExpect(jsonPath("$", is( ProcessMatcher.matchProcess("mock-script", String.valueOf(admin.getID()), parameters, ProcessStatus.FAILED)))).andReturn(); ObjectMapper mapper = new ObjectMapper(); String content = mvcResult.getResponse().getContentAsString(); Map<String, Object> map = mapper.readValue(content, Map.class); Integer processId = Integer.valueOf(String.valueOf(map.get("processId"))); getClient(token).perform(delete("/api/system/processes/" + processId)); }

Target:
public void postProcessAdminNoOptionsFailedStatus() throws Exception { LinkedList<DSpaceCommandLineParameter> parameters = new LinkedList<>(); parameters.add(new DSpaceCommandLineParameter("-z", "test")); parameters.add(new DSpaceCommandLineParameter("-q", null)); List<ParameterValueRest> list = parameters.stream() .map(dSpaceCommandLineParameter -> dSpaceRunnableParameterConverter .convert(dSpaceCommandLineParameter, Projection.DEFAULT)) .collect(Collectors.toList()); String token = getAuthToken(admin.getEmail(), password); AtomicReference<Integer> idRef = new AtomicReference<>(); try { getClient(token) .perform(post("/api/system/scripts/mock-script/processes").contentType("multipart/form-data") .param("properties", new Gson().toJson(list))) .andExpect(status().isAccepted()) .andExpect(jsonPath("$", is( ProcessMatcher.matchProcess("mock-script", String.valueOf(admin.getID()), parameters, ProcessStatus.FAILED)))) .andDo(result -> idRef .set(read(result.getResponse().getContentAsString(), "$.processId"))); } finally { ProcessBuilder.deleteProcess(idRef.get()); } }
Source:
private HostConnectionPool<CL> getFallbackHostPool(BaseOperation<CL, ?> op, Long token) { int numRemotes = remoteDCNames.getEntireList().size(); if (numRemotes == 0) { throw new NoAvailableHostsException("Could not find any remote Racks for fallback"); } int numTries = Math.min(numRemotes, cpConfig.getMaxFailoverCount()); DynoException lastEx = null; while ((numTries > 0)) { numTries--; String remoteDC = remoteDCNames.getNextElement(); HostSelectionStrategy<CL> remoteDCSelector = remoteDCSelectors.get(remoteDC); try { HostConnectionPool<CL> fallbackHostPool = (op != null) ? remoteDCSelector.getPoolForOperation(op,hashtag) : remoteDCSelector.getPoolForToken(token); if (isConnectionPoolActive(fallbackHostPool)) { return fallbackHostPool; } } catch (NoAvailableHostsException e) { cpMonitor.incOperationFailure(null, e); lastEx = e; } } if (lastEx != null) { throw lastEx; } else { throw new NoAvailableHostsException("Local rack host offline and could not find any remote hosts for fallback connection"); } }

Target:
private HostConnectionPool<CL> getFallbackHostPool(BaseOperation<CL, ?> op, Long token) { int numRemotes = remoteDCNames.getEntireList().size(); if (numRemotes == 0) { throw new NoAvailableHostsException("Could not find any remote Racks for fallback"); } int numTries = Math.min(numRemotes, cpConfig.getMaxFailoverCount()); DynoException lastEx = null; while ((numTries > 0)) { numTries--; String remoteDC = remoteDCNames.getNextElement(); HostSelectionStrategy<CL> remoteDCSelector = remoteRackSelectors.get(remoteDC); try { HostConnectionPool<CL> fallbackHostPool = (op != null) ? remoteDCSelector.getPoolForOperation(op,cpConfig.getHashtag()) : remoteDCSelector.getPoolForToken(token); if (isConnectionPoolActive(fallbackHostPool)) { return fallbackHostPool; } } catch (NoAvailableHostsException e) { cpMonitor.incOperationFailure(null, e); lastEx = e; } } if (lastEx != null) { throw lastEx; } else { throw new NoAvailableHostsException("Local rack host offline and could not find any remote hosts for fallback connection"); } }
Source:
public void afterPropertiesSet() throws Exception { DefaultConversionService conversionService = new DefaultConversionService(); conversionService.addConverter(new SpelExpressionConverterConfiguration.SpelConverter()); this.conversionService = conversionService; }

Target:
public void afterPropertiesSet() throws Exception { if (conversionService == null) { conversionService = applicationContext.getBean(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME, ConversionService.class); } }
Source:
public void setBackground (Color color) { super.setBackground(color); background = color; for (Sash sashe : sashes) { sashe.setBackground(background); } }

Target:
public void setBackground (Color color) { super.setBackground(color); background = color; for (Sash sash : sashes) { sash.setBackground(background); } }
Source:
public void fillSession(HttpServletRequest req, User user) { Boolean sessionAllowed = false; LdapUser ldapUser; Map<String, Set<String>> records; Set<String> attributeValues; updateSession(req, sessionAllowed); if ((ldapUser = (LdapUser) req.getSession().getAttribute(LdapUserPlugin.SESSION_ATTR)) == null) { LOGGER.log(Level.FINE, "cannot get {0} attribute", LdapUserPlugin.SESSION_ATTR); return; } attributeValues = ldapUser.getAttribute(ldapAttr); if (attributeValues != null) { sessionAllowed = attributeValues.stream().anyMatch((t) -> whitelist.contains(t)); } else { try { if ((records = getLdapProvider().lookupLdapContent(user, new String[]{ldapAttr})) == null) { return; } } catch (LdapException ex) { throw new AuthorizationException(ex); } if (records.isEmpty() || (attributeValues = records.get(ldapAttr)) == null) { return; } ldapUser.setAttribute(ldapAttr, attributeValues); sessionAllowed = attributeValues.stream().anyMatch((t) -> whitelist.contains(t)); } updateSession(req, sessionAllowed); }

Target:
public void fillSession(HttpServletRequest req, User user) { Boolean sessionAllowed = false; LdapUser ldapUser; Map<String, Set<String>> records; Set<String> attributeValues; updateSession(req, sessionAllowed); if ((ldapUser = (LdapUser) req.getSession().getAttribute(LdapUserPlugin.SESSION_ATTR)) == null) { LOGGER.log(Level.WARNING, "cannot get {0} attribute", LdapUserPlugin.SESSION_ATTR); return; } attributeValues = ldapUser.getAttribute(ldapAttr); if (attributeValues != null) { sessionAllowed = attributeValues.stream().anyMatch((t) -> whitelist.contains(t)); } else { try { if ((records = getLdapProvider().lookupLdapContent(user, new String[]{ldapAttr})) == null) { LOGGER.log(Level.WARNING, "cannot lookup attributes {0} for user {1}", new Object[]{ldapAttr, user}); return; } } catch (LdapException ex) { throw new AuthorizationException(ex); } if (records.isEmpty() || (attributeValues = records.get(ldapAttr)) == null) { LOGGER.log(Level.WARNING, "empty records or attribute values {0} for user {1}", new Object[]{ldapAttr, user}); return; } ldapUser.setAttribute(ldapAttr, attributeValues); sessionAllowed = attributeValues.stream().anyMatch((t) -> whitelist.contains(t)); } updateSession(req, sessionAllowed); }
Source:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { RemoveVmPoolCommand<? extends VmPoolParametersBase> command = getCommand(cmdId); boolean anyFailed = false; for (Guid childCmdId : childCmdIds) { CommandEntity entity = CommandCoordinatorUtil.getCommandEntity(childCmdId); switch (entity.getCommandStatus()) { case FAILED: case FAILED_RESTARTED: case UNKNOWN: anyFailed = true; break; default: break; } if (entity.isExecuted() && !entity.getReturnValue().getSucceeded()) { anyFailed = true; } } if (anyFailed) { command.setCommandStatus(CommandStatus.FAILED); } else { VmPool pool = DbFacade.getInstance().getVmPoolDao().get(command.getVmPoolId()); if (pool.getRunningVmsCount() == 0) { command.setCommandStatus(CommandStatus.SUCCEEDED); } } }

Target:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { RemoveVmPoolCommand<? extends VmPoolParametersBase> command = getCommand(cmdId); boolean anyFailed = false; for (Guid childCmdId : childCmdIds) { CommandEntity entity = CommandCoordinatorUtil.getCommandEntity(childCmdId); switch (entity.getCommandStatus()) { case FAILED: case FAILED_RESTARTED: case UNKNOWN: anyFailed = true; break; default: break; } } if (anyFailed) { command.setCommandStatus(CommandStatus.FAILED); } else { VmPool pool = DbFacade.getInstance().getVmPoolDao().get(command.getVmPoolId()); if (pool == null || pool.getRunningVmsCount() == 0) { command.setCommandStatus(CommandStatus.SUCCEEDED); } } }
Source:
public void hostServiceShutsdownAgentIfDifferentHost() throws Throwable { startService(); Topology.Host host = get(hostId).toBuilder().setName("unknown").build(); List<PersistenceOp> ops = new ArrayList<>(); ops.add(new DeleteWithOwnerOp(Topology.Host.class, hostId, hostId.toString())); ops.add(new CreateWithOwnerOp(host, hostId.toString())); store.multi(JavaConverters.asScalaBufferConverter(ops).asScala()); eventuallyAssertShutdown(); }

Target:
public void hostServiceShutsdownAgentIfDifferentHost() throws Throwable { TestableHostService hostService = startService(); Topology.Host host = get(hostId).toBuilder().setName("unknown").build(); List<PersistenceOp> ops = new ArrayList<>(); ops.add(new DeleteWithOwnerOp(Topology.Host.class, hostId, hostId.toString())); ops.add(new CreateWithOwnerOp(host, hostId.toString())); store.multi(JavaConverters.asScalaBufferConverter(ops).asScala()); eventuallyAssertShutdown(hostService); }
Source:
private DetailedLink decideWhichToDelete(DetailedLink link1, DetailedLink link2) { String link1ParamType = link1.getRequest().getBody().getType(); String link2ParamType = link2.getRequest().getBody().getType(); if ( (link1.getRequest().getBody().isRequired()==null || link1.getRequest().getBody().isRequired()==false) && (link2.getRequest().getBody().isRequired()==null || link2.getRequest().getBody().isRequired()==false) ){ if (link1ParamType!=null && link2ParamType==null) { return link1; } if (link1ParamType==null && link2ParamType!=null) { return link2; } } return null; }

Target:
private DetailedLink decideWhichToDelete(DetailedLink link1, DetailedLink link2) { String link1ParamType = link1.getRequest().getBody().getType(); String link2ParamType = link2.getRequest().getBody().getType(); if ( (link1.getRequest().getBody().isRequired()==false) && (link2.getRequest().getBody().isRequired()==false) ){ if (link1ParamType!=null && link2ParamType==null) { return link2; } if (link1ParamType==null && link2ParamType!=null) { return link1; } } return null; }
Source:
private PgIndexTable.Entry pgIndex(TableInfo tableInfo) { var primaryKey = tableInfo.primaryKey(); var positions = new ArrayList<Integer>(); for (var columnIdent : primaryKey) { var position = tableInfo.getReference(columnIdent).position(); if (position != null) { positions.add(position); } } return new PgIndexTable.Entry(OidHash.relationOid(tableInfo), OidHash.primaryKeyOid(tableInfo), positions); }

Target:
private PgIndexTable.Entry pgIndex(TableInfo tableInfo) { var primaryKey = tableInfo.primaryKey(); var positions = new ArrayList<Integer>(); for (var columnIdent : primaryKey) { var pkRef = tableInfo.getReference(columnIdent); assert pkRef != null : "`getReference(..)` must not return null for columns retrieved from `primaryKey()`"; var position = pkRef.position(); positions.add(position); } return new PgIndexTable.Entry(OidHash.relationOid(tableInfo), OidHash.primaryKeyOid(tableInfo), positions); }
Source:
private URI endSessionEndpoint(OAuth2AuthenticationToken token) { String registrationId = token.getAuthorizedClientRegistrationId(); ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); Object endSessionEndpoint = clientRegistration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint"); URI result = null; if (endSessionEndpoint != null) { result = URI.create(endSessionEndpoint.toString()); } return result; }

Target:
private URI endSessionEndpoint(OAuth2AuthenticationToken token) { String registrationId = token.getAuthorizedClientRegistrationId(); ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); URI result = null; if (clientRegistration != null) { Object endSessionEndpoint = clientRegistration.getProviderDetails().getConfigurationMetadata().get("end_session_endpoint"); if (endSessionEndpoint != null) { result = URI.create(endSessionEndpoint.toString()); } } return result; }
Source:
public Set<String> getTags() { return UnmodifiableSet.decorate(tags); }

Target:
public Set<String> getTags() { return Collections.unmodifiableSet(tags); }
Source:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { String actualDbName; String actualTblName; if (context.dmd.getDumpType() == DumpType.EVENT_DROP_TABLE) { AlterTableMessage msg = deserializer.getAlterTableMessage(context.dmd.getPayload()); actualDbName = context.isDbNameEmpty() ? msg.getDB() : context.dbName; actualTblName = msg.getTable(); } else { DropTableMessage msg = deserializer.getDropTableMessage(context.dmd.getPayload()); actualDbName = context.isDbNameEmpty() ? msg.getDB() : context.dbName; actualTblName = msg.getTable(); } DropTableDesc dropTableDesc = new DropTableDesc( actualDbName + "." + actualTblName, null, true, true, context.eventOnlyReplicationSpec(), false ); Task<DDLWork2> dropTableTask = TaskFactory.get( new DDLWork2(readEntitySet, writeEntitySet, dropTableDesc), context.hiveConf ); context.log.debug( "Added drop tbl task : {}:{}", dropTableTask.getId(), dropTableDesc.getTableName() ); updatedMetadata.set(context.dmd.getEventTo().toString(), actualDbName, null, null); return Collections.singletonList(dropTableTask); }

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { String actualDbName; String actualTblName; if (context.dmd.getDumpType() == DumpType.EVENT_RENAME_DROP_TABLE) { AlterTableMessage msg = deserializer.getAlterTableMessage(context.dmd.getPayload()); actualDbName = context.isDbNameEmpty() ? msg.getDB() : context.dbName; actualTblName = msg.getTable(); } else { DropTableMessage msg = deserializer.getDropTableMessage(context.dmd.getPayload()); actualDbName = context.isDbNameEmpty() ? msg.getDB() : context.dbName; actualTblName = msg.getTable(); } DropTableDesc dropTableDesc = new DropTableDesc( actualDbName + "." + actualTblName, null, true, true, context.eventOnlyReplicationSpec(), false ); Task<DDLWork> dropTableTask = TaskFactory.get( new DDLWork(readEntitySet, writeEntitySet, dropTableDesc), context.hiveConf ); context.log.debug( "Added drop tbl task : {}:{}", dropTableTask.getId(), dropTableDesc.getTableName() ); updatedMetadata.set(context.dmd.getEventTo().toString(), actualDbName, null, null); return Collections.singletonList(dropTableTask); }
Source:
public synchronized PendingStatus uninstall() { ensureStarted(); changeStatusToFrom(UNINSTALL_IN_PROGRESS, UNINSTALL_IN_PROGRESS, NONE); this.pendingInstallationStatus = UNINSTALL_IN_PROGRESS; this.pendingEditionKey = null; this.pendingLicense = null; persistProperties(); return this.pendingInstallationStatus; }

Target:
public synchronized PendingStatus uninstall() { ensureStarted(); changeStatusToFrom(UNINSTALL_IN_PROGRESS, UNINSTALL_IN_PROGRESS, NONE); checkState(currentEditionKey != null, "There is no edition currently installed"); this.pendingInstallationStatus = UNINSTALL_IN_PROGRESS; this.pendingEditionKey = null; this.pendingLicense = null; persistProperties(); return this.pendingInstallationStatus; }
Source:
private void saveScriptAsFile(String path, Script<?> script, TaskContext taskContext) throws Throwable { if (!path.contains(".")) { ScriptEngineFactory factory = new ScriptEngineManager().getEngineByName(script.getEngineName()) .getFactory(); String extension = factory.getExtensions().get(0); path = path + "." + extension; } String code = script.fetchScript().trim(); Path p = Paths.get(path); boolean isAbsolute = p.isAbsolute(); if (isAbsolute) { try (FileWriter fw = new FileWriter(new File(path))) { fw.write(code); } catch (IOException e) { throw new TaskException("Error writing script as file: " + path, e.getCause()); } } else { String uri = taskContext.getNodeDataSpaceURIs().getScratchURI(); try (FileWriter fw = new FileWriter(new File(uri, path))) { fw.write(code); } catch (IOException e) { throw new TaskException("Error writing script as file: " + path, e.getCause()); } } }

Target:
private void saveScriptAsFile(String path, Script<?> script, TaskContext taskContext) throws Throwable { if (!path.contains(".")) { ScriptEngineFactory factory = new ScriptEngineManager().getEngineByName(script.getEngineName()) .getFactory(); String extension = factory.getExtensions().get(0); path = path + "." + extension; } String code = script.fetchScript().trim(); Path p = Paths.get(path); boolean isAbsolute = p.isAbsolute(); if (isAbsolute) { try (FileWriter fw = new FileWriter(new File(path))) { fw.write(code); } catch (IOException e) { throw new TaskException("Error writing script as file: " + path, e); } } else { String uri = taskContext.getNodeDataSpaceURIs().getScratchURI(); try (FileWriter fw = new FileWriter(new File(uri, path))) { fw.write(code); } catch (IOException e) { throw new TaskException("Error writing script as file: " + path, e); } } }
Source:
public void run() { try { logger.trace("Starting replica thread on Local node: " + dataNodeId + " Thread name: " + threadName); List<List<RemoteReplicaInfo>> replicasToReplicate = new ArrayList<List<RemoteReplicaInfo>>(replicasToReplicateGroupedByNode.size()); for (Map.Entry<DataNodeId, List<RemoteReplicaInfo>> replicasToReplicateEntry : replicasToReplicateGroupedByNode.entrySet()) { logger.info("Remote node: " + replicasToReplicateEntry.getKey() + " Thread name: " + threadName + " ReplicasToReplicate: " + replicasToReplicateEntry.getValue()); replicasToReplicate.add(replicasToReplicateEntry.getValue()); } logger.info("Begin iteration for thread " + threadName); while (running) { replicate(replicasToReplicate); lock.lock(); try { if (running && allDisabled) { pauseCondition.await(); } } catch (Exception e) { logger.error("Received interrupted exception during pause", e); } finally { lock.unlock(); } } } finally { running = false; shutdownLatch.countDown(); } }

Target:
public void run() { try { logger.trace("Starting replica thread on Local node: " + dataNodeId + " Thread name: " + threadName); List<List<RemoteReplicaInfo>> replicasToReplicate = new ArrayList<>(replicasToReplicateGroupedByNode.size()); for (Map.Entry<DataNodeId, List<RemoteReplicaInfo>> replicasToReplicateEntry : replicasToReplicateGroupedByNode.entrySet()) { logger.info("Remote node: " + replicasToReplicateEntry.getKey() + " Thread name: " + threadName + " ReplicasToReplicate: " + replicasToReplicateEntry.getValue()); replicasToReplicate.add(replicasToReplicateEntry.getValue()); } logger.info("Begin iteration for thread " + threadName); while (running) { replicate(replicasToReplicate); lock.lock(); try { if (running && allDisabled) { pauseCondition.await(); } } catch (Exception e) { logger.error("Received interrupted exception during pause", e); } finally { lock.unlock(); } } } finally { running = false; shutdownLatch.countDown(); } }