jetbrains.buildServer.web.util
Class WebUtil

java.lang.Object
  extended by jetbrains.buildServer.web.util.WebUtil

public class WebUtil
extends java.lang.Object

Utility class containing various useful methods for web controllers


Nested Class Summary
static interface WebUtil.ParameterFilter
          Query string parameters filter
 
Field Summary
static java.lang.String DEFAULT_WEB_DATE_FORMAT
           
static java.lang.String FRAGMENT_ID_PARAM
           
static java.lang.String GUEST_AUTH_PREFIX
           
static java.lang.String HTTP_AUTH_PREFIX
           
static java.lang.String NTLM_AUTH_PREFIX
           
 
Method Summary
static void addCacheHeadersForIE(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Fixes IE problem when it cannot download files over https (see TW-9821).
static java.lang.String combineContextPath(java.lang.String prefixPath, java.lang.String path)
          Combines two path with prefix with regard to starting and trailing slashes.
static javax.servlet.http.Cookie createCookie(javax.servlet.http.HttpServletRequest request, java.lang.String name, java.lang.String value, int age)
          Creates a cookie with specified age
static java.lang.String createPathWithParameters(javax.servlet.http.HttpServletRequest request)
          Same as createPathWithParameters(javax.servlet.http.HttpServletRequest, jetbrains.buildServer.web.util.WebUtil.ParameterFilter) with default filter which accepts all parameters.
static java.lang.String createPathWithParameters(javax.servlet.http.HttpServletRequest request, WebUtil.ParameterFilter filter)
          From specified request creates part of the URL which contains path and query string.
static java.lang.String createRequestParameters(javax.servlet.http.HttpServletRequest request)
          Generate list of all requests parameters, i.e.
static java.lang.String createRequestParameters(javax.servlet.http.HttpServletRequest request, WebUtil.ParameterFilter filter)
          Generate list of all requests parameters, i.e.
static javax.servlet.http.Cookie createSessionCookie(javax.servlet.http.HttpServletRequest request, java.lang.String name, java.lang.String value)
          Creates session cookie (such cookie will be removed when browser exits).
static java.lang.String decode(java.lang.String string)
          Decodes specified string using URL encoding.
static void dumpRequest(javax.servlet.http.HttpServletRequest request, java.io.PrintStream out)
          Dumps request information to the specified print stream
static java.lang.String encode(java.lang.String string)
          Encodes specified string using URL encoding.
static java.lang.String escapeForJavaScript(java.lang.String text, boolean removeLineFeeds, boolean forHTMLAttribute)
          Escapes text so that it can be used in JavaScript string.
static java.lang.String escapeForJavaScriptIdentifier(java.lang.String text)
          Escapes string to be a javascript identifier
static java.lang.String escapeUrlForQuotes(java.lang.String url)
          Fixes security issues related to passing the URLs (or URL parts) to the quoted context as is.
static java.lang.String escapeXml(java.lang.String text)
          Replaces some characters like < > and others in the text with corresponding XML entities.
static java.lang.String firstLine(java.lang.String text)
          Return first line of a multiline text.
static java.lang.String getDeepestRequestUrl(javax.servlet.http.HttpServletRequest request)
          Returns currently processing request path with respect to servlet includes
static java.lang.String getFilename(SBuild build)
          Create filename candidate from build information, including project name and build type name and build number
static java.lang.String getMimeType(javax.servlet.http.HttpServletRequest request, java.lang.String relativePath)
           
static java.lang.String getOriginalPathWithoutAuthenticationType(javax.servlet.http.HttpServletRequest request)
          Returns original path without authentication types.
static java.lang.String getOriginalPathWithoutContext(javax.servlet.http.HttpServletRequest request)
          Returns path part of the request URL without context path.
static java.lang.String getPathFromUrl(java.lang.String url)
          Return path without session id and parameters
static java.lang.String getPathWithoutAuthenticationType(javax.servlet.http.HttpServletRequest request)
          Returns path without context and TeamCity specific authentication types, like httpAuth or guestAuth prefixes.
static java.lang.String getPathWithoutAuthenticationType(java.lang.String path)
          Returns path without context and TeamCity specific authentication types, like httpAuth or guestAuth prefixes.
static java.lang.String getPathWithoutContext(javax.servlet.http.HttpServletRequest request)
          Returns path part of the request URL without context path.
static java.lang.String getPathWithoutContext(javax.servlet.http.HttpServletRequest request, java.lang.String reqURI)
          Returns path part of the request URL without context path.
static java.lang.String getRequestDump(javax.servlet.http.HttpServletRequest request)
          Returns dump of a request as string.
static java.lang.String getRequestUrl(javax.servlet.http.HttpServletRequest request)
          Returns the URL used in request
static java.lang.String getRootUrl(javax.servlet.http.HttpServletRequest request)
          Reconstructs root URL from the specified request.
static java.lang.String getUserAgent(javax.servlet.http.HttpServletRequest request)
           
static boolean isAbsolute(java.lang.String url)
          Returns true if url is not relative, i.e.
static boolean isAjaxRequest(javax.servlet.http.HttpServletRequest request)
          Checks if request is AJAX request
static boolean isIE(javax.servlet.http.HttpServletRequest request)
          Returns true if the request's client is MSIE.
static boolean isJspPath(java.lang.String path)
          Returns true if the specified path taken from the HTTP request points to JSP
static boolean isPageFragmentRequest(javax.servlet.http.HttpServletRequest request)
          Returns true if request is about to serve page fragment.
static boolean isProbablyBrowser(javax.servlet.http.HttpServletRequest request)
          Returns true if user agent header specified in the request indicates that request was sent from a commonly known browser
static boolean isSafari(javax.servlet.http.HttpServletRequest request)
          Returns true if the request's client is Safari.
static void logRequestWarn(java.lang.String message, java.lang.Exception e, javax.servlet.http.HttpServletRequest request, com.intellij.openapi.diagnostic.Logger log)
          Logs warning that occurred during request processing.
static java.lang.String makeBreakable(java.lang.String source, java.lang.String regexp, boolean escape)
          Makes the text breakable in HTML by replacing some places of the string with <wbr/> tags .
static void notFound(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.String errorString, com.intellij.openapi.diagnostic.Logger log)
          Generates 404 Not Found response and logs specified message into the specified logger
static java.lang.String removeSessionId(java.lang.String uri)
           
static void setContentDisposition(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.String fileName)
          Sets the proper "Content-Disposition" response header.
static void setContentDisposition(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.String fileName, boolean considerMimeType)
          Sets the proper "Content-Disposition" response header.
static void setMimeType(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.String relativePath)
          Computes MIME type for the file located by the specified relative path and sets it into the response.
static java.lang.String truncateStringValueWithDotsInTheMiddle(java.lang.String str, int maxLength)
          Truncates string by cutting the middle part if string length exceeds specified max length.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

NTLM_AUTH_PREFIX

public static final java.lang.String NTLM_AUTH_PREFIX
See Also:
Constant Field Values

HTTP_AUTH_PREFIX

public static final java.lang.String HTTP_AUTH_PREFIX
See Also:
Constant Field Values

GUEST_AUTH_PREFIX

public static final java.lang.String GUEST_AUTH_PREFIX
See Also:
Constant Field Values

DEFAULT_WEB_DATE_FORMAT

public static final java.lang.String DEFAULT_WEB_DATE_FORMAT

FRAGMENT_ID_PARAM

public static final java.lang.String FRAGMENT_ID_PARAM
See Also:
Constant Field Values
Method Detail

getPathWithoutContext

@NotNull
public static java.lang.String getPathWithoutContext(@NotNull
                                                             javax.servlet.http.HttpServletRequest request)
Returns path part of the request URL without context path. Note, for server-included controllers this method may return path if controller and not the original page path

Parameters:
request - request
Returns:
request path without context part
See Also:
getOriginalPathWithoutContext(javax.servlet.http.HttpServletRequest)

getOriginalPathWithoutContext

public static java.lang.String getOriginalPathWithoutContext(@NotNull
                                                             javax.servlet.http.HttpServletRequest request)
Returns path part of the request URL without context path. This is exactly the same path as user may see in address in the browser.

Parameters:
request - request
Returns:
request path without context part
Since:
7.0
See Also:
getPathWithoutContext(javax.servlet.http.HttpServletRequest)

getPathWithoutContext

@NotNull
public static java.lang.String getPathWithoutContext(@NotNull
                                                             javax.servlet.http.HttpServletRequest request,
                                                             @NotNull
                                                             java.lang.String reqURI)
Returns path part of the request URL without context path.

Parameters:
request - request
reqURI - request uri to process
Returns:
request path without context part

getPathFromUrl

@NotNull
public static java.lang.String getPathFromUrl(@NotNull
                                                      java.lang.String url)
Return path without session id and parameters

Parameters:
url - url
Returns:
url without session id and parameters

getPathWithoutAuthenticationType

public static java.lang.String getPathWithoutAuthenticationType(@NotNull
                                                                javax.servlet.http.HttpServletRequest request)
Returns path without context and TeamCity specific authentication types, like httpAuth or guestAuth prefixes. Note, this method may not return original path for included requests.

Parameters:
request - request
Returns:
request path without context part and without TeamCity specific authentication types
See Also:
getOriginalPathWithoutContext(javax.servlet.http.HttpServletRequest), getPathWithoutAuthenticationType(String)

getOriginalPathWithoutAuthenticationType

public static java.lang.String getOriginalPathWithoutAuthenticationType(@NotNull
                                                                        javax.servlet.http.HttpServletRequest request)
Returns original path without authentication types.

Parameters:
request - request
Returns:
request path without context part and without TeamCity specific authentication types
Since:
7.0
See Also:
getOriginalPathWithoutContext(javax.servlet.http.HttpServletRequest), getPathWithoutAuthenticationType(javax.servlet.http.HttpServletRequest), getPathWithoutAuthenticationType(String)

getPathWithoutAuthenticationType

public static java.lang.String getPathWithoutAuthenticationType(@NotNull
                                                                java.lang.String path)
Returns path without context and TeamCity specific authentication types, like httpAuth or guestAuth prefixes.

Parameters:
request - path
Returns:
request path without context part and without TeamCity specific authentication types
Since:
7.0

removeSessionId

@NotNull
public static java.lang.String removeSessionId(@NotNull
                                                       java.lang.String uri)

combineContextPath

public static java.lang.String combineContextPath(@NotNull
                                                  java.lang.String prefixPath,
                                                  @NotNull
                                                  java.lang.String path)
Combines two path with prefix with regard to starting and trailing slashes.

Parameters:
prefixPath - prefix path
path - path
Returns:
path staring with /[prefix path]/[path] without double slashes between [prefix path] and [path]

getRootUrl

@NotNull
public static java.lang.String getRootUrl(@NotNull
                                                  javax.servlet.http.HttpServletRequest request)
Reconstructs root URL from the specified request. Root URL will include HTTP protocol prefix, server name, port and context path (for example, https://www.somehost.com/bs)

Parameters:
request - request
Returns:
root URL

isAbsolute

public static boolean isAbsolute(@NotNull
                                 java.lang.String url)
Returns true if url is not relative, i.e. starts with protocol http:// or https://

Parameters:
url - url
Returns:
see above

getMimeType

@NotNull
public static java.lang.String getMimeType(javax.servlet.http.HttpServletRequest request,
                                                   java.lang.String relativePath)

setMimeType

public static void setMimeType(javax.servlet.http.HttpServletRequest request,
                               javax.servlet.http.HttpServletResponse response,
                               java.lang.String relativePath)
Computes MIME type for the file located by the specified relative path and sets it into the response.

Parameters:
request - request
response - response
relativePath - path to a file which MIME type is to be set

notFound

public static void notFound(javax.servlet.http.HttpServletRequest request,
                            javax.servlet.http.HttpServletResponse response,
                            java.lang.String errorString,
                            @Nullable
                            com.intellij.openapi.diagnostic.Logger log)
                     throws java.io.IOException
Generates 404 Not Found response and logs specified message into the specified logger

Parameters:
response - response
errorString - message to log
log - logger to log message to
Throws:
java.io.IOException - IO exception if failed to write 404 response

encode

@NotNull
public static java.lang.String encode(@Nullable
                                              java.lang.String string)
Encodes specified string using URL encoding.

Parameters:
string - string to encode
Returns:
URL encoded string

decode

@NotNull
public static java.lang.String decode(@Nullable
                                              java.lang.String string)
Decodes specified string using URL encoding.

Parameters:
string - string to decode
Returns:
URL decoded string
Since:
7.0

escapeXml

public static java.lang.String escapeXml(java.lang.String text)
Replaces some characters like < > and others in the text with corresponding XML entities.

Parameters:
text - test
Returns:
text with XML entities

createPathWithParameters

@NotNull
public static java.lang.String createPathWithParameters(@NotNull
                                                                javax.servlet.http.HttpServletRequest request)
Same as createPathWithParameters(javax.servlet.http.HttpServletRequest, jetbrains.buildServer.web.util.WebUtil.ParameterFilter) with default filter which accepts all parameters.

Parameters:
request - current http request.
Returns:
path with parameters

createPathWithParameters

@NotNull
public static java.lang.String createPathWithParameters(@NotNull
                                                                javax.servlet.http.HttpServletRequest request,
                                                                @NotNull
                                                                WebUtil.ParameterFilter filter)
From specified request creates part of the URL which contains path and query string. Returned string always starts with / character. For example, for the following URL: http://buildserver/context/path/to/some/file.html?param1=value

this method will return: /context/path/to/some/file.html?param1=value

Parameters:
request - request
filter - to strip unneeded parameters from query string
Returns:
path and parameters

createRequestParameters

@NotNull
public static java.lang.String createRequestParameters(@NotNull
                                                               javax.servlet.http.HttpServletRequest request)
Generate list of all requests parameters, i.e. param1=value1¶m2=value2...

Parameters:
request - request
Returns:
parameters of request without leading '?' symbol
Since:
7.1

createRequestParameters

@NotNull
public static java.lang.String createRequestParameters(@NotNull
                                                               javax.servlet.http.HttpServletRequest request,
                                                               @NotNull
                                                               WebUtil.ParameterFilter filter)
Generate list of all requests parameters, i.e. param1=value1¶m2=value2...

Parameters:
request - request
filter - to strip unneeded parameter from query
Returns:
parameters of request without leading '?' symbol
Since:
7.1

getFilename

public static java.lang.String getFilename(@NotNull
                                           SBuild build)
Create filename candidate from build information, including project name and build type name and build number

Parameters:
build - build for which filename should be returned
Returns:
safe filename candidate for this build without extension

escapeForJavaScriptIdentifier

@NotNull
public static java.lang.String escapeForJavaScriptIdentifier(@Nullable
                                                                     java.lang.String text)
Escapes string to be a javascript identifier

Parameters:
text - id to escape
Returns:
escaped id
Since:
6.0

escapeForJavaScript

public static java.lang.String escapeForJavaScript(@NotNull
                                                   java.lang.String text,
                                                   boolean removeLineFeeds,
                                                   boolean forHTMLAttribute)
Escapes text so that it can be used in JavaScript string.

Parameters:
text - text to escape
removeLineFeeds - whether to remove line feeds from the text
forHTMLAttribute - specify true if text is supposed to be used in HTML attribute, in this case some characters will be replaced with HTML entities.
Returns:
text prepared to be using in JavaScript string

escapeUrlForQuotes

@NotNull
public static java.lang.String escapeUrlForQuotes(@Nullable
                                                          java.lang.String url)
Fixes security issues related to passing the URLs (or URL parts) to the quoted context as is. A quoted context can be an HTML attribute value, or javascript string literal, etc.

Suppose you use the ${url} like this in your JSP:

 SomeJsFunction("foo", '${url}', 0);
 
Passing the url equal to http://server/page.html?','');alert(1)// will lead to
 SomeJsFunction("foo", 'http://server/page.html?','');alert(1)//', 0);
 
Which executes not only SomeJsFunction function, but also user provided code (alert(1)).

A similar issue can arise in pure HTML like this:

 <form action="${url}">...</form>
 
If the url is http://server/page.html?"><script>alert(1)</script>

In order to resolve the issue, but still support URLs containing special characters, this function urlencodes dangerous characters with %-entities.

Parameters:
url - the url to process.
Returns:
the encoded url

dumpRequest

public static void dumpRequest(javax.servlet.http.HttpServletRequest request,
                               java.io.PrintStream out)
Dumps request information to the specified print stream

Parameters:
request - request
out - print stream

getRequestDump

public static java.lang.String getRequestDump(javax.servlet.http.HttpServletRequest request)
Returns dump of a request as string.

Parameters:
request - request
Returns:
dump of a request as string

logRequestWarn

public static void logRequestWarn(@NotNull
                                  java.lang.String message,
                                  @Nullable
                                  java.lang.Exception e,
                                  @NotNull
                                  javax.servlet.http.HttpServletRequest request,
                                  @NotNull
                                  com.intellij.openapi.diagnostic.Logger log)
Logs warning that occurred during request processing.

Parameters:
message - warning message
e - exception that occurred, if any
request - request during which the error occurred
log - the log to add message to

makeBreakable

public static java.lang.String makeBreakable(@NotNull
                                             java.lang.String source,
                                             @NotNull
                                             java.lang.String regexp,
                                             boolean escape)
Makes the text breakable in HTML by replacing some places of the string with <wbr/> tags .

Parameters:
source - source text
regexp - a regular expression identifying a place where replacement should be done
escape - whether entities should be escaped
Returns:
HTML breakable text

firstLine

public static java.lang.String firstLine(java.lang.String text)
Return first line of a multiline text. If there is only one line, return it.

Parameters:
text - source text
Returns:
First line of the text, or whole text if there is no newline character

createSessionCookie

public static javax.servlet.http.Cookie createSessionCookie(javax.servlet.http.HttpServletRequest request,
                                                            java.lang.String name,
                                                            java.lang.String value)
Creates session cookie (such cookie will be removed when browser exits).

Parameters:
request - HTTP request
name - cookie name
value - cookie value
Returns:
session cookie

createCookie

public static javax.servlet.http.Cookie createCookie(javax.servlet.http.HttpServletRequest request,
                                                     java.lang.String name,
                                                     java.lang.String value,
                                                     int age)
Creates a cookie with specified age

Parameters:
request - HTTP request
name - cookie name
value - cookie value
age - age in seconds
Returns:
cookie

isProbablyBrowser

public static boolean isProbablyBrowser(javax.servlet.http.HttpServletRequest request)
Returns true if user agent header specified in the request indicates that request was sent from a commonly known browser

Parameters:
request - HTTP request
Returns:
see above

getUserAgent

@Nullable
public static java.lang.String getUserAgent(@NotNull
                                                     javax.servlet.http.HttpServletRequest request)
Returns:
returns request user agent.
Since:
7.0

truncateStringValueWithDotsInTheMiddle

@Nullable
public static java.lang.String truncateStringValueWithDotsInTheMiddle(java.lang.String str,
                                                                               int maxLength)
Truncates string by cutting the middle part if string length exceeds specified max length. The resulting string also will be escaped and prepared for using in HTML page.

Parameters:
str - string to trim
maxLength - max length
Returns:
see above

isJspPath

public static boolean isJspPath(java.lang.String path)
Returns true if the specified path taken from the HTTP request points to JSP

Parameters:
path - path
Returns:
see above

isIE

public static boolean isIE(@NotNull
                           javax.servlet.http.HttpServletRequest request)
Returns true if the request's client is MSIE.

Parameters:
request - http request
Returns:
see above

isSafari

public static boolean isSafari(@NotNull
                               javax.servlet.http.HttpServletRequest request)
Returns true if the request's client is Safari.

Parameters:
request - http request
Returns:
see above

addCacheHeadersForIE

public static void addCacheHeadersForIE(@NotNull
                                        javax.servlet.http.HttpServletRequest request,
                                        @NotNull
                                        javax.servlet.http.HttpServletResponse response)
Fixes IE problem when it cannot download files over https (see TW-9821). This is due to the cache headers: The right headers are:

Parameters:
request - an http request
response - the response to make

setContentDisposition

public static void setContentDisposition(@NotNull
                                         javax.servlet.http.HttpServletRequest request,
                                         @NotNull
                                         javax.servlet.http.HttpServletResponse response,
                                         @NotNull
                                         java.lang.String fileName)
Sets the proper "Content-Disposition" response header. Can be "inline" or "attachment" depending on the fileName specified.

Parameters:
request - http request
response - http response
fileName - file name

setContentDisposition

public static void setContentDisposition(@NotNull
                                         javax.servlet.http.HttpServletRequest request,
                                         @NotNull
                                         javax.servlet.http.HttpServletResponse response,
                                         @NotNull
                                         java.lang.String fileName,
                                         boolean considerMimeType)
Sets the proper "Content-Disposition" response header. Can be "inline" or "attachment" depending on the fileName specified (if considerMimeType is true).

Since 7.1, the request parameters "forceInline" and "forceAttachment" can be used to apply "inline" or "attachment" type no matter what.

Since 8.0 supports correct Unicode file names for all modern browsers.

Parameters:
response - http response
fileName - file name
considerMimeType - use "inline" type or not depending on fileName extension (note: "inline" may cause problems in IE)

isAjaxRequest

public static boolean isAjaxRequest(@NotNull
                                    javax.servlet.http.HttpServletRequest request)
Checks if request is AJAX request

Parameters:
request - request to check
Returns:
true if request if AJAX
Since:
7.1

isPageFragmentRequest

public static boolean isPageFragmentRequest(@NotNull
                                            javax.servlet.http.HttpServletRequest request)
Returns true if request is about to serve page fragment.

Parameters:
request - request to check
Returns:
true if page fragment should be returned for this request
Since:
7.1

getRequestUrl

@NotNull
public static java.lang.String getRequestUrl(@NotNull
                                                     javax.servlet.http.HttpServletRequest request)
Returns the URL used in request

Parameters:
request - the request
Returns:
request URL as a string

getDeepestRequestUrl

@NotNull
public static java.lang.String getDeepestRequestUrl(@NotNull
                                                            javax.servlet.http.HttpServletRequest request)
Returns currently processing request path with respect to servlet includes

Parameters:
request - request
Returns:
currently processing request URL (including servlet's include url) without context and auth
Since:
8.0