auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void seekOffsetByStartTimeStamp(TopicPartition tp) { long startTimeStampOffset; try { startTimeStampOffset = consumer.offsetsForTimes(Collections.singletonMap(tp, startTimeStamp)).get(tp).offset(); } catch (IllegalArgumentException e) { LOG.error("Illegal timestamp provided for tp ", startTimeStamp, tp.toString()); throw new ReportedFailedException(); } catch (UnsupportedVersionException e) { LOG.error("Kafka Server do not support offsetsForTimes(), probably < 0.10.1", e); throw new ReportedFailedException(); } LOG.debug("First poll for topic partition [{}], seeking to partition from startTimeStamp [{}]", tp, startTimeStamp); consumer.seek(tp, startTimeStampOffset); }

Target:
private void seekOffsetByStartTimeStamp(TopicPartition tp) { Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes = consumer.offsetsForTimes(Collections.singletonMap(tp, startTimeStamp)); OffsetAndTimestamp startOffsetAndTimeStamp = offsetsForTimes.get(tp); long startTimeStampOffset = startOffsetAndTimeStamp.offset(); LOG.debug("First poll for topic partition [{}], seeking to partition from startTimeStamp [{}]", tp, startTimeStamp); consumer.seek(tp, startTimeStampOffset); }
Source:
public int hashCode() { int result = 0; for (final Field f : getClass().getFields()) { try { Object value = f.get(this); value = new FormatUtil().format(value); final int fieldHash = value != null ? value.hashCode() : 0; result = 31 * result + fieldHash; } catch (IllegalAccessException e) { throw new SAMException("Could not read field " + f.getName() + " from a " + getClass().getSimpleName()); } } return result; }

Target:
public int hashCode() { int result = 0; FormatUtil formatter = new FormatUtil(); for (final Field f : getClass().getFields()) { try { Object value = f.get(this); value = formatter.format(value); final int fieldHash = value != null ? value.hashCode() : 0; result = 31 * result + fieldHash; } catch (IllegalAccessException e) { throw new SAMException("Could not read field " + f.getName() + " from a " + getClass().getSimpleName()); } } return result; }
Source:
private Optional<Image> findImageForAppVersion(String region, String platform, String imageId, String imageOs, ImageCatalog catalog) { List<FreeIpaVersions> versions = filterFreeIpaVersionsByAppVersion(catalog.getVersions().getFreeIpaVersions()); List<Image> compatibleImages = findImage(imageId, imageOs, catalog.getImages().getFreeipaImages(), region, platform); LOGGER.debug("[{}] compatible images found, by the following parameters: imageId: {}, imageOs: {}, region: {}, platform: {}", compatibleImages.size(), imageId, imageOs, region, platform); LOGGER.debug("Attempt to find a default image to use."); return filterImages(versions, compatibleImages, FreeIpaVersions::getDefaults).or( () -> { LOGGER.debug("Default image not found. Attempt to find an image, compatible with the application version."); return filterImages(versions, compatibleImages, FreeIpaVersions::getImageIds); } ).or( () -> { LOGGER.debug("Not found any image compatible with the application version. Falling back to the most recent image."); return compatibleImages.stream().max(Comparator.comparing(Image::getDate)); } ); }

Target:
private Optional<Image> findImageForAppVersion(String region, String platform, String imageId, String imageOs, ImageCatalog catalog) { List<FreeIpaVersions> versions = filterFreeIpaVersionsByAppVersion(catalog.getVersions().getFreeIpaVersions()); List<Image> compatibleImages = findImage(imageId, imageOs, catalog.getImages().getFreeipaImages(), region, platform); LOGGER.debug("[{}] compatible images found, by the following parameters: imageId: {}, imageOs: {}, region: {}, platform: {}", compatibleImages.size(), imageId, imageOs, region, platform); return findImageInDefaults(versions, compatibleImages) .or(() -> findImageByApplicationVersion(versions, compatibleImages)) .or(() -> findMostRecentImage(compatibleImages)); }
Source:
private String getSortOrder(Sort sort) { return sort.stream() .map(this::getPropertySortOrder) .collect(Collectors.joining(", ")); }

Target:
private String getSortOrder(Sort sort) { return sort.stream() .map(Query::getPropertySortOrder) .collect(Collectors.joining(", ")); }
Source:
public FileInformationDTO uploadContestArchive(FileUploadDTO fileUploadDTO) throws AppException { List<MultipartFile> files = fileUploadDTO.getFiles(); if (files == null || files.size() > 1) { throw new AppException("Fetch uploaded file error."); } MultipartFile file = files.get(0); File targetFile = new File(getContestArchiveZipFileName()); if (targetFile.exists() && !targetFile.delete()) throw new AppException("Internal exception: target file exists and can not be deleted."); try { file.transferTo(targetFile); } catch (IOException e) { throw new AppException("Error while save files"); } return FileInformationDTO.builder() .setFileName(file.getOriginalFilename()) .build(); }

Target:
public FileInformationDTO uploadContestArchive(FileUploadDTO fileUploadDTO) throws AppException { List<MultipartFile> files = fileUploadDTO.getFiles(); if (files == null || files.size() > 1) { throw new AppException("Fetch uploaded file error."); } MultipartFile file = files.get(0); File targetFile = new File(getContestArchiveZipFileName()); if (targetFile.exists() && !targetFile.delete()) { throw new AppException("Internal exception: target file exists and can not be deleted."); } try { file.transferTo(targetFile); } catch (IOException e) { throw new AppException("Error while save files"); } return FileInformationDTO.builder() .setFileName(file.getOriginalFilename()) .build(); }
Source:
private CompletableFuture<DeployedCacheStoreMetadata> getPromise(String key) { CompletableFuture<DeployedCacheStoreMetadata> newPromise = new CompletableFuture<>(); CompletableFuture<DeployedCacheStoreMetadata> putResult = deployedCacheStores.putIfAbsent(key, newPromise); if(putResult != null) { return putResult; } return newPromise; }

Target:
private CompletableFuture<DeployedCacheStoreMetadata> getPromise(String key) { return deployedCacheStores.computeIfAbsent(key, mappedKey -> new CompletableFuture<>()); }
Source:
private Rectangle2D getNormalEdgeLabelBounds() { Line line = getConnectionPoints(); Point2D control = getControlPoint(); double x = control.getX() / 2 + line.getX1() / 4 + line.getX2() / 4; double y = control.getY() / 2 + line.getY1() / 4 + line.getY2() / 4; LABEL.setText(toHtml(edge().getMiddleLabel())); adjustLabelFont(); Dimension dimension = LABEL.getPreferredSize(); LABEL.setBounds(0, 0, dimension.width, dimension.height); int gap = 3; if( line.getY1() >= line.getY2() - VERTICAL_TOLERANCE && line.getY1() <= line.getY2() + VERTICAL_TOLERANCE ) { x -= dimension.getWidth() / 2; } else if( line.getY1() <= line.getY2() ) { x += gap; } else { x -= dimension.getWidth() + gap; } if( line.getX1() <= line.getX2() ) { y -= dimension.getHeight() + gap; } else { y += gap; } if( edge().getGraph() != null && getPosition() > 1 ) { double delta = Math.abs(Math.atan2((line.getX2()-line.getX1()),(line.getY2()-line.getY1()))); delta = dimension.getHeight() - delta*RADIANS_TO_PIXELS; if( line.getX1() <= line.getX2() ) { y -= delta; } else { y += delta; } } return new Rectangle2D.Double(x, y, dimension.width, dimension.height); }

Target:
private Rectangle2D getNormalEdgeLabelBounds() { Line line = getConnectionPoints(); Point2D control = getControlPoint(); double x = control.getX() / 2 + line.getX1() / 4 + line.getX2() / 4; double y = control.getY() / 2 + line.getY1() / 4 + line.getY2() / 4; LABEL.setText(toHtml(edge().getMiddleLabel())); adjustLabelFont(); Dimension dimension = LABEL.getPreferredSize(); LABEL.setBounds(0, 0, dimension.width, dimension.height); int gap = 3; if( line.getY1() >= line.getY2() - VERTICAL_TOLERANCE && line.getY1() <= line.getY2() + VERTICAL_TOLERANCE ) { x -= dimension.getWidth() / 2; } else if( line.getY1() <= line.getY2() ) { x += gap; } else { x -= dimension.getWidth() + gap; } if( line.getX1() <= line.getX2() ) { y -= dimension.getHeight() + gap; } else { y += gap; } if( edge().getGraph() != null && getPosition() > 1 ) { double delta = Math.abs(Math.atan2(line.getX2()-line.getX1(),line.getY2()-line.getY1())); delta = dimension.getHeight() - delta*RADIANS_TO_PIXELS; if( line.getX1() <= line.getX2() ) { y -= delta; } else { y += delta; } } return new Rectangle2D.Double(x, y, dimension.width, dimension.height); }
Source:
public List<CommitInfo> parseCommitInfos(JsonElement result) throws RestApiException { if (!result.isJsonArray()) { return Collections.singletonList(gson.fromJson(result, CommitInfo.class)); } return gson.fromJson(result, TYPE); }

Target:
public List<CommitInfo> parseCommitInfos(JsonElement result) { if (!result.isJsonArray()) { return Collections.singletonList(gson.fromJson(result, CommitInfo.class)); } return gson.fromJson(result, TYPE); }
Source:
public Event getEvent(@PathParam("uuid") String uuid) { throw new BadRequestException(i18n.tr("This API endpoint is deprecated, and will be" + " removed on the next major release.", uuid)); }

Target:
public Event getEvent(@PathParam("uuid") String uuid) { throw new NotFoundException(i18n.tr("This API endpoint is deprecated, and will be" + " removed on the next major release.", uuid)); }
Source:
public Object[] getElements(Object inputElement) { if (leftPathsWithChildren.isEmpty() && leftOnlyPaths.isEmpty()) return new String[] { UIText.CompareTreeView_NoDifferencesFoundMessage }; if (input instanceof IResource[]) { IResource[] resources = (IResource[]) input; PathNode[] nodes = new PathNode[resources.length]; for (int i = 0; i < resources.length; i++) { IResource resource = resources[i]; if (resource instanceof IFile) { IPath path = new Path(repositoryMapping .getRepoRelativePath(resource)); Type type; if (leftOnlyPaths.contains(path)) type = Type.FILE_ADDED; else if (equalContentPaths.contains(path)) type = Type.FILE_BOTH_SIDES_SAME; else type = Type.FILE_BOTH_SIDES_DIFFER; nodes[i] = new PathNode(path, type); } else nodes[i] = new PathNode(new Path(repositoryMapping .getRepoRelativePath(resource)), Type.FOLDER); } return nodes; } return new PathNode[] { new PathNode(new Path(""), Type.FOLDER) }; }

Target:
public Object[] getElements(Object inputElement) { if (baseVersionPathsWithChildren.isEmpty() && addedPaths.isEmpty()) return new String[] { UIText.CompareTreeView_NoDifferencesFoundMessage }; if (input instanceof IResource[]) { IResource[] resources = (IResource[]) input; PathNode[] nodes = new PathNode[resources.length]; for (int i = 0; i < resources.length; i++) { IResource resource = resources[i]; if (resource instanceof IFile) { IPath path = new Path(repositoryMapping .getRepoRelativePath(resource)); Type type; if (addedPaths.contains(path)) type = Type.FILE_ADDED; else if (equalContentPaths.contains(path)) type = Type.FILE_BOTH_SIDES_SAME; else type = Type.FILE_BOTH_SIDES_DIFFER; nodes[i] = new PathNode(path, type); } else nodes[i] = new PathNode(new Path(repositoryMapping .getRepoRelativePath(resource)), Type.FOLDER); } return nodes; } return new PathNode[] { new PathNode(new Path(""), Type.FOLDER) }; }
Source:
public static void main(String[] args) throws CmdLineException, NumberFormatException, HyracksException, Exception { String[] myArgs = { "-kmerLength", "55", "-localInput", "/home/anbangx/workspace/fullstack_genomix/hyracks/genomix/genomix-pregelix/data/TestSet/PathMerge/8", "-pipelineOrder", "MERGE", "localGraphOutput", "graph" }; if (System.getProperty("app.home") == null) System.setProperty("app.home", new File("target/appassembler").getAbsolutePath()); GenomixJobConf conf = GenomixJobConf.fromArguments(args); GenomixDriver driver = new GenomixDriver(); driver.runGenomix(conf); }

Target:
public static void main(String[] args) throws NumberFormatException, HyracksException, Exception { String[] myArgs = { "-runLocal", "true", "-kmerLength", "55", "-localInput", "tail600000", "-pipelineOrder", "BUILD_HYRACKS,MERGE", }; if (System.getProperty("app.home") == null) System.setProperty("app.home", new File("target/appassembler").getAbsolutePath()); GenomixJobConf conf; try { conf = GenomixJobConf.fromArguments(args); } catch (CmdLineException ex) { System.err.println("Usage: bin/genomix [options]\n"); ex.getParser().setUsageWidth(80); ex.getParser().printUsage(System.err); System.err.println("\nExample:"); System.err .println("\tbin/genomix -kmerLength 55 -pipelineOrder BUILD_HYRACKS,MERGE,TIP_REMOVE,MERGE,BUBBLE,MERGE -localInput /path/to/readfiledir/\n"); System.err.println(ex.getMessage()); return; } GenomixDriver driver = new GenomixDriver(); driver.runGenomix(conf); }
Source:
public UnixSHACryptPasswordImpl(UnixSHACryptPassword password) { this.salt = password.getSalt(); this.iterationCount = password.getIterationCount(); this.id = password.getId(); this.encoded = password.getEncoded(); this.charset = password.getCharset(); }

Target:
public UnixSHACryptPasswordImpl(UnixSHACryptPassword password) { this(password.getSalt(), password.getIterationCount(), password.getAlgorithm(), password.getHash()); }
Source:
private void loginUser(final SocketSession conn, final Request req, final LoginInformation login) { final boolean loginAsDefault = !login.hasIsInstructor(); try { final String userLoggedIn = DatabaseClient.mongoIdentify(login.getUsername(), login.getPassword(), loginAsDefault, login.getIsInstructor()); if (userLoggedIn != null) { final String[] ids = userLoggedIn.split(":"); if (ids.length == 2) { final boolean isInstructor = checkUserInstructor(login.getUsername(), login); send(conn, createLoginResponse(req, login, true, CORRECT_LOGIN_MESSAGE, isInstructor, ids)); } } } catch (LoginException e) { LOG.info("Login failed responding to proxy"); final Message.ProtoException protoEx = ExceptionUtilities.createProtoException(e); conn.send(ExceptionUtilities.createExceptionRequest(req, protoEx)); LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); send(conn, createLoginResponse(req, login, false, e.getMessage(), false, null)); } }

Target:
private void loginUser(final SocketSession conn, final Request req, final LoginInformation login) { final boolean loginAsDefault = !login.hasIsInstructor(); try { final String userLoggedIn = DatabaseClient.mongoIdentify(login.getUsername(), login.getPassword(), loginAsDefault, login.getIsInstructor()); if (userLoggedIn != null) { final String[] ids = userLoggedIn.split(":"); if (ids.length == 2) { final boolean isInstructor = checkUserInstructor(login.getUsername(), login); send(conn, createLoginResponse(req, login, true, CORRECT_LOGIN_MESSAGE, isInstructor, ids)); } } } catch (LoginException e) { LOG.warn("Login failed, creating failed response."); final Message.ProtoException protoEx = ExceptionUtilities.createProtoException(e); conn.send(ExceptionUtilities.createExceptionRequest(req, protoEx)); LOG.error(LoggingConstants.EXCEPTION_MESSAGE, e); send(conn, createLoginResponse(req, login, false, e.getMessage(), false, null)); } }
Source:
public ImmutableRatesProviderBuilder overnightIndexCurve(OvernightIndex index, Curve forwardCurve) { ArgChecker.notNull(index, "currency"); ArgChecker.notNull(forwardCurve, "forwardCurve"); this.indexCurves.put(index, forwardCurve); return this; }

Target:
public ImmutableRatesProviderBuilder overnightIndexCurve(OvernightIndex index, Curve forwardCurve) { ArgChecker.notNull(index, "index"); ArgChecker.notNull(forwardCurve, "forwardCurve"); this.indexCurves.put(index, forwardCurve); return this; }
Source:
public void testRemoveSession() { StudyParticipant participant = new StudyParticipant.Builder().withId(USER_ID).build(); UserSession session = new UserSession(participant); session.setSessionToken(DECRYPTED_SESSION_TOKEN); cacheProvider.removeSession(session); cacheProvider.getUserSession(DECRYPTED_SESSION_TOKEN); verify(transaction).del(TOKEN_TO_USER_ID.toString()); verify(transaction).del(USER_ID_TO_SESSION.toString()); verify(transaction).exec(); }

Target:
public void testRemoveSession() { StudyParticipant participant = new StudyParticipant.Builder().withId(USER_ID).build(); UserSession session = new UserSession(participant); session.setSessionToken(DECRYPTED_SESSION_TOKEN); cacheProvider.removeSession(session); cacheProvider.getUserSession(DECRYPTED_SESSION_TOKEN); verify(transaction).del(TOKEN_TO_USER_ID.toString()); verify(transaction).del(USER_ID_TO_SESSION.toString()); verify(transaction).del(CacheKey.session(DECRYPTED_SESSION_TOKEN).toString()); verify(transaction).del(CacheKey.sessionByUserId(USER_ID).toString()); verify(transaction).exec(); }
Source:
private static boolean googleIsReachable() { String host = "www.google.com"; InetAddress address; try { address = InetAddress.getByName(host); return address.isReachable(1500); } catch (UnknownHostException ex) { return false; } catch (IOException ex) { return false; } }

Target:
private static boolean googleIsReachable() { String host = "www.google.com"; InetAddress address; try { address = InetAddress.getByName(host); return address.isReachable(1500); } catch (UnknownHostException ex) { logger.log(Level.WARNING, "Unable to reach google.com due to unknown host", ex); return false; } catch (IOException ex) { logger.log(Level.WARNING, "Unable to reach google.com due IOException", ex); return false; } }
Source:
public boolean advance() throws IOException { try { currentRecord = bulkResultSet.next(); } catch (IOException e){ close(); throw e; } if (currentRecord == null) { return retrieveNextResultSet(); } dataCount++; return true; }

Target:
public boolean advance() throws IOException { try { currentRecord = bulkResultSet.next(); if (currentRecord == null) { return retrieveNextResultSet(); } } catch (IOException e) { close(); throw e; } dataCount++; return true; }
Source:
public CompletableFuture<WorkspaceRuntimeImpl> startAsync(Workspace workspace, String envName, boolean recover) throws ConflictException, ServerException { requireNonNull(workspace, "Non-null workspace required"); requireNonNull(envName, "Non-null environment name required"); EnvironmentImpl environment = copyEnv(workspace, envName); String workspaceId = workspace.getId(); CompletableFuture<WorkspaceRuntimeImpl> cmpFuture; StartTask startTask; try (@SuppressWarnings("unused") Unlocker u = locks.writeLock(workspaceId)) { checkIsNotTerminated("start the workspace"); if (isStartRefused.get()) { throw new ConflictException(format("Start of the workspace '%s' is rejected by the system, " + "no more workspaces are allow to start", workspace.getConfig().getName())); } RuntimeState state = states.get(workspaceId); if (state != null) { throw new ConflictException(format("Could not start workspace '%s' because its status is '%s'", workspace.getConfig().getName(), state.status)); } startTask = new StartTask(workspaceId, envName, environment, recover, cmpFuture = new CompletableFuture<>()); states.put(workspaceId, new RuntimeState(WorkspaceStatus.STARTING, envName, startTask, sharedPool.submit(startTask))); } eventsService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class) .withWorkspaceId(workspaceId) .withStatus(WorkspaceStatus.STARTING) .withEventType(EventType.STARTING) .withPrevStatus(WorkspaceStatus.STOPPED)); startTask.unlockStart(); return cmpFuture; }

Target:
public CompletableFuture<WorkspaceRuntimeImpl> startAsync(Workspace workspace, String envName, boolean recover) throws ConflictException, ServerException { requireNonNull(workspace, "Non-null workspace required"); requireNonNull(envName, "Non-null environment name required"); EnvironmentImpl environment = copyEnv(workspace, envName); String workspaceId = workspace.getId(); CompletableFuture<WorkspaceRuntimeImpl> cmpFuture; StartTask startTask; try (@SuppressWarnings("unused") Unlocker u = locks.writeLock(workspaceId)) { checkIsNotTerminated("start the workspace"); if (isStartRefused.get()) { throw new ConflictException(format("Start of the workspace '%s' is rejected by the system, " + "no more workspaces are allowed to start", workspace.getConfig().getName())); } RuntimeState state = states.get(workspaceId); if (state != null) { throw new ConflictException(format("Could not start workspace '%s' because its status is '%s'", workspace.getConfig().getName(), state.status)); } startTask = new StartTask(workspaceId, envName, environment, recover, cmpFuture = new CompletableFuture<>()); states.put(workspaceId, new RuntimeState(WorkspaceStatus.STARTING, envName, startTask, sharedPool.submit(startTask))); } eventsService.publish(DtoFactory.newDto(WorkspaceStatusEvent.class) .withWorkspaceId(workspaceId) .withStatus(WorkspaceStatus.STARTING) .withEventType(EventType.STARTING) .withPrevStatus(WorkspaceStatus.STOPPED)); startTask.unlockStart(); return cmpFuture; }
Source:
public Single<String> getSessions() { return readJsonAsset(Urls.SESSIONS) .flatMapCompletable(JsonHandler::handleSessions) .toSingleDefault(ConstantStrings.SESSIONS); }

Target:
public Completable getSessions() { return readJsonAsset(Urls.SESSIONS) .flatMapCompletable(JsonHandler::handleSessions); }
Source:
public CreateNattableConfigurationWizard(final TableConfiguration configuration, final Resource initialResource) { this.configuration = configuration; this.helper = new TableConfigurationHelper(this.configuration); String pluginId = Activator.PLUGIN_ID; ImageDescriptor desc = org.eclipse.papyrus.infra.widgets.Activator.getDefault().getImageDescriptor(pluginId, NattableConfigurationConstants.ICON_WIZBAN_PATH); setDefaultPageImageDescriptor(desc); setWindowTitle(WIZARD_TITLE); setForcePreviousAndNextButtons(true); this.initialResource = initialResource; isProjectCreation = null == this.initialResource; }

Target:
public CreateNattableConfigurationWizard(final TableConfiguration configuration, final Resource initialResource) { this.configuration = configuration; this.helper = new TableConfigurationHelper(this.configuration); final ImageDescriptor desc = org.eclipse.papyrus.infra.widgets.Activator.getDefault().getImageDescriptor(Activator.PLUGIN_ID, NattableConfigurationConstants.ICON_WIZBAN_PATH); setDefaultPageImageDescriptor(desc); setWindowTitle(Messages.CreateNattableConfigurationWizard_WizardTitke); setForcePreviousAndNextButtons(true); this.initialResource = initialResource; isProjectCreation = null == this.initialResource; }
Source:
public String toString() { return serialize(this); }

Target:
public String toString() { return "name="+ name + ";javaType=" + javaType.getName() + ";uuid=" + uuid.toString(); }
Source:
public void verifyFromModuleHasQuatation() { List<WebElement> List = driver.findElements(fromCommunityQuatationsBy); for (int i = 0; i < List.size(); i++) { PageObjectLogging.log("verifyFromModuleHasQuatation", "Checking quotation number "+(i+1), true); scrollToElement(List.get(i)); waitForElementByElement(List.get(i)); } PageObjectLogging.log("verifyFromModuleHasQuatation", "Verify that from the community module has a quatation", true); }

Target:
public void verifyFromModuleHasQuatation() { for (WebElement element : fromCommunityQuatations) { scrollToElement(element); waitForElementByElement(element); } PageObjectLogging.log( "verifyFromModuleHasQuatation", "Verify that from the community module has a quatation", true ); }
Source:
public SafeHtml getEntityTooltip(Cluster object) { String warning = null; if (object.isClusterCompatibilityLevelUpgradeNeeded()) { warning = constants.clusterLevelUpgradeNeeded(); } if (isDeprecated(object)) { if (warning != null) { warning += constants.seperatorHTML(); warning += constants.preCPUDepricationWarning(); } else { warning = constants.preCPUDepricationWarning(); } warning += object.getCpuName(); warning += constants.postCPUDepricationWarning(); } if (warning != null) { return SafeHtmlUtils.fromTrustedString(warning); } return null; }

Target:
public SafeHtml getEntityTooltip(Cluster object) { String warning = null; if (object.isClusterCompatibilityLevelUpgradeNeeded()) { warning = constants.clusterLevelUpgradeNeeded(); } if (isDeprecated(object)) { if (warning != null) { warning += constants.seperatorHTML(); warning += constants.preCPUDeprecationWarning(); } else { warning = constants.preCPUDeprecationWarning(); } warning += object.getCpuName(); warning += constants.postCPUDeprecationWarning(); } if (warning != null) { return SafeHtmlUtils.fromTrustedString(warning); } return null; }
Source:
private void startLatestBrokerOffsetsFetcher() { _latestBrokerOffsetsFetcher.submit(() -> { Consumer<?, ?> consumer = createKafkaConsumer(_consumerProps); while (!_shutdown) { Future<?> future = null; try { Instant currentTime = Instant.now(); Set<TopicPartition> partitionsNeedingUpdate = _consumerAssignment.stream() .filter(tp -> Optional.ofNullable(_offsetPositions.get(tp.toString())) .map(PhysicalSourcePosition::getSourceQueriedTime) .map(Instant::ofEpochMilli) .orElse(Instant.EPOCH) .isBefore(currentTime.minus(1, ChronoUnit.MINUTES))) .collect(Collectors.toSet()); future = _latestBrokerOffsetsFetcher.submit(updateLatestBrokerOffsetsByRpc(consumer, partitionsNeedingUpdate, currentTime.toEpochMilli())); future.get(1, TimeUnit.MINUTES); Thread.sleep(Duration.ofMinutes(1).toMillis()); } catch (Exception e) { if (future != null) { future.cancel(true); } } } if (consumer != null) { consumer.close(); } }); }

Target:
private void startLatestBrokerOffsetsFetcher() { _latestBrokerOffsetsFetcher.submit(() -> { Consumer<?, ?> consumer = createKafkaConsumer(_consumerProps); while (!_shutdown) { Future<?> future = null; Instant currentTime = Instant.now(); Set<TopicPartition> partitionsNeedingUpdate = _consumerAssignment.stream() .filter(tp -> Optional.ofNullable(_offsetPositions.get(tp.toString())) .map(PhysicalSourcePosition::getSourceQueriedTimeMs) .map(Instant::ofEpochMilli) .orElse(Instant.EPOCH) .isBefore(currentTime.minus(1, ChronoUnit.MINUTES))) .collect(Collectors.toSet()); try { future = _latestBrokerOffsetsFetcher.submit(updateLatestBrokerOffsetsByRpc(consumer, partitionsNeedingUpdate, currentTime.toEpochMilli())); future.get(1, TimeUnit.MINUTES); Thread.sleep(Duration.ofMinutes(1).toMillis()); } catch (Exception e) { if (future != null) { future.cancel(true); } _logger.warn("Failed to update broker end offsets via RPC.", e); } } if (consumer != null) { consumer.close(); } }); }
Source:
public List<CourseDetailsBundle> getCourseDetailsListForStudent(String googleId) throws EntityDoesNotExistException { List<CourseAttributes> courseList = getCoursesForStudentAccount(googleId); List<CourseDetailsBundle> courseDetailsList = new ArrayList<CourseDetailsBundle>(); for (CourseAttributes c : courseList) { StudentAttributes s = studentsLogic.getStudentForCourseIdAndGoogleId(c.getId(), googleId); if (s == null) { StringBuilder logMsg = new StringBuilder(); logMsg.append( "Student is null in CoursesLogic.getCourseDetailsListForStudent(String googleId)<br/> Student Google ID: " + googleId + "<br/> Course: " + c.getId() + "<br/> All Courses Retrieved using the Google ID:"); for (CourseAttributes course : courseList) { logMsg.append("<br/>").append(course.getId()); } log.severe(logMsg.toString()); Assumption.assertNotNull("Student should not be null at this point.", s); } List<FeedbackSessionAttributes> feedbackSessionList = feedbackSessionsLogic.getFeedbackSessionsForUserInCourseSkipCheck(c.getId(), s.email); CourseDetailsBundle cdd = new CourseDetailsBundle(c); for (FeedbackSessionAttributes fs : feedbackSessionList) { cdd.feedbackSessions.add(new FeedbackSessionDetailsBundle(fs)); } courseDetailsList.add(cdd); } return courseDetailsList; }

Target:
public List<CourseDetailsBundle> getCourseDetailsListForStudent(String googleId) throws EntityDoesNotExistException { List<CourseAttributes> courseList = getCoursesForStudentAccount(googleId); List<CourseDetailsBundle> courseDetailsList = new ArrayList<CourseDetailsBundle>(); for (CourseAttributes c : courseList) { StudentAttributes s = studentsLogic.getStudentForCourseIdAndGoogleId(c.getId(), googleId); if (s == null) { StringBuilder logMsg = new StringBuilder(); logMsg.append( "Student is null in CoursesLogic.getCourseDetailsListForStudent(String googleId)<br> Student Google ID: " + googleId + "<br> Course: " + c.getId() + "<br> All Courses Retrieved using the Google ID:"); for (CourseAttributes course : courseList) { logMsg.append("<br>").append(course.getId()); } log.severe(logMsg.toString()); Assumption.assertNotNull("Student should not be null at this point.", s); } List<FeedbackSessionAttributes> feedbackSessionList = feedbackSessionsLogic.getFeedbackSessionsForUserInCourseSkipCheck(c.getId(), s.email); CourseDetailsBundle cdd = new CourseDetailsBundle(c); for (FeedbackSessionAttributes fs : feedbackSessionList) { cdd.feedbackSessions.add(new FeedbackSessionDetailsBundle(fs)); } courseDetailsList.add(cdd); } return courseDetailsList; }
Source:
Request(HttpMethod method, String url, Map<String, Collection<String>> headers, Body body, RequestTemplate requestTemplate) { this.httpMethod = checkNotNull(method, "httpMethod of %s", method.name()); this.url = checkNotNull(url, "url"); this.headers = checkNotNull(headers, "headers of %s %s", method, url); this.body = (body != null) ? body : Body.EMPTY; this.requestTemplate = requestTemplate; }

Target:
Request(HttpMethod method, String url, Map<String, Collection<String>> headers, Body body, RequestTemplate requestTemplate) { this.httpMethod = checkNotNull(method, "httpMethod of %s", method.name()); this.url = checkNotNull(url, "url"); this.headers = checkNotNull(headers, "headers of %s %s", method, url); this.body = body; this.requestTemplate = requestTemplate; }
Source:
public static boolean removeAidlCallback (long id){ return callbacks.remove(id) != null; }

Target:
public boolean removeAidlCallback(long id) { for (Long key : callbacks.keySet()) { if (key == id) { callbacks.remove(id); return true; } } return false; }
Source:
Collection<CompletableFuture<Void>> getPendingFutures() { return pendingFutures.values(); }

Target:
Collection<CompletableFuture<Void>> getPendingFutures() { return pendingFutures; }
Source:
public CompletableFuture<DispatchStatus> send(S message) { CompletableFuture<DispatchStatus> sendFuture = new CompletableFuture<>(); if (!asyncPolicy.isBlockWhenFull() && dispatchQueue.isFull()) { droppedCounter.inc(); sendFuture.completeExceptionally(new RuntimeException("Dispatch queue full")); return sendFuture; } try { String newId = UUID.randomUUID().toString(); DispatchQueue.EnqueueResult result = dispatchQueue.enqueue(message, newId); LOG.trace("Result of enqueueing was {}", result); if (result == DispatchQueue.EnqueueResult.DEFERRED) { sendFuture.complete(DispatchStatus.QUEUED); } else { futureMap.put(newId, sendFuture); } } catch (WriteFailedException e) { sendFuture.completeExceptionally(e); } return sendFuture; }

Target:
public CompletableFuture<DispatchStatus> send(S message) { CompletableFuture<DispatchStatus> sendFuture = new CompletableFuture<>(); if (!asyncPolicy.isBlockWhenFull() && dispatchQueue.isFull()) { droppedCounter.inc(); sendFuture.completeExceptionally(new RuntimeException("Dispatch queue full")); return sendFuture; } try { String newId = UUID.randomUUID().toString(); DispatchQueue.EnqueueResult result = dispatchQueue.enqueue(message, newId); LOG.trace("Result of enqueueing for Id was {}", newId, result); if (result == DispatchQueue.EnqueueResult.DEFERRED) { sendFuture.complete(DispatchStatus.QUEUED); } else { futureMap.put(newId, sendFuture); } } catch (WriteFailedException e) { sendFuture.completeExceptionally(e); } return sendFuture; }
Source:
public DeleteObjectResult call() throws Exception { DeleteObjectResponse response; try { response = getClient().deleteObject(new DeleteObjectRequest(bucketName, objectName)); } catch (final IOException e) { throw new CommandException("Error: Request failed with the following error: " + e.getMessage(), e); } return new DeleteObjectResult("Success: Deleted object '" + this.objectName + "' from bucket '" + this.bucketName + "'."); }

Target:
public DeleteObjectResult call() throws Exception { try { getClient().deleteObject(new DeleteObjectRequest(bucketName, objectName)); } catch (final IOException e) { throw new CommandException("Error: Request failed with the following error: " + e.getMessage(), e); } return new DeleteObjectResult("Success: Deleted object '" + this.objectName + "' from bucket '" + this.bucketName + "'."); }
Source:
final public void run() { Thread.currentThread().setName(this.name); try { this.configure(); } catch (Exception e) { logger.error("Unable to configure {}", name, e); System.exit(1); } try { this.start(); } catch (Exception e) { logger.error("Unable to start ", name, e); System.exit(1); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutdown(); } }); try { join(); } catch (Exception e) { logger.warn("Interrupted (most likely JVM is shutting down and this is safe to ignore)"); } }

Target:
final public void run() { Thread.currentThread().setName(this.name); try { this.configure(); } catch (Exception e) { logger.error("Unable to configure {}", name, e); System.exit(1); } try { this.start(); } catch (Exception e) { logger.error("Unable to start {}", name, e); System.exit(1); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutdown(); } }); try { join(); } catch (Exception e) { logger.warn("Interrupted (most likely JVM is shutting down and this is safe to ignore)"); } }
Source:
default Iterator<T> reverseIterator() { return new AbstractIterator<T>() { final ListIterator<T> delegate = IndexedSeq.this.listIterator(IndexedSeq.this.length()); @Override public boolean hasNext() { return delegate.hasPrevious(); } @Override public T getNext() { return delegate.previous(); } }; }

Target:
default Iterator<T> reverseIterator() { return new AbstractIterator<T>() { private int i = IndexedSeq.this.length(); @Override public boolean hasNext() { return i > 0; } @Override public T getNext() { return IndexedSeq.this.get(--i); } }; }
Source:
public JSONObject schemaFor(final Object event) { if (event instanceof String) { return new JSONObject().put("type", "string"); } else if (event instanceof Integer) { return new JSONObject().put("type", "number"); } else if (event instanceof Boolean) { return new JSONObject().put("type", "boolean"); } else if (event == JSONObject.NULL) { return new JSONObject().put("type", "null"); } else if (event instanceof JSONArray) { return schemaFor((JSONArray) event); } else { return schemaFor((JSONObject) event); } }

Target:
public JSONObject schemaFor(final Object event) { if (event instanceof String) { return new JSONObject().put("type", "string"); } else if (event instanceof Integer || event instanceof Double) { return new JSONObject().put("type", "number"); } else if (event instanceof Boolean) { return new JSONObject().put("type", "boolean"); } else if (event == JSONObject.NULL) { return new JSONObject().put("type", "null"); } else if (event instanceof JSONArray) { return schemaFor((JSONArray) event); } else { return schemaFor((JSONObject) event); } }
Source:
private void updateSkinOthers() { this.offer(Keys.VANISH, true); Sponge.getScheduler().createTaskBuilder().execute(() -> this.offer(Keys.VANISH, false)).delayTicks(1).submit(SpongeImpl.getPlugin()); }

Target:
private void updateSkinOthers() { if (!this.isDead && !this.get(Keys.VANISH).get()) { this.offer(Keys.VANISH, true); this.runDelay(2, () -> this.offer(Keys.VANISH, false)); } }
Source:
private FeatureFlag findFlag(final String flagName) { for (final FeatureFlag flag : featureFlags) { if (flagName.equalsIgnoreCase(flag.getName())) { return flag; } } return null; }

Target:
private Optional<FeatureFlag> findFlag(final String flagName) { return featureFlags.stream().filter(f -> flagName.equalsIgnoreCase(f.getName())).findAny(); }
Source:
public void onRegisterItems(final RegistryEvent.Register<Item> event) { registerItem(event, CacheBlocks.WOOD); registerItem(event, CacheBlocks.IRON); registerItem(event, CacheBlocks.GOLD); registerItem(event, CacheBlocks.DIAMOND); registerItem(event, CacheBlocks.NETHER); registerItem(event, CacheBlocks.ENDER); }

Target:
public void onRegisterItems(final RegistryEvent.Register<Item> event) { final IForgeRegistry<Item> registry = event.getRegistry(); registerItem(registry, CacheBlocks.WOOD); registerItem(registry, CacheBlocks.IRON); registerItem(registry, CacheBlocks.GOLD); registerItem(registry, CacheBlocks.DIAMOND); registerItem(registry, CacheBlocks.NETHER); registerItem(registry, CacheBlocks.ENDER); }
Source:
private Object readResolve() { if (parameters == null) { parameters = Collections.emptyList(); } if (build != null) OldDataMonitor.report(build, "1.283"); if (safeParameters == null) { safeParameters = Collections.emptySet(); } return this; }

Target:
private Object readResolve() { wasInitializedWithNullParameters = parameters == null; if (parameters == null) { parameters = Collections.emptyList(); } if (build != null) OldDataMonitor.report(build, "1.283"); if (safeParameters == null) { safeParameters = Collections.emptySet(); } return this; }
Source:
protected void startMonitoring() { if (fThread == null) { fThread = new Thread(() -> read(), DebugCoreMessages.OutputStreamMonitor_label); fThread.setDaemon(true); fThread.setPriority(Thread.MIN_PRIORITY); fThread.start(); boolean reading = checkReading(MAX_WAIT_TIME_FOR_START_READING); if (!reading && DebugOptions.DEBUG) { DebugOptions.trace("OutputStreamMonitor::startMonitoring() was unable to start reading stream after " + MAX_WAIT_TIME_FOR_START_READING + " ms."); } } }

Target:
protected void startMonitoring() { if (fThread == null) { fThread = new Thread((Runnable) () -> read(), DebugCoreMessages.OutputStreamMonitor_label); fThread.setDaemon(true); fThread.setPriority(Thread.MIN_PRIORITY); fThread.start(); } }
Source:
void reset(boolean isShutdown) { logger.info("Resetting CallbackHandler: " + this.toString()); try { _ready = false; synchronized (this) { if (_batchCallbackProcessor != null) { if (isShutdown) { _batchCallbackProcessor.shutdown(); _batchCallbackProcessor = null; } else { _batchCallbackProcessor.resetEventQueue(); } } } NotificationContext changeContext = new NotificationContext(_manager); changeContext.setType(NotificationContext.Type.FINALIZE); changeContext.setChangeType(_changeType); invoke(changeContext); } catch (Exception e) { String msg = "Exception while resetting the listener:" + _listener; ZKExceptionHandler.getInstance().handle(msg, e); } }

Target:
void reset(boolean isShutdown) { logger.info("Resetting CallbackHandler: {}. Is resetting for shutdown: {}.", this.toString(), isShutdown); try { _ready = false; synchronized (this) { if (_batchCallbackProcessor != null) { if (isShutdown) { _batchCallbackProcessor.shutdown(); _batchCallbackProcessor = null; } else { _batchCallbackProcessor.resetEventQueue(); } } } NotificationContext changeContext = new NotificationContext(_manager); changeContext.setType(NotificationContext.Type.FINALIZE); changeContext.setChangeType(_changeType); invoke(changeContext); } catch (Exception e) { String msg = "Exception while resetting the listener:" + _listener; ZKExceptionHandler.getInstance().handle(msg, e); } }
Source:
private synchronized Map<Integer, double[]> initSeries(TimeQueryFilter filter) { if (!(filter instanceof SelectionTimeQueryFilter)) { return Collections.emptyMap(); } Map<Integer, double[]> map = new HashMap<>(); int length = filter.getTimesRequested().length; for (Long id : ((SelectionTimeQueryFilter) filter).getSelectedItems()) { Integer quark = fIdToQuark.get(id); if (quark != null) { map.put(quark, new double[length]); } } return map; }

Target:
private Map<Integer, double[]> initSeries(TimeQueryFilter filter) { if (!(filter instanceof SelectionTimeQueryFilter)) { return Collections.emptyMap(); } fLock.readLock().lock(); try { Map<Integer, double[]> map = new HashMap<>(); int length = filter.getTimesRequested().length; for (Long id : ((SelectionTimeQueryFilter) filter).getSelectedItems()) { Integer quark = fIdToQuark.get(id); if (quark != null) { map.put(quark, new double[length]); } } return map; } finally { fLock.readLock().unlock(); } }
Source:
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { Drawable b = getDrawable(); canvas.save(); int transY = bottom - b.getBounds().bottom; transY -= paint.getFontMetricsInt().descent * lineSpacingMultiplier; canvas.translate(x, transY); b.draw(canvas); canvas.restore(); }

Target:
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { Drawable drawable = getDrawable(); canvas.save(); int transY = bottom - drawable.getBounds().bottom; transY -= paint.getFontMetricsInt().descent * lineSpacingMultiplier; canvas.translate(x, transY); drawable.draw(canvas); canvas.restore(); }
Source:
public void testByteArrayStrippedLockTx() throws InterruptedException, TimeoutException, ExecutionException { doTest(CacheName.STRIPPED_LOCK_TX); }

Target:
public void testByteArrayStrippedLockTx() throws Exception { doTest(CacheName.STRIPPED_LOCK_TX); }
Source:
public Collection<ConstraintCheckIssue> checkMethod(ExecutableElement currentMethod) { if ( !needToPerformAnyChecks( currentMethod ) ) { return Collections.emptySet(); } TypeElement currentTypeElement = getEnclosingTypeElement( currentMethod ); if ( isJavaLangObjectOrNull( currentTypeElement ) ) { return Collections.emptySet(); } Map<Boolean, List<ExecutableElement>> overriddenMethods = findAllOverriddenElements( currentTypeElement, currentMethod ); if ( overriddenMethods.get( Boolean.TRUE ).isEmpty() && overriddenMethods.get( Boolean.FALSE ).isEmpty() ) { return Collections.emptySet(); } Set<ConstraintCheckIssue> errors = CollectionHelper.newHashSet(); for ( ExecutableElement firstExecutable : overriddenMethods.get( Boolean.TRUE ) ) { if ( !checkOverriddenMethod( currentMethod, firstExecutable ) ) { return CollectionHelper.asSet( ConstraintCheckIssue.error( currentMethod, null, getErrorMessageKey(), getEnclosingTypeElementQualifiedName( firstExecutable ) ) ); } for ( ExecutableElement secondExecutable : overriddenMethods.get( Boolean.TRUE ) ) { if ( firstExecutable.equals( secondExecutable ) ) { continue; } if ( !checkOverriddenMethod( firstExecutable, secondExecutable ) ) { errors.add( ConstraintCheckIssue.error( currentMethod, null, getErrorMessageKey(), getEnclosingTypeElementQualifiedName( secondExecutable ) ) ); } } } if ( !errors.isEmpty() ) { return errors; } for ( ExecutableElement overriddenMethod : overriddenMethods.get( Boolean.FALSE ) ) { if ( !checkOverriddenMethod( currentMethod, overriddenMethod ) ) { return CollectionHelper.asSet( ConstraintCheckIssue.error( currentMethod, null, getErrorMessageKey(), getEnclosingTypeElementQualifiedName( overriddenMethod ) ) ); } } return Collections.emptySet(); }

Target:
public Collection<ConstraintCheckIssue> checkMethod(ExecutableElement currentMethod) { if ( !needToPerformAnyChecks( currentMethod ) ) { return Collections.emptySet(); } TypeElement currentTypeElement = getEnclosingTypeElement( currentMethod ); if ( isJavaLangObjectOrNull( currentTypeElement ) ) { return Collections.emptySet(); } InheritanceTree overriddenMethodsTree = findAllOverriddenElements( currentTypeElement, currentMethod ); if ( !overriddenMethodsTree.hasOverriddenMethods() ) { return Collections.emptySet(); } return checkMethodInternal( currentMethod, overriddenMethodsTree ); }
Source:
public HandleStatus handle(final MessageReference ref) throws Exception { if (filter != null && !filter.match(ref.getMessage())) { return HandleStatus.NO_MATCH; } synchronized (this) { if (!active || !session.isWritable(this)) { if (logger.isDebugEnabled()) { logger.debug(this + "::Ignoring reference on bridge as it is set to inactive ref=" + ref); } return HandleStatus.BUSY; } if (blockedOnFlowControl) { return HandleStatus.BUSY; } if (deliveringLargeMessage) { return HandleStatus.BUSY; } if (logger.isTraceEnabled()) { logger.trace("Bridge " + this + " is handling reference=" + ref); } ref.handled(); synchronized (refs) { refs.put(ref.getMessage().getMessageID(), ref); } final SimpleString dest; if (forwardingAddress != null) { dest = forwardingAddress; } else { dest = ref.getMessage().getAddressSimpleString(); } final Message message = beforeForward(ref.getMessage(), dest); pendingAcks.countUp(); metrics.incrementEnqueueCount(); try { if (message.isLargeMessage()) { deliveringLargeMessage = true; deliverLargeMessage(dest, ref, (LargeServerMessage) message); return HandleStatus.HANDLED; } else { return deliverStandardMessage(dest, ref, message); } } catch (Exception e) { pendingAcks.countDown(); throw e; } } }

Target:
public HandleStatus handle(final MessageReference ref) throws Exception { if (filter != null && !filter.match(ref.getMessage())) { return HandleStatus.NO_MATCH; } synchronized (this) { if (!active || !session.isWritable(this)) { if (logger.isDebugEnabled()) { logger.debug(this + "::Ignoring reference on bridge as it is set to inactive ref=" + ref); } return HandleStatus.BUSY; } if (blockedOnFlowControl) { return HandleStatus.BUSY; } if (deliveringLargeMessage) { return HandleStatus.BUSY; } if (logger.isTraceEnabled()) { logger.trace("Bridge " + this + " is handling reference=" + ref); } ref.handled(); synchronized (refs) { refs.put(ref.getMessage().getMessageID(), ref); } final SimpleString dest; if (forwardingAddress != null) { dest = forwardingAddress; } else { dest = ref.getMessage().getAddressSimpleString(); } final Message message = beforeForward(ref.getMessage(), dest); pendingAcks.countUp(); try { final HandleStatus status; if (message.isLargeMessage()) { deliveringLargeMessage = true; deliverLargeMessage(dest, ref, (LargeServerMessage) message); status = HandleStatus.HANDLED; } else { status = deliverStandardMessage(dest, ref, message); } if (status == HandleStatus.HANDLED) { metrics.incrementMessagesPendingAcknowledgement(); } return status; } catch (Exception e) { pendingAcks.countDown(); throw e; } } }
Source:
protected Bitmap doInBackground(File... params) { return rescaleBackgroundImage(loadImageFromPath(params[0])); }

Target:
protected Bitmap doInBackground(File... params) { if (files == null || files.isEmpty()) { return null; } else { return rescaleBackgroundImage(loadImageFromPath(params[0])); } }
Source:
protected UnitVmModel createModel(VmModelBehaviorBase behavior) { UnitVmModel model = new UnitVmModel(behavior) { @Override public EntityModel<Boolean> getIsSingleQxlEnabled() { return new EntityModel<Boolean>(true); } VDSGroup cluster = new VDSGroup(); { cluster.setcompatibility_version(new Version(3, 5)); } @Override public VDSGroup getSelectedCluster() { return cluster; } }; model.initialize(null); return model; }

Target:
protected UnitVmModel createModel(VmModelBehaviorBase behavior) { final VDSGroup cluster = new VDSGroup(); cluster.setcompatibility_version(Version.v3_5); UnitVmModel model = new UnitVmModel(behavior) { @Override public EntityModel<Boolean> getIsSingleQxlEnabled() { return new EntityModel<Boolean>(true); } @Override public VDSGroup getSelectedCluster() { return cluster; } }; model.initialize(null); return model; }
Source:
private LiteralNode literalArray(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); List<ExpressionNode> expressions = new ArrayList<ExpressionNode>(); expect(NewLiteralArray, DelimiterOpeningTag.class); while (true) { comments(); switch (sym) { case EndLiteralArray: expect(EndLiteralArray, DelimiterClosingTag.class); return createLiteralArray(expressions, getSource(coord)); case Period: expect(Period, StatementSeparatorTag.class); break; default: expressions.add(expression(builder)); break; } } }

Target:
private LiteralNode literalArray(final MethodBuilder builder) throws ProgramDefinitionError { SourceCoordinate coord = getCoordinate(); List<ExpressionNode> expressions = new ArrayList<ExpressionNode>(); expect(NewLiteralArray, DelimiterOpeningTag.class); boolean needsSeparator = false; while (true) { comments(); if (sym == EndLiteralArray) { expect(EndLiteralArray, DelimiterClosingTag.class); return createLiteralArray(expressions, getSource(coord)); } if (needsSeparator) { expect(Period, "Could not parse statement. Expected a '.' but got '" + text + "'", StatementSeparatorTag.class); } expressions.add(expression(builder)); needsSeparator = !accept(Period, StatementSeparatorTag.class); } }