Example usage for org.apache.commons.lang StringUtils substringAfterLast

List of usage examples for org.apache.commons.lang StringUtils substringAfterLast

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringAfterLast.

Prototype

public static String substringAfterLast(String str, String separator) 

Source Link

Document

Gets the substring after the last occurrence of a separator.

Usage

From source file:org.eclipse.buildship.docs.source.TypeNameResolver.java

/**
 * Resolves a source type name into a fully qualified type name.
 *//*from w w  w.  ja  v  a 2s.co  m*/
public String resolve(String name, ClassMetaData classMetaData) {
    if (primitiveTypes.contains(name)) {
        return name;
    }

    String candidateClassName;
    String[] innerNames = name.split("\\.");
    ClassMetaData pos = classMetaData;
    for (int i = 0; i < innerNames.length; i++) {
        String innerName = innerNames[i];
        candidateClassName = pos.getClassName() + '.' + innerName;
        if (!pos.getInnerClassNames().contains(candidateClassName)) {
            break;
        }
        if (i == innerNames.length - 1) {
            return candidateClassName;
        }
        pos = metaDataRepository.get(candidateClassName);
    }

    String outerClassName = classMetaData.getOuterClassName();
    while (outerClassName != null) {
        if (name.equals(StringUtils.substringAfterLast(outerClassName, "."))) {
            return outerClassName;
        }
        ClassMetaData outerClass = metaDataRepository.get(outerClassName);
        candidateClassName = outerClassName + '.' + name;
        if (outerClass.getInnerClassNames().contains(candidateClassName)) {
            return candidateClassName;
        }
        outerClassName = outerClass.getOuterClassName();
    }

    if (name.contains(".")) {
        return name;
    }

    for (String importedClass : classMetaData.getImports()) {
        String baseName = StringUtils.substringAfterLast(importedClass, ".");
        if (baseName.equals("*")) {
            candidateClassName = StringUtils.substringBeforeLast(importedClass, ".") + "." + name;
            if (metaDataRepository.find(candidateClassName) != null) {
                return candidateClassName;
            }
            if (importedClass.startsWith("java.") && isVisibleClass(candidateClassName)) {
                return candidateClassName;
            }
        } else if (name.equals(baseName)) {
            return importedClass;
        }
    }

    candidateClassName = classMetaData.getPackageName() + "." + name;
    if (metaDataRepository.find(candidateClassName) != null) {
        return candidateClassName;
    }

    candidateClassName = "java.lang." + name;
    if (isVisibleClass(candidateClassName)) {
        return candidateClassName;
    }

    if (classMetaData.isGroovy()) {
        candidateClassName = "java.math." + name;
        if (groovyImplicitTypes.contains(candidateClassName)) {
            return candidateClassName;
        }
        for (String prefix : groovyImplicitImportPackages) {
            candidateClassName = prefix + name;
            if (isVisibleClass(candidateClassName)) {
                return candidateClassName;
            }
        }
    }

    return name;
}

From source file:org.eclipse.jubula.client.api.converter.NodeInfo.java

/**
 * @param fqFileName the fully qualified file name
 * @param node the node//  ww w. j  a  v a2s. co  m
 * @param packageBasePath the base path of the package
 * @param defaultToolkit the default toolkit
 * @param language the project language
 */
public NodeInfo(String fqFileName, INodePO node, String packageBasePath, String defaultToolkit,
        Locale language) {
    m_fqFileName = fqFileName;
    m_fileName = StringUtils.substringBeforeLast(m_fqFileName, ".java"); //$NON-NLS-1$
    m_className = StringUtils.substringAfterLast(m_fileName, StringConstants.SLASH);
    m_node = node;
    m_packageBasePath = packageBasePath;
    m_defaultToolkit = defaultToolkit;
    m_language = language;

    Logger log = LoggerFactory.getLogger(NodeInfo.class);

    IProjectPO project = null;
    try {
        project = ProjectCache.get(node.getParentProjectId());
    } catch (JBException e) {
        Plugin.getDefault().writeErrorLineToConsole("Error while loading project.", true); //$NON-NLS-1$
    }

    try {
        m_projectName = Utils.translateToPackageName(project);
    } catch (InvalidNodeNameException e) {
        log.error(e.getLocalizedMessage());
    }
    m_fqName = Utils.getFullyQualifiedTranslatedName(node, m_packageBasePath, m_projectName);
    m_packageName = StringUtils.substringBeforeLast(m_fqName, StringConstants.DOT);

}

From source file:org.eclipse.jubula.tools.internal.utils.StringParsing.java

/**
 * Checks <code>str</code> for a sequence number, based on the 
 * <code>sequencePrefix</code>. If a sequence number is found, it is 
 * incremented, and the incremented string is returned. If no sequence is 
 * found, a new sequence is started, and the string with the newly started 
 * sequence is returned. Only positive integers are recognized as a 
 * valid sequence.//w w w  .  j a  va2 s .co  m
 * 
 * <pre>
 * StringParsing.incrementSequence("abc", "_")      = "abc_1"
 * StringParsing.incrementSequence("abc_5", "_")    = "abc_6"
 * StringParsing.incrementSequence("_2", "_")       = "_3"
 * StringParsing.incrementSequence("1", "_")        = "1_1"
 * StringParsing.incrementSequence("abc_-1", "_")   = "abc_-1_1"
 * StringParsing.incrementSequence("abc_0", "_")    = "abc_0_1"
 * StringParsing.incrementSequence("abc_1_1", "_")  = "abc_1_2"
 * </pre>
 * 
 * @param str The string for which the sequence should be incremented. 
 *            Must not be empty (<code>null</code> or empty string). 
 * @param sequencePrefix The string that precedes the sequence. Must not be 
 *                       empty (<code>null</code> or empty string).
 * @return a string that represents the given string <code>str</code> with
 *         the sequence number incremented.
 */
public static String incrementSequence(String str, String sequencePrefix) {

    Validate.notEmpty(str);
    Validate.notEmpty(sequencePrefix);

    StringBuffer builder = new StringBuffer(str);
    String suffix = StringUtils.substringAfterLast(str, "_"); //$NON-NLS-1$

    // parse suffix to integer and increment if possible.
    // if we can't parse it, then we just start a new sequence.
    int sequence = -1;
    try {
        sequence = Integer.parseInt(suffix);
        if (sequence > 0) {
            sequence++;
        }
    } catch (NumberFormatException nfe) {
        // Could not parse the suffix to an integer.
        // The sequence will remain at its initialized value.
    }

    if (sequence > 0) {
        builder.replace(builder.lastIndexOf(suffix), builder.length(), String.valueOf(sequence));
    } else {
        builder.append(sequencePrefix).append(1);
    }

    return builder.toString();
}

From source file:org.eclipse.mylyn.internal.gerrit.core.remote.GerritReviewRemoteFactoryTest.java

@Test
public void testDependencies() throws Exception {
    boolean isversion29OrLater = isVersion29OrLater();
    String changeIdDep1 = "I" + StringUtils.rightPad(System.currentTimeMillis() + "", 40, "a");
    CommitCommand commandDep1 = reviewHarness.createCommitCommand(changeIdDep1);
    reviewHarness.addFile("testFile1.txt", "test 2");
    CommitResult resultDep1 = reviewHarness.commitAndPush(commandDep1);
    String resultIdDep1 = StringUtils
            .trimToEmpty(StringUtils.substringAfterLast(resultDep1.push.getMessages(), "/"));
    assertThat("Bad Push: " + resultDep1.push.getMessages(), resultIdDep1.length(), greaterThan(0));

    TestRemoteObserverConsumer<IRepository, IReview, String, GerritChange, String, Date> consumerDep1 = retrieveForRemoteKey(
            reviewHarness.getProvider().getReviewFactory(), reviewHarness.getRepository(), resultIdDep1, true);
    IReview reviewDep1 = consumerDep1.getModelObject();

    assertThat(reviewDep1.getParents().size(), is(1));
    IChange parentChange = reviewDep1.getParents().get(0);
    //Not expected to be same instance
    assertThat(parentChange.getId(), is(getReview().getId()));
    assertThat(parentChange.getSubject(), is(getReview().getSubject()));
    if (isversion29OrLater) {
        //There s an offset ~ 1 sec, so no test for now
    } else {//from   w w w .j a  v  a  2s.  c  om
        assertThat(parentChange.getModificationDate().getTime(),
                is(getReview().getModificationDate().getTime()));
    }

    reviewHarness.retrieve();
    assertThat(getReview().getChildren().size(), is(1));
    IChange childChange = getReview().getChildren().get(0);
    //Not expected to be same instance
    assertThat(childChange.getId(), is(reviewDep1.getId()));
    assertThat(childChange.getSubject(), is(reviewDep1.getSubject()));
    if (isversion29OrLater) {
        //There s an offset ~ 1 sec, so no test for now
    } else {
        assertThat(childChange.getModificationDate().getTime(), is(reviewDep1.getModificationDate().getTime()));
    }
}

From source file:org.eclipse.mylyn.internal.gerrit.core.remote.GerritReviewRemoteFactoryTest.java

@Test
public void testGlobalCommentByGerrit() throws Exception {
    //create a new commit and Review that depends on Patch Set 1 of the existing Review
    String changeIdNewChange = ReviewHarness.generateChangeId();
    CommitCommand commandNewChange = reviewHarness.createCommitCommand(changeIdNewChange);
    reviewHarness.addFile("testFileNewChange.txt");
    CommitResult result = reviewHarness.commitAndPush(commandNewChange);
    String newReviewShortId = StringUtils
            .trimToEmpty(StringUtils.substringAfterLast(result.push.getMessages(), "/"));

    TestRemoteObserver<IRepository, IReview, String, Date> newReviewListener = new TestRemoteObserver<IRepository, IReview, String, Date>(
            reviewHarness.getProvider().getReviewFactory());

    RemoteEmfConsumer<IRepository, IReview, String, GerritChange, String, Date> newReviewConsumer = reviewHarness
            .getProvider().getReviewFactory()
            .getConsumerForRemoteKey(reviewHarness.getRepository(), newReviewShortId);
    newReviewConsumer.addObserver(newReviewListener);
    newReviewConsumer.retrieve(false);// w w w  .j  av a  2s  .c o  m
    newReviewListener.waitForResponse();

    reviewHarness.retrieve();
    IReview newReview = reviewHarness.getProvider().open(newReviewShortId);
    assertThat(newReview.getId(), is(newReviewShortId));

    assertThat(getReview().getChildren().size(), is(1));
    assertThat(getReview().getSets().size(), is(1));

    reviewHarness.checkoutPatchSet(1);

    //create Patch Set 2 for Review 1
    CommitCommand command2 = reviewHarness.createCommitCommand();
    reviewHarness.addFile("testFile3.txt");
    reviewHarness.commitAndPush(command2);
    reviewHarness.retrieve();
    List<IReviewItemSet> items = getReview().getSets();
    assertThat(items.size(), is(2));
    IReviewItemSet patchSet2 = items.get(1);
    assertThat(patchSet2.getReference(), endsWith("/2"));
    reviewHarness.assertIsRecent(patchSet2.getCreationDate());

    //now approve, publish and submit Review 2 - this should create a comment authored by Gerrit
    String approvalMessage = "approval, time: " + System.currentTimeMillis();
    HashSet<Id> approvals = new HashSet<ApprovalCategoryValue.Id>(
            Collections.singleton(CRVW.getValue((short) 2).getId()));
    reviewHarness.getAdminClient().publishComments(newReviewShortId, 1, approvalMessage, approvals,
            new NullProgressMonitor());
    reviewHarness.getAdminClient().submit(newReviewShortId, 1, new NullProgressMonitor());

    newReviewConsumer.retrieve(false);
    newReviewListener.waitForResponse();

    assertThat(newReview.getState(), is(ReviewStatus.SUBMITTED));

    List<IComment> comments = newReview.getComments();

    int offset = getCommentOffset();
    assertThat(comments.size(), is(offset + 2));

    IComment commentByGerrit = comments.get(offset + 1);

    if (isVersion29OrLater()) {
        assertNotNull(commentByGerrit.getAuthor());
        assertThat(commentByGerrit.getAuthor().getId(),
                is(String.valueOf(GerritSystemAccount.GERRIT_SYSTEM.getId())));
        assertThat(commentByGerrit.getAuthor().getDisplayName(), is(GerritSystemAccount.GERRIT_SYSTEM_NAME));
    } else {
        assertThat(commentByGerrit.getAuthor(), is(nullValue()));
    }

    assertThat(commentByGerrit.getDescription().substring(0, 58),
            is("Change cannot be merged due to unsatisfiable dependencies."));
}

From source file:org.eclipse.mylyn.internal.gerrit.core.remote.GerritReviewRemoteFactoryTest.java

@Test
public void testParentCommit() throws Exception {
    if (!isVersion28OrLater()) {
        return;/*from ww  w.j  a  va 2  s.co m*/
    }
    String changeIdNewChange = ReviewHarness.generateChangeId();
    CommitCommand commandNewChange = reviewHarness.createCommitCommand(changeIdNewChange);
    reviewHarness.addFile("testFileNewChange.txt");
    CommitResult result = reviewHarness.commitAndPush(commandNewChange);
    String newReviewShortId = StringUtils
            .trimToEmpty(StringUtils.substringAfterLast(result.push.getMessages(), "/"));

    TestRemoteObserver<IRepository, IReview, String, Date> newReviewListener = new TestRemoteObserver<IRepository, IReview, String, Date>(
            reviewHarness.getProvider().getReviewFactory());

    RemoteEmfConsumer<IRepository, IReview, String, GerritChange, String, Date> newReviewConsumer = reviewHarness
            .getProvider().getReviewFactory()
            .getConsumerForRemoteKey(reviewHarness.getRepository(), newReviewShortId);
    newReviewConsumer.addObserver(newReviewListener);
    newReviewConsumer.retrieve(false);
    newReviewListener.waitForResponse();

    reviewHarness.retrieve();
    IReview parentReview = getReview();
    IReview childReview = reviewHarness.getProvider().open(newReviewShortId);
    assertThat(childReview.getId(), is(newReviewShortId));

    assertThat(parentReview.getChildren().size(), is(1));
    assertThat(parentReview.getSets().size(), is(1));
    assertThat(childReview.getSets().size(), is(1));

    IReviewItemSet childPatchSet = childReview.getSets().get(0);
    IReviewItemSet parentPatchSet = parentReview.getSets().get(0);

    assertThat(childPatchSet.getParentCommits().size(), is(1));
    String parentCommitId = childPatchSet.getParentCommits().get(0).getId();
    assertThat(parentCommitId, is(parentPatchSet.getRevision()));
}

From source file:org.eclipse.mylyn.internal.gerrit.core.remote.GerritReviewRemoteFactoryTest.java

private boolean branchExists(String branchName) throws GerritException {
    BranchInfo[] branches = reviewHarness.getAdminClient().getRemoteProjectBranches("org.eclipse.mylyn.test",
            new NullProgressMonitor());
    for (BranchInfo branch : branches) {
        String branchRef = StringUtils.trimToEmpty(StringUtils.substringAfterLast(branch.getRef(), "/"));
        if (branchRef.equals(branchName)) {
            return true;
        }/*  w w w .  j a v  a 2s .  co m*/
    }
    return false;
}

From source file:org.eclipse.mylyn.internal.gerrit.core.remote.ReviewHarness.java

public void pushFileToReview(String refSpec, PrivilegeLevel privilegeLevel, String fileName) throws Exception {
    CommitCommand command = createCommitCommand(changeId);
    addFile(fileName);/*from w  ww.  j  a va  2s .c  o m*/
    CommitResult result = commitAndPush(command, refSpec, privilegeLevel);
    shortId = StringUtils.trimToEmpty(StringUtils.substringAfterLast(result.push.getMessages(), "/"));
    shortId = StringUtils.removeEnd(getShortId(), " [DRAFT]");
    commitId = result.commit.getId().toString();
    assertThat("Bad Push: " + result.push.getMessages(), getShortId().length(), greaterThan(0));
}

From source file:org.eclipse.mylyn.reviews.connector.ui.EmfRepositorySettingsPage.java

private void browse() {
    FileDialog browseDialog = new FileDialog(getShell(), SWT.OPEN);
    String fileName = null;/*  ww w. ja  va2 s . c o  m*/
    String filterPath;
    File currentLocation = new File(uriEditor.getText());
    if (currentLocation.exists()) {
        String currentPath = currentLocation.getAbsolutePath();
        if (currentLocation.isFile()) {
            filterPath = StringUtils.substringBeforeLast(currentPath, File.separator);
            fileName = StringUtils.substringAfterLast(currentPath, File.separator);
        } else {
            filterPath = currentPath;
        }
    } else {
        IPath configurationDir = ConfigurationScope.INSTANCE.getLocation();
        filterPath = configurationDir.toString();
    }
    browseDialog.setFilterPath(filterPath);
    if (fileName != null) {
        browseDialog.setFileName(fileName);
    }
    browseDialog.setFilterExtensions(getConnectorUi().getFileNameExtensions());
    String browseResult = browseDialog.open();
    if (browseResult != null) {
        uriEditor.setText(browseResult);
    }
}

From source file:org.eclipse.mylyn.reviews.connector.ui.EmfRepositorySettingsPage.java

private void create() {
    FileDialog browseDialog = new FileDialog(getShell(), SWT.SAVE);
    String fileName = null;/*from  w  ww  . j  a va 2  s . co  m*/
    String filterPath;
    File currentLocation = new File(uriEditor.getText());
    if (currentLocation.exists()) {
        String currentPath = currentLocation.getAbsolutePath();
        if (currentLocation.isFile()) {
            filterPath = StringUtils.substringBeforeLast(currentPath, File.separator);
            fileName = StringUtils.substringAfterLast(currentPath, File.separator);
        } else {
            filterPath = currentPath;
        }
    } else {
        IPath configurationDir = ConfigurationScope.INSTANCE.getLocation();
        filterPath = configurationDir.toString();
    }
    browseDialog.setFilterPath(filterPath);
    if (fileName == null) {
        fileName = StringUtils.deleteWhitespace(labelEditor.getText());
    }
    if (fileName != null) {
        browseDialog.setFileName(getQualifiedName(fileName));
    }
    browseDialog.setFilterExtensions(getConnectorUi().getFileNameExtensions());
    String browseResult = browseDialog.open();
    if (browseResult != null) {
        File checkFile = new File(browseResult);
        if (checkFile.exists()) {
            MessageDialog dialog = new MessageDialog(getShell(), "Replace Existing?", null,
                    checkFile.getName() + " already exists. Are you sure you want to replace it?",
                    MessageDialog.WARNING, new String[] { "Yes", "No" }, 1);
            int open = dialog.open();
            if (open == 1) {
                return;
            }
        }
        ResourceSet resourceSet = new ResourceSetImpl();
        URI fileURI = URI.createFileURI(browseResult);
        Resource resource = resourceSet.createResource(fileURI);
        EClass eContainingClass = getConnector().getContainerClass();
        EObject rootObject = eContainingClass.getEPackage().getEFactoryInstance().create(eContainingClass);
        if (rootObject != null) {
            resource.getContents().add(rootObject);
            rootObject.eSet(getConnector().getContentsNameAttribute(), labelEditor.getText());
            Map<Object, Object> options = new HashMap<Object, Object>();
            try {
                resource.save(options);
            } catch (IOException e) {
                StatusManager.getManager().handle(
                        new Status(IStatus.WARNING, EmfUiPlugin.PLUGIN_ID, "Couldn't create repository."));
                return;
            }
        }

        uriEditor.setText(browseResult);
    }
}