Example usage for org.apache.commons.lang3 StringUtils removeStart

List of usage examples for org.apache.commons.lang3 StringUtils removeStart

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils removeStart.

Prototype

public static String removeStart(final String str, final String remove) 

Source Link

Document

Removes a substring only if it is at the beginning of a source string, otherwise returns the source string.

A null source string will return null .

Usage

From source file:com.google.dart.engine.services.internal.correction.CorrectionUtils.java

/**
 * Indents given source left or right.//from  www .  ja v  a  2 s.co  m
 * 
 * @return the source with changed indentation.
 */
public String getIndentSource(String source, boolean right) {
    StringBuilder sb = new StringBuilder();
    String indent = getIndent(1);
    String eol = getEndOfLine();
    String[] lines = StringUtils.splitByWholeSeparatorPreserveAllTokens(source, eol);
    for (int i = 0; i < lines.length; i++) {
        String line = lines[i];
        // last line, stop if empty
        if (i == lines.length - 1 && StringUtils.isEmpty(line)) {
            break;
        }
        // update line
        if (right) {
            line = indent + line;
        } else {
            line = StringUtils.removeStart(line, indent);
        }
        // append line
        sb.append(line);
        sb.append(eol);
    }
    return sb.toString();
}

From source file:com.google.dart.engine.services.internal.correction.CorrectionUtils.java

/**
 * @return the source with indentation changed from "oldIndent" to "newIndent", keeping
 *         indentation of the lines relative to each other.
 *//*from  www.j av  a2  s . c  o m*/
public String getIndentSource(String source, String oldIndent, String newIndent) {
    StringBuilder sb = new StringBuilder();
    String eol = getEndOfLine();
    String[] lines = StringUtils.splitByWholeSeparatorPreserveAllTokens(source, eol);
    for (int i = 0; i < lines.length; i++) {
        String line = lines[i];
        // last line, stop if empty
        if (i == lines.length - 1 && StringUtils.isEmpty(line)) {
            break;
        }
        // line should have new indent
        line = newIndent + StringUtils.removeStart(line, oldIndent);
        // append line
        sb.append(line);
        sb.append(eol);
    }
    return sb.toString();
}

From source file:de.blizzy.documentr.page.PageStore.java

@Override
public void relocatePage(final String projectName, final String branchName, final String path,
        String newParentPagePath, User user) throws IOException {

    Assert.hasLength(projectName);//from ww  w .  ja  va 2s  .c  o  m
    Assert.hasLength(branchName);
    Assert.hasLength(path);
    Assert.hasLength(newParentPagePath);
    Assert.notNull(user);
    // check if pages exist by trying to load them
    getPage(projectName, branchName, path, false);
    getPage(projectName, branchName, newParentPagePath, false);

    ILockedRepository repo = null;
    List<String> oldPagePaths;
    List<String> deletedPagePaths;
    List<String> newPagePaths;
    List<PagePathChangedEvent> pagePathChangedEvents;
    try {
        repo = globalRepositoryManager.getProjectBranchRepository(projectName, branchName);
        String pageName = path.contains("/") ? StringUtils.substringAfterLast(path, "/") : path; //$NON-NLS-1$ //$NON-NLS-2$
        final String newPagePath = newParentPagePath + "/" + pageName; //$NON-NLS-1$

        File workingDir = RepositoryUtil.getWorkingDir(repo.r());

        File oldSubPagesDir = Util.toFile(new File(workingDir, DocumentrConstants.PAGES_DIR_NAME), path);
        oldPagePaths = listPagePaths(oldSubPagesDir, true);
        oldPagePaths = Lists.newArrayList(Lists.transform(oldPagePaths, new Function<String, String>() {
            @Override
            public String apply(String p) {
                return path + "/" + p; //$NON-NLS-1$
            }
        }));
        oldPagePaths.add(path);

        File deletedPagesSubDir = Util.toFile(new File(workingDir, DocumentrConstants.PAGES_DIR_NAME),
                newPagePath);
        deletedPagePaths = listPagePaths(deletedPagesSubDir, true);
        deletedPagePaths = Lists.newArrayList(Lists.transform(deletedPagePaths, new Function<String, String>() {
            @Override
            public String apply(String p) {
                return newPagePath + "/" + p; //$NON-NLS-1$
            }
        }));
        deletedPagePaths.add(newPagePath);

        Git git = Git.wrap(repo.r());
        AddCommand addCommand = git.add();

        for (String dirName : Sets.newHashSet(DocumentrConstants.PAGES_DIR_NAME,
                DocumentrConstants.ATTACHMENTS_DIR_NAME)) {
            File dir = new File(workingDir, dirName);

            File newSubPagesDir = Util.toFile(dir, newPagePath);
            if (newSubPagesDir.exists()) {
                git.rm().addFilepattern(dirName + "/" + newPagePath).call(); //$NON-NLS-1$
            }
            File newPageFile = Util.toFile(dir, newPagePath + DocumentrConstants.PAGE_SUFFIX);
            if (newPageFile.exists()) {
                git.rm().addFilepattern(dirName + "/" + newPagePath + DocumentrConstants.PAGE_SUFFIX).call(); //$NON-NLS-1$
            }
            File newMetaFile = Util.toFile(dir, newPagePath + DocumentrConstants.META_SUFFIX);
            if (newMetaFile.exists()) {
                git.rm().addFilepattern(dirName + "/" + newPagePath + DocumentrConstants.META_SUFFIX).call(); //$NON-NLS-1$
            }

            File newParentPageDir = Util.toFile(dir, newParentPagePath);
            File subPagesDir = Util.toFile(dir, path);
            if (subPagesDir.exists()) {
                FileUtils.copyDirectoryToDirectory(subPagesDir, newParentPageDir);
                git.rm().addFilepattern(dirName + "/" + path).call(); //$NON-NLS-1$
                addCommand.addFilepattern(dirName + "/" + newParentPagePath + "/" + pageName); //$NON-NLS-1$ //$NON-NLS-2$
            }
            File pageFile = Util.toFile(dir, path + DocumentrConstants.PAGE_SUFFIX);
            if (pageFile.exists()) {
                FileUtils.copyFileToDirectory(pageFile, newParentPageDir);
                git.rm().addFilepattern(dirName + "/" + path + DocumentrConstants.PAGE_SUFFIX).call(); //$NON-NLS-1$
                addCommand.addFilepattern(
                        dirName + "/" + newParentPagePath + "/" + pageName + DocumentrConstants.PAGE_SUFFIX); //$NON-NLS-1$ //$NON-NLS-2$
            }
            File metaFile = Util.toFile(dir, path + DocumentrConstants.META_SUFFIX);
            if (metaFile.exists()) {
                FileUtils.copyFileToDirectory(metaFile, newParentPageDir);
                git.rm().addFilepattern(dirName + "/" + path + DocumentrConstants.META_SUFFIX).call(); //$NON-NLS-1$
                addCommand.addFilepattern(
                        dirName + "/" + newParentPagePath + "/" + pageName + DocumentrConstants.META_SUFFIX); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }

        addCommand.call();
        PersonIdent ident = new PersonIdent(user.getLoginName(), user.getEmail());
        git.commit().setAuthor(ident).setCommitter(ident)
                .setMessage("move " + path + " to " + newParentPagePath + "/" + pageName) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                .call();
        git.push().call();

        newPagePaths = Lists.transform(oldPagePaths, new Function<String, String>() {
            @Override
            public String apply(String p) {
                return newPagePath + StringUtils.removeStart(p, path);
            }
        });

        pagePathChangedEvents = Lists.transform(oldPagePaths, new Function<String, PagePathChangedEvent>() {
            @Override
            public PagePathChangedEvent apply(String oldPath) {
                String newPath = newPagePath + StringUtils.removeStart(oldPath, path);
                return new PagePathChangedEvent(projectName, branchName, oldPath, newPath);
            }
        });

        PageUtil.updateProjectEditTime(projectName);
    } catch (GitAPIException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(repo);
    }

    Set<String> allDeletedPagePaths = Sets.newHashSet(oldPagePaths);
    allDeletedPagePaths.addAll(deletedPagePaths);
    eventBus.post(new PagesDeletedEvent(projectName, branchName, allDeletedPagePaths));

    for (String newPath : newPagePaths) {
        eventBus.post(new PageChangedEvent(projectName, branchName, newPath));
    }

    for (PagePathChangedEvent event : pagePathChangedEvents) {
        eventBus.post(event);
    }
}

From source file:com.sonicle.webtop.core.app.WebTopManager.java

public int updateUserEmailDomain(List<UserProfileId> pids, String newEmailDomain) throws WTException {
    UserInfoDAO uiDao = UserInfoDAO.getInstance();
    Connection con = null;// www.j  ava 2s.c  om

    try {
        if (pids.isEmpty())
            return -1;
        con = wta.getConnectionManager().getConnection(false);

        String domainId = pids.get(0).getDomainId();
        List<String> userIds = pids.stream().map(pid -> pid.getUserId()).collect(Collectors.toList());
        String emailDomain = "@" + StringUtils.removeStart(newEmailDomain, "@");
        int ret = uiDao.updateEmailDomainByProfiles(con, domainId, userIds, emailDomain);
        DbUtils.commitQuietly(con);

        // Clean-up cache!
        for (UserProfileId pid : pids)
            cleanUserProfileCache(pid);

        return ret;

    } catch (SQLException | DAOException ex) {
        DbUtils.rollbackQuietly(con);
        throw wrapThrowable(ex);
    } catch (Throwable t) {
        DbUtils.rollbackQuietly(con);
        throw t;
    } finally {
        DbUtils.closeQuietly(con);
    }
}

From source file:at.bitfire.davdroid.resource.LocalAddressBook.java

protected static String xNameToLabel(String xname) {
    // "X-MY_PROPERTY"
    // 1. ensure lower case -> "x-my_property"
    // 2. remove x- from beginning -> "my_property"
    // 3. replace "_" by " " -> "my property"
    // 4. capitalize -> "My Property"
    String lowerCase = StringUtils.lowerCase(xname, Locale.US),
            withoutPrefix = StringUtils.removeStart(lowerCase, "x-"),
            withSpaces = StringUtils.replace(withoutPrefix, "_", " ");
    return StringUtils.capitalize(withSpaces);
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

@Override
public void initializeDatabaseSettings() {
    try {//  ww w. j  av  a2  s .  c o  m
        databaseConfig = new DatabaseSettings(ConfigurationConverter.getProperties(mirthConfig));

        // dir.base is not included in mirth.properties, so set it manually
        databaseConfig.setDirBase(getBaseDir());

        String password = databaseConfig.getDatabasePassword();

        if (StringUtils.isNotEmpty(password)) {
            ConfigurationController configurationController = ControllerFactory.getFactory()
                    .createConfigurationController();
            EncryptionSettings encryptionSettings = configurationController.getEncryptionSettings();
            Encryptor encryptor = configurationController.getEncryptor();

            if (encryptionSettings.getEncryptProperties()) {
                if (StringUtils.startsWith(password, EncryptionSettings.ENCRYPTION_PREFIX)) {
                    String encryptedPassword = StringUtils.removeStart(password,
                            EncryptionSettings.ENCRYPTION_PREFIX);
                    String decryptedPassword = encryptor.decrypt(encryptedPassword);
                    databaseConfig.setDatabasePassword(decryptedPassword);
                } else if (StringUtils.isNotBlank(password)) {
                    // encrypt the password and write it back to the file
                    String encryptedPassword = EncryptionSettings.ENCRYPTION_PREFIX
                            + encryptor.encrypt(password);
                    mirthConfig.setProperty("database.password", encryptedPassword);

                    /*
                     * Save using a FileOutputStream so that the file will be saved to the
                     * proper location, even if running from the IDE.
                     */
                    File confDir = new File(ControllerFactory.getFactory().createConfigurationController()
                            .getConfigurationDir());
                    OutputStream os = new FileOutputStream(new File(confDir, "mirth.properties"));

                    try {
                        mirthConfig.save(os);
                    } finally {
                        IOUtils.closeQuietly(os);
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ch.cyberduck.ui.cocoa.controller.MainController.java

/**
 * Extract the URL from the Apple event and handle it here.
 *///  ww  w.j  a  va 2  s .co m
@Action
public void handleGetURLEvent_withReplyEvent(NSAppleEventDescriptor event, NSAppleEventDescriptor reply) {
    log.debug("Received URL from Apple Event:" + event);
    final NSAppleEventDescriptor param = event.paramDescriptorForKeyword(keyAEResult);
    if (null == param) {
        log.error("No URL parameter");
        return;
    }
    final String url = param.stringValue();
    if (StringUtils.isEmpty(url)) {
        log.error("URL parameter is empty");
        return;
    }
    if (StringUtils.startsWith(url, "x-cyberduck-action:")) {
        final String action = StringUtils.removeStart(url, "x-cyberduck-action:");
        switch (action) {
        case "update":
            updater.check(false);
            break;
        default:
            if (StringUtils.startsWith(action, "oauth?token=")) {
                final OAuth2TokenListenerRegistry oauth = OAuth2TokenListenerRegistry.get();
                final String token = StringUtils.removeStart(action, "oauth?token=");
                oauth.notify(token);
                break;
            }
        }
    } else {
        final Host h = HostParser.parse(url);
        if (Path.Type.file == detector.detect(h.getDefaultPath())) {
            final Path file = new Path(h.getDefaultPath(), EnumSet.of(Path.Type.file));
            TransferControllerFactory.get()
                    .start(new DownloadTransfer(h, file,
                            LocalFactory.get(preferences.getProperty("queue.download.folder"), file.getName())),
                            new TransferOptions());
        } else {
            for (BrowserController browser : MainController.getBrowsers()) {
                if (browser.isMounted()) {
                    if (new HostUrlProvider().get(browser.getSession().getHost())
                            .equals(new HostUrlProvider().get(h))) {
                        // Handle browser window already connected to the same host. #4215
                        browser.window().makeKeyAndOrderFront(null);
                        return;
                    }
                }
            }
            final BrowserController browser = newDocument(false);
            browser.mount(h);
        }
    }
}

From source file:com.google.dart.engine.services.completion.CompletionEngine.java

void namespaceSdkReference(NamespaceDirective node) {
    String prefix = filter.prefix;
    String[] prefixStrings = prefix.split(":");
    if (!prefix.isEmpty() && !"dart:".startsWith(prefixStrings[0])) {
        return;/*from   w  ww.j a  v a  2s. c  om*/
    }
    if (prefix.isEmpty()) {
        pImportUriWithScheme(node, "dart:");
        return;
    }
    // add DartSdk libraries
    DartSdk dartSdk = getAnalysisContext().getSourceFactory().getDartSdk();
    for (SdkLibrary library : dartSdk.getSdkLibraries()) {
        String name = library.getShortName();
        // ignore internal
        if (library.isInternal()) {
            continue;
        }
        // ignore implementation
        if (library.isImplementation()) {
            continue;
        }
        // standard libraries name name starting with "dart:"
        name = StringUtils.removeStart(name, "dart:");
        // ignore private libraries
        if (Identifier.isPrivateName(name)) {
            continue;
        }
        // add with "dart:" prefix
        pName("dart:" + name, ProposalKind.IMPORT);
    }
}

From source file:com.mirth.connect.client.ui.Frame.java

public String readFileToString(File file) {
    try {// www .  j a  v  a2  s  . co  m
        String content = FileUtils.readFileToString(file, UIConstants.CHARSET);

        if (StringUtils.startsWith(content, EncryptionSettings.ENCRYPTION_PREFIX)) {
            return mirthClient.getEncryptor()
                    .decrypt(StringUtils.removeStart(content, EncryptionSettings.ENCRYPTION_PREFIX));
        } else {
            return content;
        }
    } catch (IOException e) {
        alertError(this, "Unable to read file.");
    }

    return null;
}

From source file:net.sourceforge.pmd.docs.RuleDocGenerator.java

private static String stripIndentation(String description) {
    if (description == null || description.isEmpty()) {
        return "";
    }//w w  w.  j  a  va 2 s  . c o m

    String stripped = StringUtils.stripStart(description, "\n\r");
    stripped = StringUtils.stripEnd(stripped, "\n\r ");

    int indentation = 0;
    int strLen = stripped.length();
    while (Character.isWhitespace(stripped.charAt(indentation)) && indentation < strLen) {
        indentation++;
    }

    String[] lines = stripped.split("\\n");
    String prefix = StringUtils.repeat(' ', indentation);
    StringBuilder result = new StringBuilder(stripped.length());

    if (StringUtils.isNotEmpty(prefix)) {
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            if (i > 0) {
                result.append(StringUtils.LF);
            }
            result.append(StringUtils.removeStart(line, prefix));
        }
    } else {
        result.append(stripped);
    }
    return result.toString();
}