id
int32
0
165k
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
136,400
otto-de/edison-hal
src/main/java/de/otto/edison/hal/Curies.java
Curies.register
public void register(final Link curi) { if (!curi.getRel().equals("curies")) { throw new IllegalArgumentException("Link must be a CURI"); } final boolean alreadyRegistered = curies .stream() .anyMatch(link -> link.getHref().equals(curi.getHref())); if (alreadyRegistered) { curies.removeIf(link -> link.getName().equals(curi.getName())); curies.replaceAll(link -> link.getName().equals(curi.getName()) ? curi : link); } curies.add(curi); }
java
public void register(final Link curi) { if (!curi.getRel().equals("curies")) { throw new IllegalArgumentException("Link must be a CURI"); } final boolean alreadyRegistered = curies .stream() .anyMatch(link -> link.getHref().equals(curi.getHref())); if (alreadyRegistered) { curies.removeIf(link -> link.getName().equals(curi.getName())); curies.replaceAll(link -> link.getName().equals(curi.getName()) ? curi : link); } curies.add(curi); }
[ "public", "void", "register", "(", "final", "Link", "curi", ")", "{", "if", "(", "!", "curi", ".", "getRel", "(", ")", ".", "equals", "(", "\"curies\"", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Link must be a CURI\"", ")", ";", ...
Registers a CURI link in the Curies instance. @param curi the CURI @throws IllegalArgumentException if the link-relation type of the link is not equal to 'curies'
[ "Registers", "a", "CURI", "link", "in", "the", "Curies", "instance", "." ]
1582d2b49d1f0d9103e03bf742f18afa9d166992
https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/Curies.java#L93-L106
136,401
otto-de/edison-hal
src/main/java/de/otto/edison/hal/Curies.java
Curies.mergeWith
public Curies mergeWith(final Curies other) { final Curies merged = copyOf(this); other.curies.forEach(merged::register); return merged; }
java
public Curies mergeWith(final Curies other) { final Curies merged = copyOf(this); other.curies.forEach(merged::register); return merged; }
[ "public", "Curies", "mergeWith", "(", "final", "Curies", "other", ")", "{", "final", "Curies", "merged", "=", "copyOf", "(", "this", ")", ";", "other", ".", "curies", ".", "forEach", "(", "merged", "::", "register", ")", ";", "return", "merged", ";", "...
Merges this Curies with another instance of Curies and returns the merged instance. @param other merged Curies @return a merged copy of this and other
[ "Merges", "this", "Curies", "with", "another", "instance", "of", "Curies", "and", "returns", "the", "merged", "instance", "." ]
1582d2b49d1f0d9103e03bf742f18afa9d166992
https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/Curies.java#L114-L118
136,402
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
Traverson.startWith
public Traverson startWith(final HalRepresentation resource) { this.startWith = null; this.lastResult = singletonList(requireNonNull(resource)); Optional<Link> self = resource.getLinks().getLinkBy("self"); if (self.isPresent()) { this.contextUrl = linkToUrl(self.get()); } else { resource .getLinks() .stream() .filter(link -> !link.getHref().matches("http.*//.*")) .findAny() .ifPresent(link -> {throw new IllegalArgumentException("Unable to construct Traverson from HalRepresentation w/o self link but containing relative links. Please try Traverson.startWith(URL, HalRepresentation)");}); } return this; }
java
public Traverson startWith(final HalRepresentation resource) { this.startWith = null; this.lastResult = singletonList(requireNonNull(resource)); Optional<Link> self = resource.getLinks().getLinkBy("self"); if (self.isPresent()) { this.contextUrl = linkToUrl(self.get()); } else { resource .getLinks() .stream() .filter(link -> !link.getHref().matches("http.*//.*")) .findAny() .ifPresent(link -> {throw new IllegalArgumentException("Unable to construct Traverson from HalRepresentation w/o self link but containing relative links. Please try Traverson.startWith(URL, HalRepresentation)");}); } return this; }
[ "public", "Traverson", "startWith", "(", "final", "HalRepresentation", "resource", ")", "{", "this", ".", "startWith", "=", "null", ";", "this", ".", "lastResult", "=", "singletonList", "(", "requireNonNull", "(", "resource", ")", ")", ";", "Optional", "<", ...
Start traversal at the given HAL resource. <p> It is expected, that the HalRepresentation has an absolute 'self' link, or that all links to other resources are absolute links. If this is not assured, {@link #startWith(URL, HalRepresentation)} must be used, so relative links can be resolved. </p> @param resource the initial HAL resource. @return Traverson initialized with the specified {@link HalRepresentation}.
[ "Start", "traversal", "at", "the", "given", "HAL", "resource", "." ]
1582d2b49d1f0d9103e03bf742f18afa9d166992
https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/traverson/Traverson.java#L301-L316
136,403
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
Traverson.resolve
private static Link resolve(final URL contextUrl, final Link link) { if (link != null && link.isTemplated()) { final String msg = "Link must not be templated"; LOG.error(msg); throw new IllegalStateException(msg); } if (link == null) { return self(contextUrl.toString()); } else { return copyOf(link).withHref(resolveHref(contextUrl, link.getHref()).toString()).build(); } }
java
private static Link resolve(final URL contextUrl, final Link link) { if (link != null && link.isTemplated()) { final String msg = "Link must not be templated"; LOG.error(msg); throw new IllegalStateException(msg); } if (link == null) { return self(contextUrl.toString()); } else { return copyOf(link).withHref(resolveHref(contextUrl, link.getHref()).toString()).build(); } }
[ "private", "static", "Link", "resolve", "(", "final", "URL", "contextUrl", ",", "final", "Link", "link", ")", "{", "if", "(", "link", "!=", "null", "&&", "link", ".", "isTemplated", "(", ")", ")", "{", "final", "String", "msg", "=", "\"Link must not be t...
Resolved a link using the URL of the current resource and returns it as an absolute Link. @param contextUrl the URL of the current context @param link optional link to follow @return absolute Link @throws IllegalArgumentException if resolving the link is failing
[ "Resolved", "a", "link", "using", "the", "URL", "of", "the", "current", "resource", "and", "returns", "it", "as", "an", "absolute", "Link", "." ]
1582d2b49d1f0d9103e03bf742f18afa9d166992
https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/traverson/Traverson.java#L1416-L1428
136,404
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
Traverson.checkState
private void checkState() { if (startWith == null && lastResult == null) { final String msg = "Please call startWith(uri) first."; LOG.error(msg); throw new IllegalStateException(msg); } }
java
private void checkState() { if (startWith == null && lastResult == null) { final String msg = "Please call startWith(uri) first."; LOG.error(msg); throw new IllegalStateException(msg); } }
[ "private", "void", "checkState", "(", ")", "{", "if", "(", "startWith", "==", "null", "&&", "lastResult", "==", "null", ")", "{", "final", "String", "msg", "=", "\"Please call startWith(uri) first.\"", ";", "LOG", ".", "error", "(", "msg", ")", ";", "throw...
Checks the current state of the Traverson. @throws IllegalStateException if some error occured during traversion
[ "Checks", "the", "current", "state", "of", "the", "Traverson", "." ]
1582d2b49d1f0d9103e03bf742f18afa9d166992
https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/traverson/Traverson.java#L1479-L1485
136,405
smoketurner/dropwizard-zipkin
zipkin-client/src/main/java/com/smoketurner/dropwizard/zipkin/client/ZipkinClientBuilder.java
ZipkinClientBuilder.build
public Client build(final ZipkinClientConfiguration configuration) { final Client client = new JerseyClientBuilder(environment) .using(configuration) .build(configuration.getServiceName()); return build(client); }
java
public Client build(final ZipkinClientConfiguration configuration) { final Client client = new JerseyClientBuilder(environment) .using(configuration) .build(configuration.getServiceName()); return build(client); }
[ "public", "Client", "build", "(", "final", "ZipkinClientConfiguration", "configuration", ")", "{", "final", "Client", "client", "=", "new", "JerseyClientBuilder", "(", "environment", ")", ".", "using", "(", "configuration", ")", ".", "build", "(", "configuration",...
Build a new Jersey Client that is instrumented for Zipkin @param configuration Configuration to use for the client @return new Jersey Client
[ "Build", "a", "new", "Jersey", "Client", "that", "is", "instrumented", "for", "Zipkin" ]
de67f2a7bdc5eabafe4110a07f29d03d75f2c412
https://github.com/smoketurner/dropwizard-zipkin/blob/de67f2a7bdc5eabafe4110a07f29d03d75f2c412/zipkin-client/src/main/java/com/smoketurner/dropwizard/zipkin/client/ZipkinClientBuilder.java#L46-L52
136,406
smoketurner/dropwizard-zipkin
zipkin-client/src/main/java/com/smoketurner/dropwizard/zipkin/client/ZipkinClientBuilder.java
ZipkinClientBuilder.build
public Client build(final Client client) { client.register(TracingClientFilter.create(tracing)); return client; }
java
public Client build(final Client client) { client.register(TracingClientFilter.create(tracing)); return client; }
[ "public", "Client", "build", "(", "final", "Client", "client", ")", "{", "client", ".", "register", "(", "TracingClientFilter", ".", "create", "(", "tracing", ")", ")", ";", "return", "client", ";", "}" ]
Instrument an existing Jersey client @param client Jersey client @return an instrumented Jersey client
[ "Instrument", "an", "existing", "Jersey", "client" ]
de67f2a7bdc5eabafe4110a07f29d03d75f2c412
https://github.com/smoketurner/dropwizard-zipkin/blob/de67f2a7bdc5eabafe4110a07f29d03d75f2c412/zipkin-client/src/main/java/com/smoketurner/dropwizard/zipkin/client/ZipkinClientBuilder.java#L60-L63
136,407
plivo/plivo-java
src/main/java/com/plivo/api/models/base/Creator.java
Creator.create
public CreateResponse create() throws IOException, PlivoRestException { validate(); Response<CreateResponse> response = obtainCall().execute(); handleResponse(response); return response.body(); }
java
public CreateResponse create() throws IOException, PlivoRestException { validate(); Response<CreateResponse> response = obtainCall().execute(); handleResponse(response); return response.body(); }
[ "public", "CreateResponse", "create", "(", ")", "throws", "IOException", ",", "PlivoRestException", "{", "validate", "(", ")", ";", "Response", "<", "CreateResponse", ">", "response", "=", "obtainCall", "(", ")", ".", "execute", "(", ")", ";", "handleResponse"...
Actually create an instance of the resource.
[ "Actually", "create", "an", "instance", "of", "the", "resource", "." ]
ff96a3da0ff35e8b52c3135acc53c1387608f9f6
https://github.com/plivo/plivo-java/blob/ff96a3da0ff35e8b52c3135acc53c1387608f9f6/src/main/java/com/plivo/api/models/base/Creator.java#L22-L29
136,408
plivo/plivo-java
src/main/java/com/plivo/examples/Accounts.java
Accounts.getAccountInfo
private static void getAccountInfo() { try { Account response = Account.getter() .get(); System.out.println(response); } catch (PlivoRestException | IOException e) { e.printStackTrace(); } }
java
private static void getAccountInfo() { try { Account response = Account.getter() .get(); System.out.println(response); } catch (PlivoRestException | IOException e) { e.printStackTrace(); } }
[ "private", "static", "void", "getAccountInfo", "(", ")", "{", "try", "{", "Account", "response", "=", "Account", ".", "getter", "(", ")", ".", "get", "(", ")", ";", "System", ".", "out", ".", "println", "(", "response", ")", ";", "}", "catch", "(", ...
trying to get account info without setting the client
[ "trying", "to", "get", "account", "info", "without", "setting", "the", "client" ]
ff96a3da0ff35e8b52c3135acc53c1387608f9f6
https://github.com/plivo/plivo-java/blob/ff96a3da0ff35e8b52c3135acc53c1387608f9f6/src/main/java/com/plivo/examples/Accounts.java#L30-L38
136,409
plivo/plivo-java
src/main/java/com/plivo/examples/Accounts.java
Accounts.getAccountInfoBySettingClient
private static void getAccountInfoBySettingClient() { try { Account response = Account.getter() .client(client) .get(); System.out.println(response); } catch (PlivoRestException | IOException e) { e.printStackTrace(); } }
java
private static void getAccountInfoBySettingClient() { try { Account response = Account.getter() .client(client) .get(); System.out.println(response); } catch (PlivoRestException | IOException e) { e.printStackTrace(); } }
[ "private", "static", "void", "getAccountInfoBySettingClient", "(", ")", "{", "try", "{", "Account", "response", "=", "Account", ".", "getter", "(", ")", ".", "client", "(", "client", ")", ".", "get", "(", ")", ";", "System", ".", "out", ".", "println", ...
trying to get account info by setting the client
[ "trying", "to", "get", "account", "info", "by", "setting", "the", "client" ]
ff96a3da0ff35e8b52c3135acc53c1387608f9f6
https://github.com/plivo/plivo-java/blob/ff96a3da0ff35e8b52c3135acc53c1387608f9f6/src/main/java/com/plivo/examples/Accounts.java#L41-L50
136,410
plivo/plivo-java
src/main/java/com/plivo/examples/Accounts.java
Accounts.modifyAccountBySettingClient
private static void modifyAccountBySettingClient() { try { AccountUpdateResponse response = Account.updater() .city("Test city") .client(client) .update(); System.out.println(response); } catch (PlivoRestException | IOException e) { e.printStackTrace(); } }
java
private static void modifyAccountBySettingClient() { try { AccountUpdateResponse response = Account.updater() .city("Test city") .client(client) .update(); System.out.println(response); } catch (PlivoRestException | IOException e) { e.printStackTrace(); } }
[ "private", "static", "void", "modifyAccountBySettingClient", "(", ")", "{", "try", "{", "AccountUpdateResponse", "response", "=", "Account", ".", "updater", "(", ")", ".", "city", "(", "\"Test city\"", ")", ".", "client", "(", "client", ")", ".", "update", "...
update account with different client settings
[ "update", "account", "with", "different", "client", "settings" ]
ff96a3da0ff35e8b52c3135acc53c1387608f9f6
https://github.com/plivo/plivo-java/blob/ff96a3da0ff35e8b52c3135acc53c1387608f9f6/src/main/java/com/plivo/examples/Accounts.java#L65-L75
136,411
plivo/plivo-java
src/main/java/com/plivo/examples/Accounts.java
Accounts.createSubAccountBySettingClient
private static void createSubAccountBySettingClient() { try { SubaccountCreateResponse subaccount = Subaccount.creator("Test 2") .enabled(true) .client(client) .create(); System.out.println(subaccount); } catch (PlivoRestException | IOException e) { e.printStackTrace(); } }
java
private static void createSubAccountBySettingClient() { try { SubaccountCreateResponse subaccount = Subaccount.creator("Test 2") .enabled(true) .client(client) .create(); System.out.println(subaccount); } catch (PlivoRestException | IOException e) { e.printStackTrace(); } }
[ "private", "static", "void", "createSubAccountBySettingClient", "(", ")", "{", "try", "{", "SubaccountCreateResponse", "subaccount", "=", "Subaccount", ".", "creator", "(", "\"Test 2\"", ")", ".", "enabled", "(", "true", ")", ".", "client", "(", "client", ")", ...
create subaccount with different client settings
[ "create", "subaccount", "with", "different", "client", "settings" ]
ff96a3da0ff35e8b52c3135acc53c1387608f9f6
https://github.com/plivo/plivo-java/blob/ff96a3da0ff35e8b52c3135acc53c1387608f9f6/src/main/java/com/plivo/examples/Accounts.java#L90-L100
136,412
plivo/plivo-java
src/main/java/com/plivo/api/models/base/Deleter.java
Deleter.delete
public void delete() throws IOException, PlivoRestException { validate(); Response<ResponseBody> response = obtainCall().execute(); handleResponse(response); }
java
public void delete() throws IOException, PlivoRestException { validate(); Response<ResponseBody> response = obtainCall().execute(); handleResponse(response); }
[ "public", "void", "delete", "(", ")", "throws", "IOException", ",", "PlivoRestException", "{", "validate", "(", ")", ";", "Response", "<", "ResponseBody", ">", "response", "=", "obtainCall", "(", ")", ".", "execute", "(", ")", ";", "handleResponse", "(", "...
Actually delete the resource.
[ "Actually", "delete", "the", "resource", "." ]
ff96a3da0ff35e8b52c3135acc53c1387608f9f6
https://github.com/plivo/plivo-java/blob/ff96a3da0ff35e8b52c3135acc53c1387608f9f6/src/main/java/com/plivo/api/models/base/Deleter.java#L30-L35
136,413
plivo/plivo-java
src/main/java/com/plivo/api/models/base/Updater.java
Updater.update
public T update() throws IOException, PlivoRestException { validate(); Response<T> response = obtainCall().execute(); handleResponse(response); return response.body(); }
java
public T update() throws IOException, PlivoRestException { validate(); Response<T> response = obtainCall().execute(); handleResponse(response); return response.body(); }
[ "public", "T", "update", "(", ")", "throws", "IOException", ",", "PlivoRestException", "{", "validate", "(", ")", ";", "Response", "<", "T", ">", "response", "=", "obtainCall", "(", ")", ".", "execute", "(", ")", ";", "handleResponse", "(", "response", "...
Actually update the resource.
[ "Actually", "update", "the", "resource", "." ]
ff96a3da0ff35e8b52c3135acc53c1387608f9f6
https://github.com/plivo/plivo-java/blob/ff96a3da0ff35e8b52c3135acc53c1387608f9f6/src/main/java/com/plivo/api/models/base/Updater.java#L27-L34
136,414
plivo/plivo-java
src/main/java/com/plivo/api/models/base/Lister.java
Lister.list
public ListResponse<T> list() throws IOException, PlivoRestException { validate(); Response<ListResponse<T>> response = obtainCall().execute(); handleResponse(response); return response.body(); }
java
public ListResponse<T> list() throws IOException, PlivoRestException { validate(); Response<ListResponse<T>> response = obtainCall().execute(); handleResponse(response); return response.body(); }
[ "public", "ListResponse", "<", "T", ">", "list", "(", ")", "throws", "IOException", ",", "PlivoRestException", "{", "validate", "(", ")", ";", "Response", "<", "ListResponse", "<", "T", ">", ">", "response", "=", "obtainCall", "(", ")", ".", "execute", "...
Actually list instances of the resource.
[ "Actually", "list", "instances", "of", "the", "resource", "." ]
ff96a3da0ff35e8b52c3135acc53c1387608f9f6
https://github.com/plivo/plivo-java/blob/ff96a3da0ff35e8b52c3135acc53c1387608f9f6/src/main/java/com/plivo/api/models/base/Lister.java#L72-L79
136,415
dropwizard/dropwizard-elasticsearch
src/main/java/io/dropwizard/elasticsearch/health/EsClusterHealthCheck.java
EsClusterHealthCheck.check
@Override protected Result check() throws Exception { final ClusterHealthStatus status = client.admin().cluster().prepareHealth().get().getStatus(); if (status == ClusterHealthStatus.RED || (failOnYellow && status == ClusterHealthStatus.YELLOW)) { return Result.unhealthy("Last status: %s", status.name()); } else { return Result.healthy("Last status: %s", status.name()); } }
java
@Override protected Result check() throws Exception { final ClusterHealthStatus status = client.admin().cluster().prepareHealth().get().getStatus(); if (status == ClusterHealthStatus.RED || (failOnYellow && status == ClusterHealthStatus.YELLOW)) { return Result.unhealthy("Last status: %s", status.name()); } else { return Result.healthy("Last status: %s", status.name()); } }
[ "@", "Override", "protected", "Result", "check", "(", ")", "throws", "Exception", "{", "final", "ClusterHealthStatus", "status", "=", "client", ".", "admin", "(", ")", ".", "cluster", "(", ")", ".", "prepareHealth", "(", ")", ".", "get", "(", ")", ".", ...
Perform a check of the Elasticsearch cluster health. @return if the Elasticsearch cluster is healthy, a healthy {@link com.codahale.metrics.health.HealthCheck.Result}; otherwise, an unhealthy {@link com.codahale.metrics.health.HealthCheck.Result} with a descriptive error message or exception @throws Exception if there is an unhandled error during the health check; this will result in a failed health check
[ "Perform", "a", "check", "of", "the", "Elasticsearch", "cluster", "health", "." ]
9f08953ab53ebda0b81306dadabb7b71b7f87970
https://github.com/dropwizard/dropwizard-elasticsearch/blob/9f08953ab53ebda0b81306dadabb7b71b7f87970/src/main/java/io/dropwizard/elasticsearch/health/EsClusterHealthCheck.java#L48-L57
136,416
xqbase/util
util-jdk17/src/main/java/com/xqbase/util/Log.java
Log.i
public static void i(String s, Throwable t) { log(Level.INFO, s, t); }
java
public static void i(String s, Throwable t) { log(Level.INFO, s, t); }
[ "public", "static", "void", "i", "(", "String", "s", ",", "Throwable", "t", ")", "{", "log", "(", "Level", ".", "INFO", ",", "s", ",", "t", ")", ";", "}" ]
Log an INFO message and the exception
[ "Log", "an", "INFO", "message", "and", "the", "exception" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util-jdk17/src/main/java/com/xqbase/util/Log.java#L164-L166
136,417
xqbase/util
util-jdk17/src/main/java/com/xqbase/util/Log.java
Log.w
public static void w(String s, Throwable t) { log(Level.WARNING, s, t); }
java
public static void w(String s, Throwable t) { log(Level.WARNING, s, t); }
[ "public", "static", "void", "w", "(", "String", "s", ",", "Throwable", "t", ")", "{", "log", "(", "Level", ".", "WARNING", ",", "s", ",", "t", ")", ";", "}" ]
Log a WARNING message and the exception
[ "Log", "a", "WARNING", "message", "and", "the", "exception" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util-jdk17/src/main/java/com/xqbase/util/Log.java#L179-L181
136,418
xqbase/util
util/src/main/java/com/xqbase/util/Bytes.java
Bytes.fromHex
public static byte[] fromHex(String hex) { char[] c = hex.toCharArray(); byte[] b = new byte[c.length / 2]; for (int i = 0; i < b.length; i ++) { b[i] = (byte) (HEX_DECODE_CHAR[c[i * 2] & 0xFF] * 16 + HEX_DECODE_CHAR[c[i * 2 + 1] & 0xFF]); } return b; }
java
public static byte[] fromHex(String hex) { char[] c = hex.toCharArray(); byte[] b = new byte[c.length / 2]; for (int i = 0; i < b.length; i ++) { b[i] = (byte) (HEX_DECODE_CHAR[c[i * 2] & 0xFF] * 16 + HEX_DECODE_CHAR[c[i * 2 + 1] & 0xFF]); } return b; }
[ "public", "static", "byte", "[", "]", "fromHex", "(", "String", "hex", ")", "{", "char", "[", "]", "c", "=", "hex", ".", "toCharArray", "(", ")", ";", "byte", "[", "]", "b", "=", "new", "byte", "[", "c", ".", "length", "/", "2", "]", ";", "fo...
Decode from hexadecimal
[ "Decode", "from", "hexadecimal" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/Bytes.java#L50-L58
136,419
xqbase/util
util/src/main/java/com/xqbase/util/Bytes.java
Bytes.toHexUpper
public static String toHexUpper(byte[] b, int off, int len) { return toHex(b, off, len, HEX_UPPER_CHAR); }
java
public static String toHexUpper(byte[] b, int off, int len) { return toHex(b, off, len, HEX_UPPER_CHAR); }
[ "public", "static", "String", "toHexUpper", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "{", "return", "toHex", "(", "b", ",", "off", ",", "len", ",", "HEX_UPPER_CHAR", ")", ";", "}" ]
Encode to uppercase hexadecimal
[ "Encode", "to", "uppercase", "hexadecimal" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/Bytes.java#L76-L78
136,420
xqbase/util
util/src/main/java/com/xqbase/util/Bytes.java
Bytes.toHexLower
public static String toHexLower(byte[] b, int off, int len) { return toHex(b, off, len, HEX_LOWER_CHAR); }
java
public static String toHexLower(byte[] b, int off, int len) { return toHex(b, off, len, HEX_LOWER_CHAR); }
[ "public", "static", "String", "toHexLower", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "{", "return", "toHex", "(", "b", ",", "off", ",", "len", ",", "HEX_LOWER_CHAR", ")", ";", "}" ]
Encode to lowercase hexadecimal
[ "Encode", "to", "lowercase", "hexadecimal" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/Bytes.java#L86-L88
136,421
xqbase/util
util/src/main/java/com/xqbase/util/Bytes.java
Bytes.add
public static byte[] add(byte[] b1, int off1, int len1, byte[] b2, int off2, int len2) { byte[] b = new byte[len1 + len2]; System.arraycopy(b1, off1, b, 0, len1); System.arraycopy(b2, off2, b, len1, len2); return b; }
java
public static byte[] add(byte[] b1, int off1, int len1, byte[] b2, int off2, int len2) { byte[] b = new byte[len1 + len2]; System.arraycopy(b1, off1, b, 0, len1); System.arraycopy(b2, off2, b, len1, len2); return b; }
[ "public", "static", "byte", "[", "]", "add", "(", "byte", "[", "]", "b1", ",", "int", "off1", ",", "int", "len1", ",", "byte", "[", "]", "b2", ",", "int", "off2", ",", "int", "len2", ")", "{", "byte", "[", "]", "b", "=", "new", "byte", "[", ...
Concatenate 2 byte arrays
[ "Concatenate", "2", "byte", "arrays" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/Bytes.java#L252-L257
136,422
xqbase/util
util/src/main/java/com/xqbase/util/Bytes.java
Bytes.sub
public static byte[] sub(byte[] b, int off, int len) { byte[] result = new byte[len]; System.arraycopy(b, off, result, 0, len); return result; }
java
public static byte[] sub(byte[] b, int off, int len) { byte[] result = new byte[len]; System.arraycopy(b, off, result, 0, len); return result; }
[ "public", "static", "byte", "[", "]", "sub", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "{", "byte", "[", "]", "result", "=", "new", "byte", "[", "len", "]", ";", "System", ".", "arraycopy", "(", "b", ",", "off", "...
Truncate and keep middle part of a byte array
[ "Truncate", "and", "keep", "middle", "part", "of", "a", "byte", "array" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/Bytes.java#L296-L300
136,423
xqbase/util
util-jdk17/src/main/java/com/xqbase/util/Conf.java
Conf.chdir
public static synchronized void chdir(String path) { if (path != null) { rootDir = new File(getAbsolutePath(path)).getAbsolutePath(); } }
java
public static synchronized void chdir(String path) { if (path != null) { rootDir = new File(getAbsolutePath(path)).getAbsolutePath(); } }
[ "public", "static", "synchronized", "void", "chdir", "(", "String", "path", ")", "{", "if", "(", "path", "!=", "null", ")", "{", "rootDir", "=", "new", "File", "(", "getAbsolutePath", "(", "path", ")", ")", ".", "getAbsolutePath", "(", ")", ";", "}", ...
Change the current folder
[ "Change", "the", "current", "folder" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util-jdk17/src/main/java/com/xqbase/util/Conf.java#L87-L91
136,424
xqbase/util
util-jdk17/src/main/java/com/xqbase/util/Conf.java
Conf.closeLogger
public static void closeLogger(Logger logger) { for (Handler handler : logger.getHandlers()) { logger.removeHandler(handler); handler.close(); } }
java
public static void closeLogger(Logger logger) { for (Handler handler : logger.getHandlers()) { logger.removeHandler(handler); handler.close(); } }
[ "public", "static", "void", "closeLogger", "(", "Logger", "logger", ")", "{", "for", "(", "Handler", "handler", ":", "logger", ".", "getHandlers", "(", ")", ")", "{", "logger", ".", "removeHandler", "(", "handler", ")", ";", "handler", ".", "close", "(",...
Close a logger
[ "Close", "a", "logger" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util-jdk17/src/main/java/com/xqbase/util/Conf.java#L164-L169
136,425
xqbase/util
util-jdk17/src/main/java/com/xqbase/util/Conf.java
Conf.getClasses
public static List<String> getClasses(String... packageNames) { List<String> classes = new ArrayList<>(); for (String packageName : packageNames) { String packagePath = packageName.replace('.', '/'); URL url = Conf.class.getResource("/" + packagePath); if (url == null) { return classes; } if (url.getProtocol().equals("jar")) { String path = url.getPath(); int i = path.lastIndexOf('!'); if (i >= 0) { path = path.substring(0, i); } try (JarFile jar = new JarFile(new File(new URL(path).toURI()))) { Enumeration<JarEntry> e = jar.entries(); while (e.hasMoreElements()) { path = e.nextElement().getName(); if (path.startsWith(packagePath) && path.endsWith(".class")) { classes.add(path.substring(0, path.length() - 6).replace('/', '.')); } } } catch (IOException | URISyntaxException e) { throw new RuntimeException(e); } } else { try { String root = new File(url.toURI()).getPath(); root = root.substring(0, root.length() - packagePath.length()); search(classes, root, packagePath); } catch (URISyntaxException e) { throw new RuntimeException(e); } } } return classes; }
java
public static List<String> getClasses(String... packageNames) { List<String> classes = new ArrayList<>(); for (String packageName : packageNames) { String packagePath = packageName.replace('.', '/'); URL url = Conf.class.getResource("/" + packagePath); if (url == null) { return classes; } if (url.getProtocol().equals("jar")) { String path = url.getPath(); int i = path.lastIndexOf('!'); if (i >= 0) { path = path.substring(0, i); } try (JarFile jar = new JarFile(new File(new URL(path).toURI()))) { Enumeration<JarEntry> e = jar.entries(); while (e.hasMoreElements()) { path = e.nextElement().getName(); if (path.startsWith(packagePath) && path.endsWith(".class")) { classes.add(path.substring(0, path.length() - 6).replace('/', '.')); } } } catch (IOException | URISyntaxException e) { throw new RuntimeException(e); } } else { try { String root = new File(url.toURI()).getPath(); root = root.substring(0, root.length() - packagePath.length()); search(classes, root, packagePath); } catch (URISyntaxException e) { throw new RuntimeException(e); } } } return classes; }
[ "public", "static", "List", "<", "String", ">", "getClasses", "(", "String", "...", "packageNames", ")", "{", "List", "<", "String", ">", "classes", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "String", "packageName", ":", "packageNames", "...
Traverse all classes under given packages
[ "Traverse", "all", "classes", "under", "given", "packages" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util-jdk17/src/main/java/com/xqbase/util/Conf.java#L246-L282
136,426
xqbase/util
util/src/main/java/com/xqbase/util/Pool.java
Pool.borrow
public Entry borrow() throws E { long now = System.currentTimeMillis(); if (timeout > 0) { long accessed_ = accessed.get(); if (now > accessed_ + Time.SECOND && accessed.compareAndSet(accessed_, now)) { Entry entry; while ((entry = deque.pollLast()) != null) { // inactiveCount.decrementAndGet(); if (now < entry.borrowed + timeout) { deque.offerLast(entry); // inactiveCount.incrementAndGet(); break; } inactiveCount.decrementAndGet(); try { finalizer.accept(entry.object); } catch (Exception e) { // Ignored } } } } Entry entry = deque.pollFirst(); if (entry != null) { inactiveCount.decrementAndGet(); entry.borrowed = now; entry.borrows ++; entry.valid = false; activeCount.incrementAndGet(); return entry; } entry = new Entry(); entry.object = initializer.get(); entry.created = entry.borrowed = now; entry.borrows = 0; entry.valid = false; activeCount.incrementAndGet(); return entry; }
java
public Entry borrow() throws E { long now = System.currentTimeMillis(); if (timeout > 0) { long accessed_ = accessed.get(); if (now > accessed_ + Time.SECOND && accessed.compareAndSet(accessed_, now)) { Entry entry; while ((entry = deque.pollLast()) != null) { // inactiveCount.decrementAndGet(); if (now < entry.borrowed + timeout) { deque.offerLast(entry); // inactiveCount.incrementAndGet(); break; } inactiveCount.decrementAndGet(); try { finalizer.accept(entry.object); } catch (Exception e) { // Ignored } } } } Entry entry = deque.pollFirst(); if (entry != null) { inactiveCount.decrementAndGet(); entry.borrowed = now; entry.borrows ++; entry.valid = false; activeCount.incrementAndGet(); return entry; } entry = new Entry(); entry.object = initializer.get(); entry.created = entry.borrowed = now; entry.borrows = 0; entry.valid = false; activeCount.incrementAndGet(); return entry; }
[ "public", "Entry", "borrow", "(", ")", "throws", "E", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "if", "(", "timeout", ">", "0", ")", "{", "long", "accessed_", "=", "accessed", ".", "get", "(", ")", ";", "if", "(", ...
Borrow an object from the pool, or create a new object if no valid objects in the pool @return {@link Entry} to the pooled object @throws E exception thrown by initializer
[ "Borrow", "an", "object", "from", "the", "pool", "or", "create", "a", "new", "object", "if", "no", "valid", "objects", "in", "the", "pool" ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/Pool.java#L127-L167
136,427
xqbase/util
util/src/main/java/com/xqbase/util/Service.java
Service.await
public void await() { if (interrupted.get()) { return; } try { mainLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
java
public void await() { if (interrupted.get()) { return; } try { mainLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
[ "public", "void", "await", "(", ")", "{", "if", "(", "interrupted", ".", "get", "(", ")", ")", "{", "return", ";", "}", "try", "{", "mainLatch", ".", "await", "(", ")", ";", "}", "catch", "(", "InterruptedException", "e", ")", "{", "Thread", ".", ...
Wait until a proper shutdown command is received, then return.
[ "Wait", "until", "a", "proper", "shutdown", "command", "is", "received", "then", "return", "." ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/Service.java#L135-L144
136,428
xqbase/util
util/src/main/java/com/xqbase/util/Lazy.java
Lazy.get
public T get() throws E { // use a temporary variable to reduce the number of reads of the volatile field // see commons-lang3 T result = object; if (object == null) { synchronized (this) { result = object; if (object == null) { object = result = initializer.get(); } } } return result; }
java
public T get() throws E { // use a temporary variable to reduce the number of reads of the volatile field // see commons-lang3 T result = object; if (object == null) { synchronized (this) { result = object; if (object == null) { object = result = initializer.get(); } } } return result; }
[ "public", "T", "get", "(", ")", "throws", "E", "{", "// use a temporary variable to reduce the number of reads of the volatile field\r", "// see commons-lang3\r", "T", "result", "=", "object", ";", "if", "(", "object", "==", "null", ")", "{", "synchronized", "(", "thi...
Create or get the instance. @return the instance @throws E exception thrown by initializer
[ "Create", "or", "get", "the", "instance", "." ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/Lazy.java#L35-L48
136,429
xqbase/util
util/src/main/java/com/xqbase/util/Lazy.java
Lazy.close
@Override public void close() { synchronized (this) { if (object != null) { T object_ = object; object = null; try { finalizer.accept(object_); } catch (Exception e) { // Ignored } } } }
java
@Override public void close() { synchronized (this) { if (object != null) { T object_ = object; object = null; try { finalizer.accept(object_); } catch (Exception e) { // Ignored } } } }
[ "@", "Override", "public", "void", "close", "(", ")", "{", "synchronized", "(", "this", ")", "{", "if", "(", "object", "!=", "null", ")", "{", "T", "object_", "=", "object", ";", "object", "=", "null", ";", "try", "{", "finalizer", ".", "accept", "...
Close the lazy factory and destroy the instance if created.
[ "Close", "the", "lazy", "factory", "and", "destroy", "the", "instance", "if", "created", "." ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/Lazy.java#L53-L66
136,430
xqbase/util
util/src/main/java/com/xqbase/util/ByteArrayQueue.java
ByteArrayQueue.add
public ByteArrayQueue add(byte[] b, int off, int len) { int newLength = addLength(len); System.arraycopy(b, off, array, offset + length, len); length = newLength; return this; }
java
public ByteArrayQueue add(byte[] b, int off, int len) { int newLength = addLength(len); System.arraycopy(b, off, array, offset + length, len); length = newLength; return this; }
[ "public", "ByteArrayQueue", "add", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "{", "int", "newLength", "=", "addLength", "(", "len", ")", ";", "System", ".", "arraycopy", "(", "b", ",", "off", ",", "array", ",", "offset"...
Adds a sequence of bytes into the tail of the queue.
[ "Adds", "a", "sequence", "of", "bytes", "into", "the", "tail", "of", "the", "queue", "." ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/ByteArrayQueue.java#L112-L117
136,431
xqbase/util
util/src/main/java/com/xqbase/util/ByteArrayQueue.java
ByteArrayQueue.add
public ByteArrayQueue add(int b) { int newLength = addLength(1); array[offset + length] = (byte) b; length = newLength; return this; }
java
public ByteArrayQueue add(int b) { int newLength = addLength(1); array[offset + length] = (byte) b; length = newLength; return this; }
[ "public", "ByteArrayQueue", "add", "(", "int", "b", ")", "{", "int", "newLength", "=", "addLength", "(", "1", ")", ";", "array", "[", "offset", "+", "length", "]", "=", "(", "byte", ")", "b", ";", "length", "=", "newLength", ";", "return", "this", ...
Adds one byte into the tail of the queue.
[ "Adds", "one", "byte", "into", "the", "tail", "of", "the", "queue", "." ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/ByteArrayQueue.java#L120-L125
136,432
xqbase/util
util/src/main/java/com/xqbase/util/ByteArrayQueue.java
ByteArrayQueue.remove
public ByteArrayQueue remove(byte[] b, int off, int len) { System.arraycopy(array, offset, b, off, len); return remove(len); }
java
public ByteArrayQueue remove(byte[] b, int off, int len) { System.arraycopy(array, offset, b, off, len); return remove(len); }
[ "public", "ByteArrayQueue", "remove", "(", "byte", "[", "]", "b", ",", "int", "off", ",", "int", "len", ")", "{", "System", ".", "arraycopy", "(", "array", ",", "offset", ",", "b", ",", "off", ",", "len", ")", ";", "return", "remove", "(", "len", ...
Retrieves a sequence of bytes from the head of the queue.
[ "Retrieves", "a", "sequence", "of", "bytes", "from", "the", "head", "of", "the", "queue", "." ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/ByteArrayQueue.java#L168-L171
136,433
xqbase/util
util/src/main/java/com/xqbase/util/ByteArrayQueue.java
ByteArrayQueue.remove
public ByteArrayQueue remove(int len) { offset += len; length -= len; // Release buffer if empty if (length == 0 && array.length > 1024) { array = new byte[32]; offset = 0; shared = false; } return this; }
java
public ByteArrayQueue remove(int len) { offset += len; length -= len; // Release buffer if empty if (length == 0 && array.length > 1024) { array = new byte[32]; offset = 0; shared = false; } return this; }
[ "public", "ByteArrayQueue", "remove", "(", "int", "len", ")", "{", "offset", "+=", "len", ";", "length", "-=", "len", ";", "// Release buffer if empty\r", "if", "(", "length", "==", "0", "&&", "array", ".", "length", ">", "1024", ")", "{", "array", "=", ...
Removes a sequence of bytes from the head of the queue.
[ "Removes", "a", "sequence", "of", "bytes", "from", "the", "head", "of", "the", "queue", "." ]
e7b9167b6c701b9eec988a9d1e68446cef5ef420
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/ByteArrayQueue.java#L174-L184
136,434
blackducksoftware/integration-common
src/main/java/com/synopsys/integration/util/IntegrationEscapeUtil.java
IntegrationEscapeUtil.escapePiecesForUri
public List<String> escapePiecesForUri(final List<String> pieces) { final List<String> escapedPieces = new ArrayList<>(pieces.size()); for (final String piece : pieces) { final String escaped = escapeForUri(piece); escapedPieces.add(escaped); } return escapedPieces; }
java
public List<String> escapePiecesForUri(final List<String> pieces) { final List<String> escapedPieces = new ArrayList<>(pieces.size()); for (final String piece : pieces) { final String escaped = escapeForUri(piece); escapedPieces.add(escaped); } return escapedPieces; }
[ "public", "List", "<", "String", ">", "escapePiecesForUri", "(", "final", "List", "<", "String", ">", "pieces", ")", "{", "final", "List", "<", "String", ">", "escapedPieces", "=", "new", "ArrayList", "<>", "(", "pieces", ".", "size", "(", ")", ")", ";...
Do a poor man's URI escaping. We aren't terribly interested in precision here, or in introducing a library that would do it better.
[ "Do", "a", "poor", "man", "s", "URI", "escaping", ".", "We", "aren", "t", "terribly", "interested", "in", "precision", "here", "or", "in", "introducing", "a", "library", "that", "would", "do", "it", "better", "." ]
c3d7ccbf678c25047fc60e68fc4d8182b8385f61
https://github.com/blackducksoftware/integration-common/blob/c3d7ccbf678c25047fc60e68fc4d8182b8385f61/src/main/java/com/synopsys/integration/util/IntegrationEscapeUtil.java#L32-L40
136,435
visallo/vertexium
core/src/main/java/org/vertexium/query/QueryParameters.java
QueryParameters.addIds
public void addIds(Collection<String> ids) { if (this.ids == null) { this.ids = new ArrayList<>(ids); } else { this.ids.retainAll(ids); if (this.ids.isEmpty()) { LOGGER.warn("No ids remain after addIds. All elements will be filtered out."); } } }
java
public void addIds(Collection<String> ids) { if (this.ids == null) { this.ids = new ArrayList<>(ids); } else { this.ids.retainAll(ids); if (this.ids.isEmpty()) { LOGGER.warn("No ids remain after addIds. All elements will be filtered out."); } } }
[ "public", "void", "addIds", "(", "Collection", "<", "String", ">", "ids", ")", "{", "if", "(", "this", ".", "ids", "==", "null", ")", "{", "this", ".", "ids", "=", "new", "ArrayList", "<>", "(", "ids", ")", ";", "}", "else", "{", "this", ".", "...
When called the first time, all ids are added to the filter. When called two or more times, the provided id's are and'ed with the those provided in the previous lists. @param ids The ids of the elements that should be searched in this query.
[ "When", "called", "the", "first", "time", "all", "ids", "are", "added", "to", "the", "filter", ".", "When", "called", "two", "or", "more", "times", "the", "provided", "id", "s", "are", "and", "ed", "with", "the", "those", "provided", "in", "the", "prev...
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/core/src/main/java/org/vertexium/query/QueryParameters.java#L114-L123
136,436
visallo/vertexium
security/src/main/java/org/vertexium/security/WritableComparator.java
WritableComparator.forceInit
private static void forceInit(Class<?> cls) { try { Class.forName(cls.getName(), true, cls.getClassLoader()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Can't initialize class " + cls, e); } }
java
private static void forceInit(Class<?> cls) { try { Class.forName(cls.getName(), true, cls.getClassLoader()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Can't initialize class " + cls, e); } }
[ "private", "static", "void", "forceInit", "(", "Class", "<", "?", ">", "cls", ")", "{", "try", "{", "Class", ".", "forName", "(", "cls", ".", "getName", "(", ")", ",", "true", ",", "cls", ".", "getClassLoader", "(", ")", ")", ";", "}", "catch", "...
Force initialization of the static members. As of Java 5, referencing a class doesn't force it to initialize. Since this class requires that the classes be initialized to declare their comparators, we force that initialization to happen. @param cls the class to initialize
[ "Force", "initialization", "of", "the", "static", "members", ".", "As", "of", "Java", "5", "referencing", "a", "class", "doesn", "t", "force", "it", "to", "initialize", ".", "Since", "this", "class", "requires", "that", "the", "classes", "be", "initialized",...
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/security/src/main/java/org/vertexium/security/WritableComparator.java#L66-L72
136,437
visallo/vertexium
security/src/main/java/org/vertexium/security/WritableComparator.java
WritableComparator.readInt
public static int readInt(byte[] bytes, int start) { return (((bytes[start] & 0xff) << 24) + ((bytes[start + 1] & 0xff) << 16) + ((bytes[start + 2] & 0xff) << 8) + ((bytes[start + 3] & 0xff))); }
java
public static int readInt(byte[] bytes, int start) { return (((bytes[start] & 0xff) << 24) + ((bytes[start + 1] & 0xff) << 16) + ((bytes[start + 2] & 0xff) << 8) + ((bytes[start + 3] & 0xff))); }
[ "public", "static", "int", "readInt", "(", "byte", "[", "]", "bytes", ",", "int", "start", ")", "{", "return", "(", "(", "(", "bytes", "[", "start", "]", "&", "0xff", ")", "<<", "24", ")", "+", "(", "(", "bytes", "[", "start", "+", "1", "]", ...
Parse an integer from a byte array.
[ "Parse", "an", "integer", "from", "a", "byte", "array", "." ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/security/src/main/java/org/vertexium/security/WritableComparator.java#L203-L209
136,438
visallo/vertexium
security/src/main/java/org/vertexium/security/WritableComparator.java
WritableComparator.readLong
public static long readLong(byte[] bytes, int start) { return ((long) (readInt(bytes, start)) << 32) + (readInt(bytes, start + 4) & 0xFFFFFFFFL); }
java
public static long readLong(byte[] bytes, int start) { return ((long) (readInt(bytes, start)) << 32) + (readInt(bytes, start + 4) & 0xFFFFFFFFL); }
[ "public", "static", "long", "readLong", "(", "byte", "[", "]", "bytes", ",", "int", "start", ")", "{", "return", "(", "(", "long", ")", "(", "readInt", "(", "bytes", ",", "start", ")", ")", "<<", "32", ")", "+", "(", "readInt", "(", "bytes", ",",...
Parse a long from a byte array.
[ "Parse", "a", "long", "from", "a", "byte", "array", "." ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/security/src/main/java/org/vertexium/security/WritableComparator.java#L221-L224
136,439
visallo/vertexium
security/src/main/java/org/vertexium/security/WritableComparator.java
WritableComparator.readVLong
public static long readVLong(byte[] bytes, int start) throws IOException { int len = bytes[start]; if (len >= -112) { return len; } boolean isNegative = (len < -120); len = isNegative ? -(len + 120) : -(len + 112); if (start + 1 + len > bytes.length) { throw new IOException("Not enough number of bytes for a zero-compressed integer"); } long i = 0; for (int idx = 0; idx < len; idx++) { i = i << 8; i = i | (bytes[start + 1 + idx] & 0xFF); } return (isNegative ? (i ^ -1L) : i); }
java
public static long readVLong(byte[] bytes, int start) throws IOException { int len = bytes[start]; if (len >= -112) { return len; } boolean isNegative = (len < -120); len = isNegative ? -(len + 120) : -(len + 112); if (start + 1 + len > bytes.length) { throw new IOException("Not enough number of bytes for a zero-compressed integer"); } long i = 0; for (int idx = 0; idx < len; idx++) { i = i << 8; i = i | (bytes[start + 1 + idx] & 0xFF); } return (isNegative ? (i ^ -1L) : i); }
[ "public", "static", "long", "readVLong", "(", "byte", "[", "]", "bytes", ",", "int", "start", ")", "throws", "IOException", "{", "int", "len", "=", "bytes", "[", "start", "]", ";", "if", "(", "len", ">=", "-", "112", ")", "{", "return", "len", ";",...
Reads a zero-compressed encoded long from a byte array and returns it. @param bytes byte array with decode long @param start starting index @return deserialized long @throws java.io.IOException
[ "Reads", "a", "zero", "-", "compressed", "encoded", "long", "from", "a", "byte", "array", "and", "returns", "it", "." ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/security/src/main/java/org/vertexium/security/WritableComparator.java#L241-L257
136,440
visallo/vertexium
accumulo-iterators/src/main/java/org/vertexium/accumulo/iterator/model/EdgeInfo.java
EdgeInfo.getVertexId
public static String getVertexId(Value value) { byte[] buffer = value.get(); int offset = 0; // skip label int strLen = readInt(buffer, offset); offset += 4; if (strLen > 0) { offset += strLen; } strLen = readInt(buffer, offset); return readString(buffer, offset, strLen); }
java
public static String getVertexId(Value value) { byte[] buffer = value.get(); int offset = 0; // skip label int strLen = readInt(buffer, offset); offset += 4; if (strLen > 0) { offset += strLen; } strLen = readInt(buffer, offset); return readString(buffer, offset, strLen); }
[ "public", "static", "String", "getVertexId", "(", "Value", "value", ")", "{", "byte", "[", "]", "buffer", "=", "value", ".", "get", "(", ")", ";", "int", "offset", "=", "0", ";", "// skip label", "int", "strLen", "=", "readInt", "(", "buffer", ",", "...
fast access method to avoid creating a new instance of an EdgeInfo
[ "fast", "access", "method", "to", "avoid", "creating", "a", "new", "instance", "of", "an", "EdgeInfo" ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/accumulo-iterators/src/main/java/org/vertexium/accumulo/iterator/model/EdgeInfo.java#L56-L69
136,441
visallo/vertexium
core/src/main/java/org/vertexium/util/ArrayUtils.java
ArrayUtils.intersectsAll
public static <T> boolean intersectsAll(T[] a1, T[] a2) { for (T anA1 : a1) { if (!contains(a2, anA1)) { return false; } } for (T anA2 : a2) { if (!contains(a1, anA2)) { return false; } } return true; }
java
public static <T> boolean intersectsAll(T[] a1, T[] a2) { for (T anA1 : a1) { if (!contains(a2, anA1)) { return false; } } for (T anA2 : a2) { if (!contains(a1, anA2)) { return false; } } return true; }
[ "public", "static", "<", "T", ">", "boolean", "intersectsAll", "(", "T", "[", "]", "a1", ",", "T", "[", "]", "a2", ")", "{", "for", "(", "T", "anA1", ":", "a1", ")", "{", "if", "(", "!", "contains", "(", "a2", ",", "anA1", ")", ")", "{", "r...
Determines if all values in a1 appear in a2 and that all values in a2 appear in a2.
[ "Determines", "if", "all", "values", "in", "a1", "appear", "in", "a2", "and", "that", "all", "values", "in", "a2", "appear", "in", "a2", "." ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/core/src/main/java/org/vertexium/util/ArrayUtils.java#L7-L21
136,442
visallo/vertexium
elasticsearch5/src/main/java/org/vertexium/elasticsearch5/utils/Ascii85.java
Ascii85.decode
public static byte[] decode(String chars) { if (chars == null || chars.length() == 0) { throw new IllegalArgumentException("You must provide a non-zero length input"); } //By using five ASCII characters to represent four bytes of binary data the encoded size ¹⁄₄ is larger than the original BigDecimal decodedLength = BigDecimal.valueOf(chars.length()).multiply(BigDecimal.valueOf(4)) .divide(BigDecimal.valueOf(5)); ByteBuffer bytebuff = ByteBuffer.allocate(decodedLength.intValue()); //1. Whitespace characters may occur anywhere to accommodate line length limitations. So lets strip it. chars = REMOVE_WHITESPACE.matcher(chars).replaceAll(""); //Since Base85 is an ascii encoder, we don't need to get the bytes as UTF-8. byte[] payload = chars.getBytes(StandardCharsets.US_ASCII); byte[] chunk = new byte[5]; int chunkIndex = 0; for (int i = 0; i < payload.length; i++) { byte currByte = payload[i]; //Because all-zero data is quite common, an exception is made for the sake of data compression, //and an all-zero group is encoded as a single character "z" instead of "!!!!!". if (currByte == 'z') { if (chunkIndex > 0) { throw new IllegalArgumentException("The payload is not base 85 encoded."); } chunk[chunkIndex++] = '!'; chunk[chunkIndex++] = '!'; chunk[chunkIndex++] = '!'; chunk[chunkIndex++] = '!'; chunk[chunkIndex++] = '!'; } else { chunk[chunkIndex++] = currByte; } if (chunkIndex == 5) { bytebuff.put(decodeChunk(chunk)); Arrays.fill(chunk, (byte) 0); chunkIndex = 0; } } //If we didn't end on 0, then we need some padding if (chunkIndex > 0) { int numPadded = chunk.length - chunkIndex; Arrays.fill(chunk, chunkIndex, chunk.length, (byte) 'u'); byte[] paddedDecode = decodeChunk(chunk); for (int i = 0; i < paddedDecode.length - numPadded; i++) { bytebuff.put(paddedDecode[i]); } } bytebuff.flip(); return Arrays.copyOf(bytebuff.array(), bytebuff.limit()); }
java
public static byte[] decode(String chars) { if (chars == null || chars.length() == 0) { throw new IllegalArgumentException("You must provide a non-zero length input"); } //By using five ASCII characters to represent four bytes of binary data the encoded size ¹⁄₄ is larger than the original BigDecimal decodedLength = BigDecimal.valueOf(chars.length()).multiply(BigDecimal.valueOf(4)) .divide(BigDecimal.valueOf(5)); ByteBuffer bytebuff = ByteBuffer.allocate(decodedLength.intValue()); //1. Whitespace characters may occur anywhere to accommodate line length limitations. So lets strip it. chars = REMOVE_WHITESPACE.matcher(chars).replaceAll(""); //Since Base85 is an ascii encoder, we don't need to get the bytes as UTF-8. byte[] payload = chars.getBytes(StandardCharsets.US_ASCII); byte[] chunk = new byte[5]; int chunkIndex = 0; for (int i = 0; i < payload.length; i++) { byte currByte = payload[i]; //Because all-zero data is quite common, an exception is made for the sake of data compression, //and an all-zero group is encoded as a single character "z" instead of "!!!!!". if (currByte == 'z') { if (chunkIndex > 0) { throw new IllegalArgumentException("The payload is not base 85 encoded."); } chunk[chunkIndex++] = '!'; chunk[chunkIndex++] = '!'; chunk[chunkIndex++] = '!'; chunk[chunkIndex++] = '!'; chunk[chunkIndex++] = '!'; } else { chunk[chunkIndex++] = currByte; } if (chunkIndex == 5) { bytebuff.put(decodeChunk(chunk)); Arrays.fill(chunk, (byte) 0); chunkIndex = 0; } } //If we didn't end on 0, then we need some padding if (chunkIndex > 0) { int numPadded = chunk.length - chunkIndex; Arrays.fill(chunk, chunkIndex, chunk.length, (byte) 'u'); byte[] paddedDecode = decodeChunk(chunk); for (int i = 0; i < paddedDecode.length - numPadded; i++) { bytebuff.put(paddedDecode[i]); } } bytebuff.flip(); return Arrays.copyOf(bytebuff.array(), bytebuff.limit()); }
[ "public", "static", "byte", "[", "]", "decode", "(", "String", "chars", ")", "{", "if", "(", "chars", "==", "null", "||", "chars", ".", "length", "(", ")", "==", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"You must provide a non-zero...
This is a very simple base85 decoder. It respects the 'z' optimization for empty chunks, and strips whitespace between characters to respect line limits. @param chars The input characters that are base85 encoded. @return The binary data decoded from the input @see <a href="https://en.wikipedia.org/wiki/Ascii85">Ascii85</a>
[ "This", "is", "a", "very", "simple", "base85", "decoder", ".", "It", "respects", "the", "z", "optimization", "for", "empty", "chunks", "and", "strips", "whitespace", "between", "characters", "to", "respect", "line", "limits", "." ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/elasticsearch5/src/main/java/org/vertexium/elasticsearch5/utils/Ascii85.java#L94-L144
136,443
visallo/vertexium
security/src/main/java/org/vertexium/security/ByteSequence.java
ByteSequence.compareTo
public int compareTo(ByteSequence obs) { if (isBackedByArray() && obs.isBackedByArray()) { return WritableComparator.compareBytes(getBackingArray(), offset(), length(), obs.getBackingArray(), obs.offset(), obs.length()); } return compareBytes(this, obs); }
java
public int compareTo(ByteSequence obs) { if (isBackedByArray() && obs.isBackedByArray()) { return WritableComparator.compareBytes(getBackingArray(), offset(), length(), obs.getBackingArray(), obs.offset(), obs.length()); } return compareBytes(this, obs); }
[ "public", "int", "compareTo", "(", "ByteSequence", "obs", ")", "{", "if", "(", "isBackedByArray", "(", ")", "&&", "obs", ".", "isBackedByArray", "(", ")", ")", "{", "return", "WritableComparator", ".", "compareBytes", "(", "getBackingArray", "(", ")", ",", ...
Compares this byte sequence to another. @param obs byte sequence to compare @return comparison result @see #compareBytes(ByteSequence, ByteSequence)
[ "Compares", "this", "byte", "sequence", "to", "another", "." ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/security/src/main/java/org/vertexium/security/ByteSequence.java#L113-L119
136,444
visallo/vertexium
core/src/main/java/org/vertexium/type/GeoPoint.java
GeoPoint.calculateCenter
public static GeoPoint calculateCenter(List<GeoPoint> geoPoints) { checkNotNull(geoPoints, "geoPoints cannot be null"); checkArgument(geoPoints.size() > 0, "must have at least 1 geoPoints"); if (geoPoints.size() == 1) { return geoPoints.get(0); } double x = 0.0; double y = 0.0; double z = 0.0; double totalAlt = 0.0; int altitudeCount = 0; for (GeoPoint geoPoint : geoPoints) { double latRad = Math.toRadians(geoPoint.getLatitude()); double lonRad = Math.toRadians(geoPoint.getLongitude()); x += Math.cos(latRad) * Math.cos(lonRad); y += Math.cos(latRad) * Math.sin(lonRad); z += Math.sin(latRad); if (geoPoint.getAltitude() != null) { totalAlt += geoPoint.getAltitude(); altitudeCount++; } } x = x / (double) geoPoints.size(); y = y / (double) geoPoints.size(); z = z / (double) geoPoints.size(); return new GeoPoint( Math.toDegrees(Math.atan2(z, Math.sqrt(x * x + y * y))), Math.toDegrees(Math.atan2(y, x)), altitudeCount == geoPoints.size() ? (totalAlt / (double) altitudeCount) : null ); }
java
public static GeoPoint calculateCenter(List<GeoPoint> geoPoints) { checkNotNull(geoPoints, "geoPoints cannot be null"); checkArgument(geoPoints.size() > 0, "must have at least 1 geoPoints"); if (geoPoints.size() == 1) { return geoPoints.get(0); } double x = 0.0; double y = 0.0; double z = 0.0; double totalAlt = 0.0; int altitudeCount = 0; for (GeoPoint geoPoint : geoPoints) { double latRad = Math.toRadians(geoPoint.getLatitude()); double lonRad = Math.toRadians(geoPoint.getLongitude()); x += Math.cos(latRad) * Math.cos(lonRad); y += Math.cos(latRad) * Math.sin(lonRad); z += Math.sin(latRad); if (geoPoint.getAltitude() != null) { totalAlt += geoPoint.getAltitude(); altitudeCount++; } } x = x / (double) geoPoints.size(); y = y / (double) geoPoints.size(); z = z / (double) geoPoints.size(); return new GeoPoint( Math.toDegrees(Math.atan2(z, Math.sqrt(x * x + y * y))), Math.toDegrees(Math.atan2(y, x)), altitudeCount == geoPoints.size() ? (totalAlt / (double) altitudeCount) : null ); }
[ "public", "static", "GeoPoint", "calculateCenter", "(", "List", "<", "GeoPoint", ">", "geoPoints", ")", "{", "checkNotNull", "(", "geoPoints", ",", "\"geoPoints cannot be null\"", ")", ";", "checkArgument", "(", "geoPoints", ".", "size", "(", ")", ">", "0", ",...
For large distances center point calculation has rounding errors
[ "For", "large", "distances", "center", "point", "calculation", "has", "rounding", "errors" ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/core/src/main/java/org/vertexium/type/GeoPoint.java#L304-L338
136,445
visallo/vertexium
security/src/main/java/org/vertexium/security/VisibilityEvaluator.java
VisibilityEvaluator.escape
public static byte[] escape(byte[] auth, boolean quote) { int escapeCount = 0; for (int i = 0; i < auth.length; i++) { if (auth[i] == '"' || auth[i] == '\\') { escapeCount++; } } if (escapeCount > 0 || quote) { byte[] escapedAuth = new byte[auth.length + escapeCount + (quote ? 2 : 0)]; int index = quote ? 1 : 0; for (int i = 0; i < auth.length; i++) { if (auth[i] == '"' || auth[i] == '\\') { escapedAuth[index++] = '\\'; } escapedAuth[index++] = auth[i]; } if (quote) { escapedAuth[0] = '"'; escapedAuth[escapedAuth.length - 1] = '"'; } auth = escapedAuth; } return auth; }
java
public static byte[] escape(byte[] auth, boolean quote) { int escapeCount = 0; for (int i = 0; i < auth.length; i++) { if (auth[i] == '"' || auth[i] == '\\') { escapeCount++; } } if (escapeCount > 0 || quote) { byte[] escapedAuth = new byte[auth.length + escapeCount + (quote ? 2 : 0)]; int index = quote ? 1 : 0; for (int i = 0; i < auth.length; i++) { if (auth[i] == '"' || auth[i] == '\\') { escapedAuth[index++] = '\\'; } escapedAuth[index++] = auth[i]; } if (quote) { escapedAuth[0] = '"'; escapedAuth[escapedAuth.length - 1] = '"'; } auth = escapedAuth; } return auth; }
[ "public", "static", "byte", "[", "]", "escape", "(", "byte", "[", "]", "auth", ",", "boolean", "quote", ")", "{", "int", "escapeCount", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "auth", ".", "length", ";", "i", "++", ")", ...
Properly escapes an authorization string. The string can be quoted if desired. @param auth authorization string, as UTF-8 encoded bytes @param quote true to wrap escaped authorization in quotes @return escaped authorization string
[ "Properly", "escapes", "an", "authorization", "string", ".", "The", "string", "can", "be", "quoted", "if", "desired", "." ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/security/src/main/java/org/vertexium/security/VisibilityEvaluator.java#L53-L80
136,446
visallo/vertexium
security/src/main/java/org/vertexium/security/ColumnVisibility.java
ColumnVisibility.quote
public static byte[] quote(byte[] term) { boolean needsQuote = false; for (int i = 0; i < term.length; i++) { if (!Authorizations.isValidAuthChar(term[i])) { needsQuote = true; break; } } if (!needsQuote) { return term; } return VisibilityEvaluator.escape(term, true); }
java
public static byte[] quote(byte[] term) { boolean needsQuote = false; for (int i = 0; i < term.length; i++) { if (!Authorizations.isValidAuthChar(term[i])) { needsQuote = true; break; } } if (!needsQuote) { return term; } return VisibilityEvaluator.escape(term, true); }
[ "public", "static", "byte", "[", "]", "quote", "(", "byte", "[", "]", "term", ")", "{", "boolean", "needsQuote", "=", "false", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "term", ".", "length", ";", "i", "++", ")", "{", "if", "(", "...
Properly quotes terms in a column visibility expression. If no quoting is needed, then nothing is done. @param term term to quote, encoded as UTF-8 bytes @return quoted term (unquoted if unnecessary), encoded as UTF-8 bytes @see #quote(String)
[ "Properly", "quotes", "terms", "in", "a", "column", "visibility", "expression", ".", "If", "no", "quoting", "is", "needed", "then", "nothing", "is", "done", "." ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/security/src/main/java/org/vertexium/security/ColumnVisibility.java#L534-L549
136,447
visallo/vertexium
elasticsearch5/src/main/java/org/vertexium/elasticsearch5/utils/Murmur3.java
Murmur3.hash32
public static int hash32(byte[] data, int length, int seed) { int hash = seed; final int nblocks = length >> 2; // body for (int i = 0; i < nblocks; i++) { int i_4 = i << 2; int k = (data[i_4] & 0xff) | ((data[i_4 + 1] & 0xff) << 8) | ((data[i_4 + 2] & 0xff) << 16) | ((data[i_4 + 3] & 0xff) << 24); // mix functions k *= C1_32; k = Integer.rotateLeft(k, R1_32); k *= C2_32; hash ^= k; hash = Integer.rotateLeft(hash, R2_32) * M_32 + N_32; } // tail int idx = nblocks << 2; int k1 = 0; switch (length - idx) { case 3: k1 ^= data[idx + 2] << 16; case 2: k1 ^= data[idx + 1] << 8; case 1: k1 ^= data[idx]; // mix functions k1 *= C1_32; k1 = Integer.rotateLeft(k1, R1_32); k1 *= C2_32; hash ^= k1; } // finalization hash ^= length; hash ^= (hash >>> 16); hash *= 0x85ebca6b; hash ^= (hash >>> 13); hash *= 0xc2b2ae35; hash ^= (hash >>> 16); return hash; }
java
public static int hash32(byte[] data, int length, int seed) { int hash = seed; final int nblocks = length >> 2; // body for (int i = 0; i < nblocks; i++) { int i_4 = i << 2; int k = (data[i_4] & 0xff) | ((data[i_4 + 1] & 0xff) << 8) | ((data[i_4 + 2] & 0xff) << 16) | ((data[i_4 + 3] & 0xff) << 24); // mix functions k *= C1_32; k = Integer.rotateLeft(k, R1_32); k *= C2_32; hash ^= k; hash = Integer.rotateLeft(hash, R2_32) * M_32 + N_32; } // tail int idx = nblocks << 2; int k1 = 0; switch (length - idx) { case 3: k1 ^= data[idx + 2] << 16; case 2: k1 ^= data[idx + 1] << 8; case 1: k1 ^= data[idx]; // mix functions k1 *= C1_32; k1 = Integer.rotateLeft(k1, R1_32); k1 *= C2_32; hash ^= k1; } // finalization hash ^= length; hash ^= (hash >>> 16); hash *= 0x85ebca6b; hash ^= (hash >>> 13); hash *= 0xc2b2ae35; hash ^= (hash >>> 16); return hash; }
[ "public", "static", "int", "hash32", "(", "byte", "[", "]", "data", ",", "int", "length", ",", "int", "seed", ")", "{", "int", "hash", "=", "seed", ";", "final", "int", "nblocks", "=", "length", ">>", "2", ";", "// body", "for", "(", "int", "i", ...
Murmur3 32-bit variant. @param data - input byte array @param length - length of array @param seed - seed. (default 0) @return - hashcode
[ "Murmur3", "32", "-", "bit", "variant", "." ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/elasticsearch5/src/main/java/org/vertexium/elasticsearch5/utils/Murmur3.java#L59-L106
136,448
visallo/vertexium
elasticsearch5/src/main/java/org/vertexium/elasticsearch5/utils/Murmur3.java
Murmur3.hash64
public static long hash64(byte[] data, int offset, int length, int seed) { long hash = seed; final int nblocks = length >> 3; // body for (int i = 0; i < nblocks; i++) { final int i8 = i << 3; long k = ((long) data[offset + i8] & 0xff) | (((long) data[offset + i8 + 1] & 0xff) << 8) | (((long) data[offset + i8 + 2] & 0xff) << 16) | (((long) data[offset + i8 + 3] & 0xff) << 24) | (((long) data[offset + i8 + 4] & 0xff) << 32) | (((long) data[offset + i8 + 5] & 0xff) << 40) | (((long) data[offset + i8 + 6] & 0xff) << 48) | (((long) data[offset + i8 + 7] & 0xff) << 56); // mix functions k *= C1; k = Long.rotateLeft(k, R1); k *= C2; hash ^= k; hash = Long.rotateLeft(hash, R2) * M + N1; } // tail long k1 = 0; int tailStart = nblocks << 3; switch (length - tailStart) { case 7: k1 ^= ((long) data[offset + tailStart + 6] & 0xff) << 48; case 6: k1 ^= ((long) data[offset + tailStart + 5] & 0xff) << 40; case 5: k1 ^= ((long) data[offset + tailStart + 4] & 0xff) << 32; case 4: k1 ^= ((long) data[offset + tailStart + 3] & 0xff) << 24; case 3: k1 ^= ((long) data[offset + tailStart + 2] & 0xff) << 16; case 2: k1 ^= ((long) data[offset + tailStart + 1] & 0xff) << 8; case 1: k1 ^= ((long) data[offset + tailStart] & 0xff); k1 *= C1; k1 = Long.rotateLeft(k1, R1); k1 *= C2; hash ^= k1; } // finalization hash ^= length; hash = fmix64(hash); return hash; }
java
public static long hash64(byte[] data, int offset, int length, int seed) { long hash = seed; final int nblocks = length >> 3; // body for (int i = 0; i < nblocks; i++) { final int i8 = i << 3; long k = ((long) data[offset + i8] & 0xff) | (((long) data[offset + i8 + 1] & 0xff) << 8) | (((long) data[offset + i8 + 2] & 0xff) << 16) | (((long) data[offset + i8 + 3] & 0xff) << 24) | (((long) data[offset + i8 + 4] & 0xff) << 32) | (((long) data[offset + i8 + 5] & 0xff) << 40) | (((long) data[offset + i8 + 6] & 0xff) << 48) | (((long) data[offset + i8 + 7] & 0xff) << 56); // mix functions k *= C1; k = Long.rotateLeft(k, R1); k *= C2; hash ^= k; hash = Long.rotateLeft(hash, R2) * M + N1; } // tail long k1 = 0; int tailStart = nblocks << 3; switch (length - tailStart) { case 7: k1 ^= ((long) data[offset + tailStart + 6] & 0xff) << 48; case 6: k1 ^= ((long) data[offset + tailStart + 5] & 0xff) << 40; case 5: k1 ^= ((long) data[offset + tailStart + 4] & 0xff) << 32; case 4: k1 ^= ((long) data[offset + tailStart + 3] & 0xff) << 24; case 3: k1 ^= ((long) data[offset + tailStart + 2] & 0xff) << 16; case 2: k1 ^= ((long) data[offset + tailStart + 1] & 0xff) << 8; case 1: k1 ^= ((long) data[offset + tailStart] & 0xff); k1 *= C1; k1 = Long.rotateLeft(k1, R1); k1 *= C2; hash ^= k1; } // finalization hash ^= length; hash = fmix64(hash); return hash; }
[ "public", "static", "long", "hash64", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "int", "length", ",", "int", "seed", ")", "{", "long", "hash", "=", "seed", ";", "final", "int", "nblocks", "=", "length", ">>", "3", ";", "// body", "f...
Murmur3 64-bit variant. This is essentially MSB 8 bytes of Murmur3 128-bit variant. @param data - input byte array @param length - length of array @param seed - seed. (default is 0) @return - hashcode
[ "Murmur3", "64", "-", "bit", "variant", ".", "This", "is", "essentially", "MSB", "8", "bytes", "of", "Murmur3", "128", "-", "bit", "variant", "." ]
bb132b5425ac168957667164e1409b78adbea769
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/elasticsearch5/src/main/java/org/vertexium/elasticsearch5/utils/Murmur3.java#L130-L183
136,449
nicoulaj/checksum-maven-plugin
src/main/java/net/nicoulaj/maven/plugins/checksum/mojo/ArtifactsMojo.java
ArtifactsMojo.hasValidFile
protected boolean hasValidFile( Artifact artifact ) { // Make sure the file exists. boolean hasValidFile = artifact != null && artifact.getFile() != null && artifact.getFile().exists(); // Exclude project POM file. hasValidFile = hasValidFile && !artifact.getFile().getPath().equals( project.getFile().getPath() ); // Exclude files outside of build directory. hasValidFile = hasValidFile && artifact.getFile().getPath().startsWith( project.getBuild().getDirectory() ); return hasValidFile; }
java
protected boolean hasValidFile( Artifact artifact ) { // Make sure the file exists. boolean hasValidFile = artifact != null && artifact.getFile() != null && artifact.getFile().exists(); // Exclude project POM file. hasValidFile = hasValidFile && !artifact.getFile().getPath().equals( project.getFile().getPath() ); // Exclude files outside of build directory. hasValidFile = hasValidFile && artifact.getFile().getPath().startsWith( project.getBuild().getDirectory() ); return hasValidFile; }
[ "protected", "boolean", "hasValidFile", "(", "Artifact", "artifact", ")", "{", "// Make sure the file exists.", "boolean", "hasValidFile", "=", "artifact", "!=", "null", "&&", "artifact", ".", "getFile", "(", ")", "!=", "null", "&&", "artifact", ".", "getFile", ...
Decide whether the artifact file should be processed. <p>Excludes the project POM file and any file outside the build directory, because this could lead to writing files on the user local repository for example.</p> @param artifact the artifact to check. @return true if the artifact should be included in the files to process.
[ "Decide", "whether", "the", "artifact", "file", "should", "be", "processed", "." ]
8d8feab8a0a34e24ae41621e7372be6387e1fe55
https://github.com/nicoulaj/checksum-maven-plugin/blob/8d8feab8a0a34e24ae41621e7372be6387e1fe55/src/main/java/net/nicoulaj/maven/plugins/checksum/mojo/ArtifactsMojo.java#L174-L186
136,450
nicoulaj/checksum-maven-plugin
src/main/java/net/nicoulaj/maven/plugins/checksum/mojo/DependenciesCheckMojo.java
DependenciesCheckMojo.readSummaryFile
private Map<String, Map<String, String>> readSummaryFile(File outputFile) throws ExecutionException { List<String> algorithms = new ArrayList<String>(); Map<String, Map<String, String>> filesHashcodes = new HashMap<String, Map<String, String>>(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(outputFile)); String line; while ((line = reader.readLine()) != null) { // Read the CVS file header if (isFileHeader(line)) { readFileHeader(line, algorithms); } else { // Read the dependencies checksums readDependenciesChecksums(line, algorithms, filesHashcodes); } } } catch (IOException e) { throw new ExecutionException(e.getMessage()); } finally { IOUtil.close(reader); } return filesHashcodes; }
java
private Map<String, Map<String, String>> readSummaryFile(File outputFile) throws ExecutionException { List<String> algorithms = new ArrayList<String>(); Map<String, Map<String, String>> filesHashcodes = new HashMap<String, Map<String, String>>(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(outputFile)); String line; while ((line = reader.readLine()) != null) { // Read the CVS file header if (isFileHeader(line)) { readFileHeader(line, algorithms); } else { // Read the dependencies checksums readDependenciesChecksums(line, algorithms, filesHashcodes); } } } catch (IOException e) { throw new ExecutionException(e.getMessage()); } finally { IOUtil.close(reader); } return filesHashcodes; }
[ "private", "Map", "<", "String", ",", "Map", "<", "String", ",", "String", ">", ">", "readSummaryFile", "(", "File", "outputFile", ")", "throws", "ExecutionException", "{", "List", "<", "String", ">", "algorithms", "=", "new", "ArrayList", "<", "String", "...
Read the summary file @param outputFile the summary file @return the summary content (<filename, <algo, checksum>>) @throws ExecutionException if an error happens while running the execution.
[ "Read", "the", "summary", "file" ]
8d8feab8a0a34e24ae41621e7372be6387e1fe55
https://github.com/nicoulaj/checksum-maven-plugin/blob/8d8feab8a0a34e24ae41621e7372be6387e1fe55/src/main/java/net/nicoulaj/maven/plugins/checksum/mojo/DependenciesCheckMojo.java#L264-L297
136,451
stevespringett/Alpine
alpine/src/main/java/alpine/tasks/LdapSyncTask.java
LdapSyncTask.sync
private void sync(final DirContext ctx, final AlpineQueryManager qm, final LdapConnectionWrapper ldap, LdapUser user) throws NamingException { LOGGER.debug("Syncing: " + user.getUsername()); final SearchResult result = ldap.searchForSingleUsername(ctx, user.getUsername()); if (result != null) { user.setDN(result.getNameInNamespace()); user.setEmail(ldap.getAttribute(result, LdapConnectionWrapper.ATTRIBUTE_MAIL)); user = qm.updateLdapUser(user); // Dynamically assign team membership (if enabled) if (LdapConnectionWrapper.TEAM_SYNCHRONIZATION) { final List<String> groupDNs = ldap.getGroups(ctx, user); qm.synchronizeTeamMembership(user, groupDNs); } } else { // This is an invalid user - a username that exists in the database that does not exist in LDAP user.setDN("INVALID"); user.setEmail(null); user = qm.updateLdapUser(user); if (LdapConnectionWrapper.TEAM_SYNCHRONIZATION) { qm.synchronizeTeamMembership(user, new ArrayList<>()); } } }
java
private void sync(final DirContext ctx, final AlpineQueryManager qm, final LdapConnectionWrapper ldap, LdapUser user) throws NamingException { LOGGER.debug("Syncing: " + user.getUsername()); final SearchResult result = ldap.searchForSingleUsername(ctx, user.getUsername()); if (result != null) { user.setDN(result.getNameInNamespace()); user.setEmail(ldap.getAttribute(result, LdapConnectionWrapper.ATTRIBUTE_MAIL)); user = qm.updateLdapUser(user); // Dynamically assign team membership (if enabled) if (LdapConnectionWrapper.TEAM_SYNCHRONIZATION) { final List<String> groupDNs = ldap.getGroups(ctx, user); qm.synchronizeTeamMembership(user, groupDNs); } } else { // This is an invalid user - a username that exists in the database that does not exist in LDAP user.setDN("INVALID"); user.setEmail(null); user = qm.updateLdapUser(user); if (LdapConnectionWrapper.TEAM_SYNCHRONIZATION) { qm.synchronizeTeamMembership(user, new ArrayList<>()); } } }
[ "private", "void", "sync", "(", "final", "DirContext", "ctx", ",", "final", "AlpineQueryManager", "qm", ",", "final", "LdapConnectionWrapper", "ldap", ",", "LdapUser", "user", ")", "throws", "NamingException", "{", "LOGGER", ".", "debug", "(", "\"Syncing: \"", "...
Performs the actual sync of the specified user. @param ctx a DirContext @param qm the AlpineQueryManager to use @param ldap the LdapConnectionWrapper to use @param user the LdapUser instance to sync @throws NamingException when a problem with the connection with the directory
[ "Performs", "the", "actual", "sync", "of", "the", "specified", "user", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/tasks/LdapSyncTask.java#L88-L110
136,452
stevespringett/Alpine
alpine/src/main/java/alpine/util/ThreadUtil.java
ThreadUtil.determineNumberOfWorkerThreads
public static int determineNumberOfWorkerThreads() { final int threads = Config.getInstance().getPropertyAsInt(Config.AlpineKey.WORKER_THREADS); if (threads > 0) { return threads; } else if (threads == 0) { final int cores = SystemUtil.getCpuCores(); final int multiplier = Config.getInstance().getPropertyAsInt(Config.AlpineKey.WORKER_THREAD_MULTIPLIER); if (multiplier > 0) { return cores * multiplier; } else { return cores; } } return 1; // We have to have a minimum of 1 thread }
java
public static int determineNumberOfWorkerThreads() { final int threads = Config.getInstance().getPropertyAsInt(Config.AlpineKey.WORKER_THREADS); if (threads > 0) { return threads; } else if (threads == 0) { final int cores = SystemUtil.getCpuCores(); final int multiplier = Config.getInstance().getPropertyAsInt(Config.AlpineKey.WORKER_THREAD_MULTIPLIER); if (multiplier > 0) { return cores * multiplier; } else { return cores; } } return 1; // We have to have a minimum of 1 thread }
[ "public", "static", "int", "determineNumberOfWorkerThreads", "(", ")", "{", "final", "int", "threads", "=", "Config", ".", "getInstance", "(", ")", ".", "getPropertyAsInt", "(", "Config", ".", "AlpineKey", ".", "WORKER_THREADS", ")", ";", "if", "(", "threads",...
Calculates the number of worker threads to use. Minimum return value is 1. @return the number of worker threads @since 1.0.0
[ "Calculates", "the", "number", "of", "worker", "threads", "to", "use", ".", "Minimum", "return", "value", "is", "1", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/util/ThreadUtil.java#L41-L55
136,453
stevespringett/Alpine
alpine/src/main/java/alpine/resources/AlpineResource.java
AlpineResource.contOnValidationError
@SafeVarargs protected final List<ValidationError> contOnValidationError(final Set<ConstraintViolation<Object>>... violationsArray) { final List<ValidationError> errors = new ArrayList<>(); for (final Set<ConstraintViolation<Object>> violations : violationsArray) { for (final ConstraintViolation violation : violations) { if (violation.getPropertyPath().iterator().next().getName() != null) { final String path = violation.getPropertyPath() != null ? violation.getPropertyPath().toString() : null; final String message = violation.getMessage() != null ? StringUtils.removeStart(violation.getMessage(), path + ".") : null; final String messageTemplate = violation.getMessageTemplate(); final String invalidValue = violation.getInvalidValue() != null ? violation.getInvalidValue().toString() : null; final ValidationError error = new ValidationError(message, messageTemplate, path, invalidValue); errors.add(error); } } } return errors; }
java
@SafeVarargs protected final List<ValidationError> contOnValidationError(final Set<ConstraintViolation<Object>>... violationsArray) { final List<ValidationError> errors = new ArrayList<>(); for (final Set<ConstraintViolation<Object>> violations : violationsArray) { for (final ConstraintViolation violation : violations) { if (violation.getPropertyPath().iterator().next().getName() != null) { final String path = violation.getPropertyPath() != null ? violation.getPropertyPath().toString() : null; final String message = violation.getMessage() != null ? StringUtils.removeStart(violation.getMessage(), path + ".") : null; final String messageTemplate = violation.getMessageTemplate(); final String invalidValue = violation.getInvalidValue() != null ? violation.getInvalidValue().toString() : null; final ValidationError error = new ValidationError(message, messageTemplate, path, invalidValue); errors.add(error); } } } return errors; }
[ "@", "SafeVarargs", "protected", "final", "List", "<", "ValidationError", ">", "contOnValidationError", "(", "final", "Set", "<", "ConstraintViolation", "<", "Object", ">", ">", "...", "violationsArray", ")", "{", "final", "List", "<", "ValidationError", ">", "e...
Accepts the result from one of the many validation methods available and returns a List of ValidationErrors. If the size of the List is 0, no errors were encounter during validation. Usage: <pre> Validator validator = getValidator(); List&lt;ValidationError&gt; errors = contOnValidationError( validator.validateProperty(myObject, "uuid"), validator.validateProperty(myObject, "name") ); // If validation fails, this line will be reached. </pre> @param violationsArray a Set of one or more ConstraintViolations @return a List of zero or more ValidationErrors @since 1.0.0
[ "Accepts", "the", "result", "from", "one", "of", "the", "many", "validation", "methods", "available", "and", "returns", "a", "List", "of", "ValidationErrors", ".", "If", "the", "size", "of", "the", "List", "is", "0", "no", "errors", "were", "encounter", "d...
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/resources/AlpineResource.java#L168-L184
136,454
stevespringett/Alpine
alpine/src/main/java/alpine/resources/AlpineResource.java
AlpineResource.contOnValidationError
protected final List<ValidationException> contOnValidationError(final ValidationTask... validationTasks) { final List<ValidationException> errors = new ArrayList<>(); for (final ValidationTask validationTask: validationTasks) { if (!validationTask.isRequired() && validationTask.getInput() == null) { continue; } if (!validationTask.getPattern().matcher(validationTask.getInput()).matches()) { errors.add(new ValidationException(validationTask.getInput(), validationTask.getErrorMessage())); } } return errors; }
java
protected final List<ValidationException> contOnValidationError(final ValidationTask... validationTasks) { final List<ValidationException> errors = new ArrayList<>(); for (final ValidationTask validationTask: validationTasks) { if (!validationTask.isRequired() && validationTask.getInput() == null) { continue; } if (!validationTask.getPattern().matcher(validationTask.getInput()).matches()) { errors.add(new ValidationException(validationTask.getInput(), validationTask.getErrorMessage())); } } return errors; }
[ "protected", "final", "List", "<", "ValidationException", ">", "contOnValidationError", "(", "final", "ValidationTask", "...", "validationTasks", ")", "{", "final", "List", "<", "ValidationException", ">", "errors", "=", "new", "ArrayList", "<>", "(", ")", ";", ...
Given one or mote ValidationTasks, this method will return a List of ValidationErrors. If the size of the List is 0, no errors were encountered during validation. Usage: <pre> List&lt;ValidationException&gt; errors = contOnValidationError( new ValidationTask(pattern, input, errorMessage), new ValidationTask(pattern, input, errorMessage) ); // If validation fails, this line will be reached. </pre> @param validationTasks an array of one or more ValidationTasks @return a List of zero or more ValidationException @since 1.0.0
[ "Given", "one", "or", "mote", "ValidationTasks", "this", "method", "will", "return", "a", "List", "of", "ValidationErrors", ".", "If", "the", "size", "of", "the", "List", "is", "0", "no", "errors", "were", "encountered", "during", "validation", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/resources/AlpineResource.java#L231-L242
136,455
stevespringett/Alpine
alpine/src/main/java/alpine/resources/AlpineResource.java
AlpineResource.initialize
@PostConstruct private void initialize() { final MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters(); final String offset = multiParam(queryParams, "offset"); final String page = multiParam(queryParams, "page", "pageNumber"); final String size = multiParam(queryParams, "size", "pageSize", "limit"); final String filter = multiParam(queryParams, "filter", "searchText"); final String sort = multiParam(queryParams, "sort", "sortOrder"); final OrderDirection orderDirection; String orderBy = multiParam(queryParams, "orderBy", "sortName"); if (StringUtils.isBlank(orderBy) || !RegexSequence.Pattern.ALPHA_NUMERIC.matcher(orderBy).matches()) { orderBy = null; } if ("asc".equalsIgnoreCase(sort)) { orderDirection = OrderDirection.ASCENDING; } else if ("desc".equalsIgnoreCase(sort)) { orderDirection = OrderDirection.DESCENDING; } else { orderDirection = OrderDirection.UNSPECIFIED; } final Pagination pagination; if (StringUtils.isNotBlank(offset)) { pagination = new Pagination(Pagination.Strategy.OFFSET, offset, size); } else if (StringUtils.isNotBlank(page) && StringUtils.isNotBlank(size)) { pagination = new Pagination(Pagination.Strategy.PAGES, page, size); } else { pagination = new Pagination(Pagination.Strategy.OFFSET, 0, 100); // Always paginate queries from resources } this.alpineRequest = new AlpineRequest(getPrincipal(), pagination, filter, orderBy, orderDirection); }
java
@PostConstruct private void initialize() { final MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters(); final String offset = multiParam(queryParams, "offset"); final String page = multiParam(queryParams, "page", "pageNumber"); final String size = multiParam(queryParams, "size", "pageSize", "limit"); final String filter = multiParam(queryParams, "filter", "searchText"); final String sort = multiParam(queryParams, "sort", "sortOrder"); final OrderDirection orderDirection; String orderBy = multiParam(queryParams, "orderBy", "sortName"); if (StringUtils.isBlank(orderBy) || !RegexSequence.Pattern.ALPHA_NUMERIC.matcher(orderBy).matches()) { orderBy = null; } if ("asc".equalsIgnoreCase(sort)) { orderDirection = OrderDirection.ASCENDING; } else if ("desc".equalsIgnoreCase(sort)) { orderDirection = OrderDirection.DESCENDING; } else { orderDirection = OrderDirection.UNSPECIFIED; } final Pagination pagination; if (StringUtils.isNotBlank(offset)) { pagination = new Pagination(Pagination.Strategy.OFFSET, offset, size); } else if (StringUtils.isNotBlank(page) && StringUtils.isNotBlank(size)) { pagination = new Pagination(Pagination.Strategy.PAGES, page, size); } else { pagination = new Pagination(Pagination.Strategy.OFFSET, 0, 100); // Always paginate queries from resources } this.alpineRequest = new AlpineRequest(getPrincipal(), pagination, filter, orderBy, orderDirection); }
[ "@", "PostConstruct", "private", "void", "initialize", "(", ")", "{", "final", "MultivaluedMap", "<", "String", ",", "String", ">", "queryParams", "=", "uriInfo", ".", "getQueryParameters", "(", ")", ";", "final", "String", "offset", "=", "multiParam", "(", ...
Initializes this resource instance by populating some of the features of this class
[ "Initializes", "this", "resource", "instance", "by", "populating", "some", "of", "the", "features", "of", "this", "class" ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/resources/AlpineResource.java#L272-L304
136,456
stevespringett/Alpine
alpine/src/main/java/alpine/resources/AlpineResource.java
AlpineResource.getPrincipal
protected Principal getPrincipal() { final Object principal = requestContext.getProperty("Principal"); if (principal != null) { return (Principal) principal; } else { return null; } }
java
protected Principal getPrincipal() { final Object principal = requestContext.getProperty("Principal"); if (principal != null) { return (Principal) principal; } else { return null; } }
[ "protected", "Principal", "getPrincipal", "(", ")", "{", "final", "Object", "principal", "=", "requestContext", ".", "getProperty", "(", "\"Principal\"", ")", ";", "if", "(", "principal", "!=", "null", ")", "{", "return", "(", "Principal", ")", "principal", ...
Returns the principal for who initiated the request. @return a Principal object @see alpine.model.ApiKey @see alpine.model.LdapUser @since 1.0.0
[ "Returns", "the", "principal", "for", "who", "initiated", "the", "request", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/resources/AlpineResource.java#L330-L337
136,457
stevespringett/Alpine
alpine/src/main/java/alpine/resources/AlpineResource.java
AlpineResource.hasPermission
protected boolean hasPermission(final String permission) { if (getPrincipal() == null) { return false; } try (AlpineQueryManager qm = new AlpineQueryManager()) { boolean hasPermission = false; if (getPrincipal() instanceof ApiKey) { hasPermission = qm.hasPermission((ApiKey)getPrincipal(), permission); } else if (getPrincipal() instanceof UserPrincipal) { hasPermission = qm.hasPermission((UserPrincipal)getPrincipal(), permission, true); } return hasPermission; } }
java
protected boolean hasPermission(final String permission) { if (getPrincipal() == null) { return false; } try (AlpineQueryManager qm = new AlpineQueryManager()) { boolean hasPermission = false; if (getPrincipal() instanceof ApiKey) { hasPermission = qm.hasPermission((ApiKey)getPrincipal(), permission); } else if (getPrincipal() instanceof UserPrincipal) { hasPermission = qm.hasPermission((UserPrincipal)getPrincipal(), permission, true); } return hasPermission; } }
[ "protected", "boolean", "hasPermission", "(", "final", "String", "permission", ")", "{", "if", "(", "getPrincipal", "(", ")", "==", "null", ")", "{", "return", "false", ";", "}", "try", "(", "AlpineQueryManager", "qm", "=", "new", "AlpineQueryManager", "(", ...
Convenience method that returns true if the principal has the specified permission, or false if not. @param permission the permission to check @return true if principal has permission assigned, false if not @since 1.2.0
[ "Convenience", "method", "that", "returns", "true", "if", "the", "principal", "has", "the", "specified", "permission", "or", "false", "if", "not", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/resources/AlpineResource.java#L370-L383
136,458
stevespringett/Alpine
alpine/src/main/java/alpine/auth/PasswordService.java
PasswordService.matches
public static boolean matches(final char[] assertedPassword, final ManagedUser user) { final char[] prehash = createSha512Hash(assertedPassword); // Todo: remove String when Jbcrypt supports char[] return BCrypt.checkpw(new String(prehash), user.getPassword()); }
java
public static boolean matches(final char[] assertedPassword, final ManagedUser user) { final char[] prehash = createSha512Hash(assertedPassword); // Todo: remove String when Jbcrypt supports char[] return BCrypt.checkpw(new String(prehash), user.getPassword()); }
[ "public", "static", "boolean", "matches", "(", "final", "char", "[", "]", "assertedPassword", ",", "final", "ManagedUser", "user", ")", "{", "final", "char", "[", "]", "prehash", "=", "createSha512Hash", "(", "assertedPassword", ")", ";", "// Todo: remove String...
Checks the validity of the asserted password against a ManagedUsers actual hashed password. @param assertedPassword the clear text password to check @param user The ManagedUser to check the password of @return true if assertedPassword matches the expected password of the ManangedUser, false if not @since 1.0.0
[ "Checks", "the", "validity", "of", "the", "asserted", "password", "against", "a", "ManagedUsers", "actual", "hashed", "password", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/auth/PasswordService.java#L98-L102
136,459
stevespringett/Alpine
alpine/src/main/java/alpine/auth/PasswordService.java
PasswordService.createSha512Hash
private static char[] createSha512Hash(final char[] password) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-512"); digest.update(ByteUtil.toBytes(password)); final byte[] byteData = digest.digest(); final StringBuilder sb = new StringBuilder(); for (final byte data : byteData) { sb.append(Integer.toString((data & 0xff) + 0x100, 16).substring(1)); } final char[] hash = new char[128]; sb.getChars(0, sb.length(), hash, 0); return hash; } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); } }
java
private static char[] createSha512Hash(final char[] password) { try { final MessageDigest digest = MessageDigest.getInstance("SHA-512"); digest.update(ByteUtil.toBytes(password)); final byte[] byteData = digest.digest(); final StringBuilder sb = new StringBuilder(); for (final byte data : byteData) { sb.append(Integer.toString((data & 0xff) + 0x100, 16).substring(1)); } final char[] hash = new char[128]; sb.getChars(0, sb.length(), hash, 0); return hash; } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); } }
[ "private", "static", "char", "[", "]", "createSha512Hash", "(", "final", "char", "[", "]", "password", ")", "{", "try", "{", "final", "MessageDigest", "digest", "=", "MessageDigest", ".", "getInstance", "(", "\"SHA-512\"", ")", ";", "digest", ".", "update", ...
Creates a SHA-512 hash of the specified password and returns a HEX representation of the hash. This method should NOT be used solely for password hashing, but in conjunction with password-specific hashing functions. @param password the password to hash @return a char[] of the hashed password @since 1.0.0
[ "Creates", "a", "SHA", "-", "512", "hash", "of", "the", "specified", "password", "and", "returns", "a", "HEX", "representation", "of", "the", "hash", ".", "This", "method", "should", "NOT", "be", "used", "solely", "for", "password", "hashing", "but", "in",...
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/auth/PasswordService.java#L143-L159
136,460
stevespringett/Alpine
alpine/src/main/java/alpine/filters/FqdnForwardFilter.java
FqdnForwardFilter.init
public void init(final FilterConfig filterConfig) { final String host = filterConfig.getInitParameter("host"); if (StringUtils.isNotBlank(host)) { this.host = host; } }
java
public void init(final FilterConfig filterConfig) { final String host = filterConfig.getInitParameter("host"); if (StringUtils.isNotBlank(host)) { this.host = host; } }
[ "public", "void", "init", "(", "final", "FilterConfig", "filterConfig", ")", "{", "final", "String", "host", "=", "filterConfig", ".", "getInitParameter", "(", "\"host\"", ")", ";", "if", "(", "StringUtils", ".", "isNotBlank", "(", "host", ")", ")", "{", "...
Initialize "host" parameter from web.xml. @param filterConfig A filter configuration object used by a servlet container to pass information to a filter during initialization.
[ "Initialize", "host", "parameter", "from", "web", ".", "xml", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/FqdnForwardFilter.java#L67-L72
136,461
stevespringett/Alpine
alpine/src/main/java/alpine/persistence/PersistenceInitializer.java
PersistenceInitializer.startDbServer
private void startDbServer() { final String mode = Config.getInstance().getProperty(Config.AlpineKey.DATABASE_MODE); final int port = Config.getInstance().getPropertyAsInt(Config.AlpineKey.DATABASE_PORT); if (StringUtils.isEmpty(mode) || !("server".equals(mode) || "embedded".equals(mode) || "external".equals(mode))) { LOGGER.error("Database mode not specified. Expected values are 'server', 'embedded', or 'external'"); } if (dbServer != null || "embedded".equals(mode) || "external".equals(mode)) { return; } final String[] args = new String[] { "-tcp", "-tcpPort", String.valueOf(port), "-tcpAllowOthers", }; try { LOGGER.info("Attempting to start database service"); dbServer = Server.createTcpServer(args).start(); LOGGER.info("Database service started"); } catch (SQLException e) { LOGGER.error("Unable to start database service: " + e.getMessage()); stopDbServer(); } }
java
private void startDbServer() { final String mode = Config.getInstance().getProperty(Config.AlpineKey.DATABASE_MODE); final int port = Config.getInstance().getPropertyAsInt(Config.AlpineKey.DATABASE_PORT); if (StringUtils.isEmpty(mode) || !("server".equals(mode) || "embedded".equals(mode) || "external".equals(mode))) { LOGGER.error("Database mode not specified. Expected values are 'server', 'embedded', or 'external'"); } if (dbServer != null || "embedded".equals(mode) || "external".equals(mode)) { return; } final String[] args = new String[] { "-tcp", "-tcpPort", String.valueOf(port), "-tcpAllowOthers", }; try { LOGGER.info("Attempting to start database service"); dbServer = Server.createTcpServer(args).start(); LOGGER.info("Database service started"); } catch (SQLException e) { LOGGER.error("Unable to start database service: " + e.getMessage()); stopDbServer(); } }
[ "private", "void", "startDbServer", "(", ")", "{", "final", "String", "mode", "=", "Config", ".", "getInstance", "(", ")", ".", "getProperty", "(", "Config", ".", "AlpineKey", ".", "DATABASE_MODE", ")", ";", "final", "int", "port", "=", "Config", ".", "g...
Starts the H2 database engine if the database mode is set to 'server'
[ "Starts", "the", "H2", "database", "engine", "if", "the", "database", "mode", "is", "set", "to", "server" ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/PersistenceInitializer.java#L56-L80
136,462
stevespringett/Alpine
alpine/src/main/java/alpine/Config.java
Config.init
private void init() { if (properties != null) { return; } LOGGER.info("Initializing Configuration"); properties = new Properties(); final String alpineAppProp = PathUtil.resolve(System.getProperty(ALPINE_APP_PROP)); if (StringUtils.isNotBlank(alpineAppProp)) { LOGGER.info("Loading application properties from " + alpineAppProp); try (InputStream fileInputStream = Files.newInputStream((new File(alpineAppProp)).toPath())) { properties.load(fileInputStream); } catch (FileNotFoundException e) { LOGGER.error("Could not find property file " + alpineAppProp); } catch (IOException e) { LOGGER.error("Unable to load " + alpineAppProp); } } else { LOGGER.info("System property " + ALPINE_APP_PROP + " not specified"); LOGGER.info("Loading " + PROP_FILE + " from classpath"); try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROP_FILE)) { properties.load(in); } catch (IOException e) { LOGGER.error("Unable to load " + PROP_FILE); } } if (properties.size() == 0) { LOGGER.error("A fatal error occurred loading application properties. Please correct the issue and restart the application."); } alpineVersionProperties = new Properties(); try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(ALPINE_VERSION_PROP_FILE)) { alpineVersionProperties.load(in); } catch (IOException e) { LOGGER.error("Unable to load " + ALPINE_VERSION_PROP_FILE); } if (alpineVersionProperties.size() == 0) { LOGGER.error("A fatal error occurred loading Alpine version information. Please correct the issue and restart the application."); } applicationVersionProperties = new Properties(); try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(APPLICATION_VERSION_PROP_FILE)) { applicationVersionProperties.load(in); } catch (IOException e) { LOGGER.error("Unable to load " + APPLICATION_VERSION_PROP_FILE); } if (applicationVersionProperties.size() == 0) { LOGGER.error("A fatal error occurred loading application version information. Please correct the issue and restart the application."); } }
java
private void init() { if (properties != null) { return; } LOGGER.info("Initializing Configuration"); properties = new Properties(); final String alpineAppProp = PathUtil.resolve(System.getProperty(ALPINE_APP_PROP)); if (StringUtils.isNotBlank(alpineAppProp)) { LOGGER.info("Loading application properties from " + alpineAppProp); try (InputStream fileInputStream = Files.newInputStream((new File(alpineAppProp)).toPath())) { properties.load(fileInputStream); } catch (FileNotFoundException e) { LOGGER.error("Could not find property file " + alpineAppProp); } catch (IOException e) { LOGGER.error("Unable to load " + alpineAppProp); } } else { LOGGER.info("System property " + ALPINE_APP_PROP + " not specified"); LOGGER.info("Loading " + PROP_FILE + " from classpath"); try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROP_FILE)) { properties.load(in); } catch (IOException e) { LOGGER.error("Unable to load " + PROP_FILE); } } if (properties.size() == 0) { LOGGER.error("A fatal error occurred loading application properties. Please correct the issue and restart the application."); } alpineVersionProperties = new Properties(); try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(ALPINE_VERSION_PROP_FILE)) { alpineVersionProperties.load(in); } catch (IOException e) { LOGGER.error("Unable to load " + ALPINE_VERSION_PROP_FILE); } if (alpineVersionProperties.size() == 0) { LOGGER.error("A fatal error occurred loading Alpine version information. Please correct the issue and restart the application."); } applicationVersionProperties = new Properties(); try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(APPLICATION_VERSION_PROP_FILE)) { applicationVersionProperties.load(in); } catch (IOException e) { LOGGER.error("Unable to load " + APPLICATION_VERSION_PROP_FILE); } if (applicationVersionProperties.size() == 0) { LOGGER.error("A fatal error occurred loading application version information. Please correct the issue and restart the application."); } }
[ "private", "void", "init", "(", ")", "{", "if", "(", "properties", "!=", "null", ")", "{", "return", ";", "}", "LOGGER", ".", "info", "(", "\"Initializing Configuration\"", ")", ";", "properties", "=", "new", "Properties", "(", ")", ";", "final", "String...
Initialize the Config object. This method should only be called once.
[ "Initialize", "the", "Config", "object", ".", "This", "method", "should", "only", "be", "called", "once", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/Config.java#L156-L206
136,463
stevespringett/Alpine
alpine/src/main/java/alpine/Config.java
Config.getPropertyFromEnvironment
private String getPropertyFromEnvironment(Key key) { final String envVariable = key.getPropertyName().toUpperCase().replace(".", "_"); try { return StringUtils.trimToNull(System.getenv(envVariable)); } catch (SecurityException e) { LOGGER.warn("A security exception prevented access to the environment variable. Using defaults."); } catch (NullPointerException e) { // Do nothing. The key was not specified in an environment variable. Continue along. } return null; }
java
private String getPropertyFromEnvironment(Key key) { final String envVariable = key.getPropertyName().toUpperCase().replace(".", "_"); try { return StringUtils.trimToNull(System.getenv(envVariable)); } catch (SecurityException e) { LOGGER.warn("A security exception prevented access to the environment variable. Using defaults."); } catch (NullPointerException e) { // Do nothing. The key was not specified in an environment variable. Continue along. } return null; }
[ "private", "String", "getPropertyFromEnvironment", "(", "Key", "key", ")", "{", "final", "String", "envVariable", "=", "key", ".", "getPropertyName", "(", ")", ".", "toUpperCase", "(", ")", ".", "replace", "(", "\".\"", ",", "\"_\"", ")", ";", "try", "{", ...
Attempts to retrieve the key via environment variable. Property names are always upper case with periods replaced with underscores. alpine.worker.threads becomes ALPINE_WORKER_THREADS @param key the key to retrieve from environment @return the value of the key (if set), null otherwise. @since 1.4.3
[ "Attempts", "to", "retrieve", "the", "key", "via", "environment", "variable", ".", "Property", "names", "are", "always", "upper", "case", "with", "periods", "replaced", "with", "underscores", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/Config.java#L432-L442
136,464
stevespringett/Alpine
alpine/src/main/java/alpine/upgrade/UpgradeMetaProcessor.java
UpgradeMetaProcessor.hasUpgradeRan
public boolean hasUpgradeRan(final Class<? extends UpgradeItem> upgradeClass) throws SQLException { PreparedStatement statement = null; ResultSet results = null; try { statement = connection.prepareStatement("SELECT \"UPGRADECLASS\" FROM \"INSTALLEDUPGRADES\" WHERE \"UPGRADECLASS\" = ?"); statement.setString(1, upgradeClass.getCanonicalName()); results = statement.executeQuery(); return results.next(); } finally { DbUtil.close(results); DbUtil.close(statement); //DbUtil.close(connection); // do not close connection } }
java
public boolean hasUpgradeRan(final Class<? extends UpgradeItem> upgradeClass) throws SQLException { PreparedStatement statement = null; ResultSet results = null; try { statement = connection.prepareStatement("SELECT \"UPGRADECLASS\" FROM \"INSTALLEDUPGRADES\" WHERE \"UPGRADECLASS\" = ?"); statement.setString(1, upgradeClass.getCanonicalName()); results = statement.executeQuery(); return results.next(); } finally { DbUtil.close(results); DbUtil.close(statement); //DbUtil.close(connection); // do not close connection } }
[ "public", "boolean", "hasUpgradeRan", "(", "final", "Class", "<", "?", "extends", "UpgradeItem", ">", "upgradeClass", ")", "throws", "SQLException", "{", "PreparedStatement", "statement", "=", "null", ";", "ResultSet", "results", "=", "null", ";", "try", "{", ...
Determines if the specified upgrade already has a record of being executed previously or not. @param upgradeClass the class to check fi an upgrade has previously executed @return true if already executed, false if not @throws SQLException a SQLException @since 1.2.0
[ "Determines", "if", "the", "specified", "upgrade", "already", "has", "a", "record", "of", "being", "executed", "previously", "or", "not", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/upgrade/UpgradeMetaProcessor.java#L59-L72
136,465
stevespringett/Alpine
alpine/src/main/java/alpine/upgrade/UpgradeMetaProcessor.java
UpgradeMetaProcessor.installUpgrade
public void installUpgrade(final Class<? extends UpgradeItem> upgradeClass, final long startTime, final long endTime) throws SQLException { PreparedStatement statement = null; try { statement = connection.prepareStatement("INSERT INTO \"INSTALLEDUPGRADES\" (\"UPGRADECLASS\", \"STARTTIME\", \"ENDTIME\") VALUES (?, ?, ?)"); statement.setString(1, upgradeClass.getCanonicalName()); statement.setTimestamp(2, new Timestamp(startTime)); statement.setTimestamp(3, new Timestamp(endTime)); statement.executeUpdate(); connection.commit(); LOGGER.debug("Added: " + upgradeClass.getCanonicalName() + " to UpgradeMetaProcessor table (Starttime: " + startTime + "; Endtime: " + endTime + ")"); } finally { DbUtil.close(statement); //DbUtil.close(connection); // do not close connection } }
java
public void installUpgrade(final Class<? extends UpgradeItem> upgradeClass, final long startTime, final long endTime) throws SQLException { PreparedStatement statement = null; try { statement = connection.prepareStatement("INSERT INTO \"INSTALLEDUPGRADES\" (\"UPGRADECLASS\", \"STARTTIME\", \"ENDTIME\") VALUES (?, ?, ?)"); statement.setString(1, upgradeClass.getCanonicalName()); statement.setTimestamp(2, new Timestamp(startTime)); statement.setTimestamp(3, new Timestamp(endTime)); statement.executeUpdate(); connection.commit(); LOGGER.debug("Added: " + upgradeClass.getCanonicalName() + " to UpgradeMetaProcessor table (Starttime: " + startTime + "; Endtime: " + endTime + ")"); } finally { DbUtil.close(statement); //DbUtil.close(connection); // do not close connection } }
[ "public", "void", "installUpgrade", "(", "final", "Class", "<", "?", "extends", "UpgradeItem", ">", "upgradeClass", ",", "final", "long", "startTime", ",", "final", "long", "endTime", ")", "throws", "SQLException", "{", "PreparedStatement", "statement", "=", "nu...
Documents a record in the database for the specified class indicating it has been executed. @param upgradeClass the name of the upgrade class @param startTime the time (in millis) of the execution @param endTime the time (in millis) the execution completed @throws SQLException a SQLException @since 1.2.0
[ "Documents", "a", "record", "in", "the", "database", "for", "the", "specified", "class", "indicating", "it", "has", "been", "executed", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/upgrade/UpgradeMetaProcessor.java#L82-L97
136,466
stevespringett/Alpine
alpine/src/main/java/alpine/upgrade/UpgradeMetaProcessor.java
UpgradeMetaProcessor.getSchemaVersion
public VersionComparator getSchemaVersion() { PreparedStatement statement = null; ResultSet results = null; try { statement = connection.prepareStatement("SELECT \"VERSION\" FROM \"SCHEMAVERSION\""); results = statement.executeQuery(); if (results.next()) { return new VersionComparator(results.getString(1)); } } catch (SQLException e) { // throw it away } finally { DbUtil.close(results); DbUtil.close(statement); //DbUtil.close(connection); // do not close connection } return null; }
java
public VersionComparator getSchemaVersion() { PreparedStatement statement = null; ResultSet results = null; try { statement = connection.prepareStatement("SELECT \"VERSION\" FROM \"SCHEMAVERSION\""); results = statement.executeQuery(); if (results.next()) { return new VersionComparator(results.getString(1)); } } catch (SQLException e) { // throw it away } finally { DbUtil.close(results); DbUtil.close(statement); //DbUtil.close(connection); // do not close connection } return null; }
[ "public", "VersionComparator", "getSchemaVersion", "(", ")", "{", "PreparedStatement", "statement", "=", "null", ";", "ResultSet", "results", "=", "null", ";", "try", "{", "statement", "=", "connection", ".", "prepareStatement", "(", "\"SELECT \\\"VERSION\\\" FROM \\\...
Retrieves the current schema version documented in the database. @return A VersionComparator of the schema version @since 1.2.0
[ "Retrieves", "the", "current", "schema", "version", "documented", "in", "the", "database", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/upgrade/UpgradeMetaProcessor.java#L104-L122
136,467
stevespringett/Alpine
alpine/src/main/java/alpine/upgrade/UpgradeMetaProcessor.java
UpgradeMetaProcessor.updateSchemaVersion
public void updateSchemaVersion(VersionComparator version) throws SQLException { PreparedStatement statement = null; PreparedStatement updateStatement = null; ResultSet results = null; try { statement = connection.prepareStatement("SELECT \"VERSION\" FROM \"SCHEMAVERSION\""); results = statement.executeQuery(); if (results.next()) { final VersionComparator currentVersion = new VersionComparator(results.getString(1)); if (version == null || currentVersion.isNewerThan(version)) { return; } updateStatement = connection.prepareStatement("UPDATE \"SCHEMAVERSION\" SET \"VERSION\" = ?"); } else { // Does not exist. Populate schema table with current running version version = new VersionComparator(Config.getInstance().getApplicationVersion()); updateStatement = connection.prepareStatement("INSERT INTO \"SCHEMAVERSION\" (\"VERSION\") VALUES (?)"); } LOGGER.debug("Updating database schema to: " + version.toString()); updateStatement.setString(1, version.toString()); updateStatement.executeUpdate(); connection.commit(); } finally { DbUtil.close(results); DbUtil.close(updateStatement); DbUtil.close(statement); //DbUtil.close(connection); // do not close connection } }
java
public void updateSchemaVersion(VersionComparator version) throws SQLException { PreparedStatement statement = null; PreparedStatement updateStatement = null; ResultSet results = null; try { statement = connection.prepareStatement("SELECT \"VERSION\" FROM \"SCHEMAVERSION\""); results = statement.executeQuery(); if (results.next()) { final VersionComparator currentVersion = new VersionComparator(results.getString(1)); if (version == null || currentVersion.isNewerThan(version)) { return; } updateStatement = connection.prepareStatement("UPDATE \"SCHEMAVERSION\" SET \"VERSION\" = ?"); } else { // Does not exist. Populate schema table with current running version version = new VersionComparator(Config.getInstance().getApplicationVersion()); updateStatement = connection.prepareStatement("INSERT INTO \"SCHEMAVERSION\" (\"VERSION\") VALUES (?)"); } LOGGER.debug("Updating database schema to: " + version.toString()); updateStatement.setString(1, version.toString()); updateStatement.executeUpdate(); connection.commit(); } finally { DbUtil.close(results); DbUtil.close(updateStatement); DbUtil.close(statement); //DbUtil.close(connection); // do not close connection } }
[ "public", "void", "updateSchemaVersion", "(", "VersionComparator", "version", ")", "throws", "SQLException", "{", "PreparedStatement", "statement", "=", "null", ";", "PreparedStatement", "updateStatement", "=", "null", ";", "ResultSet", "results", "=", "null", ";", ...
Updates the schema version in the database. @param version the version to set the schema to @throws SQLException a SQLException @since 1.2.0
[ "Updates", "the", "schema", "version", "in", "the", "database", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/upgrade/UpgradeMetaProcessor.java#L130-L161
136,468
stevespringett/Alpine
alpine/src/main/java/alpine/filters/ContentSecurityPolicyFilter.java
ContentSecurityPolicyFilter.getValue
private String getValue(FilterConfig filterConfig, String initParam, String variable) { final String value = filterConfig.getInitParameter(initParam); if (StringUtils.isNotBlank(value)) { return value; } else { return variable; } }
java
private String getValue(FilterConfig filterConfig, String initParam, String variable) { final String value = filterConfig.getInitParameter(initParam); if (StringUtils.isNotBlank(value)) { return value; } else { return variable; } }
[ "private", "String", "getValue", "(", "FilterConfig", "filterConfig", ",", "String", "initParam", ",", "String", "variable", ")", "{", "final", "String", "value", "=", "filterConfig", ".", "getInitParameter", "(", "initParam", ")", ";", "if", "(", "StringUtils",...
Returns the value of the initParam. @param filterConfig a FilterConfig instance @param initParam the name of the init parameter @param variable the variable to use if the init param was not defined @return a String
[ "Returns", "the", "value", "of", "the", "initParam", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/ContentSecurityPolicyFilter.java#L174-L181
136,469
stevespringett/Alpine
alpine/src/main/java/alpine/filters/ContentSecurityPolicyFilter.java
ContentSecurityPolicyFilter.formatHeader
private String formatHeader() { final StringBuilder sb = new StringBuilder(); getStringFromValue(sb, "default-src", defaultSrc); getStringFromValue(sb, "script-src", scriptSrc); getStringFromValue(sb, "style-src", styleSrc); getStringFromValue(sb, "img-src", imgSrc); getStringFromValue(sb, "connect-src", connectSrc); getStringFromValue(sb, "font-src", fontSrc); getStringFromValue(sb, "object-src", objectSrc); getStringFromValue(sb, "media-src", mediaSrc); getStringFromValue(sb, "frame-src", frameSrc); getStringFromValue(sb, "sandbox", sandbox); getStringFromValue(sb, "report-uri", reportUri); getStringFromValue(sb, "child-src", childSrc); getStringFromValue(sb, "form-action", formAction); getStringFromValue(sb, "frame-ancestors", frameAncestors); getStringFromValue(sb, "plugin-types", pluginTypes); return sb.toString().replaceAll("(\\[|\\])", "").trim(); }
java
private String formatHeader() { final StringBuilder sb = new StringBuilder(); getStringFromValue(sb, "default-src", defaultSrc); getStringFromValue(sb, "script-src", scriptSrc); getStringFromValue(sb, "style-src", styleSrc); getStringFromValue(sb, "img-src", imgSrc); getStringFromValue(sb, "connect-src", connectSrc); getStringFromValue(sb, "font-src", fontSrc); getStringFromValue(sb, "object-src", objectSrc); getStringFromValue(sb, "media-src", mediaSrc); getStringFromValue(sb, "frame-src", frameSrc); getStringFromValue(sb, "sandbox", sandbox); getStringFromValue(sb, "report-uri", reportUri); getStringFromValue(sb, "child-src", childSrc); getStringFromValue(sb, "form-action", formAction); getStringFromValue(sb, "frame-ancestors", frameAncestors); getStringFromValue(sb, "plugin-types", pluginTypes); return sb.toString().replaceAll("(\\[|\\])", "").trim(); }
[ "private", "String", "formatHeader", "(", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "getStringFromValue", "(", "sb", ",", "\"default-src\"", ",", "defaultSrc", ")", ";", "getStringFromValue", "(", "sb", ",", "\"scrip...
Formats a CSP header @return a String representation of CSP header
[ "Formats", "a", "CSP", "header" ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/ContentSecurityPolicyFilter.java#L187-L205
136,470
stevespringett/Alpine
alpine/src/main/java/alpine/filters/ContentSecurityPolicyFilter.java
ContentSecurityPolicyFilter.getStringFromValue
private void getStringFromValue(final StringBuilder builder, final String directive, final String value) { if (value != null) { builder.append(directive).append(" ").append(value).append(";"); } }
java
private void getStringFromValue(final StringBuilder builder, final String directive, final String value) { if (value != null) { builder.append(directive).append(" ").append(value).append(";"); } }
[ "private", "void", "getStringFromValue", "(", "final", "StringBuilder", "builder", ",", "final", "String", "directive", ",", "final", "String", "value", ")", "{", "if", "(", "value", "!=", "null", ")", "{", "builder", ".", "append", "(", "directive", ")", ...
Assists in the formatting of a single CSP directive. @param builder a StringBuilder object @param directive a CSP directive @param value the value of the CSP directive
[ "Assists", "in", "the", "formatting", "of", "a", "single", "CSP", "directive", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/ContentSecurityPolicyFilter.java#L213-L217
136,471
stevespringett/Alpine
alpine/src/main/java/alpine/auth/Authenticator.java
Authenticator.authenticate
public Principal authenticate() throws AlpineAuthenticationException { LOGGER.debug("Attempting to authenticate user: " + username); final ManagedUserAuthenticationService userService = new ManagedUserAuthenticationService(username, password); try{ final Principal principal = userService.authenticate(); if (principal != null) { return principal; } }catch(AlpineAuthenticationException e){ // If LDAP is enabled, a second attempt to authenticate the credentials will be // made against LDAP so we skip this validation exception. However, if the ManagedUser does exist, // return the correct error if (!LDAP_ENABLED || e.getCauseType() != AlpineAuthenticationException.CauseType.INVALID_CREDENTIALS) { throw e; } } if (LDAP_ENABLED) { final LdapAuthenticationService ldapService = new LdapAuthenticationService(username, password); return ldapService.authenticate(); } // This should never happen, but do not want to return null throw new AlpineAuthenticationException(AlpineAuthenticationException.CauseType.OTHER); }
java
public Principal authenticate() throws AlpineAuthenticationException { LOGGER.debug("Attempting to authenticate user: " + username); final ManagedUserAuthenticationService userService = new ManagedUserAuthenticationService(username, password); try{ final Principal principal = userService.authenticate(); if (principal != null) { return principal; } }catch(AlpineAuthenticationException e){ // If LDAP is enabled, a second attempt to authenticate the credentials will be // made against LDAP so we skip this validation exception. However, if the ManagedUser does exist, // return the correct error if (!LDAP_ENABLED || e.getCauseType() != AlpineAuthenticationException.CauseType.INVALID_CREDENTIALS) { throw e; } } if (LDAP_ENABLED) { final LdapAuthenticationService ldapService = new LdapAuthenticationService(username, password); return ldapService.authenticate(); } // This should never happen, but do not want to return null throw new AlpineAuthenticationException(AlpineAuthenticationException.CauseType.OTHER); }
[ "public", "Principal", "authenticate", "(", ")", "throws", "AlpineAuthenticationException", "{", "LOGGER", ".", "debug", "(", "\"Attempting to authenticate user: \"", "+", "username", ")", ";", "final", "ManagedUserAuthenticationService", "userService", "=", "new", "Manag...
Attempts to authenticate the credentials internally first and if not successful, checks to see if LDAP is enabled or not. If enabled, a second attempt to authenticate the credentials will be made, but this time against the directory service. @return a Principal upon successful authentication @throws AlpineAuthenticationException upon authentication failure @since 1.0.0
[ "Attempts", "to", "authenticate", "the", "credentials", "internally", "first", "and", "if", "not", "successful", "checks", "to", "see", "if", "LDAP", "is", "enabled", "or", "not", ".", "If", "enabled", "a", "second", "attempt", "to", "authenticate", "the", "...
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/auth/Authenticator.java#L60-L82
136,472
stevespringett/Alpine
alpine/src/main/java/alpine/util/SystemUtil.java
SystemUtil.init
private static void init() { if (hasInitialized) { return; } final String osName = System.getProperty("os.name"); if (osName != null) { final String osNameLower = osName.toLowerCase(); isWindows = osNameLower.contains("windows"); isMac = osNameLower.contains("mac os x") || osNameLower.contains("darwin"); isLinux = osNameLower.contains("nux"); isUnix = osNameLower.contains("nix") || osNameLower.contains("nux"); isSolaris = osNameLower.contains("sunos") || osNameLower.contains("solaris"); } lineEnder = isWindows ? "\r\n" : "\n"; final String model = System.getProperty("sun.arch.data.model"); // sun.arch.data.model=32 // 32 bit JVM // sun.arch.data.model=64 // 64 bit JVM if (StringUtils.isBlank(model)) { bit32 = true; bit64 = false; } else if ("64".equals(model)) { bit32 = false; bit64 = true; } else { bit32 = true; bit64 = false; } }
java
private static void init() { if (hasInitialized) { return; } final String osName = System.getProperty("os.name"); if (osName != null) { final String osNameLower = osName.toLowerCase(); isWindows = osNameLower.contains("windows"); isMac = osNameLower.contains("mac os x") || osNameLower.contains("darwin"); isLinux = osNameLower.contains("nux"); isUnix = osNameLower.contains("nix") || osNameLower.contains("nux"); isSolaris = osNameLower.contains("sunos") || osNameLower.contains("solaris"); } lineEnder = isWindows ? "\r\n" : "\n"; final String model = System.getProperty("sun.arch.data.model"); // sun.arch.data.model=32 // 32 bit JVM // sun.arch.data.model=64 // 64 bit JVM if (StringUtils.isBlank(model)) { bit32 = true; bit64 = false; } else if ("64".equals(model)) { bit32 = false; bit64 = true; } else { bit32 = true; bit64 = false; } }
[ "private", "static", "void", "init", "(", ")", "{", "if", "(", "hasInitialized", ")", "{", "return", ";", "}", "final", "String", "osName", "=", "System", ".", "getProperty", "(", "\"os.name\"", ")", ";", "if", "(", "osName", "!=", "null", ")", "{", ...
Initialize static variables.
[ "Initialize", "static", "variables", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/util/SystemUtil.java#L285-L318
136,473
stevespringett/Alpine
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
AbstractAlpineQueryManager.advancePagination
public void advancePagination() { if (pagination.isPaginated()) { pagination = new Pagination(pagination.getStrategy(), pagination.getOffset() + pagination.getLimit(), pagination.getLimit()); } }
java
public void advancePagination() { if (pagination.isPaginated()) { pagination = new Pagination(pagination.getStrategy(), pagination.getOffset() + pagination.getLimit(), pagination.getLimit()); } }
[ "public", "void", "advancePagination", "(", ")", "{", "if", "(", "pagination", ".", "isPaginated", "(", ")", ")", "{", "pagination", "=", "new", "Pagination", "(", "pagination", ".", "getStrategy", "(", ")", ",", "pagination", ".", "getOffset", "(", ")", ...
Advances the pagination based on the previous pagination settings. This is purely a convenience method as the method by itself is not aware of the query being executed, the result count, etc. @since 1.0.0
[ "Advances", "the", "pagination", "based", "on", "the", "previous", "pagination", "settings", ".", "This", "is", "purely", "a", "convenience", "method", "as", "the", "method", "by", "itself", "is", "not", "aware", "of", "the", "query", "being", "executed", "t...
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java#L221-L225
136,474
stevespringett/Alpine
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
AbstractAlpineQueryManager.decorate
public Query decorate(final Query query) { // Clear the result to fetch if previously specified (i.e. by getting count) query.setResult(null); if (pagination != null && pagination.isPaginated()) { final long begin = pagination.getOffset(); final long end = begin + pagination.getLimit(); query.setRange(begin, end); } if (orderBy != null && RegexSequence.Pattern.ALPHA_NUMERIC.matcher(orderBy).matches() && orderDirection != OrderDirection.UNSPECIFIED) { // Check to see if the specified orderBy field is defined in the class being queried. boolean found = false; final org.datanucleus.store.query.Query iq = ((JDOQuery) query).getInternalQuery(); for (final Field field: iq.getCandidateClass().getDeclaredFields()) { if (orderBy.equals(field.getName())) { found = true; break; } } if (found) { query.setOrdering(orderBy + " " + orderDirection.name().toLowerCase()); } } return query; }
java
public Query decorate(final Query query) { // Clear the result to fetch if previously specified (i.e. by getting count) query.setResult(null); if (pagination != null && pagination.isPaginated()) { final long begin = pagination.getOffset(); final long end = begin + pagination.getLimit(); query.setRange(begin, end); } if (orderBy != null && RegexSequence.Pattern.ALPHA_NUMERIC.matcher(orderBy).matches() && orderDirection != OrderDirection.UNSPECIFIED) { // Check to see if the specified orderBy field is defined in the class being queried. boolean found = false; final org.datanucleus.store.query.Query iq = ((JDOQuery) query).getInternalQuery(); for (final Field field: iq.getCandidateClass().getDeclaredFields()) { if (orderBy.equals(field.getName())) { found = true; break; } } if (found) { query.setOrdering(orderBy + " " + orderDirection.name().toLowerCase()); } } return query; }
[ "public", "Query", "decorate", "(", "final", "Query", "query", ")", "{", "// Clear the result to fetch if previously specified (i.e. by getting count)", "query", ".", "setResult", "(", "null", ")", ";", "if", "(", "pagination", "!=", "null", "&&", "pagination", ".", ...
Given a query, this method will decorate that query with pagination, ordering, and sorting direction. Specific checks are performed to ensure the execution of the query is capable of being paged and that ordering can be securely performed. @param query the JDO Query object to execute @return a Collection of objects @since 1.0.0
[ "Given", "a", "query", "this", "method", "will", "decorate", "that", "query", "with", "pagination", "ordering", "and", "sorting", "direction", ".", "Specific", "checks", "are", "performed", "to", "ensure", "the", "execution", "of", "the", "query", "is", "capab...
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java#L235-L258
136,475
stevespringett/Alpine
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
AbstractAlpineQueryManager.persist
@SuppressWarnings("unchecked") public <T> T persist(T object) { pm.currentTransaction().begin(); pm.makePersistent(object); pm.currentTransaction().commit(); pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); pm.refresh(object); return object; }
java
@SuppressWarnings("unchecked") public <T> T persist(T object) { pm.currentTransaction().begin(); pm.makePersistent(object); pm.currentTransaction().commit(); pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); pm.refresh(object); return object; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "T", "persist", "(", "T", "object", ")", "{", "pm", ".", "currentTransaction", "(", ")", ".", "begin", "(", ")", ";", "pm", ".", "makePersistent", "(", "object", ")", ";", "...
Persists the specified PersistenceCapable object. @param object a PersistenceCapable object @param <T> the type to return @return the persisted object
[ "Persists", "the", "specified", "PersistenceCapable", "object", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java#L393-L401
136,476
stevespringett/Alpine
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
AbstractAlpineQueryManager.persist
@SuppressWarnings("unchecked") public <T> T[] persist(T... pcs) { pm.currentTransaction().begin(); pm.makePersistentAll(pcs); pm.currentTransaction().commit(); pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); pm.refreshAll(pcs); return pcs; }
java
@SuppressWarnings("unchecked") public <T> T[] persist(T... pcs) { pm.currentTransaction().begin(); pm.makePersistentAll(pcs); pm.currentTransaction().commit(); pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); pm.refreshAll(pcs); return pcs; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "T", "[", "]", "persist", "(", "T", "...", "pcs", ")", "{", "pm", ".", "currentTransaction", "(", ")", ".", "begin", "(", ")", ";", "pm", ".", "makePersistentAll", "(", "pcs...
Persists the specified PersistenceCapable objects. @param pcs an array of PersistenceCapable objects @param <T> the type to return @return the persisted objects
[ "Persists", "the", "specified", "PersistenceCapable", "objects", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java#L409-L417
136,477
stevespringett/Alpine
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
AbstractAlpineQueryManager.detach
public <T> T detach(Class<T> clazz, Object id) { pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); return pm.detachCopy(pm.getObjectById(clazz, id)); }
java
public <T> T detach(Class<T> clazz, Object id) { pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); return pm.detachCopy(pm.getObjectById(clazz, id)); }
[ "public", "<", "T", ">", "T", "detach", "(", "Class", "<", "T", ">", "clazz", ",", "Object", "id", ")", "{", "pm", ".", "getFetchPlan", "(", ")", ".", "setDetachmentOptions", "(", "FetchPlan", ".", "DETACH_LOAD_FIELDS", ")", ";", "return", "pm", ".", ...
Refreshes and detaches an object by its ID. @param <T> A type parameter. This type will be returned @param clazz the persistence class to retrive the ID for @param id the object id to retrieve @return an object of the specified type @since 1.3.0
[ "Refreshes", "and", "detaches", "an", "object", "by", "its", "ID", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java#L465-L468
136,478
stevespringett/Alpine
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
AbstractAlpineQueryManager.getObjectById
public <T> T getObjectById(Class<T> clazz, Object id) { return pm.getObjectById(clazz, id); }
java
public <T> T getObjectById(Class<T> clazz, Object id) { return pm.getObjectById(clazz, id); }
[ "public", "<", "T", ">", "T", "getObjectById", "(", "Class", "<", "T", ">", "clazz", ",", "Object", "id", ")", "{", "return", "pm", ".", "getObjectById", "(", "clazz", ",", "id", ")", ";", "}" ]
Retrieves an object by its ID. @param <T> A type parameter. This type will be returned @param clazz the persistence class to retrive the ID for @param id the object id to retrieve @return an object of the specified type @since 1.0.0
[ "Retrieves", "an", "object", "by", "its", "ID", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java#L503-L505
136,479
stevespringett/Alpine
alpine/src/main/java/alpine/filters/WhitelistUrlFilter.java
WhitelistUrlFilter.init
public void init(final FilterConfig filterConfig) { final String allowParam = filterConfig.getInitParameter("allowUrls"); if (StringUtils.isNotBlank(allowParam)) { this.allowUrls = allowParam.split(","); } }
java
public void init(final FilterConfig filterConfig) { final String allowParam = filterConfig.getInitParameter("allowUrls"); if (StringUtils.isNotBlank(allowParam)) { this.allowUrls = allowParam.split(","); } }
[ "public", "void", "init", "(", "final", "FilterConfig", "filterConfig", ")", "{", "final", "String", "allowParam", "=", "filterConfig", ".", "getInitParameter", "(", "\"allowUrls\"", ")", ";", "if", "(", "StringUtils", ".", "isNotBlank", "(", "allowParam", ")", ...
Initialize "allowUrls" parameter from web.xml. @param filterConfig A filter configuration object used by a servlet container to pass information to a filter during initialization.
[ "Initialize", "allowUrls", "parameter", "from", "web", ".", "xml", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/WhitelistUrlFilter.java#L72-L79
136,480
stevespringett/Alpine
alpine/src/main/java/alpine/filters/WhitelistUrlFilter.java
WhitelistUrlFilter.doFilter
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse res = (HttpServletResponse) response; final String requestUri = req.getRequestURI(); if (requestUri != null) { boolean allowed = false; for (final String url: allowUrls) { if (requestUri.equals("/")) { if (url.trim().equals("/")) { allowed = true; } } else if (requestUri.startsWith(url.trim())) { allowed = true; } } if (!allowed) { res.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } chain.doFilter(request, response); }
java
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse res = (HttpServletResponse) response; final String requestUri = req.getRequestURI(); if (requestUri != null) { boolean allowed = false; for (final String url: allowUrls) { if (requestUri.equals("/")) { if (url.trim().equals("/")) { allowed = true; } } else if (requestUri.startsWith(url.trim())) { allowed = true; } } if (!allowed) { res.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } chain.doFilter(request, response); }
[ "public", "void", "doFilter", "(", "final", "ServletRequest", "request", ",", "final", "ServletResponse", "response", ",", "final", "FilterChain", "chain", ")", "throws", "IOException", ",", "ServletException", "{", "final", "HttpServletRequest", "req", "=", "(", ...
Check for allowed URLs being requested. @param request The request object. @param response The response object. @param chain Refers to the {@code FilterChain} object to pass control to the next {@code Filter}. @throws IOException a IOException @throws ServletException a ServletException
[ "Check", "for", "allowed", "URLs", "being", "requested", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/WhitelistUrlFilter.java#L90-L114
136,481
stevespringett/Alpine
example/src/main/java/com/example/resources/v1/LoginResource.java
LoginResource.validateCredentials
@POST @Produces(MediaType.TEXT_PLAIN) @ApiOperation( value = "Assert login credentials", notes = "Upon a successful login, a JWT will be returned in the response. This functionality requires authentication to be enabled.", response = String.class ) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 401, message = "Unauthorized") }) @AuthenticationNotRequired public Response validateCredentials(@FormParam("username") String username, @FormParam("password") String password) { final Authenticator auth = new Authenticator(username, password); try { final Principal principal = auth.authenticate(); if (principal != null) { LOGGER.info(SecurityMarkers.SECURITY_AUDIT, "Login succeeded (username: " + username + " / ip address: " + super.getRemoteAddress() + " / agent: " + super.getUserAgent() + ")"); final JsonWebToken jwt = new JsonWebToken(); final String token = jwt.createToken(principal); return Response.ok(token).build(); } } catch (AuthenticationException e) { LOGGER.warn(SecurityMarkers.SECURITY_AUDIT, "Unauthorized login attempt (username: " + username + " / ip address: " + super.getRemoteAddress() + " / agent: " + super.getUserAgent() + ")"); } return Response.status(Response.Status.UNAUTHORIZED).build(); }
java
@POST @Produces(MediaType.TEXT_PLAIN) @ApiOperation( value = "Assert login credentials", notes = "Upon a successful login, a JWT will be returned in the response. This functionality requires authentication to be enabled.", response = String.class ) @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), @ApiResponse(code = 401, message = "Unauthorized") }) @AuthenticationNotRequired public Response validateCredentials(@FormParam("username") String username, @FormParam("password") String password) { final Authenticator auth = new Authenticator(username, password); try { final Principal principal = auth.authenticate(); if (principal != null) { LOGGER.info(SecurityMarkers.SECURITY_AUDIT, "Login succeeded (username: " + username + " / ip address: " + super.getRemoteAddress() + " / agent: " + super.getUserAgent() + ")"); final JsonWebToken jwt = new JsonWebToken(); final String token = jwt.createToken(principal); return Response.ok(token).build(); } } catch (AuthenticationException e) { LOGGER.warn(SecurityMarkers.SECURITY_AUDIT, "Unauthorized login attempt (username: " + username + " / ip address: " + super.getRemoteAddress() + " / agent: " + super.getUserAgent() + ")"); } return Response.status(Response.Status.UNAUTHORIZED).build(); }
[ "@", "POST", "@", "Produces", "(", "MediaType", ".", "TEXT_PLAIN", ")", "@", "ApiOperation", "(", "value", "=", "\"Assert login credentials\"", ",", "notes", "=", "\"Upon a successful login, a JWT will be returned in the response. This functionality requires authentication to be ...
Processes login requests. @param username the asserted username @param password the asserted password @return a Response
[ "Processes", "login", "requests", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/example/src/main/java/com/example/resources/v1/LoginResource.java#L56-L87
136,482
stevespringett/Alpine
alpine/src/main/java/alpine/util/ByteUtil.java
ByteUtil.toBytes
public static byte[] toBytes(char[] chars) { final CharBuffer charBuffer = CharBuffer.wrap(chars); final ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer); final byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit()); Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data return bytes; }
java
public static byte[] toBytes(char[] chars) { final CharBuffer charBuffer = CharBuffer.wrap(chars); final ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer); final byte[] bytes = Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit()); Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data return bytes; }
[ "public", "static", "byte", "[", "]", "toBytes", "(", "char", "[", "]", "chars", ")", "{", "final", "CharBuffer", "charBuffer", "=", "CharBuffer", ".", "wrap", "(", "chars", ")", ";", "final", "ByteBuffer", "byteBuffer", "=", "Charset", ".", "forName", "...
Converts a char array to a byte array without the use of Strings. http://stackoverflow.com/questions/5513144/converting-char-to-byte @param chars the characters to convert @return a byte array of the converted characters @since 1.0.0
[ "Converts", "a", "char", "array", "to", "a", "byte", "array", "without", "the", "use", "of", "Strings", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/util/ByteUtil.java#L47-L54
136,483
stevespringett/Alpine
alpine/src/main/java/alpine/filters/BlacklistUrlFilter.java
BlacklistUrlFilter.init
public void init(final FilterConfig filterConfig) { final String denyParam = filterConfig.getInitParameter("denyUrls"); if (StringUtils.isNotBlank(denyParam)) { this.denyUrls = denyParam.split(","); } final String ignoreParam = filterConfig.getInitParameter("ignoreUrls"); if (StringUtils.isNotBlank(ignoreParam)) { this.ignoreUrls = ignoreParam.split(","); } }
java
public void init(final FilterConfig filterConfig) { final String denyParam = filterConfig.getInitParameter("denyUrls"); if (StringUtils.isNotBlank(denyParam)) { this.denyUrls = denyParam.split(","); } final String ignoreParam = filterConfig.getInitParameter("ignoreUrls"); if (StringUtils.isNotBlank(ignoreParam)) { this.ignoreUrls = ignoreParam.split(","); } }
[ "public", "void", "init", "(", "final", "FilterConfig", "filterConfig", ")", "{", "final", "String", "denyParam", "=", "filterConfig", ".", "getInitParameter", "(", "\"denyUrls\"", ")", ";", "if", "(", "StringUtils", ".", "isNotBlank", "(", "denyParam", ")", "...
Initialize "deny" parameter from web.xml. @param filterConfig A filter configuration object used by a servlet container to pass information to a filter during initialization.
[ "Initialize", "deny", "parameter", "from", "web", ".", "xml", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/BlacklistUrlFilter.java#L77-L89
136,484
stevespringett/Alpine
alpine/src/main/java/alpine/filters/BlacklistUrlFilter.java
BlacklistUrlFilter.doFilter
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse res = (HttpServletResponse) response; final String requestUri = req.getRequestURI(); if (requestUri != null) { for (final String url: denyUrls) { if (requestUri.startsWith(url.trim())) { res.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } for (final String url: ignoreUrls) { if (requestUri.startsWith(url.trim())) { res.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } } chain.doFilter(request, response); }
java
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse res = (HttpServletResponse) response; final String requestUri = req.getRequestURI(); if (requestUri != null) { for (final String url: denyUrls) { if (requestUri.startsWith(url.trim())) { res.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } } for (final String url: ignoreUrls) { if (requestUri.startsWith(url.trim())) { res.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } } chain.doFilter(request, response); }
[ "public", "void", "doFilter", "(", "final", "ServletRequest", "request", ",", "final", "ServletResponse", "response", ",", "final", "FilterChain", "chain", ")", "throws", "IOException", ",", "ServletException", "{", "final", "HttpServletRequest", "req", "=", "(", ...
Check for denied or ignored URLs being requested. @param request The request object. @param response The response object. @param chain Refers to the {@code FilterChain} object to pass control to the next {@code Filter}. @throws IOException a IOException @throws ServletException a ServletException
[ "Check", "for", "denied", "or", "ignored", "URLs", "being", "requested", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/filters/BlacklistUrlFilter.java#L100-L122
136,485
stevespringett/Alpine
alpine/src/main/java/alpine/tasks/AlpineTaskScheduler.java
AlpineTaskScheduler.scheduleEvent
protected void scheduleEvent(final Event event, final long delay, final long period) { final Timer timer = new Timer(); timer.schedule(new ScheduleEvent().event(event), delay, period); timers.add(timer); }
java
protected void scheduleEvent(final Event event, final long delay, final long period) { final Timer timer = new Timer(); timer.schedule(new ScheduleEvent().event(event), delay, period); timers.add(timer); }
[ "protected", "void", "scheduleEvent", "(", "final", "Event", "event", ",", "final", "long", "delay", ",", "final", "long", "period", ")", "{", "final", "Timer", "timer", "=", "new", "Timer", "(", ")", ";", "timer", ".", "schedule", "(", "new", "ScheduleE...
Schedules a repeating Event. @param event the Event to schedule @param delay delay in milliseconds before task is to be executed. @param period time in milliseconds between successive task executions.
[ "Schedules", "a", "repeating", "Event", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/tasks/AlpineTaskScheduler.java#L46-L50
136,486
stevespringett/Alpine
alpine/src/main/java/alpine/resources/Pagination.java
Pagination.calculateStrategy
private void calculateStrategy(final Strategy strategy, final int o1, final int o2) { if (Strategy.OFFSET == strategy) { this.offset = o1; this.limit = o2; } else if (Strategy.PAGES == strategy) { this.offset = (o1 * o2) - o2; this.limit = o2; } }
java
private void calculateStrategy(final Strategy strategy, final int o1, final int o2) { if (Strategy.OFFSET == strategy) { this.offset = o1; this.limit = o2; } else if (Strategy.PAGES == strategy) { this.offset = (o1 * o2) - o2; this.limit = o2; } }
[ "private", "void", "calculateStrategy", "(", "final", "Strategy", "strategy", ",", "final", "int", "o1", ",", "final", "int", "o2", ")", "{", "if", "(", "Strategy", ".", "OFFSET", "==", "strategy", ")", "{", "this", ".", "offset", "=", "o1", ";", "this...
Determines the offset and limit based on pagination strategy. @param strategy the pagination strategy to use @param o1 the offset or page number to use @param o2 the number of results to limit a result-set to (aka, the size of the page)
[ "Determines", "the", "offset", "and", "limit", "based", "on", "pagination", "strategy", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/resources/Pagination.java#L72-L80
136,487
stevespringett/Alpine
alpine/src/main/java/alpine/resources/Pagination.java
Pagination.parseIntegerFromParam
private Integer parseIntegerFromParam(final String value, final int defaultValue) { try { return Integer.valueOf(value); } catch (NumberFormatException | NullPointerException e) { return defaultValue; } }
java
private Integer parseIntegerFromParam(final String value, final int defaultValue) { try { return Integer.valueOf(value); } catch (NumberFormatException | NullPointerException e) { return defaultValue; } }
[ "private", "Integer", "parseIntegerFromParam", "(", "final", "String", "value", ",", "final", "int", "defaultValue", ")", "{", "try", "{", "return", "Integer", ".", "valueOf", "(", "value", ")", ";", "}", "catch", "(", "NumberFormatException", "|", "NullPointe...
Parses a parameter to an Integer, defaulting to 0 upon any errors encountered. @param value the value to parse @param defaultValue the default value to use @return an Integer
[ "Parses", "a", "parameter", "to", "an", "Integer", "defaulting", "to", "0", "upon", "any", "errors", "encountered", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/resources/Pagination.java#L121-L127
136,488
stevespringett/Alpine
alpine/src/main/java/alpine/auth/ApiKeyGenerator.java
ApiKeyGenerator.generate
public static String generate(final int chars) { final SecureRandom secureRandom = new SecureRandom(); final char[] buff = new char[chars]; for (int i = 0; i < chars; ++i) { if (i % 10 == 0) { secureRandom.setSeed(secureRandom.nextLong()); } buff[i] = VALID_CHARACTERS[secureRandom.nextInt(VALID_CHARACTERS.length)]; } return new String(buff); }
java
public static String generate(final int chars) { final SecureRandom secureRandom = new SecureRandom(); final char[] buff = new char[chars]; for (int i = 0; i < chars; ++i) { if (i % 10 == 0) { secureRandom.setSeed(secureRandom.nextLong()); } buff[i] = VALID_CHARACTERS[secureRandom.nextInt(VALID_CHARACTERS.length)]; } return new String(buff); }
[ "public", "static", "String", "generate", "(", "final", "int", "chars", ")", "{", "final", "SecureRandom", "secureRandom", "=", "new", "SecureRandom", "(", ")", ";", "final", "char", "[", "]", "buff", "=", "new", "char", "[", "chars", "]", ";", "for", ...
Generates a cryptographically secure API key of the specified length. @param chars the length of the API key to generate @return a String representation of the API key
[ "Generates", "a", "cryptographically", "secure", "API", "key", "of", "the", "specified", "length", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/auth/ApiKeyGenerator.java#L50-L60
136,489
stevespringett/Alpine
alpine/src/main/java/alpine/util/VersionComparator.java
VersionComparator.parse
private int[] parse(String version) { final Matcher m = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)-?(SNAPSHOT)?\\.?(\\d*)?").matcher(version); if (!m.matches()) { throw new IllegalArgumentException("Malformed version string: " + version); } return new int[] {Integer.parseInt(m.group(1)), // major Integer.parseInt(m.group(2)), // minor Integer.parseInt(m.group(3)), // revision m.group(4) == null ? 0 // no SNAPSHOT suffix : m.group(5).isEmpty() ? 0 // "SNAPSHOT" : Integer.parseInt(m.group(5)), // "SNAPSHOT.123" }; }
java
private int[] parse(String version) { final Matcher m = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)-?(SNAPSHOT)?\\.?(\\d*)?").matcher(version); if (!m.matches()) { throw new IllegalArgumentException("Malformed version string: " + version); } return new int[] {Integer.parseInt(m.group(1)), // major Integer.parseInt(m.group(2)), // minor Integer.parseInt(m.group(3)), // revision m.group(4) == null ? 0 // no SNAPSHOT suffix : m.group(5).isEmpty() ? 0 // "SNAPSHOT" : Integer.parseInt(m.group(5)), // "SNAPSHOT.123" }; }
[ "private", "int", "[", "]", "parse", "(", "String", "version", ")", "{", "final", "Matcher", "m", "=", "Pattern", ".", "compile", "(", "\"(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)-?(SNAPSHOT)?\\\\.?(\\\\d*)?\"", ")", ".", "matcher", "(", "version", ")", ";", "if", "(",...
Parses the version. @param version the version to parse @return an int array consisting of major, minor, revision, and suffix
[ "Parses", "the", "version", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/util/VersionComparator.java#L58-L71
136,490
stevespringett/Alpine
alpine/src/main/java/alpine/util/VersionComparator.java
VersionComparator.isNewerThan
public boolean isNewerThan(VersionComparator comparator) { if (this.major > comparator.getMajor()) { return true; } else if (this.major == comparator.getMajor() && this.minor > comparator.getMinor()) { return true; } else if (this.major == comparator.getMajor() && this.minor == comparator.getMinor() && this.revision > comparator.getRevision()) { return true; } else if (this.major == comparator.getMajor() && this.minor == comparator.getMinor() && this.revision == comparator.getRevision() && this.prereleaseNumber > comparator.getPrereleaseNumber()) { return true; } return false; }
java
public boolean isNewerThan(VersionComparator comparator) { if (this.major > comparator.getMajor()) { return true; } else if (this.major == comparator.getMajor() && this.minor > comparator.getMinor()) { return true; } else if (this.major == comparator.getMajor() && this.minor == comparator.getMinor() && this.revision > comparator.getRevision()) { return true; } else if (this.major == comparator.getMajor() && this.minor == comparator.getMinor() && this.revision == comparator.getRevision() && this.prereleaseNumber > comparator.getPrereleaseNumber()) { return true; } return false; }
[ "public", "boolean", "isNewerThan", "(", "VersionComparator", "comparator", ")", "{", "if", "(", "this", ".", "major", ">", "comparator", ".", "getMajor", "(", ")", ")", "{", "return", "true", ";", "}", "else", "if", "(", "this", ".", "major", "==", "c...
Determines if the specified VersionComparator is newer than this instance. @param comparator a VersionComparator to compare to @return true if specified version if newer, false if not
[ "Determines", "if", "the", "specified", "VersionComparator", "is", "newer", "than", "this", "instance", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/util/VersionComparator.java#L78-L89
136,491
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/KeyManager.java
KeyManager.initialize
private void initialize() { createKeysIfNotExist(); if (keyPair == null) { try { loadKeyPair(); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { LOGGER.error("An error occurred loading key pair"); LOGGER.error(e.getMessage()); } } if (secretKey == null) { try { loadSecretKey(); } catch (IOException | ClassNotFoundException e) { LOGGER.error("An error occurred loading secret key"); LOGGER.error(e.getMessage()); } } }
java
private void initialize() { createKeysIfNotExist(); if (keyPair == null) { try { loadKeyPair(); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { LOGGER.error("An error occurred loading key pair"); LOGGER.error(e.getMessage()); } } if (secretKey == null) { try { loadSecretKey(); } catch (IOException | ClassNotFoundException e) { LOGGER.error("An error occurred loading secret key"); LOGGER.error(e.getMessage()); } } }
[ "private", "void", "initialize", "(", ")", "{", "createKeysIfNotExist", "(", ")", ";", "if", "(", "keyPair", "==", "null", ")", "{", "try", "{", "loadKeyPair", "(", ")", ";", "}", "catch", "(", "IOException", "|", "NoSuchAlgorithmException", "|", "InvalidK...
Initializes the KeyManager
[ "Initializes", "the", "KeyManager" ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/KeyManager.java#L85-L103
136,492
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/KeyManager.java
KeyManager.createKeysIfNotExist
private void createKeysIfNotExist() { if (!keyPairExists()) { try { final KeyPair keyPair = generateKeyPair(); save(keyPair); } catch (NoSuchAlgorithmException e) { LOGGER.error("An error occurred generating new keypair"); LOGGER.error(e.getMessage()); } catch (IOException e) { LOGGER.error("An error occurred saving newly generated keypair"); LOGGER.error(e.getMessage()); } } if (!secretKeyExists()) { try { final SecretKey secretKey = generateSecretKey(); save(secretKey); } catch (NoSuchAlgorithmException e) { LOGGER.error("An error occurred generating new secret key"); LOGGER.error(e.getMessage()); } catch (IOException e) { LOGGER.error("An error occurred saving newly generated secret key"); LOGGER.error(e.getMessage()); } } }
java
private void createKeysIfNotExist() { if (!keyPairExists()) { try { final KeyPair keyPair = generateKeyPair(); save(keyPair); } catch (NoSuchAlgorithmException e) { LOGGER.error("An error occurred generating new keypair"); LOGGER.error(e.getMessage()); } catch (IOException e) { LOGGER.error("An error occurred saving newly generated keypair"); LOGGER.error(e.getMessage()); } } if (!secretKeyExists()) { try { final SecretKey secretKey = generateSecretKey(); save(secretKey); } catch (NoSuchAlgorithmException e) { LOGGER.error("An error occurred generating new secret key"); LOGGER.error(e.getMessage()); } catch (IOException e) { LOGGER.error("An error occurred saving newly generated secret key"); LOGGER.error(e.getMessage()); } } }
[ "private", "void", "createKeysIfNotExist", "(", ")", "{", "if", "(", "!", "keyPairExists", "(", ")", ")", "{", "try", "{", "final", "KeyPair", "keyPair", "=", "generateKeyPair", "(", ")", ";", "save", "(", "keyPair", ")", ";", "}", "catch", "(", "NoSuc...
Checks if the keys exists. If not, they will be created.
[ "Checks", "if", "the", "keys", "exists", ".", "If", "not", "they", "will", "be", "created", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/KeyManager.java#L108-L133
136,493
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/KeyManager.java
KeyManager.generateKeyPair
public KeyPair generateKeyPair() throws NoSuchAlgorithmException { LOGGER.info("Generating new key pair"); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyGen.initialize(4096, random); return this.keyPair = keyGen.generateKeyPair(); }
java
public KeyPair generateKeyPair() throws NoSuchAlgorithmException { LOGGER.info("Generating new key pair"); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyGen.initialize(4096, random); return this.keyPair = keyGen.generateKeyPair(); }
[ "public", "KeyPair", "generateKeyPair", "(", ")", "throws", "NoSuchAlgorithmException", "{", "LOGGER", ".", "info", "(", "\"Generating new key pair\"", ")", ";", "final", "KeyPairGenerator", "keyGen", "=", "KeyPairGenerator", ".", "getInstance", "(", "\"RSA\"", ")", ...
Generates a key pair. @return a KeyPair (public / private keys) @throws NoSuchAlgorithmException if the algorithm cannot be found @since 1.0.0
[ "Generates", "a", "key", "pair", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/KeyManager.java#L142-L148
136,494
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/KeyManager.java
KeyManager.getKeyPath
private File getKeyPath(final KeyType keyType) { return new File(Config.getInstance().getDataDirectorty() + File.separator + "keys" + File.separator + keyType.name().toLowerCase() + ".key"); }
java
private File getKeyPath(final KeyType keyType) { return new File(Config.getInstance().getDataDirectorty() + File.separator + "keys" + File.separator + keyType.name().toLowerCase() + ".key"); }
[ "private", "File", "getKeyPath", "(", "final", "KeyType", "keyType", ")", "{", "return", "new", "File", "(", "Config", ".", "getInstance", "(", ")", ".", "getDataDirectorty", "(", ")", "+", "File", ".", "separator", "+", "\"keys\"", "+", "File", ".", "se...
Retrieves the path where the keys should be stored. @param keyType the type of key @return a File representing the path to the key
[ "Retrieves", "the", "path", "where", "the", "keys", "should", "be", "stored", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/KeyManager.java#L169-L174
136,495
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/KeyManager.java
KeyManager.getKeyPath
private File getKeyPath(final Key key) { KeyType keyType = null; if (key instanceof PrivateKey) { keyType = KeyType.PRIVATE; } else if (key instanceof PublicKey) { keyType = KeyType.PUBLIC; } else if (key instanceof SecretKey) { keyType = KeyType.SECRET; } return getKeyPath(keyType); }
java
private File getKeyPath(final Key key) { KeyType keyType = null; if (key instanceof PrivateKey) { keyType = KeyType.PRIVATE; } else if (key instanceof PublicKey) { keyType = KeyType.PUBLIC; } else if (key instanceof SecretKey) { keyType = KeyType.SECRET; } return getKeyPath(keyType); }
[ "private", "File", "getKeyPath", "(", "final", "Key", "key", ")", "{", "KeyType", "keyType", "=", "null", ";", "if", "(", "key", "instanceof", "PrivateKey", ")", "{", "keyType", "=", "KeyType", ".", "PRIVATE", ";", "}", "else", "if", "(", "key", "insta...
Given the type of key, this method will return the File path to that key. @param key the type of key @return a File representing the path to the key
[ "Given", "the", "type", "of", "key", "this", "method", "will", "return", "the", "File", "path", "to", "that", "key", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/KeyManager.java#L181-L191
136,496
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/KeyManager.java
KeyManager.save
public void save(final KeyPair keyPair) throws IOException { LOGGER.info("Saving key pair"); final PrivateKey privateKey = keyPair.getPrivate(); final PublicKey publicKey = keyPair.getPublic(); // Store Public Key final File publicKeyFile = getKeyPath(publicKey); publicKeyFile.getParentFile().mkdirs(); // make directories if they do not exist final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); try (OutputStream fos = Files.newOutputStream(publicKeyFile.toPath())) { fos.write(x509EncodedKeySpec.getEncoded()); } // Store Private Key. final File privateKeyFile = getKeyPath(privateKey); privateKeyFile.getParentFile().mkdirs(); // make directories if they do not exist final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); try (OutputStream fos = Files.newOutputStream(privateKeyFile.toPath())) { fos.write(pkcs8EncodedKeySpec.getEncoded()); } }
java
public void save(final KeyPair keyPair) throws IOException { LOGGER.info("Saving key pair"); final PrivateKey privateKey = keyPair.getPrivate(); final PublicKey publicKey = keyPair.getPublic(); // Store Public Key final File publicKeyFile = getKeyPath(publicKey); publicKeyFile.getParentFile().mkdirs(); // make directories if they do not exist final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded()); try (OutputStream fos = Files.newOutputStream(publicKeyFile.toPath())) { fos.write(x509EncodedKeySpec.getEncoded()); } // Store Private Key. final File privateKeyFile = getKeyPath(privateKey); privateKeyFile.getParentFile().mkdirs(); // make directories if they do not exist final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded()); try (OutputStream fos = Files.newOutputStream(privateKeyFile.toPath())) { fos.write(pkcs8EncodedKeySpec.getEncoded()); } }
[ "public", "void", "save", "(", "final", "KeyPair", "keyPair", ")", "throws", "IOException", "{", "LOGGER", ".", "info", "(", "\"Saving key pair\"", ")", ";", "final", "PrivateKey", "privateKey", "=", "keyPair", ".", "getPrivate", "(", ")", ";", "final", "Pub...
Saves a key pair. @param keyPair the key pair to save @throws IOException if the files cannot be written @since 1.0.0
[ "Saves", "a", "key", "pair", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/KeyManager.java#L200-L220
136,497
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/KeyManager.java
KeyManager.save
public void save(final SecretKey key) throws IOException { final File keyFile = getKeyPath(key); keyFile.getParentFile().mkdirs(); // make directories if they do not exist try (OutputStream fos = Files.newOutputStream(keyFile.toPath()); ObjectOutputStream oout = new ObjectOutputStream(fos)) { oout.writeObject(key); } }
java
public void save(final SecretKey key) throws IOException { final File keyFile = getKeyPath(key); keyFile.getParentFile().mkdirs(); // make directories if they do not exist try (OutputStream fos = Files.newOutputStream(keyFile.toPath()); ObjectOutputStream oout = new ObjectOutputStream(fos)) { oout.writeObject(key); } }
[ "public", "void", "save", "(", "final", "SecretKey", "key", ")", "throws", "IOException", "{", "final", "File", "keyFile", "=", "getKeyPath", "(", "key", ")", ";", "keyFile", ".", "getParentFile", "(", ")", ".", "mkdirs", "(", ")", ";", "// make directorie...
Saves a secret key. @param key the SecretKey to save @throws IOException if the file cannot be written @since 1.0.0
[ "Saves", "a", "secret", "key", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/KeyManager.java#L229-L236
136,498
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/KeyManager.java
KeyManager.loadKeyPair
private KeyPair loadKeyPair() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // Read Private Key final File filePrivateKey = getKeyPath(KeyType.PRIVATE); // Read Public Key final File filePublicKey = getKeyPath(KeyType.PUBLIC); byte[] encodedPrivateKey; byte[] encodedPublicKey; try (InputStream pvtfis = Files.newInputStream(filePrivateKey.toPath()); InputStream pubfis = Files.newInputStream(filePublicKey.toPath())) { encodedPrivateKey = new byte[(int) filePrivateKey.length()]; pvtfis.read(encodedPrivateKey); encodedPublicKey = new byte[(int) filePublicKey.length()]; pubfis.read(encodedPublicKey); } // Generate KeyPair final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey); final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); final PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return this.keyPair = new KeyPair(publicKey, privateKey); }
java
private KeyPair loadKeyPair() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // Read Private Key final File filePrivateKey = getKeyPath(KeyType.PRIVATE); // Read Public Key final File filePublicKey = getKeyPath(KeyType.PUBLIC); byte[] encodedPrivateKey; byte[] encodedPublicKey; try (InputStream pvtfis = Files.newInputStream(filePrivateKey.toPath()); InputStream pubfis = Files.newInputStream(filePublicKey.toPath())) { encodedPrivateKey = new byte[(int) filePrivateKey.length()]; pvtfis.read(encodedPrivateKey); encodedPublicKey = new byte[(int) filePublicKey.length()]; pubfis.read(encodedPublicKey); } // Generate KeyPair final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey); final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); final PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return this.keyPair = new KeyPair(publicKey, privateKey); }
[ "private", "KeyPair", "loadKeyPair", "(", ")", "throws", "IOException", ",", "NoSuchAlgorithmException", ",", "InvalidKeySpecException", "{", "// Read Private Key", "final", "File", "filePrivateKey", "=", "getKeyPath", "(", "KeyType", ".", "PRIVATE", ")", ";", "// Rea...
Loads a key pair. @return a KeyPair @throws IOException if the file cannot be read @throws NoSuchAlgorithmException if the algorithm cannot be found @throws InvalidKeySpecException if the algorithm's key spec is incorrect
[ "Loads", "a", "key", "pair", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/KeyManager.java#L245-L273
136,499
stevespringett/Alpine
alpine/src/main/java/alpine/crypto/KeyManager.java
KeyManager.loadSecretKey
private SecretKey loadSecretKey() throws IOException, ClassNotFoundException { final File file = getKeyPath(KeyType.SECRET); SecretKey key; try (InputStream fis = Files.newInputStream(file.toPath()); ObjectInputStream ois = new ObjectInputStream(fis)) { key = (SecretKey) ois.readObject(); } return this.secretKey = key; }
java
private SecretKey loadSecretKey() throws IOException, ClassNotFoundException { final File file = getKeyPath(KeyType.SECRET); SecretKey key; try (InputStream fis = Files.newInputStream(file.toPath()); ObjectInputStream ois = new ObjectInputStream(fis)) { key = (SecretKey) ois.readObject(); } return this.secretKey = key; }
[ "private", "SecretKey", "loadSecretKey", "(", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "final", "File", "file", "=", "getKeyPath", "(", "KeyType", ".", "SECRET", ")", ";", "SecretKey", "key", ";", "try", "(", "InputStream", "fis", "=",...
Loads the secret key. @return a SecretKey @throws IOException if the file cannot be read @throws ClassNotFoundException if deserialization of the SecretKey fails
[ "Loads", "the", "secret", "key", "." ]
6c5ef5e1ba4f38922096f1307d3950c09edb3093
https://github.com/stevespringett/Alpine/blob/6c5ef5e1ba4f38922096f1307d3950c09edb3093/alpine/src/main/java/alpine/crypto/KeyManager.java#L281-L290