auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shouldList_withNoPrefix() throws IOException { final S3FileStore s3FileStore = new S3FileStore(BUCKET_SCHEMA); s3FileStore.initialize(amazonS3Client); final List<String> objectList = s3FileStore.list(BUCKET_NAME, null); assertNotNull(objectList); }

Target:
public void shouldList_withNoPrefix() throws IOException { final S3FileStore s3FileStore = new S3FileStore(BUCKET_SCHEMA); s3FileStore.initialize(amazonS3Client); final List<FilePath> filePathList = s3FileStore.list(BUCKET_NAME, null); assertNotNull(filePathList); assertTrue(filePathList.size() > 0); }
Source:
public static StorageServerConnections copyOf(StorageServerConnections ssc) { StorageServerConnections copy = new StorageServerConnections(ssc.connection, ssc.id, ssc.iqn, ssc.password, ssc.storageType, ssc.username, ssc.port, ssc.portal, ssc.vfsType, ssc.mountOptions, ssc.nfsVersion, ssc.nfsRetrans, ssc.nfsTimeo); copy.setGlusterVolumeId(ssc.getGlusterVolumeId()); return copy; }

Target:
public static StorageServerConnections copyOf(StorageServerConnections ssc) { return new StorageServerConnections(ssc.connection, ssc.id, ssc.iqn, ssc.password, ssc.storageType, ssc.username, ssc.port, ssc.portal, ssc.vfsType, ssc.mountOptions, ssc.nfsVersion, ssc.nfsRetrans, ssc.nfsTimeo, ssc.glusterVolumeId); }
Source:
static Map<String, HostDevice> filterOrphanedDevices(Map<String, HostDevice> fetchedDevicesMap) { if (!fetchedDevicesMap.containsKey(VdsProperties.ROOT_HOST_DEVICE)) { return Collections.EMPTY_MAP; } Map<String, List<String>> childrenDeviceMap = new HashMap<>(); for (Map.Entry<String, HostDevice> entry : fetchedDevicesMap.entrySet()) { String deviceName = entry.getKey(); HostDevice device = entry.getValue(); MultiValueMapUtils.addToMap(device.getParentDeviceName(), deviceName, childrenDeviceMap); } Stack<String> toTraverse = new Stack<>(); toTraverse.push(VdsProperties.ROOT_HOST_DEVICE); Map<String, HostDevice> result = new HashMap<>(); while (!toTraverse.empty()) { String deviceName = toTraverse.pop(); result.put(deviceName, fetchedDevicesMap.get(deviceName)); if (childrenDeviceMap.containsKey(deviceName)) { childrenDeviceMap.get(deviceName).stream() .filter(child -> !VdsProperties.ROOT_HOST_DEVICE.equals(child)) .forEach(toTraverse::push); } } return result; }

Target:
static Map<String, HostDevice> filterOrphanedDevices(Map<String, HostDevice> fetchedDevicesMap) { if (!fetchedDevicesMap.containsKey(VdsProperties.ROOT_HOST_DEVICE)) { return Collections.emptyMap(); } Map<String, List<String>> childrenDeviceMap = new HashMap<>(); for (Map.Entry<String, HostDevice> entry : fetchedDevicesMap.entrySet()) { String deviceName = entry.getKey(); HostDevice device = entry.getValue(); MultiValueMapUtils.addToMap(device.getParentDeviceName(), deviceName, childrenDeviceMap); } Stack<String> toTraverse = new Stack<>(); toTraverse.push(VdsProperties.ROOT_HOST_DEVICE); Map<String, HostDevice> result = new HashMap<>(); while (!toTraverse.empty()) { String deviceName = toTraverse.pop(); result.put(deviceName, fetchedDevicesMap.get(deviceName)); if (childrenDeviceMap.containsKey(deviceName)) { childrenDeviceMap.get(deviceName).stream() .filter(child -> !VdsProperties.ROOT_HOST_DEVICE.equals(child)) .forEach(toTraverse::push); } } return result; }
Source:
public ListenableFuture<?> commitFiles(ConnectorSession session, String schemaName, String tableName, List<PartitionUpdate> partitionUpdates) { HdfsContext context = new HdfsContext(session, schemaName, tableName); List<ListenableFuture<?>> commitFutures = new ArrayList<>(); for (PartitionUpdate partitionUpdate : partitionUpdates) { Path path = partitionUpdate.getWritePath(); FileSystem fileSystem = getFileSystem(hdfsEnvironment, context, path); for (FileWriteInfo fileWriteInfo : partitionUpdate.getFileWriteInfos()) { checkState(!fileWriteInfo.getWriteFileName().equals(fileWriteInfo.getTargetFileName())); Path source = new Path(path, fileWriteInfo.getWriteFileName()); Path target = new Path(path, fileWriteInfo.getTargetFileName()); commitFutures.add(fileRenameExecutor.submit(() -> renameFile(fileSystem, source, target))); } } ListenableFuture<?> result = whenAllSucceed(commitFutures).call(() -> null, directExecutor()); ListenableFuture<?> ioExceptionHandledResult = catching( result, IOException.class, e -> { result.cancel(true); return new PrestoException(HIVE_FILESYSTEM_ERROR, "Error moving data files to final destination", e); }, directExecutor()); return catching( ioExceptionHandledResult, RuntimeException.class, e -> { result.cancel(true); return e; }, directExecutor()); }

Target:
public ListenableFuture<Void> commitFiles(ConnectorSession session, String schemaName, String tableName, List<PartitionUpdate> partitionUpdates) { HdfsContext context = new HdfsContext(session, schemaName, tableName); List<ListenableFuture<Void>> commitFutures = new ArrayList<>(); for (PartitionUpdate partitionUpdate : partitionUpdates) { Path path = partitionUpdate.getWritePath(); FileSystem fileSystem = getFileSystem(hdfsEnvironment, context, path); for (FileWriteInfo fileWriteInfo : partitionUpdate.getFileWriteInfos()) { checkState(!fileWriteInfo.getWriteFileName().equals(fileWriteInfo.getTargetFileName())); Path source = new Path(path, fileWriteInfo.getWriteFileName()); Path target = new Path(path, fileWriteInfo.getTargetFileName()); commitFutures.add(fileRenameExecutor.submit(() -> { renameFile(fileSystem, source, target); return null; })); } } ListenableFuture<Void> result = whenAllSucceed(commitFutures).call(() -> null, directExecutor()); return catching( result, RuntimeException.class, e -> { checkState(e != null, "Null exception is caught during commitFiles"); result.cancel(true); throw e; }, directExecutor()); }
Source:
public boolean setApiKey(String apiKey) throws ConstructorException { try { this.apiKey = apiKey; return true; } catch (Exception exception) { throw new ConstructorException(exception); } }

Target:
public void setApiKey(String apiKey) { this.apiKey = apiKey; }
Source:
public void testDictionaryArtifactToSerializerMappingExtraction() throws IOException { InputStream descIn = getClass().getResourceAsStream( "/opennlp/tools/util/featuregen/TestDictionarySerializerMappingExtractionxml"); Map<String, ArtifactSerializer<?>> mapping = GeneratorFactory.extractArtifactSerializerMappings(descIn); Assert.assertTrue(mapping.get("test.dictionary") instanceof DictionarySerializer); }

Target:
public void testDictionaryArtifactToSerializerMappingExtraction() throws IOException { try (InputStream descIn = getClass().getResourceAsStream( "/opennlp/tools/util/featuregen/TestDictionarySerializerMappingExtractionxml")) { Map<String, ArtifactSerializer<?>> mapping = GeneratorFactory.extractArtifactSerializerMappings(descIn); Assert.assertTrue(mapping.get("test.dictionary") instanceof DictionarySerializer); } }
Source:
private void titleMatchOnGoogleTask(Task remote) { String title = remote.getValue(Task.TITLE); TodorooCursor<Task> match = taskService.query(Query.select(Task.ID) .join(Join.inner(Metadata.TABLE, Criterion.and(Metadata.KEY.eq(GtasksMetadata.METADATA_KEY), Metadata.TASK.eq(Task.ID)))) .where(Criterion.and(Task.TITLE.eq(title), Task.REMOTE_ID.isNull()))); try { if (match.getCount() > 0) { match.moveToFirst(); Task matchedTitle = new Task(match); remote.setId(matchedTitle.getId()); } } finally { match.close(); } }

Target:
private void titleMatchOnGoogleTask(Task remote) { String title = remote.getValue(Task.TITLE); TodorooCursor<Task> match = taskService.query(Query.select(Task.ID) .join(Join.inner(Metadata.TABLE, Criterion.and(Metadata.KEY.eq(GtasksMetadata.METADATA_KEY), Metadata.TASK.eq(Task.ID)))) .where(Criterion.and(Task.TITLE.eq(title), Task.REMOTE_ID.isNull()))); try { if (match.getCount() > 0) { match.moveToFirst(); remote.setId(match.get(Task.ID)); } } finally { match.close(); } }
Source:
public boolean next() throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { try { if (advance) { advance = false; postChildren = false; popEntriesEqual(); } for (;;) { final AbstractTreeIterator tmin = min(); if (tmin.eof()) { if (depth > 0) { exitSubtree(); if (postOrderTraversal) { advance = true; postChildren = true; return true; } popEntriesEqual(); continue; } return false; } currentHead = tmin; if (isSkipCurrentEntry() || !filter.include(this)) { skipEntriesEqual(); continue; } if (recursive && FileMode.TREE.equals(tmin.mode)) { enterSubtree(); continue; } advance = true; return true; } } catch (StopWalkException stop) { for (final AbstractTreeIterator t : trees) t.stopWalk(); return false; } }

Target:
public boolean next() throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException { try { if (advance) { advance = false; postChildren = false; popEntriesEqual(); } for (;;) { final AbstractTreeIterator t = min(); if (t.eof()) { if (depth > 0) { exitSubtree(); if (postOrderTraversal) { advance = true; postChildren = true; return true; } popEntriesEqual(); continue; } return false; } currentHead = t; if (!filter.include(this)) { skipEntriesEqual(); continue; } if (recursive && FileMode.TREE.equals(t.mode)) { enterSubtree(); continue; } advance = true; return true; } } catch (StopWalkException stop) { for (final AbstractTreeIterator t : trees) t.stopWalk(); return false; } }
Source:
public Set<TopicLabel> getLabels() { return labels; }

Target:
public Set<TopicLabel> getLabels() { return Collections.unmodifiableSet(labels); }
Source:
private List<TabletInfo<T>> listSplits() throws TableNotFoundException, AccumuloSecurityException, AccumuloException { List<Text> splits = new ArrayList<>(env.getConnector().tableOperations().listSplits(env.getTable())); Collections.sort(splits); List<TabletInfo<T>> tablets = new ArrayList<>(splits.size() + 1); for (int i = 0; i < splits.size(); i++) { tablets.add(new TabletInfo<T>(i == 0 ? null : splits.get(i - 1), splits.get(i), supplier.get())); } tablets.add(new TabletInfo<T>(splits.size() == 0 ? null : splits.get(splits.size() - 1), null, supplier.get())); listSplitsTime = System.currentTimeMillis(); return tablets; }

Target:
private List<TabletInfo<T>> listSplits() throws TableNotFoundException, AccumuloSecurityException, AccumuloException { List<Text> splits = new ArrayList<>(env.getConnector().tableOperations().listSplits(env.getTable())); Collections.sort(splits); List<TabletInfo<T>> tablets = new ArrayList<>(splits.size() + 1); for (int i = 0; i < splits.size(); i++) { tablets.add(new TabletInfo<>(i == 0 ? null : splits.get(i - 1), splits.get(i), supplier.get())); } tablets.add(new TabletInfo<>(splits.size() == 0 ? null : splits.get(splits.size() - 1), null, supplier.get())); listSplitsTime = System.currentTimeMillis(); return tablets; }
Source:
public int getEnrolmentByStatus(DeviceIdentifier deviceId, Status status, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; try { conn = this.getConnection(); String sql = "SELECT e.ID ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " + "WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) dtm " + "WHERE e.DEVICE_ID = dtm.ID AND e.STATUS = ? AND e.TENANT_ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceId.getId()); stmt.setString(2, deviceId.getType()); stmt.setInt(3, tenantId); stmt.setString(4, status.toString()); stmt.setInt(5, tenantId); rs = stmt.executeQuery(); if (rs.next()) { return rs.getInt("ENROLMENT_ID"); } else { return -1; } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " + "id of device '" + deviceId + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } }

Target:
public int getEnrolmentByStatus(DeviceIdentifier deviceId, Status status, int tenantId) throws DeviceManagementDAOException { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; try { conn = this.getConnection(); String sql = "SELECT e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " + "WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) dtm " + "WHERE e.DEVICE_ID = dtm.ID AND e.STATUS = ? AND e.TENANT_ID = ?;"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceId.getId()); stmt.setString(2, deviceId.getType()); stmt.setInt(3, tenantId); stmt.setString(4, status.toString()); stmt.setInt(5, tenantId); rs = stmt.executeQuery(); if (rs.next()) { return rs.getInt("ENROLMENT_ID"); } else { return -1; } } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while retrieving the enrolment " + "id of device '" + deviceId + "'", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } }
Source:
protected List<Result> joinEvents(EventGroup eventGroup) { IotasEvent joinedEvent = joiner.join(eventGroup); List<Result> results = new ArrayList<>(); final List<IotasEvent> events = Collections.singletonList(joinedEvent); for (String stream : joinAction.getOutputStreams()) { results.add(new Result(stream, events)); } return results; }

Target:
protected List<Result> joinEvents(EventGroup eventGroup) { IotasEvent joinedEvent = joiner.join(eventGroup); List<Result> results = new ArrayList<>(); for (String stream : getOutputStreams()) { results.add(new Result(stream, Collections.singletonList(getIotasEvent(joinedEvent, stream)))); } groupedEvents.invalidate(eventGroup.getGroupId()); return results; }
Source:
public static boolean isCppType(IProject project) { try { if (project.hasNature(CCProjectNature.CC_NATURE_ID)) { return true; } else { return false; } } catch (CoreException ex) { MessageDialogSyncedRunnable.openErrorSyncedRunnable("Error", "Getting Project type error"); return false; } }

Target:
public static boolean isCppType(IProject project) { try { if (project.hasNature(CCProjectNature.CC_NATURE_ID)) { return true; } else { return false; } } catch (CoreException ex) { MessageDialogSyncedRunnable.openErrorSyncedRunnable(ProfilingMessages.errorTitle, ProfilingMessages.errorGetProjectType); return false; } }
Source:
public boolean getAwsProxyEnabled(){ return getBoolean("aws.proxy.isEnabled", false); }

Target:
public boolean getAwsProxyEnabled(){ return getBoolean("aws.proxy.isEnabled"); }
Source:
public static void writeJobIdToFile(String hadoopJobIdFileName, String hadoopJobId) { if (hadoopJobId != null && hadoopJobIdFileName != null) { try (final OutputStream out = java.nio.file.Files.newOutputStream(Paths.get(hadoopJobIdFileName))) { HadoopDruidIndexerConfig.JSON_MAPPER.writeValue( new OutputStreamWriter(out, StandardCharsets.UTF_8), hadoopJobId ); log.info("MR job id [%s] is written to the file [%s]", hadoopJobId, hadoopJobIdFileName); } catch (IOException e) { log.warn(e, "Error writing job id [%s] to the file [%s]", hadoopJobId, hadoopJobIdFileName); } } else { log.info("Either job id or file name is null for the submitted job. Skipping writing the file [%s]", hadoopJobIdFileName); } }

Target:
public static void writeJobIdToFile(String hadoopJobIdFileName, String hadoopJobId) { if (hadoopJobId != null && hadoopJobIdFileName != null) { try (final OutputStream out = Files.newOutputStream(Paths.get(hadoopJobIdFileName))) { HadoopDruidIndexerConfig.JSON_MAPPER.writeValue( new OutputStreamWriter(out, StandardCharsets.UTF_8), hadoopJobId ); log.info("MR job id [%s] is written to the file [%s]", hadoopJobId, hadoopJobIdFileName); } catch (IOException e) { log.warn(e, "Error writing job id [%s] to the file [%s]", hadoopJobId, hadoopJobIdFileName); } } else { log.info("Either job id or file name is null for the submitted job. Skipping writing the file [%s]", hadoopJobIdFileName); } }
Source:
public void testErrorOnMultipleListBinding() { ObservableList<String> dolphinList = new ObservableArrayList<>(); ObservableList<String> dolphinList2 = new ObservableArrayList<>(); javafx.collections.ObservableList<String> javaFXList = FXCollections.observableArrayList(); FXBinder.bind(javaFXList).to(dolphinList); try { FXBinder.bind(javaFXList).to(dolphinList2); fail("A JavaFX list can only be bound to one Dolphin list"); } catch (Exception e){ } }

Target:
public void testErrorOnMultipleListBinding() { ObservableList<String> dolphinList = new ObservableArrayList<>(); ObservableList<String> dolphinList2 = new ObservableArrayList<>(); javafx.collections.ObservableList<String> javaFXList = FXCollections.observableArrayList(); FXBinder.bind(javaFXList).to(dolphinList); FXBinder.bind(javaFXList).to(dolphinList2); }
Source:
private void logServerWarnings(List<String> warnings) { StringBuilder statementString = new StringBuilder(); requestLogFormatter.appendRequest( statement, executionProfile.getInt(DefaultDriverOption.REQUEST_LOGGER_MAX_QUERY_LENGTH, 500), executionProfile.getBoolean(DefaultDriverOption.REQUEST_LOGGER_VALUES, false), executionProfile.getInt(DefaultDriverOption.REQUEST_LOGGER_MAX_VALUES, 0), executionProfile.getInt(DefaultDriverOption.REQUEST_LOGGER_MAX_VALUE_LENGTH, 0), statementString); warnings.forEach( (warning) -> { LOG.warn("Query '{}' generated server side warning(s): {}", statementString, warning); }); }

Target:
private void logServerWarnings(List<String> warnings) { StringBuilder statementString = new StringBuilder(); context .getRequestLogFormatter() .appendRequest( statement, executionProfile.getInt( DefaultDriverOption.REQUEST_LOGGER_MAX_QUERY_LENGTH, RequestLogger.DEFAULT_REQUEST_LOGGER_MAX_QUERY_LENGTH), executionProfile.getBoolean( DefaultDriverOption.REQUEST_LOGGER_VALUES, RequestLogger.DEFAULT_REQUEST_LOGGER_SHOW_VALUES), executionProfile.getInt( DefaultDriverOption.REQUEST_LOGGER_MAX_VALUES, RequestLogger.DEFAULT_REQUEST_LOGGER_MAX_VALUES), executionProfile.getInt( DefaultDriverOption.REQUEST_LOGGER_MAX_VALUE_LENGTH, RequestLogger.DEFAULT_REQUEST_LOGGER_MAX_VALUE_LENGTH), statementString); warnings.forEach( (warning) -> LOG.warn("Query '{}' generated server side warning(s): {}", statementString, warning)); }
Source:
public void compute(Iterator<RayMessage> msgIterator) throws Exception { if (getSuperstep() == 1) { initVertex(); if (isStartSeed()) { msgIterator = getStartMessage(); } } scaffold(msgIterator); voteToHalt(); }

Target:
public void compute(Iterator<RayMessage> msgIterator) throws Exception { if (getSuperstep() == 1) { if (isStartSeed()) { msgIterator = getStartMessage(); } } scaffold(msgIterator); voteToHalt(); }
Source:
public void testRowValueConstructorInWhereWithEqualsExpression() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues("aTable", tenantId, getDefaultSplits(tenantId), null, ts, getUrl()); String query = "SELECT a_integer, x_integer FROM aTable WHERE ?=organization_id AND (a_integer, x_integer) = (7, 5)"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); ResultSet rs = statement.executeQuery(); int count = 0; while(rs.next()) { assertTrue(rs.getInt(1) == 7); assertTrue(rs.getInt(2) == 5); count++; } assertTrue(count == 1); } finally { conn.close(); } }

Target:
public void testRowValueConstructorInWhereWithEqualsExpression() throws Exception { long ts = nextTimestamp(); String tenantId = getOrganizationId(); initATableValues(ATABLE_NAME, tenantId, getDefaultSplits(tenantId), null, ts, getUrl()); String query = "SELECT a_integer, x_integer FROM aTable WHERE ?=organization_id AND (a_integer, x_integer) = (7, 5)"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); ResultSet rs = statement.executeQuery(); int count = 0; while(rs.next()) { assertTrue(rs.getInt(1) == 7); assertTrue(rs.getInt(2) == 5); count++; } assertTrue(count == 1); } finally { conn.close(); } }
Source:
public void processSingleReferenceSlice(final Slice slice) { System.out.println(slice.toString()); try { final int reference = slice.sequenceId; if (reference == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) { return; } if (slice.sequenceId == Slice.MULTI_REFERENCE) { throw new SAMException("Expecting a single reference slice."); } if (reference != currentReference) { advanceToReference(reference); } indexBuilder.processAlignment(slice); } catch (final Exception e) { throw new SAMException("Exception creating BAM index for slice " + slice, e); } }

Target:
public void processSingleReferenceSlice(final Slice slice) { try { final int reference = slice.sequenceId; if (reference == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) { return; } if (slice.sequenceId == Slice.MULTI_REFERENCE) { throw new SAMException("Expecting a single reference slice."); } if (reference != currentReference) { advanceToReference(reference); } indexBuilder.processSingleReferenceSlice(slice); } catch (final Exception e) { throw new SAMException("Exception creating BAM index for slice " + slice, e); } }
Source:
private static void test(Shell shell) { File libsFolder = new File("nativeLibs"); createEmptyFolder(libsFolder); boolean isMacOS = (System.getProperty("os.name").indexOf("mac") >= 0); ProcessBuilder processBuilder = new ProcessBuilder( System.getProperty("java.home") + "/bin/java", "-Dswt.library.path=" + libsFolder.getAbsolutePath(), "-classpath", System.getProperty("java.class.path"), isMacOS ? "-XstartOnFirstThread" : "", Bug547109_JvmCrashNativeLibraryLoad.class.getName(), ARG_NO_UI ); processBuilder.inheritIO(); int numErrors = 0; try { Process[] processes = new Process[15]; for (int i = 0; i < processes.length; i++) { processes[i] = processBuilder.start(); } for (int i = 0; i < processes.length; i++) { int exitCode = processes[i].waitFor(); if (EXIT_CODE_GOOD != exitCode) numErrors++; } } catch (Throwable ex) { ex.printStackTrace(); } String message = String.format("%d crashes/errors detected", numErrors); MessageBox dialog = new MessageBox(shell, SWT.ICON_INFORMATION); dialog.setMessage(message); dialog.open(); }

Target:
private static void test(Shell shell) { File libsFolder = new File("nativeLibs"); createEmptyFolder(libsFolder); boolean isMacOS = Platform.PLATFORM.equalsIgnoreCase("cocoa"); ProcessBuilder processBuilder = new ProcessBuilder( System.getProperty("java.home") + "/bin/java", "-Dswt.library.path=" + libsFolder.getAbsolutePath(), "-classpath", System.getProperty("java.class.path"), isMacOS ? "-XstartOnFirstThread" : "", Bug547109_JvmCrashNativeLibraryLoad.class.getName(), ARG_NO_UI ); processBuilder.inheritIO(); int numErrors = 0; try { Process[] processes = new Process[15]; for (int i = 0; i < processes.length; i++) { processes[i] = processBuilder.start(); } for (int i = 0; i < processes.length; i++) { int exitCode = processes[i].waitFor(); if (EXIT_CODE_GOOD != exitCode) numErrors++; } } catch (Throwable ex) { ex.printStackTrace(); } String message = String.format("%d crashes/errors detected", numErrors); MessageBox dialog = new MessageBox(shell, SWT.ICON_INFORMATION); dialog.setMessage(message); dialog.open(); }
Source:
public void run() { int attempt = 0; while (true) { if (Thread.interrupted()) { return; } attempt++; long sleep = calculateExponentialDelay(attempt - 1, TimeUnit.MINUTES.toMillis(5)); if (sleep > 0) { try { Thread.sleep(sleep); } catch (InterruptedException e) { RealmLog.debug("Incremental backoff was interrupted."); return; } } T response = execute(); if (isSuccess(response)) { onSuccess(response); break; } else { if (shouldAbortTask(response) || attempt == maxRetries + 1) { onError(response); break; } } } }

Target:
public void run() { int attempt = 0; while (!Thread.interrupted()) { attempt++; long sleep = calculateExponentialDelay(attempt - 1, TimeUnit.MINUTES.toMillis(5)); if (sleep > 0) { try { Thread.sleep(sleep); } catch (InterruptedException e) { RealmLog.debug("Incremental backoff was interrupted."); return; } } T response = execute(); if (isSuccess(response)) { onSuccess(response); break; } else { if (shouldAbortTask(response) || attempt == maxRetries + 1) { onError(response); break; } } } }
Source:
public DhcpInfo getDhcpInfo() { enforceAccessPermission(); if (mVerboseLoggingEnabled) { mLog.info("getDhcpInfo uid=%").c(Binder.getCallingUid()).flush(); } DhcpInfo dhcpInfo = mClientModeImpl.syncGetDhcpInfo(); return dhcpInfo; }

Target:
public DhcpInfo getDhcpInfo() { enforceAccessPermission(); if (mVerboseLoggingEnabled) { mLog.info("getDhcpInfo uid=%").c(Binder.getCallingUid()).flush(); } return mClientModeImpl.syncGetDhcpInfo(); }
Source:
public void handleStatement(Statement statement) throws RDFHandlerException { String subject = statement.getSubject().stringValue(); if (subject.contains("/Special:EntityData/") && !subject.contains("/wiki/Special:EntityData/")) { subject = subject.replace("/Special:EntityData/", "/wiki/Special:EntityData/"); } if (subject.contains("ontology-0.0.1")) { subject = subject.replace("ontology-0.0.1", "ontology"); } if (!statement.getSubject().stringValue().equals(subject)) { statement = new StatementImpl(new URIImpl(subject), statement.getPredicate(), statement.getObject()); } next.handleStatement(statement); }

Target:
public void handleStatement(Statement statement) throws RDFHandlerException { String subject = statement.getSubject().stringValue(); if (subject.contains("ontology-0.0.1")) { subject = subject.replace("ontology-0.0.1", "ontology"); } if (!statement.getSubject().stringValue().equals(subject)) { statement = new StatementImpl(new URIImpl(subject), statement.getPredicate(), statement.getObject()); } next.handleStatement(statement); }
Source:
public static IInputValidator getRefNameInputValidator( final Repository repo, final String refPrefix, final boolean errorOnEmptyName) { return new IInputValidator() { public String isValid(String newText) { if (newText.length() == 0) { if (errorOnEmptyName) return UIText.ValidationUtils_PleaseEnterNameMessage; else return null; } String testFor = refPrefix + newText; if (!Repository.isValidRefName(testFor)) return NLS.bind( UIText.ValidationUtils_InvalidRefNameMessage, testFor); try { if (repo.resolve(testFor) != null) return NLS.bind( UIText.ValidationUtils_RefAlreadyExistsMessage, testFor); RefDatabase refDatabase = repo.getRefDatabase(); boolean nameConflicting = refDatabase.isNameConflicting(testFor); if (nameConflicting) return UIText.ValidationUtils_RefNameConflictsWithExistingMessage; } catch (IOException e1) { Activator.logError(NLS.bind( UIText.ValidationUtils_CanNotResolveRefMessage, testFor), e1); return e1.getMessage(); } return null; } }; }

Target:
public static IInputValidator getRefNameInputValidator( final Repository repo, final String refPrefix, final boolean errorOnEmptyName) { return new IInputValidator() { public String isValid(String newText) { if (newText.length() == 0) { if (errorOnEmptyName) return UIText.ValidationUtils_PleaseEnterNameMessage; else return null; } String testFor = refPrefix + newText; if (!Repository.isValidRefName(testFor)) return NLS.bind( UIText.ValidationUtils_InvalidRefNameMessage, testFor); try { if (repo.resolve(testFor) != null) return NLS.bind( UIText.ValidationUtils_RefAlreadyExistsMessage, testFor); RefDatabase refDatabase = repo.getRefDatabase(); List<String> conflictingNames = refDatabase.getConflictingNames(testFor); if (!conflictingNames.isEmpty()) { String joined = StringUtils.join(conflictingNames, ", "); return NLS.bind( UIText.ValidationUtils_RefNameConflictsWithExistingMessage, joined); } } catch (IOException e1) { Activator.logError(NLS.bind( UIText.ValidationUtils_CanNotResolveRefMessage, testFor), e1); return e1.getMessage(); } return null; } }; }
Source:
public int computeCellInfoMinInterval() { if (mIsScreenOn && (!mIsWifiConnected || mIsCharging)) { return CELL_INFO_INTERVAL_SHORT_MS; } return CELL_INFO_INTERVAL_LONG_MS; }

Target:
public int computeCellInfoMinInterval() { if (mIsScreenOn && !mIsWifiConnected) { return CELL_INFO_INTERVAL_SHORT_MS; } else if (mIsScreenOn && mIsCharging) { return CELL_INFO_INTERVAL_SHORT_MS; } else { return CELL_INFO_INTERVAL_LONG_MS; } }
Source:
private boolean isMemberInGracePeriod(Map<String, String> membershipExpirationRules, String membershipExpiration) throws InternalErrorException { if (membershipExpirationRules.get(AbstractMembershipExpirationRulesModule.membershipGracePeriodKeyName) == null) { return true; } if (membershipExpiration == null) { return true; } String gracePeriod = membershipExpirationRules.get(AbstractMembershipExpirationRulesModule.membershipGracePeriodKeyName); Pattern p = Pattern.compile("([0-9]+)([dmy]?)"); Matcher m = p.matcher(gracePeriod); if (!m.matches()) { throw new InternalErrorException("Wrong format of gracePeriod in VO membershipExpirationRules attribute. gracePeriod: " + gracePeriod); } int amount = Integer.valueOf(m.group(1)); TemporalUnit field; String dmyString = m.group(2); if (dmyString.equals("d")) { field = ChronoUnit.DAYS; } else if (dmyString.equals("m")) { field = ChronoUnit.MONTHS; } else if (dmyString.equals("y")) { field = ChronoUnit.YEARS; } else { throw new InternalErrorException("Wrong format of gracePeriod in VO membershipExpirationRules attribute. gracePeriod: " + gracePeriod); } LocalDate beginOfGracePeriod = LocalDate.parse(membershipExpiration, DateTimeFormatter.ISO_LOCAL_DATE); beginOfGracePeriod = beginOfGracePeriod.minus(amount, field); if (beginOfGracePeriod.isBefore(LocalDate.now())) { return true; } return false; }

Target:
private boolean isMemberInGracePeriod(Map<String, String> membershipExpirationRules, String membershipExpiration) throws InternalErrorException { if (membershipExpirationRules.get(AbstractMembershipExpirationRulesModule.membershipGracePeriodKeyName) == null) { return true; } if (membershipExpiration == null) { return true; } String gracePeriod = membershipExpirationRules.get(AbstractMembershipExpirationRulesModule.membershipGracePeriodKeyName); Pattern p = Pattern.compile("([0-9]+)([dmy]?)"); Matcher m = p.matcher(gracePeriod); if (!m.matches()) { throw new InternalErrorException("Wrong format of gracePeriod in VO membershipExpirationRules attribute. gracePeriod: " + gracePeriod); } int amount = Integer.valueOf(m.group(1)); TemporalUnit gracePeriodTimeUnit; String dmyString = m.group(2); if (dmyString.equals("d")) { gracePeriodTimeUnit = ChronoUnit.DAYS; } else if (dmyString.equals("m")) { gracePeriodTimeUnit = ChronoUnit.MONTHS; } else if (dmyString.equals("y")) { gracePeriodTimeUnit = ChronoUnit.YEARS; } else { throw new InternalErrorException("Wrong format of gracePeriod in VO membershipExpirationRules attribute. gracePeriod: " + gracePeriod); } LocalDate beginOfGracePeriod = LocalDate.parse(membershipExpiration, DateTimeFormatter.ISO_LOCAL_DATE); beginOfGracePeriod = beginOfGracePeriod.minus(amount, gracePeriodTimeUnit); if (beginOfGracePeriod.isBefore(LocalDate.now())) { return true; } return false; }
Source:
public OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) { if (nextToBeThrown == null) { return abortNullExceptionType(); } OngoingStubbing<T> stubbing = thenThrow(toBeThrown); for (Class<? extends Throwable> t : nextToBeThrown) { stubbing = stubbing.thenThrow(t); } return stubbing; }

Target:
public OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) { if (nextToBeThrown == null) { return thenThrow((Class<Throwable>) null); } OngoingStubbing<T> stubbing = thenThrow(toBeThrown); for (Class<? extends Throwable> t : nextToBeThrown) { stubbing = stubbing.thenThrow(t); } return stubbing; }
Source:
public void enabling_organizations_should_remove_template_rule_and_custom_rule() { RuleDefinitionDto template = db.rules().insert(r -> r.setIsTemplate(true)); RuleDefinitionDto custom = db.rules().insert(r -> r.setTemplateId(template.getId())); UserDto user = db.users().insertUser(); db.users().insertDefaultGroup(db.getDefaultOrganization(), "sonar-users"); logInAsSystemAdministrator(user.getLogin()); assertThat(db.getDbClient().ruleDao().selectAllDefinitions(db.getSession())).extracting(RuleDefinitionDto::getStatus).containsOnly(RuleStatus.READY); call(); assertThat(db.getDbClient().ruleDao().selectAllDefinitions(db.getSession())).extracting(RuleDefinitionDto::getStatus).containsOnly(RuleStatus.REMOVED); @SuppressWarnings("unchecked") Class<ArrayList<RuleKey>> listClass = (Class<ArrayList<RuleKey>>)(Class)ArrayList.class; ArgumentCaptor<ArrayList<RuleKey>> indexedRuleKeys = ArgumentCaptor.forClass(listClass); verify(ruleIndexer).indexRuleDefinitions(indexedRuleKeys.capture()); assertThat(indexedRuleKeys.getValue()).containsExactlyInAnyOrder(template.getKey(), custom.getKey()); }

Target:
public void enabling_organizations_should_remove_template_rule_and_custom_rule() { RuleDefinitionDto normal = db.rules().insert(); RuleDefinitionDto template = db.rules().insert(r -> r.setIsTemplate(true)); RuleDefinitionDto custom = db.rules().insert(r -> r.setTemplateId(template.getId())); UserDto user = db.users().insertUser(); db.users().insertDefaultGroup(db.getDefaultOrganization(), "sonar-users"); logInAsSystemAdministrator(user.getLogin()); assertThat(db.getDbClient().ruleDao().selectAllDefinitions(db.getSession())) .extracting(RuleDefinitionDto::getKey, RuleDefinitionDto::getStatus) .containsExactlyInAnyOrder( tuple(normal.getKey(), RuleStatus.READY), tuple(template.getKey(), RuleStatus.READY), tuple(custom.getKey(), RuleStatus.READY) ); call(); assertThat(db.getDbClient().ruleDao().selectAllDefinitions(db.getSession())) .extracting(RuleDefinitionDto::getKey, RuleDefinitionDto::getStatus) .containsExactlyInAnyOrder( tuple(normal.getKey(), RuleStatus.READY), tuple(template.getKey(), RuleStatus.REMOVED), tuple(custom.getKey(), RuleStatus.REMOVED) ); @SuppressWarnings("unchecked") Class<ArrayList<RuleKey>> listClass = (Class<ArrayList<RuleKey>>)(Class)ArrayList.class; ArgumentCaptor<ArrayList<RuleKey>> indexedRuleKeys = ArgumentCaptor.forClass(listClass); verify(ruleIndexer).indexRuleDefinitions(indexedRuleKeys.capture()); assertThat(indexedRuleKeys.getValue()).containsExactlyInAnyOrder(template.getKey(), custom.getKey()); }
Source:
private void initStore() { int initialBlockBufferSize = (int) max(MINIMUM_BUFFER_SIZE, rowGroupSize / schema.getColumns() .size() / 5); pageStore = new ColumnChunkPageWriteStore(compressor, schema, initialBlockBufferSize); int initialPageBufferSize = max(MINIMUM_BUFFER_SIZE, min(pageSize + pageSize / 10, initialBlockBufferSize)); columnStore = new ColumnWriteStoreImpl(pageStore, pageSize, initialPageBufferSize, dictionaryPageSize, enableDictionary, writerVersion); MessageColumnIO columnIO = new ColumnIOFactory(validating).getColumnIO(schema); writeSupport.prepareForWrite(columnIO.getRecordWriter(columnStore)); }

Target:
private void initStore() { int initialBlockBufferSize = Ints.checkedCast(max(MINIMUM_BUFFER_SIZE, rowGroupSize / schema.getColumns().size() / 5)); pageStore = new ColumnChunkPageWriteStore(compressor, schema, initialBlockBufferSize); int initialPageBufferSize = max(MINIMUM_BUFFER_SIZE, min(pageSize + pageSize / 10, initialBlockBufferSize)); columnStore = parquetProperties.newColumnWriteStore( schema, pageStore, pageSize, initialPageBufferSize); MessageColumnIO columnIO = new ColumnIOFactory(validating).getColumnIO(schema); writeSupport.prepareForWrite(columnIO.getRecordWriter(columnStore)); }
Source:
protected void optimizeJoinGroup(AST2BOpContext ctx, StaticAnalysis sa, IBindingSet[] bSets, JoinGroupNode op) { Collection<ServiceNode> serviceNodes = LabelServiceUtils.getLabelServiceNodes(op).collect(Collectors.toList()); for (ServiceNode serviceNode: serviceNodes) { if (Boolean.TRUE.equals(serviceNode.annotations().get(LabelService.DISABLE_REORDERING_ANNOTATION))) { return; } processProjection(serviceNode); final JoinGroupNode joinGroup = (JoinGroupNode) op; joinGroup.removeChild(serviceNode); int lastJoinIndex = findLatestPossiblePositionForTheLabelServiceNode(sa, serviceNode, joinGroup); joinGroup.addArg(lastJoinIndex + 1, (BOp) serviceNode); } }

Target:
protected void optimizeJoinGroup(AST2BOpContext ctx, StaticAnalysis sa, IBindingSet[] bSets, JoinGroupNode op) { Collection<ServiceNode> serviceNodes = LabelServiceUtils.getLabelServiceNodes(op).collect(Collectors.toList()); for (ServiceNode serviceNode: serviceNodes) { if (Boolean.TRUE.equals(serviceNode.annotations().get(LabelService.DISABLE_REORDERING_ANNOTATION))) { return; } processProjection(serviceNode); op.removeChild(serviceNode); int lastJoinIndex = findLatestPossiblePositionForTheLabelServiceNode(sa, serviceNode, op); op.addArg(lastJoinIndex + 1, serviceNode); } }
Source:
public Boolean checkWDL(File content){ Pattern taskPattern = Pattern.compile("(.*)(task)(\\s)(.*)(\\{)"); Pattern wfPattern = Pattern.compile("(.*)(workflow)(\\s)(.*)(\\{)"); String line; Integer counter = 0; try{ InputStreamReader is = new InputStreamReader(new FileInputStream(content.getPath()),StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(is); ArrayList<String> lines = new ArrayList<>(); while((line = bufferedReader.readLine()) != null) { Matcher m = taskPattern.matcher(line); lines.add(line); if (m.find()) { counter++; } } bufferedReader.close(); if(counter>0){ for(String l : lines) { Matcher m = wfPattern.matcher(l); if(m.find()){ return true; } } return false; } } catch (IOException e){ e.printStackTrace(); } return false; }

Target:
public Boolean checkWDL(File content){ Pattern taskPattern = Pattern.compile("(.*)(task)(\\s)(.*)(\\{)"); Pattern wfPattern = Pattern.compile("(.*)(workflow)(\\s)(.*)(\\{)"); Integer counter = 0; Path p = Paths.get(content.getPath()); try{ List<String> fileContent = java.nio.file.Files.readAllLines(p, StandardCharsets.UTF_8); for(String line: fileContent){ Matcher m = taskPattern.matcher(line); if (m.find()) { counter++; } } if(counter>0){ for(String l : fileContent) { Matcher m = wfPattern.matcher(l); if(m.find()){ return true; } } return false; } } catch (IOException e){ throw new RuntimeException("Failed to get content of entry file.", e); } return false; }
Source:
public static FullTextIndexItem property(@NonNull String property) { if(property == null) { throw new IllegalArgumentException("property is null"); } return new FullTextIndexItem(Expression.property(property)); }

Target:
public static FullTextIndexItem property(@NonNull String property) { if (property == null) { throw new IllegalArgumentException("property is null."); } return new FullTextIndexItem(Expression.property(property)); }
Source:
public static String getSqlFromSearchString(String searchString) { if (StringUtils.isBlank(searchString)) { return null; } searchString = textToLDapSearch(searchString); if (searchString.startsWith(PLUS_SIGN)) { return getSqlForClassicSearchFormat(searchString); } else if (searchString.startsWith(OPEN_PARENS)) { Filter filter; try { filter = Filter.create(searchString); } catch (LDAPException ex) { throw new IllegalArgumentException("Invalid Search Parameter"); } return getSqlFromLdapFilter(filter); } else { throw new IllegalArgumentException("Invalid Search Parameter"); } }

Target:
public static String getSqlFromSearchString(String searchString) { if (StringUtils.isBlank(searchString)) { return null; } if (searchString.startsWith(PLUS_SIGN)) { return getSqlForClassicSearchFormat(searchString); } else if (searchString.startsWith(OPEN_PARENS)) { searchString = textToLDapSearch(searchString); Filter filter; try { filter = Filter.create(searchString); } catch (LDAPException ex) { throw new IllegalArgumentException("Invalid LDAP Search Parameter"); } return getSqlFromLdapFilter(filter); } else { throw new IllegalArgumentException("Invalid Search Parameter: Search must begin with a '+' or a '(' character"); } }
Source:
public void producesPartsWithContentLength() throws IOException { final RqMultipart.Base multipart = new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?a=4 HTTP/1.1", "Host: rtw.example.com", "Content-Type: multipart/form-data; boundary=AaB01x", "Content-Length: 100007" ), Joiner.on("\r\n").join( "--AaB01x", new StringBuilder() .append("Content-Disposition: form-data; name=\"") .append(RqMultipartTest.PART_T2).append("\""), "", "447 N Wolfe Rd, Sunnyvale, CA 94085", "--AaB01x" ) ) ); try { MatcherAssert.assertThat( multipart.part(RqMultipartTest.PART_T2) .iterator() .next(), new HmRqHeader( "content-length", "102" ) ); } finally { multipart.body().close(); multipart.part(RqMultipartTest.PART_T2).iterator().next() .body().close(); } }

Target:
public void producesPartsWithContentLength() throws IOException { final String part = "t2"; final RqMultipart.Base multipart = new RqMultipart.Base( new RqFake( Arrays.asList( "POST /h?a=4 HTTP/1.1", "Host: rtw.example.com", "Content-Type: multipart/form-data; boundary=AaB01x", "Content-Length: 100007" ), Joiner.on("\r\n").join( "--AaB01x", String.format(RqMultipartTest.CONTENT, part), "", "447 N Wolfe Rd, Sunnyvale, CA 94085", "--AaB01x" ) ) ); try { MatcherAssert.assertThat( multipart.part(part) .iterator() .next(), new HmRqHeader( "content-length", "102" ) ); } finally { multipart.body().close(); multipart.part(part).iterator().next() .body().close(); } }
Source:
private static Escaper createEscaper(char charToEscape) { final String escapedChar = "\\" + charToEscape; final Escaper result = Escapers.builder() .addEscape('\"', "\\\"") .addEscape(':', "\\:") .addEscape(charToEscape, escapedChar) .build(); return result; }

Target:
private static Escaper createEscaper(char charToEscape) { final String escapedChar = "\\" + charToEscape; final Escaper result = Escapers.builder() .addEscape('\"', "\\\"") .addEscape(charToEscape, escapedChar) .build(); return result; }
Source:
private SiteInit createSiteInit() { final ConsoleUI ui = ConsoleUI.getInstance(batchMode); final File sitePath = getSitePath(); final List<Module> m = new ArrayList<Module>(); m.add(new InitModule()); m.add(new AbstractModule() { @Override protected void configure() { bind(ConsoleUI.class).toInstance(ui); bind(File.class).annotatedWith(SitePath.class).toInstance(sitePath); List<String> plugins = Optional.fromNullable(installPlugins).or(Lists.<String> newArrayList()); bind(new TypeLiteral<List<String>>() {}).annotatedWith(InstallPlugins.class).toInstance(plugins); } }); try { return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class); } catch (CreationException ce) { final Message first = ce.getErrorMessages().iterator().next(); Throwable why = first.getCause(); if (why instanceof Die) { throw (Die) why; } final StringBuilder buf = new StringBuilder(ce.getMessage()); while (why != null) { buf.append("\n"); buf.append(why.getMessage()); why = why.getCause(); if (why != null) { buf.append("\n caused by "); } } throw die(buf.toString(), new RuntimeException("InitInjector failed", ce)); } }

Target:
private SiteInit createSiteInit() { final ConsoleUI ui = ConsoleUI.getInstance(batchMode); final File sitePath = getSitePath(); final List<Module> m = new ArrayList<Module>(); m.add(new InitModule()); m.add(new AbstractModule() { @Override protected void configure() { bind(ConsoleUI.class).toInstance(ui); bind(File.class).annotatedWith(SitePath.class).toInstance(sitePath); List<String> plugins = Objects.firstNonNull(installPlugins, Lists.<String> newArrayList()); bind(new TypeLiteral<List<String>>() {}).annotatedWith( InstallPlugins.class).toInstance(plugins); } }); try { return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class); } catch (CreationException ce) { final Message first = ce.getErrorMessages().iterator().next(); Throwable why = first.getCause(); if (why instanceof Die) { throw (Die) why; } final StringBuilder buf = new StringBuilder(ce.getMessage()); while (why != null) { buf.append("\n"); buf.append(why.getMessage()); why = why.getCause(); if (why != null) { buf.append("\n caused by "); } } throw die(buf.toString(), new RuntimeException("InitInjector failed", ce)); } }
Source:
public void getReportTemplateHome_shouldCreateADirectoryAtGPValueIfItIsAnAbsolutePath() throws Exception { File tempFolder = temporaryFolder.newFolder("/mrrt_templates"); administrationService.setGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR, tempFolder.getAbsolutePath()); File templateHome = radiologyProperties.getReportTemplateHome(); assertNotNull(templateHome); assertThat(templateHome.exists(), is(true)); assertThat(templateHome.getName(), is(tempFolder.getName())); assertThat(templateHome.isAbsolute(), is(true)); }

Target:
public void getReportTemplateHome_shouldCreateADirectoryAtGPValueIfItIsAnAbsolutePath() throws Exception { File tempFolder = temporaryFolder.newFolder("/mrrt_templates"); administrationService.setGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR, tempFolder.getAbsolutePath()); File templateHome = radiologyProperties.getReportTemplateHome(); File templateHomeFromGP = new File(administrationService.getGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR)); assertNotNull(templateHome); assertThat(templateHome.exists(), is(true)); assertThat(templateHome.getName(), is(templateHomeFromGP.getName())); assertThat(templateHome.getName(), is(tempFolder.getName())); assertThat(templateHome.isAbsolute(), is(true)); }
Source:
public void modifyCachePool(CachePoolInfo info) throws IOException { if (this.vfs == null) { super.modifyCachePool(info); return; } throw new UnsupportedOperationException( "listCacheDirectives is not supported in ViewDFS"); }

Target:
public void modifyCachePool(CachePoolInfo info) throws IOException { if (this.vfs == null) { super.modifyCachePool(info); return; } List<IOException> failedExceptions = new ArrayList<>(); boolean isDFSExistsInChilds = false; for (FileSystem fs : getChildFileSystems()) { if (!(fs instanceof DistributedFileSystem)) { continue; } isDFSExistsInChilds = true; DistributedFileSystem dfs = (DistributedFileSystem) fs; try { dfs.modifyCachePool(info); } catch (IOException ioe) { failedExceptions.add(ioe); } } if (!isDFSExistsInChilds) { throw new UnsupportedOperationException( "No DFS available in child file systems."); } if (failedExceptions.size() > 0) { throw MultipleIOException.createIOException(failedExceptions); } }
Source:
private static String formatInstant(Instant instant, ZoneId timeZone, String pattern) { if (instant == null) { return ""; } ZonedDateTime zonedDateTime = instant.atZone(timeZone); String processedPattern; if (zonedDateTime.getHour() == 12 && zonedDateTime.getMinute() == 0) { processedPattern = pattern.replace("a", "'NOON'"); } else { processedPattern = pattern; } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(processedPattern); return zonedDateTime.format(formatter); }

Target:
private static String formatInstant(Instant instant, ZoneId timeZone, String pattern) { if (instant == null) { return ""; } ZonedDateTime zonedDateTime = instant.atZone(timeZone); String processedPattern = pattern; if (zonedDateTime.getHour() == 12 && zonedDateTime.getMinute() == 0) { processedPattern = pattern.replace("a", "'NOON'"); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(processedPattern); return zonedDateTime.format(formatter); }