code
stringlengths
73
34.1k
label
stringclasses
1 value
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()); ...
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 ==...
java
private void checkState() { if (startWith == null && lastResult == null) { final String msg = "Please call startWith(uri) first."; LOG.error(msg); throw new IllegalStateException(msg); } }
java
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 Client client) { client.register(TracingClientFilter.create(tracing)); return client; }
java
public CreateResponse create() throws IOException, PlivoRestException { validate(); Response<CreateResponse> response = obtainCall().execute(); handleResponse(response); return response.body(); }
java
private static void getAccountInfo() { try { Account response = Account.getter() .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(); } }
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(); } }
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();...
java
public void delete() throws IOException, PlivoRestException { validate(); Response<ResponseBody> response = obtainCall().execute(); handleResponse(response); }
java
public T update() throws IOException, PlivoRestException { validate(); Response<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(); }
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: %...
java
public static void i(String s, Throwable t) { log(Level.INFO, s, t); }
java
public static void w(String s, Throwable t) { log(Level.WARNING, s, t); }
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; }
java
public static String toHexUpper(byte[] b, int off, int len) { return toHex(b, off, len, HEX_UPPER_CHAR); }
java
public static String toHexLower(byte[] b, int off, int len) { return toHex(b, off, len, HEX_LOWER_CHAR); }
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; }
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; }
java
public static synchronized void chdir(String path) { if (path != null) { rootDir = new File(getAbsolutePath(path)).getAbsolutePath(); } }
java
public static void closeLogger(Logger logger) { for (Handler handler : logger.getHandlers()) { logger.removeHandler(handler); handler.close(); } }
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; } ...
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.decrem...
java
public void await() { if (interrupted.get()) { return; } try { mainLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
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(); } } } r...
java
@Override public void close() { synchronized (this) { if (object != null) { T object_ = object; object = null; try { finalizer.accept(object_); } catch (Exception e) { // Ignored } } } }
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; }
java
public ByteArrayQueue add(int b) { int newLength = addLength(1); array[offset + length] = (byte) b; length = newLength; return this; }
java
public ByteArrayQueue remove(byte[] b, int off, int len) { System.arraycopy(array, offset, b, off, len); return remove(len); }
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; }
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 escapedPiec...
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."); ...
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); } }
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))); }
java
public static long readLong(byte[] bytes, int start) { return ((long) (readInt(bytes, start)) << 32) + (readInt(bytes, start + 4) & 0xFFFFFFFFL); }
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) { ...
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); retu...
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 tru...
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 or...
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); }
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; ...
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 = ne...
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...
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) ...
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) ...
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(...
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 = ...
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()); ...
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...
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 ConstraintV...
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() =...
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(query...
java
protected Principal getPrincipal() { final Object principal = requestContext.getProperty("Principal"); if (principal != null) { return (Principal) principal; } else { return null; } }
java
protected boolean hasPermission(final String permission) { if (getPrincipal() == null) { return false; } try (AlpineQueryManager qm = new AlpineQueryManager()) { boolean hasPermission = false; if (getPrincipal() instanceof ApiKey) { hasPermissi...
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()); }
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...
java
public void init(final FilterConfig filterConfig) { final String host = filterConfig.getInitParameter("host"); if (StringUtils.isNotBlank(host)) { this.host = host; } }
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) || "ex...
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))...
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 preven...
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\" =...
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\", \...
java
public VersionComparator getSchemaVersion() { PreparedStatement statement = null; ResultSet results = null; try { statement = connection.prepareStatement("SELECT \"VERSION\" FROM \"SCHEMAVERSION\""); results = statement.executeQuery(); if (results.next()) { ...
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\"");...
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; } }
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); getS...
java
private void getStringFromValue(final StringBuilder builder, final String directive, final String value) { if (value != null) { builder.append(directive).append(" ").append(value).append(";"); } }
java
public Principal authenticate() throws AlpineAuthenticationException { LOGGER.debug("Attempting to authenticate user: " + username); final ManagedUserAuthenticationService userService = new ManagedUserAuthenticationService(username, password); try{ final Principal principal = userServic...
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 =...
java
public void advancePagination() { if (pagination.isPaginated()) { pagination = new Pagination(pagination.getStrategy(), pagination.getOffset() + pagination.getLimit(), pagination.getLimit()); } }
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 + paginat...
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; }
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; }
java
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 getObjectById(Class<T> clazz, Object id) { return pm.getObjectById(clazz, id); }
java
public void init(final FilterConfig filterConfig) { final String allowParam = filterConfig.getInitParameter("allowUrls"); if (StringUtils.isNotBlank(allowParam)) { this.allowUrls = allowParam.split(","); } }
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 Stri...
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...
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.fil...
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"); ...
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 Stri...
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); }
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; } ...
java
private Integer parseIntegerFromParam(final String value, final int defaultValue) { try { return Integer.valueOf(value); } catch (NumberFormatException | NullPointerException e) { return defaultValue; } }
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()); } bu...
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(...
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.m...
java
private void initialize() { createKeysIfNotExist(); if (keyPair == null) { try { loadKeyPair(); } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { LOGGER.error("An error occurred loading key pair"); LOGGE...
java
private void createKeysIfNotExist() { if (!keyPairExists()) { try { final KeyPair keyPair = generateKeyPair(); save(keyPair); } catch (NoSuchAlgorithmException e) { LOGGER.error("An error occurred generating new keypair"); L...
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); retur...
java
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 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.SECRE...
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); publicK...
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 ObjectOutputStre...
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;...
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...
java
public static boolean valueOf(String value) { return (value != null) && (value.trim().equalsIgnoreCase("true") || value.trim().equals("1")); }
java
public static byte[] encryptAsBytes(final SecretKey secretKey, final String plainText) throws Exception { final byte[] clean = plainText.getBytes(); // Generating IV int ivSize = 16; final byte[] iv = new byte[ivSize]; final SecureRandom random = new SecureRandom(); rand...
java