cmsstringutil.java
来自「找了很久才找到到源代码」· Java 代码 · 共 1,075 行 · 第 1/3 页
JAVA
1,075 行
/*
* File : $Source: /usr/local/cvs/opencms/src/org/opencms/util/CmsStringUtil.java,v $
* Date : $Date: 2007-08-30 12:05:47 $
* Version: $Revision: 1.46 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2007 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.util;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.I_CmsMessageBundle;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsLog;
import java.awt.Color;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.oro.text.perl.MalformedPerl5PatternException;
import org.apache.oro.text.perl.Perl5Util;
/**
* Provides String utility functions.<p>
*
* @author Andreas Zahner
* @author Alexander Kandzior
* @author Thomas Weckert
*
* @version $Revision: 1.46 $
*
* @since 6.0.0
*/
public final class CmsStringUtil {
/** Regular expression that matches the HTML body end tag. */
public static final String BODY_END_REGEX = "<\\s*/\\s*body[^>]*>";
/** Regular expression that matches the HTML body start tag. */
public static final String BODY_START_REGEX = "<\\s*body[^>]*>";
/** Constant for <code>"false"</code>. */
public static final String FALSE = Boolean.toString(false);
/** a convienient shorthand to the line separator constant. */
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
/** Context macro. */
public static final String MACRO_OPENCMS_CONTEXT = "${OpenCmsContext}";
/** Contains all chars that end a sentence in the {@link #trimToSize(String, int, int, String)} method. */
public static final char[] SENTENCE_ENDING_CHARS = {'.', '!', '?'};
/** a convienient shorthand for tabulations. */
public static final String TABULATOR = " ";
/** Constant for <code>"true"</code>. */
public static final String TRUE = Boolean.toString(true);
/** Regex pattern that matches an end body tag. */
private static final Pattern BODY_END_PATTERN = Pattern.compile(BODY_END_REGEX, Pattern.CASE_INSENSITIVE);
/** Regex pattern that matches a start body tag. */
private static final Pattern BODY_START_PATTERN = Pattern.compile(BODY_START_REGEX, Pattern.CASE_INSENSITIVE);
/** Day constant. */
private static final long DAYS = 1000 * 60 * 60 * 24;
/** Hour constant. */
private static final long HOURS = 1000 * 60 * 60;
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsStringUtil.class);
/** OpenCms context replace String, static for performance reasons. */
private static String m_contextReplace;
/** OpenCms context search String, static for performance reasons. */
private static String m_contextSearch;
/** Minute constant. */
private static final long MINUTES = 1000 * 60;
/** Second constant. */
private static final long SECONDS = 1000;
/** Regex that matches an encoding String in an xml head. */
private static final Pattern XML_ENCODING_REGEX = Pattern.compile(
"encoding\\s*=\\s*[\"'].+[\"']",
Pattern.CASE_INSENSITIVE);
/** Regex that matches an xml head. */
private static final Pattern XML_HEAD_REGEX = Pattern.compile("<\\s*\\?.*\\?\\s*>", Pattern.CASE_INSENSITIVE);
/**
* Default constructor (empty), private because this class has only
* static methods.<p>
*/
private CmsStringUtil() {
// empty
}
/**
* Changes the filename suffix.
*
* @param filename the filename to be changed
* @param suffix the new suffix of the file
* @return the filename with the replaced suffix
*/
public static String changeFileNameSuffixTo(String filename, String suffix) {
int dotPos = filename.lastIndexOf('.');
if (dotPos != -1) {
return filename.substring(0, dotPos + 1) + suffix;
} else {
// the string has no suffix
return filename;
}
}
/**
* Checks if a given name is composed only of the characters <code>a...z,A...Z,0...9</code>
* and the provided <code>contraints</code>.<p>
*
* If the check fails, an Exception is generated. The provided bundle and key is
* used to generate the Exception. 4 parameters are passed to the Exception:<ol>
* <li>The <code>name</code>
* <li>The first illegal character found
* <li>The position where the illegal character was found
* <li>The <code>contraints</code></ol>
*
* @param name the name to check
* @param contraints the additional character contraints
* @param key the key to use for generating the Exception (if required)
* @param bundle the bundle to use for generating the Exception (if required)
*
* @throws CmsIllegalArgumentException if the check fails (generated from the given key and bundle)
*/
public static void checkName(String name, String contraints, String key, I_CmsMessageBundle bundle)
throws CmsIllegalArgumentException {
int l = name.length();
for (int i = 0; i < l; i++) {
char c = name.charAt(i);
if (((c < 'a') || (c > 'z'))
&& ((c < '0') || (c > '9'))
&& ((c < 'A') || (c > 'Z'))
&& (contraints.indexOf(c) < 0)) {
throw new CmsIllegalArgumentException(bundle.container(key, new Object[] {
name,
new Character(c),
new Integer(i),
contraints}));
}
}
}
/**
* Returns a string representation for the given collection using the given separator.<p>
*
* @param collection the collection to print
* @param separator the item separator
*
* @return the string representation for the given collection
*/
public static String collectionAsString(Collection collection, String separator) {
StringBuffer string = new StringBuffer(128);
Iterator it = collection.iterator();
while (it.hasNext()) {
string.append(it.next());
if (it.hasNext()) {
string.append(separator);
}
}
return string.toString();
}
/**
* Replaces occurences of special control characters in the given input with
* a HTML representation.<p>
*
* This method currrently replaces line breaks to <code><br/></code> and special HTML chars
* like <code>< > & "</code> with their HTML entity representation.<p>
*
* @param source the String to escape
* @return the escaped String
*/
public static String escapeHtml(String source) {
if (source == null) {
return null;
}
source = CmsEncoder.escapeXml(source);
source = CmsStringUtil.substitute(source, "\r", "");
source = CmsStringUtil.substitute(source, "\n", "<br/>\n");
return source;
}
/**
* Escapes a String so it may be used in JavaScript String definitions.<p>
*
* This method replaces line breaks, quotationmarks and \ characters.<p>
*
* @param source the String to escape
* @return the escaped String
*/
public static String escapeJavaScript(String source) {
source = CmsStringUtil.substitute(source, "\\", "\\\\");
source = CmsStringUtil.substitute(source, "\"", "\\\"");
source = CmsStringUtil.substitute(source, "\'", "\\\'");
source = CmsStringUtil.substitute(source, "\r\n", "\\n");
source = CmsStringUtil.substitute(source, "\n", "\\n");
return source;
}
/**
* Escapes a String so it may be used as a Perl5 regular expression.<p>
*
* This method replaces the following characters in a String:<br>
* <code>{}[]()\$^.*+/</code>
*
*
* @param source the string to escape
* @return the escaped string
*/
public static String escapePattern(String source) {
if (source == null) {
return null;
}
StringBuffer result = new StringBuffer(source.length() * 2);
for (int i = 0; i < source.length(); ++i) {
char ch = source.charAt(i);
switch (ch) {
case '\\':
result.append("\\\\");
break;
case '/':
result.append("\\/");
break;
case '$':
result.append("\\$");
break;
case '^':
result.append("\\^");
break;
case '.':
result.append("\\.");
break;
case '*':
result.append("\\*");
break;
case '+':
result.append("\\+");
break;
case '|':
result.append("\\|");
break;
case '?':
result.append("\\?");
break;
case '{':
result.append("\\{");
break;
case '}':
result.append("\\}");
break;
case '[':
result.append("\\[");
break;
case ']':
result.append("\\]");
break;
case '(':
result.append("\\(");
break;
case ')':
result.append("\\)");
break;
default:
result.append(ch);
}
}
return new String(result);
}
/**
* This method takes a part of a html tag definition, an attribute to extend within the
* given text and a default value for this attribute; and returns a <code>{@link Map}</code>
* with 2 values: a <code>{@link String}</code> with key <code>"text"</code> with the new text
* without the given attribute, and another <code>{@link String}</code> with key <code>"value"</code>
* with the new extended value for the given attribute, this value is sourrounded by the same type of
* quotation marks as in the given text.<p>
*
* @param text the text to search in
* @param attribute the attribute to remove and extend from the text
* @param defValue a default value for the attribute, should not have any quotation mark
*
* @return a map with the new text and the new value for the given attribute
*/
public static Map extendAttribute(String text, String attribute, String defValue) {
Map retValue = new HashMap();
retValue.put("text", text);
retValue.put("value", "'" + defValue + "'");
if ((text != null) && (text.toLowerCase().indexOf(attribute.toLowerCase()) >= 0)) {
// this doesnot work for things like "att=method()" without quotations.
String quotation = "\'";
int pos1 = text.toLowerCase().indexOf(attribute.toLowerCase());
// looking for the opening quotation mark
int pos2 = text.indexOf(quotation, pos1);
int test = text.indexOf("\"", pos1);
if ((test > -1) && ((pos2 == -1) || (test < pos2))) {
quotation = "\"";
pos2 = test;
}
// assuming there is a closing quotation mark
int pos3 = text.indexOf(quotation, pos2 + 1);
// building the new attribute value
String newValue = quotation + defValue + text.substring(pos2 + 1, pos3 + 1);
// removing the onload statement from the parameters
String newText = text.substring(0, pos1);
if (pos3 < text.length()) {
newText += text.substring(pos3 + 1);
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?