Package jetbrains.buildServer.web.util
Class WebUtil
- java.lang.Object
-
- jetbrains.buildServer.web.util.WebUtil
-
public final class WebUtil extends Object
Utility class containing various useful methods for web controllers
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interface
WebUtil.ParameterFilter
Query string parameters filter
-
Field Summary
Fields Modifier and Type Field Description static String
DEFAULT_WEB_DATE_FORMAT
static String
FRAGMENT_ID_PARAM
static String
GUEST_AUTH_PREFIX
static String
HTTP_AUTH_PREFIX
static String
TC_SKIP_LOG_SESSION_MARKER
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description 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 String
combineContextPath(String prefixPath, 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, String name, String value, int age)
Creates a cookie with specified agestatic String
createPathWithParameters(javax.servlet.http.HttpServletRequest request)
Same ascreatePathWithParameters(javax.servlet.http.HttpServletRequest, jetbrains.buildServer.web.util.WebUtil.ParameterFilter)
with default filter which accepts all parameters.static 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 String
createRequestParameters(javax.servlet.http.HttpServletRequest request)
Generate list of all requests parameters, i.e.static String
createRequestParameters(javax.servlet.http.HttpServletRequest request, WebUtil.ParameterFilter filter)
Generate list of all requests parameters, i.e.static String
createRequestWithoutInit(javax.servlet.http.HttpServletRequest request)
Creates a new URL with all request parameters, except "init=1", if present.static javax.servlet.http.Cookie
createSessionCookie(javax.servlet.http.HttpServletRequest request, String name, String value)
Creates session cookie (such cookie will be removed when browser exits).static String
decode(String string)
Deprecated.static void
dumpRequest(javax.servlet.http.HttpServletRequest request, PrintStream out)
Dumps request information to the specified print streamstatic String
encode(String string)
Deprecated.static String
escapeForJavaScript(String text, boolean removeLineFeeds, boolean forHTMLAttribute)
Escapes text so that it can be used in JavaScript string.static String
escapeForJavaScriptIdentifier(String text)
Escapes string to be a javascript identifierstatic String
escapeUrlForQuotes(String url)
Fixes security issues related to passing the URLs (or URL parts) to the quoted context as is.static String
escapeXml(String text)
Replaces some characters like < > and others in the text with corresponding XML entities.static boolean
experimentalUIToggleEnabled(javax.servlet.http.HttpServletRequest request)
Deprecated.experimental features are only used on dedicated pages, see withExperimentalOverviewstatic String
findRefererInRequest(javax.servlet.http.HttpServletRequest request)
Returns the request referrer ("REFERER"
or"HTTP_REFERER"
header).static String
firstLine(String text)
Return first line of a multiline text.static String
getContentDispositionValue(javax.servlet.http.HttpServletRequest request, String type, String fileName)
Returns a properContent-Disposition
value based on thetype
("inline", "attachment") and currentrequest
.static String
getDeepestRequestUrl(javax.servlet.http.HttpServletRequest request)
Returns currently processing request path with respect to servlet includesstatic int
getDefaultPort(String scheme)
Returns a default port according to the request schema.static String
getFilename(SBuild build)
Create filename candidate from build information, including project name and build type name and build numberstatic String
getHeaderDump(javax.servlet.http.HttpServletRequest request, String headerName)
Get string representation of the specified header in the form 'name : value'.static String
getLoggableSessionId(String httpSessionId)
static int
getMaxUiTestLimit()
static String
getMimeType(javax.servlet.http.HttpServletRequest request, String relativePath)
Deprecated.usegetMimeType(HttpServletRequest, String, boolean)
insteadstatic String
getMimeType(javax.servlet.http.HttpServletRequest request, String relativePath, boolean safeMode)
Computes MIME type for the file located by the specified relative path.static String
getOriginalPathWithoutAuthenticationType(javax.servlet.http.HttpServletRequest request)
Returns original path without authentication types.static String
getOriginalPathWithoutContext(javax.servlet.http.HttpServletRequest request)
Returns path part of the request URL without context path.static String
getOriginalRequestUrl(javax.servlet.http.HttpServletRequest request)
Returns the approximation of the URI including path and query string (and excluding protocol, host and port) for the original HTTP request received by TeamCity.static StringBuilder
getOriginUrl(javax.servlet.http.HttpServletRequest request)
static String
getPathFromUrl(String url)
Return path without session id and parametersstatic String
getPathWithoutAuthenticationType(String path)
Returns path without context and TeamCity specific authentication types, like httpAuth or guestAuth prefixes.static String
getPathWithoutAuthenticationType(javax.servlet.http.HttpServletRequest request)
Returns path without context and TeamCity specific authentication types, like httpAuth or guestAuth prefixes.static String
getPathWithoutContext(javax.servlet.http.HttpServletRequest request)
Returns path part of the request URL without context path.static String
getPathWithoutContext(javax.servlet.http.HttpServletRequest request, String reqURI)
Returns path part of the request URL without context path.static String
getQueryString(javax.servlet.http.HttpServletRequest request)
Returns query string of the request if there is one,null
otherwisestatic String
getRemoteAddress(javax.servlet.http.HttpServletRequest request)
static String
getRequestDump(javax.servlet.http.HttpServletRequest request)
Returns debug representation of a request as string suitable for logging.static String
getRequestURI(javax.servlet.http.HttpServletRequest request)
Returns URI of the requeststatic String
getRequestUrl(String requestURI, javax.servlet.http.HttpServletRequest request)
Returns the URL used inrequest
static String
getRequestUrl(javax.servlet.http.HttpServletRequest request)
Returns the URL used inrequest
static String
getRootUrl(javax.servlet.http.HttpServletRequest request)
Reconstructs root URL from the specified request.static String
getScheme(javax.servlet.http.HttpServletRequest request)
Returns a schema for request.static String
getServerName(javax.servlet.http.HttpServletRequest request)
Returns a server hostname for request.static int
getServerPort(javax.servlet.http.HttpServletRequest request)
Returns a server port for request.static javax.servlet.ServletContext
getServletContext(javax.servlet.http.HttpServletRequest request)
static String
getShortRequestDescription(javax.servlet.http.HttpServletRequest request)
static String
getUrlSafe(String url)
Returns url as-is if it's valid url (i.e.static String
getUserAgent(javax.servlet.http.HttpServletRequest request)
static String
hostAndPort(String ipOrHost, Integer portNumber)
static boolean
isAbsolute(String url)
Returns true if url is not relative, i.e.static boolean
isAjaxRequest(javax.servlet.http.HttpServletRequest request)
Checks if request is AJAX requeststatic boolean
isCommonExternalError(Throwable e)
static boolean
isExperimentalUIOptional()
static boolean
isForward(javax.servlet.http.HttpServletRequest request)
True if request is being forwarded to another resourcestatic boolean
isIE(javax.servlet.http.HttpServletRequest request)
Returns true if the request's client is IEstatic boolean
isIE10OrLower(javax.servlet.http.HttpServletRequest request)
Returns true if the request's client is IE <= 10.static boolean
isInclude(javax.servlet.http.HttpServletRequest request)
True if our resource is being included by another controller.static boolean
isJspPath(String path)
Returns true if the specified path taken from the HTTP request points to JSPstatic boolean
isJspPrecompilationRequest(javax.servlet.http.HttpServletRequest request)
Deprecated.since 2024.03static 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 browserstatic boolean
isReactUISupportAware(javax.servlet.http.HttpServletRequest request)
Deprecated.react is used in all supported browsersstatic boolean
isRedirectInternal(javax.servlet.http.HttpServletRequest request, String redirectAddress, String redirectTargetDir)
Verifies redirect leads to the same host (and path inside TeamCity if defined) to prevent the Open Redirect attackstatic boolean
isSafari(javax.servlet.http.HttpServletRequest request)
Returns true if the request's client is Safari.static boolean
isSecure(javax.servlet.http.HttpServletRequest request)
Returns true if the original request was made using https:// protocol, considers proxy-added headers for the detectionstatic boolean
isStandardPort(int port, boolean isHttps)
static boolean
isTeamCityAgent(javax.servlet.http.HttpServletRequest request)
Returns true if request is sent by a teamcity agentstatic boolean
isWebComponentSupportAware(javax.servlet.http.HttpServletRequest request)
static boolean
isWebSocketUpgradeRequest(javax.servlet.http.HttpServletRequest request)
Checks whether request is a HTTP upgrade to websocketstatic void
logRequestWarn(String message, Exception e, javax.servlet.http.HttpServletRequest request, Logger log)
Logs warning that occurred during request processing.static String
makeBreakable(String source, 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, String errorString, Logger log)
Generates 404 Not Found response and logs specified message into the specified loggerstatic void
preventCaching(javax.servlet.http.HttpServletResponse response)
Prevent the response from being cached.static String
removeSessionId(String uri)
static String
replace(String text, Matcher matcher, Function<String,String> nonMatched, Function<Matcher,String> matched)
static String
replace(String text, Pattern pattern, Function<String,String> nonMatched, Function<Matcher,String> matched)
Performs replacement allowing proper escaping for all text parts
Similar to Matcher.appendReplacement(StringBuffer, String) and Matcher.appendTail(StringBuffer) yet allows to perform changes on all text parts.static boolean
requirePostMethodFail(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
If request is not POST, send 405 status to response stream.static boolean
sakuraUIOpened(javax.servlet.http.HttpServletRequest request)
The attrubute is set in the overview-plugin index.jspstatic void
sendErrorPlain(javax.servlet.http.HttpServletResponse response, int statusCode, String text)
Sends error response with given statusCode and text message regarding the reason, in text/plain format (for better reading from console)static void
sendForbiddenPlain(javax.servlet.http.HttpServletResponse response, String reasonWhyForbidden)
Sends 403 Forbidden response with text message regarding the reason, in text/plain format (for better reading from console)static void
sendTextPlain(javax.servlet.http.HttpServletResponse response, int statusCode, String text)
Sends plain text response with given statusCode and text message, in text/plain format and with UTF-8 character encodingstatic void
setContentDisposition(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, String fileName)
Sets the proper "Content-Disposition" response header.static void
setContentDisposition(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, String fileName, boolean considerMimeType)
Sets the proper "Content-Disposition" response header.static void
setContextProject(Map model, SBuildType buildType)
Set parameterContextProjectInfo.CONTEXT_PROJECT_ATTR
into model from a given buildType, if possiblestatic void
setMimeType(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, String relativePath)
Computes MIME type for the file located by the specified relative path and sets it into the response.static String
truncateStringValueWithDotsInTheMiddle(String str, int maxLength)
Truncates string by cutting the middle part if string length exceeds specified max length.static boolean
useSakuraHeader()
Deprecated.Ring UI header is stablestatic boolean
withExperimentalOverview(javax.servlet.http.HttpServletRequest request)
static boolean
withExperimentalUI(javax.servlet.http.HttpServletRequest request)
Deprecated.experimental features are only used on dedicated pages, see withExperimentalOverview
-
-
-
Field Detail
-
HTTP_AUTH_PREFIX
public static final String HTTP_AUTH_PREFIX
- See Also:
- Constant Field Values
-
GUEST_AUTH_PREFIX
public static final String GUEST_AUTH_PREFIX
- See Also:
- Constant Field Values
-
DEFAULT_WEB_DATE_FORMAT
public static final String DEFAULT_WEB_DATE_FORMAT
-
TC_SKIP_LOG_SESSION_MARKER
public static final String TC_SKIP_LOG_SESSION_MARKER
- See Also:
- Constant Field Values
-
FRAGMENT_ID_PARAM
public static final String FRAGMENT_ID_PARAM
- See Also:
- Constant Field Values
-
-
Method Detail
-
getPathWithoutContext
@NotNull public static 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
@NotNull public static 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 String getPathWithoutContext(@NotNull javax.servlet.http.HttpServletRequest request, @NotNull String reqURI)
Returns path part of the request URL without context path.- Parameters:
request
- requestreqURI
- request uri to process- Returns:
- request path without context part
-
getPathFromUrl
@NotNull public static String getPathFromUrl(@NotNull String url)
Return path without session id and parameters- Parameters:
url
- url- Returns:
- url without session id and parameters, and without protocol/host parts
-
getPathWithoutAuthenticationType
public static 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 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 String getPathWithoutAuthenticationType(@NotNull String path)
Returns path without context and TeamCity specific authentication types, like httpAuth or guestAuth prefixes.- Parameters:
path
- path- Returns:
- request path without context part and without TeamCity specific authentication types
- Since:
- 7.0
-
combineContextPath
public static String combineContextPath(@NotNull String prefixPath, @NotNull String path)
Combines two path with prefix with regard to starting and trailing slashes.- Parameters:
prefixPath
- prefix pathpath
- path- Returns:
- path staring with /[prefix path]/[path] without double slashes between [prefix path] and [path]
-
getRootUrl
@NotNull public static 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
-
getOriginUrl
@NotNull public static StringBuilder getOriginUrl(@NotNull javax.servlet.http.HttpServletRequest request)
- Returns:
- Appropriate value for Origin: header for the corresponding request
-
getUrlSafe
public static String getUrlSafe(@Nullable String url)
Returns url as-is if it's valid url (i.e. starts with http(s) protocol). Returns null if url starts with "javascript:" protocol Otherwise, adds http protocol to the url to prevent other attacks via using some strange protocol- Since:
- 2023.05
-
isAbsolute
public static boolean isAbsolute(@NotNull String url)
Returns true if url is not relative, i.e. starts with protocol http:// or https://- Parameters:
url
- url- Returns:
- see above
-
isStandardPort
public static boolean isStandardPort(int port, boolean isHttps)
-
getDefaultPort
public static int getDefaultPort(@NotNull String scheme)
Returns a default port according to the request schema.- Parameters:
scheme
- request schema- Returns:
- default port number
- Since:
- 2017.1
-
getMimeType
@Deprecated @NotNull public static String getMimeType(javax.servlet.http.HttpServletRequest request, String relativePath)
Deprecated.usegetMimeType(HttpServletRequest, String, boolean)
instead
-
getMimeType
@NotNull public static String getMimeType(javax.servlet.http.HttpServletRequest request, String relativePath, boolean safeMode)
Computes MIME type for the file located by the specified relative path.- Parameters:
relativePath
- path to a file which MIME type is to be setsafeMode
- 'false' to use all known mime types (should only be used for serving files coming from trusted sources), 'true' to select from "text/plain" : "application/octet-stream" which ensures for example that content of html files is not be rendered by the browser- Since:
- 2017.2.3
-
setMimeType
public static void setMimeType(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, String relativePath)
Computes MIME type for the file located by the specified relative path and sets it into the response.- Parameters:
request
- requestresponse
- responserelativePath
- 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, String errorString, @Nullable Logger log) throws IOException
Generates 404 Not Found response and logs specified message into the specified logger- Parameters:
response
- responseerrorString
- message to loglog
- logger to log message to- Throws:
IOException
- IO exception if failed to write 404 response
-
sendForbiddenPlain
public static void sendForbiddenPlain(@NotNull javax.servlet.http.HttpServletResponse response, @NotNull String reasonWhyForbidden) throws IOException
Sends 403 Forbidden response with text message regarding the reason, in text/plain format (for better reading from console)- Throws:
IOException
- Since:
- 2017.1
-
sendErrorPlain
public static void sendErrorPlain(@NotNull javax.servlet.http.HttpServletResponse response, int statusCode, String text) throws IOException
Sends error response with given statusCode and text message regarding the reason, in text/plain format (for better reading from console)- Parameters:
text
- follows status code in the output body- Throws:
IOException
- Since:
- 2018.2
-
sendTextPlain
public static void sendTextPlain(@NotNull javax.servlet.http.HttpServletResponse response, int statusCode, String text) throws IOException
Sends plain text response with given statusCode and text message, in text/plain format and with UTF-8 character encoding- Parameters:
text
- follows status code in the output body- Throws:
IOException
- Since:
- 2019.2
-
encode
@Deprecated @NotNull public static String encode(@Nullable String string)
Deprecated.Encodes specified string using URL encoding. Beware that this method doesn't encode input string according to the URL specification. Use StringUtil#encodeURLParameter (or extend it to your needs) instead See TW-64163- Parameters:
string
- string to encode- Returns:
- URL encoded string
-
decode
@Deprecated @NotNull public static String decode(@Nullable String string)
Deprecated.Decodes specified string using "application/x-www-form-urlencoded" encoding. Beware that this method doesn't decode input string according to the URL specification. Use StringUrl#decodeURL instead See TW-64163- Parameters:
string
- string to decode- Returns:
- URL decoded string
- Since:
- 7.0
-
escapeXml
public static String escapeXml(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 String createPathWithParameters(@NotNull javax.servlet.http.HttpServletRequest request)
Same ascreatePathWithParameters(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 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=valuethis method will return: /context/path/to/some/file.html?param1=value
- Parameters:
request
- requestfilter
- to strip unneeded parameters from query string- Returns:
- path and parameters
-
createRequestParameters
@NotNull public static 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 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
- requestfilter
- to strip unneeded parameter from query- Returns:
- parameters of request without leading '?' symbol
- Since:
- 7.1
-
createRequestWithoutInit
@NotNull public static String createRequestWithoutInit(@NotNull javax.servlet.http.HttpServletRequest request)
Creates a new URL with all request parameters, except "init=1", if present.- Parameters:
request
- the request- Returns:
- a new URL
- Since:
- 8.1.1
-
getFilename
public static 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
-
requirePostMethodFail
public static boolean requirePostMethodFail(@NotNull javax.servlet.http.HttpServletRequest request, @NotNull javax.servlet.http.HttpServletResponse response)
If request is not POST, send 405 status to response stream.- Returns:
- true if HTTP method is not POST
- Since:
- 2017.1
-
escapeForJavaScriptIdentifier
@NotNull public static String escapeForJavaScriptIdentifier(@Nullable String text)
Escapes string to be a javascript identifier- Parameters:
text
- id to escape- Returns:
- escaped id
- Since:
- 6.0
-
escapeForJavaScript
public static String escapeForJavaScript(@NotNull String text, boolean removeLineFeeds, boolean forHTMLAttribute)
Escapes text so that it can be used in JavaScript string.- Parameters:
text
- text to escaperemoveLineFeeds
- whether to remove line feeds from the textforHTMLAttribute
- 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 String escapeUrlForQuotes(@Nullable 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 theurl
equal tohttp://server/page.html?','');alert(1)//
will lead toSomeJsFunction("foo", 'http://server/page.html?','');alert(1)//', 0);
Which executes not onlySomeJsFunction
function, but also user provided code (alert(1)
).A similar issue can arise in pure HTML like this:
<form action="${url}">...</form>
If theurl
ishttp://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, PrintStream out)
Dumps request information to the specified print stream- Parameters:
request
- requestout
- print stream
-
getRequestDump
public static String getRequestDump(@NotNull javax.servlet.http.HttpServletRequest request)
Returns debug representation of a request as string suitable for logging.- Parameters:
request
- request- Returns:
- dump of a request as string
-
hostAndPort
public static String hostAndPort(@NotNull String ipOrHost, @Nullable Integer portNumber)
-
getShortRequestDescription
public static String getShortRequestDescription(javax.servlet.http.HttpServletRequest request)
-
getLoggableSessionId
@NotNull public static String getLoggableSessionId(@Nullable String httpSessionId)
-
getRemoteAddress
public static String getRemoteAddress(@NotNull javax.servlet.http.HttpServletRequest request)
-
isSecure
public static boolean isSecure(@NotNull javax.servlet.http.HttpServletRequest request)
Returns true if the original request was made using https:// protocol, considers proxy-added headers for the detection- Since:
- 2018.1
-
getScheme
public static String getScheme(@NotNull javax.servlet.http.HttpServletRequest request)
Returns a schema for request.- Parameters:
request
- request.- Returns:
- schema.
- Since:
- 2017.1
-
getServerName
public static String getServerName(@NotNull javax.servlet.http.HttpServletRequest request)
Returns a server hostname for request.- Parameters:
request
- request.- Returns:
- server hostname.
- Since:
- 2017.1
-
getServerPort
public static int getServerPort(@NotNull javax.servlet.http.HttpServletRequest request)
Returns a server port for request.- Parameters:
request
- request.- Returns:
- server port.
- Since:
- 2017.1
-
getHeaderDump
@NotNull public static String getHeaderDump(@NotNull javax.servlet.http.HttpServletRequest request, @NotNull String headerName)
Get string representation of the specified header in the form 'name : value'. If there are multiple headers with the specified name, this method returns all of them separated by comma.
-
getMaxUiTestLimit
public static int getMaxUiTestLimit()
- Returns:
- Maximum number of tests to be shown on a WebPage with test details
- Since:
- 2017.1
-
logRequestWarn
public static void logRequestWarn(@NotNull String message, @Nullable Exception e, @NotNull javax.servlet.http.HttpServletRequest request, @NotNull Logger log)
Logs warning that occurred during request processing.- Parameters:
message
- warning messagee
- exception that occurred, if anyrequest
- request during which the error occurredlog
- the log to add message to
-
makeBreakable
public static String makeBreakable(@NotNull String source, @NotNull String regexp, boolean escape)
Makes the text breakable in HTML by replacing some places of the string with <wbr/> tags .- Parameters:
source
- source textregexp
- a regular expression identifying a place where replacement should be doneescape
- whether entities should be escaped- Returns:
- HTML breakable text
-
firstLine
public static String firstLine(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, String name, String value)
Creates session cookie (such cookie will be removed when browser exits).- Parameters:
request
- HTTP requestname
- cookie namevalue
- cookie value- Returns:
- session cookie
-
createCookie
public static javax.servlet.http.Cookie createCookie(javax.servlet.http.HttpServletRequest request, String name, String value, int age)
Creates a cookie with specified age- Parameters:
request
- HTTP requestname
- cookie namevalue
- cookie valueage
- age in seconds- Returns:
- cookie
-
isProbablyBrowser
public static boolean isProbablyBrowser(@NotNull 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
-
isTeamCityAgent
public static boolean isTeamCityAgent(@NotNull javax.servlet.http.HttpServletRequest request)
Returns true if request is sent by a teamcity agent- Parameters:
request
-- Returns:
- see above
- Since:
- 2023.03
-
getUserAgent
@Nullable public static String getUserAgent(@NotNull javax.servlet.http.HttpServletRequest request)
- Returns:
- returns request user agent.
- Since:
- 7.0
-
truncateStringValueWithDotsInTheMiddle
@Nullable public static String truncateStringValueWithDotsInTheMiddle(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 trimmaxLength
- max length- Returns:
- see above
-
isJspPath
public static boolean isJspPath(String path)
Returns true if the specified path taken from the HTTP request points to JSP- Parameters:
path
- path- Returns:
- see above
-
isIE10OrLower
public static boolean isIE10OrLower(@NotNull javax.servlet.http.HttpServletRequest request)
Returns true if the request's client is IE <= 10.- Parameters:
request
- http request- Returns:
- see above
-
isIE
public static boolean isIE(@NotNull javax.servlet.http.HttpServletRequest request)
Returns true if the request's client is IE- 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:- Cache-Control: no-store, no-cache, must-revalidate
- Pragma: no-cache
- Cache-Control: private,must-revalidate
- Pragma: private
- Parameters:
request
- an http requestresponse
- the response to make
-
setContentDisposition
public static void setContentDisposition(@NotNull javax.servlet.http.HttpServletRequest request, @NotNull javax.servlet.http.HttpServletResponse response, @NotNull String fileName)
Sets the proper "Content-Disposition" response header. Can be "inline" or "attachment" depending on thefileName
specified.- Parameters:
request
- http requestresponse
- http responsefileName
- file name
-
setContentDisposition
public static void setContentDisposition(@NotNull javax.servlet.http.HttpServletRequest request, @NotNull javax.servlet.http.HttpServletResponse response, @NotNull String fileName, boolean considerMimeType)
Sets the proper "Content-Disposition" response header. Can be "inline" or "attachment" depending on thefileName
specified (ifconsiderMimeType
istrue
).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:
request
- http requestresponse
- http responsefileName
- file nameconsiderMimeType
- use "inline" type or not depending onfileName
extension (note: "inline" may cause problems in IE)
-
getContentDispositionValue
@NotNull public static String getContentDispositionValue(@NotNull javax.servlet.http.HttpServletRequest request, @Nullable String type, @NotNull String fileName)
Returns a properContent-Disposition
value based on thetype
("inline", "attachment") and currentrequest
.- Parameters:
request
- http requesttype
- disposition type ("inline", "attachment". Can benull
, in this case it is not included)fileName
- file name- Since:
- 8.1
-
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
-
isWebSocketUpgradeRequest
public static boolean isWebSocketUpgradeRequest(@NotNull javax.servlet.http.HttpServletRequest request)
Checks whether request is a HTTP upgrade to websocket- Since:
- 9.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
-
getOriginalRequestUrl
@NotNull public static String getOriginalRequestUrl(@NotNull javax.servlet.http.HttpServletRequest request)
Returns the approximation of the URI including path and query string (and excluding protocol, host and port) for the original HTTP request received by TeamCity. NOTE: The parameters returned might include form parameters passed as body of the POST request. Also, it can return the parameters in the order different from original request See WebUtil.createPathWithParameters- Parameters:
request
- the request- Returns:
- request URL as a string
- See Also:
getRequestUrl(HttpServletRequest)
-
getRequestURI
@NotNull public static String getRequestURI(@NotNull javax.servlet.http.HttpServletRequest request)
Returns URI of the request- Parameters:
request
- request- Returns:
- URI
-
getRequestUrl
@NotNull public static String getRequestUrl(@NotNull javax.servlet.http.HttpServletRequest request)
Returns the URL used inrequest
- Parameters:
request
- the request- Returns:
- request URL as a string
-
getRequestUrl
@NotNull public static String getRequestUrl(@NotNull String requestURI, @NotNull javax.servlet.http.HttpServletRequest request)
Returns the URL used inrequest
- Parameters:
request
- the request- Returns:
- request URL as a string
- Since:
- 8.0.5
-
getQueryString
@Nullable public static String getQueryString(@NotNull javax.servlet.http.HttpServletRequest request)
Returns query string of the request if there is one,null
otherwise- Parameters:
request
- request- Returns:
- query string
- Since:
- 2022.04
-
getDeepestRequestUrl
@NotNull public static 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
-
getServletContext
@NotNull public static javax.servlet.ServletContext getServletContext(@NotNull javax.servlet.http.HttpServletRequest request)
-
preventCaching
public static void preventCaching(@NotNull javax.servlet.http.HttpServletResponse response)
Prevent the response from being cached. Seehttp://www.mnot.net/cache_docs
.- Since:
- 8.1
-
findRefererInRequest
@Nullable public static String findRefererInRequest(@NotNull javax.servlet.http.HttpServletRequest request)
Returns the request referrer ("REFERER"
or"HTTP_REFERER"
header). All modern browsers include the previous used page URL for one of those.- Parameters:
request
- the request- Returns:
- request referrer.
- Since:
- 8.1
-
setContextProject
public static void setContextProject(@NotNull Map model, @Nullable SBuildType buildType)
Set parameterContextProjectInfo.CONTEXT_PROJECT_ATTR
into model from a given buildType, if possible- Parameters:
model
- Spring web model- Since:
- 9.1
-
isInclude
public static boolean isInclude(@NotNull javax.servlet.http.HttpServletRequest request)
True if our resource is being included by another controller.- Parameters:
request
- current request object- Returns:
- see above
- Since:
- 10.0
- See Also:
RequestDispatcher.include(ServletRequest, ServletResponse)
-
isForward
public static boolean isForward(@NotNull javax.servlet.http.HttpServletRequest request)
True if request is being forwarded to another resource- Parameters:
request
- current request object- Returns:
- see above
- Since:
- 2020.1.2
- See Also:
RequestDispatcher.forward(ServletRequest, ServletResponse)
-
isJspPrecompilationRequest
public static boolean isJspPrecompilationRequest(@NotNull javax.servlet.http.HttpServletRequest request)
Deprecated.since 2024.03- Returns:
- true if request is JSP pre-compilation request
- Since:
- 2017.1
-
isWebComponentSupportAware
public static boolean isWebComponentSupportAware(@NotNull javax.servlet.http.HttpServletRequest request)
-
isReactUISupportAware
@Deprecated public static boolean isReactUISupportAware(@NotNull javax.servlet.http.HttpServletRequest request)
Deprecated.react is used in all supported browsers
-
isExperimentalUIOptional
public static boolean isExperimentalUIOptional()
- Returns:
- true if "Use experimental UI" option should be available in user settings
- Since:
- 2019.2
-
experimentalUIToggleEnabled
@Deprecated public static boolean experimentalUIToggleEnabled(@NotNull javax.servlet.http.HttpServletRequest request)
Deprecated.experimental features are only used on dedicated pages, see withExperimentalOverview
-
withExperimentalUI
@Deprecated public static boolean withExperimentalUI(@NotNull javax.servlet.http.HttpServletRequest request)
Deprecated.experimental features are only used on dedicated pages, see withExperimentalOverview
-
withExperimentalOverview
public static boolean withExperimentalOverview(@NotNull javax.servlet.http.HttpServletRequest request)
- Returns:
- true if experimental UI pages should be used by default for current user
- Since:
- 2018.2
-
sakuraUIOpened
public static boolean sakuraUIOpened(@NotNull javax.servlet.http.HttpServletRequest request)
The attrubute is set in the overview-plugin index.jsp- Parameters:
request
- The HTTP request to be checked for Sakura UI- Returns:
- true if a customer is on the Sakura UI Overview page.
- Since:
- 2020.2
-
useSakuraHeader
@Deprecated public static boolean useSakuraHeader()
Deprecated.Ring UI header is stable
-
replace
public static String replace(String text, Pattern pattern, Function<String,String> nonMatched, Function<Matcher,String> matched)
Performs replacement allowing proper escaping for all text parts
Similar to Matcher.appendReplacement(StringBuffer, String) and Matcher.appendTail(StringBuffer) yet allows to perform changes on all text parts.
Note that nonMatched called at least one even if nothing found. Given pattern"P"
Input Call Chain ""
nonMatched("")
"A"
nonMatched("A")
"AP"
nonMatched("A"), matched("P"), nonMatched("")
"APA"
nonMatched("A"), matched("P"), nonMatched("A")
"P"
nonMatched(""), matched("P"), nonMatched("")
Usage example (will highlight 'b' in text):
WebUtil.replace("a b c", Pattern.compile("b"), WebUtil::escapeXml, m -> "<b>" + WebUtil.escapeXml(m.group())) + "</b>";
- Parameters:
nonMatched
- called for non-matched fragmentsmatched
- called for matched fragments- Returns:
- text with replacements
- Since:
- 2018.1.2
-
replace
public static String replace(String text, Matcher matcher, Function<String,String> nonMatched, Function<Matcher,String> matched)
- Since:
- 2018.1.2
- See Also:
replace(String, Pattern, Function, Function)
-
isCommonExternalError
public static boolean isCommonExternalError(@Nullable Throwable e)
-
isRedirectInternal
public static boolean isRedirectInternal(@NotNull javax.servlet.http.HttpServletRequest request, @NotNull String redirectAddress, @Nullable String redirectTargetDir) throws MalformedURLException
Verifies redirect leads to the same host (and path inside TeamCity if defined) to prevent the Open Redirect attack- Parameters:
request
- current request objectredirectAddress
- redirect Url, may be set as internal (/where/to/go) and as external (https://teamcity..com/where/to/go.html) redirectTargetDir
- directory in the TeamCity path where @redirectAddress must be. If null the check of internal path will be omitted.- Returns:
- true if redirect leads to the same host as request and inside @redirectTargetDir
- Throws:
MalformedURLException
- if @redirectAddress (URL) is broken
-
-