code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
public float getFloat(int columnIndex) {
Object fieldValue = data[columnIndex];
if (fieldValue == null) {
return 0.0f;
}
if (fieldValue instanceof Number) {
return ((Number) fieldValue).floatValue();
}
throw new DBFException("Unsupported type for Number at column:" + columnIndex + " "
+ fieldValue.getClass().getCanonicalName());
} | java |
public int getInt(int columnIndex) {
Object fieldValue = data[columnIndex];
if (fieldValue == null) {
return 0;
}
if (fieldValue instanceof Number) {
return ((Number) fieldValue).intValue();
}
throw new DBFException("Unsupported type for Number at column:" + columnIndex + " "
+ fieldValue.getClass().getCanonicalName());
} | java |
public long getLong(int columnIndex) {
Object fieldValue = data[columnIndex];
if (fieldValue == null) {
return 0;
}
if (fieldValue instanceof Number) {
return ((Number) fieldValue).longValue();
}
throw new DBFException("Unsupported type for Number at column:" + columnIndex + " "
+ fieldValue.getClass().getCanonicalName());
} | java |
@Deprecated
public static byte[] textPadding(String text, String characterSetName, int length, int alignment, byte paddingByte)
throws UnsupportedEncodingException {
DBFAlignment align = DBFAlignment.RIGHT;
if (alignment == ALIGN_LEFT) {
align = DBFAlignment.LEFT;
}
return textPadding(text, characterSetName, length, align, paddingByte);
} | java |
@Deprecated
public static byte[] textPadding(String text, String characterSetName, int length, DBFAlignment alignment, byte paddingByte)
throws UnsupportedEncodingException {
return textPadding(text, Charset.forName(characterSetName), length, alignment, paddingByte);
} | java |
TomcatRuntime getTomcatRuntime(WebResourceRoot resources) {
TomcatRuntime result = null;
if (isUberJar(resources)) {
result = TomcatRuntime.UBER_JAR;
}
else if (isUberWar(resources)) {
result = TomcatRuntime.UBER_WAR;
}
else if (isTesting(resources)) {
result = TomcatRuntime.TEST;
}
else if (isUnpackagedJar(resources)) {
result = TomcatRuntime.UNPACKAGED_JAR;
}
return result;
} | java |
protected void writeClassList(File file, Collection<String> classNames) throws IOException {
File baseDir = file.getParentFile();
if (baseDir.isDirectory() || baseDir.mkdirs()) {
Files.write(file.toPath(), classNames, StandardCharsets.UTF_8);
}
else {
throw new IOException(baseDir + " does not exist and could not be created");
}
} | java |
protected void writeClassMap(File file, Map<String, ? extends Collection<String>> classMap) throws IOException {
File baseDir = file.getParentFile();
if (baseDir.isDirectory() || baseDir.mkdirs()) {
//noinspection CharsetObjectCanBeUsed
try (PrintWriter printWriter = new PrintWriter(file, "UTF-8")) {
classMap.forEach((key, value) -> {
printWriter.print(key);
printWriter.print("=");
printWriter.println(String.join(",", value));
});
}
}
else {
throw new IOException(baseDir + " does not exist and could not be created");
}
} | java |
public static boolean areAllGranted(String authorities) throws IOException {
AuthorizeFaceletsTag authorizeTag = new AuthorizeFaceletsTag();
authorizeTag.setIfAllGranted(authorities);
return authorizeTag.authorize();
} | java |
public static boolean areAnyGranted(String authorities) throws IOException {
AuthorizeFaceletsTag authorizeTag = new AuthorizeFaceletsTag();
authorizeTag.setIfAnyGranted(authorities);
return authorizeTag.authorize();
} | java |
public static boolean areNotGranted(String authorities) throws IOException {
AuthorizeFaceletsTag authorizeTag = new AuthorizeFaceletsTag();
authorizeTag.setIfNotGranted(authorities);
return authorizeTag.authorize();
} | java |
public static boolean isAllowed(String url, String method) throws IOException {
AuthorizeFaceletsTag authorizeTag = new AuthorizeFaceletsTag();
authorizeTag.setUrl(url);
authorizeTag.setMethod(method);
return authorizeTag.authorizeUsingUrlCheck();
} | java |
private void registerJsfCdiToSpring(BeanDefinition definition) {
if (definition instanceof AnnotatedBeanDefinition) {
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
String scopeName = null;
// firstly check whether bean is defined via configuration
if (annDef.getFactoryMethodMetadata() != null) {
scopeName = deduceScopeName(annDef.getFactoryMethodMetadata());
}
else {
// fallback to type
scopeName = deduceScopeName(annDef.getMetadata());
}
if (scopeName != null) {
definition.setScope(scopeName);
log.debug("{} - Scope({})", definition.getBeanClassName(), scopeName.toUpperCase());
}
}
} | java |
private String getPropertyPath(Expression reference, String alias) {
if (reference instanceof Property) {
Property property = (Property)reference;
if (alias.equals(property.getScope())) {
return property.getPath();
}
else if (property.getSource() != null) {
String subPath = getPropertyPath(property.getSource(), alias);
if (subPath != null) {
return String.format("%s.%s", subPath, property.getPath());
}
}
}
return null;
} | java |
public boolean isCompatibleWith(DataType other) {
// A type is compatible with a choice type if it is a subtype of one of the choice types
if (other instanceof ChoiceType) {
for (DataType choice : ((ChoiceType)other).getTypes()) {
if (this.isSubTypeOf(choice)) {
return true;
}
}
}
return this.equals(other); // Any data type is compatible with itself
} | java |
public T visitTypeSpecifier(TypeSpecifier elm, C context) {
if (elm instanceof NamedTypeSpecifier) return visitNamedTypeSpecifier((NamedTypeSpecifier)elm, context);
else if (elm instanceof IntervalTypeSpecifier) return visitIntervalTypeSpecifier((IntervalTypeSpecifier)elm, context);
else if (elm instanceof ListTypeSpecifier) return visitListTypeSpecifier((ListTypeSpecifier)elm, context);
else if (elm instanceof TupleTypeSpecifier) return visitTupleTypeSpecifier((TupleTypeSpecifier)elm, context);
else return null;
} | java |
public T visitIntervalTypeSpecifier(IntervalTypeSpecifier elm, C context) {
visitElement(elm.getPointType(), context);
return null;
} | java |
public T visitListTypeSpecifier(ListTypeSpecifier elm, C context) {
visitElement(elm.getElementType(), context);
return null;
} | java |
public T visitTupleElementDefinition(TupleElementDefinition elm, C context) {
visitElement(elm.getType(), context);
return null;
} | java |
public T visitTupleTypeSpecifier(TupleTypeSpecifier elm, C context) {
for (TupleElementDefinition element : elm.getElement()) {
visitElement(element, context);
}
return null;
} | java |
public T visitTernaryExpression(TernaryExpression elm, C context) {
for (Expression element : elm.getOperand()) {
visitElement(element, context);
}
return null;
} | java |
public T visitNaryExpression(NaryExpression elm, C context) {
if (elm instanceof Coalesce) return visitCoalesce((Coalesce)elm, context);
else if (elm instanceof Concatenate) return visitConcatenate((Concatenate)elm, context);
else if (elm instanceof Except) return visitExcept((Except)elm, context);
else if (elm instanceof Intersect) return visitIntersect((Intersect)elm, context);
else if (elm instanceof Union) return visitUnion((Union)elm, context);
else return null;
} | java |
public T visitExpressionDef(ExpressionDef elm, C context) {
visitElement(elm.getExpression(), context);
return null;
} | java |
public T visitFunctionDef(FunctionDef elm, C context) {
for (OperandDef element : elm.getOperand()) {
visitElement(element, context);
}
visitElement(elm.getExpression(), context);
return null;
} | java |
public T visitFunctionRef(FunctionRef elm, C context) {
for (Expression element : elm.getOperand()) {
visitElement(element, context);
}
return null;
} | java |
public T visitParameterDef(ParameterDef elm, C context) {
if (elm.getParameterTypeSpecifier() != null) {
visitElement(elm.getParameterTypeSpecifier(), context);
}
if (elm.getDefault() != null) {
visitElement(elm.getDefault(), context);
}
return null;
} | java |
public T visitOperandDef(OperandDef elm, C context) {
if (elm.getOperandTypeSpecifier() != null) {
visitElement(elm.getOperandTypeSpecifier(), context);
}
return null;
} | java |
public T visitTupleElement(TupleElement elm, C context) {
visitElement(elm.getValue(), context);
return null;
} | java |
public T visitTuple(Tuple elm, C context) {
for (TupleElement element : elm.getElement()) {
visitTupleElement(element, context);
}
return null;
} | java |
public T visitInstanceElement(InstanceElement elm, C context) {
visitElement(elm.getValue(), context);
return null;
} | java |
public T visitInstance(Instance elm, C context) {
for (InstanceElement element : elm.getElement()) {
visitInstanceElement(element, context);
}
return null;
} | java |
public T visitInterval(Interval elm, C context) {
if (elm.getLow() != null) {
visitElement(elm.getLow(), context);
}
if (elm.getLowClosedExpression() != null) {
visitElement(elm.getLowClosedExpression(), context);
}
if (elm.getHigh() != null) {
visitElement(elm.getHigh(), context);
}
if (elm.getHighClosedExpression() != null) {
visitElement(elm.getHighClosedExpression(), context);
}
return null;
} | java |
public T visitList(List elm, C context) {
if (elm.getTypeSpecifier() != null) {
visitElement(elm.getTypeSpecifier(), context);
}
for (Expression element : elm.getElement()) {
visitElement(element, context);
}
return null;
} | java |
public void recordParsingException(CqlTranslatorException e) {
addException(e);
if (shouldReport(e.getSeverity())) {
CqlToElmError err = af.createCqlToElmError();
err.setMessage(e.getMessage());
err.setErrorType(e instanceof CqlSyntaxException ? ErrorType.SYNTAX : (e instanceof CqlSemanticException ? ErrorType.SEMANTIC : ErrorType.INTERNAL));
err.setErrorSeverity(toErrorSeverity(e.getSeverity()));
if (e.getLocator() != null) {
err.setStartLine(e.getLocator().getStartLine());
err.setEndLine(e.getLocator().getEndLine());
err.setStartChar(e.getLocator().getStartChar());
err.setEndChar(e.getLocator().getEndChar());
}
if (e.getCause() != null && e.getCause() instanceof CqlTranslatorIncludeException) {
CqlTranslatorIncludeException incEx = (CqlTranslatorIncludeException) e.getCause();
err.setTargetIncludeLibraryId(incEx.getLibraryId());
err.setTargetIncludeLibraryVersionId(incEx.getVersionId());
err.setErrorType(ErrorType.INCLUDE);
}
library.getAnnotation().add(err);
}
} | java |
private CalculateAge resolveCalculateAge(Expression e, DateTimePrecision p) {
CalculateAge operator = of.createCalculateAge()
.withPrecision(p)
.withOperand(e);
builder.resolveUnaryCall("System", "CalculateAge", operator);
return operator;
} | java |
private Round resolveRound(FunctionRef fun) {
if (fun.getOperand().isEmpty() || fun.getOperand().size() > 2) {
throw new IllegalArgumentException("Could not resolve call to system operator Round. Expected 1 or 2 arguments.");
}
final Round round = of.createRound().withOperand(fun.getOperand().get(0));
if (fun.getOperand().size() == 2) {
round.setPrecision(fun.getOperand().get(1));
}
builder.resolveCall("System", "Round", new RoundInvocation(round));
return round;
} | java |
private DateTime resolveDateTime(FunctionRef fun) {
final DateTime dt = of.createDateTime();
DateTimeInvocation.setDateTimeFieldsFromOperands(dt, fun.getOperand());
builder.resolveCall("System", "DateTime", new DateTimeInvocation(dt));
return dt;
} | java |
private IndexOf resolveIndexOf(FunctionRef fun) {
checkNumberOfOperands(fun, 2);
final IndexOf indexOf = of.createIndexOf();
indexOf.setSource(fun.getOperand().get(0));
indexOf.setElement(fun.getOperand().get(1));
builder.resolveCall("System", "IndexOf", new IndexOfInvocation(indexOf));
return indexOf;
} | java |
private Combine resolveCombine(FunctionRef fun) {
if (fun.getOperand().isEmpty() || fun.getOperand().size() > 2) {
throw new IllegalArgumentException("Could not resolve call to system operator Combine. Expected 1 or 2 arguments.");
}
final Combine combine = of.createCombine().withSource(fun.getOperand().get(0));
if (fun.getOperand().size() == 2) {
combine.setSeparator(fun.getOperand().get(1));
}
builder.resolveCall("System", "Combine", new CombineInvocation(combine));
return combine;
} | java |
private UnaryExpression resolveUnary(FunctionRef fun) {
UnaryExpression operator = null;
try {
Class clazz = Class.forName("org.hl7.elm.r1." + fun.getName());
if (UnaryExpression.class.isAssignableFrom(clazz)) {
operator = (UnaryExpression) clazz.newInstance();
checkNumberOfOperands(fun, 1);
operator.setOperand(fun.getOperand().get(0));
builder.resolveUnaryCall("System", fun.getName(), operator);
return operator;
}
} catch (Exception e) {
// Do nothing but fall through
}
return null;
} | java |
public void setStatusBarTintEnabled(boolean enabled) {
mStatusBarTintEnabled = enabled;
if (mStatusBarAvailable) {
mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
} | java |
public void setNavigationBarTintEnabled(boolean enabled) {
mNavBarTintEnabled = enabled;
if (mNavBarAvailable) {
mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
}
} | java |
@TargetApi(11)
public void setStatusBarAlpha(float alpha) {
if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mStatusBarTintView.setAlpha(alpha);
}
} | java |
@TargetApi(11)
public void setNavigationBarAlpha(float alpha) {
if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mNavBarTintView.setAlpha(alpha);
}
} | java |
public Completable addProduct(Product product) {
List<Product> updatedShoppingCart = new ArrayList<>();
updatedShoppingCart.addAll(itemsInShoppingCart.getValue());
updatedShoppingCart.add(product);
itemsInShoppingCart.onNext(updatedShoppingCart);
return Completable.complete();
} | java |
public Completable removeProduct(Product product) {
List<Product> updatedShoppingCart = new ArrayList<>();
updatedShoppingCart.addAll(itemsInShoppingCart.getValue());
updatedShoppingCart.remove(product);
itemsInShoppingCart.onNext(updatedShoppingCart);
return Completable.complete();
} | java |
public Completable removeProducts(List<Product> products) {
List<Product> updatedShoppingCart = new ArrayList<>();
updatedShoppingCart.addAll(itemsInShoppingCart.getValue());
updatedShoppingCart.removeAll(products);
itemsInShoppingCart.onNext(updatedShoppingCart);
return Completable.complete();
} | java |
public void subscribe(Observable<M> observable, final boolean pullToRefresh) {
if (isViewAttached()) {
getView().showLoading(pullToRefresh);
}
unsubscribe();
subscriber = new Subscriber<M>() {
private boolean ptr = pullToRefresh;
@Override public void onCompleted() {
BaseRxLcePresenter.this.onCompleted();
}
@Override public void onError(Throwable e) {
BaseRxLcePresenter.this.onError(e, ptr);
}
@Override public void onNext(M m) {
BaseRxLcePresenter.this.onNext(m);
}
};
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
} | java |
@NonNull protected ActivityMvpDelegate<V, P> getMvpDelegate() {
if (mvpDelegate == null) {
mvpDelegate = new ActivityMvpDelegateImpl(this, this, true);
}
return mvpDelegate;
} | java |
@MainThread
private void subscribeViewStateConsumerActually(@NonNull final V view) {
if (view == null) {
throw new NullPointerException("View is null");
}
if (viewStateConsumer == null) {
throw new NullPointerException(ViewStateConsumer.class.getSimpleName()
+ " is null. This is a Mosby internal bug. Please file an issue at https://github.com/sockeqwe/mosby/issues");
}
viewRelayConsumerDisposable = viewStateBehaviorSubject.subscribe(new Consumer<VS>() {
@Override
public void accept(VS vs) throws Exception {
viewStateConsumer.accept(view, vs);
}
});
} | java |
@Override public Observable<Account> doLogin(AuthCredentials credentials) {
return Observable.just(credentials).flatMap(new Func1<AuthCredentials, Observable<Account>>() {
@Override public Observable<Account> call(AuthCredentials credentials) {
try {
// Simulate network delay
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (credentials.getUsername().equals("ted") && credentials.getPassword().equals("robin")) {
currentAccount = new Account();
return Observable.just(currentAccount);
}
return Observable.error(new LoginException());
}
});
} | java |
public static void showErrorView(@NonNull final View loadingView, @NonNull final View contentView,
final View errorView) {
contentView.setVisibility(View.GONE);
final Resources resources = loadingView.getResources();
// Not visible yet, so animate the view in
AnimatorSet set = new AnimatorSet();
ObjectAnimator in = ObjectAnimator.ofFloat(errorView, View.ALPHA, 1f);
ObjectAnimator loadingOut = ObjectAnimator.ofFloat(loadingView, View.ALPHA, 0f);
set.playTogether(in, loadingOut);
set.setDuration(resources.getInteger(R.integer.lce_error_view_show_animation_time));
set.addListener(new AnimatorListenerAdapter() {
@Override public void onAnimationStart(Animator animation) {
super.onAnimationStart(animation);
errorView.setVisibility(View.VISIBLE);
}
@Override public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
loadingView.setVisibility(View.GONE);
loadingView.setAlpha(1f); // For future showLoading calls
}
});
set.start();
} | java |
public static void showContent(@NonNull final View loadingView, @NonNull final View contentView,
@NonNull final View errorView) {
if (contentView.getVisibility() == View.VISIBLE) {
// No Changing needed, because contentView is already visible
errorView.setVisibility(View.GONE);
loadingView.setVisibility(View.GONE);
} else {
errorView.setVisibility(View.GONE);
final Resources resources = loadingView.getResources();
final int translateInPixels = resources.getDimensionPixelSize(R.dimen.lce_content_view_animation_translate_y);
// Not visible yet, so animate the view in
AnimatorSet set = new AnimatorSet();
ObjectAnimator contentFadeIn = ObjectAnimator.ofFloat(contentView, View.ALPHA, 0f, 1f);
ObjectAnimator contentTranslateIn = ObjectAnimator.ofFloat(contentView, View.TRANSLATION_Y,
translateInPixels, 0);
ObjectAnimator loadingFadeOut = ObjectAnimator.ofFloat(loadingView, View.ALPHA, 1f, 0f);
ObjectAnimator loadingTranslateOut = ObjectAnimator.ofFloat(loadingView, View.TRANSLATION_Y, 0,
-translateInPixels);
set.playTogether(contentFadeIn, contentTranslateIn, loadingFadeOut, loadingTranslateOut);
set.setDuration(resources.getInteger(R.integer.lce_content_view_show_animation_time));
set.addListener(new AnimatorListenerAdapter() {
@Override public void onAnimationStart(Animator animation) {
contentView.setTranslationY(0);
loadingView.setTranslationY(0);
contentView.setVisibility(View.VISIBLE);
}
@Override public void onAnimationEnd(Animator animation) {
loadingView.setVisibility(View.GONE);
loadingView.setAlpha(1f); // For future showLoading calls
contentView.setTranslationY(0);
loadingView.setTranslationY(0);
}
});
set.start();
}
} | java |
private boolean isSubTypeOfMvpView(Class<?> klass) {
if (klass.equals(MvpView.class)) {
return true;
}
Class[] superInterfaces = klass.getInterfaces();
for (int i = 0; i < superInterfaces.length; i++) {
if (isSubTypeOfMvpView(superInterfaces[i])) {
return true;
}
}
return false;
} | java |
public static int dpToPx(Context context, float dp) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return (int) ((dp * displayMetrics.density) + 0.5);
} | java |
public static int pxToDp(Context context, int px) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return (int) ((px / displayMetrics.density) + 0.5);
} | java |
public static float pxToSp(Context context, Float px) {
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return px / scaledDensity;
} | java |
private P restorePresenterOrRecreateNewPresenterAfterProcessDeath() {
P presenter;
if (keepPresenterInstanceDuringScreenOrientationChanges) {
if (mosbyViewId != null
&& (presenter = PresenterManager.getPresenter(getActivity(), mosbyViewId)) != null) {
//
// Presenter restored from cache
//
if (DEBUG) {
Log.d(DEBUG_TAG,
"Reused presenter " + presenter + " for view " + delegateCallback.getMvpView());
}
return presenter;
} else {
//
// No presenter found in cache, most likely caused by process death
//
presenter = createViewIdAndPresenter();
if (DEBUG) {
Log.d(DEBUG_TAG, "No presenter found although view Id was here: "
+ mosbyViewId
+ ". Most likely this was caused by a process death. New Presenter created"
+ presenter
+ " for view "
+ delegateCallback.getMvpView());
}
return presenter;
}
} else {
//
// starting first time, so create a new presenter
//
presenter = createViewIdAndPresenter();
if (DEBUG) {
Log.d(DEBUG_TAG,
"New presenter " + presenter + " for view " + delegateCallback.getMvpView());
}
return presenter;
}
} | java |
private VS createViewState() {
VS viewState = delegateCallback.createViewState();
if (viewState == null) {
throw new NullPointerException(
"ViewState returned from createViewState() is null. Fragment is " + fragment);
}
if (keepPresenterInstanceDuringScreenOrientationChanges) {
PresenterManager.putViewState(getActivity(), mosbyViewId, viewState);
}
return viewState;
} | java |
public Observable<ProductDetailsViewState> getDetails(int productId) {
return getProductWithShoppingCartInfo(productId)
.subscribeOn(Schedulers.io())
.map(ProductDetailsViewState.DataState::new)
.cast(ProductDetailsViewState.class)
.startWith(new ProductDetailsViewState.LoadingState())
.onErrorReturn(ProductDetailsViewState.ErrorState::new);
} | java |
public Observable<List<Product>> getAllProducts() {
return Observable.zip(getProducts(0), getProducts(1), getProducts(2), getProducts(3),
(products0, products1, products2, products3) -> {
List<Product> productList = new ArrayList<Product>();
productList.addAll(products0);
productList.addAll(products1);
productList.addAll(products2);
productList.addAll(products3);
return productList;
});
} | java |
public Observable<List<Product>> getAllProductsOfCategory(String categoryName) {
return getAllProducts().flatMap(Observable::fromIterable)
.filter(product -> product.getCategory().equals(categoryName))
.toList()
.toObservable();
} | java |
public Observable<List<String>> getAllCategories() {
return getAllProducts().map(products -> {
Set<String> categories = new HashSet<String>();
for (Product p : products) {
categories.add(p.getCategory());
}
List<String> result = new ArrayList<String>(categories.size());
result.addAll(categories);
return result;
});
} | java |
public Observable<Product> getProduct(int productId) {
return getAllProducts().flatMap(products -> Observable.fromIterable(products))
.filter(product -> product.getId() == productId)
.take(1);
} | java |
public Observable<List<Product>> loadProductsOfCategory(String categoryName) {
return backendApi.getAllProductsOfCategory(categoryName).delay(3, TimeUnit.SECONDS);
} | java |
private void runQueuedActions() {
V view = viewRef == null ? null : viewRef.get();
if (view != null) {
while (!viewActionQueue.isEmpty()) {
ViewAction<V> action = viewActionQueue.poll();
action.run(view);
}
}
} | java |
public static boolean hideKeyboard(View view) {
if (view == null) {
throw new NullPointerException("View is null!");
}
try {
InputMethodManager imm =
(InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) {
return false;
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
} catch (Exception e) {
return false;
}
return true;
} | java |
public Observable<SearchViewState> search(String searchString) {
// Empty String, so no search
if (searchString.isEmpty()) {
return Observable.just(new SearchViewState.SearchNotStartedYet());
}
// search for product
return searchEngine.searchFor(searchString)
.map(products -> {
if (products.isEmpty()) {
return new SearchViewState.EmptyResult(searchString);
} else {
return new SearchViewState.SearchResult(searchString, products);
}
})
.startWith(new SearchViewState.Loading())
.onErrorReturn(error -> new SearchViewState.Error(searchString, error));
} | java |
public Observable<List<Label>> getLabels() {
return Observable.just(mails).flatMap(new Func1<List<Mail>, Observable<List<Label>>>() {
@Override public Observable<List<Label>> call(List<Mail> mails) {
delay();
Observable error = checkExceptions();
if (error != null) {
return error;
}
List<Label> labels = new ArrayList<>(4);
labels.add(INBOX_LABEL);
labels.add(sentLabel);
labels.add(spamLabel);
labels.add(trashLabel);
int inbox = 0;
int spam = 0;
int sent = 0;
int trash = 0;
for (Mail m : mails) {
if (m.isRead()) {
continue;
}
switch (m.getLabel()) {
case Label.INBOX:
inbox++;
break;
case Label.SENT:
sent++;
break;
case Label.SPAM:
spam++;
break;
case Label.TRASH:
trash++;
break;
}
}
INBOX_LABEL.setUnreadCount(inbox);
sentLabel.setUnreadCount(sent);
spamLabel.setUnreadCount(spam);
trashLabel.setUnreadCount(trash);
return Observable.just(labels);
}
});
} | java |
public Observable<List<Mail>> getMailsOfLabel(final String l) {
return getFilteredMailList(new Func1<Mail, Boolean>() {
@Override public Boolean call(Mail mail) {
return mail.getLabel().equals(l);
}
});
} | java |
public Observable<Mail> starMail(int mailId, final boolean star) {
return getMail(mailId).map(new Func1<Mail, Mail>() {
@Override public Mail call(Mail mail) {
mail.setStarred(star);
return mail;
}
});
} | java |
public Observable<Mail> addMailWithDelay(final Mail mail) {
return Observable.defer(new Func0<Observable<Mail>>() {
@Override public Observable<Mail> call() {
delay();
Observable o = checkExceptions();
if (o != null) {
return o;
}
return Observable.just(mail);
}
}).flatMap(new Func1<Mail, Observable<Mail>>() {
@Override public Observable<Mail> call(Mail mail) {
return addMail(mail);
}
});
} | java |
private Observable<List<Mail>> getFilteredMailList(Func1<Mail, Boolean> filterFnc,
final boolean withDelayAndError) {
return Observable.defer(new Func0<Observable<Mail>>() {
@Override public Observable<Mail> call() {
if (withDelayAndError) {
delay();
Observable o = checkExceptions();
if (o != null) {
return o;
}
}
return Observable.from(mails);
}
}).filter(filterFnc).collect(new Func0<List<Mail>>() {
@Override public List<Mail> call() {
return new ArrayList<Mail>();
}
}, new Action2<List<Mail>, Mail>() {
@Override public void call(List<Mail> mails, Mail mail) {
mails.add(mail);
}
}).map(new Func1<List<Mail>, List<Mail>>() {
@Override public List<Mail> call(List<Mail> mails) {
Collections.sort(mails, MailComparator.INSTANCE);
return mails;
}
});
} | java |
public Mail findMail(int id) {
if (items == null) {
return null;
}
for (Mail m : items) {
if (m.getId() == id) {
return m;
}
}
return null;
} | java |
private boolean isProductMatchingSearchCriteria(Product product, String searchQueryText) {
String words[] = searchQueryText.split(" ");
for (String w : words) {
if (product.getName().contains(w)) return true;
if (product.getDescription().contains(w)) return true;
if (product.getCategory().contains(w)) return true;
}
return false;
} | java |
public void addAndStartListener(final ProcessorListener<ApiType> processorListener) {
lock.writeLock().lock();
try {
addListenerLocked(processorListener);
executorService.execute(processorListener);
} finally {
lock.writeLock().unlock();
}
} | java |
public void addListener(final ProcessorListener<ApiType> processorListener) {
lock.writeLock().lock();
try {
addListenerLocked(processorListener);
} finally {
lock.writeLock().unlock();
}
} | java |
public void run() {
lock.readLock().lock();
try {
if (Collections.isEmptyCollection(listeners)) {
return;
}
for (ProcessorListener listener : listeners) {
executorService.execute(listener);
}
} finally {
lock.readLock().unlock();
}
} | java |
public void distribute(ProcessorListener.Notification<ApiType> obj, boolean isSync) {
lock.readLock().lock();
try {
if (isSync) {
for (ProcessorListener<ApiType> listener : syncingListeners) {
listener.add(obj);
}
} else {
for (ProcessorListener<ApiType> listener : listeners) {
listener.add(obj);
}
}
} finally {
lock.readLock().unlock();
}
} | java |
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
} | java |
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
} | java |
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
} | java |
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
} | java |
public void setAccessToken(String accessToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
((OAuth) auth).setAccessToken(accessToken);
return;
}
}
throw new RuntimeException("No OAuth2 authentication configured!");
} | java |
@SuppressWarnings("unchecked")
public <T> T deserialize(Response response, Type returnType) throws ApiException {
if (response == null || returnType == null) {
return null;
}
if ("byte[]".equals(returnType.toString())) {
// Handle binary response (byte array).
try {
return (T) response.body().bytes();
} catch (IOException e) {
throw new ApiException(e);
}
} else if (returnType.equals(File.class)) {
// Handle file downloading.
return (T) downloadFileFromResponse(response);
}
String respBody;
try {
if (response.body() != null)
respBody = response.body().string();
else
respBody = null;
} catch (IOException e) {
throw new ApiException(e);
}
if (respBody == null || "".equals(respBody)) {
return null;
}
String contentType = response.headers().get("Content-Type");
if (contentType == null) {
// ensuring a default content type
contentType = "application/json";
}
if (isJsonMime(contentType)) {
return json.deserialize(respBody, returnType);
} else if (returnType.equals(String.class)) {
// Expecting string, return the raw response body.
return (T) respBody;
} else {
throw new ApiException(
"Content type \"" + contentType + "\" is not supported for type: " + returnType,
response.code(),
response.headers().toMultimap(),
respBody);
}
} | java |
public RequestBody serialize(Object obj, String contentType) throws ApiException {
if (obj instanceof byte[]) {
// Binary (byte array) body parameter support.
return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
} else if (obj instanceof File) {
// File body parameter support.
return RequestBody.create(MediaType.parse(contentType), (File) obj);
} else if (isJsonMime(contentType)) {
String content;
if (obj != null) {
content = json.serialize(obj);
} else {
content = null;
}
return RequestBody.create(MediaType.parse(contentType), content);
} else {
throw new ApiException("Content type \"" + contentType + "\" is not supported");
}
} | java |
public File downloadFileFromResponse(Response response) throws ApiException {
try {
File file = prepareDownloadFile(response);
BufferedSink sink = Okio.buffer(Okio.sink(file));
sink.writeAll(response.body().source());
sink.close();
return file;
} catch (IOException e) {
throw new ApiException(e);
}
} | java |
public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
try {
Response response = call.execute();
T data = handleResponse(response, returnType);
return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
} catch (IOException e) {
throw new ApiException(e);
}
} | java |
@SuppressWarnings("unchecked")
public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
callback.onFailure(new ApiException(e), 0, null);
}
@Override
public void onResponse(Response response) throws IOException {
T result;
try {
result = (T) handleResponse(response, returnType);
} catch (ApiException e) {
callback.onFailure(e, response.code(), response.headers().toMultimap());
return;
}
callback.onSuccess(result, response.code(), response.headers().toMultimap());
}
});
} | java |
public Call buildCall(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, formParams, authNames, progressRequestListener);
return httpClient.newCall(request);
} | java |
public Request buildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
final String url = buildUrl(path, queryParams, collectionQueryParams);
final Request.Builder reqBuilder = new Request.Builder().url(url);
processHeaderParams(headerParams, reqBuilder);
String contentType = (String) headerParams.get("Content-Type");
// ensuring a default content type
if (contentType == null) {
contentType = "application/json";
}
RequestBody reqBody;
if (!HttpMethod.permitsRequestBody(method)) {
reqBody = null;
} else if ("application/x-www-form-urlencoded".equals(contentType)) {
reqBody = buildRequestBodyFormEncoding(formParams);
} else if ("multipart/form-data".equals(contentType)) {
reqBody = buildRequestBodyMultipart(formParams);
} else if (body == null) {
if ("DELETE".equals(method)) {
// allow calling DELETE without sending a request body
reqBody = null;
} else {
// use an empty request body (for POST, PUT and PATCH)
reqBody = RequestBody.create(MediaType.parse(contentType), "");
}
} else {
reqBody = serialize(body, contentType);
}
Request request = null;
if(progressRequestListener != null && reqBody != null) {
ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener);
request = reqBuilder.method(method, progressRequestBody).build();
} else {
request = reqBuilder.method(method, reqBody).build();
}
return request;
} | java |
public void processHeaderParams(Map<String, String> headerParams, Request.Builder reqBuilder) {
for (Entry<String, String> param : headerParams.entrySet()) {
reqBuilder.header(param.getKey(), parameterToString(param.getValue()));
}
for (Entry<String, String> header : defaultHeaderMap.entrySet()) {
if (!headerParams.containsKey(header.getKey())) {
reqBuilder.header(header.getKey(), parameterToString(header.getValue()));
}
}
} | java |
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams);
}
} | java |
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
FormEncodingBuilder formBuilder = new FormEncodingBuilder();
for (Entry<String, Object> param : formParams.entrySet()) {
formBuilder.add(param.getKey(), parameterToString(param.getValue()));
}
return formBuilder.build();
} | java |
private void applySslSettings() {
try {
TrustManager[] trustManagers = null;
HostnameVerifier hostnameVerifier = null;
if (!verifyingSsl) {
TrustManager trustAll = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() { return null; }
};
SSLContext sslContext = SSLContext.getInstance("TLS");
trustManagers = new TrustManager[]{ trustAll };
hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) { return true; }
};
} else if (sslCaCert != null) {
char[] password = null; // Any password will work.
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(sslCaCert);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
KeyStore caKeyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = "ca" + Integer.toString(index++);
caKeyStore.setCertificateEntry(certificateAlias, certificate);
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(caKeyStore);
trustManagers = trustManagerFactory.getTrustManagers();
}
if (keyManagers != null || trustManagers != null) {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, new SecureRandom());
httpClient.setSslSocketFactory(sslContext.getSocketFactory());
} else {
httpClient.setSslSocketFactory(null);
}
httpClient.setHostnameVerifier(hostnameVerifier);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
} | java |
public void stop() {
reflector.stop();
reflectorFuture.cancel(true);
reflectExecutor.shutdown();
if (resyncFuture != null) {
resyncFuture.cancel(true);
resyncExecutor.shutdown();
}
} | java |
private void processLoop() {
while (true) {
try {
this.queue.pop(this.processFunc);
} catch (InterruptedException t) {
log.error("DefaultController#processLoop get interrupted {}", t.getMessage(), t);
}
}
} | java |
@Override
public void add(Object obj) {
lock.writeLock().lock();
try {
populated = true;
this.queueActionLocked(DeltaType.Added, obj);
} finally {
lock.writeLock().unlock();
}
} | java |
@Override
public void update(Object obj) {
lock.writeLock().lock();
try {
populated = true;
this.queueActionLocked(DeltaType.Updated, obj);
} finally {
lock.writeLock().unlock();
}
} | java |
@Override
public void delete(Object obj) {
String id = this.keyOf(obj);
lock.writeLock().lock();
try {
this.populated = true;
if (this.knownObjects == null) {
if (!this.items.containsKey(id)) {
// Presumably, this was deleted when a relist happened.
// Don't provide a second report of the same deletion.
return;
}
} else {
// We only want to skip the "deletion" action if the object doesn't
// exist in knownObjects and it doesn't have corresponding item in items.
if (this.knownObjects.getByKey(id) == null && !this.items.containsKey(id)) {
return;
}
}
this.queueActionLocked(DeltaType.Deleted, obj);
} finally {
lock.writeLock().unlock();
}
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.