Example usage for java.util.regex Matcher replaceAll

List of usage examples for java.util.regex Matcher replaceAll

Introduction

In this page you can find the example usage for java.util.regex Matcher replaceAll.

Prototype

public String replaceAll(Function<MatchResult, String> replacer) 

Source Link

Document

Replaces every subsequence of the input sequence that matches the pattern with the result of applying the given replacer function to the match result of this matcher corresponding to that subsequence.

Usage

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatConversationPanel.java

/**
 * Processes /me command in group chats.
 *
 * @param chatMessage the chat message/*  w ww  .  j  a  v a 2s.c  o  m*/
 * @return the newly processed message string
 */
public String processMeCommand(ChatMessage chatMessage) {
    String contentType = chatMessage.getContentType();
    String message = chatMessage.getMessage();
    if (message.length() <= 4 || !message.startsWith("/me ")) {
        return "";
    }

    String msgID = ChatHtmlUtils.MESSAGE_TEXT_ID + chatMessage.getMessageUID();
    String chatString = "<DIV ID='" + msgID + "'><B><I>";
    String endHeaderTag = "</I></B></DIV>";

    chatString += GuiUtils.escapeHTMLChars("*** " + chatMessage.getContactName() + " " + message.substring(4))
            + endHeaderTag;

    Map<String, ReplacementService> listSources = GuiActivator.getReplacementSources();
    for (ReplacementService source : listSources.values()) {
        boolean isSmiley = source instanceof SmiliesReplacementService;
        if (!isSmiley) {
            continue;
        }
        String sourcePattern = source.getPattern();
        Pattern p = Pattern.compile(sourcePattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher m = p.matcher(chatString);
        chatString = m.replaceAll(ChatHtmlUtils.HTML_CONTENT_TYPE.equalsIgnoreCase(contentType) ? "$0"
                : StringEscapeUtils.escapeHtml4("$0"));
    }
    return chatString;
}

From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public boolean loadTestResultAvail(ApplicationInfo appInfo) throws PhrescoException {
    boolean isResultFileAvailable = false;
    try {/*w  w  w. j a  v a  2 s.  c  o m*/
        String baseDir = Utility.getProjectHome() + appInfo.getAppDirName();
        FrameworkUtil frameworkUtil = FrameworkUtil.getInstance();
        List<String> testResultsTypes = new ArrayList<String>();
        testResultsTypes.add("server");
        testResultsTypes.add("webservice");
        for (String testResultsType : testResultsTypes) {
            StringBuilder sb = new StringBuilder(baseDir.toString());
            String loadReportDir = frameworkUtil.getLoadTestReportDir(appInfo);
            if (StringUtils.isNotEmpty(loadReportDir) && StringUtils.isNotEmpty(testResultsType)) {
                Pattern p = Pattern.compile("dir_type");
                Matcher matcher = p.matcher(loadReportDir);
                loadReportDir = matcher.replaceAll(testResultsType);
                sb.append(loadReportDir);
            }
            File file = new File(sb.toString());
            File[] children = file.listFiles(new XmlNameFileFilter(FILE_EXTENSION_XML));
            if (!ArrayUtils.isEmpty(children)) {
                isResultFileAvailable = true;
                break;
            }
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }

    return isResultFileAvailable;
}

From source file:com.groupon.odo.bmp.http.BrowserMobHttpClient.java

private BrowserMobHttpResponse execute(BrowserMobHttpRequest req, int depth) {
    if (depth >= MAX_REDIRECT) {
        throw new IllegalStateException("Max number of redirects (" + MAX_REDIRECT + ") reached");
    }/*from w ww  . j a  v  a  2  s.c o  m*/

    RequestCallback callback = req.getRequestCallback();

    HttpRequestBase method = req.getMethod();
    String verificationText = req.getVerificationText();
    String url = method.getURI().toString();

    // save the browser and version if it's not yet been set
    if (har != null && har.getLog().getBrowser() == null) {
        Header[] uaHeaders = method.getHeaders("User-Agent");
        if (uaHeaders != null && uaHeaders.length > 0) {
            String userAgent = uaHeaders[0].getValue();
            try {
                // note: this doesn't work for 'Fandango/4.5.1 CFNetwork/548.1.4 Darwin/11.0.0'
                ReadableUserAgent uai = PARSER.parse(userAgent);
                String browser = uai.getName();
                String version = uai.getVersionNumber().toVersionString();
                har.getLog().setBrowser(new HarNameVersion(browser, version));
            } catch (Exception e) {
                LOG.warn("Failed to parse user agent string", e);
            }
        }
    }

    // process any rewrite requests
    boolean rewrote = false;
    String newUrl = url;
    for (RewriteRule rule : rewriteRules) {
        Matcher matcher = rule.match.matcher(newUrl);
        newUrl = matcher.replaceAll(rule.replace);
        rewrote = true;
    }

    if (rewrote) {
        try {
            method.setURI(new URI(newUrl));
            url = newUrl;
        } catch (URISyntaxException e) {
            LOG.warn("Could not rewrite url to %s", newUrl);
        }
    }

    // handle whitelist and blacklist entries
    int mockResponseCode = -1;
    synchronized (this) {
        // guard against concurrent modification of whitelistEntry
        if (whitelistEntry != null) {
            boolean found = false;
            for (Pattern pattern : whitelistEntry.patterns) {
                if (pattern.matcher(url).matches()) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                mockResponseCode = whitelistEntry.responseCode;
            }
        }
    }

    if (blacklistEntries != null) {
        for (BlacklistEntry blacklistEntry : blacklistEntries) {
            if (blacklistEntry.pattern.matcher(url).matches()) {
                mockResponseCode = blacklistEntry.responseCode;
                break;
            }
        }
    }

    if (!additionalHeaders.isEmpty()) {
        // Set the additional headers
        for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            method.removeHeaders(key);
            method.addHeader(key, value);
        }
    }

    String charSet = "UTF-8";
    String responseBody = null;

    InputStream is = null;
    int statusCode = -998;
    long bytes = 0;
    boolean gzipping = false;
    boolean contentMatched = true;
    OutputStream os = req.getOutputStream();
    if (os == null) {
        os = new CappedByteArrayOutputStream(1024 * 1024); // MOB-216 don't buffer more than 1 MB
    }
    if (verificationText != null) {
        contentMatched = false;
    }

    // link the object up now, before we make the request, so that if we get cut off (ie: favicon.ico request and browser shuts down)
    // we still have the attempt associated, even if we never got a response
    HarEntry entry = new HarEntry(harPageRef);

    // clear out any connection-related information so that it's not stale from previous use of this thread.
    RequestInfo.clear(url, entry);

    entry.setRequest(new HarRequest(method.getMethod(), url, method.getProtocolVersion().getProtocol()));
    entry.setResponse(new HarResponse(-999, "NO RESPONSE", method.getProtocolVersion().getProtocol()));
    if (this.har != null && harPageRef != null) {
        har.getLog().addEntry(entry);
    }

    String query = method.getURI().getRawQuery();
    if (query != null) {
        MultiMap<String> params = new MultiMap<String>();
        UrlEncoded.decodeTo(query, params, "UTF-8");
        for (String k : params.keySet()) {
            for (Object v : params.getValues(k)) {
                entry.getRequest().getQueryString().add(new HarNameValuePair(k, (String) v));
            }
        }
    }

    String errorMessage = null;
    HttpResponse response = null;

    BasicHttpContext ctx = new BasicHttpContext();

    ActiveRequest activeRequest = new ActiveRequest(method, ctx, entry.getStartedDateTime());
    synchronized (activeRequests) {
        activeRequests.add(activeRequest);
    }

    // for dealing with automatic authentication
    if (authType == AuthType.NTLM) {
        // todo: not supported yet
        //ctx.setAttribute("preemptive-auth", new NTLMScheme(new JCIFSEngine()));
    } else if (authType == AuthType.BASIC) {
        ctx.setAttribute("preemptive-auth", new BasicScheme());
    }

    StatusLine statusLine = null;
    try {
        // set the User-Agent if it's not already set
        if (method.getHeaders("User-Agent").length == 0) {
            method.addHeader("User-Agent", "BrowserMob VU/1.0");
        }

        // was the request mocked out?
        if (mockResponseCode != -1) {
            statusCode = mockResponseCode;

            // TODO: HACKY!!
            callback.handleHeaders(new Header[] { new Header() {
                @Override
                public String getName() {
                    return "Content-Type";
                }

                @Override
                public String getValue() {
                    return "text/plain";
                }

                @Override
                public HeaderElement[] getElements() throws ParseException {
                    return new HeaderElement[0];
                }
            } });
            // Make sure we set the status line here too.
            // Use the version number from the request
            ProtocolVersion version = null;
            int reqDotVersion = req.getProxyRequest().getDotVersion();
            if (reqDotVersion == -1) {
                version = new HttpVersion(0, 9);
            } else if (reqDotVersion == 0) {
                version = new HttpVersion(1, 0);
            } else if (reqDotVersion == 1) {
                version = new HttpVersion(1, 1);
            }
            // and if not any of these, trust that a Null version will
            // cause an appropriate error
            callback.handleStatusLine(
                    new BasicStatusLine(version, statusCode, "Status set by browsermob-proxy"));
            // No mechanism to look up the response text by status code,
            // so include a notification that this is a synthetic error code.
        } else {
            response = httpClient.execute(method, ctx);
            statusLine = response.getStatusLine();
            statusCode = statusLine.getStatusCode();

            if (callback != null) {
                callback.handleStatusLine(statusLine);
                callback.handleHeaders(response.getAllHeaders());
            }

            if (response.getEntity() != null) {
                is = response.getEntity().getContent();
            }

            // check for null (resp 204 can cause HttpClient to return null, which is what Google does with http://clients1.google.com/generate_204)
            if (is != null) {
                Header contentEncodingHeader = response.getFirstHeader("Content-Encoding");
                if (contentEncodingHeader != null
                        && "gzip".equalsIgnoreCase(contentEncodingHeader.getValue())) {
                    gzipping = true;
                }

                // deal with GZIP content!
                if (decompress && gzipping) {
                    is = new GZIPInputStream(is);
                }

                if (captureContent) {
                    // todo - something here?
                    os = new ClonedOutputStream(os);
                }

                bytes = copyWithStats(is, os);
            }
        }
    } catch (Exception e) {
        errorMessage = e.toString();

        if (callback != null) {
            callback.reportError(e);
        }

        // only log it if we're not shutdown (otherwise, errors that happen during a shutdown can likely be ignored)
        if (!shutdown) {
            LOG.info(String.format("%s when requesting %s", errorMessage, url));
        }
    } finally {
        // the request is done, get it out of here
        synchronized (activeRequests) {
            activeRequests.remove(activeRequest);
        }

        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // this is OK to ignore
            }
        }
    }

    // record the response as ended
    RequestInfo.get().finish();

    // set the start time and other timings
    entry.setStartedDateTime(RequestInfo.get().getStart());
    entry.setTimings(RequestInfo.get().getTimings());
    entry.setServerIPAddress(RequestInfo.get().getResolvedAddress());
    entry.setTime(RequestInfo.get().getTotalTime());

    // todo: where you store this in HAR?
    // obj.setErrorMessage(errorMessage);
    entry.getResponse().setBodySize(bytes);
    entry.getResponse().getContent().setSize(bytes);
    entry.getResponse().setStatus(statusCode);
    if (statusLine != null) {
        entry.getResponse().setStatusText(statusLine.getReasonPhrase());
    }

    boolean urlEncoded = false;
    if (captureHeaders || captureContent) {
        for (Header header : method.getAllHeaders()) {
            if (header.getValue() != null && header.getValue().startsWith(URLEncodedUtils.CONTENT_TYPE)) {
                urlEncoded = true;
            }

            entry.getRequest().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue()));
        }

        if (response != null) {
            for (Header header : response.getAllHeaders()) {
                entry.getResponse().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue()));
            }
        }
    }

    if (captureContent) {
        // can we understand the POST data at all?
        if (method instanceof HttpEntityEnclosingRequestBase && req.getCopy() != null) {
            HttpEntityEnclosingRequestBase enclosingReq = (HttpEntityEnclosingRequestBase) method;
            HttpEntity entity = enclosingReq.getEntity();

            HarPostData data = new HarPostData();
            data.setMimeType(req.getMethod().getFirstHeader("Content-Type").getValue());
            entry.getRequest().setPostData(data);

            if (urlEncoded || URLEncodedUtils.isEncoded(entity)) {
                try {
                    final String content = new String(req.getCopy().toByteArray(), "UTF-8");
                    if (content != null && content.length() > 0) {
                        List<NameValuePair> result = new ArrayList<NameValuePair>();
                        URLEncodedUtils.parse(result, new Scanner(content), null);

                        ArrayList<HarPostDataParam> params = new ArrayList<HarPostDataParam>();
                        data.setParams(params);

                        for (NameValuePair pair : result) {
                            params.add(new HarPostDataParam(pair.getName(), pair.getValue()));
                        }
                    }
                } catch (Exception e) {
                    LOG.info("Unexpected problem when parsing input copy", e);
                }
            } else {
                // not URL encoded, so let's grab the body of the POST and capture that
                data.setText(new String(req.getCopy().toByteArray()));
            }
        }
    }

    //capture request cookies
    javax.servlet.http.Cookie[] cookies = req.getProxyRequest().getCookies();
    for (javax.servlet.http.Cookie cookie : cookies) {
        HarCookie hc = new HarCookie();
        hc.setName(cookie.getName());
        hc.setValue(cookie.getValue());
        entry.getRequest().getCookies().add(hc);
    }

    String contentType = null;

    if (response != null) {
        try {
            Header contentTypeHdr = response.getFirstHeader("Content-Type");
            if (contentTypeHdr != null) {
                contentType = contentTypeHdr.getValue();
                entry.getResponse().getContent().setMimeType(contentType);

                if (captureContent && os != null && os instanceof ClonedOutputStream) {
                    ByteArrayOutputStream copy = ((ClonedOutputStream) os).getOutput();

                    if (gzipping) {
                        // ok, we need to decompress it before we can put it in the har file
                        try {
                            InputStream temp = new GZIPInputStream(
                                    new ByteArrayInputStream(copy.toByteArray()));
                            copy = new ByteArrayOutputStream();
                            IOUtils.copy(temp, copy);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    if (hasTextualContent(contentType)) {
                        setTextOfEntry(entry, copy, contentType);
                    } else if (captureBinaryContent) {
                        setBinaryContentOfEntry(entry, copy);
                    }
                }

                NameValuePair nvp = contentTypeHdr.getElements()[0].getParameterByName("charset");

                if (nvp != null) {
                    charSet = nvp.getValue();
                }
            }

            if (os instanceof ByteArrayOutputStream) {
                responseBody = ((ByteArrayOutputStream) os).toString(charSet);

                if (verificationText != null) {
                    contentMatched = responseBody.contains(verificationText);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    if (contentType != null) {
        entry.getResponse().getContent().setMimeType(contentType);
    }

    // checking to see if the client is being redirected
    boolean isRedirect = false;

    String location = null;
    if (response != null && statusCode >= 300 && statusCode < 400 && statusCode != 304) {
        isRedirect = true;

        // pulling the header for the redirect
        Header locationHeader = response.getLastHeader("location");
        if (locationHeader != null) {
            location = locationHeader.getValue();
        } else if (this.followRedirects) {
            throw new RuntimeException("Invalid redirect - missing location header");
        }
    }

    //
    // Response validation - they only work if we're not following redirects
    //

    int expectedStatusCode = req.getExpectedStatusCode();

    // if we didn't mock out the actual response code and the expected code isn't what we saw, we have a problem
    if (mockResponseCode == -1 && expectedStatusCode > -1) {
        if (this.followRedirects) {
            throw new RuntimeException("Response validation cannot be used while following redirects");
        }
        if (expectedStatusCode != statusCode) {
            if (isRedirect) {
                throw new RuntimeException("Expected status code of " + expectedStatusCode + " but saw "
                        + statusCode + " redirecting to: " + location);
            } else {
                throw new RuntimeException(
                        "Expected status code of " + expectedStatusCode + " but saw " + statusCode);
            }
        }
    }

    // Location header check:
    if (isRedirect && (req.getExpectedLocation() != null)) {
        if (this.followRedirects) {
            throw new RuntimeException("Response validation cannot be used while following redirects");
        }

        if (location.compareTo(req.getExpectedLocation()) != 0) {
            throw new RuntimeException(
                    "Expected a redirect to  " + req.getExpectedLocation() + " but saw " + location);
        }
    }

    // end of validation logic

    // basic tail recursion for redirect handling
    if (isRedirect && this.followRedirects) {
        // updating location:
        try {
            URI redirectUri = new URI(location);
            URI newUri = method.getURI().resolve(redirectUri);
            method.setURI(newUri);

            return execute(req, ++depth);
        } catch (URISyntaxException e) {
            LOG.warn("Could not parse URL", e);
        }
    }

    return new BrowserMobHttpResponse(entry, method, response, contentMatched, verificationText, errorMessage,
            responseBody, contentType, charSet);
}

From source file:net.yacy.cora.document.id.MultiProtocolURL.java

/**
 * Resolve '..' segments in the path.//  w  w  w. ja  v  a 2s.com
 * For standard pseudo algorithms, see :
 * <ul>
 * <li>https://tools.ietf.org/html/rfc3986#section-5.2.4</li>
 * <li>https://url.spec.whatwg.org/#path-state</li>
 * <li>https://www.w3.org/TR/url/#relative-path-state</li>
 * </ul>
 * @param path URL path part : must not be null
 * @return the path with '..' segments resolved
 */
private static final String resolveBackpath(final String path) {
    String p = path;
    if (p.isEmpty() || p.charAt(0) != '/') {
        p = "/" + p;
    }
    final Matcher qm = CommonPattern.QUESTION.matcher(p); // do not resolve backpaths in the post values
    final int end = qm.find() ? qm.start() : p.length();
    final Matcher matcher = backPathPattern.matcher(p);
    while (matcher.find()) {
        if (matcher.start() > end)
            break;
        p = matcher.replaceAll("");
        matcher.reset(p);
    }
    /* Let's remove any eventual remaining but inappropriate '..' segments at the beginning. 
     * See https://tools.ietf.org/html/rfc3986#section-5.2.4 -> parts 2.C and 2.D */
    while (p.startsWith("/../")) {
        p = p.substring(3);
    }
    if (p.equals("/..")) {
        p = "/";
    }
    return p.equals("") ? "/" : p;
}

From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java

public boolean performanceTestResultAvail(ApplicationInfo appInfo) throws PhrescoException {
    boolean isResultFileAvailable = false;
    try {//www  .  ja v  a  2s.  co m
        String baseDir = Utility.getProjectHome() + appInfo.getAppDirName();
        FrameworkUtil frameworkUtil = FrameworkUtil.getInstance();
        List<String> testResultsTypes = new ArrayList<String>();
        testResultsTypes.add("server");
        testResultsTypes.add("database");
        testResultsTypes.add("webservice");
        for (String testResultsType : testResultsTypes) {
            StringBuilder sb = new StringBuilder(baseDir.toString());
            String performanceReportDir = frameworkUtil.getPerformanceTestReportDir(appInfo);
            if (StringUtils.isNotEmpty(performanceReportDir) && StringUtils.isNotEmpty(testResultsType)) {
                Pattern p = Pattern.compile("dir_type");
                Matcher matcher = p.matcher(performanceReportDir);
                performanceReportDir = matcher.replaceAll(testResultsType);
                sb.append(performanceReportDir);
            }
            File file = new File(sb.toString());
            String resultExtension = FrameworkServiceUtil
                    .getPerformanceResultFileExtension(appInfo.getAppDirName(), "");
            if (StringUtils.isNotEmpty(resultExtension)) {
                File[] children = file.listFiles(new XmlNameFileFilter(resultExtension));
                if (!ArrayUtils.isEmpty(children)) {
                    isResultFileAvailable = true;
                    break;
                }
            }
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }

    return isResultFileAvailable;
}

From source file:org.openpplsoft.sql.StmtLibrary.java

private static String processAndExpandWhereStr(final String rootAlias, final String whereStr) {

    String newWhereStr = whereStr;

    // Expand any %EffDtCheck meta-SQL
    final Matcher effDtCheckMatcher = effDtCheckPattern.matcher(newWhereStr);
    while (effDtCheckMatcher.find()) {

        final String effDtCheckRecord = effDtCheckMatcher.group(1);
        // Do not use group 2 (contains whitespace preceding the optional subquery alias)
        String effDtSubqueryAlias = effDtCheckMatcher.group(3);
        final String effDtRootAlias = effDtCheckMatcher.group(4);
        String effDtBound = effDtCheckMatcher.group(5);

        if (!rootAlias.equals(effDtRootAlias)) {
            throw new OPSVMachRuntimeException(
                    "While preparing fill query, " + "found %EffDtCheck that has a root alias ("
                            + effDtRootAlias + ") different than expected (" + rootAlias + ").");
        }/* w  w  w. j a va 2  s .c o m*/

        // If subquery alias is not specified, use name of record being checked.
        if (effDtSubqueryAlias == null) {
            effDtSubqueryAlias = effDtCheckRecord;
        }

        StringBuilder effDtSubqueryBuilder = new StringBuilder("SELECT MAX(EFFDT) FROM ")
                .append(effDtCheckRecord).append(' ').append(effDtSubqueryAlias).append(" WHERE");

        final Record effDtRecord = DefnCache.getRecord(effDtCheckRecord);
        for (final Map.Entry<String, RecordField> cursor : effDtRecord.getFieldTable().entrySet()) {
            final RecordField rf = cursor.getValue();
            if (rf.isKey() && !rf.getFldName().equals("EFFDT")) {
                effDtSubqueryBuilder.append(' ').append(effDtSubqueryAlias).append('.').append(rf.getFldName())
                        .append('=').append(effDtRootAlias).append('.').append(rf.getFldName()).append(" AND");
            }
        }

        // If the effDtBound is not a meta-sql construct, it will not
        // be wrapped with TO_DATE later in this function, so wrap it now.
        if (effDtBound.length() == 0 || effDtBound.charAt(0) != '%') {
            effDtBound = "TO_DATE(" + effDtBound + ",'YYYY-MM-DD')";
        }

        effDtSubqueryBuilder.append(' ').append(effDtSubqueryAlias).append(".EFFDT<=").append(effDtBound);

        newWhereStr = effDtCheckMatcher
                .replaceAll(effDtRootAlias + ".EFFDT=(" + effDtSubqueryBuilder.toString() + ")");
    }

    // Replace occurrences of %DATEIN/DateIn with TO_DATE(*,'YYYY-MM-DD')
    final Matcher dateInMatcher = dateInPattern.matcher(newWhereStr);
    final StringBuffer dateInSb = new StringBuffer();
    while (dateInMatcher.find()) {
        dateInMatcher.appendReplacement(dateInSb, "TO_DATE(" + dateInMatcher.group(2) + ",'YYYY-MM-DD')");
    }
    dateInMatcher.appendTail(dateInSb);
    newWhereStr = dateInSb.toString();

    // Replace occurrences of %CurrentDateIn
    final Matcher currDateInMatcher = currDateInPattern.matcher(newWhereStr);
    newWhereStr = currDateInMatcher.replaceAll("TO_DATE(TO_CHAR(SYSDATE,'YYYY-MM-DD'),'YYYY-MM-DD')");

    return newWhereStr;
}

From source file:com.tao.realweb.util.StringUtil.java

/** 
* ? /*from   www .j  av a2 s .  c om*/
*  
* @param str 
*            ? 
* @param sr 
*            ?? 
* @param sd 
*            ? 
* @return  
*/
public static String stringReplace(String str, String sr, String sd) {
    String regEx = sr;
    Pattern p = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(str);
    str = m.replaceAll(sd);
    return str;
}

From source file:com.icesoft.faces.webapp.parser.JspPageToDocument.java

/**
 * @param input//from   ww w.j  a  v a  2 s.c o m
 * @return String
 */
public static String transform(String input) {
    String result = input;

    Pattern jspDeclarationPattern = Pattern.compile(JSP_DECL_PATTERN, Pattern.DOTALL);
    Matcher jspDeclarationMatcher = jspDeclarationPattern.matcher(result);
    if (!jspDeclarationMatcher.find()) {
        //no JSP declarations, must be a JSP Document, not a page
        return (preprocessJspDocument(result));
    }

    result = performStaticInclude(STATIC_INCLUDE_PATTERN, input);

    result = toLowerHTML(result);

    Pattern jspTaglibPattern = Pattern.compile(JSP_TAGLIB_PATTERN, Pattern.DOTALL);
    Pattern openTagPattern = Pattern.compile(OPEN_TAG_PATTERN, Pattern.DOTALL);
    Pattern attributePattern = Pattern.compile(ATTRIBUTE_PATTERN, Pattern.DOTALL);
    Pattern prefixPattern = Pattern.compile(PREFIX_PATTERN, Pattern.DOTALL);
    Pattern uriPattern = Pattern.compile(URI_PATTERN, Pattern.DOTALL);

    Hashtable declarationsTable = new Hashtable();
    Matcher jspTaglibMatcher = jspTaglibPattern.matcher(result);
    declarationsTable.put("xmlns:jsp", "jsp");
    declarationsTable.put("xmlns:icefaces", "http://www.icesoft.com/icefaces");

    while (jspTaglibMatcher.find()) {
        String attributes = jspTaglibMatcher.group(1);
        Matcher prefixMatcher = prefixPattern.matcher(attributes);
        Matcher uriMatcher = uriPattern.matcher(attributes);
        prefixMatcher.find();
        uriMatcher.find();
        String prefix = prefixMatcher.group(1);
        String url = uriMatcher.group(1);
        declarationsTable.put("xmlns:" + prefix, url);
    }

    Matcher openTagMatcher = openTagPattern.matcher(result);
    openTagMatcher.find();
    String tag = openTagMatcher.group(1);
    String attributes = openTagMatcher.group(2);

    Matcher attributeMatcher = attributePattern.matcher(attributes);
    while (attributeMatcher.find()) {
        String name = attributeMatcher.group(1);
        String value = attributeMatcher.group(2);
        declarationsTable.put(name, value);
    }

    Enumeration declarations = declarationsTable.keys();
    String namespaceDeclarations = "";
    while (declarations.hasMoreElements()) {
        String prefix = (String) declarations.nextElement();
        String url = (String) declarationsTable.get(prefix);
        namespaceDeclarations += prefix + "=\"" + url + "\" ";
    }

    jspDeclarationMatcher = jspDeclarationPattern.matcher(result);
    result = jspDeclarationMatcher.replaceAll("");

    //ensure single root tag for all JSPs as per bug 361
    result = "<icefaces:root " + namespaceDeclarations + ">" + result + "</icefaces:root>";

    Pattern jspIncludePattern = Pattern.compile(JSP_INCLUDE_PATTERN);
    Matcher jspIncludeMatcher = jspIncludePattern.matcher(result);
    StringBuffer jspIncludeBuf = new StringBuffer();
    while (jspIncludeMatcher.find()) {
        String args = jspIncludeMatcher.group(1);
        jspIncludeMatcher.appendReplacement(jspIncludeBuf,
                "<icefaces:include" + args + " isDynamic=\"#{true}\" />");
    }
    jspIncludeMatcher.appendTail(jspIncludeBuf);
    result = jspIncludeBuf.toString();

    //Fix HTML
    result = toSingletonTag(P_TAG_PATTERN, result);
    result = toSingletonTag(LINK_TAG_PATTERN, result);
    result = toSingletonTag(META_TAG_PATTERN, result);
    result = toSingletonTag(IMG_TAG_PATTERN, result);
    result = toSingletonTag(INPUT_TAG_PATTERN, result);

    Pattern brTagPattern = Pattern.compile(BR_TAG_PATTERN);
    Matcher brTagMatcher = brTagPattern.matcher(result);
    result = brTagMatcher.replaceAll("<br/>");

    Pattern hrTagPattern = Pattern.compile(HR_TAG_PATTERN);
    Matcher hrTagMatcher = hrTagPattern.matcher(result);
    result = hrTagMatcher.replaceAll("<hr/>");

    Pattern nbspEntityPattern = Pattern.compile(NBSP_ENTITY_PATTERN);
    Matcher nbspEntityMatcher = nbspEntityPattern.matcher(result);
    //  result = nbspEntityMatcher.replaceAll("&nbsp;");
    result = nbspEntityMatcher.replaceAll("&amp;nbsp");

    Pattern copyEntityPattern = Pattern.compile(COPY_ENTITY_PATTERN);
    Matcher copyEntityMatcher = copyEntityPattern.matcher(result);
    result = copyEntityMatcher.replaceAll("&#169;");

    Pattern docDeclPattern = Pattern.compile(DOC_DECL_PATTERN);
    Matcher docDeclMatcher = docDeclPattern.matcher(result);
    result = docDeclMatcher.replaceAll("");

    result = unescapeBackslash(result);

    return result;
}

From source file:com.tao.realweb.util.StringUtil.java

/** 
* ????? //from   www.j a  v a 2s .  com
*  
* @param str 
* @return 
*/
public static String replaceBlank(String str) {
    if (str != null) {
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(str);
        str = m.replaceAll("");
    }
    return str;
}

From source file:com.tao.realweb.util.StringUtil.java

/** 
* html //from   ww w.  ja  v  a 2 s .  c o  m
*  
* @param htmlstr 
* @return 
*/
public static String removeHtmlTag(String htmlstr) {
    Pattern pat = Pattern.compile("\\s*<.*?>\\s*",
            Pattern.DOTALL | Pattern.MULTILINE | Pattern.CASE_INSENSITIVE); // \\s?[s|Sc|Cr|Ri|Ip|Pt|T]  
    Matcher m = pat.matcher(htmlstr);
    String rs = m.replaceAll("");
    rs = rs.replaceAll(" ", " ");
    rs = rs.replaceAll("<", "<");
    rs = rs.replaceAll(">", ">");
    return rs;
}