Example usage for com.liferay.portal.kernel.util StringUtil replaceFirst

List of usage examples for com.liferay.portal.kernel.util StringUtil replaceFirst

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.util StringUtil replaceFirst.

Prototype

public static String replaceFirst(String s, String oldSub, String newSub, int fromIndex) 

Source Link

Document

Replaces the first occurrences of the elements of the string array with the corresponding elements of the new string array, beginning the element search from the index position.

Usage

From source file:com.liferay.dynamic.data.lists.form.web.internal.converter.serializer.CalculateDDLFormRuleActionSerializer.java

License:Open Source License

protected String replace(String expression, String newExpression, int start, int end) {

    String matchFound = expression.substring(start, end);

    String matchReplacement = String.format(_functionCallUnaryExpressionFormat, "getValue", matchFound);

    return StringUtil.replaceFirst(newExpression, matchFound, matchReplacement, start);
}

From source file:com.liferay.exportimport.content.processor.base.BaseTextExportImportContentProcessor.java

License:Open Source License

protected String replaceImportLayoutReferences(PortletDataContext portletDataContext, String content)
        throws Exception {

    String companyPortalURL = StringPool.BLANK;
    String privateLayoutSetPortalURL = StringPool.BLANK;
    String publicLayoutSetPortalURL = StringPool.BLANK;

    Group group = GroupLocalServiceUtil.getGroup(portletDataContext.getScopeGroupId());

    Company company = CompanyLocalServiceUtil.getCompany(group.getCompanyId());

    LayoutSet privateLayoutSet = group.getPrivateLayoutSet();
    LayoutSet publicLayoutSet = group.getPublicLayoutSet();

    int serverPort = PortalUtil.getPortalServerPort(false);

    if (serverPort != -1) {
        if (Validator.isNotNull(company.getVirtualHostname())) {
            companyPortalURL = PortalUtil.getPortalURL(company.getVirtualHostname(), serverPort, false);
        }//from w  ww.  ja va2 s  . c  o  m

        if (Validator.isNotNull(privateLayoutSet.getVirtualHostname())) {
            privateLayoutSetPortalURL = PortalUtil.getPortalURL(privateLayoutSet.getVirtualHostname(),
                    serverPort, false);
        }

        if (Validator.isNotNull(publicLayoutSet.getVirtualHostname())) {
            publicLayoutSetPortalURL = PortalUtil.getPortalURL(publicLayoutSet.getVirtualHostname(), serverPort,
                    false);
        }
    }

    int secureSecurePort = PortalUtil.getPortalServerPort(true);

    String companySecurePortalURL = StringPool.BLANK;
    String privateLayoutSetSecurePortalURL = StringPool.BLANK;
    String publicLayoutSetSecurePortalURL = StringPool.BLANK;

    if (secureSecurePort != -1) {
        if (Validator.isNotNull(company.getVirtualHostname())) {
            companySecurePortalURL = PortalUtil.getPortalURL(company.getVirtualHostname(), secureSecurePort,
                    true);
        }

        if (Validator.isNotNull(privateLayoutSet.getVirtualHostname())) {
            privateLayoutSetSecurePortalURL = PortalUtil.getPortalURL(privateLayoutSet.getVirtualHostname(),
                    secureSecurePort, true);
        }

        if (Validator.isNotNull(publicLayoutSet.getVirtualHostname())) {
            publicLayoutSetSecurePortalURL = PortalUtil.getPortalURL(publicLayoutSet.getVirtualHostname(),
                    secureSecurePort, true);
        }
    }

    StringBundler sb = new StringBundler(3);

    sb.append(VirtualLayoutConstants.CANONICAL_URL_SEPARATOR);
    sb.append(GroupConstants.CONTROL_PANEL_FRIENDLY_URL);
    sb.append(PropsValues.CONTROL_PANEL_LAYOUT_FRIENDLY_URL);

    content = StringUtil.replace(content, DATA_HANDLER_COMPANY_SECURE_URL, companySecurePortalURL);
    content = StringUtil.replace(content, DATA_HANDLER_COMPANY_URL, companyPortalURL);

    // Group friendly URLs

    while (true) {
        int groupFriendlyUrlPos = content.indexOf(DATA_HANDLER_GROUP_FRIENDLY_URL);

        if (groupFriendlyUrlPos == -1) {
            break;
        }

        int groupUuidPos = groupFriendlyUrlPos + DATA_HANDLER_GROUP_FRIENDLY_URL.length();

        int endIndex = content.indexOf(StringPool.AT, groupUuidPos + 1);

        if (endIndex < (groupUuidPos + 1)) {
            content = StringUtil.replaceFirst(content, DATA_HANDLER_GROUP_FRIENDLY_URL, StringPool.BLANK,
                    groupFriendlyUrlPos);

            continue;
        }

        String groupUuid = content.substring(groupUuidPos + 1, endIndex);

        Group groupFriendlyUrlGroup = GroupLocalServiceUtil.fetchGroupByUuidAndCompanyId(groupUuid,
                portletDataContext.getCompanyId());

        if ((groupFriendlyUrlGroup == null) || groupUuid.startsWith(StringPool.SLASH)) {

            content = StringUtil.replaceFirst(content, DATA_HANDLER_GROUP_FRIENDLY_URL, group.getFriendlyURL(),
                    groupFriendlyUrlPos);
            content = StringUtil.replaceFirst(content, StringPool.AT + groupUuid + StringPool.AT,
                    StringPool.BLANK, content.indexOf(group.getFriendlyURL()));

            continue;
        }

        content = StringUtil.replaceFirst(content, DATA_HANDLER_GROUP_FRIENDLY_URL, StringPool.BLANK,
                groupFriendlyUrlPos);
        content = StringUtil.replaceFirst(content, StringPool.AT + groupUuid + StringPool.AT,
                groupFriendlyUrlGroup.getFriendlyURL(), groupFriendlyUrlPos);
    }

    content = StringUtil.replace(content, DATA_HANDLER_PATH_CONTEXT, PortalUtil.getPathContext());
    content = StringUtil.replace(content, DATA_HANDLER_PRIVATE_GROUP_SERVLET_MAPPING,
            PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING);
    content = StringUtil.replace(content, DATA_HANDLER_PRIVATE_LAYOUT_SET_SECURE_URL,
            privateLayoutSetSecurePortalURL);
    content = StringUtil.replace(content, DATA_HANDLER_PRIVATE_LAYOUT_SET_URL, privateLayoutSetPortalURL);
    content = StringUtil.replace(content, DATA_HANDLER_PRIVATE_USER_SERVLET_MAPPING,
            PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING);
    content = StringUtil.replace(content, DATA_HANDLER_PUBLIC_LAYOUT_SET_SECURE_URL,
            publicLayoutSetSecurePortalURL);
    content = StringUtil.replace(content, DATA_HANDLER_PUBLIC_LAYOUT_SET_URL, publicLayoutSetPortalURL);
    content = StringUtil.replace(content, DATA_HANDLER_PUBLIC_SERVLET_MAPPING,
            PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING);
    content = StringUtil.replace(content, DATA_HANDLER_SITE_ADMIN_URL, sb.toString());

    return content;
}

From source file:com.liferay.exportimport.internal.content.processor.LayoutReferencesExportImportContentProcessor.java

License:Open Source License

protected String replaceImportLayoutReferences(PortletDataContext portletDataContext, String content)
        throws Exception {

    String companyPortalURL = StringPool.BLANK;
    String privateLayoutSetPortalURL = StringPool.BLANK;
    String publicLayoutSetPortalURL = StringPool.BLANK;

    Group group = _groupLocalService.getGroup(portletDataContext.getScopeGroupId());

    Company company = _companyLocalService.getCompany(group.getCompanyId());

    LayoutSet privateLayoutSet = group.getPrivateLayoutSet();
    LayoutSet publicLayoutSet = group.getPublicLayoutSet();

    int serverPort = _portal.getPortalServerPort(false);

    if (serverPort != -1) {
        if (Validator.isNotNull(company.getVirtualHostname())) {
            companyPortalURL = _portal.getPortalURL(company.getVirtualHostname(), serverPort, false);
        }/*from w w w .j a  v a  2s .  co  m*/

        if (Validator.isNotNull(privateLayoutSet.getVirtualHostname())) {
            privateLayoutSetPortalURL = _portal.getPortalURL(privateLayoutSet.getVirtualHostname(), serverPort,
                    false);
        }

        if (Validator.isNotNull(publicLayoutSet.getVirtualHostname())) {
            publicLayoutSetPortalURL = _portal.getPortalURL(publicLayoutSet.getVirtualHostname(), serverPort,
                    false);
        }
    }

    int secureSecurePort = _portal.getPortalServerPort(true);

    String companySecurePortalURL = StringPool.BLANK;
    String privateLayoutSetSecurePortalURL = StringPool.BLANK;
    String publicLayoutSetSecurePortalURL = StringPool.BLANK;

    if (secureSecurePort != -1) {
        if (Validator.isNotNull(company.getVirtualHostname())) {
            companySecurePortalURL = _portal.getPortalURL(company.getVirtualHostname(), secureSecurePort, true);
        }

        if (Validator.isNotNull(privateLayoutSet.getVirtualHostname())) {
            privateLayoutSetSecurePortalURL = _portal.getPortalURL(privateLayoutSet.getVirtualHostname(),
                    secureSecurePort, true);
        }

        if (Validator.isNotNull(publicLayoutSet.getVirtualHostname())) {
            publicLayoutSetSecurePortalURL = _portal.getPortalURL(publicLayoutSet.getVirtualHostname(),
                    secureSecurePort, true);
        }
    }

    StringBundler sb = new StringBundler(3);

    sb.append(VirtualLayoutConstants.CANONICAL_URL_SEPARATOR);
    sb.append(GroupConstants.CONTROL_PANEL_FRIENDLY_URL);
    sb.append(PropsValues.CONTROL_PANEL_LAYOUT_FRIENDLY_URL);

    content = StringUtil.replace(content, _DATA_HANDLER_COMPANY_SECURE_URL, companySecurePortalURL);
    content = StringUtil.replace(content, _DATA_HANDLER_COMPANY_URL, companyPortalURL);

    // Group friendly URLs

    while (true) {
        int groupFriendlyUrlPos = content.indexOf(_DATA_HANDLER_GROUP_FRIENDLY_URL);

        if (groupFriendlyUrlPos == -1) {
            break;
        }

        int groupUuidPos = groupFriendlyUrlPos + _DATA_HANDLER_GROUP_FRIENDLY_URL.length();

        int endIndex = content.indexOf(StringPool.AT, groupUuidPos + 1);

        if (endIndex < (groupUuidPos + 1)) {
            content = StringUtil.replaceFirst(content, _DATA_HANDLER_GROUP_FRIENDLY_URL, StringPool.BLANK,
                    groupFriendlyUrlPos);

            continue;
        }

        String groupUuid = content.substring(groupUuidPos + 1, endIndex);

        Group groupFriendlyUrlGroup = _groupLocalService.fetchGroupByUuidAndCompanyId(groupUuid,
                portletDataContext.getCompanyId());

        if ((groupFriendlyUrlGroup == null) || groupUuid.startsWith(StringPool.SLASH)) {

            content = StringUtil.replaceFirst(content, _DATA_HANDLER_GROUP_FRIENDLY_URL, group.getFriendlyURL(),
                    groupFriendlyUrlPos);
            content = StringUtil.replaceFirst(content, StringPool.AT + groupUuid + StringPool.AT,
                    StringPool.BLANK, content.indexOf(group.getFriendlyURL()));

            continue;
        }

        content = StringUtil.replaceFirst(content, _DATA_HANDLER_GROUP_FRIENDLY_URL, StringPool.BLANK,
                groupFriendlyUrlPos);
        content = StringUtil.replaceFirst(content, StringPool.AT + groupUuid + StringPool.AT,
                groupFriendlyUrlGroup.getFriendlyURL(), groupFriendlyUrlPos);
    }

    content = StringUtil.replace(content, _DATA_HANDLER_PATH_CONTEXT, _portal.getPathContext());
    content = StringUtil.replace(content, _DATA_HANDLER_PRIVATE_GROUP_SERVLET_MAPPING,
            PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING);
    content = StringUtil.replace(content, _DATA_HANDLER_PRIVATE_LAYOUT_SET_SECURE_URL,
            privateLayoutSetSecurePortalURL);
    content = StringUtil.replace(content, _DATA_HANDLER_PRIVATE_LAYOUT_SET_URL, privateLayoutSetPortalURL);
    content = StringUtil.replace(content, _DATA_HANDLER_PRIVATE_USER_SERVLET_MAPPING,
            PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING);
    content = StringUtil.replace(content, _DATA_HANDLER_PUBLIC_LAYOUT_SET_SECURE_URL,
            publicLayoutSetSecurePortalURL);
    content = StringUtil.replace(content, _DATA_HANDLER_PUBLIC_LAYOUT_SET_URL, publicLayoutSetPortalURL);
    content = StringUtil.replace(content, _DATA_HANDLER_PUBLIC_SERVLET_MAPPING,
            PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING);
    content = StringUtil.replace(content, _DATA_HANDLER_SITE_ADMIN_URL, sb.toString());

    return content;
}

From source file:com.liferay.tools.sourceformatter.CSSSourceProcessor.java

License:Open Source License

protected String fixComments(String content) {
    Matcher matcher = _commentPattern.matcher(content);

    while (matcher.find()) {
        String[] words = StringUtil.split(matcher.group(1), CharPool.SPACE);

        for (int i = 1; i < words.length; i++) {
            String previousWord = words[i - 1];

            if (previousWord.endsWith(StringPool.PERIOD) || previousWord.equals(StringPool.SLASH)) {

                continue;
            }//from  w  ww.ja v a  2s. c  om

            String word = words[i];

            if ((word.length() > 1) && Character.isUpperCase(word.charAt(0))
                    && StringUtil.isLowerCase(word.substring(1))) {

                content = StringUtil.replaceFirst(content, word, StringUtil.toLowerCase(word), matcher.start());
            }
        }
    }

    return content;
}

From source file:com.liferay.tools.sourceformatter.JavaSourceProcessor.java

License:Open Source License

@Override
protected String doFormat(File file, String fileName, String absolutePath, String content) throws Exception {

    if (isGenerated(content)) {
        return content;
    }//  www .j av  a  2  s  . c o m

    String className = file.getName();

    int pos = className.lastIndexOf(StringPool.PERIOD);

    className = className.substring(0, pos);

    String packagePath = fileName;

    int packagePathX = packagePath.indexOf("/src/");

    if (packagePathX == -1) {
        packagePathX = packagePath.indexOf("/integration/") + 8;
    }

    int packagePathY = packagePath.lastIndexOf(StringPool.SLASH);

    if ((packagePathX + 5) >= packagePathY) {
        packagePath = StringPool.BLANK;
    } else {
        packagePath = packagePath.substring(packagePathX + 5, packagePathY);
    }

    packagePath = StringUtil.replace(packagePath, StringPool.SLASH, StringPool.PERIOD);

    if (packagePath.endsWith(".model")) {
        if (content.contains("extends " + className + "Model")) {
            return content;
        }
    }

    String newContent = content;

    if (newContent.contains("$\n */")) {
        processErrorMessage(fileName, "*: " + fileName);

        newContent = StringUtil.replace(newContent, "$\n */", "$\n *\n */");
    }

    newContent = fixCopyright(newContent, absolutePath, fileName);

    if (newContent.contains(className + ".java.html")) {
        processErrorMessage(fileName, "Java2HTML: " + fileName);
    }

    if (newContent.contains(" * @author Raymond Aug") && !newContent.contains(" * @author Raymond Aug\u00e9")) {

        newContent = newContent.replaceFirst("Raymond Aug.++", "Raymond Aug\u00e9");

        processErrorMessage(fileName, "UTF-8: " + fileName);
    }

    newContent = fixDataAccessConnection(className, newContent);
    newContent = fixSessionKey(fileName, newContent, sessionKeyPattern);

    newContent = StringUtil.replace(newContent,
            new String[] { "com.liferay.portal.PortalException", "com.liferay.portal.SystemException",
                    "com.liferay.util.LocalizationUtil" },
            new String[] { "com.liferay.portal.kernel.exception.PortalException",
                    "com.liferay.portal.kernel.exception.SystemException",
                    "com.liferay.portal.kernel.util.LocalizationUtil" });

    newContent = StringUtil.replace(newContent, " final static ", " static final ");

    newContent = fixCompatClassImports(absolutePath, newContent);

    newContent = stripJavaImports(newContent, packagePath, className);

    newContent = StringUtil.replace(newContent,
            new String[] { ";\n/**", "\t/*\n\t *", "catch(", "else{", "if(", "for(", "while(", "List <", "){\n",
                    "]{\n", ";;\n" },
            new String[] { ";\n\n/**", "\t/**\n\t *", "catch (", "else {", "if (", "for (", "while (", "List<",
                    ") {\n", "] {\n", ";\n" });

    while (true) {
        Matcher matcher = _incorrectLineBreakPattern.matcher(newContent);

        if (!matcher.find()) {
            break;
        }

        newContent = StringUtil.replaceFirst(newContent, StringPool.NEW_LINE, StringPool.BLANK,
                matcher.start());
    }

    newContent = sortAnnotations(newContent, StringPool.BLANK);

    Matcher matcher = _logPattern.matcher(newContent);

    if (matcher.find()) {
        String logClassName = matcher.group(1);

        if (!logClassName.equals(className)) {
            newContent = StringUtil.replaceLast(newContent, logClassName + ".class)", className + ".class)");
        }
    }

    if (!isExcluded(_staticLogVariableExclusions, absolutePath)) {
        newContent = StringUtil.replace(newContent, "private Log _log", "private static final Log _log");
    }

    if (newContent.contains("*/\npackage ")) {
        processErrorMessage(fileName, "package: " + fileName);
    }

    if (!newContent.endsWith("\n\n}") && !newContent.endsWith("{\n}")) {
        processErrorMessage(fileName, "}: " + fileName);
    }

    if (portalSource && !_allowUseServiceUtilInServiceImpl && !className.equals("BaseServiceImpl")
            && className.endsWith("ServiceImpl") && newContent.contains("ServiceUtil.")) {

        processErrorMessage(fileName, "ServiceUtil: " + fileName);
    }

    // LPS-34911

    if (portalSource && !isExcluded(_upgradeServiceUtilExclusions, absolutePath)
            && fileName.contains("/portal/upgrade/") && !fileName.contains("/test/")
            && newContent.contains("ServiceUtil.")) {

        processErrorMessage(fileName, "ServiceUtil: " + fileName);
    }

    if (!isRunsOutsidePortal(absolutePath) && !isExcluded(_proxyExclusions, absolutePath)
            && newContent.contains("import java.lang.reflect.Proxy;")) {

        processErrorMessage(fileName, "Proxy: " + fileName);
    }

    if (newContent.contains("import edu.emory.mathcs.backport.java")) {
        processErrorMessage(fileName, "edu.emory.mathcs.backport.java: " + fileName);
    }

    if (newContent.contains("import jodd.util.StringPool")) {
        processErrorMessage(fileName, "jodd.util.StringPool: " + fileName);
    }

    // LPS-45027

    if (newContent.contains("com.liferay.portal.kernel.util.UnmodifiableList")) {

        processErrorMessage(fileName, "Use java.util.Collections.unmodifiableList instead of "
                + "com.liferay.portal.kernel.util.UnmodifiableList: " + fileName);
    }

    // LPS-28266

    for (int pos1 = -1;;) {
        pos1 = newContent.indexOf(StringPool.TAB + "try {", pos1 + 1);

        if (pos1 == -1) {
            break;
        }

        int pos2 = newContent.indexOf(StringPool.TAB + "try {", pos1 + 1);
        int pos3 = newContent.indexOf("\"select count(", pos1);

        if ((pos2 != -1) && (pos3 != -1) && (pos2 < pos3)) {
            continue;
        }

        int pos4 = newContent.indexOf("rs.getLong(1)", pos1);
        int pos5 = newContent.indexOf(StringPool.TAB + "finally {", pos1);

        if ((pos3 == -1) || (pos4 == -1) || (pos5 == -1)) {
            break;
        }

        if ((pos3 < pos4) && (pos4 < pos5)) {
            processErrorMessage(fileName, "Use getInt(1) for count: " + fileName);
        }
    }

    // LPS-33070

    matcher = _processCallablePattern.matcher(content);

    if (matcher.find() && !content.contains("private static final long serialVersionUID")) {

        processErrorMessage(fileName, "Assign ProcessCallable implementation a serialVersionUID: " + fileName);
    }

    checkLanguageKeys(fileName, newContent, languageKeyPattern);

    newContent = StringUtil.replace(newContent, StringPool.TAB + "for (;;) {",
            StringPool.TAB + "while (true) {");

    // LPS-36174

    if (_checkUnprocessedExceptions && !fileName.contains("/test/")) {
        checkUnprocessedExceptions(newContent, file, packagePath, fileName);
    }

    // LPS-39508

    if (!isExcluded(_secureRandomExclusions, absolutePath) && !isRunsOutsidePortal(absolutePath)
            && content.contains("java.security.SecureRandom")
            && !content.contains("javax.crypto.KeyGenerator")) {

        processErrorMessage(fileName, "Use SecureRandomUtil or com.liferay.portal.kernel.security."
                + "SecureRandom instead of java.security.SecureRandom: " + fileName);
    }

    // LPS-41315

    checkLogLevel(newContent, fileName, "debug");
    checkLogLevel(newContent, fileName, "info");
    checkLogLevel(newContent, fileName, "trace");
    checkLogLevel(newContent, fileName, "warn");

    // LPS-46632

    checkSystemEventAnnotations(newContent, fileName);

    // LPS-41205

    if (fileName.contains("/upgrade/") && newContent.contains("LocaleUtil.getDefault()")) {

        processErrorMessage(fileName, "Use UpgradeProcessUtil.getDefaultLanguageId(companyId) "
                + "instead of LocaleUtil.getDefault(): " + fileName);
    }

    // LPS-46017

    newContent = StringUtil.replace(newContent, " static interface ", " interface ");

    // LPS-47055

    newContent = fixSystemExceptions(newContent);

    // LPS-47648

    if (portalSource && fileName.contains("/test/integration/")) {
        newContent = StringUtil.replace(newContent, "FinderCacheUtil.clearCache();", StringPool.BLANK);
    }

    // LPS-47682

    newContent = fixIncorrectParameterTypeForLanguageUtil(newContent, false, fileName);

    if (portalSource && fileName.contains("/portal-service/")
            && content.contains("import javax.servlet.jsp.")) {

        processErrorMessage(fileName, "Never import javax.servlet.jsp.* from portal-service " + fileName);
    }

    // LPS-48153

    //newContent = applyDiamondOperator(newContent);

    // LPS-49552

    checkFinderCacheInterfaceMethod(fileName, newContent);

    newContent = fixIncorrectEmptyLineBeforeCloseCurlyBrace(newContent, fileName);

    pos = newContent.indexOf("\npublic ");

    if (pos != -1) {
        String javaClassContent = newContent.substring(pos + 1);

        String beforeJavaClass = newContent.substring(0, pos + 1);

        int javaClassLineCount = StringUtil.count(beforeJavaClass, "\n") + 1;

        newContent = formatJavaTerms(className, fileName, absolutePath, newContent, javaClassContent,
                javaClassLineCount, _checkJavaFieldTypesExclusions, _javaTermAccessLevelModifierExclusions,
                _javaTermSortExclusions, _testAnnotationsExclusions);
    }

    newContent = formatJava(fileName, absolutePath, newContent);

    return StringUtil.replace(newContent, "\n\n\n", "\n\n");
}

From source file:com.liferay.tools.sourceformatter.JavaSourceProcessor.java

License:Open Source License

protected String fixIncorrectEmptyLineBeforeCloseCurlyBrace(String content, String fileName) {

    Matcher matcher1 = _incorrectCloseCurlyBracePattern1.matcher(content);

    while (matcher1.find()) {
        String lastLine = StringUtil.trimLeading(matcher1.group(1));

        if (lastLine.startsWith("// ")) {
            continue;
        }/*from w  w w.j  av a  2s. c om*/

        String tabs = matcher1.group(2);
        int tabCount = tabs.length();

        int pos = matcher1.start();

        while (true) {
            pos = content.lastIndexOf("\n" + tabs, pos - 1);

            if (content.charAt(pos + tabCount + 1) == CharPool.TAB) {
                continue;
            }

            String codeBlock = content.substring(pos + 1, matcher1.end());

            String firstLine = codeBlock.substring(0, codeBlock.indexOf("\n"));

            Matcher matcher2 = _incorrectCloseCurlyBracePattern2.matcher(firstLine);

            if (matcher2.find()) {
                break;
            }

            return StringUtil.replaceFirst(content, "\n\n" + tabs + "}\n", "\n" + tabs + "}\n", pos);
        }
    }

    return content;
}

From source file:com.liferay.tools.sourceformatter.JSPSourceProcessor.java

License:Open Source License

@Override
protected void format() throws Exception {
    _moveFrequentlyUsedImportsToCommonInit = GetterUtil
            .getBoolean(getProperty("move.frequently.used.imports.to.common.init"));
    _unusedVariablesExclusions = getPropertyList("jsp.unused.variables.excludes.files");

    String[] excludes = new String[] { "**\\null.jsp", "**\\tools\\**" };
    String[] includes = new String[] { "**\\*.jsp", "**\\*.jspf", "**\\*.vm" };

    List<String> fileNames = getFileNames(excludes, includes);

    Pattern pattern = Pattern.compile("\\s*@\\s*include\\s*file=['\"](.*)['\"]");

    for (String fileName : fileNames) {
        File file = new File(BASEDIR + fileName);

        fileName = StringUtil.replace(fileName, StringPool.BACK_SLASH, StringPool.SLASH);

        String absolutePath = getAbsolutePath(file);

        String content = fileUtil.read(file);

        Matcher matcher = pattern.matcher(content);

        String newContent = content;

        while (matcher.find()) {
            newContent = StringUtil.replaceFirst(newContent, matcher.group(),
                    "@ include file=\"" + matcher.group(1) + "\"", matcher.start());
        }//from  w  ww  . ja  v  a 2s  .  c om

        processFormattedFile(file, fileName, content, newContent);

        if (portalSource && _moveFrequentlyUsedImportsToCommonInit && fileName.endsWith("/init.jsp")
                && !absolutePath.contains("/modules/") && !fileName.endsWith("/common/init.jsp")) {

            addImportCounts(content);
        }

        _jspContents.put(fileName, newContent);
    }

    if (portalSource && _moveFrequentlyUsedImportsToCommonInit) {
        moveFrequentlyUsedImportsToCommonInit(4);
    }

    for (String fileName : fileNames) {
        format(fileName);
    }
}

From source file:com.liferay.tools.sourceformatter.XMLSourceProcessor.java

License:Open Source License

public static String formatXML(String content) {
    String newContent = StringUtil.replace(content, "\"/>\n", "\" />\n");

    while (true) {
        Matcher matcher = _commentPattern1.matcher(newContent);

        if (matcher.find()) {
            newContent = StringUtil.replaceFirst(newContent, ">\n", ">\n\n", matcher.start());

            continue;
        }/*from   ww  w. ja v a2 s.co  m*/

        matcher = _commentPattern2.matcher(newContent);

        if (!matcher.find()) {
            break;
        }

        newContent = StringUtil.replaceFirst(newContent, "-->\n", "-->\n\n", matcher.start());
    }

    return newContent;
}

From source file:com.liferay.tools.sourceformatter.XMLSourceProcessor.java

License:Open Source License

protected String fixPoshiXMLNumberOfTabs(String content) {
    Matcher matcher = _poshiTabsPattern.matcher(content);

    int tabCount = 0;

    boolean ignoredCdataBlock = false;
    boolean ignoredCommentBlock = false;

    while (matcher.find()) {
        String statement = matcher.group();

        Matcher quoteWithSlashMatcher = _poshiQuoteWithSlashPattern.matcher(statement);

        String fixedQuoteStatement = statement;

        if (quoteWithSlashMatcher.find()) {
            fixedQuoteStatement = StringUtil.replace(statement, quoteWithSlashMatcher.group(), "\"\"");
        }/*ww  w .  j a v  a2 s .c o  m*/

        Matcher closingTagMatcher = _poshiClosingTagPattern.matcher(fixedQuoteStatement);
        Matcher openingTagMatcher = _poshiOpeningTagPattern.matcher(fixedQuoteStatement);
        Matcher wholeTagMatcher = _poshiWholeTagPattern.matcher(fixedQuoteStatement);

        if (closingTagMatcher.find() && !openingTagMatcher.find() && !wholeTagMatcher.find()
                && !statement.contains("<!--") && !statement.contains("-->") && !statement.contains("<![CDATA[")
                && !statement.contains("]]>")) {

            tabCount--;
        }

        if (statement.contains("]]>")) {
            ignoredCdataBlock = false;
        } else if (statement.contains("<![CDATA[")) {
            ignoredCdataBlock = true;
        }

        if (statement.contains("-->")) {
            ignoredCommentBlock = false;
        } else if (statement.contains("<!--")) {
            ignoredCommentBlock = true;
        }

        if (!ignoredCommentBlock && !ignoredCdataBlock) {
            StringBundler sb = new StringBundler(tabCount + 1);

            for (int i = 0; i < tabCount; i++) {
                sb.append(StringPool.TAB);
            }

            sb.append(StringPool.LESS_THAN);

            String replacement = sb.toString();

            if (!replacement.equals(matcher.group(1))) {
                String newStatement = StringUtil.replace(statement, matcher.group(1), replacement);

                return StringUtil.replaceFirst(content, statement, newStatement, matcher.start());
            }
        }

        if (openingTagMatcher.find() && !closingTagMatcher.find() && !wholeTagMatcher.find()
                && !statement.contains("<!--") && !statement.contains("-->") && !statement.contains("<![CDATA[")
                && !statement.contains("]]>")) {

            tabCount++;
        }
    }

    return content;
}