auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void writeLeaderInformation(LeaderInformation leaderInformation) { final UUID confirmedLeaderSessionID = leaderInformation.getLeaderSessionID(); final String confirmedLeaderAddress = leaderInformation.getLeaderAddress(); try { kubeClient.checkAndUpdateConfigMap( configMapName, configMap -> { if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) { if (confirmedLeaderAddress != null && confirmedLeaderSessionID != null) { configMap.getData().put(LEADER_ADDRESS_KEY, confirmedLeaderAddress); configMap.getData().put(LEADER_SESSION_ID_KEY, confirmedLeaderSessionID.toString()); } configMap.getLabels().putAll(configMapLabels); return Optional.of(configMap); } return Optional.empty(); }).get(); } catch (Exception e) { fatalErrorHandler.onFatalError( new KubernetesException("Could not update ConfigMap " + configMapName, e)); } }

Target:
public void writeLeaderInformation(LeaderInformation leaderInformation) { assert(running); final UUID confirmedLeaderSessionID = leaderInformation.getLeaderSessionID(); final String confirmedLeaderAddress = leaderInformation.getLeaderAddress(); try { kubeClient.checkAndUpdateConfigMap( configMapName, configMap -> { if (KubernetesLeaderElector.hasLeadership(configMap, lockIdentity)) { if (confirmedLeaderAddress == null) { configMap.getData().remove(LEADER_ADDRESS_KEY); } else { configMap.getData().put(LEADER_ADDRESS_KEY, confirmedLeaderAddress); } if (confirmedLeaderSessionID == null) { configMap.getData().remove(LEADER_SESSION_ID_KEY); } else { configMap.getData().put(LEADER_SESSION_ID_KEY, confirmedLeaderSessionID.toString()); } configMap.getLabels().putAll(configMapLabels); return Optional.of(configMap); } return Optional.empty(); }).get(); if (LOG.isDebugEnabled()) { LOG.debug( "Successfully wrote leader information: Leader={}, session ID={}.", confirmedLeaderAddress, confirmedLeaderSessionID); } } catch (Exception e) { fatalErrorHandler.onFatalError( new KubernetesException("Could not write leader information since ConfigMap " + configMapName + " does not exist.", e)); } }
Source:
public static void main(String[] args) throws HTTPError, NoResultsFound, MultipleResultsFound { anced.configure("ak-test-aUV295IugdhWSNx2JFckYBCSvfY2ibgq"); BankAccount bankAccount = new BankAccount("/bank_accounts/BA1BnM6LmT9DLV4bZDIjUmHD"); Order order = new Order("/orders/OR1s2WQKp0shLH9Qb0LiUfEJ"); HashMap<String, Object> payload = new HashMap<String, Object>(); payload.put("amount", 5000); try { Credit credit = order.creditTo(bankAccount, payload); } catch (HTTPError e) }

Target:
public static void main(String[] args) throws HTTPError, NoResultsFound, MultipleResultsFound { Balanced.configure("ak-test-aUV295IugdhWSNx2JFckYBCSvfY2ibgq"); BankAccount bankAccount = new BankAccount("/bank_accounts/BA5KLH6jhFgtVENHXOcF3Cfj/credits"); Order order = new Order("/orders/OR5QcYnwysJXQswImokq6ZSx"); HashMap<String, Object> payload = new HashMap<String, Object>(); payload.put("amount", 5000); try { Credit credit = order.creditTo(bankAccount, payload); } catch (HTTPError e) }
Source:
private void updateNullCheckedResources(IfStatementTree tree, boolean value) { if (isRightSideNullCheck(tree)) { contentResources.replace(tree.condition().firstToken().text(), value); } else { contentResources.replace(tree.condition().lastToken().text(), value); } }

Target:
private void updateNullCheckedResources(IfStatementTree tree, boolean value) { boolean rightOperandIsNull = Kind.NULL_LITERAL.equals(tree.condition().lastToken().parent().kind()); SyntaxToken variable = rightOperandIsNull ? tree.condition().firstToken() : tree.condition().lastToken(); contentResources.replace(variable.text(), value); }
Source:
List<XmlSuite> extractSuitesFrom(File jarFile) { try { Utils.log("TestNG", 2, "Trying to open jar file:" + jarFile); List<String> classes = Lists.newArrayList(); boolean foundTestngXml = testngXmlExistsInJar(jarFile, classes); if (!foundTestngXml) { Utils.log("TestNG", 1, "Couldn't find the " + xmlPathInJar + " in the jar file, running all the classes"); XmlSuite suite = XmlSuiteUtils.newXmlSuiteUsing(classes); if (this.mode != null) { suite.setParallel(this.mode); } suites.add(suite); } } catch (IOException ex) { throw new TestNGException(ex); } return suites; }

Target:
List<XmlSuite> extractSuitesFrom(File jarFile) { try { Utils.log("TestNG", 2, "Trying to open jar file:" + jarFile); List<String> classes = Lists.newArrayList(); boolean foundTestngXml = testngXmlExistsInJar(jarFile, classes); if (!foundTestngXml) { Utils.log("TestNG", 1, "Couldn't find the " + xmlPathInJar + " in the jar file, running all the classes"); XmlSuite suite = XmlSuiteUtils.newXmlSuiteUsing(classes); suite.setParallel(this.mode); suites.add(suite); } } catch (IOException ex) { throw new TestNGException(ex); } return suites; }
Source:
public Iterable<Edge> getEdges(Direction direction, final String[] labels, FetchHints fetchHints, Authorizations authorizations) { getFetchHints().validateHasEdgeFetchHints(direction); return getGraph().getEdges(getEdgeIdsWithOtherVertexId(null, direction, labels, authorizations), fetchHints, authorizations); }

Target:
public Iterable<Edge> getEdges(Direction direction, final String[] labels, FetchHints fetchHints, Authorizations authorizations) { getFetchHints().validateHasEdgeFetchHints(direction, labels); return getGraph().getEdges(getEdgeIdsWithOtherVertexId(null, direction, labels, authorizations), fetchHints, authorizations); }
Source:
public void selectNextBestMatchingMilestone() { Optional<Integer> curSelectedIndex = getSelectedIndex(bestMatchingMilestones); if (!canIncreaseIndex(curSelectedIndex, bestMatchingMilestones)) return; selectMilestoneAtIndex(bestMatchingMilestones, curSelectedIndex.isPresent() ? curSelectedIndex.get() + 1 : 0); }

Target:
public void selectNextBestMatchingMilestone() { Optional<Integer> curSelectedIndex = getSelectedIndex(bestMatchingMilestones); if (!canIncreaseIndex(curSelectedIndex, bestMatchingMilestones)) return; selectMilestoneAtIndex(bestMatchingMilestones, curSelectedIndex.orElse(-1) + 1); }
Source:
public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { Image image = getImage(); FontMetrics fontMetrics = gc.getFontMetrics(); gc.drawImage(image, x, y); Rectangle bounds = image.getBounds(); int labelX = bounds.width + (int) fontMetrics.getAverageCharacterWidth(); return super.draw(gc, textWidget, color, labelX, y); }

Target:
public Point draw(GC gc, StyledText textWidget, Color color, int x, int y) { Image image = getImage(); FontMetrics fontMetrics = gc.getFontMetrics(); Rectangle bounds = image.getBounds(); int imageY = y; int deltaY = fontMetrics.getHeight() - bounds.height; if (deltaY > 0) { imageY = imageY + deltaY / 2; } gc.drawImage(image, x, imageY); int labelX = x + bounds.width + (int) fontMetrics.getAverageCharacterWidth(); return super.draw(gc, textWidget, color, labelX, y); }
Source:
public String toString() { StringBuilder result = new StringBuilder(); result.append("Hint.withText(\"" + hintText + "\")"); if (effort != 0) result.append(".withEffort(" + effort + ")"); if (links != null && !links.isEmpty()) result.append(".with(" + links + ")"); return result.toString(); }

Target:
public String toString() { StringBuilder result = new StringBuilder(); result.append("Hint.withText(\"" + hintTextPattern.getPattern() + "\")"); if (effort != 0) result.append(".withEffort(" + effort + ")"); if (links != null && !links.isEmpty()) result.append(".with(" + links + ")"); return result.toString(); }
Source:
protected IFile[] getChangedFiles() throws CoreException { Set<IFile> combined= new HashSet<>(); combined.addAll(Arrays.asList(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()))); if (fRenameSubpackages) { for (IPackageFragment packagefrag : JavaElementUtil.getPackageAndSubpackages(fPackage)) { combined.addAll(Arrays.asList(ResourceUtil.getFiles(packagefrag.getCompilationUnits()))); } } else { combined.addAll(Arrays.asList(ResourceUtil.getFiles(fPackage.getCompilationUnits()))); } if (fQualifiedNameSearchResult != null) combined.addAll(Arrays.asList(fQualifiedNameSearchResult.getAllFiles())); return combined.toArray(new IFile[combined.size()]); }

Target:
protected IFile[] getChangedFiles() throws CoreException { Set<IFile> combined= new HashSet<>(); combined.addAll(Arrays.asList(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()))); if (fRenameSubpackages) { for (IPackageFragment pack : JavaElementUtil.getPackageAndSubpackages(fPackage)) { combined.addAll(Arrays.asList(ResourceUtil.getFiles(pack.getCompilationUnits()))); } } else { combined.addAll(Arrays.asList(ResourceUtil.getFiles(fPackage.getCompilationUnits()))); } if (fQualifiedNameSearchResult != null) combined.addAll(Arrays.asList(fQualifiedNameSearchResult.getAllFiles())); return combined.toArray(new IFile[combined.size()]); }
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { final ArrayList<Song> songs = getArguments().getParcelableArrayList("songs"); int title; CharSequence content; if (songs.size() > 1) { title = R.string.delete_songs_title; content = Html.fromHtml(getString(R.string.delete_x_songs, songs.size())); } else { title = R.string.delete_song_title; content = Html.fromHtml(getString(R.string.delete_song_x, songs.get(0).title)); } return new MaterialDialog.Builder(getActivity()) .title(title) .content(content) .positiveText(R.string.delete_action) .negativeText(android.R.string.cancel) .autoDismiss(false) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { Activity activity = getActivity(); if (activity == null) return; songsToRemove = songs; if (!SAFUtil.isSAFRequiredForSongs(songs)) { deleteSongs(songs, null); dismiss(); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (SAFUtil.isSDCardAccessGranted(activity)) { deleteSongs(songs, null); dismiss(); } else { startActivityForResult(new Intent(getActivity(), SAFGuideActivity.class), SAFGuideActivity.REQUEST_CODE_SAF_GUIDE); } } else { deleteSongsKitkat(); } } } }) .build(); }

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { final ArrayList<Song> songs = getArguments().getParcelableArrayList("songs"); int title; CharSequence content; if (songs.size() > 1) { title = R.string.delete_songs_title; content = Html.fromHtml(getString(R.string.delete_x_songs, songs.size())); } else { title = R.string.delete_song_title; content = Html.fromHtml(getString(R.string.delete_song_x, songs.get(0).title)); } return new MaterialDialog.Builder(getActivity()) .title(title) .content(content) .positiveText(R.string.delete_action) .negativeText(android.R.string.cancel) .autoDismiss(false) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { songsToRemove = songs; new DeleteSongsAsyncTask(DeleteSongsDialog.this).execute(new DeleteSongsAsyncTask.LoadingInfo(songs, null)); } }) .onNegative(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) { dismiss(); } }) .build(); }
Source:
public static List<Pair<String, String[]>> sqlList(List<Integer> input, int maxArgs) { List<Pair<String, String[]>> ops = new ArrayList<Pair<String, String[]>>(); int numIterations = (int)Math.ceil(((double)input.size()) / maxArgs); for(int currentRound = 0 ; currentRound < numIterations ; ++currentRound) { int startPoint = currentRound * maxArgs; int lastIndex = Math.min((currentRound + 1) * maxArgs, input.size()); String ret = "("; for(int i = startPoint ; i < lastIndex ; ++i) { ret += "?" + ","; } String[] array = new String[lastIndex - startPoint]; int count = 0 ; for(int i = startPoint ; i < lastIndex ; ++i) { array[count++] = String.valueOf(input.get(i)); } ops.add(new Pair<String, String[]>(ret.substring(0, ret.length()-1) + ")", array)); } return ops; }

Target:
public static List<Pair<String, String[]>> sqlList(List<Integer> input, int maxArgs) { List<Pair<String, String[]>> ops = new ArrayList<Pair<String, String[]>>(); int numIterations = (int)Math.ceil(((double)input.size()) / maxArgs); for(int currentRound = 0 ; currentRound < numIterations ; ++currentRound) { int startPoint = currentRound * maxArgs; int lastIndex = Math.min((currentRound + 1) * maxArgs, input.size()); StringBuilder stringBuilder = new StringBuilder("("); for(int i = startPoint ; i < lastIndex ; ++i) { stringBuilder.append("?,"); } String[] array = new String[lastIndex - startPoint]; int count = 0 ; for(int i = startPoint ; i < lastIndex ; ++i) { array[count++] = String.valueOf(input.get(i)); } ops.add(new Pair<>(stringBuilder.toString().substring(0, stringBuilder.toString().length()-1) + ")", array)); } return ops; }
Source:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { AbstractWriteAttributeHandler writeAttribute = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES); for (AttributeDefinition attribute : ATTRIBUTES) { resourceRegistration.registerReadWriteAttribute(attribute, null, writeAttribute); } HAPolicySynchronizationStatusReadHandler.registerSlaveAttributes(resourceRegistration); }

Target:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { AbstractWriteAttributeHandler writeAttribute = new ActiveMQReloadRequiredHandlers.WriteAttributeHandler(ATTRIBUTES); for (AttributeDefinition attribute : ATTRIBUTES) { resourceRegistration.registerReadWriteAttribute(attribute, null, writeAttribute); } if(registerRuntime) { HAPolicySynchronizationStatusReadHandler.registerSlaveAttributes(resourceRegistration); } }
Source:
boolean isModified(String path) throws CorruptObjectException, IOException { DirCache dc = DirCache.read(repo); NameConflictTreeWalk tw = new NameConflictTreeWalk(repo); tw.reset(); tw.addTree(new DirCacheIterator(dc)); tw.addTree(new FileTreeIterator(repo.getWorkDir(), repo.getFS())); tw.setRecursive(true); tw.setFilter(PathFilter.create(path)); DirCacheIterator dcIt; WorkingTreeIterator wtIt; while(tw.next()) { dcIt = tw.getTree(0, DirCacheIterator.class); wtIt = tw.getTree(1, WorkingTreeIterator.class); if (dcIt==null || wtIt==null) return true; if (wtIt.isModified(dcIt.getDirCacheEntry(), true, config_filemode(), repo.getFS())) { return true; } } return false; }

Target:
private boolean isModified(String path) throws CorruptObjectException, IOException { DirCache dc = DirCache.read(repo); NameConflictTreeWalk tw = new NameConflictTreeWalk(repo); tw.reset(); tw.addTree(new DirCacheIterator(dc)); tw.addTree(new FileTreeIterator(repo.getWorkDir(), repo.getFS())); tw.setRecursive(true); tw.setFilter(PathFilter.create(path)); DirCacheIterator dcIt; WorkingTreeIterator wtIt; while(tw.next()) { dcIt = tw.getTree(0, DirCacheIterator.class); wtIt = tw.getTree(1, WorkingTreeIterator.class); if (dcIt == null || wtIt == null) return true; if (wtIt.isModified(dcIt.getDirCacheEntry(), true, config_filemode(), repo.getFS())) { return true; } } return false; }
Source:
protected void cleanup(Context context) throws IOException, InterruptedException{ String strNumOfRegions = PhoenixConfigurationUtil.getNumOfRegions(context.getConfiguration()); if (strNumOfRegions != null) { String fullTableName = PhoenixConfigurationUtil.getIndexToolDataTableName(context.getConfiguration()); final Properties overrideProps = new Properties(); try { final Connection connection = ConnectionUtil.getOutputConnection(context.getConfiguration(), overrideProps); int newNumRegions = regionCountForTesting != null ? regionCountForTesting : IndexUtil.getNumOfRegions(connection, fullTableName); int prevNumRegions = Integer.parseInt(strNumOfRegions); if (newNumRegions != prevNumRegions) { throw new IOException(String.format(SPLIT_MERGE_ERROR_STR_FMT, prevNumRegions, newNumRegions)); } } catch (SQLException e) { LOGGER.error("Failed get the number of regions"); throw new RuntimeException(e.getMessage()); } } try { IndexToolUtil.updateIndexState(context.getConfiguration(), PIndexState.ACTIVE); updateTasksTable(context); } catch (SQLException e) { LOGGER.error(" Failed to update the status to Active"); throw new RuntimeException(e.getMessage()); } }

Target:
protected void cleanup(Context context) throws IOException, InterruptedException{ if (PhoenixConfigurationUtil.getFailOnRegionNumChange(context.getConfiguration())) { String strNumOfRegions = PhoenixConfigurationUtil.getNumOfRegions(context.getConfiguration()); if (strNumOfRegions != null) { String fullTableName = PhoenixConfigurationUtil.getIndexToolDataTableName(context.getConfiguration()); final Properties overrideProps = new Properties(); try { final Connection connection = ConnectionUtil .getOutputConnection(context.getConfiguration(), overrideProps); if (splitRegionForTesting) { try (Admin admin = connection.unwrap(PhoenixConnection.class).getQueryServices().getAdmin()) { TableName tbl = TableName.valueOf(fullTableName); admin.split(tbl); admin.disableTable(tbl); admin.enableTable(tbl); } } int newNumRegions = IndexUtil.getRegions(connection, fullTableName).size(); int prevNumRegions = Integer.parseInt(strNumOfRegions); if (newNumRegions != prevNumRegions) { detectChangedRegions(connection, context, fullTableName); } } catch (SQLException e) { LOGGER.error("Failed get the number of regions"); throw new RuntimeException(e.getMessage()); } } } try { IndexToolUtil.updateIndexState(context.getConfiguration(), PIndexState.ACTIVE); updateTasksTable(context); } catch (SQLException e) { LOGGER.error(" Failed to update the status to Active"); throw new RuntimeException(e.getMessage()); } }
Source:
public void onInventorySlotChanged(InventorySlotChangedEvent event, EntityRef entity) { EntityRef playerEntity = entity; EntityRef item = event.getNewItem(); if (playerEntity.hasComponent(LASTeamComponent.class) && item.hasComponent(BlockItemComponent.class)) { if (item.getComponent(BlockItemComponent.class).blockFamily.getURI().toString().equals(LASUtils.RED_FLAG_URI) && playerEntity.getComponent(LASTeamComponent.class).team.equals(LASUtils.RED_TEAM)) { worldProvider.setBlock(new Vector3i(LASUtils.CENTER_RED_BASE_POSITION.x, LASUtils.CENTER_RED_BASE_POSITION.y + 1, LASUtils.CENTER_RED_BASE_POSITION.z), blockManager.getBlock(LASUtils.RED_FLAG_URI)); inventoryManager.removeItem(playerEntity, EntityRef.NULL, item, true, 1); return; } if (item.getComponent(BlockItemComponent.class).blockFamily.getURI().toString().equals(LASUtils.BLACK_FLAG_URI) && playerEntity.getComponent(LASTeamComponent.class).team.equals(LASUtils.BLACK_TEAM)) { worldProvider.setBlock(new Vector3i(LASUtils.CENTER_BLACK_BASE_POSITION.x, LASUtils.CENTER_BLACK_BASE_POSITION.y + 1, LASUtils.CENTER_BLACK_BASE_POSITION.z), blockManager.getBlock(LASUtils.BLACK_FLAG_URI)); inventoryManager.removeItem(playerEntity, EntityRef.NULL, item, true, 1); return; } } }

Target:
public void onInventorySlotChanged(InventorySlotChangedEvent event, EntityRef entity) { EntityRef playerEntity = entity; moveFlagToBaseIfPickedBySameTeamPlayer(event, playerEntity); }
Source:
public Map<String, Map<String, Message>> getStaleMessageCache() { for (String instanceName : _staleMessageCache.keySet()) { for (String messageId : _staleMessageCache.get(instanceName).keySet()) { if (!_messageCache.getOrDefault(instanceName, Collections.emptyMap()) .containsKey(messageId)) { _staleMessageCache.get(instanceName).remove(messageId); if (_staleMessageCache.get(instanceName).size() == 0) { _staleMessageCache.remove(instanceName); } } } } return _staleMessageCache; }

Target:
public Map<String, Map<String, Message>> getStaleMessageCache() { return _staleMessageCache; }
Source:
public CaseNameRewriter() { this.upperCase = true; }

Target:
public CaseNameRewriter() { this(true); }
Source:
public Flux<Frame> resend(int remotePosition) { updateRemotePosition(remotePosition); if (remotePosition == currentPosition) { return Flux.empty(); } List<Frame> resend = new ArrayList<>(); Iterator<Map.Entry<Integer, Frame>> positions = frames.entrySet().iterator(); while (positions.hasNext()) { Map.Entry<Integer, Frame> cachePosition = positions.next(); if (remotePosition < cachePosition.getKey()) { resend.add(cachePosition.getValue().retain()); } } return Flux.fromIterable(resend); }

Target:
public Flux<Frame> resend(int remotePosition) { updateRemotePosition(remotePosition); if (remotePosition == currentPosition) { return Flux.empty(); } List<Frame> resend = new ArrayList<>(); Iterator<Map.Entry<Integer, Frame>> positions = frames.entrySet().iterator(); while (positions.hasNext()) { Map.Entry<Integer, Frame> cachePosition = positions.next(); if (remotePosition < cachePosition.getKey()) { resend.add(cachePosition.getValue()); } } return Flux.fromIterable(resend); }
Source:
public AbstractVisitor(String name, Context context) { this.context = context; this.currentDefinition = null; this.currentModule = null; this.kompileOptions = context == null ? null : context.kompileOptions; this.globalOptions = context == null ? null : context.globalOptions; this.name = name; }

Target:
public AbstractVisitor(String name, Context context) { this(name, context, null, null); }
Source:
public static SCM parseSCM(StaplerRequest req, AbstractProject target) throws FormException, ServletException { SCM scm = SCM.all().newInstanceFromRadioList(req.getSubmittedForm().getJSONObject("scm")); if (scm == null) { scm = new NullSCM(); } scm.getDescriptor().generation.incrementAndGet(); return scm; }

Target:
public static SCM parseSCM(StaplerRequest req, AbstractProject target) throws FormException, ServletException { SCM scm = SCM.all().newInstanceFromRadioList(req.getSubmittedForm().getJSONObject("scm")); if (scm == null) { scm = new NullSCM(); } scm.getDescriptor().incrementGeneration(); return scm; }
Source:
public void whenMoreThanOneCursorPerPartitionThenException() throws Exception { subscriptionBase.setInitialCursors(ImmutableList.of( new SubscriptionCursorWithoutToken(ET1, P0, ""), new SubscriptionCursorWithoutToken(ET2, P0, ""), new SubscriptionCursorWithoutToken(ET3, P0, "a"), new SubscriptionCursorWithoutToken(ET3, P0, "b") )); try { subscriptionValidationService.validateSubscription(subscriptionBase, client); fail("WrongInitialCursorsException expected"); } catch (final WrongInitialCursorsException e) { assertThat(e.getMessage(), equalTo("there should be not more than 1 cursor for each partition in initial_cursors")); } }

Target:
public void whenMoreThanOneCursorPerPartitionThenException() throws Exception { subscriptionBase.setInitialCursors(ImmutableList.of( new SubscriptionCursorWithoutToken(ET1, P0, ""), new SubscriptionCursorWithoutToken(ET2, P0, ""), new SubscriptionCursorWithoutToken(ET3, P0, "a"), new SubscriptionCursorWithoutToken(ET3, P0, "b") )); try { subscriptionValidationService.validateSubscription(subscriptionBase, client); fail("WrongInitialCursorsException expected"); } catch (final WrongInitialCursorsException e) { assertThat(e.getMessage(), equalTo("there should be no more than 1 cursor for each partition in initial_cursors")); } }
Source:
protected <T> void notifyTransactionObservers(List<ObserverMethod<? super T>> observers, T event, EventMetadata metadata, final ObserverExceptionHandler handler) { if (observers.isEmpty()) { return; } if (transactionServices == null || !transactionServices.isTransactionActive()) { notifySyncObservers(observers, event, metadata, handler); } else { List<DeferredEventNotification<?>> notifications = new ArrayList<DeferredEventNotification<?>>(); for (ObserverMethod<? super T> observer : observers) { deferNotification(event, metadata, observer, notifications); } try { transactionServices.registerSynchronization(new TransactionNotificationSynchronization(notifications)); } catch (Exception e) { if (e.getCause() instanceof RollbackException || e.getCause() instanceof IllegalStateException) { List<ObserverMethod<? super T>> filteredObservers = observers.stream() .filter(observerMethod -> !observerMethod.getTransactionPhase().equals(TransactionPhase.AFTER_SUCCESS)).collect( Collectors.toList()); notifySyncObservers(filteredObservers, event, metadata, handler); } else { throw e; } } } }

Target:
protected <T> void notifyTransactionObservers(List<ObserverMethod<? super T>> observers, T event, EventMetadata metadata, final ObserverExceptionHandler handler) { if (observers.isEmpty()) { return; } if (transactionServices == null || !transactionServices.isTransactionActive()) { notifySyncObservers(observers, event, metadata, handler); } else { List<DeferredEventNotification<?>> notifications = new ArrayList<DeferredEventNotification<?>>(); for (ObserverMethod<? super T> observer : observers) { deferNotification(event, metadata, observer, notifications); } try { transactionServices.registerSynchronization(new TransactionNotificationSynchronization(notifications)); } catch (Exception e) { if (e.getCause() instanceof RollbackException || e.getCause() instanceof IllegalStateException) { List<ObserverMethod<? super T>> filteredObservers = observers.stream() .filter(observerMethod -> !observerMethod.getTransactionPhase().equals(TransactionPhase.AFTER_SUCCESS)) .sorted((o1, o2) -> { return o2.getTransactionPhase().toString().compareTo(o1.getTransactionPhase().toString()); }) .collect(Collectors.toList()); notifySyncObservers(filteredObservers, event, metadata, handler); } else { throw e; } } } }
Source:
public void testIdleWithServer() throws Exception { Properties mailProps = new Properties(); mailProps.put("mail.debug", "true"); mailProps.put("mail.imap.connectionpool.debug", "true"); ImapMailReceiver receiver = new ImapMailReceiver("imap://user:pw@localhost:" + imapIdlePort + "/INBOX"); receiver.setJavaMailProperties(mailProps); receiver.setMaxFetchSize(1); receiver.setShouldDeleteMessages(false); receiver.setShouldMarkMessagesAsRead(true); receiver.setSearchTermStrategy(new SearchTermStrategy() { @Override public SearchTerm generateSearchTerm(Flags supportedFlags, Folder folder) { try { FromTerm fromTerm = new FromTerm(new InternetAddress("bar@baz")); AndTerm andTerm = new AndTerm(fromTerm, new FlagTerm(new Flags(Flags.Flag.SEEN), false)); return andTerm; } catch (AddressException e) { throw new RuntimeException(e); } } }); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); setUpScheduler(receiver, taskScheduler); receiver.afterPropertiesSet(); Log logger = spy(TestUtils.getPropertyValue(receiver, "logger", Log.class)); new DirectFieldAccessor(receiver).setPropertyValue("logger", logger); doAnswer(new CallsRealMethods()).when(logger).debug("Canceling IDLE"); ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(receiver); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); adapter.setTaskScheduler(taskScheduler); adapter.setCancelIdleInterval(8); adapter.start(); assertNotNull(channel.receive(6000)); assertNotNull(channel.receive(6000)); assertNull(channel.receive(10000)); verify(logger).debug("Canceling IDLE"); taskScheduler.shutdown(); }

Target:
public void testIdleWithServer() throws Exception { Properties mailProps = new Properties(); mailProps.put("mail.debug", "true"); mailProps.put("mail.imap.connectionpool.debug", "true"); ImapMailReceiver receiver = new ImapMailReceiver("imap://user:pw@localhost:" + imapIdlePort + "/INBOX"); receiver.setJavaMailProperties(mailProps); receiver.setMaxFetchSize(1); receiver.setShouldDeleteMessages(false); receiver.setShouldMarkMessagesAsRead(true); receiver.setSearchTermStrategy(new SearchTermStrategy() { @Override public SearchTerm generateSearchTerm(Flags supportedFlags, Folder folder) { try { FromTerm fromTerm = new FromTerm(new InternetAddress("bar@baz")); AndTerm andTerm = new AndTerm(fromTerm, new FlagTerm(new Flags(Flags.Flag.SEEN), false)); return andTerm; } catch (AddressException e) { throw new RuntimeException(e); } } }); receiver.setCancelIdleInterval(8); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); setUpScheduler(receiver, taskScheduler); receiver.afterPropertiesSet(); Log logger = spy(TestUtils.getPropertyValue(receiver, "logger", Log.class)); new DirectFieldAccessor(receiver).setPropertyValue("logger", logger); ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(receiver); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); adapter.setTaskScheduler(taskScheduler); adapter.start(); assertNotNull(channel.receive(6000)); assertNotNull(channel.receive(6000)); assertNull(channel.receive(10000)); verify(logger).debug("Canceling IDLE"); taskScheduler.shutdown(); }
Source:
private void deleteTempPacksIdx() { Path packDir = Paths.get(repo.getObjectsDirectory().getAbsolutePath(), "pack"); long threshold = Instant.now().toEpochMilli() - 24 * 60 * 60 * 1000; try { Files.newDirectoryStream(packDir, "gc_*_tmp") .forEach(t -> { try { long lastModified = Files.getLastModifiedTime(t) .toMillis(); if (lastModified < threshold) { Files.deleteIfExists(t); } } catch (IOException e) { LOG.error(e.getMessage(), e); } }); } catch (IOException e) { LOG.error(e.getMessage(), e); } }

Target:
private void deleteTempPacksIdx() { Path packDir = Paths.get(repo.getObjectsDirectory().getAbsolutePath(), "pack"); Instant threshold = Instant.now().minus(1, ChronoUnit.DAYS); try { Files.newDirectoryStream(packDir, "gc_*_tmp") .forEach(t -> { try { Instant lastModified = Files.getLastModifiedTime(t) .toInstant(); if (lastModified.isBefore(threshold)) { Files.deleteIfExists(t); } } catch (IOException e) { LOG.error(e.getMessage(), e); } }); } catch (IOException e) { LOG.error(e.getMessage(), e); } }
Source:
protected boolean doPoll(String sha1) { if (observer != null) { observer.setListener(listener); observer.checkAndNotify(); observer.removeListener(); return true; } else { return isMatched(null, null, null); } }

Target:
protected boolean doPoll(String sha1) { if (observer != null) { observer.setListener(listener); observer.checkAndNotify(); observer.removeListener(); return true; } else { return false; } }
Source:
public Optional<UUID> addGroup(String groupName) { if (!groupExists(groupName)) { String trimmedName = groupName.trim(); UUID groupUUIDuuid = UUID.randomUUID(); RepositoryGroup group = new RepositoryGroup(groupUUIDuuid, trimmedName); groupMap.put(groupUUIDuuid, group); savePreferences(); return Optional.of(groupUUIDuuid); } return Optional.empty(); }

Target:
public UUID addGroup(String groupName) { if (!groupExists(groupName)) { String trimmedName = groupName.trim(); UUID groupId = UUID.randomUUID(); RepositoryGroup group = new RepositoryGroup(groupId, trimmedName); groupMap.put(groupId, group); savePreferences(); return groupId; } else { throw new IllegalStateException( UIText.RepositoriesView_RepoGroup_GroupExists); } }
Source:
public QueryPlan optimize(QueryPlan dataPlan, PhoenixStatement statement, List<? extends PDatum> targetColumns, ParallelIteratorFactory parallelIteratorFactory) throws SQLException { List<QueryPlan> plans = getApplicablePlans(dataPlan, statement, targetColumns, parallelIteratorFactory, false); if (plans.size() == 1) { return plans.get(0); } Cost minCost = null; QueryPlan bestPlan = null; for (QueryPlan plan : plans) { Cost cost = plan.getCost(); if (minCost == null || cost.compareTo(minCost) < 0) { minCost = cost; bestPlan = plan; } } return bestPlan; }

Target:
public QueryPlan optimize(QueryPlan dataPlan, PhoenixStatement statement, List<? extends PDatum> targetColumns, ParallelIteratorFactory parallelIteratorFactory) throws SQLException { List<QueryPlan> plans = getApplicablePlans(dataPlan, statement, targetColumns, parallelIteratorFactory, true); return plans.get(0); }
Source:
public void assertDoesNotEndWith(AssertionInfo info, CharSequence actual, CharSequence suffix) { if (suffix == null) throw new NullPointerException("The given suffix should not be null"); assertNotNull(info, actual); if (comparisonStrategy.stringEndsWith(actual.toString(), suffix.toString())) throw failures.failure(info, shouldNotEndWith(actual, suffix, comparisonStrategy)); }

Target:
public void assertDoesNotEndWith(AssertionInfo info, CharSequence actual, CharSequence suffix) { failIfSuffixIsNull(suffix); assertNotNull(info, actual); if (comparisonStrategy.stringEndsWith(actual.toString(), suffix.toString())) throw failures.failure(info, shouldNotEndWith(actual, suffix, comparisonStrategy)); }
Source:
public void recordActivityCreation(final ActivityType entity, final long activityId, final short symbolId, final SourceSection sourceSection, final Activity current) { int requiredSpace = entity.getCreationSize(); ensureSufficientSpace(requiredSpace, current); final int start = position; assert entity.getCreationMarker() != 0; put(entity.getCreationMarker()); putLong(activityId); putShort(symbolId); if (VmSettings.TRUFFLE_DEBUGGER_ENABLED || VmSettings.KOMPOS_TRACING) { writeSourceSection(sourceSection); } assert position == start + requiredSpace; }

Target:
public void recordActivityCreation(final ActivityType entity, final long activityId, final short symbolId, final SourceSection sourceSection, final Activity current) { int requiredSpace = entity.getCreationSize(); ensureSufficientSpace(requiredSpace, current); final int start = position; assert entity.getCreationMarker() != 0; put(entity.getCreationMarker()); putLong(activityId); putShort(symbolId); if (VmSettings.KOMPOS_TRACING) { writeSourceSection(sourceSection); } assert position == start + requiredSpace; }
Source:
public Component resolve(final MarkupContainer container, final MarkupStream markupStream, final ComponentTag tag) { if (!tag.getId().startsWith(LABEL_ATTR)) { return null; } final String path = tag.getAttribute(getWicketNamespace(markupStream) + WICKET_FOR).trim(); Component component = findRelatedComponent(container, path); if (component == null) { throw new ComponentNotFoundException("Could not find form component with id '" + path + "' while trying to resolve wicket:for attribute"); } if (component instanceof ILabelProviderLocator) { component = ((ILabelProviderLocator) component).getAutoLabelComponent(); } if (!(component instanceof ILabelProvider)) { throw new WicketRuntimeException("Component pointed to by wicket:for attribute '" + path + "' does not implement " + ILabelProvider.class.getName()); } if (!component.getOutputMarkupId()) { component.setOutputMarkupId(true); if (component.hasBeenRendered()) { logger.warn( "Component: is referenced via a wicket:for attribute but does not have its outputMarkupId property set to true", component.toString(false)); } } if (component instanceof FormComponent) { component.setMetaData(MARKER_KEY, new AutoLabelMarker((FormComponent<?>)component)); } return new AutoLabel(tag.getId(), component); }

Target:
public Component resolve(final MarkupContainer container, final MarkupStream markupStream, final ComponentTag tag) { if (!tag.getId().startsWith(LABEL_ATTR)) { return null; } final String path = tag.getAttribute(getWicketNamespace(markupStream) + WICKET_FOR).trim(); Component component = findRelatedComponent(container, path); if (component == null) { throw new ComponentNotFoundException("Could not find form component with path '" + path + "' while trying to resolve wicket:for attribute"); } if (component instanceof ILabelProviderLocator) { component = ((ILabelProviderLocator) component).getAutoLabelComponent(); } if (!(component instanceof ILabelProvider)) { throw new WicketRuntimeException("Component pointed to by wicket:for attribute '" + path + "' does not implement " + ILabelProvider.class.getName()); } if (!component.getOutputMarkupId()) { component.setOutputMarkupId(true); if (component.hasBeenRendered()) { logger.warn( "Component: is referenced via a wicket:for attribute but does not have its outputMarkupId property set to true", component.toString(false)); } } if (component instanceof FormComponent) { component.setMetaData(MARKER_KEY, new AutoLabelMarker((FormComponent<?>)component)); } return new AutoLabel(tag.getId(), component); }
Source:
public static void addNewTablet(ServerContext context, KeyExtent extent, String path, TServerInstance location, Map<FileRef,DataFileValue> datafileSizes, Map<Long,? extends Collection<FileRef>> bulkLoadedFiles, String time, long lastFlushID, long lastCompactID, ZooLock zooLock) { TabletMutator mutator = context.getAmple().mutateTablet(extent); mutator.putPrevEndRow(extent.getPrevEndRow()); mutator.putZooLock(zooLock); mutator.putDir(path); mutator.putTime(time); if (lastFlushID > 0) mutator.putFlushId(lastFlushID); if (lastCompactID > 0) mutator.putCompactionId(lastCompactID); if (location != null) { mutator.putLocation(location, LocationType.CURRENT); mutator.deleteLocation(location, LocationType.FUTURE); } for (Entry<FileRef,DataFileValue> entry : datafileSizes.entrySet()) { mutator.putFile(entry.getKey(), entry.getValue()); } for (Entry<Long,? extends Collection<FileRef>> entry : bulkLoadedFiles.entrySet()) { for (FileRef ref : entry.getValue()) { mutator.putBulkFile(ref, entry.getKey().longValue()); } } mutator.mutate(); }

Target:
public static void addNewTablet(ServerContext context, KeyExtent extent, String path, TServerInstance location, Map<FileRef,DataFileValue> datafileSizes, Map<Long,? extends Collection<FileRef>> bulkLoadedFiles, String time, long lastFlushID, long lastCompactID, ZooLock zooLock) { TabletMutator mutator = context.getAmple().mutateTablet(extent); mutator.putPrevEndRow(extent.getPrevEndRow()); mutator.putZooLock(zooLock); mutator.putDir(path); mutator.putTime(time); if (lastFlushID > 0) mutator.putFlushId(lastFlushID); if (lastCompactID > 0) mutator.putCompactionId(lastCompactID); if (location != null) { mutator.putLocation(location, LocationType.CURRENT); mutator.deleteLocation(location, LocationType.FUTURE); } datafileSizes.forEach(mutator::putFile); for (Entry<Long,? extends Collection<FileRef>> entry : bulkLoadedFiles.entrySet()) { for (FileRef ref : entry.getValue()) { mutator.putBulkFile(ref, entry.getKey().longValue()); } } mutator.mutate(); }
Source:
public void addingAStudentAddsThemToTheSortedRoster() { School school = new School(); school.add("Aimee", 2); String[] expected = {"Aimee"}; assertArrayEquals(expected, school.roster().toArray(new String[0])); }

Target:
public void addingAStudentAddsThemToTheSortedRoster() { school = new School(); school.add("Aimee", 2); List<String> expected = Arrays.asList("Aimee"); assertThat(school.roster(), is(expected)); }
Source:
public void shouldCallActivityNotifier() throws IOException, ServletException { filter.doFilter(request, response, chain); verify(workspaceActivityNotifier).onActivity(); }

Target:
public void shouldCallActivityNotifier() throws IOException, ServletException { filter.doFilter(request, response, chain); verify(workspaceActivityNotifier).onActivity(); verify(chain).doFilter(request, response); }
Source:
public void fileIsOpenWhenUsingAFileOutputStream() throws IOException { File file = FileUtils.newFile(TEST_FILE); assertThat(FileUtils.isFileOpen(file), is(false)); FileOutputStream outputStream = new FileOutputStream(file); assertThat(FileUtils.isFileOpen(file), is(true)); outputStream.close(); assertThat(FileUtils.isFileOpen(file), is(false)); }

Target:
public void fileIsOpenWhenUsingAFileOutputStream() throws IOException { File file = newFile(TEST_FILE); assertThat(isFileOpen(file), is(false)); FileOutputStream outputStream = new FileOutputStream(file); assertThat(isFileOpen(file), is(true)); outputStream.close(); assertThat(isFileOpen(file), is(false)); }
Source:
Set<Artifact> resolveProjectArtifacts(MavenProject project, Configuration config) throws MojoExecutionException { final LinkedHashSet<Artifact> allArtifacts = new LinkedHashSet<>(resolveArtifacts(project.getArtifacts(), config.dependencyFilter, null, config.verifyPomFiles, false)); if (config.verifyPlugins) { allArtifacts.addAll(resolveArtifacts(project.getPluginArtifacts(), config.pluginFilter, config.dependencyFilter, config.verifyPomFiles, config.verifyPluginDependencies)); allArtifacts.addAll(resolveArtifacts(project.getReportArtifacts(), config.pluginFilter, config.dependencyFilter, config.verifyPomFiles, config.verifyPluginDependencies)); allArtifacts.addAll(resolveArtifacts(project.getBuildPlugins().stream() .flatMap(p -> p.getDependencies().stream()) .map(repositorySystem::createDependencyArtifact) .collect(Collectors.toList()), config.dependencyFilter, config.dependencyFilter, config.verifyPomFiles, config.verifyPluginDependencies)); } if (config.verifyAtypical) { allArtifacts.addAll(resolveArtifacts(searchCompilerAnnotationProcessors(project), config.dependencyFilter, config.dependencyFilter, config.verifyPomFiles, config.verifyPluginDependencies)); } log.debug("Discovered project artifacts: " + allArtifacts); return allArtifacts; }

Target:
Set<Artifact> resolveProjectArtifacts(MavenProject project, Configuration config) throws MojoExecutionException { final LinkedHashSet<Artifact> allArtifacts = new LinkedHashSet<>(resolveArtifacts(project.getArtifacts(), config.dependencyFilter, null, config.verifyPomFiles, false)); if (config.verifyPlugins) { for (final Plugin plugin : project.getBuildPlugins()) { final LinkedHashSet<Artifact> artifacts = new LinkedHashSet<>(); artifacts.add(repositorySystem.createPluginArtifact(plugin)); artifacts.addAll(plugin.getDependencies().stream() .map(repositorySystem::createDependencyArtifact) .collect(Collectors.toSet())); final Set<Artifact> resolved = resolveArtifacts(artifacts, config.pluginFilter, config.dependencyFilter, config.verifyPomFiles, config.verifyPluginDependencies); if (log.isDebugEnabled()) { log.debug("Build plugin dependencies for " + plugin.getGroupId() + ":" + plugin.getArtifactId() + ":" + plugin.getVersion() + " " + resolved); } allArtifacts.addAll(resolved); } for (final Artifact plugin : project.getReportArtifacts()) { final Set<Artifact> resolved = resolveArtifacts(singleton(plugin), config.pluginFilter, config.dependencyFilter, config.verifyPomFiles, config.verifyPluginDependencies); if (log.isDebugEnabled()) { log.debug("Report plugin dependencies for " + plugin.getGroupId() + ":" + plugin.getArtifactId() + ":" + plugin.getVersion() + " " + resolved); } allArtifacts.addAll(resolved); } } if (config.verifyAtypical) { allArtifacts.addAll(resolveArtifacts(searchCompilerAnnotationProcessors(project), config.dependencyFilter, config.dependencyFilter, config.verifyPomFiles, config.verifyPluginDependencies)); } return allArtifacts; }
Source:
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) { Span spanFromHeader = getSpanFromHeader(message); getTracer().continueSpan(spanFromHeader); Span continuedSpan = getTracer().getCurrentSpan(); if (containsServerReceived(continuedSpan)) { continuedSpan.logEvent(Span.SERVER_SEND); } else if (spanFromHeader != null) { continuedSpan.logEvent(Span.CLIENT_RECV); } addErrorTag(ex); getTracer().close(continuedSpan); }

Target:
public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) { Span currentSpan = getTracer().getCurrentSpan(); if (containsServerReceived(currentSpan)) { currentSpan.logEvent(Span.SERVER_SEND); } else if (currentSpan != null) { currentSpan.logEvent(Span.CLIENT_RECV); } addErrorTag(ex); getTracer().close(currentSpan); }
Source:
public void test() throws Exception { container.start(SERVER_CONFIG, true); try { ManagementClient client = container.getClient(); ModelNode rr = Util.createEmptyOperation(READ_RESOURCE_OPERATION, PathAddress.EMPTY_ADDRESS); rr.get(INCLUDE_RUNTIME).set(true); rr.get(RECURSIVE).set(true); ModelNode result = client.executeForResult(rr); Assert.assertTrue(result.hasDefined(SUBSYSTEM, "messaging-activemq")); Assert.assertTrue(result.hasDefined(SUBSYSTEM, "jgroups")); client.executeForResult(rr); } finally { container.stop(); } }

Target:
public void test() throws Exception { container.start(SERVER_CONFIG, false); try { ManagementClient client = container.getClient(); ModelNode rr = Util.createEmptyOperation(READ_RESOURCE_OPERATION, PathAddress.EMPTY_ADDRESS); rr.get(INCLUDE_RUNTIME).set(true); rr.get(RECURSIVE).set(true); ModelNode result = client.executeForResult(rr); Assert.assertTrue(result.hasDefined(SUBSYSTEM, "messaging-activemq")); Assert.assertTrue(result.hasDefined(SUBSYSTEM, "jgroups")); container.reload(); client.executeForResult(rr); } finally { container.stop(); } }
Source:
private boolean insertDefaultAccountsTablesContent(Connection conn) { Statement stmt = null; try { stmt = conn.createStatement(); for (Account.Type type : Account.Type.PREDEFINED_ACCOUNT_TYPES) { int correlationTypeId = getCorrelationTypeIdForAccountType(conn, type); if (correlationTypeId > 0) { String sqlString = String.format("INSERT INTO account_types (type_name, display_name, correlation_type_id) VALUES ('%s', '%s', %d)" + getOnConflictDoNothingClause(selectedPlatform), type.getTypeName(), type.getDisplayName(), correlationTypeId); stmt.execute(sqlString); } } } catch (SQLException ex) { LOGGER.log(Level.SEVERE, String.format("Failed to populate default data in Accounts tables."), ex); return false; } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ex2) { LOGGER.log(Level.SEVERE, "Error closing statement.", ex2); } } } return true; }

Target:
private boolean insertDefaultAccountsTablesContent(Connection conn) { try (Statement stmt = conn.createStatement()) { for (Account.Type type : Account.Type.PREDEFINED_ACCOUNT_TYPES) { int correlationTypeId = getCorrelationTypeIdForAccountType(conn, type); if (correlationTypeId > 0) { String sqlString = String.format("INSERT INTO account_types (type_name, display_name, correlation_type_id) VALUES ('%s', '%s', %d)" + getOnConflictDoNothingClause(selectedPlatform), type.getTypeName(), type.getDisplayName(), correlationTypeId); stmt.execute(sqlString); } } } catch (SQLException ex) { LOGGER.log(Level.SEVERE, String.format("Failed to populate default data in Accounts tables."), ex); return false; } return true; }
Source:
public static TmfProjectElement getFilledProject() throws CoreException { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(PROJECT_NAME); if (!project.exists()) { project.create(null); } project.open(null); IFolder folder = project.getFolder(TmfTraceFolder.TRACE_FOLDER_NAME); if (!folder.exists()) { folder.create(true, true, null); } File file = new File(PATH); String path = file.getAbsolutePath(); final IPath pathString = Path.fromOSString(path); IResource linkedTrace = TmfImportHelper.createLink(folder, pathString, pathString.lastSegment()); if (!(linkedTrace != null && linkedTrace.exists())) { return null; } linkedTrace.setPersistentProperty(TmfCommonConstants.TRACETYPE, "org.eclipse.linuxtools.tmf.ui.type.ctf"); final TmfProjectElement projectElement = TmfProjectRegistry.getProject(project, true); TmfTraceElement traceElement = projectElement.getTracesFolder().getTraces().get(0); traceElement.refreshTraceType(); return projectElement; }

Target:
public static TmfProjectElement getFilledProject() throws CoreException { IProject project = TmfProjectRegistry.createProject(PROJECT_NAME, null, null); IFolder traceFolder = project.getFolder(TmfTraceFolder.TRACE_FOLDER_NAME); File file = new File(PATH); String path = file.getAbsolutePath(); final IPath pathString = Path.fromOSString(path); IResource linkedTrace = TmfImportHelper.createLink(traceFolder, pathString, pathString.lastSegment()); if (!(linkedTrace != null && linkedTrace.exists())) { return null; } linkedTrace.setPersistentProperty(TmfCommonConstants.TRACETYPE, "org.eclipse.linuxtools.tmf.ui.type.ctf"); final TmfProjectElement projectElement = TmfProjectRegistry.getProject(project, true); TmfTraceElement traceElement = projectElement.getTracesFolder().getTraces().get(0); traceElement.refreshTraceType(); return projectElement; }