repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1
value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
authlete/authlete-java-common | src/main/java/com/authlete/common/web/BearerToken.java | BearerToken.parse | public static String parse(String input)
{
if (input == null)
{
return null;
}
// First, check whether the input matches the pattern
// "Bearer {access-token}".
Matcher matcher = CHALLENGE_PATTERN.matcher(input);
// If the input matches the pattern.
if (matcher.matches())
{
// Return the value as is. Note that it is not Base64-encoded.
// See https://www.ietf.org/mail-archive/web/oauth/current/msg08489.html
return matcher.group(1);
}
else
{
// Assume that the input is formatted in
// application/x-www-form-urlencoded.
return extractFromFormParameters(input);
}
} | java | public static String parse(String input)
{
if (input == null)
{
return null;
}
// First, check whether the input matches the pattern
// "Bearer {access-token}".
Matcher matcher = CHALLENGE_PATTERN.matcher(input);
// If the input matches the pattern.
if (matcher.matches())
{
// Return the value as is. Note that it is not Base64-encoded.
// See https://www.ietf.org/mail-archive/web/oauth/current/msg08489.html
return matcher.group(1);
}
else
{
// Assume that the input is formatted in
// application/x-www-form-urlencoded.
return extractFromFormParameters(input);
}
} | [
"public",
"static",
"String",
"parse",
"(",
"String",
"input",
")",
"{",
"if",
"(",
"input",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"// First, check whether the input matches the pattern\r",
"// \"Bearer {access-token}\".\r",
"Matcher",
"matcher",
"=",
... | Extract the access token embedded in the input string.
<p>
This method assumes that the input string comes from one of
the following three places that are mentioned in "RFC 6750
(OAuth 2.0 Bearer Token Usage),
<a href="http://tools.ietf.org/html/rfc6750#section-2"
>2. Authenticated Requests</a>".
</p>
<blockquote>
<ol>
<li><a href="http://tools.ietf.org/html/rfc6750#section-2.1"
>Authorization Request Header Field</a>
<li><a href="http://tools.ietf.org/html/rfc6750#section-2.2"
>Form-Encoded Body Parameter</a>
<li><a href="http://tools.ietf.org/html/rfc6750#section-2.3"
>URI Query Parameter</a>
</ol>
</blockquote>
<p>
To be concrete, this method assumes that the format of the
input string is either of the following two.
</p>
<blockquote>
<ol>
<li><code>"Bearer <i>{access-token}</i>"</code>
<li>Parameters formatted in <code>application/x-www-form-urlencoded</code>
containing <code>access_token=<i>{access-token}</i></code>.
</ol>
</blockquote>
<p>
For example, both {@link #parse(String) parse} method calls below
return <code>"hello-world"</code>.
</p>
<pre>
BearerToken.parse("Bearer hello-world");
BearerToken.parse("key1=value1&access_token=hello-world");
</pre>
@param input
The input string to be parsed.
@return
The extracted access token, or <code>null</code> if not found.
@see <a href="http://tools.ietf.org/html/rfc6750"
>RFC 6750 (OAuth 2.0 Bearer Token Usage)</a> | [
"Extract",
"the",
"access",
"token",
"embedded",
"in",
"the",
"input",
"string",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/web/BearerToken.java#L102-L126 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/dto/Scope.java | Scope.setAttributes | public Scope setAttributes(Iterable<Pair> attributes)
{
if (attributes == null)
{
this.attributes = null;
return this;
}
List<Pair> list = new ArrayList<Pair>();
for (Pair attribute : attributes)
{
if (attribute == null || attribute.getKey() == null)
{
continue;
}
list.add(attribute);
}
int size = list.size();
if (size == 0)
{
this.attributes = null;
return this;
}
Pair[] array = new Pair[size];
this.attributes = list.toArray(array);
return this;
} | java | public Scope setAttributes(Iterable<Pair> attributes)
{
if (attributes == null)
{
this.attributes = null;
return this;
}
List<Pair> list = new ArrayList<Pair>();
for (Pair attribute : attributes)
{
if (attribute == null || attribute.getKey() == null)
{
continue;
}
list.add(attribute);
}
int size = list.size();
if (size == 0)
{
this.attributes = null;
return this;
}
Pair[] array = new Pair[size];
this.attributes = list.toArray(array);
return this;
} | [
"public",
"Scope",
"setAttributes",
"(",
"Iterable",
"<",
"Pair",
">",
"attributes",
")",
"{",
"if",
"(",
"attributes",
"==",
"null",
")",
"{",
"this",
".",
"attributes",
"=",
"null",
";",
"return",
"this",
";",
"}",
"List",
"<",
"Pair",
">",
"list",
... | Set attributes.
@param attributes
Attributes.
@return
{@code this} object.
@since 2.12 | [
"Set",
"attributes",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/dto/Scope.java#L249-L283 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/dto/Scope.java | Scope.extractNames | public static String[] extractNames(Scope[] scopes)
{
if (scopes == null)
{
return null;
}
// Create an array for scope names.
String[] names = new String[scopes.length];
// For each scope.
for (int i = 0; i < scopes.length; ++i)
{
// Scope at the index.
Scope scope = scopes[i];
// Extract the scope name.
names[i] = (scope == null) ? null : scope.getName();
}
// Extracted scope names.
return names;
} | java | public static String[] extractNames(Scope[] scopes)
{
if (scopes == null)
{
return null;
}
// Create an array for scope names.
String[] names = new String[scopes.length];
// For each scope.
for (int i = 0; i < scopes.length; ++i)
{
// Scope at the index.
Scope scope = scopes[i];
// Extract the scope name.
names[i] = (scope == null) ? null : scope.getName();
}
// Extracted scope names.
return names;
} | [
"public",
"static",
"String",
"[",
"]",
"extractNames",
"(",
"Scope",
"[",
"]",
"scopes",
")",
"{",
"if",
"(",
"scopes",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"// Create an array for scope names.\r",
"String",
"[",
"]",
"names",
"=",
"new",
... | Extract scope names.
@param scopes
Scopes.
@return
Scope names. If {@code scopes} is {@code null},
{@code null} is returned. | [
"Extract",
"scope",
"names",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/dto/Scope.java#L296-L318 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/web/URLCoder.java | URLCoder.encode | public static String encode(String input)
{
try
{
return URLEncoder.encode(input, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
// This never happens.
return input;
}
} | java | public static String encode(String input)
{
try
{
return URLEncoder.encode(input, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
// This never happens.
return input;
}
} | [
"public",
"static",
"String",
"encode",
"(",
"String",
"input",
")",
"{",
"try",
"{",
"return",
"URLEncoder",
".",
"encode",
"(",
"input",
",",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"// This never happens.\r",... | URL-encode the input with UTF-8.
@param input
A string to be encoded.
@return
Encoded string. | [
"URL",
"-",
"encode",
"the",
"input",
"with",
"UTF",
"-",
"8",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/web/URLCoder.java#L42-L53 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/web/URLCoder.java | URLCoder.decode | public static String decode(String input)
{
try
{
return URLDecoder.decode(input, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
// This never happens.
return input;
}
} | java | public static String decode(String input)
{
try
{
return URLDecoder.decode(input, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
// This never happens.
return input;
}
} | [
"public",
"static",
"String",
"decode",
"(",
"String",
"input",
")",
"{",
"try",
"{",
"return",
"URLDecoder",
".",
"decode",
"(",
"input",
",",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"// This never happens.\r",... | URL-decode the input with UTF-8.
@param input
An encoded string.
@return
Decoded string. | [
"URL",
"-",
"decode",
"the",
"input",
"with",
"UTF",
"-",
"8",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/web/URLCoder.java#L65-L76 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiException.java | AuthleteApiException.setResponse | private void setResponse(int statusCode, String statusMessage, String responseBody, Map<String, List<String>> responseHeaders)
{
mStatusCode = statusCode;
mStatusMessage = statusMessage;
mResponseBody = responseBody;
mResponseHeaders = responseHeaders;
} | java | private void setResponse(int statusCode, String statusMessage, String responseBody, Map<String, List<String>> responseHeaders)
{
mStatusCode = statusCode;
mStatusMessage = statusMessage;
mResponseBody = responseBody;
mResponseHeaders = responseHeaders;
} | [
"private",
"void",
"setResponse",
"(",
"int",
"statusCode",
",",
"String",
"statusMessage",
",",
"String",
"responseBody",
",",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"responseHeaders",
")",
"{",
"mStatusCode",
"=",
"statusCode",
";",
"m... | Set the data fields related to HTTP response information.
@param statusCode
HTTP status code.
@param statusMessage
HTTP status message.
@param responseBody
HTTP response body. | [
"Set",
"the",
"data",
"fields",
"related",
"to",
"HTTP",
"response",
"information",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiException.java#L293-L299 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/dto/BackchannelAuthenticationCompleteRequest.java | BackchannelAuthenticationCompleteRequest.setClaims | public BackchannelAuthenticationCompleteRequest setClaims(Map<String, Object> claims)
{
if (claims == null || claims.size() == 0)
{
this.claims = null;
}
else
{
setClaims(Utils.toJson(claims));
}
return this;
} | java | public BackchannelAuthenticationCompleteRequest setClaims(Map<String, Object> claims)
{
if (claims == null || claims.size() == 0)
{
this.claims = null;
}
else
{
setClaims(Utils.toJson(claims));
}
return this;
} | [
"public",
"BackchannelAuthenticationCompleteRequest",
"setClaims",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"claims",
")",
"{",
"if",
"(",
"claims",
"==",
"null",
"||",
"claims",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"this",
".",
"claims",
"=... | Set additional claims which will be embedded in the ID token.
<p>
The argument is converted into a JSON string and passed to
{@link #setClaims(String)} method.
</p>
@param claims
Additional claims. Keys are claim names.
@return
{@code this} object. | [
"Set",
"additional",
"claims",
"which",
"will",
"be",
"embedded",
"in",
"the",
"ID",
"token",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/dto/BackchannelAuthenticationCompleteRequest.java#L573-L585 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiImpl.java | AuthleteApiImpl.callServiceOwnerGetApi | private <TResponse> TResponse callServiceOwnerGetApi(
String path, Map<String, String> queryParams,
Class<TResponse> responseClass) throws AuthleteApiException
{
return callGetApi(mServiceOwnerCredentials, path, queryParams, responseClass);
} | java | private <TResponse> TResponse callServiceOwnerGetApi(
String path, Map<String, String> queryParams,
Class<TResponse> responseClass) throws AuthleteApiException
{
return callGetApi(mServiceOwnerCredentials, path, queryParams, responseClass);
} | [
"private",
"<",
"TResponse",
">",
"TResponse",
"callServiceOwnerGetApi",
"(",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
",",
"Class",
"<",
"TResponse",
">",
"responseClass",
")",
"throws",
"AuthleteApiException",
"{",
"retur... | Call an API with HTTP GET method and Service Owner credentials. | [
"Call",
"an",
"API",
"with",
"HTTP",
"GET",
"method",
"and",
"Service",
"Owner",
"credentials",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L262-L267 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiImpl.java | AuthleteApiImpl.callServiceGetApi | private <TResponse> TResponse callServiceGetApi(
String path, Map<String, String> queryParams,
Class<TResponse> responseClass) throws AuthleteApiException
{
return callGetApi(mServiceCredentials, path, queryParams, responseClass);
} | java | private <TResponse> TResponse callServiceGetApi(
String path, Map<String, String> queryParams,
Class<TResponse> responseClass) throws AuthleteApiException
{
return callGetApi(mServiceCredentials, path, queryParams, responseClass);
} | [
"private",
"<",
"TResponse",
">",
"TResponse",
"callServiceGetApi",
"(",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
",",
"Class",
"<",
"TResponse",
">",
"responseClass",
")",
"throws",
"AuthleteApiException",
"{",
"return",
... | Call an API with HTTP GET method and Service credentials. | [
"Call",
"an",
"API",
"with",
"HTTP",
"GET",
"method",
"and",
"Service",
"credentials",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L283-L288 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiImpl.java | AuthleteApiImpl.callGetApi | private <TResponse> TResponse callGetApi(
BasicCredentials credentials, String path, Map<String, String> queryParams,
Class<TResponse> responseClass) throws AuthleteApiException
{
return callApi(HttpMethod.GET, credentials, path, queryParams, (Object)null, responseClass);
} | java | private <TResponse> TResponse callGetApi(
BasicCredentials credentials, String path, Map<String, String> queryParams,
Class<TResponse> responseClass) throws AuthleteApiException
{
return callApi(HttpMethod.GET, credentials, path, queryParams, (Object)null, responseClass);
} | [
"private",
"<",
"TResponse",
">",
"TResponse",
"callGetApi",
"(",
"BasicCredentials",
"credentials",
",",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
",",
"Class",
"<",
"TResponse",
">",
"responseClass",
")",
"throws",
"Auth... | Call an API with HTTP GET method. | [
"Call",
"an",
"API",
"with",
"HTTP",
"GET",
"method",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L294-L299 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiImpl.java | AuthleteApiImpl.callServiceOwnerPostApi | private <TResponse> TResponse callServiceOwnerPostApi(
String path, Map<String, String> queryParams,
Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
{
return callPostApi(mServiceOwnerCredentials, path, queryParams, requestBody, responseClass);
} | java | private <TResponse> TResponse callServiceOwnerPostApi(
String path, Map<String, String> queryParams,
Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
{
return callPostApi(mServiceOwnerCredentials, path, queryParams, requestBody, responseClass);
} | [
"private",
"<",
"TResponse",
">",
"TResponse",
"callServiceOwnerPostApi",
"(",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
",",
"Object",
"requestBody",
",",
"Class",
"<",
"TResponse",
">",
"responseClass",
")",
"throws",
"A... | Call an API with HTTP POST method and Service Owner credentials. | [
"Call",
"an",
"API",
"with",
"HTTP",
"POST",
"method",
"and",
"Service",
"Owner",
"credentials",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L315-L320 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiImpl.java | AuthleteApiImpl.callServicePostApi | private <TResponse> TResponse callServicePostApi(
String path, Map<String, String> queryParams,
Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
{
return callPostApi(mServiceCredentials, path, queryParams, requestBody, responseClass);
} | java | private <TResponse> TResponse callServicePostApi(
String path, Map<String, String> queryParams,
Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
{
return callPostApi(mServiceCredentials, path, queryParams, requestBody, responseClass);
} | [
"private",
"<",
"TResponse",
">",
"TResponse",
"callServicePostApi",
"(",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
",",
"Object",
"requestBody",
",",
"Class",
"<",
"TResponse",
">",
"responseClass",
")",
"throws",
"Authle... | Call an API with HTTP POST method and Service credentials. | [
"Call",
"an",
"API",
"with",
"HTTP",
"POST",
"method",
"and",
"Service",
"credentials",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L336-L341 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiImpl.java | AuthleteApiImpl.callPostApi | private <TResponse> TResponse callPostApi(
BasicCredentials credentials, String path, Map<String, String> queryParams,
Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
{
return callApi(HttpMethod.POST, credentials, path, queryParams, requestBody, responseClass);
} | java | private <TResponse> TResponse callPostApi(
BasicCredentials credentials, String path, Map<String, String> queryParams,
Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
{
return callApi(HttpMethod.POST, credentials, path, queryParams, requestBody, responseClass);
} | [
"private",
"<",
"TResponse",
">",
"TResponse",
"callPostApi",
"(",
"BasicCredentials",
"credentials",
",",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
",",
"Object",
"requestBody",
",",
"Class",
"<",
"TResponse",
">",
"respo... | Call an API with HTTP POST method. | [
"Call",
"an",
"API",
"with",
"HTTP",
"POST",
"method",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L347-L352 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiImpl.java | AuthleteApiImpl.callServiceOwnerDeleteApi | private <TResponse> void callServiceOwnerDeleteApi(
String path, Map<String, String> queryParams) throws AuthleteApiException
{
callDeleteApi(mServiceOwnerCredentials, path, queryParams);
} | java | private <TResponse> void callServiceOwnerDeleteApi(
String path, Map<String, String> queryParams) throws AuthleteApiException
{
callDeleteApi(mServiceOwnerCredentials, path, queryParams);
} | [
"private",
"<",
"TResponse",
">",
"void",
"callServiceOwnerDeleteApi",
"(",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
")",
"throws",
"AuthleteApiException",
"{",
"callDeleteApi",
"(",
"mServiceOwnerCredentials",
",",
"path",
"... | Call an API with HTTP DELETE method and Service Owner credentials. | [
"Call",
"an",
"API",
"with",
"HTTP",
"DELETE",
"method",
"and",
"Service",
"Owner",
"credentials",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L367-L371 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiImpl.java | AuthleteApiImpl.callServiceDeleteApi | private <TResponse> void callServiceDeleteApi(
String path, Map<String, String> queryParams) throws AuthleteApiException
{
callDeleteApi(mServiceCredentials, path, queryParams);
} | java | private <TResponse> void callServiceDeleteApi(
String path, Map<String, String> queryParams) throws AuthleteApiException
{
callDeleteApi(mServiceCredentials, path, queryParams);
} | [
"private",
"<",
"TResponse",
">",
"void",
"callServiceDeleteApi",
"(",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
")",
"throws",
"AuthleteApiException",
"{",
"callDeleteApi",
"(",
"mServiceCredentials",
",",
"path",
",",
"que... | Call an API with HTTP DELETE method and Service credentials. | [
"Call",
"an",
"API",
"with",
"HTTP",
"DELETE",
"method",
"and",
"Service",
"credentials",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L386-L390 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiImpl.java | AuthleteApiImpl.callDeleteApi | private <TResponse> void callDeleteApi(
BasicCredentials credentials, String path,
Map<String, String> queryParams) throws AuthleteApiException
{
callApi(HttpMethod.DELETE, credentials, path, queryParams, (Object)null, (Class<TResponse>)null);
} | java | private <TResponse> void callDeleteApi(
BasicCredentials credentials, String path,
Map<String, String> queryParams) throws AuthleteApiException
{
callApi(HttpMethod.DELETE, credentials, path, queryParams, (Object)null, (Class<TResponse>)null);
} | [
"private",
"<",
"TResponse",
">",
"void",
"callDeleteApi",
"(",
"BasicCredentials",
"credentials",
",",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
")",
"throws",
"AuthleteApiException",
"{",
"callApi",
"(",
"HttpMethod",
".",... | Call an API with HTTP DELETE method. | [
"Call",
"an",
"API",
"with",
"HTTP",
"DELETE",
"method",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L396-L401 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/api/AuthleteApiImpl.java | AuthleteApiImpl.callApi | private <TResponse> TResponse callApi(
HttpMethod method, BasicCredentials credentials,
String path, Map<String, String> queryParams,
Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
{
// Create a connection to the Authlete API.
HttpURLConnection con = createConnection(
method, credentials, mBaseUrl, path, queryParams, mSettings);
try
{
// Communicate with the API and get a response.
return communicate(con, requestBody, responseClass);
}
finally
{
// Disconnect the connection in any case.
con.disconnect();
}
} | java | private <TResponse> TResponse callApi(
HttpMethod method, BasicCredentials credentials,
String path, Map<String, String> queryParams,
Object requestBody, Class<TResponse> responseClass) throws AuthleteApiException
{
// Create a connection to the Authlete API.
HttpURLConnection con = createConnection(
method, credentials, mBaseUrl, path, queryParams, mSettings);
try
{
// Communicate with the API and get a response.
return communicate(con, requestBody, responseClass);
}
finally
{
// Disconnect the connection in any case.
con.disconnect();
}
} | [
"private",
"<",
"TResponse",
">",
"TResponse",
"callApi",
"(",
"HttpMethod",
"method",
",",
"BasicCredentials",
"credentials",
",",
"String",
"path",
",",
"Map",
"<",
"String",
",",
"String",
">",
"queryParams",
",",
"Object",
"requestBody",
",",
"Class",
"<",... | Call an API. | [
"Call",
"an",
"API",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/api/AuthleteApiImpl.java#L407-L426 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/util/Utils.java | Utils.join | public static String join(String[] strings, String delimiter)
{
if (strings == null)
{
return null;
}
if (strings.length == 0)
{
return "";
}
boolean useDelimiter = (delimiter != null && delimiter.length() != 0);
StringBuilder sb = new StringBuilder();
for (String string : strings)
{
sb.append(string);
if (useDelimiter);
{
sb.append(delimiter);
}
}
if (useDelimiter && sb.length() != 0)
{
// Remove the last delimiter.
sb.setLength(sb.length() - delimiter.length());
}
return sb.toString();
} | java | public static String join(String[] strings, String delimiter)
{
if (strings == null)
{
return null;
}
if (strings.length == 0)
{
return "";
}
boolean useDelimiter = (delimiter != null && delimiter.length() != 0);
StringBuilder sb = new StringBuilder();
for (String string : strings)
{
sb.append(string);
if (useDelimiter);
{
sb.append(delimiter);
}
}
if (useDelimiter && sb.length() != 0)
{
// Remove the last delimiter.
sb.setLength(sb.length() - delimiter.length());
}
return sb.toString();
} | [
"public",
"static",
"String",
"join",
"(",
"String",
"[",
"]",
"strings",
",",
"String",
"delimiter",
")",
"{",
"if",
"(",
"strings",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"strings",
".",
"length",
"==",
"0",
")",
"{",
"ret... | Concatenate string with the specified delimiter.
@param strings
Strings to be concatenated.
@param delimiter
A delimiter used between strings. If {@code null} or an empty
string is given, delimiters are not inserted between strings.
@return
A concatenated string. If {@code strings} is {@code null},
{@code null} is returned. If the size of {@code strings} is 0,
an empty string is returned. | [
"Concatenate",
"string",
"with",
"the",
"specified",
"delimiter",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/util/Utils.java#L53-L86 | train |
authlete/authlete-java-common | src/main/java/com/authlete/common/util/Utils.java | Utils.stringifyScopeNames | public static String stringifyScopeNames(Scope[] scopes)
{
if (scopes == null)
{
return null;
}
String[] array = new String[scopes.length];
for (int i = 0; i < scopes.length; ++i)
{
array[i] = (scopes[i] == null) ? null : scopes[i].getName();
}
return join(array, " ");
} | java | public static String stringifyScopeNames(Scope[] scopes)
{
if (scopes == null)
{
return null;
}
String[] array = new String[scopes.length];
for (int i = 0; i < scopes.length; ++i)
{
array[i] = (scopes[i] == null) ? null : scopes[i].getName();
}
return join(array, " ");
} | [
"public",
"static",
"String",
"stringifyScopeNames",
"(",
"Scope",
"[",
"]",
"scopes",
")",
"{",
"if",
"(",
"scopes",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"String",
"[",
"]",
"array",
"=",
"new",
"String",
"[",
"scopes",
".",
"length",
... | Generate a list of scope names.
@param scopes
An array of {@link Scope}. If {@code null} is given,
{@code null} is returned.
@return
A string containing scope names using white spaces as
the delimiter.
@since 2.5 | [
"Generate",
"a",
"list",
"of",
"scope",
"names",
"."
] | 49c94c483713cbf5a04d805ff7dbd83766c9c964 | https://github.com/authlete/authlete-java-common/blob/49c94c483713cbf5a04d805ff7dbd83766c9c964/src/main/java/com/authlete/common/util/Utils.java#L257-L272 | train |
EvidentSolutions/dalesbred | dalesbred/src/main/java/org/dalesbred/query/QueryBuilder.java | QueryBuilder.append | public @NotNull QueryBuilder append(@SuppressWarnings("ParameterHidesMemberVariable") @NotNull SqlQuery query) {
this.query.append(query.getSql());
arguments.addAll(query.getArguments());
return this;
} | java | public @NotNull QueryBuilder append(@SuppressWarnings("ParameterHidesMemberVariable") @NotNull SqlQuery query) {
this.query.append(query.getSql());
arguments.addAll(query.getArguments());
return this;
} | [
"public",
"@",
"NotNull",
"QueryBuilder",
"append",
"(",
"@",
"SuppressWarnings",
"(",
"\"ParameterHidesMemberVariable\"",
")",
"@",
"NotNull",
"SqlQuery",
"query",
")",
"{",
"this",
".",
"query",
".",
"append",
"(",
"query",
".",
"getSql",
"(",
")",
")",
";... | Appends given query and its arguments to this query. | [
"Appends",
"given",
"query",
"and",
"its",
"arguments",
"to",
"this",
"query",
"."
] | 713f5b6e152d97e1672ca68b9ff9c7c6c288ceb1 | https://github.com/EvidentSolutions/dalesbred/blob/713f5b6e152d97e1672ca68b9ff9c7c6c288ceb1/dalesbred/src/main/java/org/dalesbred/query/QueryBuilder.java#L99-L103 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/PasswordResetTokenService.java | PasswordResetTokenService.buildConcreteInstance | @SuppressWarnings("unchecked")
@Override
protected E buildConcreteInstance(User user, Integer expirationTimeInMinutes) {
if (expirationTimeInMinutes == null) {
return (E) new PasswordResetToken(user);
}
return (E) new PasswordResetToken(user, expirationTimeInMinutes);
} | java | @SuppressWarnings("unchecked")
@Override
protected E buildConcreteInstance(User user, Integer expirationTimeInMinutes) {
if (expirationTimeInMinutes == null) {
return (E) new PasswordResetToken(user);
}
return (E) new PasswordResetToken(user, expirationTimeInMinutes);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"@",
"Override",
"protected",
"E",
"buildConcreteInstance",
"(",
"User",
"user",
",",
"Integer",
"expirationTimeInMinutes",
")",
"{",
"if",
"(",
"expirationTimeInMinutes",
"==",
"null",
")",
"{",
"return",
"(",
... | Builds a concrete instance of this class. | [
"Builds",
"a",
"concrete",
"instance",
"of",
"this",
"class",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/PasswordResetTokenService.java#L102-L109 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/InitializationService.java | InitializationService.saveUser | public void saveUser(User user) {
LOG.trace("Trying to create a new user");
// encode the raw password using bcrypt
final String pwHash = passwordEncoder.encode(user.getPassword());
user.setPassword(pwHash);
dao.saveOrUpdate(user);
LOG.info("Created the user " + user.getAccountName());
} | java | public void saveUser(User user) {
LOG.trace("Trying to create a new user");
// encode the raw password using bcrypt
final String pwHash = passwordEncoder.encode(user.getPassword());
user.setPassword(pwHash);
dao.saveOrUpdate(user);
LOG.info("Created the user " + user.getAccountName());
} | [
"public",
"void",
"saveUser",
"(",
"User",
"user",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"Trying to create a new user\"",
")",
";",
"// encode the raw password using bcrypt",
"final",
"String",
"pwHash",
"=",
"passwordEncoder",
".",
"encode",
"(",
"user",
".",
"ge... | Used to create a user. Implements special logic by encoding the password.
@param user | [
"Used",
"to",
"create",
"a",
"user",
".",
"Implements",
"special",
"logic",
"by",
"encoding",
"the",
"password",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/InitializationService.java#L63-L70 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/web/MapController.java | MapController.setLayersForMap | @RequestMapping(value = "/setLayersForMap.action", method = RequestMethod.POST)
public @ResponseBody
java.util.Map<String, Object> setLayersForMap(
@RequestParam("mapModuleId") Integer mapModuleId,
@RequestParam("layerIds") List<Integer> layerIds) {
try {
if (mapModuleId == null || layerIds == null || layerIds.isEmpty()) {
throw new Exception();
}
List<Layer> layers = this.service.setLayersForMap(mapModuleId, layerIds);
return ResultSet.success(layers);
} catch (Exception e) {
return ResultSet.error(COULD_NOT_SET_ERROR_MSG);
}
} | java | @RequestMapping(value = "/setLayersForMap.action", method = RequestMethod.POST)
public @ResponseBody
java.util.Map<String, Object> setLayersForMap(
@RequestParam("mapModuleId") Integer mapModuleId,
@RequestParam("layerIds") List<Integer> layerIds) {
try {
if (mapModuleId == null || layerIds == null || layerIds.isEmpty()) {
throw new Exception();
}
List<Layer> layers = this.service.setLayersForMap(mapModuleId, layerIds);
return ResultSet.success(layers);
} catch (Exception e) {
return ResultSet.error(COULD_NOT_SET_ERROR_MSG);
}
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/setLayersForMap.action\"",
",",
"method",
"=",
"RequestMethod",
".",
"POST",
")",
"public",
"@",
"ResponseBody",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"Object",
">",
"setLayersForMap",
"(",
"@",
"R... | Set layers for map
@param mapModuleId The map module id
@param layerIds The list of layer ids
@return | [
"Set",
"layers",
"for",
"map"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/web/MapController.java#L64-L78 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/web/FileController.java | FileController.uploadFile | @RequestMapping(value = "/upload.action", method = RequestMethod.POST)
public ResponseEntity<?> uploadFile(
@RequestParam("file") MultipartFile uploadedFile) {
LOG.debug("Requested to upload a multipart-file");
// build response map
Map<String, Object> responseMap = new HashMap<String, Object>();
try {
E file = service.uploadFile(uploadedFile);
LOG.info("Successfully uploaded file " + file.getFileName());
responseMap = ResultSet.success(file);
} catch (Exception e) {
LOG.error("Could not upload the file: " + e.getMessage());
responseMap = ResultSet.error("Could not upload the file: " +
e.getMessage());
}
final HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
// rewrite the response-Map as String
return new ResponseEntity<>(responseMap, responseHeaders, HttpStatus.OK);
} | java | @RequestMapping(value = "/upload.action", method = RequestMethod.POST)
public ResponseEntity<?> uploadFile(
@RequestParam("file") MultipartFile uploadedFile) {
LOG.debug("Requested to upload a multipart-file");
// build response map
Map<String, Object> responseMap = new HashMap<String, Object>();
try {
E file = service.uploadFile(uploadedFile);
LOG.info("Successfully uploaded file " + file.getFileName());
responseMap = ResultSet.success(file);
} catch (Exception e) {
LOG.error("Could not upload the file: " + e.getMessage());
responseMap = ResultSet.error("Could not upload the file: " +
e.getMessage());
}
final HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
// rewrite the response-Map as String
return new ResponseEntity<>(responseMap, responseHeaders, HttpStatus.OK);
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/upload.action\"",
",",
"method",
"=",
"RequestMethod",
".",
"POST",
")",
"public",
"ResponseEntity",
"<",
"?",
">",
"uploadFile",
"(",
"@",
"RequestParam",
"(",
"\"file\"",
")",
"MultipartFile",
"uploadedFile",
")",
... | Persists a file as bytearray in the database
@param uploadedFile | [
"Persists",
"a",
"file",
"as",
"bytearray",
"in",
"the",
"database"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/web/FileController.java#L65-L88 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java | HttpUtil.get | public static Response get(String url, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpGet(url), credentials, requestHeaders);
} | java | public static Response get(String url, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpGet(url), credentials, requestHeaders);
} | [
"public",
"static",
"Response",
"get",
"(",
"String",
"url",
",",
"Credentials",
"credentials",
",",
"Header",
"[",
"]",
"requestHeaders",
")",
"throws",
"URISyntaxException",
",",
"HttpException",
"{",
"return",
"send",
"(",
"new",
"HttpGet",
"(",
"url",
")",... | Performs an HTTP GET on the given URL.
@param url The URL to connect to.
@param credentials instance implementing {@link Credentials} interface holding a set of credentials
@param requestHeaders Additional HTTP headers added to the request
@return The HTTP response as Response object.
@throws URISyntaxException
@throws HttpException | [
"Performs",
"an",
"HTTP",
"GET",
"on",
"the",
"given",
"URL",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java#L147-L150 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java | HttpUtil.get | public static Response get(URI uri) throws URISyntaxException, HttpException {
return send(new HttpGet(uri), null, null);
} | java | public static Response get(URI uri) throws URISyntaxException, HttpException {
return send(new HttpGet(uri), null, null);
} | [
"public",
"static",
"Response",
"get",
"(",
"URI",
"uri",
")",
"throws",
"URISyntaxException",
",",
"HttpException",
"{",
"return",
"send",
"(",
"new",
"HttpGet",
"(",
"uri",
")",
",",
"null",
",",
"null",
")",
";",
"}"
] | Performs an HTTP GET on the given URI.
No credentials needed.
@param uri The URI to connect to.
@return The HTTP response as Response object.
@throws URISyntaxException
@throws HttpException | [
"Performs",
"an",
"HTTP",
"GET",
"on",
"the",
"given",
"URI",
".",
"No",
"credentials",
"needed",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java#L189-L191 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java | HttpUtil.get | public static Response get(URI uri, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpGet(uri), credentials, requestHeaders);
} | java | public static Response get(URI uri, Credentials credentials, Header[] requestHeaders)
throws URISyntaxException, HttpException {
return send(new HttpGet(uri), credentials, requestHeaders);
} | [
"public",
"static",
"Response",
"get",
"(",
"URI",
"uri",
",",
"Credentials",
"credentials",
",",
"Header",
"[",
"]",
"requestHeaders",
")",
"throws",
"URISyntaxException",
",",
"HttpException",
"{",
"return",
"send",
"(",
"new",
"HttpGet",
"(",
"uri",
")",
... | Performs an HTTP GET on the given URI.
Basic auth is used if both username and pw are not null.
@param uri The URI to connect to.
@param credentials Instance implementing {@link Credentials} interface holding a set of credentials
@param requestHeaders Additional HTTP headers added to the request
@return The HTTP response as Response object.
@throws URISyntaxException
@throws HttpException | [
"Performs",
"an",
"HTTP",
"GET",
"on",
"the",
"given",
"URI",
".",
"Basic",
"auth",
"is",
"used",
"if",
"both",
"username",
"and",
"pw",
"are",
"not",
"null",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java#L266-L269 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java | HttpUtil.forwardGet | public static Response forwardGet(URI uri, HttpServletRequest request, boolean forwardHeaders)
throws URISyntaxException, HttpException {
Header[] headersToForward = null;
if (request != null && forwardHeaders) {
headersToForward = HttpUtil.getHeadersFromRequest(request);
}
return send(new HttpGet(uri), null, headersToForward);
} | java | public static Response forwardGet(URI uri, HttpServletRequest request, boolean forwardHeaders)
throws URISyntaxException, HttpException {
Header[] headersToForward = null;
if (request != null && forwardHeaders) {
headersToForward = HttpUtil.getHeadersFromRequest(request);
}
return send(new HttpGet(uri), null, headersToForward);
} | [
"public",
"static",
"Response",
"forwardGet",
"(",
"URI",
"uri",
",",
"HttpServletRequest",
"request",
",",
"boolean",
"forwardHeaders",
")",
"throws",
"URISyntaxException",
",",
"HttpException",
"{",
"Header",
"[",
"]",
"headersToForward",
"=",
"null",
";",
"if",... | Forward GET request to uri based on given request
@param uri uri The URI to forward to.
@param request The original {@link HttpServletRequest}
@param forwardHeaders Should headers of request should be forwarded
@return The HTTP response as Response object.
@throws URISyntaxException
@throws HttpException | [
"Forward",
"GET",
"request",
"to",
"uri",
"based",
"on",
"given",
"request"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java#L281-L291 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java | HttpUtil.post | public static Response post(String url, String password, String username)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), new ArrayList<NameValuePair>(), new UsernamePasswordCredentials(username, password), null);
} | java | public static Response post(String url, String password, String username)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(url), new ArrayList<NameValuePair>(), new UsernamePasswordCredentials(username, password), null);
} | [
"public",
"static",
"Response",
"post",
"(",
"String",
"url",
",",
"String",
"password",
",",
"String",
"username",
")",
"throws",
"URISyntaxException",
",",
"UnsupportedEncodingException",
",",
"HttpException",
"{",
"return",
"postParams",
"(",
"new",
"HttpPost",
... | Performs an HTTP POST on the given URL.
Basic auth is used if both and password are not null.
@param url The URI to connect to as String.
@param username Credentials - username
@param password Credentials - password
@return The HTTP response as Response object.
@throws URISyntaxException
@throws UnsupportedEncodingException
@throws HttpException | [
"Performs",
"an",
"HTTP",
"POST",
"on",
"the",
"given",
"URL",
".",
"Basic",
"auth",
"is",
"used",
"if",
"both",
"and",
"password",
"are",
"not",
"null",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java#L334-L337 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java | HttpUtil.post | public static Response post(URI uri)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), new ArrayList<NameValuePair>(), null, null);
} | java | public static Response post(URI uri)
throws URISyntaxException, UnsupportedEncodingException, HttpException {
return postParams(new HttpPost(uri), new ArrayList<NameValuePair>(), null, null);
} | [
"public",
"static",
"Response",
"post",
"(",
"URI",
"uri",
")",
"throws",
"URISyntaxException",
",",
"UnsupportedEncodingException",
",",
"HttpException",
"{",
"return",
"postParams",
"(",
"new",
"HttpPost",
"(",
"uri",
")",
",",
"new",
"ArrayList",
"<",
"NameVa... | Performs an HTTP POST on the given URI.
@param uri The URI to connect to.
@return The HTTP response as Response object.
@throws URISyntaxException
@throws UnsupportedEncodingException
@throws HttpException | [
"Performs",
"an",
"HTTP",
"POST",
"on",
"the",
"given",
"URI",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java#L399-L402 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java | HttpUtil.forwardPost | public static Response forwardPost(URI uri, HttpServletRequest request, boolean forwardHeaders) throws URISyntaxException, HttpException {
Header[] headersToForward = null;
if (request != null && forwardHeaders) {
headersToForward = HttpUtil.getHeadersFromRequest(request);
}
String ctString = request.getContentType();
ContentType ct = ContentType.parse(ctString);
String body = getRequestBody(request);
return HttpUtil.postBody(new HttpPost(uri), body, ct, null, headersToForward);
} | java | public static Response forwardPost(URI uri, HttpServletRequest request, boolean forwardHeaders) throws URISyntaxException, HttpException {
Header[] headersToForward = null;
if (request != null && forwardHeaders) {
headersToForward = HttpUtil.getHeadersFromRequest(request);
}
String ctString = request.getContentType();
ContentType ct = ContentType.parse(ctString);
String body = getRequestBody(request);
return HttpUtil.postBody(new HttpPost(uri), body, ct, null, headersToForward);
} | [
"public",
"static",
"Response",
"forwardPost",
"(",
"URI",
"uri",
",",
"HttpServletRequest",
"request",
",",
"boolean",
"forwardHeaders",
")",
"throws",
"URISyntaxException",
",",
"HttpException",
"{",
"Header",
"[",
"]",
"headersToForward",
"=",
"null",
";",
"if"... | Forward POST to uri based on given request
@param uri uri The URI to forward to.
@param request The original {@link HttpServletRequest}
@param forwardHeaders Should headers of request should be forwarded
@return
@throws URISyntaxException
@throws HttpException | [
"Forward",
"POST",
"to",
"uri",
"based",
"on",
"given",
"request"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java#L1214-L1225 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java | HttpUtil.put | public static Response put(URI uri, String body, ContentType contentType, String username, String password) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uri), body, contentType, new UsernamePasswordCredentials(username, password), null);
} | java | public static Response put(URI uri, String body, ContentType contentType, String username, String password) throws URISyntaxException, HttpException {
return putBody(new HttpPut(uri), body, contentType, new UsernamePasswordCredentials(username, password), null);
} | [
"public",
"static",
"Response",
"put",
"(",
"URI",
"uri",
",",
"String",
"body",
",",
"ContentType",
"contentType",
",",
"String",
"username",
",",
"String",
"password",
")",
"throws",
"URISyntaxException",
",",
"HttpException",
"{",
"return",
"putBody",
"(",
... | Performs an HTTP PUT on the given URL.
@param uri
@param body
@param contentType
@param username
@param password
@return
@throws URISyntaxException
@throws HttpException | [
"Performs",
"an",
"HTTP",
"PUT",
"on",
"the",
"given",
"URL",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java#L1530-L1532 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java | HttpUtil.isSaneRequest | public static boolean isSaneRequest(HttpServletRequest request) {
if (request != null && request.getMethod() != null) {
return true;
}
return false;
} | java | public static boolean isSaneRequest(HttpServletRequest request) {
if (request != null && request.getMethod() != null) {
return true;
}
return false;
} | [
"public",
"static",
"boolean",
"isSaneRequest",
"(",
"HttpServletRequest",
"request",
")",
"{",
"if",
"(",
"request",
"!=",
"null",
"&&",
"request",
".",
"getMethod",
"(",
")",
"!=",
"null",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"... | Checks if request and request method are not null
@param request {@link HttpServletRequest} to check
@return true if sane, false otherwise | [
"Checks",
"if",
"request",
"and",
"request",
"method",
"are",
"not",
"null"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java#L1941-L1946 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java | HttpUtil.removeHeaders | private static Header[] removeHeaders(Header[] headersToClean, String[] headersToRemove) {
ArrayList<Header> headers = new ArrayList<>();
if (headersToClean == null) {
return null;
}
for (Header header : headersToClean) {
if (!StringUtils.equalsAnyIgnoreCase(header.getName(), headersToRemove)) {
headers.add(header);
}
}
LOG.debug("Removed the content-length and content-type headers as the HTTP Client lib will care "
+ "about them as soon as the entity is set on the POST object.");
Header[] headersArray = new Header[headers.size()];
headersArray = headers.toArray(headersArray);
return headersArray;
} | java | private static Header[] removeHeaders(Header[] headersToClean, String[] headersToRemove) {
ArrayList<Header> headers = new ArrayList<>();
if (headersToClean == null) {
return null;
}
for (Header header : headersToClean) {
if (!StringUtils.equalsAnyIgnoreCase(header.getName(), headersToRemove)) {
headers.add(header);
}
}
LOG.debug("Removed the content-length and content-type headers as the HTTP Client lib will care "
+ "about them as soon as the entity is set on the POST object.");
Header[] headersArray = new Header[headers.size()];
headersArray = headers.toArray(headersArray);
return headersArray;
} | [
"private",
"static",
"Header",
"[",
"]",
"removeHeaders",
"(",
"Header",
"[",
"]",
"headersToClean",
",",
"String",
"[",
"]",
"headersToRemove",
")",
"{",
"ArrayList",
"<",
"Header",
">",
"headers",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"("... | Remove headers form header array that match Strings in headersToRemove
@param headersToClean Array of {@link Header}: Headers to clean up
@param headersToRemove Header names to remove | [
"Remove",
"headers",
"form",
"header",
"array",
"that",
"match",
"Strings",
"in",
"headersToRemove"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/http/HttpUtil.java#L2045-L2060 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.createImportJob | public RESTImport createImportJob(String workSpaceName, String dataStoreName)
throws Exception {
if (StringUtils.isEmpty(workSpaceName)) {
throw new GeoServerRESTImporterException("No workspace given. Please provide a "
+ "workspace to import the data in.");
}
RESTImport importJob = new RESTImport();
LOG.debug("Creating a new import job to import into workspace " + workSpaceName);
RESTTargetWorkspace targetWorkspace = new RESTTargetWorkspace(workSpaceName);
importJob.setTargetWorkspace(targetWorkspace);
if (!StringUtils.isEmpty(dataStoreName)) {
LOG.debug("The data will be imported into datastore " + dataStoreName);
RESTTargetDataStore targetDataStore = new RESTTargetDataStore(dataStoreName, null);
importJob.setTargetStore(targetDataStore);
} else {
LOG.debug("No datastore given. A new datastore will be created in relation to the"
+ "input data.");
}
Response httpResponse = HttpUtil.post(
this.addEndPoint(""),
this.asJSON(importJob),
ContentType.APPLICATION_JSON,
this.username,
this.password
);
HttpStatus responseStatus = httpResponse.getStatusCode();
if (responseStatus == null || !responseStatus.is2xxSuccessful()) {
throw new GeoServerRESTImporterException("Import job cannot be "
+ "created. Is the GeoServer Importer extension installed?");
}
RESTImport restImport = (RESTImport) this.asEntity(httpResponse.getBody(), RESTImport.class);
LOG.debug("Successfully created the import job with ID " + restImport.getId());
return restImport;
} | java | public RESTImport createImportJob(String workSpaceName, String dataStoreName)
throws Exception {
if (StringUtils.isEmpty(workSpaceName)) {
throw new GeoServerRESTImporterException("No workspace given. Please provide a "
+ "workspace to import the data in.");
}
RESTImport importJob = new RESTImport();
LOG.debug("Creating a new import job to import into workspace " + workSpaceName);
RESTTargetWorkspace targetWorkspace = new RESTTargetWorkspace(workSpaceName);
importJob.setTargetWorkspace(targetWorkspace);
if (!StringUtils.isEmpty(dataStoreName)) {
LOG.debug("The data will be imported into datastore " + dataStoreName);
RESTTargetDataStore targetDataStore = new RESTTargetDataStore(dataStoreName, null);
importJob.setTargetStore(targetDataStore);
} else {
LOG.debug("No datastore given. A new datastore will be created in relation to the"
+ "input data.");
}
Response httpResponse = HttpUtil.post(
this.addEndPoint(""),
this.asJSON(importJob),
ContentType.APPLICATION_JSON,
this.username,
this.password
);
HttpStatus responseStatus = httpResponse.getStatusCode();
if (responseStatus == null || !responseStatus.is2xxSuccessful()) {
throw new GeoServerRESTImporterException("Import job cannot be "
+ "created. Is the GeoServer Importer extension installed?");
}
RESTImport restImport = (RESTImport) this.asEntity(httpResponse.getBody(), RESTImport.class);
LOG.debug("Successfully created the import job with ID " + restImport.getId());
return restImport;
} | [
"public",
"RESTImport",
"createImportJob",
"(",
"String",
"workSpaceName",
",",
"String",
"dataStoreName",
")",
"throws",
"Exception",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"workSpaceName",
")",
")",
"{",
"throw",
"new",
"GeoServerRESTImporterException... | Create a new import job. | [
"Create",
"a",
"new",
"import",
"job",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L106-L149 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.createReprojectTransformTask | public boolean createReprojectTransformTask(Integer importJobId, Integer taskId,
String sourceSrs, String targetSrs) throws URISyntaxException, HttpException {
RESTReprojectTransform transformTask = new RESTReprojectTransform();
if (StringUtils.isNotEmpty(sourceSrs)) {
transformTask.setSource(sourceSrs);
}
transformTask.setTarget(targetSrs);
return createTransformTask(importJobId, taskId, transformTask);
} | java | public boolean createReprojectTransformTask(Integer importJobId, Integer taskId,
String sourceSrs, String targetSrs) throws URISyntaxException, HttpException {
RESTReprojectTransform transformTask = new RESTReprojectTransform();
if (StringUtils.isNotEmpty(sourceSrs)) {
transformTask.setSource(sourceSrs);
}
transformTask.setTarget(targetSrs);
return createTransformTask(importJobId, taskId, transformTask);
} | [
"public",
"boolean",
"createReprojectTransformTask",
"(",
"Integer",
"importJobId",
",",
"Integer",
"taskId",
",",
"String",
"sourceSrs",
",",
"String",
"targetSrs",
")",
"throws",
"URISyntaxException",
",",
"HttpException",
"{",
"RESTReprojectTransform",
"transformTask",... | Create a reprojection task. | [
"Create",
"a",
"reprojection",
"task",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L155-L164 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.uploadFile | public RESTImportTaskList uploadFile(Integer importJobId, File file, String sourceSrs) throws Exception {
LOG.debug("Uploading file " + file.getName() + " to import job " + importJobId);
Response httpResponse = HttpUtil.post(
this.addEndPoint(importJobId + "/tasks"),
file,
this.username,
this.password
);
HttpStatus responseStatus = httpResponse.getStatusCode();
if (responseStatus == null || !responseStatus.is2xxSuccessful()) {
throw new GeoServerRESTImporterException("Error while uploading the file.");
}
LOG.debug("Successfully uploaded the file to import job " + importJobId);
RESTImportTaskList importTaskList = null;
// check, if it is a list of import tasks (for multiple layers)
try {
importTaskList = mapper.readValue(httpResponse.getBody(), RESTImportTaskList.class);
LOG.debug("Imported file " + file.getName() + " contains data for multiple layers.");
return importTaskList;
} catch (Exception e) {
LOG.debug("Imported file " + file.getName() + " likely contains data for single " +
"layer. Will check this now.");
try {
RESTImportTask importTask = mapper.readValue(httpResponse.getBody(), RESTImportTask.class);
if (importTask != null) {
importTaskList = new RESTImportTaskList();
importTaskList.add(importTask);
LOG.debug("Imported file " + file.getName() + " contains data for a single layer.");
}
return importTaskList;
} catch (Exception ex) {
LOG.info("It seems that the SRS definition source file can not be interpreted by " +
"GeoServer / GeoTools. Try to set SRS definition to " + sourceSrs + ".");
File updatedGeoTiff = null;
try {
if (!StringUtils.isEmpty(sourceSrs)) {
// "First" recursion: try to add prj file to ZIP.
updatedGeoTiff = addPrjFileToArchive(file, sourceSrs);
} else {
// At least second recursion: throw exception since SRS definition
// could not be set.
throw new GeoServerRESTImporterException("Could not set SRS definition "
+ "of GeoTIFF.");
}
} catch (ZipException ze) {
throw new GeoServerRESTImporterException("No valid ZIP file given containing "
+ "GeoTiff datasets.");
}
if (updatedGeoTiff != null) {
importTaskList = uploadFile(importJobId, updatedGeoTiff, null);
return importTaskList;
}
}
}
return null;
} | java | public RESTImportTaskList uploadFile(Integer importJobId, File file, String sourceSrs) throws Exception {
LOG.debug("Uploading file " + file.getName() + " to import job " + importJobId);
Response httpResponse = HttpUtil.post(
this.addEndPoint(importJobId + "/tasks"),
file,
this.username,
this.password
);
HttpStatus responseStatus = httpResponse.getStatusCode();
if (responseStatus == null || !responseStatus.is2xxSuccessful()) {
throw new GeoServerRESTImporterException("Error while uploading the file.");
}
LOG.debug("Successfully uploaded the file to import job " + importJobId);
RESTImportTaskList importTaskList = null;
// check, if it is a list of import tasks (for multiple layers)
try {
importTaskList = mapper.readValue(httpResponse.getBody(), RESTImportTaskList.class);
LOG.debug("Imported file " + file.getName() + " contains data for multiple layers.");
return importTaskList;
} catch (Exception e) {
LOG.debug("Imported file " + file.getName() + " likely contains data for single " +
"layer. Will check this now.");
try {
RESTImportTask importTask = mapper.readValue(httpResponse.getBody(), RESTImportTask.class);
if (importTask != null) {
importTaskList = new RESTImportTaskList();
importTaskList.add(importTask);
LOG.debug("Imported file " + file.getName() + " contains data for a single layer.");
}
return importTaskList;
} catch (Exception ex) {
LOG.info("It seems that the SRS definition source file can not be interpreted by " +
"GeoServer / GeoTools. Try to set SRS definition to " + sourceSrs + ".");
File updatedGeoTiff = null;
try {
if (!StringUtils.isEmpty(sourceSrs)) {
// "First" recursion: try to add prj file to ZIP.
updatedGeoTiff = addPrjFileToArchive(file, sourceSrs);
} else {
// At least second recursion: throw exception since SRS definition
// could not be set.
throw new GeoServerRESTImporterException("Could not set SRS definition "
+ "of GeoTIFF.");
}
} catch (ZipException ze) {
throw new GeoServerRESTImporterException("No valid ZIP file given containing "
+ "GeoTiff datasets.");
}
if (updatedGeoTiff != null) {
importTaskList = uploadFile(importJobId, updatedGeoTiff, null);
return importTaskList;
}
}
}
return null;
} | [
"public",
"RESTImportTaskList",
"uploadFile",
"(",
"Integer",
"importJobId",
",",
"File",
"file",
",",
"String",
"sourceSrs",
")",
"throws",
"Exception",
"{",
"LOG",
".",
"debug",
"(",
"\"Uploading file \"",
"+",
"file",
".",
"getName",
"(",
")",
"+",
"\" to i... | Upload an import file. | [
"Upload",
"an",
"import",
"file",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L208-L271 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.updateImportTask | public boolean updateImportTask(int importJobId, int importTaskId,
AbstractRESTEntity updateTaskEntity) throws Exception {
LOG.debug("Updating the import task " + importTaskId + " in job " + importJobId +
" with " + updateTaskEntity);
Response httpResponse = HttpUtil.put(
this.addEndPoint(importJobId + "/tasks/" + importTaskId),
this.asJSON(updateTaskEntity),
ContentType.APPLICATION_JSON,
this.username,
this.password
);
boolean success = httpResponse.getStatusCode().equals(HttpStatus.NO_CONTENT);
if (success) {
LOG.debug("Successfully updated the task " + importTaskId);
} else {
LOG.error("Unknown error occured while updating the task " + importTaskId);
}
return success;
} | java | public boolean updateImportTask(int importJobId, int importTaskId,
AbstractRESTEntity updateTaskEntity) throws Exception {
LOG.debug("Updating the import task " + importTaskId + " in job " + importJobId +
" with " + updateTaskEntity);
Response httpResponse = HttpUtil.put(
this.addEndPoint(importJobId + "/tasks/" + importTaskId),
this.asJSON(updateTaskEntity),
ContentType.APPLICATION_JSON,
this.username,
this.password
);
boolean success = httpResponse.getStatusCode().equals(HttpStatus.NO_CONTENT);
if (success) {
LOG.debug("Successfully updated the task " + importTaskId);
} else {
LOG.error("Unknown error occured while updating the task " + importTaskId);
}
return success;
} | [
"public",
"boolean",
"updateImportTask",
"(",
"int",
"importJobId",
",",
"int",
"importTaskId",
",",
"AbstractRESTEntity",
"updateTaskEntity",
")",
"throws",
"Exception",
"{",
"LOG",
".",
"debug",
"(",
"\"Updating the import task \"",
"+",
"importTaskId",
"+",
"\" in ... | Updates the given import task. | [
"Updates",
"the",
"given",
"import",
"task",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L276-L299 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.deleteImportJob | public boolean deleteImportJob(Integer importJobId) throws URISyntaxException, HttpException {
LOG.debug("Deleting the import job " + importJobId);
Response httpResponse = HttpUtil.delete(
this.addEndPoint(importJobId.toString()),
this.username,
this.password);
boolean success = httpResponse.getStatusCode().equals(HttpStatus.NO_CONTENT);
if (success) {
LOG.debug("Successfully deleted the import job " + importJobId);
} else {
LOG.error("Unknown error occured while deleting the import job " + importJobId);
}
return success;
} | java | public boolean deleteImportJob(Integer importJobId) throws URISyntaxException, HttpException {
LOG.debug("Deleting the import job " + importJobId);
Response httpResponse = HttpUtil.delete(
this.addEndPoint(importJobId.toString()),
this.username,
this.password);
boolean success = httpResponse.getStatusCode().equals(HttpStatus.NO_CONTENT);
if (success) {
LOG.debug("Successfully deleted the import job " + importJobId);
} else {
LOG.error("Unknown error occured while deleting the import job " + importJobId);
}
return success;
} | [
"public",
"boolean",
"deleteImportJob",
"(",
"Integer",
"importJobId",
")",
"throws",
"URISyntaxException",
",",
"HttpException",
"{",
"LOG",
".",
"debug",
"(",
"\"Deleting the import job \"",
"+",
"importJobId",
")",
";",
"Response",
"httpResponse",
"=",
"HttpUtil",
... | Deletes an importJob. | [
"Deletes",
"an",
"importJob",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L304-L322 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.runImportJob | public boolean runImportJob(Integer importJobId) throws
UnsupportedEncodingException, URISyntaxException, HttpException {
LOG.debug("Starting the import for job " + importJobId);
Response httpResponse = HttpUtil.post(
this.addEndPoint(Integer.toString(importJobId)),
this.username,
this.password
);
boolean success = httpResponse.getStatusCode().equals(HttpStatus.NO_CONTENT);
if (success) {
LOG.debug("Successfully started the import job " + importJobId);
} else {
LOG.error("Unknown error occured while running the import job " + importJobId);
}
return success;
} | java | public boolean runImportJob(Integer importJobId) throws
UnsupportedEncodingException, URISyntaxException, HttpException {
LOG.debug("Starting the import for job " + importJobId);
Response httpResponse = HttpUtil.post(
this.addEndPoint(Integer.toString(importJobId)),
this.username,
this.password
);
boolean success = httpResponse.getStatusCode().equals(HttpStatus.NO_CONTENT);
if (success) {
LOG.debug("Successfully started the import job " + importJobId);
} else {
LOG.error("Unknown error occured while running the import job " + importJobId);
}
return success;
} | [
"public",
"boolean",
"runImportJob",
"(",
"Integer",
"importJobId",
")",
"throws",
"UnsupportedEncodingException",
",",
"URISyntaxException",
",",
"HttpException",
"{",
"LOG",
".",
"debug",
"(",
"\"Starting the import for job \"",
"+",
"importJobId",
")",
";",
"Response... | Run a previously configured import job. | [
"Run",
"a",
"previously",
"configured",
"import",
"job",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L327-L347 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.getLayer | public RESTLayer getLayer(Integer importJobId, Integer taskId) throws Exception {
Response httpResponse = HttpUtil.get(
this.addEndPoint(importJobId + "/tasks/" + taskId + "/layer"),
this.username,
this.password
);
return (RESTLayer) this.asEntity(httpResponse.getBody(), RESTLayer.class);
} | java | public RESTLayer getLayer(Integer importJobId, Integer taskId) throws Exception {
Response httpResponse = HttpUtil.get(
this.addEndPoint(importJobId + "/tasks/" + taskId + "/layer"),
this.username,
this.password
);
return (RESTLayer) this.asEntity(httpResponse.getBody(), RESTLayer.class);
} | [
"public",
"RESTLayer",
"getLayer",
"(",
"Integer",
"importJobId",
",",
"Integer",
"taskId",
")",
"throws",
"Exception",
"{",
"Response",
"httpResponse",
"=",
"HttpUtil",
".",
"get",
"(",
"this",
".",
"addEndPoint",
"(",
"importJobId",
"+",
"\"/tasks/\"",
"+",
... | Get a layer. | [
"Get",
"a",
"layer",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L352-L360 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.getAllImportedLayers | public List<RESTLayer> getAllImportedLayers(Integer importJobId, List<RESTImportTask> tasks) throws Exception {
ArrayList<RESTLayer> layers = new ArrayList<RESTLayer>();
for (RESTImportTask task : tasks) {
RESTImportTask refreshedTask = this.getRESTImportTask(importJobId, task.getId());
if (refreshedTask.getState().equalsIgnoreCase("COMPLETE")) {
Response httpResponse = HttpUtil.get(
this.addEndPoint(importJobId + "/tasks/" + task.getId() + "/layer"),
this.username,
this.password
);
RESTLayer layer = (RESTLayer) this.asEntity(httpResponse.getBody(), RESTLayer.class);
if (layer != null) {
layers.add(layer);
}
} else if ((tasks.size() == 1) && refreshedTask.getState().equalsIgnoreCase("ERROR")) {
throw new GeoServerRESTImporterException(refreshedTask.getErrorMessage());
}
}
return layers;
} | java | public List<RESTLayer> getAllImportedLayers(Integer importJobId, List<RESTImportTask> tasks) throws Exception {
ArrayList<RESTLayer> layers = new ArrayList<RESTLayer>();
for (RESTImportTask task : tasks) {
RESTImportTask refreshedTask = this.getRESTImportTask(importJobId, task.getId());
if (refreshedTask.getState().equalsIgnoreCase("COMPLETE")) {
Response httpResponse = HttpUtil.get(
this.addEndPoint(importJobId + "/tasks/" + task.getId() + "/layer"),
this.username,
this.password
);
RESTLayer layer = (RESTLayer) this.asEntity(httpResponse.getBody(), RESTLayer.class);
if (layer != null) {
layers.add(layer);
}
} else if ((tasks.size() == 1) && refreshedTask.getState().equalsIgnoreCase("ERROR")) {
throw new GeoServerRESTImporterException(refreshedTask.getErrorMessage());
}
}
return layers;
} | [
"public",
"List",
"<",
"RESTLayer",
">",
"getAllImportedLayers",
"(",
"Integer",
"importJobId",
",",
"List",
"<",
"RESTImportTask",
">",
"tasks",
")",
"throws",
"Exception",
"{",
"ArrayList",
"<",
"RESTLayer",
">",
"layers",
"=",
"new",
"ArrayList",
"<",
"REST... | fetch all created Layers of import job | [
"fetch",
"all",
"created",
"Layers",
"of",
"import",
"job"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L365-L386 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.getDataOfImportTask | public RESTData getDataOfImportTask(Integer importJobId, Integer taskId)
throws Exception {
final DeserializationFeature unwrapRootValueFeature = DeserializationFeature.UNWRAP_ROOT_VALUE;
boolean unwrapRootValueFeatureIsEnabled = mapper.isEnabled(unwrapRootValueFeature);
Response httpResponse = HttpUtil.get(
this.addEndPoint(importJobId + "/tasks/" + taskId + "/data"),
this.username,
this.password
);
// we have to disable the feature. otherwise deserialize would not work here
mapper.disable(unwrapRootValueFeature);
final RESTData resultEntity = (RESTData) this.asEntity(httpResponse.getBody(), RESTData.class);
if (unwrapRootValueFeatureIsEnabled) {
mapper.enable(unwrapRootValueFeature);
}
return resultEntity;
} | java | public RESTData getDataOfImportTask(Integer importJobId, Integer taskId)
throws Exception {
final DeserializationFeature unwrapRootValueFeature = DeserializationFeature.UNWRAP_ROOT_VALUE;
boolean unwrapRootValueFeatureIsEnabled = mapper.isEnabled(unwrapRootValueFeature);
Response httpResponse = HttpUtil.get(
this.addEndPoint(importJobId + "/tasks/" + taskId + "/data"),
this.username,
this.password
);
// we have to disable the feature. otherwise deserialize would not work here
mapper.disable(unwrapRootValueFeature);
final RESTData resultEntity = (RESTData) this.asEntity(httpResponse.getBody(), RESTData.class);
if (unwrapRootValueFeatureIsEnabled) {
mapper.enable(unwrapRootValueFeature);
}
return resultEntity;
} | [
"public",
"RESTData",
"getDataOfImportTask",
"(",
"Integer",
"importJobId",
",",
"Integer",
"taskId",
")",
"throws",
"Exception",
"{",
"final",
"DeserializationFeature",
"unwrapRootValueFeature",
"=",
"DeserializationFeature",
".",
"UNWRAP_ROOT_VALUE",
";",
"boolean",
"un... | Get the data of an import task. | [
"Get",
"the",
"data",
"of",
"an",
"import",
"task",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L391-L412 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.getRESTImportTask | public RESTImportTask getRESTImportTask(Integer importJobId, Integer taskId) throws
Exception {
Response httpResponse = HttpUtil.get(
this.addEndPoint(importJobId + "/tasks/" + taskId),
this.username,
this.password
);
return (RESTImportTask) this.asEntity(httpResponse.getBody(), RESTImportTask.class);
} | java | public RESTImportTask getRESTImportTask(Integer importJobId, Integer taskId) throws
Exception {
Response httpResponse = HttpUtil.get(
this.addEndPoint(importJobId + "/tasks/" + taskId),
this.username,
this.password
);
return (RESTImportTask) this.asEntity(httpResponse.getBody(), RESTImportTask.class);
} | [
"public",
"RESTImportTask",
"getRESTImportTask",
"(",
"Integer",
"importJobId",
",",
"Integer",
"taskId",
")",
"throws",
"Exception",
"{",
"Response",
"httpResponse",
"=",
"HttpUtil",
".",
"get",
"(",
"this",
".",
"addEndPoint",
"(",
"importJobId",
"+",
"\"/tasks/... | Get an import task. | [
"Get",
"an",
"import",
"task",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L417-L426 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.createTransformTask | private boolean createTransformTask(Integer importJobId, Integer taskId, RESTTransform transformTask)
throws URISyntaxException, HttpException {
LOG.debug("Creating a new transform task for import job" + importJobId + " and task " + taskId);
mapper.disable(SerializationFeature.WRAP_ROOT_VALUE);
Response httpResponse = HttpUtil.post(
this.addEndPoint(importJobId + "/tasks/" + taskId + "/transforms"),
this.asJSON(transformTask),
ContentType.APPLICATION_JSON,
this.username,
this.password
);
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
if (httpResponse.getStatusCode().equals(HttpStatus.CREATED)) {
LOG.debug("Successfully created the transform task");
return true;
} else {
LOG.error("Error while creating the transform task");
return false;
}
} | java | private boolean createTransformTask(Integer importJobId, Integer taskId, RESTTransform transformTask)
throws URISyntaxException, HttpException {
LOG.debug("Creating a new transform task for import job" + importJobId + " and task " + taskId);
mapper.disable(SerializationFeature.WRAP_ROOT_VALUE);
Response httpResponse = HttpUtil.post(
this.addEndPoint(importJobId + "/tasks/" + taskId + "/transforms"),
this.asJSON(transformTask),
ContentType.APPLICATION_JSON,
this.username,
this.password
);
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
if (httpResponse.getStatusCode().equals(HttpStatus.CREATED)) {
LOG.debug("Successfully created the transform task");
return true;
} else {
LOG.error("Error while creating the transform task");
return false;
}
} | [
"private",
"boolean",
"createTransformTask",
"(",
"Integer",
"importJobId",
",",
"Integer",
"taskId",
",",
"RESTTransform",
"transformTask",
")",
"throws",
"URISyntaxException",
",",
"HttpException",
"{",
"LOG",
".",
"debug",
"(",
"\"Creating a new transform task for impo... | Helper method to create an importer transformTask | [
"Helper",
"method",
"to",
"create",
"an",
"importer",
"transformTask"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L444-L468 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.addPrjFileToArchive | public static File addPrjFileToArchive(File file, String targetCrs)
throws ZipException, IOException, NoSuchAuthorityCodeException, FactoryException {
ZipFile zipFile = new ZipFile(file);
CoordinateReferenceSystem decodedTargetCrs = CRS.decode(targetCrs);
String targetCrsWkt = toSingleLineWKT(decodedTargetCrs);
ArrayList<String> zipFileNames = new ArrayList<String>();
List<FileHeader> zipFileHeaders = zipFile.getFileHeaders();
for (FileHeader zipFileHeader : zipFileHeaders) {
if (FilenameUtils.getExtension(zipFileHeader.getFileName()).equalsIgnoreCase("prj")) {
continue;
}
zipFileNames.add(FilenameUtils.getBaseName(zipFileHeader.getFileName()));
}
LOG.debug("Following files will be created and added to ZIP file: " + zipFileNames);
for (String prefix : zipFileNames) {
File targetPrj = null;
try {
targetPrj = File.createTempFile("TMP_" + prefix, ".prj");
FileUtils.write(targetPrj, targetCrsWkt, "UTF-8");
ZipParameters params = new ZipParameters();
params.setSourceExternalStream(true);
params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
params.setFileNameInZip(prefix + ".prj");
zipFile.addFile(targetPrj, params);
} finally {
if (targetPrj != null) {
targetPrj.delete();
}
}
}
return zipFile.getFile();
} | java | public static File addPrjFileToArchive(File file, String targetCrs)
throws ZipException, IOException, NoSuchAuthorityCodeException, FactoryException {
ZipFile zipFile = new ZipFile(file);
CoordinateReferenceSystem decodedTargetCrs = CRS.decode(targetCrs);
String targetCrsWkt = toSingleLineWKT(decodedTargetCrs);
ArrayList<String> zipFileNames = new ArrayList<String>();
List<FileHeader> zipFileHeaders = zipFile.getFileHeaders();
for (FileHeader zipFileHeader : zipFileHeaders) {
if (FilenameUtils.getExtension(zipFileHeader.getFileName()).equalsIgnoreCase("prj")) {
continue;
}
zipFileNames.add(FilenameUtils.getBaseName(zipFileHeader.getFileName()));
}
LOG.debug("Following files will be created and added to ZIP file: " + zipFileNames);
for (String prefix : zipFileNames) {
File targetPrj = null;
try {
targetPrj = File.createTempFile("TMP_" + prefix, ".prj");
FileUtils.write(targetPrj, targetCrsWkt, "UTF-8");
ZipParameters params = new ZipParameters();
params.setSourceExternalStream(true);
params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
params.setFileNameInZip(prefix + ".prj");
zipFile.addFile(targetPrj, params);
} finally {
if (targetPrj != null) {
targetPrj.delete();
}
}
}
return zipFile.getFile();
} | [
"public",
"static",
"File",
"addPrjFileToArchive",
"(",
"File",
"file",
",",
"String",
"targetCrs",
")",
"throws",
"ZipException",
",",
"IOException",
",",
"NoSuchAuthorityCodeException",
",",
"FactoryException",
"{",
"ZipFile",
"zipFile",
"=",
"new",
"ZipFile",
"("... | Add a projection file to a shapefile zip archive. | [
"Add",
"a",
"projection",
"file",
"to",
"a",
"shapefile",
"zip",
"archive",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L473-L511 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.toSingleLineWKT | public static String toSingleLineWKT(CoordinateReferenceSystem crs) {
String wkt = null;
try {
// this is a lenient transformation, works with polar stereographics too
Formattable formattable = (Formattable) crs;
wkt = formattable.toWKT(0, false);
} catch (ClassCastException e) {
wkt = crs.toWKT();
}
wkt = wkt.replaceAll("\n", "").replaceAll(" ", "");
return wkt;
} | java | public static String toSingleLineWKT(CoordinateReferenceSystem crs) {
String wkt = null;
try {
// this is a lenient transformation, works with polar stereographics too
Formattable formattable = (Formattable) crs;
wkt = formattable.toWKT(0, false);
} catch (ClassCastException e) {
wkt = crs.toWKT();
}
wkt = wkt.replaceAll("\n", "").replaceAll(" ", "");
return wkt;
} | [
"public",
"static",
"String",
"toSingleLineWKT",
"(",
"CoordinateReferenceSystem",
"crs",
")",
"{",
"String",
"wkt",
"=",
"null",
";",
"try",
"{",
"// this is a lenient transformation, works with polar stereographics too",
"Formattable",
"formattable",
"=",
"(",
"Formattabl... | Turns the CRS into a single line WKT
@param crs CoordinateReferenceSystem which should be formatted
@return Single line String which can be written to PRJ file | [
"Turns",
"the",
"CRS",
"into",
"a",
"single",
"line",
"WKT"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L519-L531 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.asEntity | private AbstractRESTEntity asEntity(byte[] responseBody, Class<?> clazz)
throws Exception {
AbstractRESTEntity entity = null;
entity = (AbstractRESTEntity) mapper.readValue(responseBody, clazz);
return entity;
} | java | private AbstractRESTEntity asEntity(byte[] responseBody, Class<?> clazz)
throws Exception {
AbstractRESTEntity entity = null;
entity = (AbstractRESTEntity) mapper.readValue(responseBody, clazz);
return entity;
} | [
"private",
"AbstractRESTEntity",
"asEntity",
"(",
"byte",
"[",
"]",
"responseBody",
",",
"Class",
"<",
"?",
">",
"clazz",
")",
"throws",
"Exception",
"{",
"AbstractRESTEntity",
"entity",
"=",
"null",
";",
"entity",
"=",
"(",
"AbstractRESTEntity",
")",
"mapper"... | Convert a byte array to an importer REST entity. | [
"Convert",
"a",
"byte",
"array",
"to",
"an",
"importer",
"REST",
"entity",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L536-L544 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.asJSON | private String asJSON(Object entity) {
String entityJson = null;
try {
entityJson = this.mapper.writeValueAsString(entity);
} catch (Exception e) {
LOG.error("Could not parse as JSON: " + e.getMessage());
}
return entityJson;
} | java | private String asJSON(Object entity) {
String entityJson = null;
try {
entityJson = this.mapper.writeValueAsString(entity);
} catch (Exception e) {
LOG.error("Could not parse as JSON: " + e.getMessage());
}
return entityJson;
} | [
"private",
"String",
"asJSON",
"(",
"Object",
"entity",
")",
"{",
"String",
"entityJson",
"=",
"null",
";",
"try",
"{",
"entityJson",
"=",
"this",
".",
"mapper",
".",
"writeValueAsString",
"(",
"entity",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")"... | Convert an object to json. | [
"Convert",
"an",
"object",
"to",
"json",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L549-L560 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java | GeoServerRESTImporter.addEndPoint | private URI addEndPoint(String endPoint) throws URISyntaxException {
if (StringUtils.isEmpty(endPoint) || endPoint.equals("/")) {
return this.baseUri;
}
if (this.baseUri.getPath().endsWith("/") || endPoint.startsWith("/")) {
endPoint = this.baseUri.getPath() + endPoint;
} else {
endPoint = this.baseUri.getPath() + "/" + endPoint;
}
URI uri = null;
URIBuilder builder = new URIBuilder();
builder.setScheme(this.baseUri.getScheme());
builder.setHost(this.baseUri.getHost());
builder.setPort(this.baseUri.getPort());
builder.setPath(endPoint);
uri = builder.build();
return uri;
} | java | private URI addEndPoint(String endPoint) throws URISyntaxException {
if (StringUtils.isEmpty(endPoint) || endPoint.equals("/")) {
return this.baseUri;
}
if (this.baseUri.getPath().endsWith("/") || endPoint.startsWith("/")) {
endPoint = this.baseUri.getPath() + endPoint;
} else {
endPoint = this.baseUri.getPath() + "/" + endPoint;
}
URI uri = null;
URIBuilder builder = new URIBuilder();
builder.setScheme(this.baseUri.getScheme());
builder.setHost(this.baseUri.getHost());
builder.setPort(this.baseUri.getPort());
builder.setPath(endPoint);
uri = builder.build();
return uri;
} | [
"private",
"URI",
"addEndPoint",
"(",
"String",
"endPoint",
")",
"throws",
"URISyntaxException",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"endPoint",
")",
"||",
"endPoint",
".",
"equals",
"(",
"\"/\"",
")",
")",
"{",
"return",
"this",
".",
"base... | Add an endpoint. | [
"Add",
"an",
"endpoint",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/importer/GeoServerRESTImporter.java#L565-L588 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/data/ResultSet.java | ResultSet.error | public static final Map<String, Object> error(String errorMsg, Map additionalReturnValuesMap) {
Map<String, Object> returnMap = new HashMap<String, Object>(3);
returnMap.put("message", errorMsg);
returnMap.put("additionalInfo", additionalReturnValuesMap);
returnMap.put("success", false);
return returnMap;
} | java | public static final Map<String, Object> error(String errorMsg, Map additionalReturnValuesMap) {
Map<String, Object> returnMap = new HashMap<String, Object>(3);
returnMap.put("message", errorMsg);
returnMap.put("additionalInfo", additionalReturnValuesMap);
returnMap.put("success", false);
return returnMap;
} | [
"public",
"static",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"error",
"(",
"String",
"errorMsg",
",",
"Map",
"additionalReturnValuesMap",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"returnMap",
"=",
"new",
"HashMap",
"<",
"String",
",",
... | Method returning error message and additional return values
@param errorMsg The error message
@param additionalReturnValuesMap {@link Map} containing additional information
@return Map to use e.g. as {@link org.springframework.http.ResponseEntity} | [
"Method",
"returning",
"error",
"message",
"and",
"additional",
"return",
"values"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/data/ResultSet.java#L60-L68 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/Csv2ExtJsLocaleService.java | Csv2ExtJsLocaleService.detectColumnIndexOfLocale | private int detectColumnIndexOfLocale(String locale, CSVReader csvReader) throws Exception {
int indexOfLocale = -1;
List<String> headerLine = Arrays.asList(ArrayUtils.nullToEmpty(csvReader.readNext()));
if (headerLine == null || headerLine.isEmpty()) {
throw new Exception("CSV locale file seems to be empty.");
}
if (headerLine.size() < 3) {
// we expect at least three columns: component;field;locale1
throw new Exception("CSV locale file is invalid: Not enough columns.");
}
// start with the third column as the first two columns must not be a
// locale column
for (int i = 2; i < headerLine.size(); i++) {
String columnName = headerLine.get(i);
if (locale.equalsIgnoreCase(columnName)) {
indexOfLocale = headerLine.indexOf(columnName);
break;
}
}
if (indexOfLocale < 0) {
throw new Exception("Could not find locale " + locale + " in CSV file");
}
return indexOfLocale;
} | java | private int detectColumnIndexOfLocale(String locale, CSVReader csvReader) throws Exception {
int indexOfLocale = -1;
List<String> headerLine = Arrays.asList(ArrayUtils.nullToEmpty(csvReader.readNext()));
if (headerLine == null || headerLine.isEmpty()) {
throw new Exception("CSV locale file seems to be empty.");
}
if (headerLine.size() < 3) {
// we expect at least three columns: component;field;locale1
throw new Exception("CSV locale file is invalid: Not enough columns.");
}
// start with the third column as the first two columns must not be a
// locale column
for (int i = 2; i < headerLine.size(); i++) {
String columnName = headerLine.get(i);
if (locale.equalsIgnoreCase(columnName)) {
indexOfLocale = headerLine.indexOf(columnName);
break;
}
}
if (indexOfLocale < 0) {
throw new Exception("Could not find locale " + locale + " in CSV file");
}
return indexOfLocale;
} | [
"private",
"int",
"detectColumnIndexOfLocale",
"(",
"String",
"locale",
",",
"CSVReader",
"csvReader",
")",
"throws",
"Exception",
"{",
"int",
"indexOfLocale",
"=",
"-",
"1",
";",
"List",
"<",
"String",
">",
"headerLine",
"=",
"Arrays",
".",
"asList",
"(",
"... | Extracts the column index of the given locale in the CSV file.
@param locale
@param csvReader
@return
@throws IOException
@throws Exception | [
"Extracts",
"the",
"column",
"index",
"of",
"the",
"given",
"locale",
"in",
"the",
"CSV",
"file",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/Csv2ExtJsLocaleService.java#L140-L166 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/HttpProxyService.java | HttpProxyService.isInWhiteList | private boolean isInWhiteList(URL url) {
final String host = url.getHost();
final int port = url.getPort();
final String protocol = url.getProtocol();
final int portToTest = (port != -1) ? port : (StringUtils.equalsIgnoreCase(protocol, "https") ? 443 : 80);
List<String> matchingWhiteListEntries = proxyWhiteList.stream().filter((String whitelistEntry) -> {
String whitelistHost;
int whitelistPort;
if (StringUtils.contains(whitelistEntry, ":")) {
whitelistHost = whitelistEntry.split(":")[0];
whitelistPort = Integer.parseInt(whitelistEntry.split(":")[1]);
} else {
whitelistHost = whitelistEntry;
whitelistPort = -1;
}
final int portToTestAgainst = (whitelistPort != -1) ? whitelistPort : (StringUtils.equalsIgnoreCase(protocol, "https") ? 443 : 80);
final boolean portIsMatching = portToTestAgainst == portToTest;
final boolean domainIsMatching = StringUtils.equalsIgnoreCase(host, whitelistHost) || StringUtils.endsWith(host, whitelistHost);
return (portIsMatching && domainIsMatching);
}).collect(Collectors.toList());
boolean isAllowed = !matchingWhiteListEntries.isEmpty();
return isAllowed;
} | java | private boolean isInWhiteList(URL url) {
final String host = url.getHost();
final int port = url.getPort();
final String protocol = url.getProtocol();
final int portToTest = (port != -1) ? port : (StringUtils.equalsIgnoreCase(protocol, "https") ? 443 : 80);
List<String> matchingWhiteListEntries = proxyWhiteList.stream().filter((String whitelistEntry) -> {
String whitelistHost;
int whitelistPort;
if (StringUtils.contains(whitelistEntry, ":")) {
whitelistHost = whitelistEntry.split(":")[0];
whitelistPort = Integer.parseInt(whitelistEntry.split(":")[1]);
} else {
whitelistHost = whitelistEntry;
whitelistPort = -1;
}
final int portToTestAgainst = (whitelistPort != -1) ? whitelistPort : (StringUtils.equalsIgnoreCase(protocol, "https") ? 443 : 80);
final boolean portIsMatching = portToTestAgainst == portToTest;
final boolean domainIsMatching = StringUtils.equalsIgnoreCase(host, whitelistHost) || StringUtils.endsWith(host, whitelistHost);
return (portIsMatching && domainIsMatching);
}).collect(Collectors.toList());
boolean isAllowed = !matchingWhiteListEntries.isEmpty();
return isAllowed;
} | [
"private",
"boolean",
"isInWhiteList",
"(",
"URL",
"url",
")",
"{",
"final",
"String",
"host",
"=",
"url",
".",
"getHost",
"(",
")",
";",
"final",
"int",
"port",
"=",
"url",
".",
"getPort",
"(",
")",
";",
"final",
"String",
"protocol",
"=",
"url",
".... | Helper method to check whether the URI is contained in the host whitelist provided in list of whitelisted hosts
@param url {@link URI} to check
@return true if contained, false otherwise | [
"Helper",
"method",
"to",
"check",
"whether",
"the",
"URI",
"is",
"contained",
"in",
"the",
"host",
"whitelist",
"provided",
"in",
"list",
"of",
"whitelisted",
"hosts"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/HttpProxyService.java#L317-L342 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/web/EndpointDocController.java | EndpointDocController.getEndpoints | @RequestMapping(value = "/endpointdoc", method = RequestMethod.GET)
public @ResponseBody
Set<RequestMappingInfo> getEndpoints() {
return this.service.getEndpoints(requestMappingHandlerMapping);
} | java | @RequestMapping(value = "/endpointdoc", method = RequestMethod.GET)
public @ResponseBody
Set<RequestMappingInfo> getEndpoints() {
return this.service.getEndpoints(requestMappingHandlerMapping);
} | [
"@",
"RequestMapping",
"(",
"value",
"=",
"\"/endpointdoc\"",
",",
"method",
"=",
"RequestMethod",
".",
"GET",
")",
"public",
"@",
"ResponseBody",
"Set",
"<",
"RequestMappingInfo",
">",
"getEndpoints",
"(",
")",
"{",
"return",
"this",
".",
"service",
".",
"g... | Provides an overview of all mapped endpoints. | [
"Provides",
"an",
"overview",
"of",
"all",
"mapped",
"endpoints",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/web/EndpointDocController.java#L42-L47 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java | GenericHibernateDao.findById | public E findById(ID id) {
LOG.trace("Finding " + entityClass.getSimpleName() + " with ID " + id);
return (E) getSession().get(entityClass, id);
} | java | public E findById(ID id) {
LOG.trace("Finding " + entityClass.getSimpleName() + " with ID " + id);
return (E) getSession().get(entityClass, id);
} | [
"public",
"E",
"findById",
"(",
"ID",
"id",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"Finding \"",
"+",
"entityClass",
".",
"getSimpleName",
"(",
")",
"+",
"\" with ID \"",
"+",
"id",
")",
";",
"return",
"(",
"E",
")",
"getSession",
"(",
")",
".",
"get"... | Return the real object from the database. Returns null if the object does
not exist.
@param id
@return The object from the database or null if it does not exist
@see http://www.mkyong.com/hibernate/different-between-session-get-and-session-load/ | [
"Return",
"the",
"real",
"object",
"from",
"the",
"database",
".",
"Returns",
"null",
"if",
"the",
"object",
"does",
"not",
"exist",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java#L89-L92 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java | GenericHibernateDao.saveOrUpdate | public void saveOrUpdate(E e) {
final Integer id = e.getId();
final boolean hasId = id != null;
String createOrUpdatePrefix = hasId ? "Updating" : "Creating a new";
String idSuffix = hasId ? " with ID " + id : "";
LOG.trace(createOrUpdatePrefix + " instance of " + entityClass.getSimpleName()
+ idSuffix);
e.setModified(DateTime.now());
getSession().saveOrUpdate(e);
} | java | public void saveOrUpdate(E e) {
final Integer id = e.getId();
final boolean hasId = id != null;
String createOrUpdatePrefix = hasId ? "Updating" : "Creating a new";
String idSuffix = hasId ? " with ID " + id : "";
LOG.trace(createOrUpdatePrefix + " instance of " + entityClass.getSimpleName()
+ idSuffix);
e.setModified(DateTime.now());
getSession().saveOrUpdate(e);
} | [
"public",
"void",
"saveOrUpdate",
"(",
"E",
"e",
")",
"{",
"final",
"Integer",
"id",
"=",
"e",
".",
"getId",
"(",
")",
";",
"final",
"boolean",
"hasId",
"=",
"id",
"!=",
"null",
";",
"String",
"createOrUpdatePrefix",
"=",
"hasId",
"?",
"\"Updating\"",
... | Saves or updates the passed entity.
@param e The entity to save or update in the database. | [
"Saves",
"or",
"updates",
"the",
"passed",
"entity",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java#L203-L214 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java | GenericHibernateDao.delete | public void delete(E e) {
LOG.trace("Deleting " + entityClass.getSimpleName() + " with ID " + e.getId());
getSession().delete(e);
} | java | public void delete(E e) {
LOG.trace("Deleting " + entityClass.getSimpleName() + " with ID " + e.getId());
getSession().delete(e);
} | [
"public",
"void",
"delete",
"(",
"E",
"e",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"Deleting \"",
"+",
"entityClass",
".",
"getSimpleName",
"(",
")",
"+",
"\" with ID \"",
"+",
"e",
".",
"getId",
"(",
")",
")",
";",
"getSession",
"(",
")",
".",
"delete... | Deletes the passed entity.
@param e The entity to remove from the database. | [
"Deletes",
"the",
"passed",
"entity",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java#L221-L224 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java | GenericHibernateDao.findByCriteria | @SuppressWarnings("unchecked")
public List<E> findByCriteria(Criterion... criterion) throws HibernateException {
LOG.trace("Finding instances of " + entityClass.getSimpleName()
+ " based on " + criterion.length + " criteria");
Criteria criteria = createDistinctRootEntityCriteria(criterion);
return criteria.list();
} | java | @SuppressWarnings("unchecked")
public List<E> findByCriteria(Criterion... criterion) throws HibernateException {
LOG.trace("Finding instances of " + entityClass.getSimpleName()
+ " based on " + criterion.length + " criteria");
Criteria criteria = createDistinctRootEntityCriteria(criterion);
return criteria.list();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"List",
"<",
"E",
">",
"findByCriteria",
"(",
"Criterion",
"...",
"criterion",
")",
"throws",
"HibernateException",
"{",
"LOG",
".",
"trace",
"(",
"\"Finding instances of \"",
"+",
"entityClass",
".",
... | Gets the results, that match a variable number of passed criterions. Call
this method without arguments to find all entities.
@param criterion A variable number of hibernate criterions
@return Entities matching the passed hibernate criterions | [
"Gets",
"the",
"results",
"that",
"match",
"a",
"variable",
"number",
"of",
"passed",
"criterions",
".",
"Call",
"this",
"method",
"without",
"arguments",
"to",
"find",
"all",
"entities",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java#L261-L268 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java | GenericHibernateDao.findByUniqueCriteria | @SuppressWarnings("unchecked")
public E findByUniqueCriteria(Criterion... criterion) throws HibernateException {
LOG.trace("Finding one unique " + entityClass.getSimpleName()
+ " based on " + criterion.length + " criteria");
Criteria criteria = createDistinctRootEntityCriteria(criterion);
return (E) criteria.uniqueResult();
} | java | @SuppressWarnings("unchecked")
public E findByUniqueCriteria(Criterion... criterion) throws HibernateException {
LOG.trace("Finding one unique " + entityClass.getSimpleName()
+ " based on " + criterion.length + " criteria");
Criteria criteria = createDistinctRootEntityCriteria(criterion);
return (E) criteria.uniqueResult();
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"E",
"findByUniqueCriteria",
"(",
"Criterion",
"...",
"criterion",
")",
"throws",
"HibernateException",
"{",
"LOG",
".",
"trace",
"(",
"\"Finding one unique \"",
"+",
"entityClass",
".",
"getSimpleName",
... | Gets the unique result, that matches a variable number of passed
criterions.
@param criterion A variable number of hibernate criterions
@return Entity matching the passed hibernate criterions
@throws HibernateException if there is more than one matching result | [
"Gets",
"the",
"unique",
"result",
"that",
"matches",
"a",
"variable",
"number",
"of",
"passed",
"criterions",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java#L319-L326 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java | GenericHibernateDao.findByCriteriaWithSortingAndPaging | @SuppressWarnings("unchecked")
public PagingResult<E> findByCriteriaWithSortingAndPaging(Integer firstResult,
Integer maxResults, List<Order> sorters, Criterion... criterion) throws HibernateException {
int nrOfSorters = sorters == null ? 0 : sorters.size();
LOG.trace("Finding instances of " + entityClass.getSimpleName()
+ " based on " + criterion.length + " criteria"
+ " with " + nrOfSorters + " sorters");
Criteria criteria = createDistinctRootEntityCriteria(criterion);
// add paging info
if (maxResults != null) {
LOG.trace("Limiting result set size to " + maxResults);
criteria.setMaxResults(maxResults);
}
if (firstResult != null) {
LOG.trace("Setting the first result to be retrieved to "
+ firstResult);
criteria.setFirstResult(firstResult);
}
// add sort info
if (sorters != null) {
for (Order sortInfo : sorters) {
criteria.addOrder(sortInfo);
}
}
return new PagingResult<E>(criteria.list(), getTotalCount(criterion));
} | java | @SuppressWarnings("unchecked")
public PagingResult<E> findByCriteriaWithSortingAndPaging(Integer firstResult,
Integer maxResults, List<Order> sorters, Criterion... criterion) throws HibernateException {
int nrOfSorters = sorters == null ? 0 : sorters.size();
LOG.trace("Finding instances of " + entityClass.getSimpleName()
+ " based on " + criterion.length + " criteria"
+ " with " + nrOfSorters + " sorters");
Criteria criteria = createDistinctRootEntityCriteria(criterion);
// add paging info
if (maxResults != null) {
LOG.trace("Limiting result set size to " + maxResults);
criteria.setMaxResults(maxResults);
}
if (firstResult != null) {
LOG.trace("Setting the first result to be retrieved to "
+ firstResult);
criteria.setFirstResult(firstResult);
}
// add sort info
if (sorters != null) {
for (Order sortInfo : sorters) {
criteria.addOrder(sortInfo);
}
}
return new PagingResult<E>(criteria.list(), getTotalCount(criterion));
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"PagingResult",
"<",
"E",
">",
"findByCriteriaWithSortingAndPaging",
"(",
"Integer",
"firstResult",
",",
"Integer",
"maxResults",
",",
"List",
"<",
"Order",
">",
"sorters",
",",
"Criterion",
"...",
"cri... | Gets the results, that match a variable number of passed criterions,
considering the paging- and sort-info at the same time.
@param firstResult Starting index for the paging request.
@param maxResults Max number of result size.
@param criterion A variable number of hibernate criterions
@return | [
"Gets",
"the",
"results",
"that",
"match",
"a",
"variable",
"number",
"of",
"passed",
"criterions",
"considering",
"the",
"paging",
"-",
"and",
"sort",
"-",
"info",
"at",
"the",
"same",
"time",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java#L337-L368 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java | GenericHibernateDao.getTotalCount | public Number getTotalCount(Criterion... criterion) throws HibernateException {
Criteria criteria = getSession().createCriteria(entityClass);
addCriterionsToCriteria(criteria, criterion);
criteria.setProjection(Projections.rowCount());
return (Long) criteria.uniqueResult();
} | java | public Number getTotalCount(Criterion... criterion) throws HibernateException {
Criteria criteria = getSession().createCriteria(entityClass);
addCriterionsToCriteria(criteria, criterion);
criteria.setProjection(Projections.rowCount());
return (Long) criteria.uniqueResult();
} | [
"public",
"Number",
"getTotalCount",
"(",
"Criterion",
"...",
"criterion",
")",
"throws",
"HibernateException",
"{",
"Criteria",
"criteria",
"=",
"getSession",
"(",
")",
".",
"createCriteria",
"(",
"entityClass",
")",
";",
"addCriterionsToCriteria",
"(",
"criteria",... | Returns the total count of db entries for the current type.
@param criterion
@return | [
"Returns",
"the",
"total",
"count",
"of",
"db",
"entries",
"for",
"the",
"current",
"type",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/dao/GenericHibernateDao.java#L476-L481 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/LdapService.java | LdapService.authenticate | public void authenticate(String username, String password) {
ldapTemplate.authenticate(query().where("objectClass").is("simpleSecurityObject").and("cn").is(username), password);
LOGGER.info("Successfully authenticated " + username);
} | java | public void authenticate(String username, String password) {
ldapTemplate.authenticate(query().where("objectClass").is("simpleSecurityObject").and("cn").is(username), password);
LOGGER.info("Successfully authenticated " + username);
} | [
"public",
"void",
"authenticate",
"(",
"String",
"username",
",",
"String",
"password",
")",
"{",
"ldapTemplate",
".",
"authenticate",
"(",
"query",
"(",
")",
".",
"where",
"(",
"\"objectClass\"",
")",
".",
"is",
"(",
"\"simpleSecurityObject\"",
")",
".",
"a... | Authenticate against ldap.
@param username the username
@param password the password | [
"Authenticate",
"against",
"ldap",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/LdapService.java#L44-L47 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/LdapService.java | LdapService.getGroups | public List<String> getGroups(String username, String property) {
final List<String> result = new ArrayList<>();
ldapTemplate.search(query().where("cn").is(username), new AttributesMapper<String>() {
public String mapFromAttributes(Attributes attrs) throws NamingException {
NamingEnumeration<?> ous = attrs.get(property).getAll();
// since we can generate multiple values here but may only return a single string, we ignore
// the ldapTemplate#search result and just put the values in our own list, returning an empty string
// which is effectively ignored
while (ous.hasMore()) {
result.add((String) ous.next());
}
return "";
}
});
return result;
} | java | public List<String> getGroups(String username, String property) {
final List<String> result = new ArrayList<>();
ldapTemplate.search(query().where("cn").is(username), new AttributesMapper<String>() {
public String mapFromAttributes(Attributes attrs) throws NamingException {
NamingEnumeration<?> ous = attrs.get(property).getAll();
// since we can generate multiple values here but may only return a single string, we ignore
// the ldapTemplate#search result and just put the values in our own list, returning an empty string
// which is effectively ignored
while (ous.hasMore()) {
result.add((String) ous.next());
}
return "";
}
});
return result;
} | [
"public",
"List",
"<",
"String",
">",
"getGroups",
"(",
"String",
"username",
",",
"String",
"property",
")",
"{",
"final",
"List",
"<",
"String",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"ldapTemplate",
".",
"search",
"(",
"query",
... | Extract groups from ldap.
@param username username to search for
@param property the property to extract the groups from
@return a list of group names from ldap | [
"Extract",
"groups",
"from",
"ldap",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/LdapService.java#L56-L71 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/mail/MailPublisher.java | MailPublisher.sendMail | public void sendMail(String from, String replyTo, String[] to, String[] cc,
String[] bcc, String subject, String msg) throws Exception {
SimpleMailMessage simpleMailMassage = new SimpleMailMessage();
// fallback to default mail sender
if (from == null || from.isEmpty()) {
from = defaultMailSender;
}
simpleMailMassage.setFrom(from);
simpleMailMassage.setReplyTo(replyTo);
simpleMailMassage.setTo(to);
simpleMailMassage.setBcc(bcc);
simpleMailMassage.setCc(cc);
simpleMailMassage.setSubject(subject);
simpleMailMassage.setText(msg);
sendMail(simpleMailMassage);
} | java | public void sendMail(String from, String replyTo, String[] to, String[] cc,
String[] bcc, String subject, String msg) throws Exception {
SimpleMailMessage simpleMailMassage = new SimpleMailMessage();
// fallback to default mail sender
if (from == null || from.isEmpty()) {
from = defaultMailSender;
}
simpleMailMassage.setFrom(from);
simpleMailMassage.setReplyTo(replyTo);
simpleMailMassage.setTo(to);
simpleMailMassage.setBcc(bcc);
simpleMailMassage.setCc(cc);
simpleMailMassage.setSubject(subject);
simpleMailMassage.setText(msg);
sendMail(simpleMailMassage);
} | [
"public",
"void",
"sendMail",
"(",
"String",
"from",
",",
"String",
"replyTo",
",",
"String",
"[",
"]",
"to",
",",
"String",
"[",
"]",
"cc",
",",
"String",
"[",
"]",
"bcc",
",",
"String",
"subject",
",",
"String",
"msg",
")",
"throws",
"Exception",
"... | Sends a SimpleMailMessage.
@param from The mail sender address.
@param replyTo The reply to address.
@param to A list of mail recipient addresses.
@param cc A list of carbon copy mail recipient addresses.
@param bcc A list of blind carbon copy mail recipient addresses.
@param subject The mail subject.
@param msg The mail message text.
@throws Exception | [
"Sends",
"a",
"SimpleMailMessage",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/mail/MailPublisher.java#L56-L75 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/mail/MailPublisher.java | MailPublisher.sendMimeMail | public void sendMimeMail(String from, String replyTo, String[] to, String[] cc,
String[] bcc, String subject, String msg, Boolean html,
String attachmentFilename, File attachmentFile)
throws MessagingException, MailException {
Boolean multipart = false;
// if a attachment file is required, we have to use a multipart massage
if (attachmentFilename != null && attachmentFile != null) {
multipart = true;
}
MimeMessage mimeMailMessage = mailSender.createMimeMessage();
MimeMessageHelper mimeHelper = new MimeMessageHelper(mimeMailMessage,
multipart);
// fallback to default mail sender
if (from == null || from.isEmpty()) {
from = defaultMailSender;
}
// set minimal configuration
mimeHelper.setFrom(from);
mimeHelper.setTo(to);
mimeHelper.setSubject(subject);
mimeHelper.setText(msg, html);
// add replyTo address if set
if (replyTo != null && !replyTo.isEmpty()) {
mimeHelper.setReplyTo(replyTo);
}
// add bcc address(es) if set
if (bcc != null && bcc.length > 0) {
mimeHelper.setBcc(bcc);
}
// add cc address(es) if set
if (cc != null && cc.length > 0) {
mimeHelper.setCc(cc);
}
// add attachment file if set
if (attachmentFilename != null && attachmentFile != null) {
mimeHelper.addAttachment(attachmentFilename, attachmentFile);
}
sendMail(mimeMailMessage);
} | java | public void sendMimeMail(String from, String replyTo, String[] to, String[] cc,
String[] bcc, String subject, String msg, Boolean html,
String attachmentFilename, File attachmentFile)
throws MessagingException, MailException {
Boolean multipart = false;
// if a attachment file is required, we have to use a multipart massage
if (attachmentFilename != null && attachmentFile != null) {
multipart = true;
}
MimeMessage mimeMailMessage = mailSender.createMimeMessage();
MimeMessageHelper mimeHelper = new MimeMessageHelper(mimeMailMessage,
multipart);
// fallback to default mail sender
if (from == null || from.isEmpty()) {
from = defaultMailSender;
}
// set minimal configuration
mimeHelper.setFrom(from);
mimeHelper.setTo(to);
mimeHelper.setSubject(subject);
mimeHelper.setText(msg, html);
// add replyTo address if set
if (replyTo != null && !replyTo.isEmpty()) {
mimeHelper.setReplyTo(replyTo);
}
// add bcc address(es) if set
if (bcc != null && bcc.length > 0) {
mimeHelper.setBcc(bcc);
}
// add cc address(es) if set
if (cc != null && cc.length > 0) {
mimeHelper.setCc(cc);
}
// add attachment file if set
if (attachmentFilename != null && attachmentFile != null) {
mimeHelper.addAttachment(attachmentFilename, attachmentFile);
}
sendMail(mimeMailMessage);
} | [
"public",
"void",
"sendMimeMail",
"(",
"String",
"from",
",",
"String",
"replyTo",
",",
"String",
"[",
"]",
"to",
",",
"String",
"[",
"]",
"cc",
",",
"String",
"[",
"]",
"bcc",
",",
"String",
"subject",
",",
"String",
"msg",
",",
"Boolean",
"html",
"... | Sends a MimeMessage.
@param from The mail sender address.
@param replyTo The reply to address.
@param to A list of mail recipient addresses.
@param cc A list of carbon copy mail recipient addresses.
@param bcc A list of blind carbon copy mail recipient addresses.
@param subject The mail subject.
@param msg The mail message text.
@param html Whether to apply content type "text/html" or the default
content type ("text/plain").
@param attachmentFilename The attachment file name.
@param attachmentFile The file resource to be applied to the mail.
@throws MessagingException | [
"Sends",
"a",
"MimeMessage",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/mail/MailPublisher.java#L93-L141 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/naming/ImplicitNamingStrategyShogunCore.java | ImplicitNamingStrategyShogunCore.transformEntityName | @Override
protected String transformEntityName(EntityNaming entityNaming) {
String singular = super.transformEntityName(entityNaming);
return transformToPluralForm(singular);
} | java | @Override
protected String transformEntityName(EntityNaming entityNaming) {
String singular = super.transformEntityName(entityNaming);
return transformToPluralForm(singular);
} | [
"@",
"Override",
"protected",
"String",
"transformEntityName",
"(",
"EntityNaming",
"entityNaming",
")",
"{",
"String",
"singular",
"=",
"super",
".",
"transformEntityName",
"(",
"entityNaming",
")",
";",
"return",
"transformToPluralForm",
"(",
"singular",
")",
";",... | Transforms an entity name to plural form. | [
"Transforms",
"an",
"entity",
"name",
"to",
"plural",
"form",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/naming/ImplicitNamingStrategyShogunCore.java#L114-L120 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/UserService.java | UserService.registerUser | public E registerUser(E user, HttpServletRequest request) throws Exception {
String email = user.getEmail();
// check if a user with the email already exists
E existingUser = dao.findByEmail(email);
if (existingUser != null) {
final String errorMessage = "User with eMail '" + email + "' already exists.";
LOG.info(errorMessage);
throw new Exception(errorMessage);
}
user = (E) this.persistNewUser(user, true);
// create a token for the user and send an email with an "activation" link
registrationTokenService.sendRegistrationActivationMail(request, user);
return user;
} | java | public E registerUser(E user, HttpServletRequest request) throws Exception {
String email = user.getEmail();
// check if a user with the email already exists
E existingUser = dao.findByEmail(email);
if (existingUser != null) {
final String errorMessage = "User with eMail '" + email + "' already exists.";
LOG.info(errorMessage);
throw new Exception(errorMessage);
}
user = (E) this.persistNewUser(user, true);
// create a token for the user and send an email with an "activation" link
registrationTokenService.sendRegistrationActivationMail(request, user);
return user;
} | [
"public",
"E",
"registerUser",
"(",
"E",
"user",
",",
"HttpServletRequest",
"request",
")",
"throws",
"Exception",
"{",
"String",
"email",
"=",
"user",
".",
"getEmail",
"(",
")",
";",
"// check if a user with the email already exists",
"E",
"existingUser",
"=",
"d... | Registers a new user. Initially, the user will be inactive. An email with
an activation link will be sent to the user.
@param user A user with an UNencrypted password (!)
@param request
@throws Exception | [
"Registers",
"a",
"new",
"user",
".",
"Initially",
"the",
"user",
"will",
"be",
"inactive",
".",
"An",
"email",
"with",
"an",
"activation",
"link",
"will",
"be",
"sent",
"to",
"the",
"user",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/UserService.java#L122-L141 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/UserService.java | UserService.persistNewUser | public E persistNewUser(E user, boolean encryptPassword) {
if (user.getId() != null) {
// to be sure that we are in the
// "create" case, the id must be null
return user;
}
if (encryptPassword) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
dao.saveOrUpdate(user);
return user;
} | java | public E persistNewUser(E user, boolean encryptPassword) {
if (user.getId() != null) {
// to be sure that we are in the
// "create" case, the id must be null
return user;
}
if (encryptPassword) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
}
dao.saveOrUpdate(user);
return user;
} | [
"public",
"E",
"persistNewUser",
"(",
"E",
"user",
",",
"boolean",
"encryptPassword",
")",
"{",
"if",
"(",
"user",
".",
"getId",
"(",
")",
"!=",
"null",
")",
"{",
"// to be sure that we are in the",
"// \"create\" case, the id must be null",
"return",
"user",
";",... | Persists a new user in the database.
@param user The user to create
@param encryptPassword Whether or not the current password of the user object should
be encrypted or not before the object is persisted in the db
@return The persisted user object (incl. ID value) | [
"Persists",
"a",
"new",
"user",
"in",
"the",
"database",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/UserService.java#L189-L204 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/converter/PropertyValueConverter.java | PropertyValueConverter.convertToEntityAttribute | @Override
public Object convertToEntityAttribute(String dbData) {
if ("true".equalsIgnoreCase(dbData)) {
return true;
} else if ("false".equalsIgnoreCase(dbData)) {
return false;
} else if (NumberUtils.isParsable(dbData)) {
if (NumberUtils.isDigits(dbData) ||
(dbData.startsWith("-") &&
NumberUtils.isDigits(dbData.substring(1)))) {
return Long.parseLong(dbData);
} else {
return Double.parseDouble(dbData);
}
}
return dbData;
} | java | @Override
public Object convertToEntityAttribute(String dbData) {
if ("true".equalsIgnoreCase(dbData)) {
return true;
} else if ("false".equalsIgnoreCase(dbData)) {
return false;
} else if (NumberUtils.isParsable(dbData)) {
if (NumberUtils.isDigits(dbData) ||
(dbData.startsWith("-") &&
NumberUtils.isDigits(dbData.substring(1)))) {
return Long.parseLong(dbData);
} else {
return Double.parseDouble(dbData);
}
}
return dbData;
} | [
"@",
"Override",
"public",
"Object",
"convertToEntityAttribute",
"(",
"String",
"dbData",
")",
"{",
"if",
"(",
"\"true\"",
".",
"equalsIgnoreCase",
"(",
"dbData",
")",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"\"false\"",
".",
"equalsIgnoreCa... | Converts a string value from the database to the best matching java
primitive type. | [
"Converts",
"a",
"string",
"value",
"from",
"the",
"database",
"to",
"the",
"best",
"matching",
"java",
"primitive",
"type",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/converter/PropertyValueConverter.java#L37-L53 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/security/access/entity/UserGroupPermissionEvaluator.java | UserGroupPermissionEvaluator.hasPermission | @Override
public boolean hasPermission(User user, E userGroup, Permission permission) {
// always grant READ access to groups in which the user itself is a member
if (user != null && permission.equals(Permission.READ)
&& userGroup.getMembers().contains(user)) {
LOG.trace("Granting READ access on group where the user is member.");
return true;
}
// call parent implementation
return super.hasPermission(user, userGroup, permission);
} | java | @Override
public boolean hasPermission(User user, E userGroup, Permission permission) {
// always grant READ access to groups in which the user itself is a member
if (user != null && permission.equals(Permission.READ)
&& userGroup.getMembers().contains(user)) {
LOG.trace("Granting READ access on group where the user is member.");
return true;
}
// call parent implementation
return super.hasPermission(user, userGroup, permission);
} | [
"@",
"Override",
"public",
"boolean",
"hasPermission",
"(",
"User",
"user",
",",
"E",
"userGroup",
",",
"Permission",
"permission",
")",
"{",
"// always grant READ access to groups in which the user itself is a member",
"if",
"(",
"user",
"!=",
"null",
"&&",
"permission... | Grants READ permission on groups where the user is a member.
Uses default implementation otherwise. | [
"Grants",
"READ",
"permission",
"on",
"groups",
"where",
"the",
"user",
"is",
"a",
"member",
".",
"Uses",
"default",
"implementation",
"otherwise",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/security/access/entity/UserGroupPermissionEvaluator.java#L34-L46 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/naming/PhysicalNamingStrategyShogunCore.java | PhysicalNamingStrategyShogunCore.toPhysicalTableName | @Override
public Identifier toPhysicalTableName(Identifier tableIdentifier, JdbcEnvironment context) {
return convertToLimitedLowerCase(context, tableIdentifier, tablePrefix);
} | java | @Override
public Identifier toPhysicalTableName(Identifier tableIdentifier, JdbcEnvironment context) {
return convertToLimitedLowerCase(context, tableIdentifier, tablePrefix);
} | [
"@",
"Override",
"public",
"Identifier",
"toPhysicalTableName",
"(",
"Identifier",
"tableIdentifier",
",",
"JdbcEnvironment",
"context",
")",
"{",
"return",
"convertToLimitedLowerCase",
"(",
"context",
",",
"tableIdentifier",
",",
"tablePrefix",
")",
";",
"}"
] | Converts table names to lower case and limits the length if necessary. | [
"Converts",
"table",
"names",
"to",
"lower",
"case",
"and",
"limits",
"the",
"length",
"if",
"necessary",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/naming/PhysicalNamingStrategyShogunCore.java#L48-L51 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/naming/PhysicalNamingStrategyShogunCore.java | PhysicalNamingStrategyShogunCore.toPhysicalColumnName | @Override
public Identifier toPhysicalColumnName(Identifier columnIdentifier, JdbcEnvironment context) {
return convertToLimitedLowerCase(context, columnIdentifier, null);
} | java | @Override
public Identifier toPhysicalColumnName(Identifier columnIdentifier, JdbcEnvironment context) {
return convertToLimitedLowerCase(context, columnIdentifier, null);
} | [
"@",
"Override",
"public",
"Identifier",
"toPhysicalColumnName",
"(",
"Identifier",
"columnIdentifier",
",",
"JdbcEnvironment",
"context",
")",
"{",
"return",
"convertToLimitedLowerCase",
"(",
"context",
",",
"columnIdentifier",
",",
"null",
")",
";",
"}"
] | Converts column names to lower case and limits the length if necessary. | [
"Converts",
"column",
"names",
"to",
"lower",
"case",
"and",
"limits",
"the",
"length",
"if",
"necessary",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/naming/PhysicalNamingStrategyShogunCore.java#L56-L59 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/naming/PhysicalNamingStrategyShogunCore.java | PhysicalNamingStrategyShogunCore.getIdentifierLengthLimit | protected Integer getIdentifierLengthLimit(JdbcEnvironment context) {
// https://docs.jboss.org/hibernate/orm/5.0/javadocs/org/hibernate/dialect/package-summary.html
String dialectName = context.getDialect().getClass().getSimpleName();
if (dialectName.startsWith("Oracle")) {
// identifier limit of 30 chars -->
// http://stackoverflow.com/a/756569
return LENGTH_LIMIT_ORACLE;
} else if (context.getDialect() instanceof ShogunCoreOracleDialect) {
// identifier limit of 30 chars -->
return LENGTH_LIMIT_ORACLE;
} else if (dialectName.startsWith("PostgreSQL")) {
// identifier limit of 63 chars -->
// http://stackoverflow.com/a/8218026
return LENGTH_LIMIT_POSTGRESQL;
}
// H2 has no limit --> http://stackoverflow.com/a/30477403
return null;
} | java | protected Integer getIdentifierLengthLimit(JdbcEnvironment context) {
// https://docs.jboss.org/hibernate/orm/5.0/javadocs/org/hibernate/dialect/package-summary.html
String dialectName = context.getDialect().getClass().getSimpleName();
if (dialectName.startsWith("Oracle")) {
// identifier limit of 30 chars -->
// http://stackoverflow.com/a/756569
return LENGTH_LIMIT_ORACLE;
} else if (context.getDialect() instanceof ShogunCoreOracleDialect) {
// identifier limit of 30 chars -->
return LENGTH_LIMIT_ORACLE;
} else if (dialectName.startsWith("PostgreSQL")) {
// identifier limit of 63 chars -->
// http://stackoverflow.com/a/8218026
return LENGTH_LIMIT_POSTGRESQL;
}
// H2 has no limit --> http://stackoverflow.com/a/30477403
return null;
} | [
"protected",
"Integer",
"getIdentifierLengthLimit",
"(",
"JdbcEnvironment",
"context",
")",
"{",
"// https://docs.jboss.org/hibernate/orm/5.0/javadocs/org/hibernate/dialect/package-summary.html",
"String",
"dialectName",
"=",
"context",
".",
"getDialect",
"(",
")",
".",
"getClass... | Determines the identifier length limit for the given JDBC context.
Returns null if no limitation is necessary.
@param context The current JDBC context
@return The identifier length limit for the given context. null
otherwise. | [
"Determines",
"the",
"identifier",
"length",
"limit",
"for",
"the",
"given",
"JDBC",
"context",
".",
"Returns",
"null",
"if",
"no",
"limitation",
"is",
"necessary",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/naming/PhysicalNamingStrategyShogunCore.java#L101-L120 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/interceptor/MutableHttpServletRequest.java | MutableHttpServletRequest.getParameterIgnoreCase | public String getParameterIgnoreCase(String name) {
for (Map.Entry<String, String[]> entry : customParameters.entrySet()) {
if (entry.getKey().equalsIgnoreCase(name)) {
return StringUtils.join(entry.getValue(), ",");
}
}
return null;
} | java | public String getParameterIgnoreCase(String name) {
for (Map.Entry<String, String[]> entry : customParameters.entrySet()) {
if (entry.getKey().equalsIgnoreCase(name)) {
return StringUtils.join(entry.getValue(), ",");
}
}
return null;
} | [
"public",
"String",
"getParameterIgnoreCase",
"(",
"String",
"name",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
"[",
"]",
">",
"entry",
":",
"customParameters",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"entry",
".",... | Get a parameter by name, ignoring case.
@param name the parameter to get
@return a comma separated list of parameter values | [
"Get",
"a",
"parameter",
"by",
"name",
"ignoring",
"case",
"."
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/util/interceptor/MutableHttpServletRequest.java#L358-L365 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/init/ContentInitializer.java | ContentInitializer.initializeDatabaseContent | public void initializeDatabaseContent() {
if (this.shogunInitEnabled) {
LOG.info("Initializing SHOGun content");
for (PersistentObject object : objectsToCreate) {
if (object instanceof User) {
// special handling of users to encrypt the password!
initService.saveUser((User) object);
} else {
initService.savePersistentObject(object);
}
}
} else {
LOG.info("Not initializing anything for SHOGun.");
}
} | java | public void initializeDatabaseContent() {
if (this.shogunInitEnabled) {
LOG.info("Initializing SHOGun content");
for (PersistentObject object : objectsToCreate) {
if (object instanceof User) {
// special handling of users to encrypt the password!
initService.saveUser((User) object);
} else {
initService.savePersistentObject(object);
}
}
} else {
LOG.info("Not initializing anything for SHOGun.");
}
} | [
"public",
"void",
"initializeDatabaseContent",
"(",
")",
"{",
"if",
"(",
"this",
".",
"shogunInitEnabled",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Initializing SHOGun content\"",
")",
";",
"for",
"(",
"PersistentObject",
"object",
":",
"objectsToCreate",
")",
"{",... | The method called on initialization | [
"The",
"method",
"called",
"on",
"initialization"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/init/ContentInitializer.java#L56-L70 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/FileService.java | FileService.uploadFile | @PreAuthorize("isAuthenticated()")
public E uploadFile(MultipartFile file) throws Exception {
if (file == null) {
final String errMsg = "Upload failed. File is null.";
LOG.error(errMsg);
throw new Exception(errMsg);
} else if (file.isEmpty()) {
final String errMsg = "Upload failed. File is empty.";
LOG.error(errMsg);
throw new Exception(errMsg);
}
InputStream is = null;
byte[] fileByteArray = null;
E fileToPersist = getEntityClass().newInstance();
try {
is = file.getInputStream();
fileByteArray = IOUtils.toByteArray(is);
} catch (Exception e) {
throw new Exception("Could not create the bytearray: " + e.getMessage());
} finally {
IOUtils.closeQuietly(is);
}
fileToPersist.setFile(fileByteArray);
fileToPersist.setFileType(file.getContentType());
fileToPersist.setFileName(file.getOriginalFilename());
dao.saveOrUpdate(fileToPersist);
return fileToPersist;
} | java | @PreAuthorize("isAuthenticated()")
public E uploadFile(MultipartFile file) throws Exception {
if (file == null) {
final String errMsg = "Upload failed. File is null.";
LOG.error(errMsg);
throw new Exception(errMsg);
} else if (file.isEmpty()) {
final String errMsg = "Upload failed. File is empty.";
LOG.error(errMsg);
throw new Exception(errMsg);
}
InputStream is = null;
byte[] fileByteArray = null;
E fileToPersist = getEntityClass().newInstance();
try {
is = file.getInputStream();
fileByteArray = IOUtils.toByteArray(is);
} catch (Exception e) {
throw new Exception("Could not create the bytearray: " + e.getMessage());
} finally {
IOUtils.closeQuietly(is);
}
fileToPersist.setFile(fileByteArray);
fileToPersist.setFileType(file.getContentType());
fileToPersist.setFileName(file.getOriginalFilename());
dao.saveOrUpdate(fileToPersist);
return fileToPersist;
} | [
"@",
"PreAuthorize",
"(",
"\"isAuthenticated()\"",
")",
"public",
"E",
"uploadFile",
"(",
"MultipartFile",
"file",
")",
"throws",
"Exception",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"final",
"String",
"errMsg",
"=",
"\"Upload failed. File is null.\"",
"... | Method persists a given MultipartFile as a bytearray in the database
@param file
@throws Exception | [
"Method",
"persists",
"a",
"given",
"MultipartFile",
"as",
"a",
"bytearray",
"in",
"the",
"database"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/FileService.java#L59-L92 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/ImageFileService.java | ImageFileService.saveImage | @PreAuthorize("isAuthenticated()")
public E saveImage(MultipartFile file, boolean createThumbnail, Integer thumbnailTargetSize)
throws Exception {
InputStream is = null;
ByteArrayInputStream bais = null;
E imageToPersist = null;
try {
is = file.getInputStream();
byte[] imageByteArray = IOUtils.toByteArray(is);
// create a new instance (generic)
imageToPersist = getEntityClass().newInstance();
// create a thumbnail if requested
if (createThumbnail) {
byte[] thumbnail = scaleImage(
imageByteArray,
FilenameUtils.getExtension(file.getOriginalFilename()),
thumbnailTargetSize);
imageToPersist.setThumbnail(thumbnail);
}
// set binary image data
imageToPersist.setFile(imageByteArray);
// detect dimensions
bais = new ByteArrayInputStream(imageByteArray);
BufferedImage bimg = ImageIO.read(bais);
// set basic image properties
imageToPersist.setWidth(bimg.getWidth());
imageToPersist.setHeight(bimg.getHeight());
imageToPersist.setFileType(file.getContentType());
imageToPersist.setFileName(file.getOriginalFilename());
// persist the image
dao.saveOrUpdate(imageToPersist);
} catch (Exception e) {
throw new Exception("Could not create the Image in DB: "
+ e.getMessage());
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(bais);
}
return imageToPersist;
} | java | @PreAuthorize("isAuthenticated()")
public E saveImage(MultipartFile file, boolean createThumbnail, Integer thumbnailTargetSize)
throws Exception {
InputStream is = null;
ByteArrayInputStream bais = null;
E imageToPersist = null;
try {
is = file.getInputStream();
byte[] imageByteArray = IOUtils.toByteArray(is);
// create a new instance (generic)
imageToPersist = getEntityClass().newInstance();
// create a thumbnail if requested
if (createThumbnail) {
byte[] thumbnail = scaleImage(
imageByteArray,
FilenameUtils.getExtension(file.getOriginalFilename()),
thumbnailTargetSize);
imageToPersist.setThumbnail(thumbnail);
}
// set binary image data
imageToPersist.setFile(imageByteArray);
// detect dimensions
bais = new ByteArrayInputStream(imageByteArray);
BufferedImage bimg = ImageIO.read(bais);
// set basic image properties
imageToPersist.setWidth(bimg.getWidth());
imageToPersist.setHeight(bimg.getHeight());
imageToPersist.setFileType(file.getContentType());
imageToPersist.setFileName(file.getOriginalFilename());
// persist the image
dao.saveOrUpdate(imageToPersist);
} catch (Exception e) {
throw new Exception("Could not create the Image in DB: "
+ e.getMessage());
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(bais);
}
return imageToPersist;
} | [
"@",
"PreAuthorize",
"(",
"\"isAuthenticated()\"",
")",
"public",
"E",
"saveImage",
"(",
"MultipartFile",
"file",
",",
"boolean",
"createThumbnail",
",",
"Integer",
"thumbnailTargetSize",
")",
"throws",
"Exception",
"{",
"InputStream",
"is",
"=",
"null",
";",
"Byt... | Method persists a given Image as a bytearray in the database
@param file
@param createThumbnail
@param thumbnailTargetSize
@throws Exception | [
"Method",
"persists",
"a",
"given",
"Image",
"as",
"a",
"bytearray",
"in",
"the",
"database"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/ImageFileService.java#L98-L148 | train |
terrestris/shogun-core | src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/ImageFileService.java | ImageFileService.scaleImage | public static byte[] scaleImage(byte[] imageBytes, String outputFormat,
Integer targetSize) throws Exception {
InputStream is = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] imageInBytes = null;
BufferedImage image = null;
BufferedImage resizedImage = null;
try {
is = new ByteArrayInputStream(imageBytes);
image = ImageIO.read(is);
resizedImage = Scalr.resize(image, targetSize);
ImageIO.write(resizedImage, outputFormat, baos);
imageInBytes = baos.toByteArray();
} catch (Exception e) {
throw new Exception("Error on resizing an image: " + e.getMessage());
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(baos);
if (image != null) {
image.flush();
}
if (resizedImage != null) {
resizedImage.flush();
}
}
return imageInBytes;
} | java | public static byte[] scaleImage(byte[] imageBytes, String outputFormat,
Integer targetSize) throws Exception {
InputStream is = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] imageInBytes = null;
BufferedImage image = null;
BufferedImage resizedImage = null;
try {
is = new ByteArrayInputStream(imageBytes);
image = ImageIO.read(is);
resizedImage = Scalr.resize(image, targetSize);
ImageIO.write(resizedImage, outputFormat, baos);
imageInBytes = baos.toByteArray();
} catch (Exception e) {
throw new Exception("Error on resizing an image: " + e.getMessage());
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(baos);
if (image != null) {
image.flush();
}
if (resizedImage != null) {
resizedImage.flush();
}
}
return imageInBytes;
} | [
"public",
"static",
"byte",
"[",
"]",
"scaleImage",
"(",
"byte",
"[",
"]",
"imageBytes",
",",
"String",
"outputFormat",
",",
"Integer",
"targetSize",
")",
"throws",
"Exception",
"{",
"InputStream",
"is",
"=",
"null",
";",
"ByteArrayOutputStream",
"baos",
"=",
... | Scales an image by the given dimensions
@param outputFormat
@param targetSize width/height in px (square)
@throws Exception | [
"Scales",
"an",
"image",
"by",
"the",
"given",
"dimensions"
] | 3dbabda35ae63235265913c865dba389b050b6e6 | https://github.com/terrestris/shogun-core/blob/3dbabda35ae63235265913c865dba389b050b6e6/src/shogun-core-main/src/main/java/de/terrestris/shoguncore/service/ImageFileService.java#L157-L185 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/impl/JenkinsLogs.java | JenkinsLogs.addMasterJulLogRecords | private void addMasterJulLogRecords(Container result) {
// this file captures the most recent of those that are still kept around in memory.
// this overlaps with Jenkins.logRecords, and also overlaps with what's written in files,
// but added nonetheless just in case.
//
// should be ignorable.
result.add(new LogRecordContent("nodes/master/logs/all_memory_buffer.log") {
@Override
public Iterable<LogRecord> getLogRecords() {
return SupportPlugin.getInstance().getAllLogRecords();
}
});
final File[] julLogFiles = SupportPlugin.getRootDirectory().listFiles(new LogFilenameFilter());
if (julLogFiles == null) {
LOGGER.log(Level.WARNING, "Cannot add master java.util.logging logs to the bundle. Cannot access log files");
return;
}
// log records written to the disk
for (File file : julLogFiles){
result.add(new FileContent("nodes/master/logs/{0}", new String[]{file.getName()}, file));
}
} | java | private void addMasterJulLogRecords(Container result) {
// this file captures the most recent of those that are still kept around in memory.
// this overlaps with Jenkins.logRecords, and also overlaps with what's written in files,
// but added nonetheless just in case.
//
// should be ignorable.
result.add(new LogRecordContent("nodes/master/logs/all_memory_buffer.log") {
@Override
public Iterable<LogRecord> getLogRecords() {
return SupportPlugin.getInstance().getAllLogRecords();
}
});
final File[] julLogFiles = SupportPlugin.getRootDirectory().listFiles(new LogFilenameFilter());
if (julLogFiles == null) {
LOGGER.log(Level.WARNING, "Cannot add master java.util.logging logs to the bundle. Cannot access log files");
return;
}
// log records written to the disk
for (File file : julLogFiles){
result.add(new FileContent("nodes/master/logs/{0}", new String[]{file.getName()}, file));
}
} | [
"private",
"void",
"addMasterJulLogRecords",
"(",
"Container",
"result",
")",
"{",
"// this file captures the most recent of those that are still kept around in memory.",
"// this overlaps with Jenkins.logRecords, and also overlaps with what's written in files,",
"// but added nonetheless just i... | Adds j.u.l logging output that the support-core plugin captures.
<p>
Compared to {@link #addMasterJulRingBuffer(Container)}, this one uses disk files,
so it remembers larger number of entries. | [
"Adds",
"j",
".",
"u",
".",
"l",
"logging",
"output",
"that",
"the",
"support",
"-",
"core",
"plugin",
"captures",
"."
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/impl/JenkinsLogs.java#L172-L195 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/impl/LoadStats.java | LoadStats.camelCaseToSentenceCase | private static String camelCaseToSentenceCase(String camelCase) {
String name = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(camelCase), " ");
return name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1)
.toLowerCase(Locale.ENGLISH);
} | java | private static String camelCaseToSentenceCase(String camelCase) {
String name = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(camelCase), " ");
return name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1)
.toLowerCase(Locale.ENGLISH);
} | [
"private",
"static",
"String",
"camelCaseToSentenceCase",
"(",
"String",
"camelCase",
")",
"{",
"String",
"name",
"=",
"StringUtils",
".",
"join",
"(",
"StringUtils",
".",
"splitByCharacterTypeCamelCase",
"(",
"camelCase",
")",
",",
"\" \"",
")",
";",
"return",
... | Converts "aCamelCaseString" into "A sentence case string".
@param camelCase camelCase.
@return Sentence case. | [
"Converts",
"aCamelCaseString",
"into",
"A",
"sentence",
"case",
"string",
"."
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/impl/LoadStats.java#L295-L299 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/filter/ContentMappings.java | ContentMappings.newInstance | public static @Extension ContentMappings newInstance() throws IOException {
ContentMappings mappings = Persistence.load(ContentMappings.class);
if (mappings == null) {
mappings = (ContentMappings) new XmlProxy().readResolve();
}
return mappings;
} | java | public static @Extension ContentMappings newInstance() throws IOException {
ContentMappings mappings = Persistence.load(ContentMappings.class);
if (mappings == null) {
mappings = (ContentMappings) new XmlProxy().readResolve();
}
return mappings;
} | [
"public",
"static",
"@",
"Extension",
"ContentMappings",
"newInstance",
"(",
")",
"throws",
"IOException",
"{",
"ContentMappings",
"mappings",
"=",
"Persistence",
".",
"load",
"(",
"ContentMappings",
".",
"class",
")",
";",
"if",
"(",
"mappings",
"==",
"null",
... | Constructs a new ContentMappings using an existing config file or default settings if not found. | [
"Constructs",
"a",
"new",
"ContentMappings",
"using",
"an",
"existing",
"config",
"file",
"or",
"default",
"settings",
"if",
"not",
"found",
"."
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/filter/ContentMappings.java#L74-L80 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/SupportAction.java | SupportAction.doDownload | @RequirePOST
public void doDownload(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
doGenerateAllBundles(req, rsp);
} | java | @RequirePOST
public void doDownload(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
doGenerateAllBundles(req, rsp);
} | [
"@",
"RequirePOST",
"public",
"void",
"doDownload",
"(",
"StaplerRequest",
"req",
",",
"StaplerResponse",
"rsp",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"doGenerateAllBundles",
"(",
"req",
",",
"rsp",
")",
";",
"}"
] | Generates a support bundle.
@param req The stapler request
@param rsp The stapler response
@throws ServletException
@throws IOException | [
"Generates",
"a",
"support",
"bundle",
"."
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/SupportAction.java#L165-L168 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/api/FileContent.java | FileContent.isBinary | private boolean isBinary() {
try (InputStream in = getInputStream()) {
long size = Files.size(file.toPath());
if (size == 0) {
// Empty file, so no need to check
return true;
}
byte[] b = new byte[( size < StreamUtils.DEFAULT_PROBE_SIZE ? (int)size : StreamUtils.DEFAULT_PROBE_SIZE)];
int read = in.read(b);
if (read != b.length) {
// Something went wrong, so better not to read line by line
return true;
}
return StreamUtils.isNonWhitespaceControlCharacter(b);
} catch (IOException e) {
// If cannot be checked, then considered as binary, so we do not
// read line by line
return true;
}
} | java | private boolean isBinary() {
try (InputStream in = getInputStream()) {
long size = Files.size(file.toPath());
if (size == 0) {
// Empty file, so no need to check
return true;
}
byte[] b = new byte[( size < StreamUtils.DEFAULT_PROBE_SIZE ? (int)size : StreamUtils.DEFAULT_PROBE_SIZE)];
int read = in.read(b);
if (read != b.length) {
// Something went wrong, so better not to read line by line
return true;
}
return StreamUtils.isNonWhitespaceControlCharacter(b);
} catch (IOException e) {
// If cannot be checked, then considered as binary, so we do not
// read line by line
return true;
}
} | [
"private",
"boolean",
"isBinary",
"(",
")",
"{",
"try",
"(",
"InputStream",
"in",
"=",
"getInputStream",
"(",
")",
")",
"{",
"long",
"size",
"=",
"Files",
".",
"size",
"(",
"file",
".",
"toPath",
"(",
")",
")",
";",
"if",
"(",
"size",
"==",
"0",
... | Check if the file is binary or not | [
"Check",
"if",
"the",
"file",
"is",
"binary",
"or",
"not"
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/api/FileContent.java#L169-L190 | train |
rosette-api/java | api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java | HttpRosetteAPI.getVersion | private static String getVersion() {
Properties properties = new Properties();
try (InputStream ins = HttpRosetteAPI.class.getClassLoader().getResourceAsStream("version.properties")) {
properties.load(ins);
} catch (IOException e) {
// should not happen
}
return properties.getProperty("version", "undefined");
} | java | private static String getVersion() {
Properties properties = new Properties();
try (InputStream ins = HttpRosetteAPI.class.getClassLoader().getResourceAsStream("version.properties")) {
properties.load(ins);
} catch (IOException e) {
// should not happen
}
return properties.getProperty("version", "undefined");
} | [
"private",
"static",
"String",
"getVersion",
"(",
")",
"{",
"Properties",
"properties",
"=",
"new",
"Properties",
"(",
")",
";",
"try",
"(",
"InputStream",
"ins",
"=",
"HttpRosetteAPI",
".",
"class",
".",
"getClassLoader",
"(",
")",
".",
"getResourceAsStream",... | Returns the version of the binding.
@return version of the binding | [
"Returns",
"the",
"version",
"of",
"the",
"binding",
"."
] | 35faf9fbb9c940eae47df004da7639a3b177b80b | https://github.com/rosette-api/java/blob/35faf9fbb9c940eae47df004da7639a3b177b80b/api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java#L144-L152 | train |
rosette-api/java | api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java | HttpRosetteAPI.getBytes | private static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
while (true) {
int r = is.read(buf);
if (r == -1) {
out.flush();
return out.toByteArray();
}
out.write(buf, 0, r);
}
} | java | private static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
while (true) {
int r = is.read(buf);
if (r == -1) {
out.flush();
return out.toByteArray();
}
out.write(buf, 0, r);
}
} | [
"private",
"static",
"byte",
"[",
"]",
"getBytes",
"(",
"InputStream",
"is",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"out",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"byte",
"[",
"]",
"buf",
"=",
"new",
"byte",
"[",
"4096",
"]... | Returns a byte array from InputStream.
@param is InputStream
@return byte array
@throws IOException | [
"Returns",
"a",
"byte",
"array",
"from",
"InputStream",
"."
] | 35faf9fbb9c940eae47df004da7639a3b177b80b | https://github.com/rosette-api/java/blob/35faf9fbb9c940eae47df004da7639a3b177b80b/api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java#L161-L174 | train |
rosette-api/java | api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java | HttpRosetteAPI.getSupportedLanguages | @Override
public SupportedLanguagesResponse getSupportedLanguages(String endpoint) throws HttpRosetteAPIException {
if (DOC_ENDPOINTS.contains(endpoint) || NAME_DEDUPLICATION_SERVICE_PATH.equals(endpoint)) {
return sendGetRequest(urlBase + endpoint + SUPPORTED_LANGUAGES_SUBPATH, SupportedLanguagesResponse.class);
} else {
return null;
}
} | java | @Override
public SupportedLanguagesResponse getSupportedLanguages(String endpoint) throws HttpRosetteAPIException {
if (DOC_ENDPOINTS.contains(endpoint) || NAME_DEDUPLICATION_SERVICE_PATH.equals(endpoint)) {
return sendGetRequest(urlBase + endpoint + SUPPORTED_LANGUAGES_SUBPATH, SupportedLanguagesResponse.class);
} else {
return null;
}
} | [
"@",
"Override",
"public",
"SupportedLanguagesResponse",
"getSupportedLanguages",
"(",
"String",
"endpoint",
")",
"throws",
"HttpRosetteAPIException",
"{",
"if",
"(",
"DOC_ENDPOINTS",
".",
"contains",
"(",
"endpoint",
")",
"||",
"NAME_DEDUPLICATION_SERVICE_PATH",
".",
"... | Gets the set of language and script codes supported by the specified Rosette API endpoint.
@return SupportedLanguagesResponse
@throws HttpRosetteAPIException for an error returned from the Rosette API. | [
"Gets",
"the",
"set",
"of",
"language",
"and",
"script",
"codes",
"supported",
"by",
"the",
"specified",
"Rosette",
"API",
"endpoint",
"."
] | 35faf9fbb9c940eae47df004da7639a3b177b80b | https://github.com/rosette-api/java/blob/35faf9fbb9c940eae47df004da7639a3b177b80b/api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java#L240-L247 | train |
rosette-api/java | api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java | HttpRosetteAPI.getSupportedLanguagePairs | @Override
public SupportedLanguagePairsResponse getSupportedLanguagePairs(String endpoint) throws HttpRosetteAPIException {
if (NAMES_ENDPOINTS.contains(endpoint) && !NAME_DEDUPLICATION_SERVICE_PATH.equals(endpoint)) {
return sendGetRequest(urlBase + endpoint + SUPPORTED_LANGUAGES_SUBPATH, SupportedLanguagePairsResponse.class);
} else {
return null;
}
} | java | @Override
public SupportedLanguagePairsResponse getSupportedLanguagePairs(String endpoint) throws HttpRosetteAPIException {
if (NAMES_ENDPOINTS.contains(endpoint) && !NAME_DEDUPLICATION_SERVICE_PATH.equals(endpoint)) {
return sendGetRequest(urlBase + endpoint + SUPPORTED_LANGUAGES_SUBPATH, SupportedLanguagePairsResponse.class);
} else {
return null;
}
} | [
"@",
"Override",
"public",
"SupportedLanguagePairsResponse",
"getSupportedLanguagePairs",
"(",
"String",
"endpoint",
")",
"throws",
"HttpRosetteAPIException",
"{",
"if",
"(",
"NAMES_ENDPOINTS",
".",
"contains",
"(",
"endpoint",
")",
"&&",
"!",
"NAME_DEDUPLICATION_SERVICE_... | Gets the set of language, script codes and transliteration scheme pairs supported by the specified Rosette API
endpoint.
@param endpoint Rosette API endpoint.
@return SupportedLanguagePairsResponse
@throws HttpRosetteAPIException for an error returned from the Rosette API. | [
"Gets",
"the",
"set",
"of",
"language",
"script",
"codes",
"and",
"transliteration",
"scheme",
"pairs",
"supported",
"by",
"the",
"specified",
"Rosette",
"API",
"endpoint",
"."
] | 35faf9fbb9c940eae47df004da7639a3b177b80b | https://github.com/rosette-api/java/blob/35faf9fbb9c940eae47df004da7639a3b177b80b/api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java#L257-L264 | train |
rosette-api/java | api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java | HttpRosetteAPI.performAsync | @Override
public <RequestType extends Request, ResponseType extends Response> Future<ResponseType> performAsync(String endpoint, RequestType request, Class<ResponseType> responseClass) throws HttpRosetteAPIException {
throw new UnsupportedOperationException("Asynchronous operations are not yet supported");
} | java | @Override
public <RequestType extends Request, ResponseType extends Response> Future<ResponseType> performAsync(String endpoint, RequestType request, Class<ResponseType> responseClass) throws HttpRosetteAPIException {
throw new UnsupportedOperationException("Asynchronous operations are not yet supported");
} | [
"@",
"Override",
"public",
"<",
"RequestType",
"extends",
"Request",
",",
"ResponseType",
"extends",
"Response",
">",
"Future",
"<",
"ResponseType",
">",
"performAsync",
"(",
"String",
"endpoint",
",",
"RequestType",
"request",
",",
"Class",
"<",
"ResponseType",
... | This method always throws UnsupportedOperationException. | [
"This",
"method",
"always",
"throws",
"UnsupportedOperationException",
"."
] | 35faf9fbb9c940eae47df004da7639a3b177b80b | https://github.com/rosette-api/java/blob/35faf9fbb9c940eae47df004da7639a3b177b80b/api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java#L311-L314 | train |
rosette-api/java | api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java | HttpRosetteAPI.getResponse | private <T extends Object> T getResponse(HttpResponse httpResponse, Class<T> clazz) throws IOException, HttpRosetteAPIException {
int status = httpResponse.getStatusLine().getStatusCode();
String encoding = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_ENCODING));
try (
InputStream stream = httpResponse.getEntity().getContent();
InputStream inputStream = "gzip".equalsIgnoreCase(encoding) ? new GZIPInputStream(stream) : stream) {
String ridHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-DocumentRequest-Id"));
if (HTTP_OK != status) {
String ecHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Code"));
String emHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Message"));
String responseContentType = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE));
if ("application/json".equals(responseContentType)) {
ErrorResponse errorResponse = mapper.readValue(inputStream, ErrorResponse.class);
if (ridHeader != null) {
LOG.debug("DocumentRequest ID " + ridHeader);
}
if (ecHeader != null) {
errorResponse.setCode(ecHeader);
}
if (429 == status) {
String concurrencyMessage = "You have exceeded your plan's limit on concurrent calls. "
+ "This could be caused by multiple processes or threads making Rosette API calls in parallel, "
+ "or if your httpClient is configured with higher concurrency than your plan allows.";
if (emHeader == null) {
emHeader = concurrencyMessage;
} else {
emHeader = concurrencyMessage + System.lineSeparator() + emHeader;
}
}
if (emHeader != null) {
errorResponse.setMessage(emHeader);
}
throw new HttpRosetteAPIException(errorResponse, status);
} else {
String errorContent;
if (inputStream != null) {
byte[] content = getBytes(inputStream);
errorContent = new String(content, "utf-8");
} else {
errorContent = "(no body)";
}
// something not from us at all
throw new HttpRosetteAPIException("Invalid error response (not json)",
ErrorResponse.builder().code("invalidErrorResponse").message(errorContent).build(), status);
}
} else {
return mapper.readValue(inputStream, clazz);
}
}
} | java | private <T extends Object> T getResponse(HttpResponse httpResponse, Class<T> clazz) throws IOException, HttpRosetteAPIException {
int status = httpResponse.getStatusLine().getStatusCode();
String encoding = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_ENCODING));
try (
InputStream stream = httpResponse.getEntity().getContent();
InputStream inputStream = "gzip".equalsIgnoreCase(encoding) ? new GZIPInputStream(stream) : stream) {
String ridHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-DocumentRequest-Id"));
if (HTTP_OK != status) {
String ecHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Code"));
String emHeader = headerValueOrNull(httpResponse.getFirstHeader("X-RosetteAPI-Status-Message"));
String responseContentType = headerValueOrNull(httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE));
if ("application/json".equals(responseContentType)) {
ErrorResponse errorResponse = mapper.readValue(inputStream, ErrorResponse.class);
if (ridHeader != null) {
LOG.debug("DocumentRequest ID " + ridHeader);
}
if (ecHeader != null) {
errorResponse.setCode(ecHeader);
}
if (429 == status) {
String concurrencyMessage = "You have exceeded your plan's limit on concurrent calls. "
+ "This could be caused by multiple processes or threads making Rosette API calls in parallel, "
+ "or if your httpClient is configured with higher concurrency than your plan allows.";
if (emHeader == null) {
emHeader = concurrencyMessage;
} else {
emHeader = concurrencyMessage + System.lineSeparator() + emHeader;
}
}
if (emHeader != null) {
errorResponse.setMessage(emHeader);
}
throw new HttpRosetteAPIException(errorResponse, status);
} else {
String errorContent;
if (inputStream != null) {
byte[] content = getBytes(inputStream);
errorContent = new String(content, "utf-8");
} else {
errorContent = "(no body)";
}
// something not from us at all
throw new HttpRosetteAPIException("Invalid error response (not json)",
ErrorResponse.builder().code("invalidErrorResponse").message(errorContent).build(), status);
}
} else {
return mapper.readValue(inputStream, clazz);
}
}
} | [
"private",
"<",
"T",
"extends",
"Object",
">",
"T",
"getResponse",
"(",
"HttpResponse",
"httpResponse",
",",
"Class",
"<",
"T",
">",
"clazz",
")",
"throws",
"IOException",
",",
"HttpRosetteAPIException",
"{",
"int",
"status",
"=",
"httpResponse",
".",
"getStat... | Gets response from HTTP connection, according to the specified response class;
throws for an error response.
@param httpResponse the response object
@param clazz Response class
@return Response
@throws IOException | [
"Gets",
"response",
"from",
"HTTP",
"connection",
"according",
"to",
"the",
"specified",
"response",
"class",
";",
"throws",
"for",
"an",
"error",
"response",
"."
] | 35faf9fbb9c940eae47df004da7639a3b177b80b | https://github.com/rosette-api/java/blob/35faf9fbb9c940eae47df004da7639a3b177b80b/api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java#L535-L585 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/configfiles/SecretHandler.java | SecretHandler.findSecrets | public static String findSecrets(File xmlFile) throws SAXException, IOException, TransformerException {
XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
private String tagName = "";
@Override
public void startElement(String uri, String localName, String qName, Attributes atts)
throws SAXException {
tagName = qName;
super.startElement(uri, localName, qName, atts);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
tagName = "";
super.endElement(uri, localName, qName);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (!"".equals(tagName)) {
String value = new String(ch, start, length).trim();
//if it's a secret, then use a place holder
// convenience check !"{}".equals(value) because of JENKINS-47500
if (!"".equals(value) && !"{}".equals(value)) {
if ((Secret.decrypt(value)) != null || SecretBytes.isSecretBytes(value)) {
ch = SECRET_MARKER.toCharArray();
start = 0;
length = ch.length;
}
}
}
super.characters(ch, start, length);
}
};
String str = FileUtils.readFileToString(xmlFile);
Source src = createSafeSource(xr, new InputSource(new StringReader(str)));
final ByteArrayOutputStream result = new ByteArrayOutputStream();
Result res = new StreamResult(result);
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = factory.newTransformer();
//omit xml declaration because of https://bugs.openjdk.java.net/browse/JDK-8035437
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, OUTPUT_ENCODING);
try {
transformer.transform(src, res);
return result.toString("UTF-8");
} catch (TransformerException e) {
if (ENABLE_FALLBACK) {
return findSecretFallback(str);
} else {
throw e;
}
}
} | java | public static String findSecrets(File xmlFile) throws SAXException, IOException, TransformerException {
XMLReader xr = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
private String tagName = "";
@Override
public void startElement(String uri, String localName, String qName, Attributes atts)
throws SAXException {
tagName = qName;
super.startElement(uri, localName, qName, atts);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
tagName = "";
super.endElement(uri, localName, qName);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (!"".equals(tagName)) {
String value = new String(ch, start, length).trim();
//if it's a secret, then use a place holder
// convenience check !"{}".equals(value) because of JENKINS-47500
if (!"".equals(value) && !"{}".equals(value)) {
if ((Secret.decrypt(value)) != null || SecretBytes.isSecretBytes(value)) {
ch = SECRET_MARKER.toCharArray();
start = 0;
length = ch.length;
}
}
}
super.characters(ch, start, length);
}
};
String str = FileUtils.readFileToString(xmlFile);
Source src = createSafeSource(xr, new InputSource(new StringReader(str)));
final ByteArrayOutputStream result = new ByteArrayOutputStream();
Result res = new StreamResult(result);
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = factory.newTransformer();
//omit xml declaration because of https://bugs.openjdk.java.net/browse/JDK-8035437
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, OUTPUT_ENCODING);
try {
transformer.transform(src, res);
return result.toString("UTF-8");
} catch (TransformerException e) {
if (ENABLE_FALLBACK) {
return findSecretFallback(str);
} else {
throw e;
}
}
} | [
"public",
"static",
"String",
"findSecrets",
"(",
"File",
"xmlFile",
")",
"throws",
"SAXException",
",",
"IOException",
",",
"TransformerException",
"{",
"XMLReader",
"xr",
"=",
"new",
"XMLFilterImpl",
"(",
"XMLReaderFactory",
".",
"createXMLReader",
"(",
")",
")"... | find the secret in the xml file and replace it with the place holder
@param xmlFile we want to parse
@return the patched xml content with redacted secrets
@throws SAXException if some XML parsing issue occurs.
@throws IOException if some issue occurs while reading the providing file.
@throws TransformerException if an issue occurs while writing the result. | [
"find",
"the",
"secret",
"in",
"the",
"xml",
"file",
"and",
"replace",
"it",
"with",
"the",
"place",
"holder"
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/configfiles/SecretHandler.java#L62-L117 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/configfiles/SecretHandler.java | SecretHandler.createSafeSource | private static Source createSafeSource(XMLReader reader, InputSource source) {
try {
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
} catch (SAXException ignored) {
/* Fallback entity resolver will be used */
}
try {
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch (SAXException ignored) {
/* Fallback entity resolver will be used */
}
// Fallback in case the above features are not supported by the underlying XML library.
reader.setEntityResolver((publicId, systemId) -> {
return new InputSource(new ByteArrayInputStream(XXE_MARKER.getBytes(StandardCharsets.US_ASCII)));
});
return new SAXSource(reader, source);
} | java | private static Source createSafeSource(XMLReader reader, InputSource source) {
try {
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
} catch (SAXException ignored) {
/* Fallback entity resolver will be used */
}
try {
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
} catch (SAXException ignored) {
/* Fallback entity resolver will be used */
}
// Fallback in case the above features are not supported by the underlying XML library.
reader.setEntityResolver((publicId, systemId) -> {
return new InputSource(new ByteArrayInputStream(XXE_MARKER.getBytes(StandardCharsets.US_ASCII)));
});
return new SAXSource(reader, source);
} | [
"private",
"static",
"Source",
"createSafeSource",
"(",
"XMLReader",
"reader",
",",
"InputSource",
"source",
")",
"{",
"try",
"{",
"reader",
".",
"setFeature",
"(",
"\"http://xml.org/sax/features/external-general-entities\"",
",",
"false",
")",
";",
"}",
"catch",
"(... | Converts a Source into a Source that is protected against XXE attacks.
@see jenkins.util.xml.XMLUtils#safeTransform | [
"Converts",
"a",
"Source",
"into",
"a",
"Source",
"that",
"is",
"protected",
"against",
"XXE",
"attacks",
"."
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/configfiles/SecretHandler.java#L138-L154 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/impl/FileDescriptorLimit.java | FileDescriptorLimit.getUlimit | @edu.umd.cs.findbugs.annotations.SuppressWarnings({"DM_DEFAULT_ENCODING", "OS_OPEN_STREAM"})
private static void getUlimit(PrintWriter writer) throws IOException {
// TODO should first check whether /bin/bash even exists
InputStream is = new ProcessBuilder("bash", "-c", "ulimit -a").start().getInputStream();
try {
// this is reading from the process so platform encoding is correct
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = bufferedReader.readLine()) != null) {
writer.println(line);
}
} finally {
is.close();
}
} | java | @edu.umd.cs.findbugs.annotations.SuppressWarnings({"DM_DEFAULT_ENCODING", "OS_OPEN_STREAM"})
private static void getUlimit(PrintWriter writer) throws IOException {
// TODO should first check whether /bin/bash even exists
InputStream is = new ProcessBuilder("bash", "-c", "ulimit -a").start().getInputStream();
try {
// this is reading from the process so platform encoding is correct
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = bufferedReader.readLine()) != null) {
writer.println(line);
}
} finally {
is.close();
}
} | [
"@",
"edu",
".",
"umd",
".",
"cs",
".",
"findbugs",
".",
"annotations",
".",
"SuppressWarnings",
"(",
"{",
"\"DM_DEFAULT_ENCODING\"",
",",
"\"OS_OPEN_STREAM\"",
"}",
")",
"private",
"static",
"void",
"getUlimit",
"(",
"PrintWriter",
"writer",
")",
"throws",
"I... | This method executes the command "bash -c ulimit -a" on the machine. | [
"This",
"method",
"executes",
"the",
"command",
"bash",
"-",
"c",
"ulimit",
"-",
"a",
"on",
"the",
"machine",
"."
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/impl/FileDescriptorLimit.java#L188-L202 | train |
rosette-api/java | model/src/main/java/com/basistech/rosette/apimodel/Response.java | Response.addExtendedInformation | public void addExtendedInformation(String key, Object value) {
if (extendedInformation == null) {
extendedInformation = new HashMap<>();
}
extendedInformation.put(key, value);
} | java | public void addExtendedInformation(String key, Object value) {
if (extendedInformation == null) {
extendedInformation = new HashMap<>();
}
extendedInformation.put(key, value);
} | [
"public",
"void",
"addExtendedInformation",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"extendedInformation",
"==",
"null",
")",
"{",
"extendedInformation",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"}",
"extendedInformation",
".",
... | add more extended information to the response
@param key
@param value | [
"add",
"more",
"extended",
"information",
"to",
"the",
"response"
] | 35faf9fbb9c940eae47df004da7639a3b177b80b | https://github.com/rosette-api/java/blob/35faf9fbb9c940eae47df004da7639a3b177b80b/model/src/main/java/com/basistech/rosette/apimodel/Response.java#L40-L45 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/filter/FilteredOutputStream.java | FilteredOutputStream.flush | @Override
public synchronized void flush() throws IOException {
ensureOpen();
if (decodedBuf.position() > 0) {
decodedBuf.flip();
String contents = decodedBuf.toString();
String filtered = contentFilter.filter(contents);
out.write(filtered.getBytes(charset));
decodedBuf.clear();
}
out.flush();
} | java | @Override
public synchronized void flush() throws IOException {
ensureOpen();
if (decodedBuf.position() > 0) {
decodedBuf.flip();
String contents = decodedBuf.toString();
String filtered = contentFilter.filter(contents);
out.write(filtered.getBytes(charset));
decodedBuf.clear();
}
out.flush();
} | [
"@",
"Override",
"public",
"synchronized",
"void",
"flush",
"(",
")",
"throws",
"IOException",
"{",
"ensureOpen",
"(",
")",
";",
"if",
"(",
"decodedBuf",
".",
"position",
"(",
")",
">",
"0",
")",
"{",
"decodedBuf",
".",
"flip",
"(",
")",
";",
"String",... | Flushes the current buffered contents and filters them as is. | [
"Flushes",
"the",
"current",
"buffered",
"contents",
"and",
"filters",
"them",
"as",
"is",
"."
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/filter/FilteredOutputStream.java#L131-L142 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/filter/FilteredOutputStream.java | FilteredOutputStream.reset | public synchronized void reset() {
ensureOpen();
encodedBuf.clear();
if (decodedBuf.capacity() > FilteredConstants.DEFAULT_DECODER_CAPACITY) {
this.decodedBuf = CharBuffer.allocate(FilteredConstants.DEFAULT_DECODER_CAPACITY);
} else {
decodedBuf.clear();
}
decoder.reset();
} | java | public synchronized void reset() {
ensureOpen();
encodedBuf.clear();
if (decodedBuf.capacity() > FilteredConstants.DEFAULT_DECODER_CAPACITY) {
this.decodedBuf = CharBuffer.allocate(FilteredConstants.DEFAULT_DECODER_CAPACITY);
} else {
decodedBuf.clear();
}
decoder.reset();
} | [
"public",
"synchronized",
"void",
"reset",
"(",
")",
"{",
"ensureOpen",
"(",
")",
";",
"encodedBuf",
".",
"clear",
"(",
")",
";",
"if",
"(",
"decodedBuf",
".",
"capacity",
"(",
")",
">",
"FilteredConstants",
".",
"DEFAULT_DECODER_CAPACITY",
")",
"{",
"this... | Resets the state of this stream's decoders and buffers. | [
"Resets",
"the",
"state",
"of",
"this",
"stream",
"s",
"decoders",
"and",
"buffers",
"."
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/filter/FilteredOutputStream.java#L199-L208 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/impl/SlaveLogs.java | SlaveLogs.getActiveCacheKeys | private Set<String> getActiveCacheKeys(final List<Node> nodes) {
Set<String> cacheKeys = new HashSet<>(nodes.size());
for (Node node : nodes) {
// can't use node.getRootPath() cause won't work with disconnected agents.
String cacheKey = Util.getDigestOf(node.getNodeName() + ":" + ((hudson.model.Slave)node).getRemoteFS());
LOGGER.log(Level.FINEST, "cacheKey {0} is active", cacheKey);
cacheKeys.add(StringUtils.right(cacheKey, 8));
}
return cacheKeys;
} | java | private Set<String> getActiveCacheKeys(final List<Node> nodes) {
Set<String> cacheKeys = new HashSet<>(nodes.size());
for (Node node : nodes) {
// can't use node.getRootPath() cause won't work with disconnected agents.
String cacheKey = Util.getDigestOf(node.getNodeName() + ":" + ((hudson.model.Slave)node).getRemoteFS());
LOGGER.log(Level.FINEST, "cacheKey {0} is active", cacheKey);
cacheKeys.add(StringUtils.right(cacheKey, 8));
}
return cacheKeys;
} | [
"private",
"Set",
"<",
"String",
">",
"getActiveCacheKeys",
"(",
"final",
"List",
"<",
"Node",
">",
"nodes",
")",
"{",
"Set",
"<",
"String",
">",
"cacheKeys",
"=",
"new",
"HashSet",
"<>",
"(",
"nodes",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"... | Build a Set including the cacheKeys associated to every agent in the instance | [
"Build",
"a",
"Set",
"including",
"the",
"cacheKeys",
"associated",
"to",
"every",
"agent",
"in",
"the",
"instance"
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/impl/SlaveLogs.java#L234-L243 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/impl/AboutJenkins.java | AboutJenkins.mayBeDate | static boolean mayBeDate(String s) {
if (s == null || s.length() != "yyyy-MM-dd_HH-mm-ss".length()) {
return false;
}
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '-':
switch (i) {
case 4:
case 7:
case 13:
case 16:
break;
default:
return false;
}
break;
case '_':
if (i != 10) {
return false;
}
break;
case '0':
case '1':
switch (i) {
case 4: // -
case 7: // -
case 10: // _
case 13: // -
case 16: // -
return false;
default:
break;
}
break;
case '2':
switch (i) {
case 4: // -
case 5: // months 0-1
case 7: // -
case 10: // _
case 13: // -
case 16: // -
return false;
default:
break;
}
break;
case '3':
switch (i) {
case 0: // year will safely begin with digit 2 for next 800-odd years
case 4: // -
case 5: // months 0-1
case 7: // -
case 10: // _
case 11: // hours 0-2
case 13: // -
case 16: // -
return false;
default:
break;
}
break;
case '4':
case '5':
switch (i) {
case 0: // year will safely begin with digit 2 for next 800-odd years
case 4: // -
case 5: // months 0-1
case 7: // -
case 8: // days 0-3
case 10: // _
case 11: // hours 0-2
case 13: // -
case 16: // -
return false;
default:
break;
}
break;
case '6':
case '7':
case '8':
case '9':
switch (i) {
case 0: // year will safely begin with digit 2 for next 800-odd years
case 4: // -
case 5: // months 0-1
case 7: // -
case 8: // days 0-3
case 10: // _
case 11: // hours 0-2
case 13: // -
case 14: // minutes 0-5
case 16: // -
case 17: // seconds 0-5
return false;
default:
break;
}
break;
default:
return false;
}
}
return true;
} | java | static boolean mayBeDate(String s) {
if (s == null || s.length() != "yyyy-MM-dd_HH-mm-ss".length()) {
return false;
}
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '-':
switch (i) {
case 4:
case 7:
case 13:
case 16:
break;
default:
return false;
}
break;
case '_':
if (i != 10) {
return false;
}
break;
case '0':
case '1':
switch (i) {
case 4: // -
case 7: // -
case 10: // _
case 13: // -
case 16: // -
return false;
default:
break;
}
break;
case '2':
switch (i) {
case 4: // -
case 5: // months 0-1
case 7: // -
case 10: // _
case 13: // -
case 16: // -
return false;
default:
break;
}
break;
case '3':
switch (i) {
case 0: // year will safely begin with digit 2 for next 800-odd years
case 4: // -
case 5: // months 0-1
case 7: // -
case 10: // _
case 11: // hours 0-2
case 13: // -
case 16: // -
return false;
default:
break;
}
break;
case '4':
case '5':
switch (i) {
case 0: // year will safely begin with digit 2 for next 800-odd years
case 4: // -
case 5: // months 0-1
case 7: // -
case 8: // days 0-3
case 10: // _
case 11: // hours 0-2
case 13: // -
case 16: // -
return false;
default:
break;
}
break;
case '6':
case '7':
case '8':
case '9':
switch (i) {
case 0: // year will safely begin with digit 2 for next 800-odd years
case 4: // -
case 5: // months 0-1
case 7: // -
case 8: // days 0-3
case 10: // _
case 11: // hours 0-2
case 13: // -
case 14: // minutes 0-5
case 16: // -
case 17: // seconds 0-5
return false;
default:
break;
}
break;
default:
return false;
}
}
return true;
} | [
"static",
"boolean",
"mayBeDate",
"(",
"String",
"s",
")",
"{",
"if",
"(",
"s",
"==",
"null",
"||",
"s",
".",
"length",
"(",
")",
"!=",
"\"yyyy-MM-dd_HH-mm-ss\"",
".",
"length",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"int",
"i... | A pre-check to see if a string is a build timestamp formatted date.
@param s the string.
@return {@code true} if it is likely that the string will parse as a build timestamp formatted date. | [
"A",
"pre",
"-",
"check",
"to",
"see",
"if",
"a",
"string",
"is",
"a",
"build",
"timestamp",
"formatted",
"date",
"."
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/impl/AboutJenkins.java#L141-L247 | train |
jenkinsci/support-core-plugin | src/main/java/com/cloudbees/jenkins/support/impl/AboutJenkins.java | AboutJenkins.getPluginsSorted | private static Iterable<PluginWrapper> getPluginsSorted() {
PluginManager pluginManager = Jenkins.getInstance().getPluginManager();
return getPluginsSorted(pluginManager);
} | java | private static Iterable<PluginWrapper> getPluginsSorted() {
PluginManager pluginManager = Jenkins.getInstance().getPluginManager();
return getPluginsSorted(pluginManager);
} | [
"private",
"static",
"Iterable",
"<",
"PluginWrapper",
">",
"getPluginsSorted",
"(",
")",
"{",
"PluginManager",
"pluginManager",
"=",
"Jenkins",
".",
"getInstance",
"(",
")",
".",
"getPluginManager",
"(",
")",
";",
"return",
"getPluginsSorted",
"(",
"pluginManager... | Fixes JENKINS-47779 caused by JENKINS-47713
Not using SortedSet because of PluginWrapper doesn't implements equals and hashCode.
@return new copy of the PluginManager.getPlugins sorted | [
"Fixes",
"JENKINS",
"-",
"47779",
"caused",
"by",
"JENKINS",
"-",
"47713",
"Not",
"using",
"SortedSet",
"because",
"of",
"PluginWrapper",
"doesn",
"t",
"implements",
"equals",
"and",
"hashCode",
"."
] | bcbe1dfd5bf48ac89903645cd48ed897c1a04688 | https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/impl/AboutJenkins.java#L876-L879 | train |
rosette-api/java | examples/src/main/java/com/basistech/rosette/examples/ExampleBase.java | ExampleBase.showUsage | protected static void showUsage(Class<? extends ExampleBase> commandClass) {
System.err.println(USAGE_STR + commandClass.getName());
} | java | protected static void showUsage(Class<? extends ExampleBase> commandClass) {
System.err.println(USAGE_STR + commandClass.getName());
} | [
"protected",
"static",
"void",
"showUsage",
"(",
"Class",
"<",
"?",
"extends",
"ExampleBase",
">",
"commandClass",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"USAGE_STR",
"+",
"commandClass",
".",
"getName",
"(",
")",
")",
";",
"}"
] | Prints out how to run the program
@param commandClass the class to use in the usage message. | [
"Prints",
"out",
"how",
"to",
"run",
"the",
"program"
] | 35faf9fbb9c940eae47df004da7639a3b177b80b | https://github.com/rosette-api/java/blob/35faf9fbb9c940eae47df004da7639a3b177b80b/examples/src/main/java/com/basistech/rosette/examples/ExampleBase.java#L61-L63 | train |
rosette-api/java | examples/src/main/java/com/basistech/rosette/examples/ExampleBase.java | ExampleBase.responseToJson | protected static String responseToJson(Response response) throws JsonProcessingException {
ObjectMapper mapper = ApiModelMixinModule.setupObjectMapper(new ObjectMapper());
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsString(response);
} | java | protected static String responseToJson(Response response) throws JsonProcessingException {
ObjectMapper mapper = ApiModelMixinModule.setupObjectMapper(new ObjectMapper());
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.writeValueAsString(response);
} | [
"protected",
"static",
"String",
"responseToJson",
"(",
"Response",
"response",
")",
"throws",
"JsonProcessingException",
"{",
"ObjectMapper",
"mapper",
"=",
"ApiModelMixinModule",
".",
"setupObjectMapper",
"(",
"new",
"ObjectMapper",
"(",
")",
")",
";",
"mapper",
"... | Converts a response to JSON string
@param response {@link com.basistech.rosette.apimodel.Response Response} from RosetteAPI
@return the json string.
@throws JsonProcessingException if the Jackson library throws an error serializing. | [
"Converts",
"a",
"response",
"to",
"JSON",
"string"
] | 35faf9fbb9c940eae47df004da7639a3b177b80b | https://github.com/rosette-api/java/blob/35faf9fbb9c940eae47df004da7639a3b177b80b/examples/src/main/java/com/basistech/rosette/examples/ExampleBase.java#L72-L77 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.