code
stringlengths
73
34.1k
label
stringclasses
1 value
public static int hash(ByteBuffer buf, int seed) { // save byte order for later restoration ByteOrder byteOrder = buf.order(); buf.order(ByteOrder.LITTLE_ENDIAN); int m = 0x5bd1e995; int r = 24; int h = seed ^ buf.remaining(); while (buf.remaining() >= 4) { int...
java
@Override public String getTopologyJsonPayload(Set<Host> activeHosts) { int count = NUM_RETRIER_ACROSS_NODES; String response; Exception lastEx = null; do { try { response = getTopologyFromRandomNodeWithRetry(activeHosts); if (response != null) { return response; } } catch (Exception...
java
public Host getRandomHost(Set<Host> activeHosts) { Random random = new Random(); List<Host> hostsUp = new ArrayList<Host>(CollectionUtils.filter(activeHosts, new Predicate<Host>() { @Override public boolean apply(Host x) { return x.isUp(); } })); return hostsUp.get(random.nextInt(hostsUp.size())...
java
private String getTopologyFromRandomNodeWithRetry(Set<Host> activeHosts) { int count = NUM_RETRIES_PER_NODE; String nodeResponse; Exception lastEx; final Host randomHost = getRandomHost(activeHosts); do { try { lastEx = null; nodeResponse = getResponseViaHttp(randomHost.getHostName()); if (node...
java
List<HostToken> parseTokenListFromJson(String json) { List<HostToken> hostTokens = new ArrayList<HostToken>(); JSONParser parser = new JSONParser(); try { JSONArray arr = (JSONArray) parser.parse(json); Iterator<?> iter = arr.iterator(); while (iter.hasNext...
java
@Override public void start(final BaseCallback<Authentication, AuthenticationException> callback) { credentialsRequest.start(new BaseCallback<Credentials, AuthenticationException>() { @Override public void onSuccess(final Credentials credentials) { userInfoRequest ...
java
@Override public Authentication execute() throws Auth0Exception { Credentials credentials = credentialsRequest.execute(); UserProfile profile = userInfoRequest .addHeader(HEADER_AUTHORIZATION, "Bearer " + credentials.getAccessToken()) .execute(); return new Au...
java
public Map<String, Object> getExtraInfo() { return extraInfo != null ? new HashMap<>(extraInfo) : Collections.<String, Object>emptyMap(); }
java
@Override public SignUpRequest addAuthenticationParameters(Map<String, Object> parameters) { authenticationRequest.addAuthenticationParameters(parameters); return this; }
java
@Override public void start(final BaseCallback<Credentials, AuthenticationException> callback) { signUpRequest.start(new BaseCallback<DatabaseUser, AuthenticationException>() { @Override public void onSuccess(final DatabaseUser user) { authenticationRequest.start(call...
java
public void bindService() { Log.v(TAG, "Trying to bind the service"); Context context = this.context.get(); isBound = false; if (context != null && preferredPackage != null) { isBound = CustomTabsClient.bindCustomTabsService(context, preferredPackage, this); } ...
java
public void unbindService() { Log.v(TAG, "Trying to unbind the service"); Context context = this.context.get(); if (isBound && context != null) { context.unbindService(this); isBound = false; } }
java
public void getToken(String authorizationCode, @NonNull final AuthCallback callback) { apiClient.token(authorizationCode, redirectUri) .setCodeVerifier(codeVerifier) .start(new BaseCallback<Credentials, AuthenticationException>() { @Override ...
java
private boolean checkPermissions(Activity activity) { String[] permissions = getRequiredAndroidPermissions(); return handler.areAllPermissionsGranted(activity, permissions); }
java
private void requestPermissions(Activity activity, int requestCode) { String[] permissions = getRequiredAndroidPermissions(); handler.requestPermissions(activity, permissions, requestCode); }
java
public DelegationRequest<T> addParameters(Map<String, Object> parameters) { request.addParameters(parameters); return this; }
java
public DelegationRequest<T> setScope(String scope) { request.addParameter(ParameterBuilder.SCOPE_KEY, scope); return this; }
java
@SuppressWarnings("WeakerAccess") private ParameterizableRequest<Void, AuthenticationException> passwordless() { HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder() .addPathSegment(PASSWORDLESS_PATH) .addPathSegment(START_PATH) .build(); fi...
java
@Override public AuthenticationRequest setConnection(String connection) { if (!hasLegacyPath()) { Log.w(TAG, "Not setting the 'connection' parameter as the request is using a OAuth 2.0 API Authorization endpoint that doesn't support it."); return this; } addParameter(...
java
@Override public AuthenticationRequest setRealm(String realm) { if (hasLegacyPath()) { Log.w(TAG, "Not setting the 'realm' parameter as the request is using a Legacy Authorization API endpoint that doesn't support it."); return this; } addParameter(REALM_KEY, realm); ...
java
public DatabaseConnectionRequest<T, U> addParameters(Map<String, Object> parameters) { request.addParameters(parameters); return this; }
java
public DatabaseConnectionRequest<T, U> addParameter(String name, Object value) { request.addParameter(name, value); return this; }
java
public DatabaseConnectionRequest<T, U> setConnection(String connection) { request.addParameter(ParameterBuilder.CONNECTION_KEY, connection); return this; }
java
public OkHttpClient createClient(boolean loggingEnabled, boolean tls12Enforced, int connectTimeout, int readTimeout, int writeTimeout) { return modifyClient(new OkHttpClient(), loggingEnabled, tls12Enforced, connectTimeout, readTimeout, writeTimeout); }
java
private void enforceTls12(OkHttpClient client) { // No need to modify client as TLS 1.2 is enabled by default on API21+ // Lollipop is included because some Samsung devices face the same problem on API 21. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN || Build.VERSIO...
java
public ParameterBuilder addAll(Map<String, Object> parameters) { if (parameters != null) { for (String k : parameters.keySet()) { if (parameters.get(k) != null) { this.parameters.put(k, parameters.get(k)); } } } return t...
java
public boolean isValid(int expectedRequestCode) { Uri uri = intent != null ? intent.getData() : null; if (uri == null) { Log.d(TAG, "Result is invalid: Received Intent's Uri is null."); return false; } if (requestCode == MISSING_REQUEST_CODE) { return...
java
public boolean hasValidCredentials() { String accessToken = storage.retrieveString(KEY_ACCESS_TOKEN); String refreshToken = storage.retrieveString(KEY_REFRESH_TOKEN); String idToken = storage.retrieveString(KEY_ID_TOKEN); Long expiresAt = storage.retrieveLong(KEY_EXPIRES_AT); re...
java
public void clearCredentials() { storage.remove(KEY_ACCESS_TOKEN); storage.remove(KEY_REFRESH_TOKEN); storage.remove(KEY_ID_TOKEN); storage.remove(KEY_TOKEN_TYPE); storage.remove(KEY_EXPIRES_AT); storage.remove(KEY_SCOPE); }
java
public void clearCredentials() { storage.remove(KEY_CREDENTIALS); storage.remove(KEY_EXPIRES_AT); storage.remove(KEY_CAN_REFRESH); Log.d(TAG, "Credentials were just removed from the storage"); }
java
public boolean hasValidCredentials() { String encryptedEncoded = storage.retrieveString(KEY_CREDENTIALS); Long expiresAt = storage.retrieveLong(KEY_EXPIRES_AT); Boolean canRefresh = storage.retrieveBoolean(KEY_CAN_REFRESH); return !(isEmpty(encryptedEncoded) || expiresAt ...
java
@Override public boolean hasNext() { if (!members.hasNext()) { try { getNextEntries(); } catch (final Exception ignored) { LOG.error("An error occured while getting next entries", ignored); } } return members.hasNext(); ...
java
@Override public ClientEntry next() { if (hasNext()) { final Entry romeEntry = members.next(); try { if (!romeEntry.isMediaEntry()) { return new ClientEntry(null, collection, romeEntry, true); } else { return new...
java
public ClientEntry getEntry(final String uri) throws ProponoException { final GetMethod method = new GetMethod(uri); authStrategy.addAuthentication(httpClient, method); try { httpClient.executeMethod(method); if (method.getStatusCode() != 200) { throw new ...
java
public ClientMediaEntry createMediaEntry(final String title, final String slug, final String contentType, final byte[] bytes) throws ProponoException { if (!isWritable()) { throw new ProponoException("Collection is not writable"); } return new ClientMediaEntry(service, this, title, s...
java
public ClientMediaEntry createMediaEntry(final String title, final String slug, final String contentType, final InputStream is) throws ProponoException { if (!isWritable()) { throw new ProponoException("Collection is not writable"); } return new ClientMediaEntry(service, this, title,...
java
@Override public Module parse(final Element elem, final Locale locale) { final AppModule m = new AppModuleImpl(); final Element control = elem.getChild("control", getContentNamespace()); if (control != null) { final Element draftElem = control.getChild("draft", getContentNamespac...
java
public InputStream getAsStream() throws ProponoException { if (getContents() != null && !getContents().isEmpty()) { final Content c = getContents().get(0); if (c.getSrc() != null) { return getResourceAsStream(); } else if (inputStream != null) { ...
java
@Override public void update() throws ProponoException { if (partial) { throw new ProponoException("ERROR: attempt to update partial entry"); } EntityEnclosingMethod method = null; final Content updateContent = getContents().get(0); try { if (getMediaL...
java
@Override public final synchronized void setSyndFeed(final SyndFeed feed) { super.setSyndFeed(feed); changedMap.clear(); final List<SyndEntry> entries = feed.getEntries(); for (final SyndEntry entry : entries) { final String currentEntryTag = computeEntryTag(entry); ...
java
public void setContent(final String contentString, final String type) { final Content newContent = new Content(); newContent.setType(type == null ? Content.HTML : type); newContent.setValue(contentString); final ArrayList<Content> contents = new ArrayList<Content>(); contents.add...
java
public void setContent(final Content c) { final ArrayList<Content> contents = new ArrayList<Content>(); contents.add(c); setContents(contents); }
java
public Content getContent() { if (getContents() != null && !getContents().isEmpty()) { final Content c = getContents().get(0); return c; } return null; }
java
public void remove() throws ProponoException { if (getEditURI() == null) { throw new ProponoException("ERROR: cannot delete unsaved entry"); } final DeleteMethod method = new DeleteMethod(getEditURI()); addAuthentication(method); try { getHttpClient().exec...
java
public String getEditURI() { for (int i = 0; i < getOtherLinks().size(); i++) { final Link link = getOtherLinks().get(i); if (link.getRel() != null && link.getRel().equals("edit")) { return link.getHrefResolved(); } } return null; }
java
public void setDefaultContentIndex(final Integer defaultContentIndex) { for (int i = 0; i < getContents().length; i++) { if (i == defaultContentIndex.intValue()) { getContents()[i].setDefaultContent(true); } else { getContents()[i].setDefaultContent(false)...
java
public Element workspaceToElement() { final Workspace space = this; final Element element = new Element("workspace", AtomService.ATOM_PROTOCOL); final Element titleElem = new Element("title", AtomService.ATOM_FORMAT); titleElem.setText(space.getTitle()); if (space.getTitleType(...
java
protected void parseWorkspaceElement(final Element element) throws ProponoException { final Element titleElem = element.getChild("title", AtomService.ATOM_FORMAT); setTitle(titleElem.getText()); if (titleElem.getAttribute("type", AtomService.ATOM_FORMAT) != null) { setTitleType(title...
java
public Workspace findWorkspace(final String title) { for (final Object element : workspaces) { final Workspace ws = (Workspace) element; if (title.equals(ws.getTitle())) { return ws; } } return null; }
java
public Document serviceToDocument() { final AtomService service = this; final Document doc = new Document(); final Element root = new Element("service", ATOM_PROTOCOL); doc.setRootElement(root); final List<Workspace> spaces = service.getWorkspaces(); for (final Workspace...
java
public synchronized void sortOnProperty(final Object value, final boolean ascending, final ValueStrategy strategy) { final int elementCount = size(); for (int i = 0; i < elementCount - 1; i++) { for (int j = i + 1; j < elementCount; j++) { final T entry1 = get(i); ...
java
@Override public InputStream getAsStream() throws BlogClientException { final HttpClient httpClient = new HttpClient(); final GetMethod method = new GetMethod(permalink); try { httpClient.executeMethod(method); } catch (final Exception e) { throw new BlogClien...
java
protected SAXBuilder createSAXBuilder() { SAXBuilder saxBuilder; if (validate) { saxBuilder = new SAXBuilder(XMLReaders.DTDVALIDATING); } else { saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING); } saxBuilder.setEntityResolver(RESOLVER); // ...
java
public String getRootCauseMessage() { String rcmessage = null; if (getRootCause() != null) { if (getRootCause().getCause() != null) { rcmessage = getRootCause().getCause().getMessage(); } rcmessage = rcmessage == null ? getRootCause().getMessage() : rc...
java
public String getHrefResolved() { if (Atom10Parser.isAbsoluteURI(href)) { return href; } else if (baseURI != null && categoriesElement != null) { return Atom10Parser.resolveURI(baseURI, categoriesElement, href); } return null; }
java
public static <T> List<T> createWhenNull(final List<T> list) { if (list == null) { return new ArrayList<T>(); } else { return list; } }
java
public static <T> List<T> create(final T item) { final List<T> list = new ArrayList<T>(); list.add(item); return list; }
java
public static <T> T firstEntry(final List<T> list) { if (list != null && !list.isEmpty()) { return list.get(0); } else { return null; } }
java
public static boolean sizeIs(final List<?> list, final int size) { if (size == 0) { return list == null || list.isEmpty(); } else { return list != null && list.size() == size; } }
java
public static <T> List<T> emptyToNull(final List<T> list) { if (isEmpty(list)) { return null; } else { return list; } }
java
public static Long parseLong(final String str) { if (null != str) { try { return new Long(Long.parseLong(str.trim())); } catch (final Exception e) { // :IGNORE: } } return null; }
java
public static Float parseFloat(final String str) { if (null != str) { try { return new Float(Float.parseFloat(str.trim())); } catch (final Exception e) { // :IGNORE: } } return null; }
java
public static float parseFloat(final String str, final float def) { final Float result = parseFloat(str); if (result == null) { return def; } else { return result.floatValue(); } }
java
public static long parseLong(final String str, final long def) { final Long ret = parseLong(str); if (ret == null) { return def; } else { return ret.longValue(); } }
java
public static PropertiesLoader getPropertiesLoader() { synchronized (PropertiesLoader.class) { final ClassLoader classLoader = ConfigurableClassLoader.INSTANCE.getClassLoader(); PropertiesLoader loader = clMap.get(classLoader); if (loader == null) { try { loader = new PropertiesLoader(MASTER_PLUGIN_...
java
public static void serializeEntry(final Entry entry, final Writer writer) throws IllegalArgumentException, FeedException, IOException { // Build a feed containing only the entry final List<Entry> entries = new ArrayList<Entry>(); entries.add(entry); final Feed feed1 = new Feed(); ...
java
@Override public SyndFeed retrieveFeed(final String userAgent, final URL feedUrl) throws IllegalArgumentException, IOException, FeedException, FetcherException { if (feedUrl == null) { throw new IllegalArgumentException("null is not a valid URL"); } final URLConnection connectio...
java
private static Object newInstance(final String className, ClassLoader cl, final boolean doFallback) throws ConfigurationError { try { Class<?> providerClass; if (cl == null) { // If classloader is null Use the bootstrap ClassLoader. // Thus Class.forName(...
java
static Object find(final String factoryId, final String fallbackClassName) throws ConfigurationError { // Figure out which ClassLoader to use for loading the provider // class. If there is a Context ClassLoader then use it. ClassLoader classLoader = ss.getContextClassLoader(); if (cla...
java
public static Double parse(final String s) { Double parsed = null; try { if (s != null) { parsed = Double.parseDouble(s); } } catch (final NumberFormatException e) { } return parsed; }
java
public static PriceTypeEnumeration findByValue(final String value) { if (value.equalsIgnoreCase("negotiable")) { return PriceTypeEnumeration.NEGOTIABLE; } else { return PriceTypeEnumeration.STARTING; } }
java
protected void populateChannel(final Channel channel, final Element eChannel) { final String title = channel.getTitle(); if (title != null) { eChannel.addContent(generateSimpleElement("title", title)); } final String link = channel.getLink(); if (link != null) { ...
java
@Override protected SyndEntry createSyndEntry(final Item item, final boolean preserveWireItem) { final SyndEntry syndEntry = super.createSyndEntry(item, preserveWireItem); final Description desc = item.getDescription(); if (desc != null) { final SyndContent descContent = new Sy...
java
@Override protected void doDelete(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { LOG.debug("Entering"); final AtomHandler handler = createAtomRequestHandler(req, res); final String userName = handler.getAuthenticatedUsername(); if ...
java
public String getAttributeValue(final String name) { final List<Attribute> attributes = Collections.synchronizedList(getAttributes()); for (int i = 0; i < attributes.size(); i++) { final Attribute a = attributes.get(i); if (a.getName() != null && a.getName().equals(name)) { ...
java
public void sendUpdateNotification(final String hub, final String topic) throws NotificationException { try { final StringBuilder sb = new StringBuilder("hub.mode=publish&hub.url=").append(URLEncoder.encode(topic, "UTF-8")); final URL hubUrl = new URL(hub); final HttpURLConne...
java
public void sendUpdateNotification(final String topic, final SyndFeed feed) throws NotificationException { for (final SyndLink link : feed.getLinks()) { if ("hub".equals(link.getRel())) { sendUpdateNotification(link.getRel(), topic); return; } } ...
java
public void sendUpdateNotification(final SyndFeed feed) throws NotificationException { SyndLink hub = null; SyndLink self = null; for (final SyndLink link : feed.getLinks()) { if ("hub".equals(link.getRel())) { hub = link; } if ("self".equals...
java
public void sendUpdateNotificationAsyncronously(final String hub, final String topic, final AsyncNotificationCallback callback) { final Runnable r = new Runnable() { @Override public void run() { try { sendUpdateNotification(hub, topic); ...
java
@Override public Categories getCategories(final AtomRequest areq) throws AtomException { LOG.debug("getCollection"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String handle = pathInfo[0]; final String collection = pathInfo[1]; final FileBased...
java
@Override public Feed getCollection(final AtomRequest areq) throws AtomException { LOG.debug("getCollection"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String handle = pathInfo[0]; final String collection = pathInfo[1]; final FileBasedCollec...
java
@Override public Entry postEntry(final AtomRequest areq, final Entry entry) throws AtomException { LOG.debug("postEntry"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String handle = pathInfo[0]; final String collection = pathInfo[1]; final Fi...
java
@Override public void putEntry(final AtomRequest areq, final Entry entry) throws AtomException { LOG.debug("putEntry"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String handle = pathInfo[0]; final String collection = pathInfo[1]; final String...
java
@Override public void deleteEntry(final AtomRequest areq) throws AtomException { LOG.debug("deleteEntry"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String handle = pathInfo[0]; final String collection = pathInfo[1]; final String fileName = p...
java
@Override public Entry postMedia(final AtomRequest areq, final Entry entry) throws AtomException { // get incoming slug from HTTP header final String slug = areq.getHeader("Slug"); if (LOG.isDebugEnabled()) { LOG.debug("postMedia - title: " + entry.getTitle() + " slug:" + slug)...
java
@Override public void putMedia(final AtomRequest areq) throws AtomException { LOG.debug("putMedia"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String handle = pathInfo[0]; final String collection = pathInfo[1]; final String fileName = pathIn...
java
@Override public boolean isAtomServiceURI(final AtomRequest areq) { final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); if (pathInfo.length == 0) { return true; } return false; }
java
@Override public boolean isCategoriesURI(final AtomRequest areq) { LOG.debug("isCategoriesDocumentURI"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); if (pathInfo.length == 3 && "categories".equals(pathInfo[2])) { return true; } return fal...
java
@Override public boolean isCollectionURI(final AtomRequest areq) { LOG.debug("isCollectionURI"); // workspace/collection-plural // if length is 2 and points to a valid collection then YES final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); if (pathInfo.lengt...
java
public String authenticateBASIC(final HttpServletRequest request) { LOG.debug("authenticateBASIC"); boolean valid = false; String userID = null; String password = null; try { final String authHeader = request.getHeader("Authorization"); if (authHeader != n...
java
public boolean isMediaEntry() { boolean mediaEntry = false; final List<Link> links = getOtherLinks(); for (final Link link : links) { if ("edit-media".equals(link.getRel())) { mediaEntry = true; break; } } return mediaEntry;...
java
@Override protected void enqueueNotification(final Notification not) { final Runnable r = new Runnable() { @Override public void run() { not.lastRun = System.currentTimeMillis(); final SubscriptionSummary summary = postNotification(not.subscriber, not...
java
protected void retry(final Notification not) { if (!pendings.contains(not.subscriber.getCallback())) { // We don't have a current retry for this callback pending, so we // will schedule the retry pendings.add(not.subscriber.getCallback()); timer.schedule(new Timer...
java
@Override protected List<Element> getItems(final Element rssRoot) { final Element eChannel = rssRoot.getChild("channel", getRSSNamespace()); if (eChannel != null) { return eChannel.getChildren("item", getRSSNamespace()); } else { return Collections.emptyList(); ...
java
@Override protected Element getImage(final Element rssRoot) { final Element eChannel = rssRoot.getChild("channel", getRSSNamespace()); if (eChannel != null) { return eChannel.getChild("image", getRSSNamespace()); } else { return null; } }
java
@Override protected Element getTextInput(final Element rssRoot) { final String elementName = getTextInputLabel(); final Element eChannel = rssRoot.getChild("channel", getRSSNamespace()); if (eChannel != null) { return eChannel.getChild(elementName, getRSSNamespace()); }...
java
@Override public List<Category> getCategories() { return categories == null ? (categories = new ArrayList<Category>()) : categories; }
java
public static Long parseDecimal(final String s) { Long parsed = null; try { if (s != null) { parsed = (long) Double.parseDouble(s); } } catch (final NumberFormatException e) { } return parsed; }
java
public void add(final double latitude, final double longitude) { ensureCapacity(size + 1); this.longitude[size] = longitude; this.latitude[size] = latitude; ++size; }
java
public void insert(final int pos, final double latitude, final double longitude) { ensureCapacity(size + 1); System.arraycopy(this.longitude, pos, this.longitude, pos + 1, size - pos); System.arraycopy(this.latitude, pos, this.latitude, pos + 1, size - pos); this.longitude[pos] = longitu...
java