repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
|---|---|---|---|---|---|---|
gelldur/Common-Android
|
src/com/dexode/util/ShareIntentBuilder.java
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
|
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.LabeledIntent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.annotation.Nullable;
import com.dexode.util.log.Logger;
import com.google.android.gms.plus.PlusShare;
import java.util.ArrayList;
import java.util.List;
|
final PackageManager packageManager = context.getPackageManager();
ArrayList<LabeledIntent> extraIntents = new ArrayList<>(_intents.size() * 2);
Intent mainIntent = null;
for (int i = 0; i < _intents.size(); ++i) {
Intent intent = _intents.get(i);
List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, 0);
if (resolveInfoList == null) {//Some devices return null...
continue;
}
if (mainIntent == null && resolveInfoList.isEmpty() == false) {
mainIntent = intent;
//This will be main chooser so we don't want duplicates
continue;
}
for (ResolveInfo info : resolveInfoList) {
// Extract the label, append it, and repackage it in a LabeledIntent
String packageName = info.activityInfo.packageName;
intent.setComponent(new ComponentName(packageName, info.activityInfo.name));
final LabeledIntent labeledIntent =
new LabeledIntent(intent, packageName, info.loadLabel(packageManager), info.icon);
extraIntents.add(labeledIntent);
}
}
if (mainIntent == null) {
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
// Path: src/com/dexode/util/ShareIntentBuilder.java
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.LabeledIntent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.annotation.Nullable;
import com.dexode.util.log.Logger;
import com.google.android.gms.plus.PlusShare;
import java.util.ArrayList;
import java.util.List;
final PackageManager packageManager = context.getPackageManager();
ArrayList<LabeledIntent> extraIntents = new ArrayList<>(_intents.size() * 2);
Intent mainIntent = null;
for (int i = 0; i < _intents.size(); ++i) {
Intent intent = _intents.get(i);
List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, 0);
if (resolveInfoList == null) {//Some devices return null...
continue;
}
if (mainIntent == null && resolveInfoList.isEmpty() == false) {
mainIntent = intent;
//This will be main chooser so we don't want duplicates
continue;
}
for (ResolveInfo info : resolveInfoList) {
// Extract the label, append it, and repackage it in a LabeledIntent
String packageName = info.activityInfo.packageName;
intent.setComponent(new ComponentName(packageName, info.activityInfo.name));
final LabeledIntent labeledIntent =
new LabeledIntent(intent, packageName, info.loadLabel(packageManager), info.icon);
extraIntents.add(labeledIntent);
}
}
if (mainIntent == null) {
|
Logger.e("No app can't handle such share request");
|
gelldur/Common-Android
|
src/okhttp3/interceptor/LogInterceptor.java
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
|
import com.dexode.util.log.Logger;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
|
package okhttp3.interceptor;
/**
* Created by Dawid Drozd aka Gelldur on 25.01.16.
*/
public class LogInterceptor implements Interceptor {
private static final String F_BREAK = " %n";
private static final String F_URL = " %s";
private static final String F_TIME = " in %.1fms";
private static final String F_HEADERS = "%s";
private static final String F_RESPONSE = F_BREAK + "Response: %d";
private static final String F_BODY = "body: %s";
private static final String F_BREAKER = F_BREAK + "-------------------------------------------" + F_BREAK;
private static final String F_REQUEST_WITHOUT_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS;
private static final String F_RESPONSE_WITHOUT_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BREAKER;
private static final String F_REQUEST_WITH_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS + F_BODY + F_BREAK;
private static final String F_RESPONSE_WITH_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BODY + F_BREAK + F_BREAKER;
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Response response = chain.proceed(request);
long t2 = System.nanoTime();
MediaType contentType = null;
String bodyString = null;
if (response.body() != null) {
contentType = response.body().contentType();
bodyString = response.body().string();
}
double time = (t2 - t1) / 1e6d;
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
// Path: src/okhttp3/interceptor/LogInterceptor.java
import com.dexode.util.log.Logger;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
package okhttp3.interceptor;
/**
* Created by Dawid Drozd aka Gelldur on 25.01.16.
*/
public class LogInterceptor implements Interceptor {
private static final String F_BREAK = " %n";
private static final String F_URL = " %s";
private static final String F_TIME = " in %.1fms";
private static final String F_HEADERS = "%s";
private static final String F_RESPONSE = F_BREAK + "Response: %d";
private static final String F_BODY = "body: %s";
private static final String F_BREAKER = F_BREAK + "-------------------------------------------" + F_BREAK;
private static final String F_REQUEST_WITHOUT_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS;
private static final String F_RESPONSE_WITHOUT_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BREAKER;
private static final String F_REQUEST_WITH_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS + F_BODY + F_BREAK;
private static final String F_RESPONSE_WITH_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BODY + F_BREAK + F_BREAKER;
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Response response = chain.proceed(request);
long t2 = System.nanoTime();
MediaType contentType = null;
String bodyString = null;
if (response.body() != null) {
contentType = response.body().contentType();
bodyString = response.body().string();
}
double time = (t2 - t1) / 1e6d;
|
Logger.i(
|
gelldur/Common-Android
|
src/com/dexode/util/UtilsHash.java
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
|
import com.dexode.util.log.Logger;
import java.math.BigInteger;
import java.security.MessageDigest;
|
package com.dexode.util;
/**
* Created by Dawid Drozd aka Gelldur on 11.03.15.
*/
public class UtilsHash {
public static String md5(String input) {
MessageDigest digest;
try {
byte[] bytes = input.getBytes("UTF-8");
digest = MessageDigest.getInstance("MD5");
digest.update(bytes);
return new BigInteger(1, digest.digest()).toString(16);
} catch (Exception e) {
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
// Path: src/com/dexode/util/UtilsHash.java
import com.dexode.util.log.Logger;
import java.math.BigInteger;
import java.security.MessageDigest;
package com.dexode.util;
/**
* Created by Dawid Drozd aka Gelldur on 11.03.15.
*/
public class UtilsHash {
public static String md5(String input) {
MessageDigest digest;
try {
byte[] bytes = input.getBytes("UTF-8");
digest = MessageDigest.getInstance("MD5");
digest.update(bytes);
return new BigInteger(1, digest.digest()).toString(16);
} catch (Exception e) {
|
Logger.e(e);
|
gelldur/Common-Android
|
src/com/dexode/adapter/ViewHolderAdapterHelper.java
|
// Path: src/com/dexode/util/Assert.java
// public class Assert {
// public static void check(boolean value) {
// check(value, null);
// }
//
// public static void check(boolean value, @Nullable String message) {
// if (value) {
// return;
// }
// throw new AssertionError(message);
// }
// }
|
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import com.dexode.util.Assert;
|
package com.dexode.adapter;
/**
* Created by Dawid Drozd aka Gelldur on 09.02.15.
*/
public class ViewHolderAdapterHelper {
public ViewHolderAdapterHelper(final Adapter adapter) {
_adapter = adapter;
}
public View getView(int position, View convertView, ViewGroup parent) {
Object holder = null;
if (convertView == null || convertView.getTag() == null) {
convertView = _adapter.getInflatedRow(position, parent);
holder = _adapter.getNewHolder(position);
_adapter.inflateHolder(holder, convertView, position);
convertView.setTag(holder);
} else {
holder = convertView.getTag();
}
final View view = _adapter.setHolder(holder, convertView, parent, position);
|
// Path: src/com/dexode/util/Assert.java
// public class Assert {
// public static void check(boolean value) {
// check(value, null);
// }
//
// public static void check(boolean value, @Nullable String message) {
// if (value) {
// return;
// }
// throw new AssertionError(message);
// }
// }
// Path: src/com/dexode/adapter/ViewHolderAdapterHelper.java
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import com.dexode.util.Assert;
package com.dexode.adapter;
/**
* Created by Dawid Drozd aka Gelldur on 09.02.15.
*/
public class ViewHolderAdapterHelper {
public ViewHolderAdapterHelper(final Adapter adapter) {
_adapter = adapter;
}
public View getView(int position, View convertView, ViewGroup parent) {
Object holder = null;
if (convertView == null || convertView.getTag() == null) {
convertView = _adapter.getInflatedRow(position, parent);
holder = _adapter.getNewHolder(position);
_adapter.inflateHolder(holder, convertView, position);
convertView.setTag(holder);
} else {
holder = convertView.getTag();
}
final View view = _adapter.setHolder(holder, convertView, parent, position);
|
Assert.check(view != null, "setHolder must return view");
|
gelldur/Common-Android
|
src/com/dexode/adapter/RecyclerAdapter.java
|
// Path: src/com/dexode/adapter/holder/BaseHolder.java
// public abstract class BaseHolder extends RecyclerView.ViewHolder {
// public BaseHolder(final View itemView) {
// super(itemView);
// }
//
//
// public abstract void setData(final RecyclerAdapter.Element element);
// }
//
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
|
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.dexode.adapter.holder.BaseHolder;
import com.dexode.util.log.Logger;
import java.util.ArrayList;
import java.util.List;
|
package com.dexode.adapter;
/**
* Created by Dawid Drozd aka Gelldur on 16.02.16.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<BaseHolder> {
public RecyclerAdapter(final Activity activity) {
_layoutInflater = activity.getLayoutInflater();
_commandManager = new RecyclerAdapterCommandManager(this);
}
@Override
public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
_commandManager.onAttachedToRecyclerView();
}
@Override
public BaseHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
final View view = _layoutInflater.inflate(viewType, parent, false);
final ViewHolderCreator viewHolderCreator = _holderCreators.get(viewType);
if (viewHolderCreator == null) {
|
// Path: src/com/dexode/adapter/holder/BaseHolder.java
// public abstract class BaseHolder extends RecyclerView.ViewHolder {
// public BaseHolder(final View itemView) {
// super(itemView);
// }
//
//
// public abstract void setData(final RecyclerAdapter.Element element);
// }
//
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
// Path: src/com/dexode/adapter/RecyclerAdapter.java
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.dexode.adapter.holder.BaseHolder;
import com.dexode.util.log.Logger;
import java.util.ArrayList;
import java.util.List;
package com.dexode.adapter;
/**
* Created by Dawid Drozd aka Gelldur on 16.02.16.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<BaseHolder> {
public RecyclerAdapter(final Activity activity) {
_layoutInflater = activity.getLayoutInflater();
_commandManager = new RecyclerAdapterCommandManager(this);
}
@Override
public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
_commandManager.onAttachedToRecyclerView();
}
@Override
public BaseHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
final View view = _layoutInflater.inflate(viewType, parent, false);
final ViewHolderCreator viewHolderCreator = _holderCreators.get(viewType);
if (viewHolderCreator == null) {
|
Logger.e("Unknown holder creator " + viewType);
|
gelldur/Common-Android
|
src/com/dexode/service/WorkerService.java
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
|
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.dexode.util.log.Logger;
|
package com.dexode.service;
/**
* Created by Dawid Drozd aka Gelldur on 1/13/16.
*/
public class WorkerService extends IntentService {
public WorkerService() {
super("BackgroundWorker");
}
@Override
public void onCreate() {
super.onCreate();
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
// Path: src/com/dexode/service/WorkerService.java
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.dexode.util.log.Logger;
package com.dexode.service;
/**
* Created by Dawid Drozd aka Gelldur on 1/13/16.
*/
public class WorkerService extends IntentService {
public WorkerService() {
super("BackgroundWorker");
}
@Override
public void onCreate() {
super.onCreate();
|
Logger.d("%s - onCreate", getClass().getSimpleName());
|
gelldur/Common-Android
|
src/com/dexode/util/DeviceId.java
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
|
import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.provider.Settings.Secure;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.dexode.util.log.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
|
package com.dexode.util;
/**
* Created by Dawid Drozd aka Gelldur on 23.02.15.
*/
public class DeviceId {
@NonNull
public static String getDeviceId(Context appContext) throws RuntimeException {
final String deviceId = getDeviceIdBestFit(appContext);
return deviceId.toLowerCase();
}
@NonNull
private static String getDeviceIdBestFit(Context appContext) throws RuntimeException {
String deviceId = null;
if (deviceId == null && checkPermission(appContext, Manifest.permission.ACCESS_WIFI_STATE)) {
deviceId = getWiFiMacAddress(appContext);
if (deviceId != null) {
return deviceId;
}
} else {
|
// Path: src/com/dexode/util/log/Logger.java
// public class Logger {
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void d(final String text, Object... args) {
// if (_log != null) {
// _log.d(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void i(final String text, Object... args) {
// if (_log != null) {
// _log.i(text, args);
// }
// }
//
// /**
// * This method should be removed in release code by proguard
// */
// public static void w(final String text, Object... args) {
// if (_log != null) {
// _log.w(text, args);
// }
// }
//
// public static void e(final String text, Object... args) {
// if (_log != null) {
// _log.e(text, args);
// }
// }
//
// public static void e(final Exception exception, @Nullable final String text) {
// if (_log != null) {
// _log.e(exception, text);
// }
// }
//
// public static void e(final Exception exception) {
// if (_log != null) {
// _log.e(exception, null);
// }
// }
//
//
// public static void setLog(Log log) {
// _log = log;
// }
//
// @Nullable
// private static Log _log;
//
// public interface Log {
// /**
// * This method should be removed in release code by proguard
// */
// public void d(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void i(final String text, Object... args);
//
// /**
// * This method should be removed in release code by proguard
// */
// public void w(final String text, Object... args);
//
// public void e(final String text, Object... args);
//
// public void e(final Exception exception, @Nullable final String text);
// }
// }
// Path: src/com/dexode/util/DeviceId.java
import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.provider.Settings.Secure;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.dexode.util.log.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
package com.dexode.util;
/**
* Created by Dawid Drozd aka Gelldur on 23.02.15.
*/
public class DeviceId {
@NonNull
public static String getDeviceId(Context appContext) throws RuntimeException {
final String deviceId = getDeviceIdBestFit(appContext);
return deviceId.toLowerCase();
}
@NonNull
private static String getDeviceIdBestFit(Context appContext) throws RuntimeException {
String deviceId = null;
if (deviceId == null && checkPermission(appContext, Manifest.permission.ACCESS_WIFI_STATE)) {
deviceId = getWiFiMacAddress(appContext);
if (deviceId != null) {
return deviceId;
}
} else {
|
Logger.i("Please set android.permission.ACCESS_WIFI_STATE permission to get better user id");
|
yammer/telemetry
|
telemetry-example/src/main/java/com/yammer/telemetry/example/resources/DelayedWriteResource.java
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
|
import com.yammer.metrics.Metrics;
import com.yammer.metrics.annotation.Timed;
import com.yammer.metrics.core.Timer;
import com.yammer.metrics.core.TimerContext;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
|
package com.yammer.telemetry.example.resources;
@Path("/delayed")
public class DelayedWriteResource {
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/resources/DelayedWriteResource.java
import com.yammer.metrics.Metrics;
import com.yammer.metrics.annotation.Timed;
import com.yammer.metrics.core.Timer;
import com.yammer.metrics.core.TimerContext;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
package com.yammer.telemetry.example.resources;
@Path("/delayed")
public class DelayedWriteResource {
|
private final NapDAO napDAO;
|
yammer/telemetry
|
telemetry-example/src/main/java/com/yammer/telemetry/example/resources/DelayedWriteResource.java
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
|
import com.yammer.metrics.Metrics;
import com.yammer.metrics.annotation.Timed;
import com.yammer.metrics.core.Timer;
import com.yammer.metrics.core.TimerContext;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
|
package com.yammer.telemetry.example.resources;
@Path("/delayed")
public class DelayedWriteResource {
private final NapDAO napDAO;
private final ScheduledExecutorService executorService;
private static final Timer timer = Metrics.newTimer(DelayedWriteResource.class, "delayed-write");
public DelayedWriteResource(NapDAO napDAO, ScheduledExecutorService executorService) {
this.napDAO = napDAO;
this.executorService = executorService;
}
@GET
@Timed
@Path("/start/{start}/duration/{duration}")
public String delayedWrite(@PathParam("start") long start, @PathParam("duration") long duration) {
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/resources/DelayedWriteResource.java
import com.yammer.metrics.Metrics;
import com.yammer.metrics.annotation.Timed;
import com.yammer.metrics.core.Timer;
import com.yammer.metrics.core.TimerContext;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
package com.yammer.telemetry.example.resources;
@Path("/delayed")
public class DelayedWriteResource {
private final NapDAO napDAO;
private final ScheduledExecutorService executorService;
private static final Timer timer = Metrics.newTimer(DelayedWriteResource.class, "delayed-write");
public DelayedWriteResource(NapDAO napDAO, ScheduledExecutorService executorService) {
this.napDAO = napDAO;
this.executorService = executorService;
}
@GET
@Timed
@Path("/start/{start}/duration/{duration}")
public String delayedWrite(@PathParam("start") long start, @PathParam("duration") long duration) {
|
final Nap nap = new Nap(start, duration);
|
yammer/telemetry
|
telemetry-agent/src/test/java/com/yammer/telemetry/agent/handlers/EnvironmentExecutorClassHandlerTest.java
|
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
// public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
// Method[] methods = clazz.getDeclaredMethods();
// Map<Method, Throwable> testFailures = new HashMap<>();
// int ran = 0;
//
// for (Method method : methods) {
// if (method.isAnnotationPresent(TransformedTest.class)) {
// try {
// ran++;
// runTransformed(clazz, method.getName(), handlers);
// } catch (Exception e) {
// //noinspection ThrowableResultOfMethodCallIgnored
// testFailures.put(method, unwrap(e));
// }
// }
// }
//
// if (!testFailures.isEmpty()) {
// StringWriter builder = new StringWriter();
// PrintWriter writer = new PrintWriter(builder);
// writer.println("Transformed tests failed:");
// for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
// writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
// //noinspection ThrowableResultOfMethodCallIgnored
// entry.getValue().printStackTrace(writer);
// writer.println();
// }
// fail(builder.toString());
// }
//
// if (ran == 0) {
// fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
// }
// }
|
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.json.ObjectMapperFactory;
import com.yammer.dropwizard.validation.Validator;
import com.yammer.telemetry.test.TransformedTest;
import com.yammer.telemetry.tracing.*;
import javassist.ClassPool;
import javassist.CtClass;
import org.junit.After;
import org.junit.Test;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.*;
import static com.yammer.telemetry.test.TelemetryTestHelpers.runTransformed;
import static org.junit.Assert.*;
|
package com.yammer.telemetry.agent.handlers;
public class EnvironmentExecutorClassHandlerTest {
private EnvironmentExecutorClassHandler handler = new EnvironmentExecutorClassHandler();
@After
public void clearSpanSinkRegistry() {
SpanSinkRegistry.clear();
}
@Test
public void testNothingForUnrelatedClasses() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("java.lang.String");
assertFalse(handler.transformed(ctClass, cp));
}
@Test
public void testAltersEnvironmentsClass() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("com.yammer.dropwizard.config.Environment");
assertTrue(handler.transformed(ctClass, cp));
}
@Test
public void testRunTransformedTests() throws Exception {
|
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
// public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
// Method[] methods = clazz.getDeclaredMethods();
// Map<Method, Throwable> testFailures = new HashMap<>();
// int ran = 0;
//
// for (Method method : methods) {
// if (method.isAnnotationPresent(TransformedTest.class)) {
// try {
// ran++;
// runTransformed(clazz, method.getName(), handlers);
// } catch (Exception e) {
// //noinspection ThrowableResultOfMethodCallIgnored
// testFailures.put(method, unwrap(e));
// }
// }
// }
//
// if (!testFailures.isEmpty()) {
// StringWriter builder = new StringWriter();
// PrintWriter writer = new PrintWriter(builder);
// writer.println("Transformed tests failed:");
// for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
// writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
// //noinspection ThrowableResultOfMethodCallIgnored
// entry.getValue().printStackTrace(writer);
// writer.println();
// }
// fail(builder.toString());
// }
//
// if (ran == 0) {
// fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
// }
// }
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/handlers/EnvironmentExecutorClassHandlerTest.java
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.config.Environment;
import com.yammer.dropwizard.json.ObjectMapperFactory;
import com.yammer.dropwizard.validation.Validator;
import com.yammer.telemetry.test.TransformedTest;
import com.yammer.telemetry.tracing.*;
import javassist.ClassPool;
import javassist.CtClass;
import org.junit.After;
import org.junit.Test;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.*;
import static com.yammer.telemetry.test.TelemetryTestHelpers.runTransformed;
import static org.junit.Assert.*;
package com.yammer.telemetry.agent.handlers;
public class EnvironmentExecutorClassHandlerTest {
private EnvironmentExecutorClassHandler handler = new EnvironmentExecutorClassHandler();
@After
public void clearSpanSinkRegistry() {
SpanSinkRegistry.clear();
}
@Test
public void testNothingForUnrelatedClasses() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("java.lang.String");
assertFalse(handler.transformed(ctClass, cp));
}
@Test
public void testAltersEnvironmentsClass() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("com.yammer.dropwizard.config.Environment");
assertTrue(handler.transformed(ctClass, cp));
}
@Test
public void testRunTransformedTests() throws Exception {
|
runTransformed(TransformedTests.class, handler);
|
yammer/telemetry
|
telemetry-lib/src/test/java/com/yammer/telemetry/tracing/logging/LogJobFactoryTest.java
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/AnnotationData.java
// public interface AnnotationData {
// long getLoggedAt();
//
// String getName();
//
// String getMessage();
// }
//
// Path: telemetry-lib/src/test/java/com/yammer/telemetry/tracing/BeanSpanData.java
// public class BeanSpanData implements SpanData {
// private int duration;
// private String host;
// private String name;
// private Optional<BigInteger> parentSpanId;
// private BigInteger spanId;
// private long startTime;
// private BigInteger traceId;
// private List<AnnotationData> annotations;
//
// public BeanSpanData() {
// this.spanId = BigInteger.TEN;
// this.startTime = System.nanoTime();
// traceId = BigInteger.ONE;
// parentSpanId = Optional.absent();
// name = "Some Name";
// host = "Host-001";
// duration = 100;
// annotations = ImmutableList.of();
// }
//
// public BeanSpanData(int duration, String host, String name, Optional<BigInteger> parentSpanId, BigInteger spanId, long startTime, BigInteger traceId, List<AnnotationData> annotations) {
// this.duration = duration;
// this.host = host;
// this.name = name;
// this.parentSpanId = parentSpanId;
// this.spanId = spanId;
// this.startTime = startTime;
// this.traceId = traceId;
// this.annotations = annotations;
// }
//
// @Override
// public BigInteger getTraceId() {
// return traceId;
// }
//
// @Override
// public BigInteger getSpanId() {
// return spanId;
// }
//
// @Override
// public Optional<BigInteger> getParentSpanId() {
// return parentSpanId;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public String getHost() {
// return host;
// }
//
// @Override
// public long getStartTime() {
// return startTime;
// }
//
// @Override
// public long getDuration() {
// return duration;
// }
//
// @Override
// public List<AnnotationData> getAnnotations() {
// return annotations;
// }
//
// @SuppressWarnings("RedundantIfStatement")
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BeanSpanData that = (BeanSpanData) o;
//
// if (duration != that.duration) return false;
// if (startTime != that.startTime) return false;
// if (annotations != null ? !annotations.equals(that.annotations) : that.annotations != null) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (name != null ? !name.equals(that.name) : that.name != null) return false;
// if (parentSpanId != null ? !parentSpanId.equals(that.parentSpanId) : that.parentSpanId != null) return false;
// if (spanId != null ? !spanId.equals(that.spanId) : that.spanId != null) return false;
// if (traceId != null ? !traceId.equals(that.traceId) : that.traceId != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = duration;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + (name != null ? name.hashCode() : 0);
// result = 31 * result + (parentSpanId != null ? parentSpanId.hashCode() : 0);
// result = 31 * result + (spanId != null ? spanId.hashCode() : 0);
// result = 31 * result + (int) (startTime ^ (startTime >>> 32));
// result = 31 * result + (traceId != null ? traceId.hashCode() : 0);
// result = 31 * result + (annotations != null ? annotations.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "BeanSpanData{" +
// "duration=" + duration +
// ", host='" + host + '\'' +
// ", name='" + name + '\'' +
// ", parentSpanId=" + parentSpanId +
// ", spanId=" + spanId +
// ", startTime=" + startTime +
// ", traceId=" + traceId +
// ", annotations=" + annotations +
// '}';
// }
// }
|
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.yammer.telemetry.tracing.AnnotationData;
import com.yammer.telemetry.tracing.BeanSpanData;
import org.junit.Test;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigInteger;
import static org.junit.Assert.assertEquals;
|
public void testCreateWithNullFile() throws Exception {
LogJobFactory.withFile(null);
}
@Test
public void testCreateWithWriter() throws Exception {
LogJobFactory.withWriter(new StringWriter());
}
@Test(expected = NullPointerException.class)
public void testCreateWithNullWriter() throws Exception {
LogJobFactory.withWriter(null);
}
@Test
public void testWriteNull() throws Exception {
StringWriter writer = new StringWriter();
LogJobFactory logJobFactory = LogJobFactory.withWriter(writer);
Runnable job = logJobFactory.createJob(null);
job.run();
assertEquals(String.format("null%n"), writer.toString());
}
@Test
public void testWriteSpanData() throws Exception {
StringWriter writer = new StringWriter();
LogJobFactory logJobFactory = LogJobFactory.withWriter(writer);
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/AnnotationData.java
// public interface AnnotationData {
// long getLoggedAt();
//
// String getName();
//
// String getMessage();
// }
//
// Path: telemetry-lib/src/test/java/com/yammer/telemetry/tracing/BeanSpanData.java
// public class BeanSpanData implements SpanData {
// private int duration;
// private String host;
// private String name;
// private Optional<BigInteger> parentSpanId;
// private BigInteger spanId;
// private long startTime;
// private BigInteger traceId;
// private List<AnnotationData> annotations;
//
// public BeanSpanData() {
// this.spanId = BigInteger.TEN;
// this.startTime = System.nanoTime();
// traceId = BigInteger.ONE;
// parentSpanId = Optional.absent();
// name = "Some Name";
// host = "Host-001";
// duration = 100;
// annotations = ImmutableList.of();
// }
//
// public BeanSpanData(int duration, String host, String name, Optional<BigInteger> parentSpanId, BigInteger spanId, long startTime, BigInteger traceId, List<AnnotationData> annotations) {
// this.duration = duration;
// this.host = host;
// this.name = name;
// this.parentSpanId = parentSpanId;
// this.spanId = spanId;
// this.startTime = startTime;
// this.traceId = traceId;
// this.annotations = annotations;
// }
//
// @Override
// public BigInteger getTraceId() {
// return traceId;
// }
//
// @Override
// public BigInteger getSpanId() {
// return spanId;
// }
//
// @Override
// public Optional<BigInteger> getParentSpanId() {
// return parentSpanId;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public String getHost() {
// return host;
// }
//
// @Override
// public long getStartTime() {
// return startTime;
// }
//
// @Override
// public long getDuration() {
// return duration;
// }
//
// @Override
// public List<AnnotationData> getAnnotations() {
// return annotations;
// }
//
// @SuppressWarnings("RedundantIfStatement")
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BeanSpanData that = (BeanSpanData) o;
//
// if (duration != that.duration) return false;
// if (startTime != that.startTime) return false;
// if (annotations != null ? !annotations.equals(that.annotations) : that.annotations != null) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (name != null ? !name.equals(that.name) : that.name != null) return false;
// if (parentSpanId != null ? !parentSpanId.equals(that.parentSpanId) : that.parentSpanId != null) return false;
// if (spanId != null ? !spanId.equals(that.spanId) : that.spanId != null) return false;
// if (traceId != null ? !traceId.equals(that.traceId) : that.traceId != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = duration;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + (name != null ? name.hashCode() : 0);
// result = 31 * result + (parentSpanId != null ? parentSpanId.hashCode() : 0);
// result = 31 * result + (spanId != null ? spanId.hashCode() : 0);
// result = 31 * result + (int) (startTime ^ (startTime >>> 32));
// result = 31 * result + (traceId != null ? traceId.hashCode() : 0);
// result = 31 * result + (annotations != null ? annotations.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "BeanSpanData{" +
// "duration=" + duration +
// ", host='" + host + '\'' +
// ", name='" + name + '\'' +
// ", parentSpanId=" + parentSpanId +
// ", spanId=" + spanId +
// ", startTime=" + startTime +
// ", traceId=" + traceId +
// ", annotations=" + annotations +
// '}';
// }
// }
// Path: telemetry-lib/src/test/java/com/yammer/telemetry/tracing/logging/LogJobFactoryTest.java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.yammer.telemetry.tracing.AnnotationData;
import com.yammer.telemetry.tracing.BeanSpanData;
import org.junit.Test;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigInteger;
import static org.junit.Assert.assertEquals;
public void testCreateWithNullFile() throws Exception {
LogJobFactory.withFile(null);
}
@Test
public void testCreateWithWriter() throws Exception {
LogJobFactory.withWriter(new StringWriter());
}
@Test(expected = NullPointerException.class)
public void testCreateWithNullWriter() throws Exception {
LogJobFactory.withWriter(null);
}
@Test
public void testWriteNull() throws Exception {
StringWriter writer = new StringWriter();
LogJobFactory logJobFactory = LogJobFactory.withWriter(writer);
Runnable job = logJobFactory.createJob(null);
job.run();
assertEquals(String.format("null%n"), writer.toString());
}
@Test
public void testWriteSpanData() throws Exception {
StringWriter writer = new StringWriter();
LogJobFactory logJobFactory = LogJobFactory.withWriter(writer);
|
BeanSpanData expectedData = new BeanSpanData(100, "host", "name", Optional.<BigInteger>absent(), BigInteger.ZERO, 15, BigInteger.ONE, ImmutableList.<AnnotationData>of());
|
yammer/telemetry
|
telemetry-lib/src/test/java/com/yammer/telemetry/tracing/logging/LogJobFactoryTest.java
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/AnnotationData.java
// public interface AnnotationData {
// long getLoggedAt();
//
// String getName();
//
// String getMessage();
// }
//
// Path: telemetry-lib/src/test/java/com/yammer/telemetry/tracing/BeanSpanData.java
// public class BeanSpanData implements SpanData {
// private int duration;
// private String host;
// private String name;
// private Optional<BigInteger> parentSpanId;
// private BigInteger spanId;
// private long startTime;
// private BigInteger traceId;
// private List<AnnotationData> annotations;
//
// public BeanSpanData() {
// this.spanId = BigInteger.TEN;
// this.startTime = System.nanoTime();
// traceId = BigInteger.ONE;
// parentSpanId = Optional.absent();
// name = "Some Name";
// host = "Host-001";
// duration = 100;
// annotations = ImmutableList.of();
// }
//
// public BeanSpanData(int duration, String host, String name, Optional<BigInteger> parentSpanId, BigInteger spanId, long startTime, BigInteger traceId, List<AnnotationData> annotations) {
// this.duration = duration;
// this.host = host;
// this.name = name;
// this.parentSpanId = parentSpanId;
// this.spanId = spanId;
// this.startTime = startTime;
// this.traceId = traceId;
// this.annotations = annotations;
// }
//
// @Override
// public BigInteger getTraceId() {
// return traceId;
// }
//
// @Override
// public BigInteger getSpanId() {
// return spanId;
// }
//
// @Override
// public Optional<BigInteger> getParentSpanId() {
// return parentSpanId;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public String getHost() {
// return host;
// }
//
// @Override
// public long getStartTime() {
// return startTime;
// }
//
// @Override
// public long getDuration() {
// return duration;
// }
//
// @Override
// public List<AnnotationData> getAnnotations() {
// return annotations;
// }
//
// @SuppressWarnings("RedundantIfStatement")
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BeanSpanData that = (BeanSpanData) o;
//
// if (duration != that.duration) return false;
// if (startTime != that.startTime) return false;
// if (annotations != null ? !annotations.equals(that.annotations) : that.annotations != null) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (name != null ? !name.equals(that.name) : that.name != null) return false;
// if (parentSpanId != null ? !parentSpanId.equals(that.parentSpanId) : that.parentSpanId != null) return false;
// if (spanId != null ? !spanId.equals(that.spanId) : that.spanId != null) return false;
// if (traceId != null ? !traceId.equals(that.traceId) : that.traceId != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = duration;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + (name != null ? name.hashCode() : 0);
// result = 31 * result + (parentSpanId != null ? parentSpanId.hashCode() : 0);
// result = 31 * result + (spanId != null ? spanId.hashCode() : 0);
// result = 31 * result + (int) (startTime ^ (startTime >>> 32));
// result = 31 * result + (traceId != null ? traceId.hashCode() : 0);
// result = 31 * result + (annotations != null ? annotations.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "BeanSpanData{" +
// "duration=" + duration +
// ", host='" + host + '\'' +
// ", name='" + name + '\'' +
// ", parentSpanId=" + parentSpanId +
// ", spanId=" + spanId +
// ", startTime=" + startTime +
// ", traceId=" + traceId +
// ", annotations=" + annotations +
// '}';
// }
// }
|
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.yammer.telemetry.tracing.AnnotationData;
import com.yammer.telemetry.tracing.BeanSpanData;
import org.junit.Test;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigInteger;
import static org.junit.Assert.assertEquals;
|
public void testCreateWithNullFile() throws Exception {
LogJobFactory.withFile(null);
}
@Test
public void testCreateWithWriter() throws Exception {
LogJobFactory.withWriter(new StringWriter());
}
@Test(expected = NullPointerException.class)
public void testCreateWithNullWriter() throws Exception {
LogJobFactory.withWriter(null);
}
@Test
public void testWriteNull() throws Exception {
StringWriter writer = new StringWriter();
LogJobFactory logJobFactory = LogJobFactory.withWriter(writer);
Runnable job = logJobFactory.createJob(null);
job.run();
assertEquals(String.format("null%n"), writer.toString());
}
@Test
public void testWriteSpanData() throws Exception {
StringWriter writer = new StringWriter();
LogJobFactory logJobFactory = LogJobFactory.withWriter(writer);
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/AnnotationData.java
// public interface AnnotationData {
// long getLoggedAt();
//
// String getName();
//
// String getMessage();
// }
//
// Path: telemetry-lib/src/test/java/com/yammer/telemetry/tracing/BeanSpanData.java
// public class BeanSpanData implements SpanData {
// private int duration;
// private String host;
// private String name;
// private Optional<BigInteger> parentSpanId;
// private BigInteger spanId;
// private long startTime;
// private BigInteger traceId;
// private List<AnnotationData> annotations;
//
// public BeanSpanData() {
// this.spanId = BigInteger.TEN;
// this.startTime = System.nanoTime();
// traceId = BigInteger.ONE;
// parentSpanId = Optional.absent();
// name = "Some Name";
// host = "Host-001";
// duration = 100;
// annotations = ImmutableList.of();
// }
//
// public BeanSpanData(int duration, String host, String name, Optional<BigInteger> parentSpanId, BigInteger spanId, long startTime, BigInteger traceId, List<AnnotationData> annotations) {
// this.duration = duration;
// this.host = host;
// this.name = name;
// this.parentSpanId = parentSpanId;
// this.spanId = spanId;
// this.startTime = startTime;
// this.traceId = traceId;
// this.annotations = annotations;
// }
//
// @Override
// public BigInteger getTraceId() {
// return traceId;
// }
//
// @Override
// public BigInteger getSpanId() {
// return spanId;
// }
//
// @Override
// public Optional<BigInteger> getParentSpanId() {
// return parentSpanId;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public String getHost() {
// return host;
// }
//
// @Override
// public long getStartTime() {
// return startTime;
// }
//
// @Override
// public long getDuration() {
// return duration;
// }
//
// @Override
// public List<AnnotationData> getAnnotations() {
// return annotations;
// }
//
// @SuppressWarnings("RedundantIfStatement")
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// BeanSpanData that = (BeanSpanData) o;
//
// if (duration != that.duration) return false;
// if (startTime != that.startTime) return false;
// if (annotations != null ? !annotations.equals(that.annotations) : that.annotations != null) return false;
// if (host != null ? !host.equals(that.host) : that.host != null) return false;
// if (name != null ? !name.equals(that.name) : that.name != null) return false;
// if (parentSpanId != null ? !parentSpanId.equals(that.parentSpanId) : that.parentSpanId != null) return false;
// if (spanId != null ? !spanId.equals(that.spanId) : that.spanId != null) return false;
// if (traceId != null ? !traceId.equals(that.traceId) : that.traceId != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = duration;
// result = 31 * result + (host != null ? host.hashCode() : 0);
// result = 31 * result + (name != null ? name.hashCode() : 0);
// result = 31 * result + (parentSpanId != null ? parentSpanId.hashCode() : 0);
// result = 31 * result + (spanId != null ? spanId.hashCode() : 0);
// result = 31 * result + (int) (startTime ^ (startTime >>> 32));
// result = 31 * result + (traceId != null ? traceId.hashCode() : 0);
// result = 31 * result + (annotations != null ? annotations.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "BeanSpanData{" +
// "duration=" + duration +
// ", host='" + host + '\'' +
// ", name='" + name + '\'' +
// ", parentSpanId=" + parentSpanId +
// ", spanId=" + spanId +
// ", startTime=" + startTime +
// ", traceId=" + traceId +
// ", annotations=" + annotations +
// '}';
// }
// }
// Path: telemetry-lib/src/test/java/com/yammer/telemetry/tracing/logging/LogJobFactoryTest.java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.yammer.telemetry.tracing.AnnotationData;
import com.yammer.telemetry.tracing.BeanSpanData;
import org.junit.Test;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigInteger;
import static org.junit.Assert.assertEquals;
public void testCreateWithNullFile() throws Exception {
LogJobFactory.withFile(null);
}
@Test
public void testCreateWithWriter() throws Exception {
LogJobFactory.withWriter(new StringWriter());
}
@Test(expected = NullPointerException.class)
public void testCreateWithNullWriter() throws Exception {
LogJobFactory.withWriter(null);
}
@Test
public void testWriteNull() throws Exception {
StringWriter writer = new StringWriter();
LogJobFactory logJobFactory = LogJobFactory.withWriter(writer);
Runnable job = logJobFactory.createJob(null);
job.run();
assertEquals(String.format("null%n"), writer.toString());
}
@Test
public void testWriteSpanData() throws Exception {
StringWriter writer = new StringWriter();
LogJobFactory logJobFactory = LogJobFactory.withWriter(writer);
|
BeanSpanData expectedData = new BeanSpanData(100, "host", "name", Optional.<BigInteger>absent(), BigInteger.ZERO, 15, BigInteger.ONE, ImmutableList.<AnnotationData>of());
|
yammer/telemetry
|
telemetry-agent/src/test/java/com/yammer/telemetry/agent/TelemetryTransformerTest.java
|
// Path: telemetry-instrumentation/src/main/java/com/yammer/telemetry/instrumentation/ClassInstrumentationHandler.java
// public interface ClassInstrumentationHandler {
// boolean transformed(CtClass cc, ClassPool pool);
// }
//
// Path: telemetry-agent/src/main/java/com/yammer/telemetry/agent/handlers/SubTypeInstrumentationHandler.java
// public abstract class SubTypeInstrumentationHandler implements ClassInstrumentationHandler {
// private static final Logger LOGGER = Logger.getLogger(SubTypeInstrumentationHandler.class.getName());
// protected final String superTypeName;
// private boolean enabled = true;
//
// public SubTypeInstrumentationHandler(String superTypeName) {
// this.superTypeName = superTypeName;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// @Override
// public final boolean transformed(CtClass cc, ClassPool pool) {
// try {
// if (canTransform(cc, pool)) {
// return transform(cc, pool);
// }
// } catch (NotFoundException | CannotCompileException | IOException e) {
// // Disable the handler for the remainder.
// LOGGER.warning("Error instrumenting " + cc.getName() + ": " + e.toString() + " [" + getClass().getName() + "]");
// enabled = false;
// }
//
// return false;
// }
//
// private boolean canTransform(CtClass cc, ClassPool pool) throws NotFoundException {
// return isEnabled() && cc.subtypeOf(pool.get(superTypeName));
// }
//
// protected abstract boolean transform(CtClass cc, ClassPool pool) throws NotFoundException, CannotCompileException, IOException;
// }
//
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TransformingClassLoader.java
// public class TransformingClassLoader extends URLClassLoader {
// private final TelemetryTransformer transformer;
// private final ClassPool classPool;
//
// public TransformingClassLoader(TelemetryTransformer transformer) {
// super(new URL[] {});
// this.transformer = checkNotNull(transformer);
// classPool = new ClassPool(null);
// classPool.appendSystemPath();
// }
//
// @Override
// public Class<?> loadClass(String name) throws ClassNotFoundException {
// Class<?> loadedClass = super.findLoadedClass(name);
// if (loadedClass != null) return loadedClass;
// try (InputStream classStream = super.getResourceAsStream(name.replace('.', '/') + ".class")) {
// byte[] classfileBuffer = ByteStreams.toByteArray(classStream);
// byte[] transformedBytes = transformer.transform(this, name, classfileBuffer, classPool);
//
// if (transformedBytes == null) {
// if (name.startsWith("java")) {
// return super.loadClass(name);
// }
// return super.defineClass(name, classfileBuffer, 0, classfileBuffer.length);
// } else {
// return super.defineClass(name, transformedBytes, 0, transformedBytes.length);
// }
// } catch (IOException | IllegalClassFormatException | RuntimeException e) {
// throw new ClassNotFoundException(name, e);
// }
// }
// }
//
// Path: telemetry-instrumentation/src/main/java/com/yammer/telemetry/instrumentation/TelemetryTransformer.java
// public class TelemetryTransformer implements ClassFileTransformer {
// private final Set<ClassInstrumentationHandler> handlers = new HashSet<>();
//
// public void addHandler(ClassInstrumentationHandler handler) {
// handlers.add(handler);
// }
//
// @Override
// public byte[] transform(ClassLoader loader,
// String className,
// Class<?> classBeingRedefined,
// ProtectionDomain protectionDomain,
// byte[] classfileBuffer) throws IllegalClassFormatException {
// return transform(loader, className, classfileBuffer, ClassPool.getDefault());
// }
//
// /**
// * Allows specifying the ClassPool, this allows tests to essentially 'reload' classes.
// *
// * @param loader
// * @param className
// * @param classfileBuffer
// * @param cp
// * @return
// * @throws IllegalClassFormatException
// */
// public byte[] transform(ClassLoader loader,
// String className,
// byte[] classfileBuffer,
// ClassPool cp) throws IllegalClassFormatException {
// try {
// final String realClassName = className.replace('/', '.');
// cp.insertClassPath(new LoaderClassPath(loader));
// cp.insertClassPath(new ByteArrayClassPath(realClassName, classfileBuffer));
// CtClass cc = cp.get(realClassName);
//
// boolean classUpdated = false;
// for (ClassInstrumentationHandler handler : handlers) {
// if (classUpdated = handler.transformed(cc, cp)) {
// break;
// }
// }
//
// if (classUpdated) {
// return cc.toBytecode();
// } else {
// return null;
// }
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// } catch (Throwable t) {
// t.printStackTrace();
// throw t;
// }
// }
// }
//
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/TelemetryTransformerTest.java
// public static boolean wrapMethod(CtClass cc, String method, String body) {
// try {
// if (cc.isFrozen()) cc.defrost();
//
// CtMethod getMethod = cc.getDeclaredMethod(method);
// CtMethod copiedMethod = CtNewMethod.copy(getMethod, cc.makeUniqueName(method), cc, null);
//
// copiedMethod.setModifiers(Modifier.PRIVATE);
// cc.addMethod(copiedMethod);
//
// getMethod.setBody(body, "this", copiedMethod.getName());
//
// return true;
// } catch (NotFoundException | CannotCompileException e) {
// throw new RuntimeException(e);
// }
// }
|
import com.yammer.telemetry.instrumentation.ClassInstrumentationHandler;
import com.yammer.telemetry.agent.handlers.SubTypeInstrumentationHandler;
import com.yammer.telemetry.test.TransformingClassLoader;
import com.yammer.telemetry.instrumentation.TelemetryTransformer;
import javassist.*;
import org.junit.Test;
import java.io.IOException;
import static com.yammer.telemetry.agent.TelemetryTransformerTest.ClassUtils.wrapMethod;
import static org.junit.Assert.*;
|
package com.yammer.telemetry.agent;
public class TelemetryTransformerTest {
@Test
public void testUnmodifiedWhenNoHandlersAdded() throws Exception {
|
// Path: telemetry-instrumentation/src/main/java/com/yammer/telemetry/instrumentation/ClassInstrumentationHandler.java
// public interface ClassInstrumentationHandler {
// boolean transformed(CtClass cc, ClassPool pool);
// }
//
// Path: telemetry-agent/src/main/java/com/yammer/telemetry/agent/handlers/SubTypeInstrumentationHandler.java
// public abstract class SubTypeInstrumentationHandler implements ClassInstrumentationHandler {
// private static final Logger LOGGER = Logger.getLogger(SubTypeInstrumentationHandler.class.getName());
// protected final String superTypeName;
// private boolean enabled = true;
//
// public SubTypeInstrumentationHandler(String superTypeName) {
// this.superTypeName = superTypeName;
// }
//
// public boolean isEnabled() {
// return enabled;
// }
//
// @Override
// public final boolean transformed(CtClass cc, ClassPool pool) {
// try {
// if (canTransform(cc, pool)) {
// return transform(cc, pool);
// }
// } catch (NotFoundException | CannotCompileException | IOException e) {
// // Disable the handler for the remainder.
// LOGGER.warning("Error instrumenting " + cc.getName() + ": " + e.toString() + " [" + getClass().getName() + "]");
// enabled = false;
// }
//
// return false;
// }
//
// private boolean canTransform(CtClass cc, ClassPool pool) throws NotFoundException {
// return isEnabled() && cc.subtypeOf(pool.get(superTypeName));
// }
//
// protected abstract boolean transform(CtClass cc, ClassPool pool) throws NotFoundException, CannotCompileException, IOException;
// }
//
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TransformingClassLoader.java
// public class TransformingClassLoader extends URLClassLoader {
// private final TelemetryTransformer transformer;
// private final ClassPool classPool;
//
// public TransformingClassLoader(TelemetryTransformer transformer) {
// super(new URL[] {});
// this.transformer = checkNotNull(transformer);
// classPool = new ClassPool(null);
// classPool.appendSystemPath();
// }
//
// @Override
// public Class<?> loadClass(String name) throws ClassNotFoundException {
// Class<?> loadedClass = super.findLoadedClass(name);
// if (loadedClass != null) return loadedClass;
// try (InputStream classStream = super.getResourceAsStream(name.replace('.', '/') + ".class")) {
// byte[] classfileBuffer = ByteStreams.toByteArray(classStream);
// byte[] transformedBytes = transformer.transform(this, name, classfileBuffer, classPool);
//
// if (transformedBytes == null) {
// if (name.startsWith("java")) {
// return super.loadClass(name);
// }
// return super.defineClass(name, classfileBuffer, 0, classfileBuffer.length);
// } else {
// return super.defineClass(name, transformedBytes, 0, transformedBytes.length);
// }
// } catch (IOException | IllegalClassFormatException | RuntimeException e) {
// throw new ClassNotFoundException(name, e);
// }
// }
// }
//
// Path: telemetry-instrumentation/src/main/java/com/yammer/telemetry/instrumentation/TelemetryTransformer.java
// public class TelemetryTransformer implements ClassFileTransformer {
// private final Set<ClassInstrumentationHandler> handlers = new HashSet<>();
//
// public void addHandler(ClassInstrumentationHandler handler) {
// handlers.add(handler);
// }
//
// @Override
// public byte[] transform(ClassLoader loader,
// String className,
// Class<?> classBeingRedefined,
// ProtectionDomain protectionDomain,
// byte[] classfileBuffer) throws IllegalClassFormatException {
// return transform(loader, className, classfileBuffer, ClassPool.getDefault());
// }
//
// /**
// * Allows specifying the ClassPool, this allows tests to essentially 'reload' classes.
// *
// * @param loader
// * @param className
// * @param classfileBuffer
// * @param cp
// * @return
// * @throws IllegalClassFormatException
// */
// public byte[] transform(ClassLoader loader,
// String className,
// byte[] classfileBuffer,
// ClassPool cp) throws IllegalClassFormatException {
// try {
// final String realClassName = className.replace('/', '.');
// cp.insertClassPath(new LoaderClassPath(loader));
// cp.insertClassPath(new ByteArrayClassPath(realClassName, classfileBuffer));
// CtClass cc = cp.get(realClassName);
//
// boolean classUpdated = false;
// for (ClassInstrumentationHandler handler : handlers) {
// if (classUpdated = handler.transformed(cc, cp)) {
// break;
// }
// }
//
// if (classUpdated) {
// return cc.toBytecode();
// } else {
// return null;
// }
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// } catch (Throwable t) {
// t.printStackTrace();
// throw t;
// }
// }
// }
//
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/TelemetryTransformerTest.java
// public static boolean wrapMethod(CtClass cc, String method, String body) {
// try {
// if (cc.isFrozen()) cc.defrost();
//
// CtMethod getMethod = cc.getDeclaredMethod(method);
// CtMethod copiedMethod = CtNewMethod.copy(getMethod, cc.makeUniqueName(method), cc, null);
//
// copiedMethod.setModifiers(Modifier.PRIVATE);
// cc.addMethod(copiedMethod);
//
// getMethod.setBody(body, "this", copiedMethod.getName());
//
// return true;
// } catch (NotFoundException | CannotCompileException e) {
// throw new RuntimeException(e);
// }
// }
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/TelemetryTransformerTest.java
import com.yammer.telemetry.instrumentation.ClassInstrumentationHandler;
import com.yammer.telemetry.agent.handlers.SubTypeInstrumentationHandler;
import com.yammer.telemetry.test.TransformingClassLoader;
import com.yammer.telemetry.instrumentation.TelemetryTransformer;
import javassist.*;
import org.junit.Test;
import java.io.IOException;
import static com.yammer.telemetry.agent.TelemetryTransformerTest.ClassUtils.wrapMethod;
import static org.junit.Assert.*;
package com.yammer.telemetry.agent;
public class TelemetryTransformerTest {
@Test
public void testUnmodifiedWhenNoHandlersAdded() throws Exception {
|
TelemetryTransformer transformer = new TelemetryTransformer();
|
yammer/telemetry
|
telemetry-example/src/main/java/com/yammer/telemetry/example/resources/NapsResource.java
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
|
import com.yammer.dropwizard.hibernate.UnitOfWork;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
|
package com.yammer.telemetry.example.resources;
@Path("/naps")
@Produces(MediaType.APPLICATION_JSON)
public class NapsResource {
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/resources/NapsResource.java
import com.yammer.dropwizard.hibernate.UnitOfWork;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
package com.yammer.telemetry.example.resources;
@Path("/naps")
@Produces(MediaType.APPLICATION_JSON)
public class NapsResource {
|
private final NapDAO napDAO;
|
yammer/telemetry
|
telemetry-example/src/main/java/com/yammer/telemetry/example/resources/NapsResource.java
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
|
import com.yammer.dropwizard.hibernate.UnitOfWork;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
|
package com.yammer.telemetry.example.resources;
@Path("/naps")
@Produces(MediaType.APPLICATION_JSON)
public class NapsResource {
private final NapDAO napDAO;
public NapsResource(NapDAO napDAO) {
this.napDAO = napDAO;
}
@GET
@UnitOfWork
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/resources/NapsResource.java
import com.yammer.dropwizard.hibernate.UnitOfWork;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
package com.yammer.telemetry.example.resources;
@Path("/naps")
@Produces(MediaType.APPLICATION_JSON)
public class NapsResource {
private final NapDAO napDAO;
public NapsResource(NapDAO napDAO) {
this.napDAO = napDAO;
}
@GET
@UnitOfWork
|
public List<Nap> getNaps() {
|
yammer/telemetry
|
telemetry-agent/src/test/java/com/yammer/telemetry/agent/handlers/HttpServletClassHandlerTest.java
|
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/test/SimpleServlet.java
// public class SimpleServlet extends HttpServlet {
// //// currently need this, should we?
// // @Override
// // protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// // super.service(req, resp);
// // }
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.getWriter().print("foof");
// }
//
// @Override
// protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setStatus(201);
// }
// }
//
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
// public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
// Method[] methods = clazz.getDeclaredMethods();
// Map<Method, Throwable> testFailures = new HashMap<>();
// int ran = 0;
//
// for (Method method : methods) {
// if (method.isAnnotationPresent(TransformedTest.class)) {
// try {
// ran++;
// runTransformed(clazz, method.getName(), handlers);
// } catch (Exception e) {
// //noinspection ThrowableResultOfMethodCallIgnored
// testFailures.put(method, unwrap(e));
// }
// }
// }
//
// if (!testFailures.isEmpty()) {
// StringWriter builder = new StringWriter();
// PrintWriter writer = new PrintWriter(builder);
// writer.println("Transformed tests failed:");
// for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
// writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
// //noinspection ThrowableResultOfMethodCallIgnored
// entry.getValue().printStackTrace(writer);
// writer.println();
// }
// fail(builder.toString());
// }
//
// if (ran == 0) {
// fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
// }
// }
|
import com.google.common.base.Optional;
import com.yammer.telemetry.agent.test.SimpleServlet;
import com.yammer.telemetry.test.TransformedTest;
import com.yammer.telemetry.tracing.*;
import javassist.ClassPool;
import javassist.CtClass;
import org.junit.After;
import org.junit.Test;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.math.BigInteger;
import java.security.Principal;
import java.util.*;
import static com.yammer.telemetry.test.TelemetryTestHelpers.runTransformed;
import static org.junit.Assert.*;
|
@Test
public void testNothingForNonHttpServletClasses() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("java.lang.String");
assertFalse(handler.transformed(ctClass, cp));
}
@Test
public void testTransformsHttpServletClasses() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("javax.servlet.http.HttpServlet");
assertTrue(handler.transformed(ctClass, cp));
}
@Test
public void testTransformsHttpServletSubclassesThatOverrideService() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("com.sun.jersey.spi.container.servlet.ServletContainer");
assertTrue(handler.transformed(ctClass, cp));
}
@Test
public void testNothingForHttpServletSubclassesWithoutServiceMethodOverride() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("com.yammer.dropwizard.tasks.TaskServlet");
assertFalse(handler.transformed(ctClass, cp));
}
@Test
public void testRunTransformedTests() throws Exception {
|
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/test/SimpleServlet.java
// public class SimpleServlet extends HttpServlet {
// //// currently need this, should we?
// // @Override
// // protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// // super.service(req, resp);
// // }
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.getWriter().print("foof");
// }
//
// @Override
// protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setStatus(201);
// }
// }
//
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
// public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
// Method[] methods = clazz.getDeclaredMethods();
// Map<Method, Throwable> testFailures = new HashMap<>();
// int ran = 0;
//
// for (Method method : methods) {
// if (method.isAnnotationPresent(TransformedTest.class)) {
// try {
// ran++;
// runTransformed(clazz, method.getName(), handlers);
// } catch (Exception e) {
// //noinspection ThrowableResultOfMethodCallIgnored
// testFailures.put(method, unwrap(e));
// }
// }
// }
//
// if (!testFailures.isEmpty()) {
// StringWriter builder = new StringWriter();
// PrintWriter writer = new PrintWriter(builder);
// writer.println("Transformed tests failed:");
// for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
// writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
// //noinspection ThrowableResultOfMethodCallIgnored
// entry.getValue().printStackTrace(writer);
// writer.println();
// }
// fail(builder.toString());
// }
//
// if (ran == 0) {
// fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
// }
// }
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/handlers/HttpServletClassHandlerTest.java
import com.google.common.base.Optional;
import com.yammer.telemetry.agent.test.SimpleServlet;
import com.yammer.telemetry.test.TransformedTest;
import com.yammer.telemetry.tracing.*;
import javassist.ClassPool;
import javassist.CtClass;
import org.junit.After;
import org.junit.Test;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.math.BigInteger;
import java.security.Principal;
import java.util.*;
import static com.yammer.telemetry.test.TelemetryTestHelpers.runTransformed;
import static org.junit.Assert.*;
@Test
public void testNothingForNonHttpServletClasses() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("java.lang.String");
assertFalse(handler.transformed(ctClass, cp));
}
@Test
public void testTransformsHttpServletClasses() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("javax.servlet.http.HttpServlet");
assertTrue(handler.transformed(ctClass, cp));
}
@Test
public void testTransformsHttpServletSubclassesThatOverrideService() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("com.sun.jersey.spi.container.servlet.ServletContainer");
assertTrue(handler.transformed(ctClass, cp));
}
@Test
public void testNothingForHttpServletSubclassesWithoutServiceMethodOverride() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("com.yammer.dropwizard.tasks.TaskServlet");
assertFalse(handler.transformed(ctClass, cp));
}
@Test
public void testRunTransformedTests() throws Exception {
|
runTransformed(TransformedTests.class, handler);
|
yammer/telemetry
|
telemetry-agent/src/test/java/com/yammer/telemetry/agent/handlers/HttpServletClassHandlerTest.java
|
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/test/SimpleServlet.java
// public class SimpleServlet extends HttpServlet {
// //// currently need this, should we?
// // @Override
// // protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// // super.service(req, resp);
// // }
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.getWriter().print("foof");
// }
//
// @Override
// protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setStatus(201);
// }
// }
//
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
// public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
// Method[] methods = clazz.getDeclaredMethods();
// Map<Method, Throwable> testFailures = new HashMap<>();
// int ran = 0;
//
// for (Method method : methods) {
// if (method.isAnnotationPresent(TransformedTest.class)) {
// try {
// ran++;
// runTransformed(clazz, method.getName(), handlers);
// } catch (Exception e) {
// //noinspection ThrowableResultOfMethodCallIgnored
// testFailures.put(method, unwrap(e));
// }
// }
// }
//
// if (!testFailures.isEmpty()) {
// StringWriter builder = new StringWriter();
// PrintWriter writer = new PrintWriter(builder);
// writer.println("Transformed tests failed:");
// for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
// writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
// //noinspection ThrowableResultOfMethodCallIgnored
// entry.getValue().printStackTrace(writer);
// writer.println();
// }
// fail(builder.toString());
// }
//
// if (ran == 0) {
// fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
// }
// }
|
import com.google.common.base.Optional;
import com.yammer.telemetry.agent.test.SimpleServlet;
import com.yammer.telemetry.test.TransformedTest;
import com.yammer.telemetry.tracing.*;
import javassist.ClassPool;
import javassist.CtClass;
import org.junit.After;
import org.junit.Test;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.math.BigInteger;
import java.security.Principal;
import java.util.*;
import static com.yammer.telemetry.test.TelemetryTestHelpers.runTransformed;
import static org.junit.Assert.*;
|
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("com.yammer.dropwizard.tasks.TaskServlet");
assertFalse(handler.transformed(ctClass, cp));
}
@Test
public void testRunTransformedTests() throws Exception {
runTransformed(TransformedTests.class, handler);
}
@SuppressWarnings("UnusedDeclaration")
/**
* This provides static methods which get invoked within the transformed classloader context. This means we can
* largely just write code for tests as we would. Right now mockito doesn't play happily in this environment
* however so instead rely on fake objects, defined below.
*/
public static class TransformedTests {
@TransformedTest
public static void testBaseBehaviour() throws Exception {
InMemorySpanSinkSource sink = new InMemorySpanSinkSource();
Annotations.setServiceAnnotations(new ServiceAnnotations("testing"));
SpanSinkRegistry.register(sink);
StringWriter underlyingWriter = new StringWriter();
HttpServletRequest request = new FakeHttpServletRequest("GET", "http://localhost:8080/foo");
HttpServletResponse response = new FakeHttpServletResponse(underlyingWriter);
|
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/test/SimpleServlet.java
// public class SimpleServlet extends HttpServlet {
// //// currently need this, should we?
// // @Override
// // protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// // super.service(req, resp);
// // }
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.getWriter().print("foof");
// }
//
// @Override
// protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setStatus(201);
// }
// }
//
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
// public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
// Method[] methods = clazz.getDeclaredMethods();
// Map<Method, Throwable> testFailures = new HashMap<>();
// int ran = 0;
//
// for (Method method : methods) {
// if (method.isAnnotationPresent(TransformedTest.class)) {
// try {
// ran++;
// runTransformed(clazz, method.getName(), handlers);
// } catch (Exception e) {
// //noinspection ThrowableResultOfMethodCallIgnored
// testFailures.put(method, unwrap(e));
// }
// }
// }
//
// if (!testFailures.isEmpty()) {
// StringWriter builder = new StringWriter();
// PrintWriter writer = new PrintWriter(builder);
// writer.println("Transformed tests failed:");
// for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
// writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
// //noinspection ThrowableResultOfMethodCallIgnored
// entry.getValue().printStackTrace(writer);
// writer.println();
// }
// fail(builder.toString());
// }
//
// if (ran == 0) {
// fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
// }
// }
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/handlers/HttpServletClassHandlerTest.java
import com.google.common.base.Optional;
import com.yammer.telemetry.agent.test.SimpleServlet;
import com.yammer.telemetry.test.TransformedTest;
import com.yammer.telemetry.tracing.*;
import javassist.ClassPool;
import javassist.CtClass;
import org.junit.After;
import org.junit.Test;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.math.BigInteger;
import java.security.Principal;
import java.util.*;
import static com.yammer.telemetry.test.TelemetryTestHelpers.runTransformed;
import static org.junit.Assert.*;
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("com.yammer.dropwizard.tasks.TaskServlet");
assertFalse(handler.transformed(ctClass, cp));
}
@Test
public void testRunTransformedTests() throws Exception {
runTransformed(TransformedTests.class, handler);
}
@SuppressWarnings("UnusedDeclaration")
/**
* This provides static methods which get invoked within the transformed classloader context. This means we can
* largely just write code for tests as we would. Right now mockito doesn't play happily in this environment
* however so instead rely on fake objects, defined below.
*/
public static class TransformedTests {
@TransformedTest
public static void testBaseBehaviour() throws Exception {
InMemorySpanSinkSource sink = new InMemorySpanSinkSource();
Annotations.setServiceAnnotations(new ServiceAnnotations("testing"));
SpanSinkRegistry.register(sink);
StringWriter underlyingWriter = new StringWriter();
HttpServletRequest request = new FakeHttpServletRequest("GET", "http://localhost:8080/foo");
HttpServletResponse response = new FakeHttpServletResponse(underlyingWriter);
|
SimpleServlet servlet = new SimpleServlet();
|
yammer/telemetry
|
telemetry-example/src/main/java/com/yammer/telemetry/example/resources/NapResource.java
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
|
import com.yammer.dropwizard.hibernate.UnitOfWork;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.annotation.Timed;
import com.yammer.metrics.core.Meter;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.TimeUnit;
|
package com.yammer.telemetry.example.resources;
@Path("/nap/{duration}")
@Produces(MediaType.TEXT_PLAIN)
public class NapResource {
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/resources/NapResource.java
import com.yammer.dropwizard.hibernate.UnitOfWork;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.annotation.Timed;
import com.yammer.metrics.core.Meter;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.TimeUnit;
package com.yammer.telemetry.example.resources;
@Path("/nap/{duration}")
@Produces(MediaType.TEXT_PLAIN)
public class NapResource {
|
private final NapDAO napDAO;
|
yammer/telemetry
|
telemetry-example/src/main/java/com/yammer/telemetry/example/resources/NapResource.java
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
|
import com.yammer.dropwizard.hibernate.UnitOfWork;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.annotation.Timed;
import com.yammer.metrics.core.Meter;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.TimeUnit;
|
package com.yammer.telemetry.example.resources;
@Path("/nap/{duration}")
@Produces(MediaType.TEXT_PLAIN)
public class NapResource {
private final NapDAO napDAO;
private final Meter sleepsTaken = Metrics.newMeter(NapResource.class, "sleeps", "taken", TimeUnit.MILLISECONDS);
private final Meter sleepsDuration = Metrics.newMeter(NapResource.class, "sleeps", "duration", TimeUnit.MILLISECONDS);
public NapResource(NapDAO napDAO) {
this.napDAO = napDAO;
}
@GET
@UnitOfWork
@Timed
public String nap(@PathParam("duration") DurationParam duration) throws InterruptedException {
|
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/core/Nap.java
// @Entity
// @Table(name = "naps")
// @NamedQueries({
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findAll",
// query = "SELECT n FROM Nap n"
// ),
// @NamedQuery(
// name = "com.yammer.telemetry.example.core.Nap.findById",
// query = "SELECT n FROM Nap n WHERE n.id = :id"
// )
// })
// public class Nap {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private long id;
//
// @Column(name = "start", nullable = false)
// private long start;
//
// @Column(name = "duration", nullable = false)
// private long duration;
//
// public Nap() {
// }
//
// public Nap(long start, long duration) {
// this.start = start;
// this.duration = duration;
// }
//
// public long getStart() {
// return start;
// }
//
// public void setStart(long start) {
// this.start = start;
// }
//
// public long getDuration() {
// return duration;
// }
//
// public void setDuration(long duration) {
// this.duration = duration;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// @Override
// public String toString() {
// return "Nap{" +
// "id=" + id +
// ", start=" + start +
// ", duration=" + duration +
// '}';
// }
// }
//
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/db/NapDAO.java
// public class NapDAO extends AbstractDAO<Nap> {
// public NapDAO(SessionFactory sessionFactory) {
// super(sessionFactory);
// }
//
// public Optional<Nap> findById(long id) {
// return Optional.fromNullable(get(id));
// }
//
// public Nap create(Nap nap) {
// return persist(nap);
// }
//
// public List<Nap> findAll() {
// return list(namedQuery("com.yammer.telemetry.example.core.Nap.findAll"));
// }
// }
// Path: telemetry-example/src/main/java/com/yammer/telemetry/example/resources/NapResource.java
import com.yammer.dropwizard.hibernate.UnitOfWork;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.annotation.Timed;
import com.yammer.metrics.core.Meter;
import com.yammer.telemetry.example.core.Nap;
import com.yammer.telemetry.example.db.NapDAO;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.TimeUnit;
package com.yammer.telemetry.example.resources;
@Path("/nap/{duration}")
@Produces(MediaType.TEXT_PLAIN)
public class NapResource {
private final NapDAO napDAO;
private final Meter sleepsTaken = Metrics.newMeter(NapResource.class, "sleeps", "taken", TimeUnit.MILLISECONDS);
private final Meter sleepsDuration = Metrics.newMeter(NapResource.class, "sleeps", "duration", TimeUnit.MILLISECONDS);
public NapResource(NapDAO napDAO) {
this.napDAO = napDAO;
}
@GET
@UnitOfWork
@Timed
public String nap(@PathParam("duration") DurationParam duration) throws InterruptedException {
|
final Nap nap = new Nap(System.currentTimeMillis(), duration.getDuration().toMilliseconds());
|
yammer/telemetry
|
telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
|
// Path: telemetry-instrumentation/src/main/java/com/yammer/telemetry/instrumentation/ClassInstrumentationHandler.java
// public interface ClassInstrumentationHandler {
// boolean transformed(CtClass cc, ClassPool pool);
// }
//
// Path: telemetry-instrumentation/src/main/java/com/yammer/telemetry/instrumentation/TelemetryTransformer.java
// public class TelemetryTransformer implements ClassFileTransformer {
// private final Set<ClassInstrumentationHandler> handlers = new HashSet<>();
//
// public void addHandler(ClassInstrumentationHandler handler) {
// handlers.add(handler);
// }
//
// @Override
// public byte[] transform(ClassLoader loader,
// String className,
// Class<?> classBeingRedefined,
// ProtectionDomain protectionDomain,
// byte[] classfileBuffer) throws IllegalClassFormatException {
// return transform(loader, className, classfileBuffer, ClassPool.getDefault());
// }
//
// /**
// * Allows specifying the ClassPool, this allows tests to essentially 'reload' classes.
// *
// * @param loader
// * @param className
// * @param classfileBuffer
// * @param cp
// * @return
// * @throws IllegalClassFormatException
// */
// public byte[] transform(ClassLoader loader,
// String className,
// byte[] classfileBuffer,
// ClassPool cp) throws IllegalClassFormatException {
// try {
// final String realClassName = className.replace('/', '.');
// cp.insertClassPath(new LoaderClassPath(loader));
// cp.insertClassPath(new ByteArrayClassPath(realClassName, classfileBuffer));
// CtClass cc = cp.get(realClassName);
//
// boolean classUpdated = false;
// for (ClassInstrumentationHandler handler : handlers) {
// if (classUpdated = handler.transformed(cc, cp)) {
// break;
// }
// }
//
// if (classUpdated) {
// return cc.toBytecode();
// } else {
// return null;
// }
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// } catch (Throwable t) {
// t.printStackTrace();
// throw t;
// }
// }
// }
|
import com.yammer.telemetry.instrumentation.ClassInstrumentationHandler;
import com.yammer.telemetry.instrumentation.TelemetryTransformer;
import org.junit.Before;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.fail;
|
writer.println("Transformed tests failed:");
for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
//noinspection ThrowableResultOfMethodCallIgnored
entry.getValue().printStackTrace(writer);
writer.println();
}
fail(builder.toString());
}
if (ran == 0) {
fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
}
}
private static Throwable unwrap(Throwable e) {
if (e instanceof InvocationTargetException) {
return e.getCause();
}
return e;
}
public static void runTransformed(Class<?> clazz, String method, ClassInstrumentationHandler... handlers) throws Exception {
Set<String> befores = new HashSet<>();
for (Method beforeMethod : clazz.getDeclaredMethods()) {
if (beforeMethod.isAnnotationPresent(Before.class)) {
befores.add(beforeMethod.getName());
}
}
|
// Path: telemetry-instrumentation/src/main/java/com/yammer/telemetry/instrumentation/ClassInstrumentationHandler.java
// public interface ClassInstrumentationHandler {
// boolean transformed(CtClass cc, ClassPool pool);
// }
//
// Path: telemetry-instrumentation/src/main/java/com/yammer/telemetry/instrumentation/TelemetryTransformer.java
// public class TelemetryTransformer implements ClassFileTransformer {
// private final Set<ClassInstrumentationHandler> handlers = new HashSet<>();
//
// public void addHandler(ClassInstrumentationHandler handler) {
// handlers.add(handler);
// }
//
// @Override
// public byte[] transform(ClassLoader loader,
// String className,
// Class<?> classBeingRedefined,
// ProtectionDomain protectionDomain,
// byte[] classfileBuffer) throws IllegalClassFormatException {
// return transform(loader, className, classfileBuffer, ClassPool.getDefault());
// }
//
// /**
// * Allows specifying the ClassPool, this allows tests to essentially 'reload' classes.
// *
// * @param loader
// * @param className
// * @param classfileBuffer
// * @param cp
// * @return
// * @throws IllegalClassFormatException
// */
// public byte[] transform(ClassLoader loader,
// String className,
// byte[] classfileBuffer,
// ClassPool cp) throws IllegalClassFormatException {
// try {
// final String realClassName = className.replace('/', '.');
// cp.insertClassPath(new LoaderClassPath(loader));
// cp.insertClassPath(new ByteArrayClassPath(realClassName, classfileBuffer));
// CtClass cc = cp.get(realClassName);
//
// boolean classUpdated = false;
// for (ClassInstrumentationHandler handler : handlers) {
// if (classUpdated = handler.transformed(cc, cp)) {
// break;
// }
// }
//
// if (classUpdated) {
// return cc.toBytecode();
// } else {
// return null;
// }
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// } catch (Throwable t) {
// t.printStackTrace();
// throw t;
// }
// }
// }
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
import com.yammer.telemetry.instrumentation.ClassInstrumentationHandler;
import com.yammer.telemetry.instrumentation.TelemetryTransformer;
import org.junit.Before;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.fail;
writer.println("Transformed tests failed:");
for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
//noinspection ThrowableResultOfMethodCallIgnored
entry.getValue().printStackTrace(writer);
writer.println();
}
fail(builder.toString());
}
if (ran == 0) {
fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
}
}
private static Throwable unwrap(Throwable e) {
if (e instanceof InvocationTargetException) {
return e.getCause();
}
return e;
}
public static void runTransformed(Class<?> clazz, String method, ClassInstrumentationHandler... handlers) throws Exception {
Set<String> befores = new HashSet<>();
for (Method beforeMethod : clazz.getDeclaredMethods()) {
if (beforeMethod.isAnnotationPresent(Before.class)) {
befores.add(beforeMethod.getName());
}
}
|
final TelemetryTransformer transformer = new TelemetryTransformer();
|
yammer/telemetry
|
telemetry-agent/src/test/java/com/yammer/telemetry/agent/handlers/MetricsRegistryHandlerTest.java
|
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
// public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
// Method[] methods = clazz.getDeclaredMethods();
// Map<Method, Throwable> testFailures = new HashMap<>();
// int ran = 0;
//
// for (Method method : methods) {
// if (method.isAnnotationPresent(TransformedTest.class)) {
// try {
// ran++;
// runTransformed(clazz, method.getName(), handlers);
// } catch (Exception e) {
// //noinspection ThrowableResultOfMethodCallIgnored
// testFailures.put(method, unwrap(e));
// }
// }
// }
//
// if (!testFailures.isEmpty()) {
// StringWriter builder = new StringWriter();
// PrintWriter writer = new PrintWriter(builder);
// writer.println("Transformed tests failed:");
// for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
// writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
// //noinspection ThrowableResultOfMethodCallIgnored
// entry.getValue().printStackTrace(writer);
// writer.println();
// }
// fail(builder.toString());
// }
//
// if (ran == 0) {
// fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
// }
// }
|
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.*;
import com.yammer.telemetry.test.TransformedTest;
import com.yammer.telemetry.tracing.*;
import javassist.ClassPool;
import javassist.CtClass;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import static com.yammer.telemetry.test.TelemetryTestHelpers.runTransformed;
import static org.junit.Assert.*;
|
@Test
public void testTransformsMetricsRegistryClass() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("com.yammer.metrics.core.MetricsRegistry");
assertTrue(handler.transformed(ctClass, cp));
}
@Test
public void testUnwrappedTimer() throws Exception {
MetricsRegistry registry = new MetricsRegistry();
Timer timer = registry.newTimer(MetricsRegistryHandlerTest.class, "example");
TimerContext context = timer.time();
context.stop();
assertEquals(1, timer.count());
}
@Test
public void testUnwrappedMeter() throws Exception {
MetricsRegistry registry = new MetricsRegistry();
Meter meter = registry.newMeter(MetricsRegistryHandlerTest.class, "example", "things", TimeUnit.SECONDS);
meter.mark(10);
assertEquals(10, meter.count());
}
@Test
public void testRunTransformedTests() throws Exception {
|
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
// public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
// Method[] methods = clazz.getDeclaredMethods();
// Map<Method, Throwable> testFailures = new HashMap<>();
// int ran = 0;
//
// for (Method method : methods) {
// if (method.isAnnotationPresent(TransformedTest.class)) {
// try {
// ran++;
// runTransformed(clazz, method.getName(), handlers);
// } catch (Exception e) {
// //noinspection ThrowableResultOfMethodCallIgnored
// testFailures.put(method, unwrap(e));
// }
// }
// }
//
// if (!testFailures.isEmpty()) {
// StringWriter builder = new StringWriter();
// PrintWriter writer = new PrintWriter(builder);
// writer.println("Transformed tests failed:");
// for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
// writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
// //noinspection ThrowableResultOfMethodCallIgnored
// entry.getValue().printStackTrace(writer);
// writer.println();
// }
// fail(builder.toString());
// }
//
// if (ran == 0) {
// fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
// }
// }
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/handlers/MetricsRegistryHandlerTest.java
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.*;
import com.yammer.telemetry.test.TransformedTest;
import com.yammer.telemetry.tracing.*;
import javassist.ClassPool;
import javassist.CtClass;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import static com.yammer.telemetry.test.TelemetryTestHelpers.runTransformed;
import static org.junit.Assert.*;
@Test
public void testTransformsMetricsRegistryClass() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get("com.yammer.metrics.core.MetricsRegistry");
assertTrue(handler.transformed(ctClass, cp));
}
@Test
public void testUnwrappedTimer() throws Exception {
MetricsRegistry registry = new MetricsRegistry();
Timer timer = registry.newTimer(MetricsRegistryHandlerTest.class, "example");
TimerContext context = timer.time();
context.stop();
assertEquals(1, timer.count());
}
@Test
public void testUnwrappedMeter() throws Exception {
MetricsRegistry registry = new MetricsRegistry();
Meter meter = registry.newMeter(MetricsRegistryHandlerTest.class, "example", "things", TimeUnit.SECONDS);
meter.mark(10);
assertEquals(10, meter.count());
}
@Test
public void testRunTransformedTests() throws Exception {
|
runTransformed(TransformedTests.class, handler);
|
yammer/telemetry
|
telemetry-agent/src/main/java/com/yammer/telemetry/agent/handlers/EnvironmentExecutorClassHandler.java
|
// Path: telemetry-agent/src/main/java/com/yammer/telemetry/agent/handlers/MetricsRegistryHandler.java
// public static void switchImplementation(CtClass cc, ClassPool pool, String from, String to) throws NotFoundException, CannotCompileException {
// CtClass oldClass = pool.get(from);
// CtClass newClass = pool.get(to);
//
// CodeConverter converter = new CodeConverter();
// converter.replaceNew(oldClass, newClass);
//
// cc.instrument(converter);
// }
|
import javassist.*;
import java.io.IOException;
import static com.yammer.telemetry.agent.handlers.MetricsRegistryHandler.switchImplementation;
|
package com.yammer.telemetry.agent.handlers;
public class EnvironmentExecutorClassHandler extends SubTypeInstrumentationHandler {
public EnvironmentExecutorClassHandler() {
super("com.yammer.dropwizard.config.Environment");
}
@Override
protected boolean transform(CtClass cc, ClassPool pool) throws NotFoundException, CannotCompileException, IOException {
if ("com.yammer.dropwizard.config.Environment".equals(cc.getName())) {
|
// Path: telemetry-agent/src/main/java/com/yammer/telemetry/agent/handlers/MetricsRegistryHandler.java
// public static void switchImplementation(CtClass cc, ClassPool pool, String from, String to) throws NotFoundException, CannotCompileException {
// CtClass oldClass = pool.get(from);
// CtClass newClass = pool.get(to);
//
// CodeConverter converter = new CodeConverter();
// converter.replaceNew(oldClass, newClass);
//
// cc.instrument(converter);
// }
// Path: telemetry-agent/src/main/java/com/yammer/telemetry/agent/handlers/EnvironmentExecutorClassHandler.java
import javassist.*;
import java.io.IOException;
import static com.yammer.telemetry.agent.handlers.MetricsRegistryHandler.switchImplementation;
package com.yammer.telemetry.agent.handlers;
public class EnvironmentExecutorClassHandler extends SubTypeInstrumentationHandler {
public EnvironmentExecutorClassHandler() {
super("com.yammer.dropwizard.config.Environment");
}
@Override
protected boolean transform(CtClass cc, ClassPool pool) throws NotFoundException, CannotCompileException, IOException {
if ("com.yammer.dropwizard.config.Environment".equals(cc.getName())) {
|
switchImplementation(cc, pool, "java.util.concurrent.ThreadPoolExecutor", "com.yammer.telemetry.agent.handlers.InstrumentedThreadPoolExecutor");
|
yammer/telemetry
|
telemetry-lib/src/main/java/com/yammer/telemetry/tracing/logging/LogJobFactory.java
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/AsynchronousSpanSink.java
// public class AsynchronousSpanSink implements SpanSink {
// private final ExecutorService executor;
// private final JobFactory jobFactory;
//
// public AsynchronousSpanSink(JobFactory jobFactory) {
// this(Executors.newSingleThreadExecutor(), jobFactory);
// }
//
// public AsynchronousSpanSink(ExecutorService executor, JobFactory jobFactory) {
// this.executor = executor;
// this.jobFactory = jobFactory;
// }
//
// @Override
// public void record(SpanData spanData) {
// Runnable job = jobFactory.createJob(spanData);
// executor.execute(job);
// }
//
// /**
// * Shutdown the underlying executor in a graceful manner.
// *
// * @param timeout grace period for the shutdown to happen within
// * @param timeunit timeunit for grace period
// * @return the number of tasks remaining if executor was forcefully killed.
// */
// public int shutdown(long timeout, TimeUnit timeunit) {
// try {
// executor.shutdown();
// if (executor.awaitTermination(timeout, timeunit)) {
// return 0;
// }
// } catch (InterruptedException ignore) {
// }
//
// return executor.shutdownNow().size();
// }
//
// public static interface JobFactory {
// Runnable createJob(SpanData data);
// }
// }
//
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/SpanData.java
// @SuppressWarnings("UnusedDeclaration")
// public interface SpanData {
// BigInteger getTraceId();
//
// BigInteger getSpanId();
//
// Optional<BigInteger> getParentSpanId();
//
// String getName();
//
// String getHost();
//
// long getStartTime();
//
// long getDuration();
//
// List<AnnotationData> getAnnotations();
// }
|
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.yammer.telemetry.tracing.AsynchronousSpanSink;
import com.yammer.telemetry.tracing.SpanData;
import java.io.*;
import java.nio.charset.Charset;
import java.util.logging.Logger;
|
package com.yammer.telemetry.tracing.logging;
public class LogJobFactory implements AsynchronousSpanSink.JobFactory {
private static final Logger LOG = Logger.getLogger(LogJob.class.getName());
private final WriterProvider writerProvider;
private ObjectMapper objectMapper;
private LogJobFactory(WriterProvider writerProvider) {
this.writerProvider = writerProvider;
this.objectMapper = new ObjectMapper().setPropertyNamingStrategy(new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy()).setSerializationInclusion(JsonInclude.Include.NON_NULL).registerModule(new GuavaModule());
}
public static LogJobFactory withWriter(final Writer writer) {
if (writer == null) throw new NullPointerException("Writer must not be null");
return withWriterProvider(new WriterProvider() {
@Override
public Writer getWriter() throws IOException {
return writer;
}
});
}
public static LogJobFactory withFile(final String file) throws IOException {
// We try and open the file for append to get early warning of misconfiguration, it will fail is file is not
// writable.
try (FileOutputStream ignored = new FileOutputStream(file, true)) {
return withWriterProvider(new WriterProvider() {
@Override
public Writer getWriter() throws IOException {
return new OutputStreamWriter(new FileOutputStream(file, true), Charset.forName("UTF-8").newEncoder());
}
});
}
}
@Override
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/AsynchronousSpanSink.java
// public class AsynchronousSpanSink implements SpanSink {
// private final ExecutorService executor;
// private final JobFactory jobFactory;
//
// public AsynchronousSpanSink(JobFactory jobFactory) {
// this(Executors.newSingleThreadExecutor(), jobFactory);
// }
//
// public AsynchronousSpanSink(ExecutorService executor, JobFactory jobFactory) {
// this.executor = executor;
// this.jobFactory = jobFactory;
// }
//
// @Override
// public void record(SpanData spanData) {
// Runnable job = jobFactory.createJob(spanData);
// executor.execute(job);
// }
//
// /**
// * Shutdown the underlying executor in a graceful manner.
// *
// * @param timeout grace period for the shutdown to happen within
// * @param timeunit timeunit for grace period
// * @return the number of tasks remaining if executor was forcefully killed.
// */
// public int shutdown(long timeout, TimeUnit timeunit) {
// try {
// executor.shutdown();
// if (executor.awaitTermination(timeout, timeunit)) {
// return 0;
// }
// } catch (InterruptedException ignore) {
// }
//
// return executor.shutdownNow().size();
// }
//
// public static interface JobFactory {
// Runnable createJob(SpanData data);
// }
// }
//
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/SpanData.java
// @SuppressWarnings("UnusedDeclaration")
// public interface SpanData {
// BigInteger getTraceId();
//
// BigInteger getSpanId();
//
// Optional<BigInteger> getParentSpanId();
//
// String getName();
//
// String getHost();
//
// long getStartTime();
//
// long getDuration();
//
// List<AnnotationData> getAnnotations();
// }
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/logging/LogJobFactory.java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.yammer.telemetry.tracing.AsynchronousSpanSink;
import com.yammer.telemetry.tracing.SpanData;
import java.io.*;
import java.nio.charset.Charset;
import java.util.logging.Logger;
package com.yammer.telemetry.tracing.logging;
public class LogJobFactory implements AsynchronousSpanSink.JobFactory {
private static final Logger LOG = Logger.getLogger(LogJob.class.getName());
private final WriterProvider writerProvider;
private ObjectMapper objectMapper;
private LogJobFactory(WriterProvider writerProvider) {
this.writerProvider = writerProvider;
this.objectMapper = new ObjectMapper().setPropertyNamingStrategy(new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy()).setSerializationInclusion(JsonInclude.Include.NON_NULL).registerModule(new GuavaModule());
}
public static LogJobFactory withWriter(final Writer writer) {
if (writer == null) throw new NullPointerException("Writer must not be null");
return withWriterProvider(new WriterProvider() {
@Override
public Writer getWriter() throws IOException {
return writer;
}
});
}
public static LogJobFactory withFile(final String file) throws IOException {
// We try and open the file for append to get early warning of misconfiguration, it will fail is file is not
// writable.
try (FileOutputStream ignored = new FileOutputStream(file, true)) {
return withWriterProvider(new WriterProvider() {
@Override
public Writer getWriter() throws IOException {
return new OutputStreamWriter(new FileOutputStream(file, true), Charset.forName("UTF-8").newEncoder());
}
});
}
}
@Override
|
public Runnable createJob(SpanData data) {
|
yammer/telemetry
|
telemetry-agent/src/test/java/com/yammer/telemetry/agent/handlers/ApacheHttpClientClassHandlerTest.java
|
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
// public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
// Method[] methods = clazz.getDeclaredMethods();
// Map<Method, Throwable> testFailures = new HashMap<>();
// int ran = 0;
//
// for (Method method : methods) {
// if (method.isAnnotationPresent(TransformedTest.class)) {
// try {
// ran++;
// runTransformed(clazz, method.getName(), handlers);
// } catch (Exception e) {
// //noinspection ThrowableResultOfMethodCallIgnored
// testFailures.put(method, unwrap(e));
// }
// }
// }
//
// if (!testFailures.isEmpty()) {
// StringWriter builder = new StringWriter();
// PrintWriter writer = new PrintWriter(builder);
// writer.println("Transformed tests failed:");
// for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
// writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
// //noinspection ThrowableResultOfMethodCallIgnored
// entry.getValue().printStackTrace(writer);
// writer.println();
// }
// fail(builder.toString());
// }
//
// if (ran == 0) {
// fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
// }
// }
|
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import com.yammer.telemetry.test.TransformedTest;
import com.yammer.telemetry.tracing.*;
import javassist.ClassPool;
import javassist.CtClass;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import static com.yammer.telemetry.test.TelemetryTestHelpers.runTransformed;
import static org.junit.Assert.*;
|
@Test
public void testHttpClientSubClassDoesGetTransformedIfNonAbstractExecuteMethodExists() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get(HttpClientSubClass.class.getName());
assertTrue(handler.transform(ctClass, cp));
}
@Test
public void testHttpClientAbstractSubClassDoesNotGetTransformed() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get(HttpClientAbstractSubClass.class.getName());
assertFalse(handler.transform(ctClass, cp));
}
@Test
public void testHttpClientSubClassGetsTransformed() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get(AbstractHttpClient.class.getName());
assertTrue(handler.transform(ctClass, cp));
}
@Test
public void testNonHttpClientClassDoesNotGetTransformed() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get(String.class.getName());
assertFalse(handler.transform(ctClass, cp));
}
@Test
public void runTransformedTests() throws Exception {
|
// Path: telemetry-test-framework/src/main/java/com/yammer/telemetry/test/TelemetryTestHelpers.java
// public static void runTransformed(Class<?> clazz, ClassInstrumentationHandler... handlers) throws Exception {
// Method[] methods = clazz.getDeclaredMethods();
// Map<Method, Throwable> testFailures = new HashMap<>();
// int ran = 0;
//
// for (Method method : methods) {
// if (method.isAnnotationPresent(TransformedTest.class)) {
// try {
// ran++;
// runTransformed(clazz, method.getName(), handlers);
// } catch (Exception e) {
// //noinspection ThrowableResultOfMethodCallIgnored
// testFailures.put(method, unwrap(e));
// }
// }
// }
//
// if (!testFailures.isEmpty()) {
// StringWriter builder = new StringWriter();
// PrintWriter writer = new PrintWriter(builder);
// writer.println("Transformed tests failed:");
// for (Map.Entry<Method, Throwable> entry : testFailures.entrySet()) {
// writer.printf("%s:%n%s%n%n", entry.getKey(), entry.getValue());
// //noinspection ThrowableResultOfMethodCallIgnored
// entry.getValue().printStackTrace(writer);
// writer.println();
// }
// fail(builder.toString());
// }
//
// if (ran == 0) {
// fail("No tests were found within '" + clazz.getName() + "' that were annotated as '" + TransformedTest.class.getName() + "'");
// }
// }
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/handlers/ApacheHttpClientClassHandlerTest.java
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import com.yammer.telemetry.test.TransformedTest;
import com.yammer.telemetry.tracing.*;
import javassist.ClassPool;
import javassist.CtClass;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.conn.BasicClientConnectionManager;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.junit.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import static com.yammer.telemetry.test.TelemetryTestHelpers.runTransformed;
import static org.junit.Assert.*;
@Test
public void testHttpClientSubClassDoesGetTransformedIfNonAbstractExecuteMethodExists() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get(HttpClientSubClass.class.getName());
assertTrue(handler.transform(ctClass, cp));
}
@Test
public void testHttpClientAbstractSubClassDoesNotGetTransformed() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get(HttpClientAbstractSubClass.class.getName());
assertFalse(handler.transform(ctClass, cp));
}
@Test
public void testHttpClientSubClassGetsTransformed() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get(AbstractHttpClient.class.getName());
assertTrue(handler.transform(ctClass, cp));
}
@Test
public void testNonHttpClientClassDoesNotGetTransformed() throws Exception {
ClassPool cp = ClassPool.getDefault();
CtClass ctClass = cp.get(String.class.getName());
assertFalse(handler.transform(ctClass, cp));
}
@Test
public void runTransformedTests() throws Exception {
|
runTransformed(TransformedTests.class, handler);
|
yammer/telemetry
|
telemetry-agent/src/main/java/com/yammer/telemetry/agent/TelemetryConfiguration.java
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/Sampling.java
// public abstract class Sampling {
// public static final Sampling ON = new SamplingOn();
// public static final Sampling OFF = new SamplingOff();
//
// public abstract boolean trace();
//
// public static Sampling valueOf(String samplerName) {
// if ("off".equalsIgnoreCase(samplerName)) return OFF;
// if ("on".equalsIgnoreCase(samplerName)) return ON;
// return null;
// }
//
// private static class SamplingOff extends Sampling {
// @Override
// public boolean trace() {
// return false;
// }
// }
//
// private static class SamplingOn extends Sampling {
// @Override
// public boolean trace() {
// return true;
// }
// }
// }
//
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/ServiceAnnotations.java
// public class ServiceAnnotations {
// public String service;
// public int pid;
// public String host;
//
// public ServiceAnnotations() {
// initPidAndHost();
// }
//
// public ServiceAnnotations(String service) {
// this.service = service;
// initPidAndHost();
// }
//
// private void initPidAndHost() {
// String pidAndHostString = ManagementFactory.getRuntimeMXBean().getName();
// if (pidAndHostString != null) {
// String[] pidAndHost = pidAndHostString.split("@");
// if (pidAndHost.length == 2) {
// try {
// this.pid = Integer.parseInt(pidAndHost[0]);
// } catch (NumberFormatException ignored) {
// }
// this.host = pidAndHost[1];
// } else {
// this.host = pidAndHostString;
// }
// }
// }
//
// public String getService() {
// return service;
// }
//
// @JsonIgnore
// public int getPid() {
// return pid;
// }
//
// @JsonIgnore
// public String getHost() {
// return host;
// }
// }
|
import com.yammer.telemetry.tracing.Sampling;
import com.yammer.telemetry.tracing.ServiceAnnotations;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
|
package com.yammer.telemetry.agent;
public class TelemetryConfiguration {
private List<String> instruments = Collections.emptyList();
private SinkConfiguration sinks = new SinkConfiguration();
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/Sampling.java
// public abstract class Sampling {
// public static final Sampling ON = new SamplingOn();
// public static final Sampling OFF = new SamplingOff();
//
// public abstract boolean trace();
//
// public static Sampling valueOf(String samplerName) {
// if ("off".equalsIgnoreCase(samplerName)) return OFF;
// if ("on".equalsIgnoreCase(samplerName)) return ON;
// return null;
// }
//
// private static class SamplingOff extends Sampling {
// @Override
// public boolean trace() {
// return false;
// }
// }
//
// private static class SamplingOn extends Sampling {
// @Override
// public boolean trace() {
// return true;
// }
// }
// }
//
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/ServiceAnnotations.java
// public class ServiceAnnotations {
// public String service;
// public int pid;
// public String host;
//
// public ServiceAnnotations() {
// initPidAndHost();
// }
//
// public ServiceAnnotations(String service) {
// this.service = service;
// initPidAndHost();
// }
//
// private void initPidAndHost() {
// String pidAndHostString = ManagementFactory.getRuntimeMXBean().getName();
// if (pidAndHostString != null) {
// String[] pidAndHost = pidAndHostString.split("@");
// if (pidAndHost.length == 2) {
// try {
// this.pid = Integer.parseInt(pidAndHost[0]);
// } catch (NumberFormatException ignored) {
// }
// this.host = pidAndHost[1];
// } else {
// this.host = pidAndHostString;
// }
// }
// }
//
// public String getService() {
// return service;
// }
//
// @JsonIgnore
// public int getPid() {
// return pid;
// }
//
// @JsonIgnore
// public String getHost() {
// return host;
// }
// }
// Path: telemetry-agent/src/main/java/com/yammer/telemetry/agent/TelemetryConfiguration.java
import com.yammer.telemetry.tracing.Sampling;
import com.yammer.telemetry.tracing.ServiceAnnotations;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
package com.yammer.telemetry.agent;
public class TelemetryConfiguration {
private List<String> instruments = Collections.emptyList();
private SinkConfiguration sinks = new SinkConfiguration();
|
private ServiceAnnotations annotations = new ServiceAnnotations("unknown");
|
yammer/telemetry
|
telemetry-agent/src/main/java/com/yammer/telemetry/agent/TelemetryConfiguration.java
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/Sampling.java
// public abstract class Sampling {
// public static final Sampling ON = new SamplingOn();
// public static final Sampling OFF = new SamplingOff();
//
// public abstract boolean trace();
//
// public static Sampling valueOf(String samplerName) {
// if ("off".equalsIgnoreCase(samplerName)) return OFF;
// if ("on".equalsIgnoreCase(samplerName)) return ON;
// return null;
// }
//
// private static class SamplingOff extends Sampling {
// @Override
// public boolean trace() {
// return false;
// }
// }
//
// private static class SamplingOn extends Sampling {
// @Override
// public boolean trace() {
// return true;
// }
// }
// }
//
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/ServiceAnnotations.java
// public class ServiceAnnotations {
// public String service;
// public int pid;
// public String host;
//
// public ServiceAnnotations() {
// initPidAndHost();
// }
//
// public ServiceAnnotations(String service) {
// this.service = service;
// initPidAndHost();
// }
//
// private void initPidAndHost() {
// String pidAndHostString = ManagementFactory.getRuntimeMXBean().getName();
// if (pidAndHostString != null) {
// String[] pidAndHost = pidAndHostString.split("@");
// if (pidAndHost.length == 2) {
// try {
// this.pid = Integer.parseInt(pidAndHost[0]);
// } catch (NumberFormatException ignored) {
// }
// this.host = pidAndHost[1];
// } else {
// this.host = pidAndHostString;
// }
// }
// }
//
// public String getService() {
// return service;
// }
//
// @JsonIgnore
// public int getPid() {
// return pid;
// }
//
// @JsonIgnore
// public String getHost() {
// return host;
// }
// }
|
import com.yammer.telemetry.tracing.Sampling;
import com.yammer.telemetry.tracing.ServiceAnnotations;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
|
package com.yammer.telemetry.agent;
public class TelemetryConfiguration {
private List<String> instruments = Collections.emptyList();
private SinkConfiguration sinks = new SinkConfiguration();
private ServiceAnnotations annotations = new ServiceAnnotations("unknown");
@NotNull
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/Sampling.java
// public abstract class Sampling {
// public static final Sampling ON = new SamplingOn();
// public static final Sampling OFF = new SamplingOff();
//
// public abstract boolean trace();
//
// public static Sampling valueOf(String samplerName) {
// if ("off".equalsIgnoreCase(samplerName)) return OFF;
// if ("on".equalsIgnoreCase(samplerName)) return ON;
// return null;
// }
//
// private static class SamplingOff extends Sampling {
// @Override
// public boolean trace() {
// return false;
// }
// }
//
// private static class SamplingOn extends Sampling {
// @Override
// public boolean trace() {
// return true;
// }
// }
// }
//
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/ServiceAnnotations.java
// public class ServiceAnnotations {
// public String service;
// public int pid;
// public String host;
//
// public ServiceAnnotations() {
// initPidAndHost();
// }
//
// public ServiceAnnotations(String service) {
// this.service = service;
// initPidAndHost();
// }
//
// private void initPidAndHost() {
// String pidAndHostString = ManagementFactory.getRuntimeMXBean().getName();
// if (pidAndHostString != null) {
// String[] pidAndHost = pidAndHostString.split("@");
// if (pidAndHost.length == 2) {
// try {
// this.pid = Integer.parseInt(pidAndHost[0]);
// } catch (NumberFormatException ignored) {
// }
// this.host = pidAndHost[1];
// } else {
// this.host = pidAndHostString;
// }
// }
// }
//
// public String getService() {
// return service;
// }
//
// @JsonIgnore
// public int getPid() {
// return pid;
// }
//
// @JsonIgnore
// public String getHost() {
// return host;
// }
// }
// Path: telemetry-agent/src/main/java/com/yammer/telemetry/agent/TelemetryConfiguration.java
import com.yammer.telemetry.tracing.Sampling;
import com.yammer.telemetry.tracing.ServiceAnnotations;
import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.List;
package com.yammer.telemetry.agent;
public class TelemetryConfiguration {
private List<String> instruments = Collections.emptyList();
private SinkConfiguration sinks = new SinkConfiguration();
private ServiceAnnotations annotations = new ServiceAnnotations("unknown");
@NotNull
|
private Sampling sampler = Sampling.ON;
|
yammer/telemetry
|
telemetry-agent/src/test/java/com/yammer/telemetry/agent/TelemetryConfigurationTest.java
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/Sampling.java
// public abstract class Sampling {
// public static final Sampling ON = new SamplingOn();
// public static final Sampling OFF = new SamplingOff();
//
// public abstract boolean trace();
//
// public static Sampling valueOf(String samplerName) {
// if ("off".equalsIgnoreCase(samplerName)) return OFF;
// if ("on".equalsIgnoreCase(samplerName)) return ON;
// return null;
// }
//
// private static class SamplingOff extends Sampling {
// @Override
// public boolean trace() {
// return false;
// }
// }
//
// private static class SamplingOn extends Sampling {
// @Override
// public boolean trace() {
// return true;
// }
// }
// }
|
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.google.common.collect.ImmutableList;
import com.yammer.dropwizard.config.ConfigurationException;
import com.yammer.dropwizard.validation.Validator;
import com.yammer.telemetry.tracing.Sampling;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import static org.junit.Assert.*;
|
package com.yammer.telemetry.agent;
public class TelemetryConfigurationTest {
@Test
public void testConstructionDefaults() {
TelemetryConfiguration configuration = new TelemetryConfiguration();
assertEquals(ImmutableList.<String>of(), configuration.getInstruments());
assertEquals("unknown", configuration.getAnnotations().getService());
|
// Path: telemetry-lib/src/main/java/com/yammer/telemetry/tracing/Sampling.java
// public abstract class Sampling {
// public static final Sampling ON = new SamplingOn();
// public static final Sampling OFF = new SamplingOff();
//
// public abstract boolean trace();
//
// public static Sampling valueOf(String samplerName) {
// if ("off".equalsIgnoreCase(samplerName)) return OFF;
// if ("on".equalsIgnoreCase(samplerName)) return ON;
// return null;
// }
//
// private static class SamplingOff extends Sampling {
// @Override
// public boolean trace() {
// return false;
// }
// }
//
// private static class SamplingOn extends Sampling {
// @Override
// public boolean trace() {
// return true;
// }
// }
// }
// Path: telemetry-agent/src/test/java/com/yammer/telemetry/agent/TelemetryConfigurationTest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.google.common.collect.ImmutableList;
import com.yammer.dropwizard.config.ConfigurationException;
import com.yammer.dropwizard.validation.Validator;
import com.yammer.telemetry.tracing.Sampling;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import static org.junit.Assert.*;
package com.yammer.telemetry.agent;
public class TelemetryConfigurationTest {
@Test
public void testConstructionDefaults() {
TelemetryConfiguration configuration = new TelemetryConfiguration();
assertEquals(ImmutableList.<String>of(), configuration.getInstruments());
assertEquals("unknown", configuration.getAnnotations().getService());
|
assertEquals(Sampling.ON, configuration.getSampler());
|
Vrekt/Lunar
|
src/main/java/com/lunar/Lunar.java
|
// Path: src/main/java/com/lunar/asset/AssetManager.java
// public class AssetManager {
//
// private final List<Tile> TILES = new ArrayList<>();
//
// /**
// * Add a tile.
// */
// public void addTile(Tile tile) {
// TILES.add(tile);
// }
//
// /**
// * Remove the tile.
// */
// public void removeTile(Tile tile) {
// TILES.remove(tile);
// }
//
// /**
// * @param ID the tile ID.
// * @return the Tile with the ID.
// */
// public Tile getByID(int ID) {
// return TILES.stream().filter(tile -> tile.getID() == ID).findAny().orElse(null);
// }
//
// /**
// * @return list of all TILES.
// */
// public List<Tile> getTiles() {
// return TILES;
// }
// }
//
// Path: src/main/java/com/lunar/sound/SoundManager.java
// public class SoundManager {
//
// private final List<Sound> GAME_SOUNDS = new ArrayList<>();
//
// /**
// * Adds a sound.
// *
// * @param sound The sound Object.
// */
// public void addSound(Sound sound) {
// GAME_SOUNDS.add(sound);
// }
//
// /**
// * Adds a sound.
// *
// * @param name The name of the audio.
// * @param file The audio file.
// */
// public void addSound(String name, File file) {
// GAME_SOUNDS.add(new Sound(name, file));
// }
//
// /**
// * Gets a sound via ID.
// *
// * @param name The name of the Sound.
// */
// public Sound getSound(String name) {
// return GAME_SOUNDS.stream().filter(sound -> sound.getName().equals(name)).findAny().orElse(null);
// }
//
// /**
// * Check if the sound exists.
// *
// * @return if the sound exists.
// */
// public boolean doesSoundExist(String name) {
// return getSound(name) != null;
// }
//
// /**
// * Removes a sound from the list.
// *
// * @param name The ID of the Sound.
// */
// public void removeSound(String name) {
// Sound s = getSound(name);
// if (GAME_SOUNDS.contains(s)) {
// GAME_SOUNDS.remove(s);
// }
// }
//
// /**
// * Remove the sound.
// */
// public void removeSound(Sound sound) {
// if (GAME_SOUNDS.contains(sound)) {
// GAME_SOUNDS.remove(sound);
// }
// }
//
// /**
// * Plays a sound with a clip.
// *
// * @param sound The Sound object.
// */
// public void playSound(Sound sound) {
// sound.play();
// }
//
// /**
// * Plays a sound with a clip.
// */
// public void playSound(String name) {
// getSound(name).play();
// }
//
// /**
// * Plays a sound with a clip. This does not support stopping.
// *
// * @param file The audio file.
// */
// public void playSound(File file) {
// Sound sound = new Sound("TEMP_" + file.getName(), file);
// sound.play();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(Sound sound) {
// sound.stop();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(String name) {
// getSound(name).stop();
// }
//
// }
//
// Path: src/main/java/com/lunar/state/GameState.java
// public abstract class GameState {
//
// protected int priority = 0;
//
// /**
// * Initializes the GameState.
// */
// public GameState(int priority) {
// this.priority = priority;
// }
//
// public abstract void onDraw(Graphics graphics);
//
// public abstract void onTick();
//
// public void onStart() {
// }
//
// /**
// * @return the priority.
// */
// public int getPriority() {
// return priority;
// }
//
// }
|
import com.lunar.asset.AssetManager;
import com.lunar.sound.SoundManager;
import com.lunar.state.GameState;
|
package com.lunar;
public class Lunar {
private Game game;
|
// Path: src/main/java/com/lunar/asset/AssetManager.java
// public class AssetManager {
//
// private final List<Tile> TILES = new ArrayList<>();
//
// /**
// * Add a tile.
// */
// public void addTile(Tile tile) {
// TILES.add(tile);
// }
//
// /**
// * Remove the tile.
// */
// public void removeTile(Tile tile) {
// TILES.remove(tile);
// }
//
// /**
// * @param ID the tile ID.
// * @return the Tile with the ID.
// */
// public Tile getByID(int ID) {
// return TILES.stream().filter(tile -> tile.getID() == ID).findAny().orElse(null);
// }
//
// /**
// * @return list of all TILES.
// */
// public List<Tile> getTiles() {
// return TILES;
// }
// }
//
// Path: src/main/java/com/lunar/sound/SoundManager.java
// public class SoundManager {
//
// private final List<Sound> GAME_SOUNDS = new ArrayList<>();
//
// /**
// * Adds a sound.
// *
// * @param sound The sound Object.
// */
// public void addSound(Sound sound) {
// GAME_SOUNDS.add(sound);
// }
//
// /**
// * Adds a sound.
// *
// * @param name The name of the audio.
// * @param file The audio file.
// */
// public void addSound(String name, File file) {
// GAME_SOUNDS.add(new Sound(name, file));
// }
//
// /**
// * Gets a sound via ID.
// *
// * @param name The name of the Sound.
// */
// public Sound getSound(String name) {
// return GAME_SOUNDS.stream().filter(sound -> sound.getName().equals(name)).findAny().orElse(null);
// }
//
// /**
// * Check if the sound exists.
// *
// * @return if the sound exists.
// */
// public boolean doesSoundExist(String name) {
// return getSound(name) != null;
// }
//
// /**
// * Removes a sound from the list.
// *
// * @param name The ID of the Sound.
// */
// public void removeSound(String name) {
// Sound s = getSound(name);
// if (GAME_SOUNDS.contains(s)) {
// GAME_SOUNDS.remove(s);
// }
// }
//
// /**
// * Remove the sound.
// */
// public void removeSound(Sound sound) {
// if (GAME_SOUNDS.contains(sound)) {
// GAME_SOUNDS.remove(sound);
// }
// }
//
// /**
// * Plays a sound with a clip.
// *
// * @param sound The Sound object.
// */
// public void playSound(Sound sound) {
// sound.play();
// }
//
// /**
// * Plays a sound with a clip.
// */
// public void playSound(String name) {
// getSound(name).play();
// }
//
// /**
// * Plays a sound with a clip. This does not support stopping.
// *
// * @param file The audio file.
// */
// public void playSound(File file) {
// Sound sound = new Sound("TEMP_" + file.getName(), file);
// sound.play();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(Sound sound) {
// sound.stop();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(String name) {
// getSound(name).stop();
// }
//
// }
//
// Path: src/main/java/com/lunar/state/GameState.java
// public abstract class GameState {
//
// protected int priority = 0;
//
// /**
// * Initializes the GameState.
// */
// public GameState(int priority) {
// this.priority = priority;
// }
//
// public abstract void onDraw(Graphics graphics);
//
// public abstract void onTick();
//
// public void onStart() {
// }
//
// /**
// * @return the priority.
// */
// public int getPriority() {
// return priority;
// }
//
// }
// Path: src/main/java/com/lunar/Lunar.java
import com.lunar.asset.AssetManager;
import com.lunar.sound.SoundManager;
import com.lunar.state.GameState;
package com.lunar;
public class Lunar {
private Game game;
|
private SoundManager soundManager;
|
Vrekt/Lunar
|
src/main/java/com/lunar/Lunar.java
|
// Path: src/main/java/com/lunar/asset/AssetManager.java
// public class AssetManager {
//
// private final List<Tile> TILES = new ArrayList<>();
//
// /**
// * Add a tile.
// */
// public void addTile(Tile tile) {
// TILES.add(tile);
// }
//
// /**
// * Remove the tile.
// */
// public void removeTile(Tile tile) {
// TILES.remove(tile);
// }
//
// /**
// * @param ID the tile ID.
// * @return the Tile with the ID.
// */
// public Tile getByID(int ID) {
// return TILES.stream().filter(tile -> tile.getID() == ID).findAny().orElse(null);
// }
//
// /**
// * @return list of all TILES.
// */
// public List<Tile> getTiles() {
// return TILES;
// }
// }
//
// Path: src/main/java/com/lunar/sound/SoundManager.java
// public class SoundManager {
//
// private final List<Sound> GAME_SOUNDS = new ArrayList<>();
//
// /**
// * Adds a sound.
// *
// * @param sound The sound Object.
// */
// public void addSound(Sound sound) {
// GAME_SOUNDS.add(sound);
// }
//
// /**
// * Adds a sound.
// *
// * @param name The name of the audio.
// * @param file The audio file.
// */
// public void addSound(String name, File file) {
// GAME_SOUNDS.add(new Sound(name, file));
// }
//
// /**
// * Gets a sound via ID.
// *
// * @param name The name of the Sound.
// */
// public Sound getSound(String name) {
// return GAME_SOUNDS.stream().filter(sound -> sound.getName().equals(name)).findAny().orElse(null);
// }
//
// /**
// * Check if the sound exists.
// *
// * @return if the sound exists.
// */
// public boolean doesSoundExist(String name) {
// return getSound(name) != null;
// }
//
// /**
// * Removes a sound from the list.
// *
// * @param name The ID of the Sound.
// */
// public void removeSound(String name) {
// Sound s = getSound(name);
// if (GAME_SOUNDS.contains(s)) {
// GAME_SOUNDS.remove(s);
// }
// }
//
// /**
// * Remove the sound.
// */
// public void removeSound(Sound sound) {
// if (GAME_SOUNDS.contains(sound)) {
// GAME_SOUNDS.remove(sound);
// }
// }
//
// /**
// * Plays a sound with a clip.
// *
// * @param sound The Sound object.
// */
// public void playSound(Sound sound) {
// sound.play();
// }
//
// /**
// * Plays a sound with a clip.
// */
// public void playSound(String name) {
// getSound(name).play();
// }
//
// /**
// * Plays a sound with a clip. This does not support stopping.
// *
// * @param file The audio file.
// */
// public void playSound(File file) {
// Sound sound = new Sound("TEMP_" + file.getName(), file);
// sound.play();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(Sound sound) {
// sound.stop();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(String name) {
// getSound(name).stop();
// }
//
// }
//
// Path: src/main/java/com/lunar/state/GameState.java
// public abstract class GameState {
//
// protected int priority = 0;
//
// /**
// * Initializes the GameState.
// */
// public GameState(int priority) {
// this.priority = priority;
// }
//
// public abstract void onDraw(Graphics graphics);
//
// public abstract void onTick();
//
// public void onStart() {
// }
//
// /**
// * @return the priority.
// */
// public int getPriority() {
// return priority;
// }
//
// }
|
import com.lunar.asset.AssetManager;
import com.lunar.sound.SoundManager;
import com.lunar.state.GameState;
|
package com.lunar;
public class Lunar {
private Game game;
private SoundManager soundManager;
|
// Path: src/main/java/com/lunar/asset/AssetManager.java
// public class AssetManager {
//
// private final List<Tile> TILES = new ArrayList<>();
//
// /**
// * Add a tile.
// */
// public void addTile(Tile tile) {
// TILES.add(tile);
// }
//
// /**
// * Remove the tile.
// */
// public void removeTile(Tile tile) {
// TILES.remove(tile);
// }
//
// /**
// * @param ID the tile ID.
// * @return the Tile with the ID.
// */
// public Tile getByID(int ID) {
// return TILES.stream().filter(tile -> tile.getID() == ID).findAny().orElse(null);
// }
//
// /**
// * @return list of all TILES.
// */
// public List<Tile> getTiles() {
// return TILES;
// }
// }
//
// Path: src/main/java/com/lunar/sound/SoundManager.java
// public class SoundManager {
//
// private final List<Sound> GAME_SOUNDS = new ArrayList<>();
//
// /**
// * Adds a sound.
// *
// * @param sound The sound Object.
// */
// public void addSound(Sound sound) {
// GAME_SOUNDS.add(sound);
// }
//
// /**
// * Adds a sound.
// *
// * @param name The name of the audio.
// * @param file The audio file.
// */
// public void addSound(String name, File file) {
// GAME_SOUNDS.add(new Sound(name, file));
// }
//
// /**
// * Gets a sound via ID.
// *
// * @param name The name of the Sound.
// */
// public Sound getSound(String name) {
// return GAME_SOUNDS.stream().filter(sound -> sound.getName().equals(name)).findAny().orElse(null);
// }
//
// /**
// * Check if the sound exists.
// *
// * @return if the sound exists.
// */
// public boolean doesSoundExist(String name) {
// return getSound(name) != null;
// }
//
// /**
// * Removes a sound from the list.
// *
// * @param name The ID of the Sound.
// */
// public void removeSound(String name) {
// Sound s = getSound(name);
// if (GAME_SOUNDS.contains(s)) {
// GAME_SOUNDS.remove(s);
// }
// }
//
// /**
// * Remove the sound.
// */
// public void removeSound(Sound sound) {
// if (GAME_SOUNDS.contains(sound)) {
// GAME_SOUNDS.remove(sound);
// }
// }
//
// /**
// * Plays a sound with a clip.
// *
// * @param sound The Sound object.
// */
// public void playSound(Sound sound) {
// sound.play();
// }
//
// /**
// * Plays a sound with a clip.
// */
// public void playSound(String name) {
// getSound(name).play();
// }
//
// /**
// * Plays a sound with a clip. This does not support stopping.
// *
// * @param file The audio file.
// */
// public void playSound(File file) {
// Sound sound = new Sound("TEMP_" + file.getName(), file);
// sound.play();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(Sound sound) {
// sound.stop();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(String name) {
// getSound(name).stop();
// }
//
// }
//
// Path: src/main/java/com/lunar/state/GameState.java
// public abstract class GameState {
//
// protected int priority = 0;
//
// /**
// * Initializes the GameState.
// */
// public GameState(int priority) {
// this.priority = priority;
// }
//
// public abstract void onDraw(Graphics graphics);
//
// public abstract void onTick();
//
// public void onStart() {
// }
//
// /**
// * @return the priority.
// */
// public int getPriority() {
// return priority;
// }
//
// }
// Path: src/main/java/com/lunar/Lunar.java
import com.lunar.asset.AssetManager;
import com.lunar.sound.SoundManager;
import com.lunar.state.GameState;
package com.lunar;
public class Lunar {
private Game game;
private SoundManager soundManager;
|
private AssetManager assetManager;
|
Vrekt/Lunar
|
src/main/java/com/lunar/Lunar.java
|
// Path: src/main/java/com/lunar/asset/AssetManager.java
// public class AssetManager {
//
// private final List<Tile> TILES = new ArrayList<>();
//
// /**
// * Add a tile.
// */
// public void addTile(Tile tile) {
// TILES.add(tile);
// }
//
// /**
// * Remove the tile.
// */
// public void removeTile(Tile tile) {
// TILES.remove(tile);
// }
//
// /**
// * @param ID the tile ID.
// * @return the Tile with the ID.
// */
// public Tile getByID(int ID) {
// return TILES.stream().filter(tile -> tile.getID() == ID).findAny().orElse(null);
// }
//
// /**
// * @return list of all TILES.
// */
// public List<Tile> getTiles() {
// return TILES;
// }
// }
//
// Path: src/main/java/com/lunar/sound/SoundManager.java
// public class SoundManager {
//
// private final List<Sound> GAME_SOUNDS = new ArrayList<>();
//
// /**
// * Adds a sound.
// *
// * @param sound The sound Object.
// */
// public void addSound(Sound sound) {
// GAME_SOUNDS.add(sound);
// }
//
// /**
// * Adds a sound.
// *
// * @param name The name of the audio.
// * @param file The audio file.
// */
// public void addSound(String name, File file) {
// GAME_SOUNDS.add(new Sound(name, file));
// }
//
// /**
// * Gets a sound via ID.
// *
// * @param name The name of the Sound.
// */
// public Sound getSound(String name) {
// return GAME_SOUNDS.stream().filter(sound -> sound.getName().equals(name)).findAny().orElse(null);
// }
//
// /**
// * Check if the sound exists.
// *
// * @return if the sound exists.
// */
// public boolean doesSoundExist(String name) {
// return getSound(name) != null;
// }
//
// /**
// * Removes a sound from the list.
// *
// * @param name The ID of the Sound.
// */
// public void removeSound(String name) {
// Sound s = getSound(name);
// if (GAME_SOUNDS.contains(s)) {
// GAME_SOUNDS.remove(s);
// }
// }
//
// /**
// * Remove the sound.
// */
// public void removeSound(Sound sound) {
// if (GAME_SOUNDS.contains(sound)) {
// GAME_SOUNDS.remove(sound);
// }
// }
//
// /**
// * Plays a sound with a clip.
// *
// * @param sound The Sound object.
// */
// public void playSound(Sound sound) {
// sound.play();
// }
//
// /**
// * Plays a sound with a clip.
// */
// public void playSound(String name) {
// getSound(name).play();
// }
//
// /**
// * Plays a sound with a clip. This does not support stopping.
// *
// * @param file The audio file.
// */
// public void playSound(File file) {
// Sound sound = new Sound("TEMP_" + file.getName(), file);
// sound.play();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(Sound sound) {
// sound.stop();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(String name) {
// getSound(name).stop();
// }
//
// }
//
// Path: src/main/java/com/lunar/state/GameState.java
// public abstract class GameState {
//
// protected int priority = 0;
//
// /**
// * Initializes the GameState.
// */
// public GameState(int priority) {
// this.priority = priority;
// }
//
// public abstract void onDraw(Graphics graphics);
//
// public abstract void onTick();
//
// public void onStart() {
// }
//
// /**
// * @return the priority.
// */
// public int getPriority() {
// return priority;
// }
//
// }
|
import com.lunar.asset.AssetManager;
import com.lunar.sound.SoundManager;
import com.lunar.state.GameState;
|
package com.lunar;
public class Lunar {
private Game game;
private SoundManager soundManager;
private AssetManager assetManager;
/**
* Initialize the game.
*
* @param title The title of the game's window.
* @param width The width of the game's window.
* @param height The height of the game's window.
* @param tickRate indicates how fast the game is drawn/updated.
* A good tickrate is 64 or above.
*/
public void initializeGame(String title, int width, int height, int tickRate) {
game = new Game(title, width, height, tickRate);
soundManager = new SoundManager();
assetManager = new AssetManager();
}
/**
* Initialize the game.
*
* @param title The title of the game's window.
* @param width The width of the game's window.
* @param height The height of the game's window.
* @param state A default {@link GameState} object to use.
* @param tickRate indicates how fast the game is drawn/updated.
* A good tickrate is 64 or above.
*/
|
// Path: src/main/java/com/lunar/asset/AssetManager.java
// public class AssetManager {
//
// private final List<Tile> TILES = new ArrayList<>();
//
// /**
// * Add a tile.
// */
// public void addTile(Tile tile) {
// TILES.add(tile);
// }
//
// /**
// * Remove the tile.
// */
// public void removeTile(Tile tile) {
// TILES.remove(tile);
// }
//
// /**
// * @param ID the tile ID.
// * @return the Tile with the ID.
// */
// public Tile getByID(int ID) {
// return TILES.stream().filter(tile -> tile.getID() == ID).findAny().orElse(null);
// }
//
// /**
// * @return list of all TILES.
// */
// public List<Tile> getTiles() {
// return TILES;
// }
// }
//
// Path: src/main/java/com/lunar/sound/SoundManager.java
// public class SoundManager {
//
// private final List<Sound> GAME_SOUNDS = new ArrayList<>();
//
// /**
// * Adds a sound.
// *
// * @param sound The sound Object.
// */
// public void addSound(Sound sound) {
// GAME_SOUNDS.add(sound);
// }
//
// /**
// * Adds a sound.
// *
// * @param name The name of the audio.
// * @param file The audio file.
// */
// public void addSound(String name, File file) {
// GAME_SOUNDS.add(new Sound(name, file));
// }
//
// /**
// * Gets a sound via ID.
// *
// * @param name The name of the Sound.
// */
// public Sound getSound(String name) {
// return GAME_SOUNDS.stream().filter(sound -> sound.getName().equals(name)).findAny().orElse(null);
// }
//
// /**
// * Check if the sound exists.
// *
// * @return if the sound exists.
// */
// public boolean doesSoundExist(String name) {
// return getSound(name) != null;
// }
//
// /**
// * Removes a sound from the list.
// *
// * @param name The ID of the Sound.
// */
// public void removeSound(String name) {
// Sound s = getSound(name);
// if (GAME_SOUNDS.contains(s)) {
// GAME_SOUNDS.remove(s);
// }
// }
//
// /**
// * Remove the sound.
// */
// public void removeSound(Sound sound) {
// if (GAME_SOUNDS.contains(sound)) {
// GAME_SOUNDS.remove(sound);
// }
// }
//
// /**
// * Plays a sound with a clip.
// *
// * @param sound The Sound object.
// */
// public void playSound(Sound sound) {
// sound.play();
// }
//
// /**
// * Plays a sound with a clip.
// */
// public void playSound(String name) {
// getSound(name).play();
// }
//
// /**
// * Plays a sound with a clip. This does not support stopping.
// *
// * @param file The audio file.
// */
// public void playSound(File file) {
// Sound sound = new Sound("TEMP_" + file.getName(), file);
// sound.play();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(Sound sound) {
// sound.stop();
// }
//
// /**
// * Stop playing the sound.
// */
// public void stopPlayingSound(String name) {
// getSound(name).stop();
// }
//
// }
//
// Path: src/main/java/com/lunar/state/GameState.java
// public abstract class GameState {
//
// protected int priority = 0;
//
// /**
// * Initializes the GameState.
// */
// public GameState(int priority) {
// this.priority = priority;
// }
//
// public abstract void onDraw(Graphics graphics);
//
// public abstract void onTick();
//
// public void onStart() {
// }
//
// /**
// * @return the priority.
// */
// public int getPriority() {
// return priority;
// }
//
// }
// Path: src/main/java/com/lunar/Lunar.java
import com.lunar.asset.AssetManager;
import com.lunar.sound.SoundManager;
import com.lunar.state.GameState;
package com.lunar;
public class Lunar {
private Game game;
private SoundManager soundManager;
private AssetManager assetManager;
/**
* Initialize the game.
*
* @param title The title of the game's window.
* @param width The width of the game's window.
* @param height The height of the game's window.
* @param tickRate indicates how fast the game is drawn/updated.
* A good tickrate is 64 or above.
*/
public void initializeGame(String title, int width, int height, int tickRate) {
game = new Game(title, width, height, tickRate);
soundManager = new SoundManager();
assetManager = new AssetManager();
}
/**
* Initialize the game.
*
* @param title The title of the game's window.
* @param width The width of the game's window.
* @param height The height of the game's window.
* @param state A default {@link GameState} object to use.
* @param tickRate indicates how fast the game is drawn/updated.
* A good tickrate is 64 or above.
*/
|
public void initializeGame(String title, int width, int height, GameState state, int tickRate) {
|
Vrekt/Lunar
|
src/main/java/com/lunar/animation/AnimationManager.java
|
// Path: src/main/java/com/lunar/utilities/Logger.java
// public class Logger {
//
// /**
// * Log information.
// *
// * @param information the information.
// */
// public static void logInformation(String information) {
// System.out.println("[INFO] " + information);
// }
//
// /**
// * Log an error.
// *
// * @param error the error
// */
// public static void logError(String error) {
// System.out.println("[ERROR] " + error);
// }
//
// /**
// * Log a warning
// *
// * @param warning the warning
// */
// public static void logWarning(String warning) {
// System.out.println("[WARNING] " + warning);
// }
//
// /**
// * Log a critical message.
// *
// * @param critical the critical message.
// */
// public static void logCritical(String critical) {
// System.out.println("[CRITICAL] " + critical);
// }
//
// }
|
import com.lunar.utilities.Logger;
import com.sun.istack.internal.Nullable;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
|
package com.lunar.animation;
public class AnimationManager {
private List<Animation> animationFrames;
private Animation playingAnimation;
public AnimationManager(Animation[] animations) {
animationFrames = Arrays.asList(animations);
}
public AnimationManager(List<Animation> animations) {
animationFrames = new ArrayList<>(animations);
}
public AnimationManager(Animation animation) {
animationFrames = new ArrayList<>();
animationFrames.add(animation);
}
/**
* @return all the animations.
*/
public List<Animation> getAnimationFrames() {
return animationFrames;
}
/**
* @return the current playing animation.
*/
@Nullable
public Animation getPlayingAnimation() {
return playingAnimation == null ? null : playingAnimation.isRunning() ? playingAnimation : null;
}
/**
* Update the current playing animation.
*/
public void updatePlayingAnimation() {
if (playingAnimation == null) {
|
// Path: src/main/java/com/lunar/utilities/Logger.java
// public class Logger {
//
// /**
// * Log information.
// *
// * @param information the information.
// */
// public static void logInformation(String information) {
// System.out.println("[INFO] " + information);
// }
//
// /**
// * Log an error.
// *
// * @param error the error
// */
// public static void logError(String error) {
// System.out.println("[ERROR] " + error);
// }
//
// /**
// * Log a warning
// *
// * @param warning the warning
// */
// public static void logWarning(String warning) {
// System.out.println("[WARNING] " + warning);
// }
//
// /**
// * Log a critical message.
// *
// * @param critical the critical message.
// */
// public static void logCritical(String critical) {
// System.out.println("[CRITICAL] " + critical);
// }
//
// }
// Path: src/main/java/com/lunar/animation/AnimationManager.java
import com.lunar.utilities.Logger;
import com.sun.istack.internal.Nullable;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
package com.lunar.animation;
public class AnimationManager {
private List<Animation> animationFrames;
private Animation playingAnimation;
public AnimationManager(Animation[] animations) {
animationFrames = Arrays.asList(animations);
}
public AnimationManager(List<Animation> animations) {
animationFrames = new ArrayList<>(animations);
}
public AnimationManager(Animation animation) {
animationFrames = new ArrayList<>();
animationFrames.add(animation);
}
/**
* @return all the animations.
*/
public List<Animation> getAnimationFrames() {
return animationFrames;
}
/**
* @return the current playing animation.
*/
@Nullable
public Animation getPlayingAnimation() {
return playingAnimation == null ? null : playingAnimation.isRunning() ? playingAnimation : null;
}
/**
* Update the current playing animation.
*/
public void updatePlayingAnimation() {
if (playingAnimation == null) {
|
Logger.logWarning("Attempted to update a null animation frame.");
|
Vrekt/Lunar
|
src/main/java/com/lunar/tile/Tile.java
|
// Path: src/main/java/com/lunar/collision/BoundingBox.java
// public class BoundingBox {
//
// /**
// * The x origin of this BoundingBox.
// */
// public int x;
//
// /**
// * The y origin of this BoundingBox.
// */
// public int y;
//
// /**
// * The width of this BoundingBox.
// */
// public int width;
//
// /**
// * The height of this BoundingBox.
// */
// public int height;
//
// /**
// * The bounds of this BoundingBox.
// */
// public Rectangle bounds;
//
// /**
// * Initialize the BoundingBox.
// * @param x The x origin to initialize this BoundingBox with.
// * @param y The y origin to initialize this BoundingBox with.
// * @param width The width to initialize this BoundingBox with.
// * @param height The height to initialize this BoundingBox with.
// */
// public BoundingBox(int x, int y, int width, int height) {
// this.x = x;
// this.y = y;
// this.width = width;
// this.height = height;
//
// this.bounds = new Rectangle(x, y, width, height);
// }
//
// /**
// * Set the values of this BoundingBox.
// * @param x The x origin to set.
// * @param y The y origin to set.
// * @param width The width to set.
// * @param height The height to set.
// */
// public void update(int x, int y, int width, int height) {
// this.x = x;
// this.y = y;
// this.width = width;
// this.height = height;
//
// bounds.setBounds(x, y, width, height);
// }
//
// /**
// * Return if the current BoundingBox intersects with another.
// * @param box The other BoundingBox to check against.
// * @return True if the passed in BoundingBox intersects with this one,
// * otherwise false.
// */
// public boolean doesIntersect(BoundingBox box) {
// return bounds.intersects(box.bounds);
// }
// }
|
import com.lunar.collision.BoundingBox;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
|
*/
public boolean isPassable() {
return properties.isPassable;
}
/**
* Set if this tile is passable or not.
*/
public void setPassable(boolean passable) {
properties.setPassable(passable);
}
public TileProperties getProperties() {
return properties;
}
public void setProperties(TileProperties properties) {
this.properties = properties;
}
/**
* Draw the tile.
*/
public void drawTile(Graphics graphics, int x, int y) {
graphics.drawImage(texture, x, y, null);
}
/**
* Create a boundingBox that represents this tile.
*/
|
// Path: src/main/java/com/lunar/collision/BoundingBox.java
// public class BoundingBox {
//
// /**
// * The x origin of this BoundingBox.
// */
// public int x;
//
// /**
// * The y origin of this BoundingBox.
// */
// public int y;
//
// /**
// * The width of this BoundingBox.
// */
// public int width;
//
// /**
// * The height of this BoundingBox.
// */
// public int height;
//
// /**
// * The bounds of this BoundingBox.
// */
// public Rectangle bounds;
//
// /**
// * Initialize the BoundingBox.
// * @param x The x origin to initialize this BoundingBox with.
// * @param y The y origin to initialize this BoundingBox with.
// * @param width The width to initialize this BoundingBox with.
// * @param height The height to initialize this BoundingBox with.
// */
// public BoundingBox(int x, int y, int width, int height) {
// this.x = x;
// this.y = y;
// this.width = width;
// this.height = height;
//
// this.bounds = new Rectangle(x, y, width, height);
// }
//
// /**
// * Set the values of this BoundingBox.
// * @param x The x origin to set.
// * @param y The y origin to set.
// * @param width The width to set.
// * @param height The height to set.
// */
// public void update(int x, int y, int width, int height) {
// this.x = x;
// this.y = y;
// this.width = width;
// this.height = height;
//
// bounds.setBounds(x, y, width, height);
// }
//
// /**
// * Return if the current BoundingBox intersects with another.
// * @param box The other BoundingBox to check against.
// * @return True if the passed in BoundingBox intersects with this one,
// * otherwise false.
// */
// public boolean doesIntersect(BoundingBox box) {
// return bounds.intersects(box.bounds);
// }
// }
// Path: src/main/java/com/lunar/tile/Tile.java
import com.lunar.collision.BoundingBox;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
*/
public boolean isPassable() {
return properties.isPassable;
}
/**
* Set if this tile is passable or not.
*/
public void setPassable(boolean passable) {
properties.setPassable(passable);
}
public TileProperties getProperties() {
return properties;
}
public void setProperties(TileProperties properties) {
this.properties = properties;
}
/**
* Draw the tile.
*/
public void drawTile(Graphics graphics, int x, int y) {
graphics.drawImage(texture, x, y, null);
}
/**
* Create a boundingBox that represents this tile.
*/
|
public BoundingBox createBounds(int cX, int cY) {
|
Vrekt/Lunar
|
src/main/java/com/lunar/input/InputListener.java
|
// Path: src/main/java/com/lunar/utilities/Logger.java
// public class Logger {
//
// /**
// * Log information.
// *
// * @param information the information.
// */
// public static void logInformation(String information) {
// System.out.println("[INFO] " + information);
// }
//
// /**
// * Log an error.
// *
// * @param error the error
// */
// public static void logError(String error) {
// System.out.println("[ERROR] " + error);
// }
//
// /**
// * Log a warning
// *
// * @param warning the warning
// */
// public static void logWarning(String warning) {
// System.out.println("[WARNING] " + warning);
// }
//
// /**
// * Log a critical message.
// *
// * @param critical the critical message.
// */
// public static void logCritical(String critical) {
// System.out.println("[CRITICAL] " + critical);
// }
//
// }
|
import com.lunar.utilities.Logger;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Map;
|
package com.lunar.input;
public class InputListener implements KeyListener {
private static boolean keyData[] = new boolean[256];
private static final KeyDuration KEY_TIMES = new KeyDuration();
/**
* Return if the key is down.
*/
public static boolean isKeyDown(int key) {
if (key > keyData.length) {
|
// Path: src/main/java/com/lunar/utilities/Logger.java
// public class Logger {
//
// /**
// * Log information.
// *
// * @param information the information.
// */
// public static void logInformation(String information) {
// System.out.println("[INFO] " + information);
// }
//
// /**
// * Log an error.
// *
// * @param error the error
// */
// public static void logError(String error) {
// System.out.println("[ERROR] " + error);
// }
//
// /**
// * Log a warning
// *
// * @param warning the warning
// */
// public static void logWarning(String warning) {
// System.out.println("[WARNING] " + warning);
// }
//
// /**
// * Log a critical message.
// *
// * @param critical the critical message.
// */
// public static void logCritical(String critical) {
// System.out.println("[CRITICAL] " + critical);
// }
//
// }
// Path: src/main/java/com/lunar/input/InputListener.java
import com.lunar.utilities.Logger;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Map;
package com.lunar.input;
public class InputListener implements KeyListener {
private static boolean keyData[] = new boolean[256];
private static final KeyDuration KEY_TIMES = new KeyDuration();
/**
* Return if the key is down.
*/
public static boolean isKeyDown(int key) {
if (key > keyData.length) {
|
Logger.logWarning("Key " + key + " too big for the 256 array size.");
|
meltzow/tonegodgui
|
src/tonegod/gui/controls/extras/emitter/SpriteInfluencer.java
|
// Path: src/tonegod/gui/controls/extras/emitter/ElementEmitter.java
// public class ElementParticle {
// public QuadData particle;
// public Vector2f initialPosition = new Vector2f();
// public Vector2f position = new Vector2f();
// public Vector2f velocity = new Vector2f();
// public float randforce;
// public ColorRGBA color = new ColorRGBA();
// public float size = 1;
// public float life;
// public float startlife;
// public float angle;
// public float rotateSpeed;
// public boolean rotateDir;
// public boolean active = false;
// public float blend;
// private Map<String,Object> data = new HashMap();
// private float diffX, diffY;
//
// public void update(float tpf) {
// life -= tpf;
// blend = (startlife - life) / startlife;
// if (interpolation != null) blend = interpolation.apply(blend);
// if (life <= 0) {
// killParticle();
// return;
// }
//
// for (Influencer inf : influencers.values()) {
// if (inf.getIsEnabled())
// inf.update(this, tpf);
// }
//
// particle.setPosition(position);
// particle.setScaleX(size);
// particle.setScaleY(size);
// particle.getOrigin().set(spriteWidth*0.5f,spriteHeight*0.5f);
// particle.setColor(color);
// particle.setRotation(angle);
// };
//
// public void initialize(boolean hide) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
//
// if (emitterShape != null) {
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// while (tempColor.r < 0.2f) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// }
// }
//
// diffX *= emitterWidth;
// diffY *= emitterHeight;
//
// position.set(emitterPosition);
// position.subtractLocal(spriteWidth*0.5f,spriteHeight*0.5f);
// position.addLocal(diffX,diffY);
// initialPosition.set(position);
//
// if (!useFixedForce)
// randforce = (FastMath.nextRandomFloat()*(maxforce-minforce))+minforce;
// else
// randforce = maxforce;
//
// if (!centerVelocity) {
// float velX = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velX = -velX;
// float velY = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velY = -velY;
// velocity.set(velX,velY);
// } else {
// velocity.set(1/emitterWidth*diffX, 1/emitterHeight*diffY);
// velocity.subtractLocal(0.5f,0.5f);
// }
//
// if (useFixedDirection)
// velocity.interpolate(fixedDirection, fixedDirectionStrength);
//
// velocity.multLocal(randforce);
//
// if (useFixedLife)
// life = highLife;
// else {
// startlife = (highLife - lowLife) * FastMath.nextRandomFloat() + lowLife ;
// life = startlife;
// }
// rotateDir = FastMath.rand.nextBoolean();
// rotateSpeed = FastMath.rand.nextFloat();
// size = 1;
//
// for (Influencer inf : influencers.values()) {
// inf.initialize(this);
// }
//
// active = !hide;
// if (hide) particle.hide();
// else particle.show();
// update(0);
// }
//
// public void killParticle() {
// active = false;
// activeParticleCount--;
// particle.hide();
// }
//
// public void putData(String key, Object object) {
// data.put(key, object);
// }
//
// public Object getData(String key) {
// return data.get(key);
// }
// }
|
import tonegod.gui.framework.core.AnimElement;
import tonegod.gui.framework.core.TextureRegion;
import com.jme3.math.FastMath;
import tonegod.gui.controls.extras.emitter.ElementEmitter.ElementParticle;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.controls.extras.emitter;
/**
*
* @author t0neg0d
*/
public class SpriteInfluencer extends InfluencerBase {
public static enum AnimOrder {
SequentialAll,
SequentialAllOverLife,
SequentialDefinedOrder,
SequentialDefinedOrderOverLife,
RandomAll,
RandomAllOverLife,
RandomDefinedOrder,
RandomDefinedOrderOverLife,
SingleImage
}
private boolean isEnabled = true;
private boolean randomStartImage = false;
private AnimOrder animOrder = AnimOrder.SingleImage;
private boolean spriteOrderSet = false;
private int[] spriteOrder = new int[] { 0 };
private int currentIndex = 0;
private float targetInterval = 1f;
private float currentInterval = 0f;
private float fps = 4f;
public SpriteInfluencer(ElementEmitter emitter) {
super(emitter);
}
@Override
|
// Path: src/tonegod/gui/controls/extras/emitter/ElementEmitter.java
// public class ElementParticle {
// public QuadData particle;
// public Vector2f initialPosition = new Vector2f();
// public Vector2f position = new Vector2f();
// public Vector2f velocity = new Vector2f();
// public float randforce;
// public ColorRGBA color = new ColorRGBA();
// public float size = 1;
// public float life;
// public float startlife;
// public float angle;
// public float rotateSpeed;
// public boolean rotateDir;
// public boolean active = false;
// public float blend;
// private Map<String,Object> data = new HashMap();
// private float diffX, diffY;
//
// public void update(float tpf) {
// life -= tpf;
// blend = (startlife - life) / startlife;
// if (interpolation != null) blend = interpolation.apply(blend);
// if (life <= 0) {
// killParticle();
// return;
// }
//
// for (Influencer inf : influencers.values()) {
// if (inf.getIsEnabled())
// inf.update(this, tpf);
// }
//
// particle.setPosition(position);
// particle.setScaleX(size);
// particle.setScaleY(size);
// particle.getOrigin().set(spriteWidth*0.5f,spriteHeight*0.5f);
// particle.setColor(color);
// particle.setRotation(angle);
// };
//
// public void initialize(boolean hide) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
//
// if (emitterShape != null) {
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// while (tempColor.r < 0.2f) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// }
// }
//
// diffX *= emitterWidth;
// diffY *= emitterHeight;
//
// position.set(emitterPosition);
// position.subtractLocal(spriteWidth*0.5f,spriteHeight*0.5f);
// position.addLocal(diffX,diffY);
// initialPosition.set(position);
//
// if (!useFixedForce)
// randforce = (FastMath.nextRandomFloat()*(maxforce-minforce))+minforce;
// else
// randforce = maxforce;
//
// if (!centerVelocity) {
// float velX = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velX = -velX;
// float velY = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velY = -velY;
// velocity.set(velX,velY);
// } else {
// velocity.set(1/emitterWidth*diffX, 1/emitterHeight*diffY);
// velocity.subtractLocal(0.5f,0.5f);
// }
//
// if (useFixedDirection)
// velocity.interpolate(fixedDirection, fixedDirectionStrength);
//
// velocity.multLocal(randforce);
//
// if (useFixedLife)
// life = highLife;
// else {
// startlife = (highLife - lowLife) * FastMath.nextRandomFloat() + lowLife ;
// life = startlife;
// }
// rotateDir = FastMath.rand.nextBoolean();
// rotateSpeed = FastMath.rand.nextFloat();
// size = 1;
//
// for (Influencer inf : influencers.values()) {
// inf.initialize(this);
// }
//
// active = !hide;
// if (hide) particle.hide();
// else particle.show();
// update(0);
// }
//
// public void killParticle() {
// active = false;
// activeParticleCount--;
// particle.hide();
// }
//
// public void putData(String key, Object object) {
// data.put(key, object);
// }
//
// public Object getData(String key) {
// return data.get(key);
// }
// }
// Path: src/tonegod/gui/controls/extras/emitter/SpriteInfluencer.java
import tonegod.gui.framework.core.AnimElement;
import tonegod.gui.framework.core.TextureRegion;
import com.jme3.math.FastMath;
import tonegod.gui.controls.extras.emitter.ElementEmitter.ElementParticle;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.controls.extras.emitter;
/**
*
* @author t0neg0d
*/
public class SpriteInfluencer extends InfluencerBase {
public static enum AnimOrder {
SequentialAll,
SequentialAllOverLife,
SequentialDefinedOrder,
SequentialDefinedOrderOverLife,
RandomAll,
RandomAllOverLife,
RandomDefinedOrder,
RandomDefinedOrderOverLife,
SingleImage
}
private boolean isEnabled = true;
private boolean randomStartImage = false;
private AnimOrder animOrder = AnimOrder.SingleImage;
private boolean spriteOrderSet = false;
private int[] spriteOrder = new int[] { 0 };
private int currentIndex = 0;
private float targetInterval = 1f;
private float currentInterval = 0f;
private float fps = 4f;
public SpriteInfluencer(ElementEmitter emitter) {
super(emitter);
}
@Override
|
public void update(ElementParticle particle, float tpf) {
|
meltzow/tonegodgui
|
src/tonegod/gui/controls/extras/emitter/DirectionInfluencer.java
|
// Path: src/tonegod/gui/controls/extras/emitter/ElementEmitter.java
// public class ElementParticle {
// public QuadData particle;
// public Vector2f initialPosition = new Vector2f();
// public Vector2f position = new Vector2f();
// public Vector2f velocity = new Vector2f();
// public float randforce;
// public ColorRGBA color = new ColorRGBA();
// public float size = 1;
// public float life;
// public float startlife;
// public float angle;
// public float rotateSpeed;
// public boolean rotateDir;
// public boolean active = false;
// public float blend;
// private Map<String,Object> data = new HashMap();
// private float diffX, diffY;
//
// public void update(float tpf) {
// life -= tpf;
// blend = (startlife - life) / startlife;
// if (interpolation != null) blend = interpolation.apply(blend);
// if (life <= 0) {
// killParticle();
// return;
// }
//
// for (Influencer inf : influencers.values()) {
// if (inf.getIsEnabled())
// inf.update(this, tpf);
// }
//
// particle.setPosition(position);
// particle.setScaleX(size);
// particle.setScaleY(size);
// particle.getOrigin().set(spriteWidth*0.5f,spriteHeight*0.5f);
// particle.setColor(color);
// particle.setRotation(angle);
// };
//
// public void initialize(boolean hide) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
//
// if (emitterShape != null) {
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// while (tempColor.r < 0.2f) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// }
// }
//
// diffX *= emitterWidth;
// diffY *= emitterHeight;
//
// position.set(emitterPosition);
// position.subtractLocal(spriteWidth*0.5f,spriteHeight*0.5f);
// position.addLocal(diffX,diffY);
// initialPosition.set(position);
//
// if (!useFixedForce)
// randforce = (FastMath.nextRandomFloat()*(maxforce-minforce))+minforce;
// else
// randforce = maxforce;
//
// if (!centerVelocity) {
// float velX = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velX = -velX;
// float velY = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velY = -velY;
// velocity.set(velX,velY);
// } else {
// velocity.set(1/emitterWidth*diffX, 1/emitterHeight*diffY);
// velocity.subtractLocal(0.5f,0.5f);
// }
//
// if (useFixedDirection)
// velocity.interpolate(fixedDirection, fixedDirectionStrength);
//
// velocity.multLocal(randforce);
//
// if (useFixedLife)
// life = highLife;
// else {
// startlife = (highLife - lowLife) * FastMath.nextRandomFloat() + lowLife ;
// life = startlife;
// }
// rotateDir = FastMath.rand.nextBoolean();
// rotateSpeed = FastMath.rand.nextFloat();
// size = 1;
//
// for (Influencer inf : influencers.values()) {
// inf.initialize(this);
// }
//
// active = !hide;
// if (hide) particle.hide();
// else particle.show();
// update(0);
// }
//
// public void killParticle() {
// active = false;
// activeParticleCount--;
// particle.hide();
// }
//
// public void putData(String key, Object object) {
// data.put(key, object);
// }
//
// public Object getData(String key) {
// return data.get(key);
// }
// }
|
import com.jme3.math.Vector2f;
import tonegod.gui.controls.extras.emitter.ElementEmitter.ElementParticle;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.controls.extras.emitter;
/**
*
* @author t0neg0d
*/
public class DirectionInfluencer extends InfluencerBase {
private boolean isEnabled = true;
private Vector2f direction = Vector2f.ZERO.clone();
private Vector2f temp = new Vector2f();
private float strength = 1;
public DirectionInfluencer(ElementEmitter emitter) {
super(emitter);
}
@Override
|
// Path: src/tonegod/gui/controls/extras/emitter/ElementEmitter.java
// public class ElementParticle {
// public QuadData particle;
// public Vector2f initialPosition = new Vector2f();
// public Vector2f position = new Vector2f();
// public Vector2f velocity = new Vector2f();
// public float randforce;
// public ColorRGBA color = new ColorRGBA();
// public float size = 1;
// public float life;
// public float startlife;
// public float angle;
// public float rotateSpeed;
// public boolean rotateDir;
// public boolean active = false;
// public float blend;
// private Map<String,Object> data = new HashMap();
// private float diffX, diffY;
//
// public void update(float tpf) {
// life -= tpf;
// blend = (startlife - life) / startlife;
// if (interpolation != null) blend = interpolation.apply(blend);
// if (life <= 0) {
// killParticle();
// return;
// }
//
// for (Influencer inf : influencers.values()) {
// if (inf.getIsEnabled())
// inf.update(this, tpf);
// }
//
// particle.setPosition(position);
// particle.setScaleX(size);
// particle.setScaleY(size);
// particle.getOrigin().set(spriteWidth*0.5f,spriteHeight*0.5f);
// particle.setColor(color);
// particle.setRotation(angle);
// };
//
// public void initialize(boolean hide) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
//
// if (emitterShape != null) {
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// while (tempColor.r < 0.2f) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// }
// }
//
// diffX *= emitterWidth;
// diffY *= emitterHeight;
//
// position.set(emitterPosition);
// position.subtractLocal(spriteWidth*0.5f,spriteHeight*0.5f);
// position.addLocal(diffX,diffY);
// initialPosition.set(position);
//
// if (!useFixedForce)
// randforce = (FastMath.nextRandomFloat()*(maxforce-minforce))+minforce;
// else
// randforce = maxforce;
//
// if (!centerVelocity) {
// float velX = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velX = -velX;
// float velY = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velY = -velY;
// velocity.set(velX,velY);
// } else {
// velocity.set(1/emitterWidth*diffX, 1/emitterHeight*diffY);
// velocity.subtractLocal(0.5f,0.5f);
// }
//
// if (useFixedDirection)
// velocity.interpolate(fixedDirection, fixedDirectionStrength);
//
// velocity.multLocal(randforce);
//
// if (useFixedLife)
// life = highLife;
// else {
// startlife = (highLife - lowLife) * FastMath.nextRandomFloat() + lowLife ;
// life = startlife;
// }
// rotateDir = FastMath.rand.nextBoolean();
// rotateSpeed = FastMath.rand.nextFloat();
// size = 1;
//
// for (Influencer inf : influencers.values()) {
// inf.initialize(this);
// }
//
// active = !hide;
// if (hide) particle.hide();
// else particle.show();
// update(0);
// }
//
// public void killParticle() {
// active = false;
// activeParticleCount--;
// particle.hide();
// }
//
// public void putData(String key, Object object) {
// data.put(key, object);
// }
//
// public Object getData(String key) {
// return data.get(key);
// }
// }
// Path: src/tonegod/gui/controls/extras/emitter/DirectionInfluencer.java
import com.jme3.math.Vector2f;
import tonegod.gui.controls.extras.emitter.ElementEmitter.ElementParticle;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.controls.extras.emitter;
/**
*
* @author t0neg0d
*/
public class DirectionInfluencer extends InfluencerBase {
private boolean isEnabled = true;
private Vector2f direction = Vector2f.ZERO.clone();
private Vector2f temp = new Vector2f();
private float strength = 1;
public DirectionInfluencer(ElementEmitter emitter) {
super(emitter);
}
@Override
|
public void update(ElementParticle p, float tpf) {
|
meltzow/tonegodgui
|
src/tonegod/gui/controls/extras/emitter/AlphaInfluencer.java
|
// Path: src/tonegod/gui/controls/extras/emitter/ElementEmitter.java
// public class ElementParticle {
// public QuadData particle;
// public Vector2f initialPosition = new Vector2f();
// public Vector2f position = new Vector2f();
// public Vector2f velocity = new Vector2f();
// public float randforce;
// public ColorRGBA color = new ColorRGBA();
// public float size = 1;
// public float life;
// public float startlife;
// public float angle;
// public float rotateSpeed;
// public boolean rotateDir;
// public boolean active = false;
// public float blend;
// private Map<String,Object> data = new HashMap();
// private float diffX, diffY;
//
// public void update(float tpf) {
// life -= tpf;
// blend = (startlife - life) / startlife;
// if (interpolation != null) blend = interpolation.apply(blend);
// if (life <= 0) {
// killParticle();
// return;
// }
//
// for (Influencer inf : influencers.values()) {
// if (inf.getIsEnabled())
// inf.update(this, tpf);
// }
//
// particle.setPosition(position);
// particle.setScaleX(size);
// particle.setScaleY(size);
// particle.getOrigin().set(spriteWidth*0.5f,spriteHeight*0.5f);
// particle.setColor(color);
// particle.setRotation(angle);
// };
//
// public void initialize(boolean hide) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
//
// if (emitterShape != null) {
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// while (tempColor.r < 0.2f) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// }
// }
//
// diffX *= emitterWidth;
// diffY *= emitterHeight;
//
// position.set(emitterPosition);
// position.subtractLocal(spriteWidth*0.5f,spriteHeight*0.5f);
// position.addLocal(diffX,diffY);
// initialPosition.set(position);
//
// if (!useFixedForce)
// randforce = (FastMath.nextRandomFloat()*(maxforce-minforce))+minforce;
// else
// randforce = maxforce;
//
// if (!centerVelocity) {
// float velX = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velX = -velX;
// float velY = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velY = -velY;
// velocity.set(velX,velY);
// } else {
// velocity.set(1/emitterWidth*diffX, 1/emitterHeight*diffY);
// velocity.subtractLocal(0.5f,0.5f);
// }
//
// if (useFixedDirection)
// velocity.interpolate(fixedDirection, fixedDirectionStrength);
//
// velocity.multLocal(randforce);
//
// if (useFixedLife)
// life = highLife;
// else {
// startlife = (highLife - lowLife) * FastMath.nextRandomFloat() + lowLife ;
// life = startlife;
// }
// rotateDir = FastMath.rand.nextBoolean();
// rotateSpeed = FastMath.rand.nextFloat();
// size = 1;
//
// for (Influencer inf : influencers.values()) {
// inf.initialize(this);
// }
//
// active = !hide;
// if (hide) particle.hide();
// else particle.show();
// update(0);
// }
//
// public void killParticle() {
// active = false;
// activeParticleCount--;
// particle.hide();
// }
//
// public void putData(String key, Object object) {
// data.put(key, object);
// }
//
// public Object getData(String key) {
// return data.get(key);
// }
// }
|
import tonegod.gui.framework.animation.Interpolation;
import com.jme3.math.Vector2f;
import tonegod.gui.controls.extras.emitter.ElementEmitter.ElementParticle;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.controls.extras.emitter;
/**
*
* @author t0neg0d
*/
public class AlphaInfluencer extends InfluencerBase {
private boolean isEnabled = true;
private float startAlpha = 1.0f;
private float endAlpha = 0.01f;
private Interpolation interpolation = Interpolation.linear;
private Vector2f tempV2a = new Vector2f();
private Vector2f tempV2b = new Vector2f();
public AlphaInfluencer(ElementEmitter emitter) {
super(emitter);
}
@Override
|
// Path: src/tonegod/gui/controls/extras/emitter/ElementEmitter.java
// public class ElementParticle {
// public QuadData particle;
// public Vector2f initialPosition = new Vector2f();
// public Vector2f position = new Vector2f();
// public Vector2f velocity = new Vector2f();
// public float randforce;
// public ColorRGBA color = new ColorRGBA();
// public float size = 1;
// public float life;
// public float startlife;
// public float angle;
// public float rotateSpeed;
// public boolean rotateDir;
// public boolean active = false;
// public float blend;
// private Map<String,Object> data = new HashMap();
// private float diffX, diffY;
//
// public void update(float tpf) {
// life -= tpf;
// blend = (startlife - life) / startlife;
// if (interpolation != null) blend = interpolation.apply(blend);
// if (life <= 0) {
// killParticle();
// return;
// }
//
// for (Influencer inf : influencers.values()) {
// if (inf.getIsEnabled())
// inf.update(this, tpf);
// }
//
// particle.setPosition(position);
// particle.setScaleX(size);
// particle.setScaleY(size);
// particle.getOrigin().set(spriteWidth*0.5f,spriteHeight*0.5f);
// particle.setColor(color);
// particle.setRotation(angle);
// };
//
// public void initialize(boolean hide) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
//
// if (emitterShape != null) {
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// while (tempColor.r < 0.2f) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// }
// }
//
// diffX *= emitterWidth;
// diffY *= emitterHeight;
//
// position.set(emitterPosition);
// position.subtractLocal(spriteWidth*0.5f,spriteHeight*0.5f);
// position.addLocal(diffX,diffY);
// initialPosition.set(position);
//
// if (!useFixedForce)
// randforce = (FastMath.nextRandomFloat()*(maxforce-minforce))+minforce;
// else
// randforce = maxforce;
//
// if (!centerVelocity) {
// float velX = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velX = -velX;
// float velY = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velY = -velY;
// velocity.set(velX,velY);
// } else {
// velocity.set(1/emitterWidth*diffX, 1/emitterHeight*diffY);
// velocity.subtractLocal(0.5f,0.5f);
// }
//
// if (useFixedDirection)
// velocity.interpolate(fixedDirection, fixedDirectionStrength);
//
// velocity.multLocal(randforce);
//
// if (useFixedLife)
// life = highLife;
// else {
// startlife = (highLife - lowLife) * FastMath.nextRandomFloat() + lowLife ;
// life = startlife;
// }
// rotateDir = FastMath.rand.nextBoolean();
// rotateSpeed = FastMath.rand.nextFloat();
// size = 1;
//
// for (Influencer inf : influencers.values()) {
// inf.initialize(this);
// }
//
// active = !hide;
// if (hide) particle.hide();
// else particle.show();
// update(0);
// }
//
// public void killParticle() {
// active = false;
// activeParticleCount--;
// particle.hide();
// }
//
// public void putData(String key, Object object) {
// data.put(key, object);
// }
//
// public Object getData(String key) {
// return data.get(key);
// }
// }
// Path: src/tonegod/gui/controls/extras/emitter/AlphaInfluencer.java
import tonegod.gui.framework.animation.Interpolation;
import com.jme3.math.Vector2f;
import tonegod.gui.controls.extras.emitter.ElementEmitter.ElementParticle;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.controls.extras.emitter;
/**
*
* @author t0neg0d
*/
public class AlphaInfluencer extends InfluencerBase {
private boolean isEnabled = true;
private float startAlpha = 1.0f;
private float endAlpha = 0.01f;
private Interpolation interpolation = Interpolation.linear;
private Vector2f tempV2a = new Vector2f();
private Vector2f tempV2b = new Vector2f();
public AlphaInfluencer(ElementEmitter emitter) {
super(emitter);
}
@Override
|
public void update(ElementParticle particle, float tpf) {
|
meltzow/tonegodgui
|
src/tonegod/gui/controls/extras/emitter/DestinationInfluencer.java
|
// Path: src/tonegod/gui/controls/extras/emitter/ElementEmitter.java
// public class ElementParticle {
// public QuadData particle;
// public Vector2f initialPosition = new Vector2f();
// public Vector2f position = new Vector2f();
// public Vector2f velocity = new Vector2f();
// public float randforce;
// public ColorRGBA color = new ColorRGBA();
// public float size = 1;
// public float life;
// public float startlife;
// public float angle;
// public float rotateSpeed;
// public boolean rotateDir;
// public boolean active = false;
// public float blend;
// private Map<String,Object> data = new HashMap();
// private float diffX, diffY;
//
// public void update(float tpf) {
// life -= tpf;
// blend = (startlife - life) / startlife;
// if (interpolation != null) blend = interpolation.apply(blend);
// if (life <= 0) {
// killParticle();
// return;
// }
//
// for (Influencer inf : influencers.values()) {
// if (inf.getIsEnabled())
// inf.update(this, tpf);
// }
//
// particle.setPosition(position);
// particle.setScaleX(size);
// particle.setScaleY(size);
// particle.getOrigin().set(spriteWidth*0.5f,spriteHeight*0.5f);
// particle.setColor(color);
// particle.setRotation(angle);
// };
//
// public void initialize(boolean hide) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
//
// if (emitterShape != null) {
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// while (tempColor.r < 0.2f) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// }
// }
//
// diffX *= emitterWidth;
// diffY *= emitterHeight;
//
// position.set(emitterPosition);
// position.subtractLocal(spriteWidth*0.5f,spriteHeight*0.5f);
// position.addLocal(diffX,diffY);
// initialPosition.set(position);
//
// if (!useFixedForce)
// randforce = (FastMath.nextRandomFloat()*(maxforce-minforce))+minforce;
// else
// randforce = maxforce;
//
// if (!centerVelocity) {
// float velX = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velX = -velX;
// float velY = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velY = -velY;
// velocity.set(velX,velY);
// } else {
// velocity.set(1/emitterWidth*diffX, 1/emitterHeight*diffY);
// velocity.subtractLocal(0.5f,0.5f);
// }
//
// if (useFixedDirection)
// velocity.interpolate(fixedDirection, fixedDirectionStrength);
//
// velocity.multLocal(randforce);
//
// if (useFixedLife)
// life = highLife;
// else {
// startlife = (highLife - lowLife) * FastMath.nextRandomFloat() + lowLife ;
// life = startlife;
// }
// rotateDir = FastMath.rand.nextBoolean();
// rotateSpeed = FastMath.rand.nextFloat();
// size = 1;
//
// for (Influencer inf : influencers.values()) {
// inf.initialize(this);
// }
//
// active = !hide;
// if (hide) particle.hide();
// else particle.show();
// update(0);
// }
//
// public void killParticle() {
// active = false;
// activeParticleCount--;
// particle.hide();
// }
//
// public void putData(String key, Object object) {
// data.put(key, object);
// }
//
// public Object getData(String key) {
// return data.get(key);
// }
// }
|
import com.jme3.math.Vector2f;
import tonegod.gui.controls.extras.emitter.ElementEmitter.ElementParticle;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.controls.extras.emitter;
/**
*
* @author t0neg0d
*/
public class DestinationInfluencer extends InfluencerBase {
private boolean isEnabled = true;
private Vector2f destination = Vector2f.ZERO.clone();
private Vector2f temp = new Vector2f();
private Vector2f temp2 = new Vector2f();
private float strength = .25f;
public DestinationInfluencer(ElementEmitter emitter) {
super(emitter);
}
@Override
|
// Path: src/tonegod/gui/controls/extras/emitter/ElementEmitter.java
// public class ElementParticle {
// public QuadData particle;
// public Vector2f initialPosition = new Vector2f();
// public Vector2f position = new Vector2f();
// public Vector2f velocity = new Vector2f();
// public float randforce;
// public ColorRGBA color = new ColorRGBA();
// public float size = 1;
// public float life;
// public float startlife;
// public float angle;
// public float rotateSpeed;
// public boolean rotateDir;
// public boolean active = false;
// public float blend;
// private Map<String,Object> data = new HashMap();
// private float diffX, diffY;
//
// public void update(float tpf) {
// life -= tpf;
// blend = (startlife - life) / startlife;
// if (interpolation != null) blend = interpolation.apply(blend);
// if (life <= 0) {
// killParticle();
// return;
// }
//
// for (Influencer inf : influencers.values()) {
// if (inf.getIsEnabled())
// inf.update(this, tpf);
// }
//
// particle.setPosition(position);
// particle.setScaleX(size);
// particle.setScaleY(size);
// particle.getOrigin().set(spriteWidth*0.5f,spriteHeight*0.5f);
// particle.setColor(color);
// particle.setRotation(angle);
// };
//
// public void initialize(boolean hide) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
//
// if (emitterShape != null) {
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// while (tempColor.r < 0.2f) {
// diffX = FastMath.rand.nextFloat();
// diffY = FastMath.rand.nextFloat();
// ir.getPixel((int)(diffX*(emitterShape.getImage().getWidth())),(int)(diffY*(emitterShape.getImage().getHeight())), tempColor);
// }
// }
//
// diffX *= emitterWidth;
// diffY *= emitterHeight;
//
// position.set(emitterPosition);
// position.subtractLocal(spriteWidth*0.5f,spriteHeight*0.5f);
// position.addLocal(diffX,diffY);
// initialPosition.set(position);
//
// if (!useFixedForce)
// randforce = (FastMath.nextRandomFloat()*(maxforce-minforce))+minforce;
// else
// randforce = maxforce;
//
// if (!centerVelocity) {
// float velX = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velX = -velX;
// float velY = FastMath.rand.nextFloat();
// if (FastMath.rand.nextBoolean()) velY = -velY;
// velocity.set(velX,velY);
// } else {
// velocity.set(1/emitterWidth*diffX, 1/emitterHeight*diffY);
// velocity.subtractLocal(0.5f,0.5f);
// }
//
// if (useFixedDirection)
// velocity.interpolate(fixedDirection, fixedDirectionStrength);
//
// velocity.multLocal(randforce);
//
// if (useFixedLife)
// life = highLife;
// else {
// startlife = (highLife - lowLife) * FastMath.nextRandomFloat() + lowLife ;
// life = startlife;
// }
// rotateDir = FastMath.rand.nextBoolean();
// rotateSpeed = FastMath.rand.nextFloat();
// size = 1;
//
// for (Influencer inf : influencers.values()) {
// inf.initialize(this);
// }
//
// active = !hide;
// if (hide) particle.hide();
// else particle.show();
// update(0);
// }
//
// public void killParticle() {
// active = false;
// activeParticleCount--;
// particle.hide();
// }
//
// public void putData(String key, Object object) {
// data.put(key, object);
// }
//
// public Object getData(String key) {
// return data.get(key);
// }
// }
// Path: src/tonegod/gui/controls/extras/emitter/DestinationInfluencer.java
import com.jme3.math.Vector2f;
import tonegod.gui.controls.extras.emitter.ElementEmitter.ElementParticle;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.controls.extras.emitter;
/**
*
* @author t0neg0d
*/
public class DestinationInfluencer extends InfluencerBase {
private boolean isEnabled = true;
private Vector2f destination = Vector2f.ZERO.clone();
private Vector2f temp = new Vector2f();
private Vector2f temp2 = new Vector2f();
private float strength = .25f;
public DestinationInfluencer(ElementEmitter emitter) {
super(emitter);
}
@Override
|
public void update(ElementParticle p, float tpf) {
|
jenkinsci/google-storage-plugin
|
src/main/java/com/google/jenkins/plugins/storage/reports/BuildGcsUploadReport.java
|
// Path: src/main/java/com/google/jenkins/plugins/storage/util/BucketPath.java
// public class BucketPath implements Serializable {
// private final String bucket;
// private final String object;
//
// /**
// * Prepares a new BucketPath.
// *
// * @param uri path to the bucket object, of the form "gs://bucket_name/path/to/object". May
// * contain other characters (i.e., *), no verification is done in this class.
// */
// public BucketPath(String uri) throws IllegalArgumentException {
// // Ensure the uri starts with "gs://"
// if (!uri.startsWith(GCS_SCHEME)) {
// throw new IllegalArgumentException(
// Messages.AbstractUploadDescriptor_BadPrefix(uri, GCS_SCHEME));
// }
//
// // Lop off the GCS_SCHEME prefix.
// uri = uri.substring(GCS_SCHEME.length());
//
// // Break things down to a compatible format:
// // foo / bar / baz / blah.log
// // ^---^ ^--------------------^
// // bucket storage-object
// //
// // TODO(mattmoor): Test objectPrefix on Windows, where '\' != '/'
// // Must we translate? Can we require them to specify in unix-style
// // and still have things work?
// String[] halves = uri.split("/", 2);
// this.bucket = halves[0];
// this.object = (halves.length == 1) ? "" : halves[1];
// }
//
// /**
// * Initializes BucketPath directly, with no parsing or substitutions.
// *
// * @param bucket The bucket portion of the URI.
// * @param object The path to the object portion of the URI not including bucket.
// */
// public BucketPath(String bucket, String object) {
// this.bucket = bucket;
// this.object = object;
// }
//
// /**
// * Determines if this is an invalid {@link BucketPath}.
// *
// * @return False if the bucket is empty.
// */
// public boolean error() {
// // The bucket cannot be empty under normal circumstances.
// return getBucket().length() <= 0;
// }
//
// /** @return Regenerate the path (without gs:// prefix) */
// public String getPath() {
// return bucket + (object.isEmpty() ? "" : "/" + object);
// }
//
// /** @return The Bucket portion of the URI */
// public String getBucket() {
// return bucket;
// }
//
// /** @return The object portion of the URI */
// public String getObject() {
// return object;
// }
// }
|
import com.google.api.client.util.Sets;
import com.google.jenkins.plugins.storage.util.BucketPath;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Run;
import java.util.Collections;
import java.util.Set;
import javax.annotation.Nullable;
|
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage.reports;
/**
* A build {@link hudson.model.Action} to surface direct links of objects uploaded through the
* {@link com.google.jenkins.plugins.storage.StdoutUpload} Listener to the Jenkins UI.
*/
public class BuildGcsUploadReport extends AbstractGcsUploadReport {
private final Set<String> buckets;
private final Set<String> files;
public BuildGcsUploadReport(Run<?, ?> run) {
super(run);
this.buckets = Sets.newHashSet();
this.files = Sets.newHashSet();
}
/**
* @param project a project to get {@link BuildGcsUploadReport} for.
* @return the {@link BuildGcsUploadReport} of the last build, as returned by {@link #of(Run)}, or
* null of no build existed.
*/
@Nullable
public static BuildGcsUploadReport of(AbstractProject<?, ?> project) {
// TODO(nghia) : Put more thoughts into whether we want getLastBuild()
// or getLastSuccessfulBuild() here.
//
// Displaying the last build has the advantage that logs for failed builds
// are also easily accessible through these links.
//
// On the other hand, last successful builds have a more complete set of
// links.
//
// May we only display the last build _if_ the project has uploads for
// failed build as well?
AbstractBuild<?, ?> lastBuild = project.getLastBuild();
return lastBuild == null ? null : BuildGcsUploadReport.of(lastBuild);
}
/**
* @param run the run to get {@link BuildGcsUploadReport} for.
* @return the existing {@link BuildGcsUploadReport} of a build. If none, create a new {@link
* BuildGcsUploadReport} and return.
*/
public static synchronized BuildGcsUploadReport of(Run<?, ?> run) {
BuildGcsUploadReport links = run.getAction(BuildGcsUploadReport.class);
if (links != null) {
return links;
}
links = new BuildGcsUploadReport(run);
run.addAction(links);
return links;
}
/** @param bucketName the name of the destination bucket. */
public void addBucket(String bucketName) {
buckets.add(bucketName);
}
/**
* @param relativePath the relative path (to the workspace) of the uploaded file.
* @param bucket the directory location in the cloud
*/
|
// Path: src/main/java/com/google/jenkins/plugins/storage/util/BucketPath.java
// public class BucketPath implements Serializable {
// private final String bucket;
// private final String object;
//
// /**
// * Prepares a new BucketPath.
// *
// * @param uri path to the bucket object, of the form "gs://bucket_name/path/to/object". May
// * contain other characters (i.e., *), no verification is done in this class.
// */
// public BucketPath(String uri) throws IllegalArgumentException {
// // Ensure the uri starts with "gs://"
// if (!uri.startsWith(GCS_SCHEME)) {
// throw new IllegalArgumentException(
// Messages.AbstractUploadDescriptor_BadPrefix(uri, GCS_SCHEME));
// }
//
// // Lop off the GCS_SCHEME prefix.
// uri = uri.substring(GCS_SCHEME.length());
//
// // Break things down to a compatible format:
// // foo / bar / baz / blah.log
// // ^---^ ^--------------------^
// // bucket storage-object
// //
// // TODO(mattmoor): Test objectPrefix on Windows, where '\' != '/'
// // Must we translate? Can we require them to specify in unix-style
// // and still have things work?
// String[] halves = uri.split("/", 2);
// this.bucket = halves[0];
// this.object = (halves.length == 1) ? "" : halves[1];
// }
//
// /**
// * Initializes BucketPath directly, with no parsing or substitutions.
// *
// * @param bucket The bucket portion of the URI.
// * @param object The path to the object portion of the URI not including bucket.
// */
// public BucketPath(String bucket, String object) {
// this.bucket = bucket;
// this.object = object;
// }
//
// /**
// * Determines if this is an invalid {@link BucketPath}.
// *
// * @return False if the bucket is empty.
// */
// public boolean error() {
// // The bucket cannot be empty under normal circumstances.
// return getBucket().length() <= 0;
// }
//
// /** @return Regenerate the path (without gs:// prefix) */
// public String getPath() {
// return bucket + (object.isEmpty() ? "" : "/" + object);
// }
//
// /** @return The Bucket portion of the URI */
// public String getBucket() {
// return bucket;
// }
//
// /** @return The object portion of the URI */
// public String getObject() {
// return object;
// }
// }
// Path: src/main/java/com/google/jenkins/plugins/storage/reports/BuildGcsUploadReport.java
import com.google.api.client.util.Sets;
import com.google.jenkins.plugins.storage.util.BucketPath;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Run;
import java.util.Collections;
import java.util.Set;
import javax.annotation.Nullable;
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage.reports;
/**
* A build {@link hudson.model.Action} to surface direct links of objects uploaded through the
* {@link com.google.jenkins.plugins.storage.StdoutUpload} Listener to the Jenkins UI.
*/
public class BuildGcsUploadReport extends AbstractGcsUploadReport {
private final Set<String> buckets;
private final Set<String> files;
public BuildGcsUploadReport(Run<?, ?> run) {
super(run);
this.buckets = Sets.newHashSet();
this.files = Sets.newHashSet();
}
/**
* @param project a project to get {@link BuildGcsUploadReport} for.
* @return the {@link BuildGcsUploadReport} of the last build, as returned by {@link #of(Run)}, or
* null of no build existed.
*/
@Nullable
public static BuildGcsUploadReport of(AbstractProject<?, ?> project) {
// TODO(nghia) : Put more thoughts into whether we want getLastBuild()
// or getLastSuccessfulBuild() here.
//
// Displaying the last build has the advantage that logs for failed builds
// are also easily accessible through these links.
//
// On the other hand, last successful builds have a more complete set of
// links.
//
// May we only display the last build _if_ the project has uploads for
// failed build as well?
AbstractBuild<?, ?> lastBuild = project.getLastBuild();
return lastBuild == null ? null : BuildGcsUploadReport.of(lastBuild);
}
/**
* @param run the run to get {@link BuildGcsUploadReport} for.
* @return the existing {@link BuildGcsUploadReport} of a build. If none, create a new {@link
* BuildGcsUploadReport} and return.
*/
public static synchronized BuildGcsUploadReport of(Run<?, ?> run) {
BuildGcsUploadReport links = run.getAction(BuildGcsUploadReport.class);
if (links != null) {
return links;
}
links = new BuildGcsUploadReport(run);
run.addAction(links);
return links;
}
/** @param bucketName the name of the destination bucket. */
public void addBucket(String bucketName) {
buckets.add(bucketName);
}
/**
* @param relativePath the relative path (to the workspace) of the uploaded file.
* @param bucket the directory location in the cloud
*/
|
public void addUpload(String relativePath, BucketPath bucket) {
|
jenkinsci/google-storage-plugin
|
src/main/java/com/google/jenkins/plugins/storage/StdoutUpload.java
|
// Path: src/main/java/com/google/jenkins/plugins/storage/util/StorageUtil.java
// public class StorageUtil {
//
// /**
// * Compute the relative path of the given file inclusion, relative to the given workspace. If the
// * path is absolute, it returns the root-relative path instead.
// *
// * @param include The file whose relative path we are computing.
// * @param workspace The workspace containing the included file.
// * @return The unix-style relative path of file.
// * @throws UploadException when the input is malformed
// */
// public static String getRelative(FilePath include, FilePath workspace) throws UploadException {
// LinkedList<String> segments = new LinkedList<String>();
// while (!include.equals(workspace)) {
// segments.push(include.getName());
// include = include.getParent();
// if (Strings.isNullOrEmpty(include.getName())) {
// // When we reach "/" we're done either way.
// break;
// }
// }
// return String.join("/", segments);
// }
//
// /**
// * If a path prefix to strip has been specified, and the input string starts with that prefix,
// * returns the portion of the input after that prefix. Otherwise, returns the unmodified input.
// *
// * @param filename Input string to strip.
// * @param pathPrefix Name of the path prefix to strip on.
// * @return Remaining portion of the input after prefix is stripped.
// */
// public static String getStrippedFilename(String filename, String pathPrefix) {
// if (pathPrefix != null && filename != null && filename.startsWith(pathPrefix)) {
// return filename.substring(pathPrefix.length());
// }
// return filename;
// }
//
// /**
// * Perform variable expansion for non-pipeline steps.
// *
// * @param name The name, potentially including with variables
// * @param run The current run, used to determine pipeline status and to get environment.
// * @param listener Task listener, used to get environment
// * @return The updated name, with variables resolved
// * @throws InterruptedException If getting the environment of the run throws an
// * InterruptedException.
// * @throws IOException If getting the environment of the run throws an IOException.
// */
// public static String replaceMacro(String name, Run<?, ?> run, TaskListener listener)
// throws InterruptedException, IOException {
// if (run instanceof AbstractBuild) {
// name = Util.replaceMacro(name, run.getEnvironment(listener));
// }
// return name;
// }
//
// /**
// * Look up credentials by name.
// *
// * @param credentials The name of the credentials to look up.
// * @return The corresponding {@link GoogleRobotCredentials}.
// * @throws AbortException If credentials not found.
// */
// public static GoogleRobotCredentials lookupCredentials(String credentials) throws AbortException {
// GoogleRobotCredentials result = GoogleRobotCredentials.getById(credentials);
// if (result == null) {
// throw new AbortException("Unknown credentials: " + credentials);
// }
// return result;
// }
// }
|
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Closeables;
import com.google.jenkins.plugins.storage.util.StorageUtil;
import com.google.jenkins.plugins.util.Resolve;
import hudson.Extension;
import hudson.FilePath;
import hudson.console.PlainTextConsoleOutputStream;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.util.FormValidation;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
|
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage;
/**
* This upload extension allow the user to upload the build log for the Jenkins build to a given
* bucket, with a specified file name. By default, the file is named "build-log.txt".
*/
public class StdoutUpload extends AbstractUpload {
private final String logName;
/**
* Construct the Upload with the stock properties, and the additional information about how to
* name the build log file.
*
* @param bucket GCS bucket to upload build artifacts to.
* @param module An {@link UploadModule} to use for execution.
* @param logName Name of log file to store to GCS bucket.
* @param bucketNameWithVars Deprecated format for bucket.
*/
@DataBoundConstructor
public StdoutUpload(
@Nullable String bucket,
@Nullable UploadModule module,
String logName,
// Legacy arguments for backwards compatibility
@Deprecated @Nullable String bucketNameWithVars) {
super(bucket != null ? bucket : bucketNameWithVars, module);
this.logName = checkNotNull(logName);
}
/** @return The name to give the file we upload for the build log. */
public String getLogName() {
return logName;
}
/** {@inheritDoc} */
@Override
public String getDetails() {
return Messages.StdoutUpload_DetailsMessage(getLogName());
}
/** {@inheritDoc} */
@Override
public boolean forResult(Result result) {
if (result == null) {
return true;
}
if (result == Result.NOT_BUILT) {
return true;
}
return super.forResult(result);
}
/** {@inheritDoc} */
@Override
@Nullable
protected UploadSpec getInclusions(Run<?, ?> run, FilePath workspace, TaskListener listener)
throws UploadException {
try {
OutputStream outputStream = null;
InputStream inputStream = null;
try {
FilePath logDir = new FilePath(run.getLogFile()).getParent();
|
// Path: src/main/java/com/google/jenkins/plugins/storage/util/StorageUtil.java
// public class StorageUtil {
//
// /**
// * Compute the relative path of the given file inclusion, relative to the given workspace. If the
// * path is absolute, it returns the root-relative path instead.
// *
// * @param include The file whose relative path we are computing.
// * @param workspace The workspace containing the included file.
// * @return The unix-style relative path of file.
// * @throws UploadException when the input is malformed
// */
// public static String getRelative(FilePath include, FilePath workspace) throws UploadException {
// LinkedList<String> segments = new LinkedList<String>();
// while (!include.equals(workspace)) {
// segments.push(include.getName());
// include = include.getParent();
// if (Strings.isNullOrEmpty(include.getName())) {
// // When we reach "/" we're done either way.
// break;
// }
// }
// return String.join("/", segments);
// }
//
// /**
// * If a path prefix to strip has been specified, and the input string starts with that prefix,
// * returns the portion of the input after that prefix. Otherwise, returns the unmodified input.
// *
// * @param filename Input string to strip.
// * @param pathPrefix Name of the path prefix to strip on.
// * @return Remaining portion of the input after prefix is stripped.
// */
// public static String getStrippedFilename(String filename, String pathPrefix) {
// if (pathPrefix != null && filename != null && filename.startsWith(pathPrefix)) {
// return filename.substring(pathPrefix.length());
// }
// return filename;
// }
//
// /**
// * Perform variable expansion for non-pipeline steps.
// *
// * @param name The name, potentially including with variables
// * @param run The current run, used to determine pipeline status and to get environment.
// * @param listener Task listener, used to get environment
// * @return The updated name, with variables resolved
// * @throws InterruptedException If getting the environment of the run throws an
// * InterruptedException.
// * @throws IOException If getting the environment of the run throws an IOException.
// */
// public static String replaceMacro(String name, Run<?, ?> run, TaskListener listener)
// throws InterruptedException, IOException {
// if (run instanceof AbstractBuild) {
// name = Util.replaceMacro(name, run.getEnvironment(listener));
// }
// return name;
// }
//
// /**
// * Look up credentials by name.
// *
// * @param credentials The name of the credentials to look up.
// * @return The corresponding {@link GoogleRobotCredentials}.
// * @throws AbortException If credentials not found.
// */
// public static GoogleRobotCredentials lookupCredentials(String credentials) throws AbortException {
// GoogleRobotCredentials result = GoogleRobotCredentials.getById(credentials);
// if (result == null) {
// throw new AbortException("Unknown credentials: " + credentials);
// }
// return result;
// }
// }
// Path: src/main/java/com/google/jenkins/plugins/storage/StdoutUpload.java
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Closeables;
import com.google.jenkins.plugins.storage.util.StorageUtil;
import com.google.jenkins.plugins.util.Resolve;
import hudson.Extension;
import hudson.FilePath;
import hudson.console.PlainTextConsoleOutputStream;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.util.FormValidation;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage;
/**
* This upload extension allow the user to upload the build log for the Jenkins build to a given
* bucket, with a specified file name. By default, the file is named "build-log.txt".
*/
public class StdoutUpload extends AbstractUpload {
private final String logName;
/**
* Construct the Upload with the stock properties, and the additional information about how to
* name the build log file.
*
* @param bucket GCS bucket to upload build artifacts to.
* @param module An {@link UploadModule} to use for execution.
* @param logName Name of log file to store to GCS bucket.
* @param bucketNameWithVars Deprecated format for bucket.
*/
@DataBoundConstructor
public StdoutUpload(
@Nullable String bucket,
@Nullable UploadModule module,
String logName,
// Legacy arguments for backwards compatibility
@Deprecated @Nullable String bucketNameWithVars) {
super(bucket != null ? bucket : bucketNameWithVars, module);
this.logName = checkNotNull(logName);
}
/** @return The name to give the file we upload for the build log. */
public String getLogName() {
return logName;
}
/** {@inheritDoc} */
@Override
public String getDetails() {
return Messages.StdoutUpload_DetailsMessage(getLogName());
}
/** {@inheritDoc} */
@Override
public boolean forResult(Result result) {
if (result == null) {
return true;
}
if (result == Result.NOT_BUILT) {
return true;
}
return super.forResult(result);
}
/** {@inheritDoc} */
@Override
@Nullable
protected UploadSpec getInclusions(Run<?, ?> run, FilePath workspace, TaskListener listener)
throws UploadException {
try {
OutputStream outputStream = null;
InputStream inputStream = null;
try {
FilePath logDir = new FilePath(run.getLogFile()).getParent();
|
String resolvedLogName = StorageUtil.replaceMacro(getLogName(), run, listener);
|
jenkinsci/google-storage-plugin
|
src/main/java/com/google/jenkins/plugins/storage/client/ClientFactory.java
|
// Path: src/main/java/com/google/jenkins/plugins/storage/util/CredentialsUtil.java
// public static Credential getGoogleCredential(GoogleRobotCredentials robotCreds)
// throws AbortException {
// Credential credential;
// try {
// credential = robotCreds.getGoogleCredential(new StorageScopeRequirement());
// } catch (GeneralSecurityException gse) {
// throw new AbortException(Messages.CredentialsUtil_FailedToInitializeHTTPTransport(gse));
// }
//
// return credential;
// }
//
// Path: src/main/java/com/google/jenkins/plugins/storage/util/CredentialsUtil.java
// public static GoogleRobotCredentials getRobotCredentials(
// ItemGroup itemGroup,
// ImmutableList<DomainRequirement> domainRequirements,
// String credentialsId)
// throws AbortException {
// Preconditions.checkNotNull(itemGroup);
// Preconditions.checkNotNull(domainRequirements);
// Preconditions.checkArgument(!Strings.isNullOrEmpty(credentialsId));
//
// GoogleRobotCredentials robotCreds =
// CredentialsMatchers.firstOrNull(
// CredentialsProvider.lookupCredentials(
// GoogleRobotCredentials.class, itemGroup, ACL.SYSTEM, domainRequirements),
// CredentialsMatchers.withId(credentialsId));
//
// if (robotCreds == null) {
// throw new AbortException(Messages.CredentialsUtil_FailedToRetrieveCredentials(credentialsId));
// }
//
// return robotCreds;
// }
|
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Optional;
import static com.google.jenkins.plugins.storage.util.CredentialsUtil.getGoogleCredential;
import static com.google.jenkins.plugins.storage.util.CredentialsUtil.getRobotCredentials;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import hudson.AbortException;
import hudson.model.ItemGroup;
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage.client;
/** Creates clients for communicating with Google APIs. */
public class ClientFactory {
public static final String APPLICATION_NAME = "jenkins-google-storage-plugin";
private final Credential credential;
private final HttpTransport transport;
private final JsonFactory jsonFactory;
private final String credentialsId;
private final String defaultProjectId;
/**
* Creates a {@link ClientFactory} instance.
*
* @param itemGroup A handle to the Jenkins instance.
* @param domainRequirements A list of domain requirements.
* @param credentialsId The ID of the GoogleRobotCredentials to be retrieved from Jenkins and
* utilized for authorization.
* @param httpTransport If specified, the HTTP transport this factory will utilize for clients it
* creates.
* @throws hudson.AbortException If failed to create a new client factory.
*/
public ClientFactory(
ItemGroup itemGroup,
ImmutableList<DomainRequirement> domainRequirements,
String credentialsId,
Optional<HttpTransport> httpTransport)
throws AbortException {
GoogleRobotCredentials robotCreds =
|
// Path: src/main/java/com/google/jenkins/plugins/storage/util/CredentialsUtil.java
// public static Credential getGoogleCredential(GoogleRobotCredentials robotCreds)
// throws AbortException {
// Credential credential;
// try {
// credential = robotCreds.getGoogleCredential(new StorageScopeRequirement());
// } catch (GeneralSecurityException gse) {
// throw new AbortException(Messages.CredentialsUtil_FailedToInitializeHTTPTransport(gse));
// }
//
// return credential;
// }
//
// Path: src/main/java/com/google/jenkins/plugins/storage/util/CredentialsUtil.java
// public static GoogleRobotCredentials getRobotCredentials(
// ItemGroup itemGroup,
// ImmutableList<DomainRequirement> domainRequirements,
// String credentialsId)
// throws AbortException {
// Preconditions.checkNotNull(itemGroup);
// Preconditions.checkNotNull(domainRequirements);
// Preconditions.checkArgument(!Strings.isNullOrEmpty(credentialsId));
//
// GoogleRobotCredentials robotCreds =
// CredentialsMatchers.firstOrNull(
// CredentialsProvider.lookupCredentials(
// GoogleRobotCredentials.class, itemGroup, ACL.SYSTEM, domainRequirements),
// CredentialsMatchers.withId(credentialsId));
//
// if (robotCreds == null) {
// throw new AbortException(Messages.CredentialsUtil_FailedToRetrieveCredentials(credentialsId));
// }
//
// return robotCreds;
// }
// Path: src/main/java/com/google/jenkins/plugins/storage/client/ClientFactory.java
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Optional;
import static com.google.jenkins.plugins.storage.util.CredentialsUtil.getGoogleCredential;
import static com.google.jenkins.plugins.storage.util.CredentialsUtil.getRobotCredentials;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import hudson.AbortException;
import hudson.model.ItemGroup;
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage.client;
/** Creates clients for communicating with Google APIs. */
public class ClientFactory {
public static final String APPLICATION_NAME = "jenkins-google-storage-plugin";
private final Credential credential;
private final HttpTransport transport;
private final JsonFactory jsonFactory;
private final String credentialsId;
private final String defaultProjectId;
/**
* Creates a {@link ClientFactory} instance.
*
* @param itemGroup A handle to the Jenkins instance.
* @param domainRequirements A list of domain requirements.
* @param credentialsId The ID of the GoogleRobotCredentials to be retrieved from Jenkins and
* utilized for authorization.
* @param httpTransport If specified, the HTTP transport this factory will utilize for clients it
* creates.
* @throws hudson.AbortException If failed to create a new client factory.
*/
public ClientFactory(
ItemGroup itemGroup,
ImmutableList<DomainRequirement> domainRequirements,
String credentialsId,
Optional<HttpTransport> httpTransport)
throws AbortException {
GoogleRobotCredentials robotCreds =
|
getRobotCredentials(itemGroup, domainRequirements, credentialsId);
|
jenkinsci/google-storage-plugin
|
src/main/java/com/google/jenkins/plugins/storage/client/ClientFactory.java
|
// Path: src/main/java/com/google/jenkins/plugins/storage/util/CredentialsUtil.java
// public static Credential getGoogleCredential(GoogleRobotCredentials robotCreds)
// throws AbortException {
// Credential credential;
// try {
// credential = robotCreds.getGoogleCredential(new StorageScopeRequirement());
// } catch (GeneralSecurityException gse) {
// throw new AbortException(Messages.CredentialsUtil_FailedToInitializeHTTPTransport(gse));
// }
//
// return credential;
// }
//
// Path: src/main/java/com/google/jenkins/plugins/storage/util/CredentialsUtil.java
// public static GoogleRobotCredentials getRobotCredentials(
// ItemGroup itemGroup,
// ImmutableList<DomainRequirement> domainRequirements,
// String credentialsId)
// throws AbortException {
// Preconditions.checkNotNull(itemGroup);
// Preconditions.checkNotNull(domainRequirements);
// Preconditions.checkArgument(!Strings.isNullOrEmpty(credentialsId));
//
// GoogleRobotCredentials robotCreds =
// CredentialsMatchers.firstOrNull(
// CredentialsProvider.lookupCredentials(
// GoogleRobotCredentials.class, itemGroup, ACL.SYSTEM, domainRequirements),
// CredentialsMatchers.withId(credentialsId));
//
// if (robotCreds == null) {
// throw new AbortException(Messages.CredentialsUtil_FailedToRetrieveCredentials(credentialsId));
// }
//
// return robotCreds;
// }
|
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Optional;
import static com.google.jenkins.plugins.storage.util.CredentialsUtil.getGoogleCredential;
import static com.google.jenkins.plugins.storage.util.CredentialsUtil.getRobotCredentials;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import hudson.AbortException;
import hudson.model.ItemGroup;
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage.client;
/** Creates clients for communicating with Google APIs. */
public class ClientFactory {
public static final String APPLICATION_NAME = "jenkins-google-storage-plugin";
private final Credential credential;
private final HttpTransport transport;
private final JsonFactory jsonFactory;
private final String credentialsId;
private final String defaultProjectId;
/**
* Creates a {@link ClientFactory} instance.
*
* @param itemGroup A handle to the Jenkins instance.
* @param domainRequirements A list of domain requirements.
* @param credentialsId The ID of the GoogleRobotCredentials to be retrieved from Jenkins and
* utilized for authorization.
* @param httpTransport If specified, the HTTP transport this factory will utilize for clients it
* creates.
* @throws hudson.AbortException If failed to create a new client factory.
*/
public ClientFactory(
ItemGroup itemGroup,
ImmutableList<DomainRequirement> domainRequirements,
String credentialsId,
Optional<HttpTransport> httpTransport)
throws AbortException {
GoogleRobotCredentials robotCreds =
getRobotCredentials(itemGroup, domainRequirements, credentialsId);
|
// Path: src/main/java/com/google/jenkins/plugins/storage/util/CredentialsUtil.java
// public static Credential getGoogleCredential(GoogleRobotCredentials robotCreds)
// throws AbortException {
// Credential credential;
// try {
// credential = robotCreds.getGoogleCredential(new StorageScopeRequirement());
// } catch (GeneralSecurityException gse) {
// throw new AbortException(Messages.CredentialsUtil_FailedToInitializeHTTPTransport(gse));
// }
//
// return credential;
// }
//
// Path: src/main/java/com/google/jenkins/plugins/storage/util/CredentialsUtil.java
// public static GoogleRobotCredentials getRobotCredentials(
// ItemGroup itemGroup,
// ImmutableList<DomainRequirement> domainRequirements,
// String credentialsId)
// throws AbortException {
// Preconditions.checkNotNull(itemGroup);
// Preconditions.checkNotNull(domainRequirements);
// Preconditions.checkArgument(!Strings.isNullOrEmpty(credentialsId));
//
// GoogleRobotCredentials robotCreds =
// CredentialsMatchers.firstOrNull(
// CredentialsProvider.lookupCredentials(
// GoogleRobotCredentials.class, itemGroup, ACL.SYSTEM, domainRequirements),
// CredentialsMatchers.withId(credentialsId));
//
// if (robotCreds == null) {
// throw new AbortException(Messages.CredentialsUtil_FailedToRetrieveCredentials(credentialsId));
// }
//
// return robotCreds;
// }
// Path: src/main/java/com/google/jenkins/plugins/storage/client/ClientFactory.java
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Optional;
import static com.google.jenkins.plugins.storage.util.CredentialsUtil.getGoogleCredential;
import static com.google.jenkins.plugins.storage.util.CredentialsUtil.getRobotCredentials;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import hudson.AbortException;
import hudson.model.ItemGroup;
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage.client;
/** Creates clients for communicating with Google APIs. */
public class ClientFactory {
public static final String APPLICATION_NAME = "jenkins-google-storage-plugin";
private final Credential credential;
private final HttpTransport transport;
private final JsonFactory jsonFactory;
private final String credentialsId;
private final String defaultProjectId;
/**
* Creates a {@link ClientFactory} instance.
*
* @param itemGroup A handle to the Jenkins instance.
* @param domainRequirements A list of domain requirements.
* @param credentialsId The ID of the GoogleRobotCredentials to be retrieved from Jenkins and
* utilized for authorization.
* @param httpTransport If specified, the HTTP transport this factory will utilize for clients it
* creates.
* @throws hudson.AbortException If failed to create a new client factory.
*/
public ClientFactory(
ItemGroup itemGroup,
ImmutableList<DomainRequirement> domainRequirements,
String credentialsId,
Optional<HttpTransport> httpTransport)
throws AbortException {
GoogleRobotCredentials robotCreds =
getRobotCredentials(itemGroup, domainRequirements, credentialsId);
|
this.credential = getGoogleCredential(robotCreds);
|
jenkinsci/google-storage-plugin
|
src/main/java/com/google/jenkins/plugins/storage/ClassicUpload.java
|
// Path: src/main/java/com/google/jenkins/plugins/storage/util/StorageUtil.java
// public class StorageUtil {
//
// /**
// * Compute the relative path of the given file inclusion, relative to the given workspace. If the
// * path is absolute, it returns the root-relative path instead.
// *
// * @param include The file whose relative path we are computing.
// * @param workspace The workspace containing the included file.
// * @return The unix-style relative path of file.
// * @throws UploadException when the input is malformed
// */
// public static String getRelative(FilePath include, FilePath workspace) throws UploadException {
// LinkedList<String> segments = new LinkedList<String>();
// while (!include.equals(workspace)) {
// segments.push(include.getName());
// include = include.getParent();
// if (Strings.isNullOrEmpty(include.getName())) {
// // When we reach "/" we're done either way.
// break;
// }
// }
// return String.join("/", segments);
// }
//
// /**
// * If a path prefix to strip has been specified, and the input string starts with that prefix,
// * returns the portion of the input after that prefix. Otherwise, returns the unmodified input.
// *
// * @param filename Input string to strip.
// * @param pathPrefix Name of the path prefix to strip on.
// * @return Remaining portion of the input after prefix is stripped.
// */
// public static String getStrippedFilename(String filename, String pathPrefix) {
// if (pathPrefix != null && filename != null && filename.startsWith(pathPrefix)) {
// return filename.substring(pathPrefix.length());
// }
// return filename;
// }
//
// /**
// * Perform variable expansion for non-pipeline steps.
// *
// * @param name The name, potentially including with variables
// * @param run The current run, used to determine pipeline status and to get environment.
// * @param listener Task listener, used to get environment
// * @return The updated name, with variables resolved
// * @throws InterruptedException If getting the environment of the run throws an
// * InterruptedException.
// * @throws IOException If getting the environment of the run throws an IOException.
// */
// public static String replaceMacro(String name, Run<?, ?> run, TaskListener listener)
// throws InterruptedException, IOException {
// if (run instanceof AbstractBuild) {
// name = Util.replaceMacro(name, run.getEnvironment(listener));
// }
// return name;
// }
//
// /**
// * Look up credentials by name.
// *
// * @param credentials The name of the credentials to look up.
// * @return The corresponding {@link GoogleRobotCredentials}.
// * @throws AbortException If credentials not found.
// */
// public static GoogleRobotCredentials lookupCredentials(String credentials) throws AbortException {
// GoogleRobotCredentials result = GoogleRobotCredentials.getById(credentials);
// if (result == null) {
// throw new AbortException("Unknown credentials: " + credentials);
// }
// return result;
// }
// }
|
import com.google.jenkins.plugins.storage.util.StorageUtil;
import com.google.jenkins.plugins.util.Resolve;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.util.FormValidation;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Nullable;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
|
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage;
/**
* This upload extension implements the classical upload pattern where a user provides an Ant-style
* glob, e.g. ** / *.java relative to the build workspace, and those files are uploaded to the
* storage bucket.
*/
public class ClassicUpload extends AbstractUpload {
/**
* Construct the classic upload implementation from the base properties and the glob for matching
* files.
*
* @param bucket GCS bucket to upload files to.
* @param module Helper class for connecting to the GCS API.
* @param pattern The glob of files to upload, which potentially contains unresolved symbols, such
* as $JOB_NAME and $BUILD_NUMBER.
* @param bucketNameWithVars Deprecated format for bucket.
* @param sourceGlobWithVars Deprecated. Old name kept for deserialization.
*/
@DataBoundConstructor
public ClassicUpload(
String bucket,
@Nullable UploadModule module,
String pattern,
// Legacy arguments for backwards compatibility
@Deprecated @Nullable String bucketNameWithVars,
@Deprecated @Nullable String sourceGlobWithVars) {
super(bucket != null ? bucket : bucketNameWithVars, module);
this.sourceGlobWithVars = pattern != null ? pattern : sourceGlobWithVars;
Objects.requireNonNull(this.sourceGlobWithVars);
}
/** {@inheritDoc} */
@Override
public String getDetails() {
return getPattern();
}
/** {@inheritDoc} */
@Override
@Nullable
protected UploadSpec getInclusions(Run<?, ?> run, FilePath workspace, TaskListener listener)
throws UploadException {
try {
|
// Path: src/main/java/com/google/jenkins/plugins/storage/util/StorageUtil.java
// public class StorageUtil {
//
// /**
// * Compute the relative path of the given file inclusion, relative to the given workspace. If the
// * path is absolute, it returns the root-relative path instead.
// *
// * @param include The file whose relative path we are computing.
// * @param workspace The workspace containing the included file.
// * @return The unix-style relative path of file.
// * @throws UploadException when the input is malformed
// */
// public static String getRelative(FilePath include, FilePath workspace) throws UploadException {
// LinkedList<String> segments = new LinkedList<String>();
// while (!include.equals(workspace)) {
// segments.push(include.getName());
// include = include.getParent();
// if (Strings.isNullOrEmpty(include.getName())) {
// // When we reach "/" we're done either way.
// break;
// }
// }
// return String.join("/", segments);
// }
//
// /**
// * If a path prefix to strip has been specified, and the input string starts with that prefix,
// * returns the portion of the input after that prefix. Otherwise, returns the unmodified input.
// *
// * @param filename Input string to strip.
// * @param pathPrefix Name of the path prefix to strip on.
// * @return Remaining portion of the input after prefix is stripped.
// */
// public static String getStrippedFilename(String filename, String pathPrefix) {
// if (pathPrefix != null && filename != null && filename.startsWith(pathPrefix)) {
// return filename.substring(pathPrefix.length());
// }
// return filename;
// }
//
// /**
// * Perform variable expansion for non-pipeline steps.
// *
// * @param name The name, potentially including with variables
// * @param run The current run, used to determine pipeline status and to get environment.
// * @param listener Task listener, used to get environment
// * @return The updated name, with variables resolved
// * @throws InterruptedException If getting the environment of the run throws an
// * InterruptedException.
// * @throws IOException If getting the environment of the run throws an IOException.
// */
// public static String replaceMacro(String name, Run<?, ?> run, TaskListener listener)
// throws InterruptedException, IOException {
// if (run instanceof AbstractBuild) {
// name = Util.replaceMacro(name, run.getEnvironment(listener));
// }
// return name;
// }
//
// /**
// * Look up credentials by name.
// *
// * @param credentials The name of the credentials to look up.
// * @return The corresponding {@link GoogleRobotCredentials}.
// * @throws AbortException If credentials not found.
// */
// public static GoogleRobotCredentials lookupCredentials(String credentials) throws AbortException {
// GoogleRobotCredentials result = GoogleRobotCredentials.getById(credentials);
// if (result == null) {
// throw new AbortException("Unknown credentials: " + credentials);
// }
// return result;
// }
// }
// Path: src/main/java/com/google/jenkins/plugins/storage/ClassicUpload.java
import com.google.jenkins.plugins.storage.util.StorageUtil;
import com.google.jenkins.plugins.util.Resolve;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.util.FormValidation;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.Nullable;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage;
/**
* This upload extension implements the classical upload pattern where a user provides an Ant-style
* glob, e.g. ** / *.java relative to the build workspace, and those files are uploaded to the
* storage bucket.
*/
public class ClassicUpload extends AbstractUpload {
/**
* Construct the classic upload implementation from the base properties and the glob for matching
* files.
*
* @param bucket GCS bucket to upload files to.
* @param module Helper class for connecting to the GCS API.
* @param pattern The glob of files to upload, which potentially contains unresolved symbols, such
* as $JOB_NAME and $BUILD_NUMBER.
* @param bucketNameWithVars Deprecated format for bucket.
* @param sourceGlobWithVars Deprecated. Old name kept for deserialization.
*/
@DataBoundConstructor
public ClassicUpload(
String bucket,
@Nullable UploadModule module,
String pattern,
// Legacy arguments for backwards compatibility
@Deprecated @Nullable String bucketNameWithVars,
@Deprecated @Nullable String sourceGlobWithVars) {
super(bucket != null ? bucket : bucketNameWithVars, module);
this.sourceGlobWithVars = pattern != null ? pattern : sourceGlobWithVars;
Objects.requireNonNull(this.sourceGlobWithVars);
}
/** {@inheritDoc} */
@Override
public String getDetails() {
return getPattern();
}
/** {@inheritDoc} */
@Override
@Nullable
protected UploadSpec getInclusions(Run<?, ?> run, FilePath workspace, TaskListener listener)
throws UploadException {
try {
|
String globResolvedVars = StorageUtil.replaceMacro(getPattern(), run, listener);
|
jenkinsci/google-storage-plugin
|
src/main/java/com/google/jenkins/plugins/storage/util/CredentialsUtil.java
|
// Path: src/main/java/com/google/jenkins/plugins/storage/StorageScopeRequirement.java
// public class StorageScopeRequirement extends GoogleOAuth2ScopeRequirement {
// /** {@inheritDoc} */
// @Override
// public Collection<String> getScopes() {
// return ImmutableList.of(StorageScopes.DEVSTORAGE_FULL_CONTROL);
// }
// }
|
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import com.google.jenkins.plugins.storage.StorageScopeRequirement;
import hudson.AbortException;
import hudson.model.ItemGroup;
import hudson.security.ACL;
import java.security.GeneralSecurityException;
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage.util;
/** Provides a library of utility functions for credentials-related work. */
public class CredentialsUtil {
/**
* Get the Google Robot Credentials for the given credentialsId.
*
* @param itemGroup A handle to the Jenkins instance. Must be non-null.
* @param domainRequirements A list of domain requirements. Must be non-null.
* @param credentialsId The ID of the GoogleRobotCredentials to be retrieved from Jenkins and
* utilized for authorization. Must be non-empty or non-null and exist in credentials store.
* @return Google Robot Credential for the given credentialsId.
* @throws hudson.AbortException If there was an issue retrieving the Google Robot Credentials.
*/
public static GoogleRobotCredentials getRobotCredentials(
ItemGroup itemGroup,
ImmutableList<DomainRequirement> domainRequirements,
String credentialsId)
throws AbortException {
Preconditions.checkNotNull(itemGroup);
Preconditions.checkNotNull(domainRequirements);
Preconditions.checkArgument(!Strings.isNullOrEmpty(credentialsId));
GoogleRobotCredentials robotCreds =
CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(
GoogleRobotCredentials.class, itemGroup, ACL.SYSTEM, domainRequirements),
CredentialsMatchers.withId(credentialsId));
if (robotCreds == null) {
throw new AbortException(Messages.CredentialsUtil_FailedToRetrieveCredentials(credentialsId));
}
return robotCreds;
}
/**
* Get the Credential from the Google robot credentials for GKE access.
*
* @param robotCreds Google Robot Credential for desired service account.
* @return Google Credential for the service account.
* @throws AbortException if there was an error initializing HTTP transport.
*/
public static Credential getGoogleCredential(GoogleRobotCredentials robotCreds)
throws AbortException {
Credential credential;
try {
|
// Path: src/main/java/com/google/jenkins/plugins/storage/StorageScopeRequirement.java
// public class StorageScopeRequirement extends GoogleOAuth2ScopeRequirement {
// /** {@inheritDoc} */
// @Override
// public Collection<String> getScopes() {
// return ImmutableList.of(StorageScopes.DEVSTORAGE_FULL_CONTROL);
// }
// }
// Path: src/main/java/com/google/jenkins/plugins/storage/util/CredentialsUtil.java
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import com.google.jenkins.plugins.storage.StorageScopeRequirement;
import hudson.AbortException;
import hudson.model.ItemGroup;
import hudson.security.ACL;
import java.security.GeneralSecurityException;
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage.util;
/** Provides a library of utility functions for credentials-related work. */
public class CredentialsUtil {
/**
* Get the Google Robot Credentials for the given credentialsId.
*
* @param itemGroup A handle to the Jenkins instance. Must be non-null.
* @param domainRequirements A list of domain requirements. Must be non-null.
* @param credentialsId The ID of the GoogleRobotCredentials to be retrieved from Jenkins and
* utilized for authorization. Must be non-empty or non-null and exist in credentials store.
* @return Google Robot Credential for the given credentialsId.
* @throws hudson.AbortException If there was an issue retrieving the Google Robot Credentials.
*/
public static GoogleRobotCredentials getRobotCredentials(
ItemGroup itemGroup,
ImmutableList<DomainRequirement> domainRequirements,
String credentialsId)
throws AbortException {
Preconditions.checkNotNull(itemGroup);
Preconditions.checkNotNull(domainRequirements);
Preconditions.checkArgument(!Strings.isNullOrEmpty(credentialsId));
GoogleRobotCredentials robotCreds =
CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(
GoogleRobotCredentials.class, itemGroup, ACL.SYSTEM, domainRequirements),
CredentialsMatchers.withId(credentialsId));
if (robotCreds == null) {
throw new AbortException(Messages.CredentialsUtil_FailedToRetrieveCredentials(credentialsId));
}
return robotCreds;
}
/**
* Get the Credential from the Google robot credentials for GKE access.
*
* @param robotCreds Google Robot Credential for desired service account.
* @return Google Credential for the service account.
* @throws AbortException if there was an error initializing HTTP transport.
*/
public static Credential getGoogleCredential(GoogleRobotCredentials robotCreds)
throws AbortException {
Credential credential;
try {
|
credential = robotCreds.getGoogleCredential(new StorageScopeRequirement());
|
jenkinsci/google-storage-plugin
|
src/test/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploaderTest.java
|
// Path: src/main/java/com/google/jenkins/plugins/storage/AbstractUploadDescriptor.java
// public static final String GCS_SCHEME = "gs://";
//
// Path: src/main/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploader.java
// @Extension
// public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
//
// /** {@inheritDoc} */
// @Override
// public boolean isApplicable(
// @SuppressWarnings("rawtypes") Class<? extends AbstractProject> aClass) {
// // Indicates that this builder can be used with all kinds of project types
// return true;
// }
//
// /** {@inheritDoc} */
// @Override
// public String getDisplayName() {
// return Messages.GoogleCloudStorageUploader_DisplayName();
// }
//
// /**
// * @return the default uploads when the user configure {@link GoogleCloudStorageUploader} for
// * the first time.
// */
// public List<AbstractUpload> getDefaultUploads() {
// StdoutUpload upload =
// new StdoutUpload(
// GCS_SCHEME, null, "build-log.txt", null /* legacy arg: bucketNameWithVars */);
// upload.setForFailedJobs(true);
// return ImmutableList.<AbstractUpload>of(upload);
// }
//
// /** @return All registered {@link AbstractUpload}s. */
// public List<AbstractUploadDescriptor> getUploads() {
// return AbstractUpload.all();
// }
// }
|
import static com.google.jenkins.plugins.storage.AbstractUploadDescriptor.GCS_SCHEME;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.when;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.StorageObject;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleOAuth2ScopeRequirement;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import com.google.jenkins.plugins.storage.GoogleCloudStorageUploader.DescriptorImpl;
import com.google.jenkins.plugins.util.ConflictException;
import com.google.jenkins.plugins.util.ForbiddenException;
import com.google.jenkins.plugins.util.MockExecutor;
import com.google.jenkins.plugins.util.NotFoundException;
import hudson.model.AbstractProject;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Result;
import hudson.model.Run;
import hudson.tasks.Shell;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Verifier;
import org.jvnet.hudson.test.FailureBuilder;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.WithoutJenkins;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
|
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage;
/** Tests for {@link GoogleCloudStorageUploader}. */
public class GoogleCloudStorageUploaderTest {
@Rule public JenkinsRule jenkins = new JenkinsRule();
@Mock private GoogleRobotCredentials credentials;
private GoogleCredential credential;
private String bucket;
private String glob;
private FreeStyleProject project;
private GoogleCloudStorageUploader underTest;
private boolean sharedPublicly;
private boolean forFailedJobs;
private boolean showInline;
private boolean stripPathPrefix;
private String pathPrefix;
private final MockExecutor executor = new MockExecutor();
private ConflictException conflictException;
private ForbiddenException forbiddenException;
private NotFoundException notFoundException;
private AbstractUpload setOptionalParams(AbstractUpload a) {
a.setSharedPublicly(sharedPublicly);
a.setForFailedJobs(forFailedJobs);
a.setShowInline(showInline);
if (stripPathPrefix) {
a.setPathPrefix(pathPrefix);
}
return a;
}
private static class MockUploadModule extends UploadModule {
public MockUploadModule(MockExecutor executor) {
this.executor = executor;
}
@Override
public MockExecutor newExecutor() {
return executor;
}
private final MockExecutor executor;
}
@Rule
public Verifier verifySawAll =
new Verifier() {
@Override
public void verify() {
assertTrue(executor.sawAll());
assertFalse(executor.sawUnexpected());
}
};
/**
* Checks that any object insertion that we do has certain properties at the point of execution.
*/
private Predicate<Storage.Objects.Insert> checkFieldsMatch =
new Predicate<Storage.Objects.Insert>() {
public boolean apply(Storage.Objects.Insert insertion) {
assertNotNull(insertion.getMediaHttpUploader());
|
// Path: src/main/java/com/google/jenkins/plugins/storage/AbstractUploadDescriptor.java
// public static final String GCS_SCHEME = "gs://";
//
// Path: src/main/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploader.java
// @Extension
// public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
//
// /** {@inheritDoc} */
// @Override
// public boolean isApplicable(
// @SuppressWarnings("rawtypes") Class<? extends AbstractProject> aClass) {
// // Indicates that this builder can be used with all kinds of project types
// return true;
// }
//
// /** {@inheritDoc} */
// @Override
// public String getDisplayName() {
// return Messages.GoogleCloudStorageUploader_DisplayName();
// }
//
// /**
// * @return the default uploads when the user configure {@link GoogleCloudStorageUploader} for
// * the first time.
// */
// public List<AbstractUpload> getDefaultUploads() {
// StdoutUpload upload =
// new StdoutUpload(
// GCS_SCHEME, null, "build-log.txt", null /* legacy arg: bucketNameWithVars */);
// upload.setForFailedJobs(true);
// return ImmutableList.<AbstractUpload>of(upload);
// }
//
// /** @return All registered {@link AbstractUpload}s. */
// public List<AbstractUploadDescriptor> getUploads() {
// return AbstractUpload.all();
// }
// }
// Path: src/test/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploaderTest.java
import static com.google.jenkins.plugins.storage.AbstractUploadDescriptor.GCS_SCHEME;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.when;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.StorageObject;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleOAuth2ScopeRequirement;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import com.google.jenkins.plugins.storage.GoogleCloudStorageUploader.DescriptorImpl;
import com.google.jenkins.plugins.util.ConflictException;
import com.google.jenkins.plugins.util.ForbiddenException;
import com.google.jenkins.plugins.util.MockExecutor;
import com.google.jenkins.plugins.util.NotFoundException;
import hudson.model.AbstractProject;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Result;
import hudson.model.Run;
import hudson.tasks.Shell;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Verifier;
import org.jvnet.hudson.test.FailureBuilder;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.WithoutJenkins;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage;
/** Tests for {@link GoogleCloudStorageUploader}. */
public class GoogleCloudStorageUploaderTest {
@Rule public JenkinsRule jenkins = new JenkinsRule();
@Mock private GoogleRobotCredentials credentials;
private GoogleCredential credential;
private String bucket;
private String glob;
private FreeStyleProject project;
private GoogleCloudStorageUploader underTest;
private boolean sharedPublicly;
private boolean forFailedJobs;
private boolean showInline;
private boolean stripPathPrefix;
private String pathPrefix;
private final MockExecutor executor = new MockExecutor();
private ConflictException conflictException;
private ForbiddenException forbiddenException;
private NotFoundException notFoundException;
private AbstractUpload setOptionalParams(AbstractUpload a) {
a.setSharedPublicly(sharedPublicly);
a.setForFailedJobs(forFailedJobs);
a.setShowInline(showInline);
if (stripPathPrefix) {
a.setPathPrefix(pathPrefix);
}
return a;
}
private static class MockUploadModule extends UploadModule {
public MockUploadModule(MockExecutor executor) {
this.executor = executor;
}
@Override
public MockExecutor newExecutor() {
return executor;
}
private final MockExecutor executor;
}
@Rule
public Verifier verifySawAll =
new Verifier() {
@Override
public void verify() {
assertTrue(executor.sawAll());
assertFalse(executor.sawUnexpected());
}
};
/**
* Checks that any object insertion that we do has certain properties at the point of execution.
*/
private Predicate<Storage.Objects.Insert> checkFieldsMatch =
new Predicate<Storage.Objects.Insert>() {
public boolean apply(Storage.Objects.Insert insertion) {
assertNotNull(insertion.getMediaHttpUploader());
|
assertEquals(bucket.substring(GCS_SCHEME.length()), insertion.getBucket());
|
jenkinsci/google-storage-plugin
|
src/test/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploaderTest.java
|
// Path: src/main/java/com/google/jenkins/plugins/storage/AbstractUploadDescriptor.java
// public static final String GCS_SCHEME = "gs://";
//
// Path: src/main/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploader.java
// @Extension
// public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
//
// /** {@inheritDoc} */
// @Override
// public boolean isApplicable(
// @SuppressWarnings("rawtypes") Class<? extends AbstractProject> aClass) {
// // Indicates that this builder can be used with all kinds of project types
// return true;
// }
//
// /** {@inheritDoc} */
// @Override
// public String getDisplayName() {
// return Messages.GoogleCloudStorageUploader_DisplayName();
// }
//
// /**
// * @return the default uploads when the user configure {@link GoogleCloudStorageUploader} for
// * the first time.
// */
// public List<AbstractUpload> getDefaultUploads() {
// StdoutUpload upload =
// new StdoutUpload(
// GCS_SCHEME, null, "build-log.txt", null /* legacy arg: bucketNameWithVars */);
// upload.setForFailedJobs(true);
// return ImmutableList.<AbstractUpload>of(upload);
// }
//
// /** @return All registered {@link AbstractUpload}s. */
// public List<AbstractUploadDescriptor> getUploads() {
// return AbstractUpload.all();
// }
// }
|
import static com.google.jenkins.plugins.storage.AbstractUploadDescriptor.GCS_SCHEME;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.when;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.StorageObject;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleOAuth2ScopeRequirement;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import com.google.jenkins.plugins.storage.GoogleCloudStorageUploader.DescriptorImpl;
import com.google.jenkins.plugins.util.ConflictException;
import com.google.jenkins.plugins.util.ForbiddenException;
import com.google.jenkins.plugins.util.MockExecutor;
import com.google.jenkins.plugins.util.NotFoundException;
import hudson.model.AbstractProject;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Result;
import hudson.model.Run;
import hudson.tasks.Shell;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Verifier;
import org.jvnet.hudson.test.FailureBuilder;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.WithoutJenkins;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
|
public void testMultiFileGlob() throws Exception {
glob = "*.txt";
underTest =
new GoogleCloudStorageUploader(
CREDENTIALS_ID,
ImmutableList.<AbstractUpload>of(
setOptionalParams(
new ClassicUpload(
bucket,
new MockUploadModule(executor),
glob,
null /* legacy arg */,
null /* legacy arg */))));
project.getBuildersList().add(new Shell("echo foo > foo.txt; echo bar > bar.txt"));
project.getPublishersList().add(underTest);
executor.throwWhen(Storage.Buckets.Get.class, notFoundException);
executor.passThruWhen(Storage.Buckets.Insert.class);
executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);
executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);
FreeStyleBuild build = project.scheduleBuild2(0).get();
assertEquals(Result.SUCCESS, build.getResult());
}
@Test
@WithoutJenkins
public void testDescriptor() {
|
// Path: src/main/java/com/google/jenkins/plugins/storage/AbstractUploadDescriptor.java
// public static final String GCS_SCHEME = "gs://";
//
// Path: src/main/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploader.java
// @Extension
// public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
//
// /** {@inheritDoc} */
// @Override
// public boolean isApplicable(
// @SuppressWarnings("rawtypes") Class<? extends AbstractProject> aClass) {
// // Indicates that this builder can be used with all kinds of project types
// return true;
// }
//
// /** {@inheritDoc} */
// @Override
// public String getDisplayName() {
// return Messages.GoogleCloudStorageUploader_DisplayName();
// }
//
// /**
// * @return the default uploads when the user configure {@link GoogleCloudStorageUploader} for
// * the first time.
// */
// public List<AbstractUpload> getDefaultUploads() {
// StdoutUpload upload =
// new StdoutUpload(
// GCS_SCHEME, null, "build-log.txt", null /* legacy arg: bucketNameWithVars */);
// upload.setForFailedJobs(true);
// return ImmutableList.<AbstractUpload>of(upload);
// }
//
// /** @return All registered {@link AbstractUpload}s. */
// public List<AbstractUploadDescriptor> getUploads() {
// return AbstractUpload.all();
// }
// }
// Path: src/test/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploaderTest.java
import static com.google.jenkins.plugins.storage.AbstractUploadDescriptor.GCS_SCHEME;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.when;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.StorageObject;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleOAuth2ScopeRequirement;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import com.google.jenkins.plugins.storage.GoogleCloudStorageUploader.DescriptorImpl;
import com.google.jenkins.plugins.util.ConflictException;
import com.google.jenkins.plugins.util.ForbiddenException;
import com.google.jenkins.plugins.util.MockExecutor;
import com.google.jenkins.plugins.util.NotFoundException;
import hudson.model.AbstractProject;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Result;
import hudson.model.Run;
import hudson.tasks.Shell;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Verifier;
import org.jvnet.hudson.test.FailureBuilder;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.WithoutJenkins;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public void testMultiFileGlob() throws Exception {
glob = "*.txt";
underTest =
new GoogleCloudStorageUploader(
CREDENTIALS_ID,
ImmutableList.<AbstractUpload>of(
setOptionalParams(
new ClassicUpload(
bucket,
new MockUploadModule(executor),
glob,
null /* legacy arg */,
null /* legacy arg */))));
project.getBuildersList().add(new Shell("echo foo > foo.txt; echo bar > bar.txt"));
project.getPublishersList().add(underTest);
executor.throwWhen(Storage.Buckets.Get.class, notFoundException);
executor.passThruWhen(Storage.Buckets.Insert.class);
executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);
executor.passThruWhen(Storage.Objects.Insert.class, checkFieldsMatch);
FreeStyleBuild build = project.scheduleBuild2(0).get();
assertEquals(Result.SUCCESS, build.getResult());
}
@Test
@WithoutJenkins
public void testDescriptor() {
|
DescriptorImpl descriptor = new DescriptorImpl();
|
jenkinsci/google-storage-plugin
|
src/test/java/com/google/jenkins/plugins/storage/util/CredentialsUtilTest.java
|
// Path: src/main/java/com/google/jenkins/plugins/storage/StorageScopeRequirement.java
// public class StorageScopeRequirement extends GoogleOAuth2ScopeRequirement {
// /** {@inheritDoc} */
// @Override
// public Collection<String> getScopes() {
// return ImmutableList.of(StorageScopes.DEVSTORAGE_FULL_CONTROL);
// }
// }
|
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import com.google.jenkins.plugins.storage.StorageScopeRequirement;
import hudson.AbortException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import jenkins.model.Jenkins;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage.util;
@RunWith(MockitoJUnitRunner.class)
public class CredentialsUtilTest {
private static final String TEST_CREDENTIALS_ID = "test-credentials-id";
private static final String TEST_INVALID_CREDENTIALS_ID = "test-invalid-credentials-id";
@ClassRule public static JenkinsRule r = new JenkinsRule();
public static Jenkins jenkins;
@BeforeClass
public static void init() throws IOException {
jenkins = r.jenkins;
CredentialsStore store = new SystemCredentialsProvider.ProviderImpl().getStore(jenkins);
GoogleRobotCredentials credentials = Mockito.mock(GoogleRobotCredentials.class);
Mockito.when(credentials.getId()).thenReturn(TEST_CREDENTIALS_ID);
store.addCredentials(Domain.global(), credentials);
}
@Test
public void testGetRobotCredentialsReturnsFirstCredential() throws IOException {
assertNotNull(
CredentialsUtil.getRobotCredentials(
jenkins.get(), ImmutableList.<DomainRequirement>of(), TEST_CREDENTIALS_ID));
}
@Test(expected = AbortException.class)
public void testGetRobotCredentialsInvalidCredentialsIdAbortException() throws AbortException {
CredentialsUtil.getRobotCredentials(
jenkins.get(), ImmutableList.<DomainRequirement>of(), TEST_INVALID_CREDENTIALS_ID);
}
@Test(expected = AbortException.class)
public void testGetGoogleCredentialAbortException()
throws GeneralSecurityException, AbortException {
GoogleRobotCredentials robotCreds = Mockito.mock(GoogleRobotCredentials.class);
|
// Path: src/main/java/com/google/jenkins/plugins/storage/StorageScopeRequirement.java
// public class StorageScopeRequirement extends GoogleOAuth2ScopeRequirement {
// /** {@inheritDoc} */
// @Override
// public Collection<String> getScopes() {
// return ImmutableList.of(StorageScopes.DEVSTORAGE_FULL_CONTROL);
// }
// }
// Path: src/test/java/com/google/jenkins/plugins/storage/util/CredentialsUtilTest.java
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import com.google.jenkins.plugins.storage.StorageScopeRequirement;
import hudson.AbortException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import jenkins.model.Jenkins;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage.util;
@RunWith(MockitoJUnitRunner.class)
public class CredentialsUtilTest {
private static final String TEST_CREDENTIALS_ID = "test-credentials-id";
private static final String TEST_INVALID_CREDENTIALS_ID = "test-invalid-credentials-id";
@ClassRule public static JenkinsRule r = new JenkinsRule();
public static Jenkins jenkins;
@BeforeClass
public static void init() throws IOException {
jenkins = r.jenkins;
CredentialsStore store = new SystemCredentialsProvider.ProviderImpl().getStore(jenkins);
GoogleRobotCredentials credentials = Mockito.mock(GoogleRobotCredentials.class);
Mockito.when(credentials.getId()).thenReturn(TEST_CREDENTIALS_ID);
store.addCredentials(Domain.global(), credentials);
}
@Test
public void testGetRobotCredentialsReturnsFirstCredential() throws IOException {
assertNotNull(
CredentialsUtil.getRobotCredentials(
jenkins.get(), ImmutableList.<DomainRequirement>of(), TEST_CREDENTIALS_ID));
}
@Test(expected = AbortException.class)
public void testGetRobotCredentialsInvalidCredentialsIdAbortException() throws AbortException {
CredentialsUtil.getRobotCredentials(
jenkins.get(), ImmutableList.<DomainRequirement>of(), TEST_INVALID_CREDENTIALS_ID);
}
@Test(expected = AbortException.class)
public void testGetGoogleCredentialAbortException()
throws GeneralSecurityException, AbortException {
GoogleRobotCredentials robotCreds = Mockito.mock(GoogleRobotCredentials.class);
|
Mockito.when(robotCreds.getGoogleCredential(any(StorageScopeRequirement.class)))
|
jenkinsci/google-storage-plugin
|
src/main/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploader.java
|
// Path: src/main/java/com/google/jenkins/plugins/storage/AbstractUploadDescriptor.java
// public static final String GCS_SCHEME = "gs://";
//
// Path: src/main/java/com/google/jenkins/plugins/storage/reports/ProjectGcsUploadReport.java
// public class ProjectGcsUploadReport extends AbstractGcsUploadReport {
//
// public ProjectGcsUploadReport(AbstractProject<?, ?> project) {
// super(project);
// }
//
// /** @return the project that this {@link ProjectGcsUploadReport} belongs to. */
// public AbstractProject<?, ?> getProject() {
// return (AbstractProject<?, ?>) getParent();
// }
//
// /** {@inheritDoc} */
// @Override
// public Set<String> getBuckets() {
// BuildGcsUploadReport links = BuildGcsUploadReport.of(getProject());
// return links == null ? ImmutableSet.<String>of() : links.getBuckets();
// }
//
// /** {@inheritDoc} */
// @Override
// public Set<String> getStorageObjects() {
// BuildGcsUploadReport links = BuildGcsUploadReport.of(getProject());
// return links == null ? ImmutableSet.<String>of() : links.getStorageObjects();
// }
//
// /** {@inheritDoc} */
// @Override
// public Integer getBuildNumber() {
// BuildGcsUploadReport links = BuildGcsUploadReport.of(getProject());
// return links == null ? null : links.getBuildNumber();
// }
// }
|
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.jenkins.plugins.storage.AbstractUploadDescriptor.GCS_SCHEME;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.domains.RequiresDomain;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import com.google.jenkins.plugins.storage.reports.ProjectGcsUploadReport;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.kohsuke.stapler.DataBoundConstructor;
|
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage;
/** A Jenkins plugin for uploading files to Google Cloud Storage (GCS). */
@RequiresDomain(value = StorageScopeRequirement.class)
public class GoogleCloudStorageUploader extends Recorder {
private final String credentialsId;
private final List<AbstractUpload> uploads;
/**
* Construct the GCS uploader to use the provided credentials to upload build artifacts.
*
* @param credentialsId The credentials to utilize for authenticating with GCS
* @param uploads The list of uploads the user has requested be done
*/
@DataBoundConstructor
public GoogleCloudStorageUploader(String credentialsId, @Nullable List<AbstractUpload> uploads) {
this.credentialsId = checkNotNull(credentialsId);
if (uploads == null) {
this.uploads = ImmutableList.<AbstractUpload>of();
} else {
checkArgument(uploads.size() > 0);
this.uploads = uploads;
}
}
/** @return The unique ID for the credentials we are using to authenticate with GCS. */
public String getCredentialsId() {
return credentialsId;
}
/** @return The credentials we are using to authenticate with GCS. */
public GoogleRobotCredentials getCredentials() {
return GoogleRobotCredentials.getById(getCredentialsId());
}
/** @return The set of tuples describing the artifacts to upload, and where to upload them. */
public Collection<AbstractUpload> getUploads() {
return Collections.unmodifiableCollection(uploads);
}
/** {@inheritDoc} */
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws IOException, InterruptedException {
// TODO(mattmoor): threadpool?
boolean result = true;
for (AbstractUpload upload : uploads) {
try {
upload.perform(getCredentialsId(), build, listener);
} catch (UploadException e) {
e.printStackTrace(
listener.error(
Messages.StorageUtil_PrefixFormat(
getDescriptor().getDisplayName(),
Messages.GoogleCloudStorageUploader_ExceptionDuringUpload(e.getMessage()))));
build.setResult(Result.FAILURE);
result = false;
}
}
return result;
}
/** {@inheritDoc} */
@Override
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
/** {@inheritDoc} */
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
/** Descriptor for the extension for uploading build artifacts to Google Cloud Storage. */
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
/** {@inheritDoc} */
@Override
public boolean isApplicable(
@SuppressWarnings("rawtypes") Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/** {@inheritDoc} */
@Override
public String getDisplayName() {
return Messages.GoogleCloudStorageUploader_DisplayName();
}
/**
* @return the default uploads when the user configure {@link GoogleCloudStorageUploader} for
* the first time.
*/
public List<AbstractUpload> getDefaultUploads() {
StdoutUpload upload =
new StdoutUpload(
|
// Path: src/main/java/com/google/jenkins/plugins/storage/AbstractUploadDescriptor.java
// public static final String GCS_SCHEME = "gs://";
//
// Path: src/main/java/com/google/jenkins/plugins/storage/reports/ProjectGcsUploadReport.java
// public class ProjectGcsUploadReport extends AbstractGcsUploadReport {
//
// public ProjectGcsUploadReport(AbstractProject<?, ?> project) {
// super(project);
// }
//
// /** @return the project that this {@link ProjectGcsUploadReport} belongs to. */
// public AbstractProject<?, ?> getProject() {
// return (AbstractProject<?, ?>) getParent();
// }
//
// /** {@inheritDoc} */
// @Override
// public Set<String> getBuckets() {
// BuildGcsUploadReport links = BuildGcsUploadReport.of(getProject());
// return links == null ? ImmutableSet.<String>of() : links.getBuckets();
// }
//
// /** {@inheritDoc} */
// @Override
// public Set<String> getStorageObjects() {
// BuildGcsUploadReport links = BuildGcsUploadReport.of(getProject());
// return links == null ? ImmutableSet.<String>of() : links.getStorageObjects();
// }
//
// /** {@inheritDoc} */
// @Override
// public Integer getBuildNumber() {
// BuildGcsUploadReport links = BuildGcsUploadReport.of(getProject());
// return links == null ? null : links.getBuildNumber();
// }
// }
// Path: src/main/java/com/google/jenkins/plugins/storage/GoogleCloudStorageUploader.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.jenkins.plugins.storage.AbstractUploadDescriptor.GCS_SCHEME;
import com.google.common.collect.ImmutableList;
import com.google.jenkins.plugins.credentials.domains.RequiresDomain;
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials;
import com.google.jenkins.plugins.storage.reports.ProjectGcsUploadReport;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.kohsuke.stapler.DataBoundConstructor;
/*
* Copyright 2013 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.jenkins.plugins.storage;
/** A Jenkins plugin for uploading files to Google Cloud Storage (GCS). */
@RequiresDomain(value = StorageScopeRequirement.class)
public class GoogleCloudStorageUploader extends Recorder {
private final String credentialsId;
private final List<AbstractUpload> uploads;
/**
* Construct the GCS uploader to use the provided credentials to upload build artifacts.
*
* @param credentialsId The credentials to utilize for authenticating with GCS
* @param uploads The list of uploads the user has requested be done
*/
@DataBoundConstructor
public GoogleCloudStorageUploader(String credentialsId, @Nullable List<AbstractUpload> uploads) {
this.credentialsId = checkNotNull(credentialsId);
if (uploads == null) {
this.uploads = ImmutableList.<AbstractUpload>of();
} else {
checkArgument(uploads.size() > 0);
this.uploads = uploads;
}
}
/** @return The unique ID for the credentials we are using to authenticate with GCS. */
public String getCredentialsId() {
return credentialsId;
}
/** @return The credentials we are using to authenticate with GCS. */
public GoogleRobotCredentials getCredentials() {
return GoogleRobotCredentials.getById(getCredentialsId());
}
/** @return The set of tuples describing the artifacts to upload, and where to upload them. */
public Collection<AbstractUpload> getUploads() {
return Collections.unmodifiableCollection(uploads);
}
/** {@inheritDoc} */
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws IOException, InterruptedException {
// TODO(mattmoor): threadpool?
boolean result = true;
for (AbstractUpload upload : uploads) {
try {
upload.perform(getCredentialsId(), build, listener);
} catch (UploadException e) {
e.printStackTrace(
listener.error(
Messages.StorageUtil_PrefixFormat(
getDescriptor().getDisplayName(),
Messages.GoogleCloudStorageUploader_ExceptionDuringUpload(e.getMessage()))));
build.setResult(Result.FAILURE);
result = false;
}
}
return result;
}
/** {@inheritDoc} */
@Override
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
/** {@inheritDoc} */
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
/** Descriptor for the extension for uploading build artifacts to Google Cloud Storage. */
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
/** {@inheritDoc} */
@Override
public boolean isApplicable(
@SuppressWarnings("rawtypes") Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/** {@inheritDoc} */
@Override
public String getDisplayName() {
return Messages.GoogleCloudStorageUploader_DisplayName();
}
/**
* @return the default uploads when the user configure {@link GoogleCloudStorageUploader} for
* the first time.
*/
public List<AbstractUpload> getDefaultUploads() {
StdoutUpload upload =
new StdoutUpload(
|
GCS_SCHEME, null, "build-log.txt", null /* legacy arg: bucketNameWithVars */);
|
chucknorris-io/chuck-api
|
src/main/java/io/chucknorris/lib/mailchimp/MailingList.java
|
// Path: src/main/java/io/chucknorris/lib/mailchimp/MailingListStatistic.java
// @Data
// public class MailingListStatistic implements Serializable {
//
// @JsonProperty("member_count")
// private AtomicInteger memberCount;
//
// @JsonProperty("unsubscribe_count")
// private AtomicInteger unsubscribeCount;
//
// @JsonProperty("cleaned_count")
// private AtomicInteger cleanedCount;
//
// @JsonProperty("member_count_since_send")
// private AtomicInteger memberCountSinceSend;
//
// @JsonProperty("unsubscribe_count_since_send")
// private AtomicInteger unsubscribeCountSinceSend;
//
// @JsonProperty("cleaned_count_since_send")
// private AtomicInteger cleanedCountSinceSend;
//
// @JsonProperty("campaign_count")
// private AtomicInteger campaignCount;
//
// @JsonProperty("campaign_last_sent")
// private Date campaignLastSent;
//
// @JsonProperty("merge_field_count")
// private AtomicInteger mergeFieldCount;
//
// @JsonProperty("avg_sub_rate")
// private AtomicInteger avgSubRate;
//
// @JsonProperty("avg_unsub_rate")
// private AtomicInteger avgUnsubRate;
//
// @JsonProperty("target_sub_rate")
// private AtomicInteger targetSubRate;
//
// @JsonProperty("openRate")
// private AtomicDouble openRate;
//
// @JsonProperty("click_rate")
// private AtomicDouble clickRate;
//
// @JsonProperty("last_sub_date")
// private Date lastDubDate;
//
// @JsonProperty("last_unsub_date")
// private Date lastUnsubDate;
// }
|
import com.fasterxml.jackson.annotation.JsonProperty;
import io.chucknorris.lib.mailchimp.MailingListStatistic;
import java.io.Serializable;
import lombok.Data;
|
package io.chucknorris.lib.mailchimp;
@Data
public class MailingList implements Serializable {
@JsonProperty("id")
private String id;
@JsonProperty("stats")
|
// Path: src/main/java/io/chucknorris/lib/mailchimp/MailingListStatistic.java
// @Data
// public class MailingListStatistic implements Serializable {
//
// @JsonProperty("member_count")
// private AtomicInteger memberCount;
//
// @JsonProperty("unsubscribe_count")
// private AtomicInteger unsubscribeCount;
//
// @JsonProperty("cleaned_count")
// private AtomicInteger cleanedCount;
//
// @JsonProperty("member_count_since_send")
// private AtomicInteger memberCountSinceSend;
//
// @JsonProperty("unsubscribe_count_since_send")
// private AtomicInteger unsubscribeCountSinceSend;
//
// @JsonProperty("cleaned_count_since_send")
// private AtomicInteger cleanedCountSinceSend;
//
// @JsonProperty("campaign_count")
// private AtomicInteger campaignCount;
//
// @JsonProperty("campaign_last_sent")
// private Date campaignLastSent;
//
// @JsonProperty("merge_field_count")
// private AtomicInteger mergeFieldCount;
//
// @JsonProperty("avg_sub_rate")
// private AtomicInteger avgSubRate;
//
// @JsonProperty("avg_unsub_rate")
// private AtomicInteger avgUnsubRate;
//
// @JsonProperty("target_sub_rate")
// private AtomicInteger targetSubRate;
//
// @JsonProperty("openRate")
// private AtomicDouble openRate;
//
// @JsonProperty("click_rate")
// private AtomicDouble clickRate;
//
// @JsonProperty("last_sub_date")
// private Date lastDubDate;
//
// @JsonProperty("last_unsub_date")
// private Date lastUnsubDate;
// }
// Path: src/main/java/io/chucknorris/lib/mailchimp/MailingList.java
import com.fasterxml.jackson.annotation.JsonProperty;
import io.chucknorris.lib.mailchimp.MailingListStatistic;
import java.io.Serializable;
import lombok.Data;
package io.chucknorris.lib.mailchimp;
@Data
public class MailingList implements Serializable {
@JsonProperty("id")
private String id;
@JsonProperty("stats")
|
private MailingListStatistic mailingListStatistic;
|
chucknorris-io/chuck-api
|
src/test/java/io/chucknorris/api/joke/JokeControllerTest.java
|
// Path: src/main/java/io/chucknorris/lib/exception/EntityNotFoundException.java
// @ResponseStatus(value = HttpStatus.NOT_FOUND)
// public class EntityNotFoundException extends RuntimeException {
//
// public EntityNotFoundException(String message) {
// super(message);
// }
// }
|
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import io.chucknorris.lib.exception.EntityNotFoundException;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
|
assertEquals("dev", categories[0]);
assertEquals("animal", categories[1]);
assertEquals(2, categories.length);
verify(jokeRepository, times(1)).findAllCategories();
verifyNoMoreInteractions(jokeRepository);
}
@Test
public void testGetCategoryValues() {
when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev", "animal"});
String categoryValues = jokeController.getCategoryValues();
assertEquals("dev\nanimal\n", categoryValues);
verify(jokeRepository, times(1)).findAllCategories();
verifyNoMoreInteractions(jokeRepository);
}
@Test
public void testGetJokeReturnsJoke() {
when(jokeRepository.findById(jokeId)).thenReturn(Optional.of(joke));
Joke joke = jokeController.getJoke(jokeId);
assertEquals(JokeControllerTest.joke, joke);
verify(jokeRepository, times(1)).findById(jokeId);
verifyNoMoreInteractions(jokeRepository);
}
|
// Path: src/main/java/io/chucknorris/lib/exception/EntityNotFoundException.java
// @ResponseStatus(value = HttpStatus.NOT_FOUND)
// public class EntityNotFoundException extends RuntimeException {
//
// public EntityNotFoundException(String message) {
// super(message);
// }
// }
// Path: src/test/java/io/chucknorris/api/joke/JokeControllerTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import io.chucknorris.lib.exception.EntityNotFoundException;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
assertEquals("dev", categories[0]);
assertEquals("animal", categories[1]);
assertEquals(2, categories.length);
verify(jokeRepository, times(1)).findAllCategories();
verifyNoMoreInteractions(jokeRepository);
}
@Test
public void testGetCategoryValues() {
when(jokeRepository.findAllCategories()).thenReturn(new String[]{"dev", "animal"});
String categoryValues = jokeController.getCategoryValues();
assertEquals("dev\nanimal\n", categoryValues);
verify(jokeRepository, times(1)).findAllCategories();
verifyNoMoreInteractions(jokeRepository);
}
@Test
public void testGetJokeReturnsJoke() {
when(jokeRepository.findById(jokeId)).thenReturn(Optional.of(joke));
Joke joke = jokeController.getJoke(jokeId);
assertEquals(JokeControllerTest.joke, joke);
verify(jokeRepository, times(1)).findById(jokeId);
verifyNoMoreInteractions(jokeRepository);
}
|
@Test(expected = EntityNotFoundException.class)
|
chucknorris-io/chuck-api
|
src/main/java/io/chucknorris/api/configuration/MailchimpConfig.java
|
// Path: src/main/java/io/chucknorris/lib/mailchimp/MailchimpService.java
// public class MailchimpService {
//
// private String apiKey;
// private String baseUrl;
//
// @Autowired
// private RestTemplate restTemplate;
//
// public MailchimpService(String apiKey, String baseUrl) {
// this.apiKey = apiKey;
// this.baseUrl = baseUrl;
// }
//
// /**
// * Fetch mailing list stats by a given list id.
// *
// * @param listId The list id
// * @return list
// */
// public MailingListStatistic fetchListStats(final String listId) {
// return fetchList(listId).getMailingListStatistic();
// }
//
// private MailingList fetchList(final String listId) {
// HttpHeaders headers = new HttpHeaders();
// headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
// headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
// headers.add(HttpHeaders.AUTHORIZATION, "apikey " + this.apiKey);
//
// ResponseEntity<MailingList> responseEntity = restTemplate.exchange(
// baseUrl + "/3.0/lists/" + listId,
// HttpMethod.GET,
// new HttpEntity<>(null, headers),
// MailingList.class
// );
//
// return responseEntity.getBody();
// }
// }
|
import io.chucknorris.lib.mailchimp.MailchimpService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
|
package io.chucknorris.api.configuration;
@Configuration
public class MailchimpConfig {
@Value("${mailchimp.api_key}")
private String apiKey;
/**
* Returns a new {@link MailchimpService} instance.
*/
|
// Path: src/main/java/io/chucknorris/lib/mailchimp/MailchimpService.java
// public class MailchimpService {
//
// private String apiKey;
// private String baseUrl;
//
// @Autowired
// private RestTemplate restTemplate;
//
// public MailchimpService(String apiKey, String baseUrl) {
// this.apiKey = apiKey;
// this.baseUrl = baseUrl;
// }
//
// /**
// * Fetch mailing list stats by a given list id.
// *
// * @param listId The list id
// * @return list
// */
// public MailingListStatistic fetchListStats(final String listId) {
// return fetchList(listId).getMailingListStatistic();
// }
//
// private MailingList fetchList(final String listId) {
// HttpHeaders headers = new HttpHeaders();
// headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
// headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
// headers.add(HttpHeaders.AUTHORIZATION, "apikey " + this.apiKey);
//
// ResponseEntity<MailingList> responseEntity = restTemplate.exchange(
// baseUrl + "/3.0/lists/" + listId,
// HttpMethod.GET,
// new HttpEntity<>(null, headers),
// MailingList.class
// );
//
// return responseEntity.getBody();
// }
// }
// Path: src/main/java/io/chucknorris/api/configuration/MailchimpConfig.java
import io.chucknorris.lib.mailchimp.MailchimpService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
package io.chucknorris.api.configuration;
@Configuration
public class MailchimpConfig {
@Value("${mailchimp.api_key}")
private String apiKey;
/**
* Returns a new {@link MailchimpService} instance.
*/
|
public @Bean MailchimpService mailchimpService() {
|
chucknorris-io/chuck-api
|
src/main/java/io/chucknorris/api/joke/JokeController.java
|
// Path: src/main/java/io/chucknorris/lib/exception/EntityNotFoundException.java
// @ResponseStatus(value = HttpStatus.NOT_FOUND)
// public class EntityNotFoundException extends RuntimeException {
//
// public EntityNotFoundException(String message) {
// super(message);
// }
// }
|
import io.chucknorris.lib.exception.EntityNotFoundException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
|
* Returns all joke categories delimited by a new line.
*/
public @ResponseBody @RequestMapping(
value = "/categories",
method = RequestMethod.GET,
headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_PLAIN_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE
) String getCategoryValues() {
StringBuilder stringBuilder = new StringBuilder();
for (String category : jokeRepository.findAllCategories()) {
stringBuilder.append(category + '\n');
}
return stringBuilder.toString();
}
/**
* Returns a Joke {@link Joke} by id.
*
* @param id The joke id
* @return joke
*/
public @ResponseBody @RequestMapping(
value = "/{id}",
method = RequestMethod.GET,
headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
) Joke getJoke(@PathVariable String id) {
return jokeRepository.findById(id).orElseThrow(
|
// Path: src/main/java/io/chucknorris/lib/exception/EntityNotFoundException.java
// @ResponseStatus(value = HttpStatus.NOT_FOUND)
// public class EntityNotFoundException extends RuntimeException {
//
// public EntityNotFoundException(String message) {
// super(message);
// }
// }
// Path: src/main/java/io/chucknorris/api/joke/JokeController.java
import io.chucknorris.lib.exception.EntityNotFoundException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
* Returns all joke categories delimited by a new line.
*/
public @ResponseBody @RequestMapping(
value = "/categories",
method = RequestMethod.GET,
headers = HttpHeaders.ACCEPT + "=" + MediaType.TEXT_PLAIN_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE
) String getCategoryValues() {
StringBuilder stringBuilder = new StringBuilder();
for (String category : jokeRepository.findAllCategories()) {
stringBuilder.append(category + '\n');
}
return stringBuilder.toString();
}
/**
* Returns a Joke {@link Joke} by id.
*
* @param id The joke id
* @return joke
*/
public @ResponseBody @RequestMapping(
value = "/{id}",
method = RequestMethod.GET,
headers = HttpHeaders.ACCEPT + "=" + MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
) Joke getJoke(@PathVariable String id) {
return jokeRepository.findById(id).orElseThrow(
|
() -> new EntityNotFoundException("Joke with id \"" + id + "\" not found.")
|
chucknorris-io/chuck-api
|
src/main/java/io/chucknorris/api/configuration/ResolverConfig.java
|
// Path: src/main/java/io/chucknorris/api/slack/RequestArgumentResolver.java
// public class RequestArgumentResolver implements HandlerMethodArgumentResolver {
//
// @Override
// public boolean supportsParameter(MethodParameter methodParameter) {
// return methodParameter.getParameterType().equals(Request.class);
// }
//
// @Override
// public Object resolveArgument(MethodParameter methodParameter,
// ModelAndViewContainer modelAndViewContainer,
// NativeWebRequest nativeWebRequest,
// WebDataBinderFactory webDataBinderFactory) {
// Request request = new Request();
//
// request.setChannelId(nativeWebRequest.getParameter("channel_id"));
// request.setChannelName(nativeWebRequest.getParameter("channel_name"));
// request.setCommand(nativeWebRequest.getParameter("command"));
// request.setEnterpriseId(nativeWebRequest.getParameter("enterprise_id"));
// request.setEnterpriseName(nativeWebRequest.getParameter("enterprise_name"));
// request.setResponseUrl(nativeWebRequest.getParameter("response_url"));
// request.setTeamDomain(nativeWebRequest.getParameter("team_domain"));
// request.setTeamId(nativeWebRequest.getParameter("team_id"));
// request.setText(nativeWebRequest.getParameter("text"));
// request.setToken(nativeWebRequest.getParameter("token"));
// request.setTriggerId(nativeWebRequest.getParameter("trigger_id"));
// request.setUserId(nativeWebRequest.getParameter("user_id"));
// request.setUserName(nativeWebRequest.getParameter("user_name"));
//
// return request;
// }
// }
|
import io.chucknorris.api.slack.RequestArgumentResolver;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
package io.chucknorris.api.configuration;
@Configuration
public class ResolverConfig implements WebMvcConfigurer {
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
|
// Path: src/main/java/io/chucknorris/api/slack/RequestArgumentResolver.java
// public class RequestArgumentResolver implements HandlerMethodArgumentResolver {
//
// @Override
// public boolean supportsParameter(MethodParameter methodParameter) {
// return methodParameter.getParameterType().equals(Request.class);
// }
//
// @Override
// public Object resolveArgument(MethodParameter methodParameter,
// ModelAndViewContainer modelAndViewContainer,
// NativeWebRequest nativeWebRequest,
// WebDataBinderFactory webDataBinderFactory) {
// Request request = new Request();
//
// request.setChannelId(nativeWebRequest.getParameter("channel_id"));
// request.setChannelName(nativeWebRequest.getParameter("channel_name"));
// request.setCommand(nativeWebRequest.getParameter("command"));
// request.setEnterpriseId(nativeWebRequest.getParameter("enterprise_id"));
// request.setEnterpriseName(nativeWebRequest.getParameter("enterprise_name"));
// request.setResponseUrl(nativeWebRequest.getParameter("response_url"));
// request.setTeamDomain(nativeWebRequest.getParameter("team_domain"));
// request.setTeamId(nativeWebRequest.getParameter("team_id"));
// request.setText(nativeWebRequest.getParameter("text"));
// request.setToken(nativeWebRequest.getParameter("token"));
// request.setTriggerId(nativeWebRequest.getParameter("trigger_id"));
// request.setUserId(nativeWebRequest.getParameter("user_id"));
// request.setUserName(nativeWebRequest.getParameter("user_name"));
//
// return request;
// }
// }
// Path: src/main/java/io/chucknorris/api/configuration/ResolverConfig.java
import io.chucknorris.api.slack.RequestArgumentResolver;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
package io.chucknorris.api.configuration;
@Configuration
public class ResolverConfig implements WebMvcConfigurer {
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
|
argumentResolvers.add(new RequestArgumentResolver());
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/model/PutObjectResult.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Consts.java
// public final class Consts {
// public static final String XIAOMI_HEADER_PREFIX = "x-xiaomi-";
// public static final String XIAOMI_META_HEADER_PREFIX = XIAOMI_HEADER_PREFIX
// + "meta-";
// public static final String ESTIMATED_OBJECT_SIZE = XIAOMI_HEADER_PREFIX
// + "estimated-object-size";
// public static final String GALAXY_ACCESS_KEY_ID = "GalaxyAccessKeyId";
// public static final String SIGNATURE = "Signature";
// public static final String EXPIRES = "Expires";
// public static String APPLICATION_OCTET_STREAM = "application/octet-stream";
// }
|
import com.xiaomi.infra.galaxy.fds.android.util.Consts;
|
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public long getExpires() {
return expires;
}
public void setExpires(long expires) {
this.expires = expires;
}
public void setFdsServiceBaseUri(String fdsServiceBaseUri) {
this.fdsServiceBaseUri = fdsServiceBaseUri;
}
public void setCdnServiceBaseUri(String cdnServiceBaseUri) {
this.cdnServiceBaseUri = cdnServiceBaseUri;
}
public String getRelativePresignedUri() {
return "/" + bucketName + "/" + objectName + "?"
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Consts.java
// public final class Consts {
// public static final String XIAOMI_HEADER_PREFIX = "x-xiaomi-";
// public static final String XIAOMI_META_HEADER_PREFIX = XIAOMI_HEADER_PREFIX
// + "meta-";
// public static final String ESTIMATED_OBJECT_SIZE = XIAOMI_HEADER_PREFIX
// + "estimated-object-size";
// public static final String GALAXY_ACCESS_KEY_ID = "GalaxyAccessKeyId";
// public static final String SIGNATURE = "Signature";
// public static final String EXPIRES = "Expires";
// public static String APPLICATION_OCTET_STREAM = "application/octet-stream";
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/PutObjectResult.java
import com.xiaomi.infra.galaxy.fds.android.util.Consts;
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public long getExpires() {
return expires;
}
public void setExpires(long expires) {
this.expires = expires;
}
public void setFdsServiceBaseUri(String fdsServiceBaseUri) {
this.fdsServiceBaseUri = fdsServiceBaseUri;
}
public void setCdnServiceBaseUri(String cdnServiceBaseUri) {
this.cdnServiceBaseUri = cdnServiceBaseUri;
}
public String getRelativePresignedUri() {
return "/" + bucketName + "/" + objectName + "?"
|
+ Consts.GALAXY_ACCESS_KEY_ID + "=" + accessKeyId + "&" + Consts.EXPIRES
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Util.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/FDSObject.java
// public class FDSObject implements Closeable {
//
// /**
// * The name of the object
// */
// private final String objectName;
//
// /**
// * The name of the bucket in which this object is contained
// */
// private final String bucketName;
//
// /**
// * The metadata stored by Galaxy FDS for this object
// */
// private ObjectMetadata metadata;
//
// /**
// * The stream containing the contents of this object from FDS
// */
// private InputStream objectContent;
//
// public FDSObject(String bucketName, String objectName) {
// this.bucketName = bucketName;
// this.objectName = objectName;
// }
//
// /**
// * Gets the name of the object
// *
// * @return The name of the object
// */
// public String getObjectName() {
// return objectName;
// }
//
// /**
// * Gets the name of the bucket in which this object is contained.
// *
// * @return The name of the bucket in which this object is contained.
// */
// public String getBucketName() {
// return bucketName;
// }
//
// /**
// * Gets the metadata stored by Galaxy FDS for this object. The
// * {@link ObjectMetadata} object includes any custom user metadata supplied by
// * the caller when the object was uploaded, as well as HTTP metadata such as
// * content length and content type.
// *
// * @return The metadata stored by Galaxy FDS for this object.
// * @see FDSObject#getObjectContent()
// */
// public ObjectMetadata getObjectMetadata() {
// return metadata;
// }
//
// /**
// * Sets the object metadata for this object in memory.
// * <p/>
// * <b>NOTE:</b> This does not update the object metadata stored in Galaxy
// * FDS, but only updates this object in local memory.
// *
// * @param metadata The new metadata to set for this object in memory.
// */
// public void setObjectMetadata(ObjectMetadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// * Gets an input stream containing the contents of this object. Callers should
// * close this input stream as soon as possible, because the object contents
// * aren't buffered in memory and stream directly from Galaxy FDS.
// *
// * @return An input stream containing the contents of this object.
// * @see FDSObject#setObjectContent(InputStream)
// */
// public InputStream getObjectContent() {
// return objectContent;
// }
//
// /**
// * Sets the input stream containing this object's contents.
// *
// * @param objectContent The input stream containing this object's contents.
// * @see FDSObject#getObjectContent()
// */
// public void setObjectContent(InputStream objectContent) {
// this.objectContent = objectContent;
// }
//
// /**
// * Releases any underlying system resources. If the resources are already
// * released then invoking this method has no effect.
// */
// @Override
// public void close() {
// if (objectContent != null) {
// try {
// objectContent.close();
// } catch (IOException e) {
// // ignored
// }
// }
// }
// }
|
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import android.webkit.MimeTypeMap;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.FDSObject;
|
package com.xiaomi.infra.galaxy.fds.android.util;
public class Util {
private static final int BUFFER_SIZE = 4096;
private static final ThreadLocal<SimpleDateFormat> DATE_FOPMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat format = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format;
}
};
/**
* Download an object to the specified file
*
* @param object The FDS object contains a reference to an
* InputStream contains the object's data
* @param destinationFile The file to store the object's data
* @param isAppend If append to the end of the file or overwrite it
* @throws GalaxyFDSClientException
*/
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/FDSObject.java
// public class FDSObject implements Closeable {
//
// /**
// * The name of the object
// */
// private final String objectName;
//
// /**
// * The name of the bucket in which this object is contained
// */
// private final String bucketName;
//
// /**
// * The metadata stored by Galaxy FDS for this object
// */
// private ObjectMetadata metadata;
//
// /**
// * The stream containing the contents of this object from FDS
// */
// private InputStream objectContent;
//
// public FDSObject(String bucketName, String objectName) {
// this.bucketName = bucketName;
// this.objectName = objectName;
// }
//
// /**
// * Gets the name of the object
// *
// * @return The name of the object
// */
// public String getObjectName() {
// return objectName;
// }
//
// /**
// * Gets the name of the bucket in which this object is contained.
// *
// * @return The name of the bucket in which this object is contained.
// */
// public String getBucketName() {
// return bucketName;
// }
//
// /**
// * Gets the metadata stored by Galaxy FDS for this object. The
// * {@link ObjectMetadata} object includes any custom user metadata supplied by
// * the caller when the object was uploaded, as well as HTTP metadata such as
// * content length and content type.
// *
// * @return The metadata stored by Galaxy FDS for this object.
// * @see FDSObject#getObjectContent()
// */
// public ObjectMetadata getObjectMetadata() {
// return metadata;
// }
//
// /**
// * Sets the object metadata for this object in memory.
// * <p/>
// * <b>NOTE:</b> This does not update the object metadata stored in Galaxy
// * FDS, but only updates this object in local memory.
// *
// * @param metadata The new metadata to set for this object in memory.
// */
// public void setObjectMetadata(ObjectMetadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// * Gets an input stream containing the contents of this object. Callers should
// * close this input stream as soon as possible, because the object contents
// * aren't buffered in memory and stream directly from Galaxy FDS.
// *
// * @return An input stream containing the contents of this object.
// * @see FDSObject#setObjectContent(InputStream)
// */
// public InputStream getObjectContent() {
// return objectContent;
// }
//
// /**
// * Sets the input stream containing this object's contents.
// *
// * @param objectContent The input stream containing this object's contents.
// * @see FDSObject#getObjectContent()
// */
// public void setObjectContent(InputStream objectContent) {
// this.objectContent = objectContent;
// }
//
// /**
// * Releases any underlying system resources. If the resources are already
// * released then invoking this method has no effect.
// */
// @Override
// public void close() {
// if (objectContent != null) {
// try {
// objectContent.close();
// } catch (IOException e) {
// // ignored
// }
// }
// }
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Util.java
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import android.webkit.MimeTypeMap;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.FDSObject;
package com.xiaomi.infra.galaxy.fds.android.util;
public class Util {
private static final int BUFFER_SIZE = 4096;
private static final ThreadLocal<SimpleDateFormat> DATE_FOPMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat format = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format;
}
};
/**
* Download an object to the specified file
*
* @param object The FDS object contains a reference to an
* InputStream contains the object's data
* @param destinationFile The file to store the object's data
* @param isAppend If append to the end of the file or overwrite it
* @throws GalaxyFDSClientException
*/
|
public static void downloadObjectToFile(FDSObject object,
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Util.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/FDSObject.java
// public class FDSObject implements Closeable {
//
// /**
// * The name of the object
// */
// private final String objectName;
//
// /**
// * The name of the bucket in which this object is contained
// */
// private final String bucketName;
//
// /**
// * The metadata stored by Galaxy FDS for this object
// */
// private ObjectMetadata metadata;
//
// /**
// * The stream containing the contents of this object from FDS
// */
// private InputStream objectContent;
//
// public FDSObject(String bucketName, String objectName) {
// this.bucketName = bucketName;
// this.objectName = objectName;
// }
//
// /**
// * Gets the name of the object
// *
// * @return The name of the object
// */
// public String getObjectName() {
// return objectName;
// }
//
// /**
// * Gets the name of the bucket in which this object is contained.
// *
// * @return The name of the bucket in which this object is contained.
// */
// public String getBucketName() {
// return bucketName;
// }
//
// /**
// * Gets the metadata stored by Galaxy FDS for this object. The
// * {@link ObjectMetadata} object includes any custom user metadata supplied by
// * the caller when the object was uploaded, as well as HTTP metadata such as
// * content length and content type.
// *
// * @return The metadata stored by Galaxy FDS for this object.
// * @see FDSObject#getObjectContent()
// */
// public ObjectMetadata getObjectMetadata() {
// return metadata;
// }
//
// /**
// * Sets the object metadata for this object in memory.
// * <p/>
// * <b>NOTE:</b> This does not update the object metadata stored in Galaxy
// * FDS, but only updates this object in local memory.
// *
// * @param metadata The new metadata to set for this object in memory.
// */
// public void setObjectMetadata(ObjectMetadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// * Gets an input stream containing the contents of this object. Callers should
// * close this input stream as soon as possible, because the object contents
// * aren't buffered in memory and stream directly from Galaxy FDS.
// *
// * @return An input stream containing the contents of this object.
// * @see FDSObject#setObjectContent(InputStream)
// */
// public InputStream getObjectContent() {
// return objectContent;
// }
//
// /**
// * Sets the input stream containing this object's contents.
// *
// * @param objectContent The input stream containing this object's contents.
// * @see FDSObject#getObjectContent()
// */
// public void setObjectContent(InputStream objectContent) {
// this.objectContent = objectContent;
// }
//
// /**
// * Releases any underlying system resources. If the resources are already
// * released then invoking this method has no effect.
// */
// @Override
// public void close() {
// if (objectContent != null) {
// try {
// objectContent.close();
// } catch (IOException e) {
// // ignored
// }
// }
// }
// }
|
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import android.webkit.MimeTypeMap;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.FDSObject;
|
package com.xiaomi.infra.galaxy.fds.android.util;
public class Util {
private static final int BUFFER_SIZE = 4096;
private static final ThreadLocal<SimpleDateFormat> DATE_FOPMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat format = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format;
}
};
/**
* Download an object to the specified file
*
* @param object The FDS object contains a reference to an
* InputStream contains the object's data
* @param destinationFile The file to store the object's data
* @param isAppend If append to the end of the file or overwrite it
* @throws GalaxyFDSClientException
*/
public static void downloadObjectToFile(FDSObject object,
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/FDSObject.java
// public class FDSObject implements Closeable {
//
// /**
// * The name of the object
// */
// private final String objectName;
//
// /**
// * The name of the bucket in which this object is contained
// */
// private final String bucketName;
//
// /**
// * The metadata stored by Galaxy FDS for this object
// */
// private ObjectMetadata metadata;
//
// /**
// * The stream containing the contents of this object from FDS
// */
// private InputStream objectContent;
//
// public FDSObject(String bucketName, String objectName) {
// this.bucketName = bucketName;
// this.objectName = objectName;
// }
//
// /**
// * Gets the name of the object
// *
// * @return The name of the object
// */
// public String getObjectName() {
// return objectName;
// }
//
// /**
// * Gets the name of the bucket in which this object is contained.
// *
// * @return The name of the bucket in which this object is contained.
// */
// public String getBucketName() {
// return bucketName;
// }
//
// /**
// * Gets the metadata stored by Galaxy FDS for this object. The
// * {@link ObjectMetadata} object includes any custom user metadata supplied by
// * the caller when the object was uploaded, as well as HTTP metadata such as
// * content length and content type.
// *
// * @return The metadata stored by Galaxy FDS for this object.
// * @see FDSObject#getObjectContent()
// */
// public ObjectMetadata getObjectMetadata() {
// return metadata;
// }
//
// /**
// * Sets the object metadata for this object in memory.
// * <p/>
// * <b>NOTE:</b> This does not update the object metadata stored in Galaxy
// * FDS, but only updates this object in local memory.
// *
// * @param metadata The new metadata to set for this object in memory.
// */
// public void setObjectMetadata(ObjectMetadata metadata) {
// this.metadata = metadata;
// }
//
// /**
// * Gets an input stream containing the contents of this object. Callers should
// * close this input stream as soon as possible, because the object contents
// * aren't buffered in memory and stream directly from Galaxy FDS.
// *
// * @return An input stream containing the contents of this object.
// * @see FDSObject#setObjectContent(InputStream)
// */
// public InputStream getObjectContent() {
// return objectContent;
// }
//
// /**
// * Sets the input stream containing this object's contents.
// *
// * @param objectContent The input stream containing this object's contents.
// * @see FDSObject#getObjectContent()
// */
// public void setObjectContent(InputStream objectContent) {
// this.objectContent = objectContent;
// }
//
// /**
// * Releases any underlying system resources. If the resources are already
// * released then invoking this method has no effect.
// */
// @Override
// public void close() {
// if (objectContent != null) {
// try {
// objectContent.close();
// } catch (IOException e) {
// // ignored
// }
// }
// }
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Util.java
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import android.webkit.MimeTypeMap;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.FDSObject;
package com.xiaomi.infra.galaxy.fds.android.util;
public class Util {
private static final int BUFFER_SIZE = 4096;
private static final ThreadLocal<SimpleDateFormat> DATE_FOPMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat format = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format;
}
};
/**
* Download an object to the specified file
*
* @param object The FDS object contains a reference to an
* InputStream contains the object's data
* @param destinationFile The file to store the object's data
* @param isAppend If append to the end of the file or overwrite it
* @throws GalaxyFDSClientException
*/
public static void downloadObjectToFile(FDSObject object,
|
File destinationFile, boolean isAppend) throws GalaxyFDSClientException {
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/util/RequestFactory.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/GalaxyFDSCredential.java
// public interface GalaxyFDSCredential {
//
// /**
// * Add HTTP header to request
// * @param request
// */
// void addHeader(HttpRequestBase request) throws GalaxyFDSClientException;
//
// /**
// * Adds parameter to the URL string
// * @param uri
// * @return
// */
// String addParam(String uri);
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
|
import java.util.Date;
import java.util.Map;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import com.xiaomi.infra.galaxy.fds.android.auth.GalaxyFDSCredential;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.model.HttpMethod;
|
package com.xiaomi.infra.galaxy.fds.android.util;
public class RequestFactory {
public static HttpUriRequest createRequest(String uri,
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/GalaxyFDSCredential.java
// public interface GalaxyFDSCredential {
//
// /**
// * Add HTTP header to request
// * @param request
// */
// void addHeader(HttpRequestBase request) throws GalaxyFDSClientException;
//
// /**
// * Adds parameter to the URL string
// * @param uri
// * @return
// */
// String addParam(String uri);
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/RequestFactory.java
import java.util.Date;
import java.util.Map;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import com.xiaomi.infra.galaxy.fds.android.auth.GalaxyFDSCredential;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.model.HttpMethod;
package com.xiaomi.infra.galaxy.fds.android.util;
public class RequestFactory {
public static HttpUriRequest createRequest(String uri,
|
GalaxyFDSCredential credential, HttpMethod method,
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/util/RequestFactory.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/GalaxyFDSCredential.java
// public interface GalaxyFDSCredential {
//
// /**
// * Add HTTP header to request
// * @param request
// */
// void addHeader(HttpRequestBase request) throws GalaxyFDSClientException;
//
// /**
// * Adds parameter to the URL string
// * @param uri
// * @return
// */
// String addParam(String uri);
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
|
import java.util.Date;
import java.util.Map;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import com.xiaomi.infra.galaxy.fds.android.auth.GalaxyFDSCredential;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.model.HttpMethod;
|
package com.xiaomi.infra.galaxy.fds.android.util;
public class RequestFactory {
public static HttpUriRequest createRequest(String uri,
GalaxyFDSCredential credential, HttpMethod method,
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/GalaxyFDSCredential.java
// public interface GalaxyFDSCredential {
//
// /**
// * Add HTTP header to request
// * @param request
// */
// void addHeader(HttpRequestBase request) throws GalaxyFDSClientException;
//
// /**
// * Adds parameter to the URL string
// * @param uri
// * @return
// */
// String addParam(String uri);
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/RequestFactory.java
import java.util.Date;
import java.util.Map;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import com.xiaomi.infra.galaxy.fds.android.auth.GalaxyFDSCredential;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.model.HttpMethod;
package com.xiaomi.infra.galaxy.fds.android.util;
public class RequestFactory {
public static HttpUriRequest createRequest(String uri,
GalaxyFDSCredential credential, HttpMethod method,
|
Map<String, String> headers) throws GalaxyFDSClientException {
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/util/RequestFactory.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/GalaxyFDSCredential.java
// public interface GalaxyFDSCredential {
//
// /**
// * Add HTTP header to request
// * @param request
// */
// void addHeader(HttpRequestBase request) throws GalaxyFDSClientException;
//
// /**
// * Adds parameter to the URL string
// * @param uri
// * @return
// */
// String addParam(String uri);
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
|
import java.util.Date;
import java.util.Map;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import com.xiaomi.infra.galaxy.fds.android.auth.GalaxyFDSCredential;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.model.HttpMethod;
|
package com.xiaomi.infra.galaxy.fds.android.util;
public class RequestFactory {
public static HttpUriRequest createRequest(String uri,
GalaxyFDSCredential credential, HttpMethod method,
Map<String, String> headers) throws GalaxyFDSClientException {
uri = credential.addParam(uri);
HttpRequestBase request;
switch(method) {
case GET:
request = new HttpGet(uri);
break;
case PUT:
request = new HttpPut(uri);
break;
case POST:
request = new HttpPost(uri);
break;
case DELETE:
request = new HttpDelete(uri);
break;
case HEAD:
request = new HttpHead(uri);
break;
default:
request = null;
break;
}
if (request != null) {
if (headers != null) {
// Should not set content length here, otherwise the fucking apache
// library will throw an exception
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/GalaxyFDSCredential.java
// public interface GalaxyFDSCredential {
//
// /**
// * Add HTTP header to request
// * @param request
// */
// void addHeader(HttpRequestBase request) throws GalaxyFDSClientException;
//
// /**
// * Adds parameter to the URL string
// * @param uri
// * @return
// */
// String addParam(String uri);
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/RequestFactory.java
import java.util.Date;
import java.util.Map;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import com.xiaomi.infra.galaxy.fds.android.auth.GalaxyFDSCredential;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.model.HttpMethod;
package com.xiaomi.infra.galaxy.fds.android.util;
public class RequestFactory {
public static HttpUriRequest createRequest(String uri,
GalaxyFDSCredential credential, HttpMethod method,
Map<String, String> headers) throws GalaxyFDSClientException {
uri = credential.addParam(uri);
HttpRequestBase request;
switch(method) {
case GET:
request = new HttpGet(uri);
break;
case PUT:
request = new HttpPut(uri);
break;
case POST:
request = new HttpPost(uri);
break;
case DELETE:
request = new HttpDelete(uri);
break;
case HEAD:
request = new HttpHead(uri);
break;
default:
request = null;
break;
}
if (request != null) {
if (headers != null) {
// Should not set content length here, otherwise the fucking apache
// library will throw an exception
|
headers.remove(HttpHeaders.CONTENT_LENGTH);
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/SignatureCredential.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
|
import java.net.URI;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.common.collect.LinkedListMultimap;
import org.apache.http.Header;
import org.apache.http.client.methods.HttpRequestBase;
import com.xiaomi.infra.galaxy.fds.Common;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.auth.signature.SignAlgorithm;
import com.xiaomi.infra.galaxy.fds.auth.signature.Signer;
import com.xiaomi.infra.galaxy.fds.model.HttpMethod;
|
package com.xiaomi.infra.galaxy.fds.android.auth;
public class SignatureCredential implements GalaxyFDSCredential {
private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat format = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format;
}
};
private final String accessKeyId;
private final String secretAccessKeyId;
public SignatureCredential(String accessKeyId, String secretAccessKeyId) {
this.accessKeyId = accessKeyId;
this.secretAccessKeyId = secretAccessKeyId;
}
@Override
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/SignatureCredential.java
import java.net.URI;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.common.collect.LinkedListMultimap;
import org.apache.http.Header;
import org.apache.http.client.methods.HttpRequestBase;
import com.xiaomi.infra.galaxy.fds.Common;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.auth.signature.SignAlgorithm;
import com.xiaomi.infra.galaxy.fds.auth.signature.Signer;
import com.xiaomi.infra.galaxy.fds.model.HttpMethod;
package com.xiaomi.infra.galaxy.fds.android.auth;
public class SignatureCredential implements GalaxyFDSCredential {
private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat format = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format;
}
};
private final String accessKeyId;
private final String secretAccessKeyId;
public SignatureCredential(String accessKeyId, String secretAccessKeyId) {
this.accessKeyId = accessKeyId;
this.secretAccessKeyId = secretAccessKeyId;
}
@Override
|
public void addHeader(HttpRequestBase request) throws GalaxyFDSClientException {
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/SignatureCredential.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
|
import java.net.URI;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.common.collect.LinkedListMultimap;
import org.apache.http.Header;
import org.apache.http.client.methods.HttpRequestBase;
import com.xiaomi.infra.galaxy.fds.Common;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.auth.signature.SignAlgorithm;
import com.xiaomi.infra.galaxy.fds.auth.signature.Signer;
import com.xiaomi.infra.galaxy.fds.model.HttpMethod;
|
package com.xiaomi.infra.galaxy.fds.android.auth;
public class SignatureCredential implements GalaxyFDSCredential {
private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat format = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format;
}
};
private final String accessKeyId;
private final String secretAccessKeyId;
public SignatureCredential(String accessKeyId, String secretAccessKeyId) {
this.accessKeyId = accessKeyId;
this.secretAccessKeyId = secretAccessKeyId;
}
@Override
public void addHeader(HttpRequestBase request) throws GalaxyFDSClientException {
request.setHeader(Common.DATE, DATE_FORMAT.get().format(new Date()));
try {
URI uri = request.getURI();
LinkedListMultimap<String, String> httpHeaders = LinkedListMultimap.create();
for (Header httpHeader : request.getAllHeaders()) {
httpHeaders.put(httpHeader.getName(), httpHeader.getValue());
}
HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod());
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/SignatureCredential.java
import java.net.URI;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import com.google.common.collect.LinkedListMultimap;
import org.apache.http.Header;
import org.apache.http.client.methods.HttpRequestBase;
import com.xiaomi.infra.galaxy.fds.Common;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.auth.signature.SignAlgorithm;
import com.xiaomi.infra.galaxy.fds.auth.signature.Signer;
import com.xiaomi.infra.galaxy.fds.model.HttpMethod;
package com.xiaomi.infra.galaxy.fds.android.auth;
public class SignatureCredential implements GalaxyFDSCredential {
private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT =
new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat format = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
return format;
}
};
private final String accessKeyId;
private final String secretAccessKeyId;
public SignatureCredential(String accessKeyId, String secretAccessKeyId) {
this.accessKeyId = accessKeyId;
this.secretAccessKeyId = secretAccessKeyId;
}
@Override
public void addHeader(HttpRequestBase request) throws GalaxyFDSClientException {
request.setHeader(Common.DATE, DATE_FORMAT.get().format(new Date()));
try {
URI uri = request.getURI();
LinkedListMultimap<String, String> httpHeaders = LinkedListMultimap.create();
for (Header httpHeader : request.getAllHeaders()) {
httpHeaders.put(httpHeader.getName(), httpHeader.getValue());
}
HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod());
|
request.setHeader(HttpHeaders.AUTHORIZATION, Signer.getAuthorizationHeader(
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/SSOCredential.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Args.java
// public class Args {
//
// public static void check(final boolean expression, final String message) {
// if (!expression) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object... args) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object arg) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, arg));
// }
// }
//
// public static <T> T notNull(final T argument, final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// return argument;
// }
//
// public static <T extends CharSequence> T notEmpty(final T argument,
// final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// if (argument.length() == 0) {
// throw new IllegalArgumentException(name + " may not be empty");
// }
// return argument;
// }
//
// public static int positive(final int n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static long positive(final long n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static int notNegative(final int n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// public static long notNegative(final long n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// }
|
import org.apache.http.client.methods.HttpRequestBase;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.android.util.Args;
|
package com.xiaomi.infra.galaxy.fds.android.auth;
public class SSOCredential implements GalaxyFDSCredential {
private final String HEADER_VALUE = "SSO";
private final String SERVICE_TOKEN_PARAM = "serviceToken";
private final String APP_ID = "appId";
private final String serviceToken;
private final String appId;
@Deprecated
public SSOCredential(String serviceToken) {
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Args.java
// public class Args {
//
// public static void check(final boolean expression, final String message) {
// if (!expression) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object... args) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object arg) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, arg));
// }
// }
//
// public static <T> T notNull(final T argument, final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// return argument;
// }
//
// public static <T extends CharSequence> T notEmpty(final T argument,
// final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// if (argument.length() == 0) {
// throw new IllegalArgumentException(name + " may not be empty");
// }
// return argument;
// }
//
// public static int positive(final int n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static long positive(final long n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static int notNegative(final int n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// public static long notNegative(final long n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/SSOCredential.java
import org.apache.http.client.methods.HttpRequestBase;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.android.util.Args;
package com.xiaomi.infra.galaxy.fds.android.auth;
public class SSOCredential implements GalaxyFDSCredential {
private final String HEADER_VALUE = "SSO";
private final String SERVICE_TOKEN_PARAM = "serviceToken";
private final String APP_ID = "appId";
private final String serviceToken;
private final String appId;
@Deprecated
public SSOCredential(String serviceToken) {
|
Args.notNull(serviceToken, "Service token");
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/SSOCredential.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Args.java
// public class Args {
//
// public static void check(final boolean expression, final String message) {
// if (!expression) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object... args) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object arg) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, arg));
// }
// }
//
// public static <T> T notNull(final T argument, final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// return argument;
// }
//
// public static <T extends CharSequence> T notEmpty(final T argument,
// final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// if (argument.length() == 0) {
// throw new IllegalArgumentException(name + " may not be empty");
// }
// return argument;
// }
//
// public static int positive(final int n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static long positive(final long n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static int notNegative(final int n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// public static long notNegative(final long n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// }
|
import org.apache.http.client.methods.HttpRequestBase;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.android.util.Args;
|
package com.xiaomi.infra.galaxy.fds.android.auth;
public class SSOCredential implements GalaxyFDSCredential {
private final String HEADER_VALUE = "SSO";
private final String SERVICE_TOKEN_PARAM = "serviceToken";
private final String APP_ID = "appId";
private final String serviceToken;
private final String appId;
@Deprecated
public SSOCredential(String serviceToken) {
Args.notNull(serviceToken, "Service token");
Args.notEmpty(serviceToken, "Service token");
this.serviceToken = serviceToken;
this.appId = null;
}
public SSOCredential(String serviceToken, String appId) {
Args.notNull(serviceToken, "Service token");
Args.notEmpty(serviceToken, "Service token");
Args.notNull(appId, "App id");
Args.notEmpty(appId, "App id");
this.serviceToken = serviceToken;
this.appId = appId;
}
@Override
public void addHeader(HttpRequestBase request) {
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Args.java
// public class Args {
//
// public static void check(final boolean expression, final String message) {
// if (!expression) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object... args) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object arg) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, arg));
// }
// }
//
// public static <T> T notNull(final T argument, final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// return argument;
// }
//
// public static <T extends CharSequence> T notEmpty(final T argument,
// final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// if (argument.length() == 0) {
// throw new IllegalArgumentException(name + " may not be empty");
// }
// return argument;
// }
//
// public static int positive(final int n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static long positive(final long n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static int notNegative(final int n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// public static long notNegative(final long n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/SSOCredential.java
import org.apache.http.client.methods.HttpRequestBase;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.android.util.Args;
package com.xiaomi.infra.galaxy.fds.android.auth;
public class SSOCredential implements GalaxyFDSCredential {
private final String HEADER_VALUE = "SSO";
private final String SERVICE_TOKEN_PARAM = "serviceToken";
private final String APP_ID = "appId";
private final String serviceToken;
private final String appId;
@Deprecated
public SSOCredential(String serviceToken) {
Args.notNull(serviceToken, "Service token");
Args.notEmpty(serviceToken, "Service token");
this.serviceToken = serviceToken;
this.appId = null;
}
public SSOCredential(String serviceToken, String appId) {
Args.notNull(serviceToken, "Service token");
Args.notEmpty(serviceToken, "Service token");
Args.notNull(appId, "App id");
Args.notEmpty(appId, "App id");
this.serviceToken = serviceToken;
this.appId = appId;
}
@Override
public void addHeader(HttpRequestBase request) {
|
request.addHeader(HttpHeaders.AUTHORIZATION, HEADER_VALUE);
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/OAuthCredential.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/StorageAccessToken.java
// public class StorageAccessToken {
//
// private String token;
// private long expireTime; // ms
//
// public StorageAccessToken() {}
//
// public StorageAccessToken(String token, long expireTime) {
// this.token = token;
// this.expireTime = expireTime;
// }
//
// public String getToken() {
// return token;
// }
//
// public void setToken(String token) {
// this.token = token;
// }
//
// public long getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(long expireTime) {
// this.expireTime = expireTime;
// }
// }
|
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.android.model.StorageAccessToken;
|
package com.xiaomi.infra.galaxy.fds.android.auth;
public class OAuthCredential implements GalaxyFDSCredential {
private static final String STORAGE_ACCESS_TOKEN = "storageAccessToken";
private static final String APP_ID = "appId";
private static final String OAUTH_APPID = "oauthAppId";
private static final String OAUTH_ACCESS_TOKEN = "oauthAccessToken";
private static final String OAUTH_PROVIDER = "oauthProvider";
private static final String OAUTH_MAC_KEY = "oauthMacKey";
private static final String OAUTH_MAC_ALGORITHM = "oauthMacAlgorithm";
private final String HEADER_VALUE = "OAuth";
private final String appId;
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/StorageAccessToken.java
// public class StorageAccessToken {
//
// private String token;
// private long expireTime; // ms
//
// public StorageAccessToken() {}
//
// public StorageAccessToken(String token, long expireTime) {
// this.token = token;
// this.expireTime = expireTime;
// }
//
// public String getToken() {
// return token;
// }
//
// public void setToken(String token) {
// this.token = token;
// }
//
// public long getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(long expireTime) {
// this.expireTime = expireTime;
// }
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/OAuthCredential.java
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.android.model.StorageAccessToken;
package com.xiaomi.infra.galaxy.fds.android.auth;
public class OAuthCredential implements GalaxyFDSCredential {
private static final String STORAGE_ACCESS_TOKEN = "storageAccessToken";
private static final String APP_ID = "appId";
private static final String OAUTH_APPID = "oauthAppId";
private static final String OAUTH_ACCESS_TOKEN = "oauthAccessToken";
private static final String OAUTH_PROVIDER = "oauthProvider";
private static final String OAUTH_MAC_KEY = "oauthMacKey";
private static final String OAUTH_MAC_ALGORITHM = "oauthMacAlgorithm";
private final String HEADER_VALUE = "OAuth";
private final String appId;
|
private final StorageAccessToken storageAccessToken;
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/OAuthCredential.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/StorageAccessToken.java
// public class StorageAccessToken {
//
// private String token;
// private long expireTime; // ms
//
// public StorageAccessToken() {}
//
// public StorageAccessToken(String token, long expireTime) {
// this.token = token;
// this.expireTime = expireTime;
// }
//
// public String getToken() {
// return token;
// }
//
// public void setToken(String token) {
// this.token = token;
// }
//
// public long getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(long expireTime) {
// this.expireTime = expireTime;
// }
// }
|
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.android.model.StorageAccessToken;
|
package com.xiaomi.infra.galaxy.fds.android.auth;
public class OAuthCredential implements GalaxyFDSCredential {
private static final String STORAGE_ACCESS_TOKEN = "storageAccessToken";
private static final String APP_ID = "appId";
private static final String OAUTH_APPID = "oauthAppId";
private static final String OAUTH_ACCESS_TOKEN = "oauthAccessToken";
private static final String OAUTH_PROVIDER = "oauthProvider";
private static final String OAUTH_MAC_KEY = "oauthMacKey";
private static final String OAUTH_MAC_ALGORITHM = "oauthMacAlgorithm";
private final String HEADER_VALUE = "OAuth";
private final String appId;
private final StorageAccessToken storageAccessToken;
public OAuthCredential(String fdsServiceBaseUri, String appId,
String oauthAppId, String oauthAccessToken, String oauthProvider,
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/StorageAccessToken.java
// public class StorageAccessToken {
//
// private String token;
// private long expireTime; // ms
//
// public StorageAccessToken() {}
//
// public StorageAccessToken(String token, long expireTime) {
// this.token = token;
// this.expireTime = expireTime;
// }
//
// public String getToken() {
// return token;
// }
//
// public void setToken(String token) {
// this.token = token;
// }
//
// public long getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(long expireTime) {
// this.expireTime = expireTime;
// }
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/OAuthCredential.java
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.android.model.StorageAccessToken;
package com.xiaomi.infra.galaxy.fds.android.auth;
public class OAuthCredential implements GalaxyFDSCredential {
private static final String STORAGE_ACCESS_TOKEN = "storageAccessToken";
private static final String APP_ID = "appId";
private static final String OAUTH_APPID = "oauthAppId";
private static final String OAUTH_ACCESS_TOKEN = "oauthAccessToken";
private static final String OAUTH_PROVIDER = "oauthProvider";
private static final String OAUTH_MAC_KEY = "oauthMacKey";
private static final String OAUTH_MAC_ALGORITHM = "oauthMacAlgorithm";
private final String HEADER_VALUE = "OAuth";
private final String appId;
private final StorageAccessToken storageAccessToken;
public OAuthCredential(String fdsServiceBaseUri, String appId,
String oauthAppId, String oauthAccessToken, String oauthProvider,
|
String macKey, String macAlgorithm) throws GalaxyFDSClientException {
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/OAuthCredential.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/StorageAccessToken.java
// public class StorageAccessToken {
//
// private String token;
// private long expireTime; // ms
//
// public StorageAccessToken() {}
//
// public StorageAccessToken(String token, long expireTime) {
// this.token = token;
// this.expireTime = expireTime;
// }
//
// public String getToken() {
// return token;
// }
//
// public void setToken(String token) {
// this.token = token;
// }
//
// public long getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(long expireTime) {
// this.expireTime = expireTime;
// }
// }
|
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.android.model.StorageAccessToken;
|
private static final String OAUTH_ACCESS_TOKEN = "oauthAccessToken";
private static final String OAUTH_PROVIDER = "oauthProvider";
private static final String OAUTH_MAC_KEY = "oauthMacKey";
private static final String OAUTH_MAC_ALGORITHM = "oauthMacAlgorithm";
private final String HEADER_VALUE = "OAuth";
private final String appId;
private final StorageAccessToken storageAccessToken;
public OAuthCredential(String fdsServiceBaseUri, String appId,
String oauthAppId, String oauthAccessToken, String oauthProvider,
String macKey, String macAlgorithm) throws GalaxyFDSClientException {
this.appId = appId;
this.storageAccessToken = getStorageAccessToken(fdsServiceBaseUri, appId,
oauthAppId, oauthAccessToken, oauthProvider, macKey, macAlgorithm);
}
private StorageAccessToken getStorageAccessToken(String serviceBaseUri,
String appId, String oauthAppId, String oauthAccessToken,
String oauthProvider, String macKey, String macAlgorithm)
throws GalaxyFDSClientException {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(serviceBaseUri + "/?" + STORAGE_ACCESS_TOKEN
+ "&" + APP_ID + "=" + appId
+ "&" + OAUTH_APPID + "=" + oauthAppId
+ "&" + OAUTH_ACCESS_TOKEN + "=" + oauthAccessToken
+ "&" + OAUTH_PROVIDER + "=" + oauthProvider
+ "&" + OAUTH_MAC_ALGORITHM + "=" + macAlgorithm
+ "&" + OAUTH_MAC_KEY + "=" + macKey);
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/exception/GalaxyFDSClientException.java
// public class GalaxyFDSClientException extends Exception {
//
// public GalaxyFDSClientException() {}
//
// public GalaxyFDSClientException(String message) {
// super(message);
// }
//
// public GalaxyFDSClientException(Throwable cause) {
// super(cause);
// }
//
// public GalaxyFDSClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/HttpHeaders.java
// public final class HttpHeaders {
// /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */
// public static final String AUTHORIZATION = "Authorization";
//
// /** RFC 2616 (HTTP/1.1) Section 14.9 */
// public static final String CACHE_CONTROL = "Cache-Control";
//
// /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */
// public static final String CONTENT_ENCODING = "Content-Encoding";
//
// /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */
// public static final String CONTENT_LENGTH = "Content-Length";
//
// /** RFC 2616 (HTTP/1.1) Section 14.15 */
// public static final String CONTENT_MD5 = "Content-MD5";
//
// /** RFC 2616 (HTTP/1.1) Section 14.16 */
// public static final String CONTENT_RANGE = "Content-Range";
//
// /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */
// public static final String CONTENT_TYPE = "Content-Type";
//
// /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */
// public static final String DATE = "Date";
//
// /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */
// public static final String LAST_MODIFIED = "Last-Modified";
//
// /** RFC 2616 (HTTP/1.1) Section 14.35 */
// public static final String RANGE = "Range";
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/model/StorageAccessToken.java
// public class StorageAccessToken {
//
// private String token;
// private long expireTime; // ms
//
// public StorageAccessToken() {}
//
// public StorageAccessToken(String token, long expireTime) {
// this.token = token;
// this.expireTime = expireTime;
// }
//
// public String getToken() {
// return token;
// }
//
// public void setToken(String token) {
// this.token = token;
// }
//
// public long getExpireTime() {
// return expireTime;
// }
//
// public void setExpireTime(long expireTime) {
// this.expireTime = expireTime;
// }
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/OAuthCredential.java
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import com.xiaomi.infra.galaxy.fds.android.exception.GalaxyFDSClientException;
import com.xiaomi.infra.galaxy.fds.android.model.HttpHeaders;
import com.xiaomi.infra.galaxy.fds.android.model.StorageAccessToken;
private static final String OAUTH_ACCESS_TOKEN = "oauthAccessToken";
private static final String OAUTH_PROVIDER = "oauthProvider";
private static final String OAUTH_MAC_KEY = "oauthMacKey";
private static final String OAUTH_MAC_ALGORITHM = "oauthMacAlgorithm";
private final String HEADER_VALUE = "OAuth";
private final String appId;
private final StorageAccessToken storageAccessToken;
public OAuthCredential(String fdsServiceBaseUri, String appId,
String oauthAppId, String oauthAccessToken, String oauthProvider,
String macKey, String macAlgorithm) throws GalaxyFDSClientException {
this.appId = appId;
this.storageAccessToken = getStorageAccessToken(fdsServiceBaseUri, appId,
oauthAppId, oauthAccessToken, oauthProvider, macKey, macAlgorithm);
}
private StorageAccessToken getStorageAccessToken(String serviceBaseUri,
String appId, String oauthAppId, String oauthAccessToken,
String oauthProvider, String macKey, String macAlgorithm)
throws GalaxyFDSClientException {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(serviceBaseUri + "/?" + STORAGE_ACCESS_TOKEN
+ "&" + APP_ID + "=" + appId
+ "&" + OAUTH_APPID + "=" + oauthAppId
+ "&" + OAUTH_ACCESS_TOKEN + "=" + oauthAccessToken
+ "&" + OAUTH_PROVIDER + "=" + oauthProvider
+ "&" + OAUTH_MAC_ALGORITHM + "=" + macAlgorithm
+ "&" + OAUTH_MAC_KEY + "=" + macKey);
|
get.setHeader(HttpHeaders.AUTHORIZATION, HEADER_VALUE);
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/FDSClientConfiguration.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/GalaxyFDSCredential.java
// public interface GalaxyFDSCredential {
//
// /**
// * Add HTTP header to request
// * @param request
// */
// void addHeader(HttpRequestBase request) throws GalaxyFDSClientException;
//
// /**
// * Adds parameter to the URL string
// * @param uri
// * @return
// */
// String addParam(String uri);
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Args.java
// public class Args {
//
// public static void check(final boolean expression, final String message) {
// if (!expression) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object... args) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object arg) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, arg));
// }
// }
//
// public static <T> T notNull(final T argument, final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// return argument;
// }
//
// public static <T extends CharSequence> T notEmpty(final T argument,
// final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// if (argument.length() == 0) {
// throw new IllegalArgumentException(name + " may not be empty");
// }
// return argument;
// }
//
// public static int positive(final int n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static long positive(final long n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static int notNegative(final int n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// public static long notNegative(final long n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// }
|
import com.xiaomi.infra.galaxy.fds.android.auth.GalaxyFDSCredential;
import com.xiaomi.infra.galaxy.fds.android.util.Args;
|
package com.xiaomi.infra.galaxy.fds.android;
public class FDSClientConfiguration {
private static final String URI_HTTP_PREFIX = "http://";
private static final String URI_HTTPS_PREFIX = "https://";
private static final String URI_CDN = "cdn";
private static final String URI_SUFFIX = "fds.api.xiaomi.com";
private static final String URI_CDN_SUFFIX = "fds.api.mi-img.com";
/**
* The default timeout for a connected socket.
*/
public static final int DEFAULT_SOCKET_TIMEOUT_MS = 50 * 1000;
/**
* The default max retry times
*/
public static final int DEFAULT_MAX_RETRY_TIMES = 3;
/**
* The default size of a upload part
*/
public static final int DEFAULT_UPLOAD_PART_SIZE = 4096;
/**
* The amount of time to wait (in milliseconds) for data to be transfered
* over an established, open connection before the connection is timed out.
* A value of 0 means infinity, and is not recommended.
*/
private int socketTimeoutMs = DEFAULT_SOCKET_TIMEOUT_MS;
/**
* The default timeout for establishing a connection.
*/
public static final int DEFAULT_CONNECTION_TIMEOUT_MS = 50 * 1000;
/**
* The amount of time to wait (in milliseconds) when initially establishing
* a connection before giving up and timing out. A value of 0 means
* infinity, and is not recommended.
*/
private int connectionTimeoutMs = DEFAULT_CONNECTION_TIMEOUT_MS;
/**
* Optional size hint (in bytes) for the low level TCP send buffer. This is
* an advanced option for advanced users who want to tune low level TCP
* parameters to try and squeeze out more performance.
*/
private int socketSendBufferSizeHint = 0;
/**
* Optional size hint (in bytes) for the low level TCP receive buffer. This
* is an advanced option for advanced users who want to tune low level TCP
* parameters to try and squeeze out more performance.
*/
private int socketReceiveBufferSizeHint = 0;
/**
* The maximum number of times that a failed request will be retried
*/
private int maxRetryTimes = DEFAULT_MAX_RETRY_TIMES;
/**
* The size of each upload part
*/
private int uploadPartSize = DEFAULT_UPLOAD_PART_SIZE;
public static final int DEFAULT_THREAD_POOL_CORE_SIZE = 4;
private int threadPoolCoreSize = DEFAULT_THREAD_POOL_CORE_SIZE;
public static final int DEFAULT_THREAD_POOL_MAX_SIZE = 10;
private int threadPoolMaxSize = DEFAULT_THREAD_POOL_MAX_SIZE;
public static final int DEFAULT_THREAD_POOL_KEEP_ALIVE_SECS = 30;
private int threadPoolKeepAliveSecs = DEFAULT_THREAD_POOL_KEEP_ALIVE_SECS;
public static final int DEFAULT_WORK_QUEUE_CAPACITY = 10240;
private int workQueueCapacity = DEFAULT_WORK_QUEUE_CAPACITY;
/**
* The credential of FDS client
*/
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/GalaxyFDSCredential.java
// public interface GalaxyFDSCredential {
//
// /**
// * Add HTTP header to request
// * @param request
// */
// void addHeader(HttpRequestBase request) throws GalaxyFDSClientException;
//
// /**
// * Adds parameter to the URL string
// * @param uri
// * @return
// */
// String addParam(String uri);
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Args.java
// public class Args {
//
// public static void check(final boolean expression, final String message) {
// if (!expression) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object... args) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object arg) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, arg));
// }
// }
//
// public static <T> T notNull(final T argument, final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// return argument;
// }
//
// public static <T extends CharSequence> T notEmpty(final T argument,
// final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// if (argument.length() == 0) {
// throw new IllegalArgumentException(name + " may not be empty");
// }
// return argument;
// }
//
// public static int positive(final int n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static long positive(final long n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static int notNegative(final int n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// public static long notNegative(final long n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/FDSClientConfiguration.java
import com.xiaomi.infra.galaxy.fds.android.auth.GalaxyFDSCredential;
import com.xiaomi.infra.galaxy.fds.android.util.Args;
package com.xiaomi.infra.galaxy.fds.android;
public class FDSClientConfiguration {
private static final String URI_HTTP_PREFIX = "http://";
private static final String URI_HTTPS_PREFIX = "https://";
private static final String URI_CDN = "cdn";
private static final String URI_SUFFIX = "fds.api.xiaomi.com";
private static final String URI_CDN_SUFFIX = "fds.api.mi-img.com";
/**
* The default timeout for a connected socket.
*/
public static final int DEFAULT_SOCKET_TIMEOUT_MS = 50 * 1000;
/**
* The default max retry times
*/
public static final int DEFAULT_MAX_RETRY_TIMES = 3;
/**
* The default size of a upload part
*/
public static final int DEFAULT_UPLOAD_PART_SIZE = 4096;
/**
* The amount of time to wait (in milliseconds) for data to be transfered
* over an established, open connection before the connection is timed out.
* A value of 0 means infinity, and is not recommended.
*/
private int socketTimeoutMs = DEFAULT_SOCKET_TIMEOUT_MS;
/**
* The default timeout for establishing a connection.
*/
public static final int DEFAULT_CONNECTION_TIMEOUT_MS = 50 * 1000;
/**
* The amount of time to wait (in milliseconds) when initially establishing
* a connection before giving up and timing out. A value of 0 means
* infinity, and is not recommended.
*/
private int connectionTimeoutMs = DEFAULT_CONNECTION_TIMEOUT_MS;
/**
* Optional size hint (in bytes) for the low level TCP send buffer. This is
* an advanced option for advanced users who want to tune low level TCP
* parameters to try and squeeze out more performance.
*/
private int socketSendBufferSizeHint = 0;
/**
* Optional size hint (in bytes) for the low level TCP receive buffer. This
* is an advanced option for advanced users who want to tune low level TCP
* parameters to try and squeeze out more performance.
*/
private int socketReceiveBufferSizeHint = 0;
/**
* The maximum number of times that a failed request will be retried
*/
private int maxRetryTimes = DEFAULT_MAX_RETRY_TIMES;
/**
* The size of each upload part
*/
private int uploadPartSize = DEFAULT_UPLOAD_PART_SIZE;
public static final int DEFAULT_THREAD_POOL_CORE_SIZE = 4;
private int threadPoolCoreSize = DEFAULT_THREAD_POOL_CORE_SIZE;
public static final int DEFAULT_THREAD_POOL_MAX_SIZE = 10;
private int threadPoolMaxSize = DEFAULT_THREAD_POOL_MAX_SIZE;
public static final int DEFAULT_THREAD_POOL_KEEP_ALIVE_SECS = 30;
private int threadPoolKeepAliveSecs = DEFAULT_THREAD_POOL_KEEP_ALIVE_SECS;
public static final int DEFAULT_WORK_QUEUE_CAPACITY = 10240;
private int workQueueCapacity = DEFAULT_WORK_QUEUE_CAPACITY;
/**
* The credential of FDS client
*/
|
private GalaxyFDSCredential credential;
|
XiaoMi/galaxy-fds-sdk-android
|
src/main/java/com/xiaomi/infra/galaxy/fds/android/FDSClientConfiguration.java
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/GalaxyFDSCredential.java
// public interface GalaxyFDSCredential {
//
// /**
// * Add HTTP header to request
// * @param request
// */
// void addHeader(HttpRequestBase request) throws GalaxyFDSClientException;
//
// /**
// * Adds parameter to the URL string
// * @param uri
// * @return
// */
// String addParam(String uri);
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Args.java
// public class Args {
//
// public static void check(final boolean expression, final String message) {
// if (!expression) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object... args) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object arg) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, arg));
// }
// }
//
// public static <T> T notNull(final T argument, final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// return argument;
// }
//
// public static <T extends CharSequence> T notEmpty(final T argument,
// final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// if (argument.length() == 0) {
// throw new IllegalArgumentException(name + " may not be empty");
// }
// return argument;
// }
//
// public static int positive(final int n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static long positive(final long n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static int notNegative(final int n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// public static long notNegative(final long n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// }
|
import com.xiaomi.infra.galaxy.fds.android.auth.GalaxyFDSCredential;
import com.xiaomi.infra.galaxy.fds.android.util.Args;
|
public static final int DEFAULT_WORK_QUEUE_CAPACITY = 10240;
private int workQueueCapacity = DEFAULT_WORK_QUEUE_CAPACITY;
/**
* The credential of FDS client
*/
private GalaxyFDSCredential credential;
private String regionName = "cnbj0";
private boolean enableHttps = true;
private boolean enableCdnForUpload = false;
private boolean enableCdnForDownload = true;
private boolean enableUnitTestMode = false;
private String baseUriForUnitTest = "";
private String endpoint;
/**
* Returns the maximum number of retry attempts for failed requests
*/
public int getMaxRetryTimes() {
return maxRetryTimes;
}
/**
* Sets the maximum number of retry attempts for failed requests
*/
public void setMaxRetryTimes(int maxRetryTimes) {
|
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/auth/GalaxyFDSCredential.java
// public interface GalaxyFDSCredential {
//
// /**
// * Add HTTP header to request
// * @param request
// */
// void addHeader(HttpRequestBase request) throws GalaxyFDSClientException;
//
// /**
// * Adds parameter to the URL string
// * @param uri
// * @return
// */
// String addParam(String uri);
// }
//
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/util/Args.java
// public class Args {
//
// public static void check(final boolean expression, final String message) {
// if (!expression) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object... args) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, args));
// }
// }
//
// public static void check(final boolean expression, final String message,
// final Object arg) {
// if (!expression) {
// throw new IllegalArgumentException(String.format(message, arg));
// }
// }
//
// public static <T> T notNull(final T argument, final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// return argument;
// }
//
// public static <T extends CharSequence> T notEmpty(final T argument,
// final String name) {
// if (argument == null) {
// throw new IllegalArgumentException(name + " may not be null");
// }
// if (argument.length() == 0) {
// throw new IllegalArgumentException(name + " may not be empty");
// }
// return argument;
// }
//
// public static int positive(final int n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static long positive(final long n, final String name) {
// if (n <= 0) {
// throw new IllegalArgumentException(name + " may not be negative or zero");
// }
// return n;
// }
//
// public static int notNegative(final int n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// public static long notNegative(final long n, final String name) {
// if (n < 0) {
// throw new IllegalArgumentException(name + " may not be negative");
// }
// return n;
// }
//
// }
// Path: src/main/java/com/xiaomi/infra/galaxy/fds/android/FDSClientConfiguration.java
import com.xiaomi.infra.galaxy.fds.android.auth.GalaxyFDSCredential;
import com.xiaomi.infra.galaxy.fds.android.util.Args;
public static final int DEFAULT_WORK_QUEUE_CAPACITY = 10240;
private int workQueueCapacity = DEFAULT_WORK_QUEUE_CAPACITY;
/**
* The credential of FDS client
*/
private GalaxyFDSCredential credential;
private String regionName = "cnbj0";
private boolean enableHttps = true;
private boolean enableCdnForUpload = false;
private boolean enableCdnForDownload = true;
private boolean enableUnitTestMode = false;
private String baseUriForUnitTest = "";
private String endpoint;
/**
* Returns the maximum number of retry attempts for failed requests
*/
public int getMaxRetryTimes() {
return maxRetryTimes;
}
/**
* Sets the maximum number of retry attempts for failed requests
*/
public void setMaxRetryTimes(int maxRetryTimes) {
|
Args.notNegative(maxRetryTimes, "max retry times");
|
pac4j/play-pac4j
|
shared/src/main/java/org/pac4j/play/CallbackController.java
|
// Path: shared/src/main/java/org/pac4j/play/context/PlayContextFactory.java
// public class PlayContextFactory implements WebContextFactory {
//
// public static final PlayContextFactory INSTANCE = new PlayContextFactory();
//
// protected PlayContextFactory() {}
//
// @Override
// public PlayWebContext newContext(final Object... parameters) {
// return new PlayWebContext((Http.Request) parameters[0]);
// }
// }
//
// Path: shared/src/main/java/org/pac4j/play/http/PlayHttpActionAdapter.java
// public class PlayHttpActionAdapter implements HttpActionAdapter {
//
// protected final Logger logger = LoggerFactory.getLogger(getClass());
//
// public static final PlayHttpActionAdapter INSTANCE = new PlayHttpActionAdapter();
//
// protected Map<Integer, Result> results = new HashMap<>();
//
// @Override
// public Result adapt(final HttpAction action, final WebContext context) {
// if (action != null) {
// final int code = action.getCode();
// logger.debug("requires HTTP action: {}", code);
//
// final Result predefinedResult = results.get(code);
// if (predefinedResult != null) {
// logger.debug("using pre-defined result for code: {}", code);
// return ((PlayWebContext) context).supplementResponse(predefinedResult);
// }
//
// Map<String, String> headers = new HashMap<>();
// HttpEntity httpEntity = HttpEntity.NO_ENTITY;
//
// if (action instanceof WithLocationAction) {
// final WithLocationAction withLocationAction = (WithLocationAction) action;
// headers.put(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
// } else if (action instanceof WithContentAction) {
// final WithContentAction withContentAction = (WithContentAction) action;
// final String content = withContentAction.getContent();
//
// if (content != null) {
// logger.debug("render: {}", content);
// httpEntity = HttpEntity.fromString(content, "UTF-8");
// }
// }
//
// return ((PlayWebContext) context).supplementResponse(new Result(code, headers, httpEntity));
// }
//
// throw new TechnicalException("No action provided");
// }
//
// public Map<Integer, Result> getResults() {
// return results;
// }
//
// public void setResults(final Map<Integer, Result> results) {
// CommonHelper.assertNotNull("results", results);
// this.results = results;
// }
// }
|
import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.engine.CallbackLogic;
import org.pac4j.core.engine.DefaultCallbackLogic;
import org.pac4j.core.http.adapter.HttpActionAdapter;
import org.pac4j.core.util.FindBest;
import org.pac4j.play.context.PlayContextFactory;
import org.pac4j.play.http.PlayHttpActionAdapter;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.libs.concurrent.HttpExecutionContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
|
package org.pac4j.play;
/**
* <p>This filter finishes the login process for an indirect client.</p>
*
* @author Jerome Leleu
* @author Michael Remond
* @since 1.5.0
*/
public class CallbackController extends Controller {
private CallbackLogic callbackLogic;
private String defaultUrl;
private Boolean renewSession;
private String defaultClient;
@Inject
protected Config config;
@Inject
protected SessionStore sessionStore;
@Inject
protected HttpExecutionContext ec;
public CompletionStage<Result> callback(final Http.Request request) {
|
// Path: shared/src/main/java/org/pac4j/play/context/PlayContextFactory.java
// public class PlayContextFactory implements WebContextFactory {
//
// public static final PlayContextFactory INSTANCE = new PlayContextFactory();
//
// protected PlayContextFactory() {}
//
// @Override
// public PlayWebContext newContext(final Object... parameters) {
// return new PlayWebContext((Http.Request) parameters[0]);
// }
// }
//
// Path: shared/src/main/java/org/pac4j/play/http/PlayHttpActionAdapter.java
// public class PlayHttpActionAdapter implements HttpActionAdapter {
//
// protected final Logger logger = LoggerFactory.getLogger(getClass());
//
// public static final PlayHttpActionAdapter INSTANCE = new PlayHttpActionAdapter();
//
// protected Map<Integer, Result> results = new HashMap<>();
//
// @Override
// public Result adapt(final HttpAction action, final WebContext context) {
// if (action != null) {
// final int code = action.getCode();
// logger.debug("requires HTTP action: {}", code);
//
// final Result predefinedResult = results.get(code);
// if (predefinedResult != null) {
// logger.debug("using pre-defined result for code: {}", code);
// return ((PlayWebContext) context).supplementResponse(predefinedResult);
// }
//
// Map<String, String> headers = new HashMap<>();
// HttpEntity httpEntity = HttpEntity.NO_ENTITY;
//
// if (action instanceof WithLocationAction) {
// final WithLocationAction withLocationAction = (WithLocationAction) action;
// headers.put(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
// } else if (action instanceof WithContentAction) {
// final WithContentAction withContentAction = (WithContentAction) action;
// final String content = withContentAction.getContent();
//
// if (content != null) {
// logger.debug("render: {}", content);
// httpEntity = HttpEntity.fromString(content, "UTF-8");
// }
// }
//
// return ((PlayWebContext) context).supplementResponse(new Result(code, headers, httpEntity));
// }
//
// throw new TechnicalException("No action provided");
// }
//
// public Map<Integer, Result> getResults() {
// return results;
// }
//
// public void setResults(final Map<Integer, Result> results) {
// CommonHelper.assertNotNull("results", results);
// this.results = results;
// }
// }
// Path: shared/src/main/java/org/pac4j/play/CallbackController.java
import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.engine.CallbackLogic;
import org.pac4j.core.engine.DefaultCallbackLogic;
import org.pac4j.core.http.adapter.HttpActionAdapter;
import org.pac4j.core.util.FindBest;
import org.pac4j.play.context.PlayContextFactory;
import org.pac4j.play.http.PlayHttpActionAdapter;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.libs.concurrent.HttpExecutionContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
package org.pac4j.play;
/**
* <p>This filter finishes the login process for an indirect client.</p>
*
* @author Jerome Leleu
* @author Michael Remond
* @since 1.5.0
*/
public class CallbackController extends Controller {
private CallbackLogic callbackLogic;
private String defaultUrl;
private Boolean renewSession;
private String defaultClient;
@Inject
protected Config config;
@Inject
protected SessionStore sessionStore;
@Inject
protected HttpExecutionContext ec;
public CompletionStage<Result> callback(final Http.Request request) {
|
final HttpActionAdapter bestAdapter = FindBest.httpActionAdapter(null, config, PlayHttpActionAdapter.INSTANCE);
|
pac4j/play-pac4j
|
shared/src/main/java/org/pac4j/play/CallbackController.java
|
// Path: shared/src/main/java/org/pac4j/play/context/PlayContextFactory.java
// public class PlayContextFactory implements WebContextFactory {
//
// public static final PlayContextFactory INSTANCE = new PlayContextFactory();
//
// protected PlayContextFactory() {}
//
// @Override
// public PlayWebContext newContext(final Object... parameters) {
// return new PlayWebContext((Http.Request) parameters[0]);
// }
// }
//
// Path: shared/src/main/java/org/pac4j/play/http/PlayHttpActionAdapter.java
// public class PlayHttpActionAdapter implements HttpActionAdapter {
//
// protected final Logger logger = LoggerFactory.getLogger(getClass());
//
// public static final PlayHttpActionAdapter INSTANCE = new PlayHttpActionAdapter();
//
// protected Map<Integer, Result> results = new HashMap<>();
//
// @Override
// public Result adapt(final HttpAction action, final WebContext context) {
// if (action != null) {
// final int code = action.getCode();
// logger.debug("requires HTTP action: {}", code);
//
// final Result predefinedResult = results.get(code);
// if (predefinedResult != null) {
// logger.debug("using pre-defined result for code: {}", code);
// return ((PlayWebContext) context).supplementResponse(predefinedResult);
// }
//
// Map<String, String> headers = new HashMap<>();
// HttpEntity httpEntity = HttpEntity.NO_ENTITY;
//
// if (action instanceof WithLocationAction) {
// final WithLocationAction withLocationAction = (WithLocationAction) action;
// headers.put(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
// } else if (action instanceof WithContentAction) {
// final WithContentAction withContentAction = (WithContentAction) action;
// final String content = withContentAction.getContent();
//
// if (content != null) {
// logger.debug("render: {}", content);
// httpEntity = HttpEntity.fromString(content, "UTF-8");
// }
// }
//
// return ((PlayWebContext) context).supplementResponse(new Result(code, headers, httpEntity));
// }
//
// throw new TechnicalException("No action provided");
// }
//
// public Map<Integer, Result> getResults() {
// return results;
// }
//
// public void setResults(final Map<Integer, Result> results) {
// CommonHelper.assertNotNull("results", results);
// this.results = results;
// }
// }
|
import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.engine.CallbackLogic;
import org.pac4j.core.engine.DefaultCallbackLogic;
import org.pac4j.core.http.adapter.HttpActionAdapter;
import org.pac4j.core.util.FindBest;
import org.pac4j.play.context.PlayContextFactory;
import org.pac4j.play.http.PlayHttpActionAdapter;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.libs.concurrent.HttpExecutionContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
|
package org.pac4j.play;
/**
* <p>This filter finishes the login process for an indirect client.</p>
*
* @author Jerome Leleu
* @author Michael Remond
* @since 1.5.0
*/
public class CallbackController extends Controller {
private CallbackLogic callbackLogic;
private String defaultUrl;
private Boolean renewSession;
private String defaultClient;
@Inject
protected Config config;
@Inject
protected SessionStore sessionStore;
@Inject
protected HttpExecutionContext ec;
public CompletionStage<Result> callback(final Http.Request request) {
final HttpActionAdapter bestAdapter = FindBest.httpActionAdapter(null, config, PlayHttpActionAdapter.INSTANCE);
final CallbackLogic bestLogic = FindBest.callbackLogic(callbackLogic, config, DefaultCallbackLogic.INSTANCE);
|
// Path: shared/src/main/java/org/pac4j/play/context/PlayContextFactory.java
// public class PlayContextFactory implements WebContextFactory {
//
// public static final PlayContextFactory INSTANCE = new PlayContextFactory();
//
// protected PlayContextFactory() {}
//
// @Override
// public PlayWebContext newContext(final Object... parameters) {
// return new PlayWebContext((Http.Request) parameters[0]);
// }
// }
//
// Path: shared/src/main/java/org/pac4j/play/http/PlayHttpActionAdapter.java
// public class PlayHttpActionAdapter implements HttpActionAdapter {
//
// protected final Logger logger = LoggerFactory.getLogger(getClass());
//
// public static final PlayHttpActionAdapter INSTANCE = new PlayHttpActionAdapter();
//
// protected Map<Integer, Result> results = new HashMap<>();
//
// @Override
// public Result adapt(final HttpAction action, final WebContext context) {
// if (action != null) {
// final int code = action.getCode();
// logger.debug("requires HTTP action: {}", code);
//
// final Result predefinedResult = results.get(code);
// if (predefinedResult != null) {
// logger.debug("using pre-defined result for code: {}", code);
// return ((PlayWebContext) context).supplementResponse(predefinedResult);
// }
//
// Map<String, String> headers = new HashMap<>();
// HttpEntity httpEntity = HttpEntity.NO_ENTITY;
//
// if (action instanceof WithLocationAction) {
// final WithLocationAction withLocationAction = (WithLocationAction) action;
// headers.put(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
// } else if (action instanceof WithContentAction) {
// final WithContentAction withContentAction = (WithContentAction) action;
// final String content = withContentAction.getContent();
//
// if (content != null) {
// logger.debug("render: {}", content);
// httpEntity = HttpEntity.fromString(content, "UTF-8");
// }
// }
//
// return ((PlayWebContext) context).supplementResponse(new Result(code, headers, httpEntity));
// }
//
// throw new TechnicalException("No action provided");
// }
//
// public Map<Integer, Result> getResults() {
// return results;
// }
//
// public void setResults(final Map<Integer, Result> results) {
// CommonHelper.assertNotNull("results", results);
// this.results = results;
// }
// }
// Path: shared/src/main/java/org/pac4j/play/CallbackController.java
import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.engine.CallbackLogic;
import org.pac4j.core.engine.DefaultCallbackLogic;
import org.pac4j.core.http.adapter.HttpActionAdapter;
import org.pac4j.core.util.FindBest;
import org.pac4j.play.context.PlayContextFactory;
import org.pac4j.play.http.PlayHttpActionAdapter;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.libs.concurrent.HttpExecutionContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
package org.pac4j.play;
/**
* <p>This filter finishes the login process for an indirect client.</p>
*
* @author Jerome Leleu
* @author Michael Remond
* @since 1.5.0
*/
public class CallbackController extends Controller {
private CallbackLogic callbackLogic;
private String defaultUrl;
private Boolean renewSession;
private String defaultClient;
@Inject
protected Config config;
@Inject
protected SessionStore sessionStore;
@Inject
protected HttpExecutionContext ec;
public CompletionStage<Result> callback(final Http.Request request) {
final HttpActionAdapter bestAdapter = FindBest.httpActionAdapter(null, config, PlayHttpActionAdapter.INSTANCE);
final CallbackLogic bestLogic = FindBest.callbackLogic(callbackLogic, config, DefaultCallbackLogic.INSTANCE);
|
final WebContext context = FindBest.webContextFactory(null, config, PlayContextFactory.INSTANCE).newContext(request);
|
pac4j/play-pac4j
|
shared/src/main/java/org/pac4j/play/LogoutController.java
|
// Path: shared/src/main/java/org/pac4j/play/context/PlayContextFactory.java
// public class PlayContextFactory implements WebContextFactory {
//
// public static final PlayContextFactory INSTANCE = new PlayContextFactory();
//
// protected PlayContextFactory() {}
//
// @Override
// public PlayWebContext newContext(final Object... parameters) {
// return new PlayWebContext((Http.Request) parameters[0]);
// }
// }
//
// Path: shared/src/main/java/org/pac4j/play/http/PlayHttpActionAdapter.java
// public class PlayHttpActionAdapter implements HttpActionAdapter {
//
// protected final Logger logger = LoggerFactory.getLogger(getClass());
//
// public static final PlayHttpActionAdapter INSTANCE = new PlayHttpActionAdapter();
//
// protected Map<Integer, Result> results = new HashMap<>();
//
// @Override
// public Result adapt(final HttpAction action, final WebContext context) {
// if (action != null) {
// final int code = action.getCode();
// logger.debug("requires HTTP action: {}", code);
//
// final Result predefinedResult = results.get(code);
// if (predefinedResult != null) {
// logger.debug("using pre-defined result for code: {}", code);
// return ((PlayWebContext) context).supplementResponse(predefinedResult);
// }
//
// Map<String, String> headers = new HashMap<>();
// HttpEntity httpEntity = HttpEntity.NO_ENTITY;
//
// if (action instanceof WithLocationAction) {
// final WithLocationAction withLocationAction = (WithLocationAction) action;
// headers.put(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
// } else if (action instanceof WithContentAction) {
// final WithContentAction withContentAction = (WithContentAction) action;
// final String content = withContentAction.getContent();
//
// if (content != null) {
// logger.debug("render: {}", content);
// httpEntity = HttpEntity.fromString(content, "UTF-8");
// }
// }
//
// return ((PlayWebContext) context).supplementResponse(new Result(code, headers, httpEntity));
// }
//
// throw new TechnicalException("No action provided");
// }
//
// public Map<Integer, Result> getResults() {
// return results;
// }
//
// public void setResults(final Map<Integer, Result> results) {
// CommonHelper.assertNotNull("results", results);
// this.results = results;
// }
// }
|
import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.engine.DefaultLogoutLogic;
import org.pac4j.core.engine.LogoutLogic;
import org.pac4j.core.http.adapter.HttpActionAdapter;
import org.pac4j.core.util.FindBest;
import org.pac4j.play.context.PlayContextFactory;
import org.pac4j.play.http.PlayHttpActionAdapter;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.libs.concurrent.HttpExecutionContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
|
package org.pac4j.play;
/**
* <p>This filter handles the (application + identity provider) logout process.</p>
*
* @author Jerome Leleu
* @since 2.0.0
*/
public class LogoutController extends Controller {
private LogoutLogic logoutLogic;
private String defaultUrl;
private String logoutUrlPattern;
private Boolean localLogout;
private Boolean destroySession;
private Boolean centralLogout;
@Inject
protected Config config;
@Inject
protected SessionStore sessionStore;
@Inject
protected HttpExecutionContext ec;
public CompletionStage<Result> logout(final Http.Request request) {
|
// Path: shared/src/main/java/org/pac4j/play/context/PlayContextFactory.java
// public class PlayContextFactory implements WebContextFactory {
//
// public static final PlayContextFactory INSTANCE = new PlayContextFactory();
//
// protected PlayContextFactory() {}
//
// @Override
// public PlayWebContext newContext(final Object... parameters) {
// return new PlayWebContext((Http.Request) parameters[0]);
// }
// }
//
// Path: shared/src/main/java/org/pac4j/play/http/PlayHttpActionAdapter.java
// public class PlayHttpActionAdapter implements HttpActionAdapter {
//
// protected final Logger logger = LoggerFactory.getLogger(getClass());
//
// public static final PlayHttpActionAdapter INSTANCE = new PlayHttpActionAdapter();
//
// protected Map<Integer, Result> results = new HashMap<>();
//
// @Override
// public Result adapt(final HttpAction action, final WebContext context) {
// if (action != null) {
// final int code = action.getCode();
// logger.debug("requires HTTP action: {}", code);
//
// final Result predefinedResult = results.get(code);
// if (predefinedResult != null) {
// logger.debug("using pre-defined result for code: {}", code);
// return ((PlayWebContext) context).supplementResponse(predefinedResult);
// }
//
// Map<String, String> headers = new HashMap<>();
// HttpEntity httpEntity = HttpEntity.NO_ENTITY;
//
// if (action instanceof WithLocationAction) {
// final WithLocationAction withLocationAction = (WithLocationAction) action;
// headers.put(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
// } else if (action instanceof WithContentAction) {
// final WithContentAction withContentAction = (WithContentAction) action;
// final String content = withContentAction.getContent();
//
// if (content != null) {
// logger.debug("render: {}", content);
// httpEntity = HttpEntity.fromString(content, "UTF-8");
// }
// }
//
// return ((PlayWebContext) context).supplementResponse(new Result(code, headers, httpEntity));
// }
//
// throw new TechnicalException("No action provided");
// }
//
// public Map<Integer, Result> getResults() {
// return results;
// }
//
// public void setResults(final Map<Integer, Result> results) {
// CommonHelper.assertNotNull("results", results);
// this.results = results;
// }
// }
// Path: shared/src/main/java/org/pac4j/play/LogoutController.java
import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.engine.DefaultLogoutLogic;
import org.pac4j.core.engine.LogoutLogic;
import org.pac4j.core.http.adapter.HttpActionAdapter;
import org.pac4j.core.util.FindBest;
import org.pac4j.play.context.PlayContextFactory;
import org.pac4j.play.http.PlayHttpActionAdapter;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.libs.concurrent.HttpExecutionContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
package org.pac4j.play;
/**
* <p>This filter handles the (application + identity provider) logout process.</p>
*
* @author Jerome Leleu
* @since 2.0.0
*/
public class LogoutController extends Controller {
private LogoutLogic logoutLogic;
private String defaultUrl;
private String logoutUrlPattern;
private Boolean localLogout;
private Boolean destroySession;
private Boolean centralLogout;
@Inject
protected Config config;
@Inject
protected SessionStore sessionStore;
@Inject
protected HttpExecutionContext ec;
public CompletionStage<Result> logout(final Http.Request request) {
|
final HttpActionAdapter bestAdapter = FindBest.httpActionAdapter(null, config, PlayHttpActionAdapter.INSTANCE);
|
pac4j/play-pac4j
|
shared/src/main/java/org/pac4j/play/LogoutController.java
|
// Path: shared/src/main/java/org/pac4j/play/context/PlayContextFactory.java
// public class PlayContextFactory implements WebContextFactory {
//
// public static final PlayContextFactory INSTANCE = new PlayContextFactory();
//
// protected PlayContextFactory() {}
//
// @Override
// public PlayWebContext newContext(final Object... parameters) {
// return new PlayWebContext((Http.Request) parameters[0]);
// }
// }
//
// Path: shared/src/main/java/org/pac4j/play/http/PlayHttpActionAdapter.java
// public class PlayHttpActionAdapter implements HttpActionAdapter {
//
// protected final Logger logger = LoggerFactory.getLogger(getClass());
//
// public static final PlayHttpActionAdapter INSTANCE = new PlayHttpActionAdapter();
//
// protected Map<Integer, Result> results = new HashMap<>();
//
// @Override
// public Result adapt(final HttpAction action, final WebContext context) {
// if (action != null) {
// final int code = action.getCode();
// logger.debug("requires HTTP action: {}", code);
//
// final Result predefinedResult = results.get(code);
// if (predefinedResult != null) {
// logger.debug("using pre-defined result for code: {}", code);
// return ((PlayWebContext) context).supplementResponse(predefinedResult);
// }
//
// Map<String, String> headers = new HashMap<>();
// HttpEntity httpEntity = HttpEntity.NO_ENTITY;
//
// if (action instanceof WithLocationAction) {
// final WithLocationAction withLocationAction = (WithLocationAction) action;
// headers.put(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
// } else if (action instanceof WithContentAction) {
// final WithContentAction withContentAction = (WithContentAction) action;
// final String content = withContentAction.getContent();
//
// if (content != null) {
// logger.debug("render: {}", content);
// httpEntity = HttpEntity.fromString(content, "UTF-8");
// }
// }
//
// return ((PlayWebContext) context).supplementResponse(new Result(code, headers, httpEntity));
// }
//
// throw new TechnicalException("No action provided");
// }
//
// public Map<Integer, Result> getResults() {
// return results;
// }
//
// public void setResults(final Map<Integer, Result> results) {
// CommonHelper.assertNotNull("results", results);
// this.results = results;
// }
// }
|
import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.engine.DefaultLogoutLogic;
import org.pac4j.core.engine.LogoutLogic;
import org.pac4j.core.http.adapter.HttpActionAdapter;
import org.pac4j.core.util.FindBest;
import org.pac4j.play.context.PlayContextFactory;
import org.pac4j.play.http.PlayHttpActionAdapter;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.libs.concurrent.HttpExecutionContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
|
package org.pac4j.play;
/**
* <p>This filter handles the (application + identity provider) logout process.</p>
*
* @author Jerome Leleu
* @since 2.0.0
*/
public class LogoutController extends Controller {
private LogoutLogic logoutLogic;
private String defaultUrl;
private String logoutUrlPattern;
private Boolean localLogout;
private Boolean destroySession;
private Boolean centralLogout;
@Inject
protected Config config;
@Inject
protected SessionStore sessionStore;
@Inject
protected HttpExecutionContext ec;
public CompletionStage<Result> logout(final Http.Request request) {
final HttpActionAdapter bestAdapter = FindBest.httpActionAdapter(null, config, PlayHttpActionAdapter.INSTANCE);
final LogoutLogic bestLogic = FindBest.logoutLogic(logoutLogic, config, DefaultLogoutLogic.INSTANCE);
|
// Path: shared/src/main/java/org/pac4j/play/context/PlayContextFactory.java
// public class PlayContextFactory implements WebContextFactory {
//
// public static final PlayContextFactory INSTANCE = new PlayContextFactory();
//
// protected PlayContextFactory() {}
//
// @Override
// public PlayWebContext newContext(final Object... parameters) {
// return new PlayWebContext((Http.Request) parameters[0]);
// }
// }
//
// Path: shared/src/main/java/org/pac4j/play/http/PlayHttpActionAdapter.java
// public class PlayHttpActionAdapter implements HttpActionAdapter {
//
// protected final Logger logger = LoggerFactory.getLogger(getClass());
//
// public static final PlayHttpActionAdapter INSTANCE = new PlayHttpActionAdapter();
//
// protected Map<Integer, Result> results = new HashMap<>();
//
// @Override
// public Result adapt(final HttpAction action, final WebContext context) {
// if (action != null) {
// final int code = action.getCode();
// logger.debug("requires HTTP action: {}", code);
//
// final Result predefinedResult = results.get(code);
// if (predefinedResult != null) {
// logger.debug("using pre-defined result for code: {}", code);
// return ((PlayWebContext) context).supplementResponse(predefinedResult);
// }
//
// Map<String, String> headers = new HashMap<>();
// HttpEntity httpEntity = HttpEntity.NO_ENTITY;
//
// if (action instanceof WithLocationAction) {
// final WithLocationAction withLocationAction = (WithLocationAction) action;
// headers.put(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
// } else if (action instanceof WithContentAction) {
// final WithContentAction withContentAction = (WithContentAction) action;
// final String content = withContentAction.getContent();
//
// if (content != null) {
// logger.debug("render: {}", content);
// httpEntity = HttpEntity.fromString(content, "UTF-8");
// }
// }
//
// return ((PlayWebContext) context).supplementResponse(new Result(code, headers, httpEntity));
// }
//
// throw new TechnicalException("No action provided");
// }
//
// public Map<Integer, Result> getResults() {
// return results;
// }
//
// public void setResults(final Map<Integer, Result> results) {
// CommonHelper.assertNotNull("results", results);
// this.results = results;
// }
// }
// Path: shared/src/main/java/org/pac4j/play/LogoutController.java
import org.pac4j.core.config.Config;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.engine.DefaultLogoutLogic;
import org.pac4j.core.engine.LogoutLogic;
import org.pac4j.core.http.adapter.HttpActionAdapter;
import org.pac4j.core.util.FindBest;
import org.pac4j.play.context.PlayContextFactory;
import org.pac4j.play.http.PlayHttpActionAdapter;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
import play.libs.concurrent.HttpExecutionContext;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
package org.pac4j.play;
/**
* <p>This filter handles the (application + identity provider) logout process.</p>
*
* @author Jerome Leleu
* @since 2.0.0
*/
public class LogoutController extends Controller {
private LogoutLogic logoutLogic;
private String defaultUrl;
private String logoutUrlPattern;
private Boolean localLogout;
private Boolean destroySession;
private Boolean centralLogout;
@Inject
protected Config config;
@Inject
protected SessionStore sessionStore;
@Inject
protected HttpExecutionContext ec;
public CompletionStage<Result> logout(final Http.Request request) {
final HttpActionAdapter bestAdapter = FindBest.httpActionAdapter(null, config, PlayHttpActionAdapter.INSTANCE);
final LogoutLogic bestLogic = FindBest.logoutLogic(logoutLogic, config, DefaultLogoutLogic.INSTANCE);
|
final WebContext context = FindBest.webContextFactory(null, config, PlayContextFactory.INSTANCE).newContext(request);
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/list/ItemsAdapter.java
// public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ItemsViewHolder> {
//
// List<String> items = new ArrayList<>();
// @Inject
// public ItemsAdapter() {
//
// }
//
// @Override
// public ItemsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_held, parent, false);
// return new ItemsViewHolder(view);
// }
//
// @Override
// public void onBindViewHolder(ItemsViewHolder holder, int position) {
// String move = items.get(position);
// holder.dataBinding.setMove(move);
// }
//
// public void updateList(List<String> items) {
// this.items.clear();
// this.items.addAll(items);
// notifyDataSetChanged();
// }
//
// @Override
// public int getItemCount() {
// return items.size();
// }
//
// public class ItemsViewHolder extends RecyclerView.ViewHolder {
//
// private final ItemHeldBinding dataBinding;
//
// public ItemsViewHolder(View itemView) {
// super(itemView);
// dataBinding = DataBindingUtil.bind(itemView);
// }
// }
//
// }
|
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import com.ragdroid.dahaka.activity.items.list.ItemsAdapter;
import dagger.Module;
import dagger.Provides;
|
package com.ragdroid.dahaka.activity.items;
/**
* Created by garimajain on 17/08/17.
*/
@Module
public class ItemsModule {
@Provides
static ItemsContract.Presenter provideHomePresenter(ItemsPresenter presenter) {
return presenter;
}
@Provides
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/list/ItemsAdapter.java
// public class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ItemsViewHolder> {
//
// List<String> items = new ArrayList<>();
// @Inject
// public ItemsAdapter() {
//
// }
//
// @Override
// public ItemsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_held, parent, false);
// return new ItemsViewHolder(view);
// }
//
// @Override
// public void onBindViewHolder(ItemsViewHolder holder, int position) {
// String move = items.get(position);
// holder.dataBinding.setMove(move);
// }
//
// public void updateList(List<String> items) {
// this.items.clear();
// this.items.addAll(items);
// notifyDataSetChanged();
// }
//
// @Override
// public int getItemCount() {
// return items.size();
// }
//
// public class ItemsViewHolder extends RecyclerView.ViewHolder {
//
// private final ItemHeldBinding dataBinding;
//
// public ItemsViewHolder(View itemView) {
// super(itemView);
// dataBinding = DataBindingUtil.bind(itemView);
// }
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsModule.java
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import com.ragdroid.dahaka.activity.items.list.ItemsAdapter;
import dagger.Module;
import dagger.Provides;
package com.ragdroid.dahaka.activity.items;
/**
* Created by garimajain on 17/08/17.
*/
@Module
public class ItemsModule {
@Provides
static ItemsContract.Presenter provideHomePresenter(ItemsPresenter presenter) {
return presenter;
}
@Provides
|
static ItemsAdapter provideItemsAdapter() {
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/activity/home/stats/StatsContract.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
//
// void onViewAdded(T view);
//
// void onViewRemoved();
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseView.java
// public interface BaseView {
//
// void showMessage(String message);
//
// void finishView();
//
// }
|
import com.ragdroid.dahaka.mvp.BasePresenter;
import com.ragdroid.dahaka.mvp.BaseView;
|
package com.ragdroid.dahaka.activity.home.stats;
/**
* Created by garimajain on 13/08/17.
*/
public interface StatsContract {
interface View extends BaseView {
void showModel(StatsModel statsModel);
}
|
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
//
// void onViewAdded(T view);
//
// void onViewRemoved();
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseView.java
// public interface BaseView {
//
// void showMessage(String message);
//
// void finishView();
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/stats/StatsContract.java
import com.ragdroid.dahaka.mvp.BasePresenter;
import com.ragdroid.dahaka.mvp.BaseView;
package com.ragdroid.dahaka.activity.home.stats;
/**
* Created by garimajain on 13/08/17.
*/
public interface StatsContract {
interface View extends BaseView {
void showModel(StatsModel statsModel);
}
|
interface Presenter extends BasePresenter<View> {
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/app/AppModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/util/BaseSchedulerProvider.java
// public interface BaseSchedulerProvider {
// @NonNull
// Scheduler computation();
//
// @NonNull
// Scheduler io();
//
// @NonNull
// Scheduler ui();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/util/SchedulerProvider.java
// @Reusable
// public class SchedulerProvider implements BaseSchedulerProvider {
//
// @Inject
// public SchedulerProvider() {
//
// }
//
// @Override
// @NonNull
// public Scheduler computation() {
// return Schedulers.computation();
// }
//
// @Override
// @NonNull
// public Scheduler io() {
// return Schedulers.io();
// }
//
// @Override
// @NonNull
// public Scheduler ui() {
// return AndroidSchedulers.mainThread();
// }
// }
|
import com.ragdroid.dahaka.util.BaseSchedulerProvider;
import com.ragdroid.dahaka.util.SchedulerProvider;
import dagger.Binds;
import dagger.Module;
import dagger.Provides;
|
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class AppModule {
@Binds
|
// Path: app/src/main/java/com/ragdroid/dahaka/util/BaseSchedulerProvider.java
// public interface BaseSchedulerProvider {
// @NonNull
// Scheduler computation();
//
// @NonNull
// Scheduler io();
//
// @NonNull
// Scheduler ui();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/util/SchedulerProvider.java
// @Reusable
// public class SchedulerProvider implements BaseSchedulerProvider {
//
// @Inject
// public SchedulerProvider() {
//
// }
//
// @Override
// @NonNull
// public Scheduler computation() {
// return Schedulers.computation();
// }
//
// @Override
// @NonNull
// public Scheduler io() {
// return Schedulers.io();
// }
//
// @Override
// @NonNull
// public Scheduler ui() {
// return AndroidSchedulers.mainThread();
// }
// }
// Path: app/src/main/java/com/ragdroid/dahaka/app/AppModule.java
import com.ragdroid.dahaka.util.BaseSchedulerProvider;
import com.ragdroid.dahaka.util.SchedulerProvider;
import dagger.Binds;
import dagger.Module;
import dagger.Provides;
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class AppModule {
@Binds
|
abstract BaseSchedulerProvider providerSchedulerProvider(SchedulerProvider provider);
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/app/AppModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/util/BaseSchedulerProvider.java
// public interface BaseSchedulerProvider {
// @NonNull
// Scheduler computation();
//
// @NonNull
// Scheduler io();
//
// @NonNull
// Scheduler ui();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/util/SchedulerProvider.java
// @Reusable
// public class SchedulerProvider implements BaseSchedulerProvider {
//
// @Inject
// public SchedulerProvider() {
//
// }
//
// @Override
// @NonNull
// public Scheduler computation() {
// return Schedulers.computation();
// }
//
// @Override
// @NonNull
// public Scheduler io() {
// return Schedulers.io();
// }
//
// @Override
// @NonNull
// public Scheduler ui() {
// return AndroidSchedulers.mainThread();
// }
// }
|
import com.ragdroid.dahaka.util.BaseSchedulerProvider;
import com.ragdroid.dahaka.util.SchedulerProvider;
import dagger.Binds;
import dagger.Module;
import dagger.Provides;
|
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class AppModule {
@Binds
|
// Path: app/src/main/java/com/ragdroid/dahaka/util/BaseSchedulerProvider.java
// public interface BaseSchedulerProvider {
// @NonNull
// Scheduler computation();
//
// @NonNull
// Scheduler io();
//
// @NonNull
// Scheduler ui();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/util/SchedulerProvider.java
// @Reusable
// public class SchedulerProvider implements BaseSchedulerProvider {
//
// @Inject
// public SchedulerProvider() {
//
// }
//
// @Override
// @NonNull
// public Scheduler computation() {
// return Schedulers.computation();
// }
//
// @Override
// @NonNull
// public Scheduler io() {
// return Schedulers.io();
// }
//
// @Override
// @NonNull
// public Scheduler ui() {
// return AndroidSchedulers.mainThread();
// }
// }
// Path: app/src/main/java/com/ragdroid/dahaka/app/AppModule.java
import com.ragdroid.dahaka.util.BaseSchedulerProvider;
import com.ragdroid.dahaka.util.SchedulerProvider;
import dagger.Binds;
import dagger.Module;
import dagger.Provides;
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class AppModule {
@Binds
|
abstract BaseSchedulerProvider providerSchedulerProvider(SchedulerProvider provider);
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/mvp/BaseActivity.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
// public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
//
// private ActivityLoginBinding binding;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setTitle(R.string.title_activity_login);
// binding.setPresenter(getPresenter());
// }
//
// @Override
// public void showHome() {
// Intent intent = new Intent(this, HomeActivity.class);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void setModel(LoginModel loginModel) {
// binding.setModel(loginModel);
// }
// }
|
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.ragdroid.dahaka.activity.login.LoginActivity;
import javax.inject.Inject;
import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
|
package com.ragdroid.dahaka.mvp;
/**
* Created by garimajain on 13/08/17.
*/
public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements BaseView,
HasSupportFragmentInjector {
public T getPresenter() {
return presenter;
}
@Inject DispatchingAndroidInjector<Fragment> injector;
@Inject
T presenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
androidInject();
super.onCreate(savedInstanceState);
presenter.onViewAdded(this);
}
protected void androidInject() {
AndroidInjection.inject(this);
}
@Override
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
presenter.onViewRemoved();
super.onDestroy();
}
@Override
public void finishView() {
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
// public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
//
// private ActivityLoginBinding binding;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setTitle(R.string.title_activity_login);
// binding.setPresenter(getPresenter());
// }
//
// @Override
// public void showHome() {
// Intent intent = new Intent(this, HomeActivity.class);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void setModel(LoginModel loginModel) {
// binding.setModel(loginModel);
// }
// }
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.ragdroid.dahaka.activity.login.LoginActivity;
import javax.inject.Inject;
import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
package com.ragdroid.dahaka.mvp;
/**
* Created by garimajain on 13/08/17.
*/
public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements BaseView,
HasSupportFragmentInjector {
public T getPresenter() {
return presenter;
}
@Inject DispatchingAndroidInjector<Fragment> injector;
@Inject
T presenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
androidInject();
super.onCreate(savedInstanceState);
presenter.onViewAdded(this);
}
protected void androidInject() {
AndroidInjection.inject(this);
}
@Override
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
presenter.onViewRemoved();
super.onDestroy();
}
@Override
public void finishView() {
|
startActivity(new Intent(this, LoginActivity.class));
|
ragdroid/Dahaka
|
app/src/androidTest/java/com/ragdroid/dahaka/app/MockAppModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/util/BaseSchedulerProvider.java
// public interface BaseSchedulerProvider {
// @NonNull
// Scheduler computation();
//
// @NonNull
// Scheduler io();
//
// @NonNull
// Scheduler ui();
// }
|
import com.ragdroid.dahaka.util.BaseSchedulerProvider;
import org.mockito.Mockito;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.TestScheduler;
import static org.mockito.Mockito.when;
|
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 28/08/17.
*/
@Module
public class MockAppModule {
@Singleton
@Provides
static TestScheduler provideTestScheduler() {
return new TestScheduler();
}
@Provides
@Singleton
|
// Path: app/src/main/java/com/ragdroid/dahaka/util/BaseSchedulerProvider.java
// public interface BaseSchedulerProvider {
// @NonNull
// Scheduler computation();
//
// @NonNull
// Scheduler io();
//
// @NonNull
// Scheduler ui();
// }
// Path: app/src/androidTest/java/com/ragdroid/dahaka/app/MockAppModule.java
import com.ragdroid.dahaka.util.BaseSchedulerProvider;
import org.mockito.Mockito;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.TestScheduler;
import static org.mockito.Mockito.when;
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 28/08/17.
*/
@Module
public class MockAppModule {
@Singleton
@Provides
static TestScheduler provideTestScheduler() {
return new TestScheduler();
}
@Provides
@Singleton
|
public static BaseSchedulerProvider provideBaseScheduler(TestScheduler testScheduler) {
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/activity/home/moves/MovesContract.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
//
// void onViewAdded(T view);
//
// void onViewRemoved();
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseView.java
// public interface BaseView {
//
// void showMessage(String message);
//
// void finishView();
//
// }
|
import com.ragdroid.dahaka.mvp.BasePresenter;
import com.ragdroid.dahaka.mvp.BaseView;
|
package com.ragdroid.dahaka.activity.home.moves;
/**
* Created by garimajain on 13/08/17.
*/
public interface MovesContract {
interface View extends BaseView {
void showModel(MovesModel statsModel);
}
|
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
//
// void onViewAdded(T view);
//
// void onViewRemoved();
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseView.java
// public interface BaseView {
//
// void showMessage(String message);
//
// void finishView();
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/moves/MovesContract.java
import com.ragdroid.dahaka.mvp.BasePresenter;
import com.ragdroid.dahaka.mvp.BaseView;
package com.ragdroid.dahaka.activity.home.moves;
/**
* Created by garimajain on 13/08/17.
*/
public interface MovesContract {
interface View extends BaseView {
void showModel(MovesModel statsModel);
}
|
interface Presenter extends BasePresenter<View> {
|
ragdroid/Dahaka
|
app/src/androidTest/java/com/ragdroid/dahaka/api/MockApiModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/user/PokemonService.java
// @UserScope
// public interface PokemonService {
//
// /**
// * fetch pokemon user
// * @param id
// * @return
// */
// @Headers("Content-Type: application/json")
// @GET("pokemon/{name}")
// Single<Pokemon> getPokemon(@Path("name") String id);
//
// }
|
import com.ragdroid.dahaka.user.PokemonService;
import org.mockito.Mockito;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
|
package com.ragdroid.dahaka.api;
/**
* Created by garimajain on 28/08/17.
*/
@Module
public class MockApiModule {
@Provides
@Singleton
|
// Path: app/src/main/java/com/ragdroid/dahaka/user/PokemonService.java
// @UserScope
// public interface PokemonService {
//
// /**
// * fetch pokemon user
// * @param id
// * @return
// */
// @Headers("Content-Type: application/json")
// @GET("pokemon/{name}")
// Single<Pokemon> getPokemon(@Path("name") String id);
//
// }
// Path: app/src/androidTest/java/com/ragdroid/dahaka/api/MockApiModule.java
import com.ragdroid.dahaka.user.PokemonService;
import org.mockito.Mockito;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
package com.ragdroid.dahaka.api;
/**
* Created by garimajain on 28/08/17.
*/
@Module
public class MockApiModule {
@Provides
@Singleton
|
static PokemonService providePokemonService() {
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/app/AppComponent.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/DahakaApplication.java
// public class DahakaApplication extends Application implements HasActivityInjector {
//
// @Inject DispatchingAndroidInjector<Activity> activityInjector;
// @Inject UserManager userManager;
//
// public AppComponent getAppComponent() {
// return appComponent;
// }
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DataBindingUtil.setDefaultComponent(buildDataBindingComponent());
// createComponent();
// }
//
// protected void createComponent() {
// appComponent = DaggerAppComponent.builder().application(this).build();
// appComponent.inject(this);
// }
//
// private DataBindingComponent buildDataBindingComponent() {
// return DaggerAppDataBindingComponent.builder().application(this).build();
// }
//
// @Override
// public AndroidInjector<Activity> activityInjector() {
// return userManager.activityInjector();
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
// @Module(subcomponents = UserComponent.class)
// public abstract class AppBindingModule {
//
// @ContributesAndroidInjector(modules = LoginModule.class)
// @ActivityScope
// abstract LoginActivity loginActivity();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/api/ApiModule.java
// @Module
// public class ApiModule {
//
//
// private static final long CACHE_SIZE = 10 * 1024 * 1024; //10 MB
//
// @Provides
// @Singleton
// public static HttpLoggingInterceptor getLoggingInterceptor() {
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// return loggingInterceptor;
// }
//
//
// @Provides
// @Singleton
// static Gson provideGson() {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// return gsonBuilder.create();
// }
//
// @Provides
// @Singleton
// static Cache provideOkhttpCache(Application application) {
// return new Cache(application.getCacheDir(), CACHE_SIZE);
// }
//
// @Provides
// @Singleton
// static Interceptor provideCacheOverrideInterceptor() {
// return chain -> {
// int maxStale = 60 * 60 * 24 * 7; // tolerate 1-week stale
// return chain.proceed(chain.request())
// .newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-age=" + maxStale)
// .build();
// };
// }
//
// @Provides
// @Singleton
// static OkHttpClient provideOkHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache,
// Interceptor cacheOverrideInterceptor) {
// OkHttpClient.Builder builder = new OkHttpClient.Builder()
// .cache(cache)
// .addInterceptor(loggingInterceptor)
// .connectTimeout(60, TimeUnit.SECONDS)
// .readTimeout(60, TimeUnit.SECONDS)
// .writeTimeout(60, TimeUnit.SECONDS)
// .addNetworkInterceptor(cacheOverrideInterceptor);
// return builder
// .build();
//
// }
//
//
// @Provides
// @Singleton
// static Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(gson))
// .baseUrl(getBaseUrl())
// .client(okHttpClient)
// .build();
// }
//
// protected static String getBaseUrl() {
// return "http://pokeapi.co/api/v2/";
// }
//
// @Provides
// @Singleton
// public static PokemonService providePokemonService(Retrofit retrofit) {
// return retrofit.create(PokemonService.class);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
|
import android.app.Application;
import com.ragdroid.dahaka.DahakaApplication;
import com.ragdroid.dahaka.activity.AppBindingModule;
import com.ragdroid.dahaka.api.ApiModule;
import com.ragdroid.dahaka.user.UserComponent;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import dagger.android.support.AndroidSupportInjectionModule;
|
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Singleton
@Component(modules = {
AppModule.class,
|
// Path: app/src/main/java/com/ragdroid/dahaka/DahakaApplication.java
// public class DahakaApplication extends Application implements HasActivityInjector {
//
// @Inject DispatchingAndroidInjector<Activity> activityInjector;
// @Inject UserManager userManager;
//
// public AppComponent getAppComponent() {
// return appComponent;
// }
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DataBindingUtil.setDefaultComponent(buildDataBindingComponent());
// createComponent();
// }
//
// protected void createComponent() {
// appComponent = DaggerAppComponent.builder().application(this).build();
// appComponent.inject(this);
// }
//
// private DataBindingComponent buildDataBindingComponent() {
// return DaggerAppDataBindingComponent.builder().application(this).build();
// }
//
// @Override
// public AndroidInjector<Activity> activityInjector() {
// return userManager.activityInjector();
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
// @Module(subcomponents = UserComponent.class)
// public abstract class AppBindingModule {
//
// @ContributesAndroidInjector(modules = LoginModule.class)
// @ActivityScope
// abstract LoginActivity loginActivity();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/api/ApiModule.java
// @Module
// public class ApiModule {
//
//
// private static final long CACHE_SIZE = 10 * 1024 * 1024; //10 MB
//
// @Provides
// @Singleton
// public static HttpLoggingInterceptor getLoggingInterceptor() {
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// return loggingInterceptor;
// }
//
//
// @Provides
// @Singleton
// static Gson provideGson() {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// return gsonBuilder.create();
// }
//
// @Provides
// @Singleton
// static Cache provideOkhttpCache(Application application) {
// return new Cache(application.getCacheDir(), CACHE_SIZE);
// }
//
// @Provides
// @Singleton
// static Interceptor provideCacheOverrideInterceptor() {
// return chain -> {
// int maxStale = 60 * 60 * 24 * 7; // tolerate 1-week stale
// return chain.proceed(chain.request())
// .newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-age=" + maxStale)
// .build();
// };
// }
//
// @Provides
// @Singleton
// static OkHttpClient provideOkHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache,
// Interceptor cacheOverrideInterceptor) {
// OkHttpClient.Builder builder = new OkHttpClient.Builder()
// .cache(cache)
// .addInterceptor(loggingInterceptor)
// .connectTimeout(60, TimeUnit.SECONDS)
// .readTimeout(60, TimeUnit.SECONDS)
// .writeTimeout(60, TimeUnit.SECONDS)
// .addNetworkInterceptor(cacheOverrideInterceptor);
// return builder
// .build();
//
// }
//
//
// @Provides
// @Singleton
// static Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(gson))
// .baseUrl(getBaseUrl())
// .client(okHttpClient)
// .build();
// }
//
// protected static String getBaseUrl() {
// return "http://pokeapi.co/api/v2/";
// }
//
// @Provides
// @Singleton
// public static PokemonService providePokemonService(Retrofit retrofit) {
// return retrofit.create(PokemonService.class);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/app/AppComponent.java
import android.app.Application;
import com.ragdroid.dahaka.DahakaApplication;
import com.ragdroid.dahaka.activity.AppBindingModule;
import com.ragdroid.dahaka.api.ApiModule;
import com.ragdroid.dahaka.user.UserComponent;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import dagger.android.support.AndroidSupportInjectionModule;
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Singleton
@Component(modules = {
AppModule.class,
|
ApiModule.class,
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/app/AppComponent.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/DahakaApplication.java
// public class DahakaApplication extends Application implements HasActivityInjector {
//
// @Inject DispatchingAndroidInjector<Activity> activityInjector;
// @Inject UserManager userManager;
//
// public AppComponent getAppComponent() {
// return appComponent;
// }
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DataBindingUtil.setDefaultComponent(buildDataBindingComponent());
// createComponent();
// }
//
// protected void createComponent() {
// appComponent = DaggerAppComponent.builder().application(this).build();
// appComponent.inject(this);
// }
//
// private DataBindingComponent buildDataBindingComponent() {
// return DaggerAppDataBindingComponent.builder().application(this).build();
// }
//
// @Override
// public AndroidInjector<Activity> activityInjector() {
// return userManager.activityInjector();
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
// @Module(subcomponents = UserComponent.class)
// public abstract class AppBindingModule {
//
// @ContributesAndroidInjector(modules = LoginModule.class)
// @ActivityScope
// abstract LoginActivity loginActivity();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/api/ApiModule.java
// @Module
// public class ApiModule {
//
//
// private static final long CACHE_SIZE = 10 * 1024 * 1024; //10 MB
//
// @Provides
// @Singleton
// public static HttpLoggingInterceptor getLoggingInterceptor() {
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// return loggingInterceptor;
// }
//
//
// @Provides
// @Singleton
// static Gson provideGson() {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// return gsonBuilder.create();
// }
//
// @Provides
// @Singleton
// static Cache provideOkhttpCache(Application application) {
// return new Cache(application.getCacheDir(), CACHE_SIZE);
// }
//
// @Provides
// @Singleton
// static Interceptor provideCacheOverrideInterceptor() {
// return chain -> {
// int maxStale = 60 * 60 * 24 * 7; // tolerate 1-week stale
// return chain.proceed(chain.request())
// .newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-age=" + maxStale)
// .build();
// };
// }
//
// @Provides
// @Singleton
// static OkHttpClient provideOkHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache,
// Interceptor cacheOverrideInterceptor) {
// OkHttpClient.Builder builder = new OkHttpClient.Builder()
// .cache(cache)
// .addInterceptor(loggingInterceptor)
// .connectTimeout(60, TimeUnit.SECONDS)
// .readTimeout(60, TimeUnit.SECONDS)
// .writeTimeout(60, TimeUnit.SECONDS)
// .addNetworkInterceptor(cacheOverrideInterceptor);
// return builder
// .build();
//
// }
//
//
// @Provides
// @Singleton
// static Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(gson))
// .baseUrl(getBaseUrl())
// .client(okHttpClient)
// .build();
// }
//
// protected static String getBaseUrl() {
// return "http://pokeapi.co/api/v2/";
// }
//
// @Provides
// @Singleton
// public static PokemonService providePokemonService(Retrofit retrofit) {
// return retrofit.create(PokemonService.class);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
|
import android.app.Application;
import com.ragdroid.dahaka.DahakaApplication;
import com.ragdroid.dahaka.activity.AppBindingModule;
import com.ragdroid.dahaka.api.ApiModule;
import com.ragdroid.dahaka.user.UserComponent;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import dagger.android.support.AndroidSupportInjectionModule;
|
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Singleton
@Component(modules = {
AppModule.class,
ApiModule.class,
|
// Path: app/src/main/java/com/ragdroid/dahaka/DahakaApplication.java
// public class DahakaApplication extends Application implements HasActivityInjector {
//
// @Inject DispatchingAndroidInjector<Activity> activityInjector;
// @Inject UserManager userManager;
//
// public AppComponent getAppComponent() {
// return appComponent;
// }
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DataBindingUtil.setDefaultComponent(buildDataBindingComponent());
// createComponent();
// }
//
// protected void createComponent() {
// appComponent = DaggerAppComponent.builder().application(this).build();
// appComponent.inject(this);
// }
//
// private DataBindingComponent buildDataBindingComponent() {
// return DaggerAppDataBindingComponent.builder().application(this).build();
// }
//
// @Override
// public AndroidInjector<Activity> activityInjector() {
// return userManager.activityInjector();
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
// @Module(subcomponents = UserComponent.class)
// public abstract class AppBindingModule {
//
// @ContributesAndroidInjector(modules = LoginModule.class)
// @ActivityScope
// abstract LoginActivity loginActivity();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/api/ApiModule.java
// @Module
// public class ApiModule {
//
//
// private static final long CACHE_SIZE = 10 * 1024 * 1024; //10 MB
//
// @Provides
// @Singleton
// public static HttpLoggingInterceptor getLoggingInterceptor() {
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// return loggingInterceptor;
// }
//
//
// @Provides
// @Singleton
// static Gson provideGson() {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// return gsonBuilder.create();
// }
//
// @Provides
// @Singleton
// static Cache provideOkhttpCache(Application application) {
// return new Cache(application.getCacheDir(), CACHE_SIZE);
// }
//
// @Provides
// @Singleton
// static Interceptor provideCacheOverrideInterceptor() {
// return chain -> {
// int maxStale = 60 * 60 * 24 * 7; // tolerate 1-week stale
// return chain.proceed(chain.request())
// .newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-age=" + maxStale)
// .build();
// };
// }
//
// @Provides
// @Singleton
// static OkHttpClient provideOkHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache,
// Interceptor cacheOverrideInterceptor) {
// OkHttpClient.Builder builder = new OkHttpClient.Builder()
// .cache(cache)
// .addInterceptor(loggingInterceptor)
// .connectTimeout(60, TimeUnit.SECONDS)
// .readTimeout(60, TimeUnit.SECONDS)
// .writeTimeout(60, TimeUnit.SECONDS)
// .addNetworkInterceptor(cacheOverrideInterceptor);
// return builder
// .build();
//
// }
//
//
// @Provides
// @Singleton
// static Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(gson))
// .baseUrl(getBaseUrl())
// .client(okHttpClient)
// .build();
// }
//
// protected static String getBaseUrl() {
// return "http://pokeapi.co/api/v2/";
// }
//
// @Provides
// @Singleton
// public static PokemonService providePokemonService(Retrofit retrofit) {
// return retrofit.create(PokemonService.class);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/app/AppComponent.java
import android.app.Application;
import com.ragdroid.dahaka.DahakaApplication;
import com.ragdroid.dahaka.activity.AppBindingModule;
import com.ragdroid.dahaka.api.ApiModule;
import com.ragdroid.dahaka.user.UserComponent;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import dagger.android.support.AndroidSupportInjectionModule;
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Singleton
@Component(modules = {
AppModule.class,
ApiModule.class,
|
AppBindingModule.class,
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/app/AppComponent.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/DahakaApplication.java
// public class DahakaApplication extends Application implements HasActivityInjector {
//
// @Inject DispatchingAndroidInjector<Activity> activityInjector;
// @Inject UserManager userManager;
//
// public AppComponent getAppComponent() {
// return appComponent;
// }
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DataBindingUtil.setDefaultComponent(buildDataBindingComponent());
// createComponent();
// }
//
// protected void createComponent() {
// appComponent = DaggerAppComponent.builder().application(this).build();
// appComponent.inject(this);
// }
//
// private DataBindingComponent buildDataBindingComponent() {
// return DaggerAppDataBindingComponent.builder().application(this).build();
// }
//
// @Override
// public AndroidInjector<Activity> activityInjector() {
// return userManager.activityInjector();
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
// @Module(subcomponents = UserComponent.class)
// public abstract class AppBindingModule {
//
// @ContributesAndroidInjector(modules = LoginModule.class)
// @ActivityScope
// abstract LoginActivity loginActivity();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/api/ApiModule.java
// @Module
// public class ApiModule {
//
//
// private static final long CACHE_SIZE = 10 * 1024 * 1024; //10 MB
//
// @Provides
// @Singleton
// public static HttpLoggingInterceptor getLoggingInterceptor() {
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// return loggingInterceptor;
// }
//
//
// @Provides
// @Singleton
// static Gson provideGson() {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// return gsonBuilder.create();
// }
//
// @Provides
// @Singleton
// static Cache provideOkhttpCache(Application application) {
// return new Cache(application.getCacheDir(), CACHE_SIZE);
// }
//
// @Provides
// @Singleton
// static Interceptor provideCacheOverrideInterceptor() {
// return chain -> {
// int maxStale = 60 * 60 * 24 * 7; // tolerate 1-week stale
// return chain.proceed(chain.request())
// .newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-age=" + maxStale)
// .build();
// };
// }
//
// @Provides
// @Singleton
// static OkHttpClient provideOkHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache,
// Interceptor cacheOverrideInterceptor) {
// OkHttpClient.Builder builder = new OkHttpClient.Builder()
// .cache(cache)
// .addInterceptor(loggingInterceptor)
// .connectTimeout(60, TimeUnit.SECONDS)
// .readTimeout(60, TimeUnit.SECONDS)
// .writeTimeout(60, TimeUnit.SECONDS)
// .addNetworkInterceptor(cacheOverrideInterceptor);
// return builder
// .build();
//
// }
//
//
// @Provides
// @Singleton
// static Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(gson))
// .baseUrl(getBaseUrl())
// .client(okHttpClient)
// .build();
// }
//
// protected static String getBaseUrl() {
// return "http://pokeapi.co/api/v2/";
// }
//
// @Provides
// @Singleton
// public static PokemonService providePokemonService(Retrofit retrofit) {
// return retrofit.create(PokemonService.class);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
|
import android.app.Application;
import com.ragdroid.dahaka.DahakaApplication;
import com.ragdroid.dahaka.activity.AppBindingModule;
import com.ragdroid.dahaka.api.ApiModule;
import com.ragdroid.dahaka.user.UserComponent;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import dagger.android.support.AndroidSupportInjectionModule;
|
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Singleton
@Component(modules = {
AppModule.class,
ApiModule.class,
AppBindingModule.class,
AndroidSupportInjectionModule.class})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
|
// Path: app/src/main/java/com/ragdroid/dahaka/DahakaApplication.java
// public class DahakaApplication extends Application implements HasActivityInjector {
//
// @Inject DispatchingAndroidInjector<Activity> activityInjector;
// @Inject UserManager userManager;
//
// public AppComponent getAppComponent() {
// return appComponent;
// }
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DataBindingUtil.setDefaultComponent(buildDataBindingComponent());
// createComponent();
// }
//
// protected void createComponent() {
// appComponent = DaggerAppComponent.builder().application(this).build();
// appComponent.inject(this);
// }
//
// private DataBindingComponent buildDataBindingComponent() {
// return DaggerAppDataBindingComponent.builder().application(this).build();
// }
//
// @Override
// public AndroidInjector<Activity> activityInjector() {
// return userManager.activityInjector();
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
// @Module(subcomponents = UserComponent.class)
// public abstract class AppBindingModule {
//
// @ContributesAndroidInjector(modules = LoginModule.class)
// @ActivityScope
// abstract LoginActivity loginActivity();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/api/ApiModule.java
// @Module
// public class ApiModule {
//
//
// private static final long CACHE_SIZE = 10 * 1024 * 1024; //10 MB
//
// @Provides
// @Singleton
// public static HttpLoggingInterceptor getLoggingInterceptor() {
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// return loggingInterceptor;
// }
//
//
// @Provides
// @Singleton
// static Gson provideGson() {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// return gsonBuilder.create();
// }
//
// @Provides
// @Singleton
// static Cache provideOkhttpCache(Application application) {
// return new Cache(application.getCacheDir(), CACHE_SIZE);
// }
//
// @Provides
// @Singleton
// static Interceptor provideCacheOverrideInterceptor() {
// return chain -> {
// int maxStale = 60 * 60 * 24 * 7; // tolerate 1-week stale
// return chain.proceed(chain.request())
// .newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-age=" + maxStale)
// .build();
// };
// }
//
// @Provides
// @Singleton
// static OkHttpClient provideOkHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache,
// Interceptor cacheOverrideInterceptor) {
// OkHttpClient.Builder builder = new OkHttpClient.Builder()
// .cache(cache)
// .addInterceptor(loggingInterceptor)
// .connectTimeout(60, TimeUnit.SECONDS)
// .readTimeout(60, TimeUnit.SECONDS)
// .writeTimeout(60, TimeUnit.SECONDS)
// .addNetworkInterceptor(cacheOverrideInterceptor);
// return builder
// .build();
//
// }
//
//
// @Provides
// @Singleton
// static Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(gson))
// .baseUrl(getBaseUrl())
// .client(okHttpClient)
// .build();
// }
//
// protected static String getBaseUrl() {
// return "http://pokeapi.co/api/v2/";
// }
//
// @Provides
// @Singleton
// public static PokemonService providePokemonService(Retrofit retrofit) {
// return retrofit.create(PokemonService.class);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/app/AppComponent.java
import android.app.Application;
import com.ragdroid.dahaka.DahakaApplication;
import com.ragdroid.dahaka.activity.AppBindingModule;
import com.ragdroid.dahaka.api.ApiModule;
import com.ragdroid.dahaka.user.UserComponent;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import dagger.android.support.AndroidSupportInjectionModule;
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Singleton
@Component(modules = {
AppModule.class,
ApiModule.class,
AppBindingModule.class,
AndroidSupportInjectionModule.class})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
|
UserComponent.Builder userBuilder();
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/app/AppComponent.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/DahakaApplication.java
// public class DahakaApplication extends Application implements HasActivityInjector {
//
// @Inject DispatchingAndroidInjector<Activity> activityInjector;
// @Inject UserManager userManager;
//
// public AppComponent getAppComponent() {
// return appComponent;
// }
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DataBindingUtil.setDefaultComponent(buildDataBindingComponent());
// createComponent();
// }
//
// protected void createComponent() {
// appComponent = DaggerAppComponent.builder().application(this).build();
// appComponent.inject(this);
// }
//
// private DataBindingComponent buildDataBindingComponent() {
// return DaggerAppDataBindingComponent.builder().application(this).build();
// }
//
// @Override
// public AndroidInjector<Activity> activityInjector() {
// return userManager.activityInjector();
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
// @Module(subcomponents = UserComponent.class)
// public abstract class AppBindingModule {
//
// @ContributesAndroidInjector(modules = LoginModule.class)
// @ActivityScope
// abstract LoginActivity loginActivity();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/api/ApiModule.java
// @Module
// public class ApiModule {
//
//
// private static final long CACHE_SIZE = 10 * 1024 * 1024; //10 MB
//
// @Provides
// @Singleton
// public static HttpLoggingInterceptor getLoggingInterceptor() {
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// return loggingInterceptor;
// }
//
//
// @Provides
// @Singleton
// static Gson provideGson() {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// return gsonBuilder.create();
// }
//
// @Provides
// @Singleton
// static Cache provideOkhttpCache(Application application) {
// return new Cache(application.getCacheDir(), CACHE_SIZE);
// }
//
// @Provides
// @Singleton
// static Interceptor provideCacheOverrideInterceptor() {
// return chain -> {
// int maxStale = 60 * 60 * 24 * 7; // tolerate 1-week stale
// return chain.proceed(chain.request())
// .newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-age=" + maxStale)
// .build();
// };
// }
//
// @Provides
// @Singleton
// static OkHttpClient provideOkHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache,
// Interceptor cacheOverrideInterceptor) {
// OkHttpClient.Builder builder = new OkHttpClient.Builder()
// .cache(cache)
// .addInterceptor(loggingInterceptor)
// .connectTimeout(60, TimeUnit.SECONDS)
// .readTimeout(60, TimeUnit.SECONDS)
// .writeTimeout(60, TimeUnit.SECONDS)
// .addNetworkInterceptor(cacheOverrideInterceptor);
// return builder
// .build();
//
// }
//
//
// @Provides
// @Singleton
// static Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(gson))
// .baseUrl(getBaseUrl())
// .client(okHttpClient)
// .build();
// }
//
// protected static String getBaseUrl() {
// return "http://pokeapi.co/api/v2/";
// }
//
// @Provides
// @Singleton
// public static PokemonService providePokemonService(Retrofit retrofit) {
// return retrofit.create(PokemonService.class);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
|
import android.app.Application;
import com.ragdroid.dahaka.DahakaApplication;
import com.ragdroid.dahaka.activity.AppBindingModule;
import com.ragdroid.dahaka.api.ApiModule;
import com.ragdroid.dahaka.user.UserComponent;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import dagger.android.support.AndroidSupportInjectionModule;
|
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Singleton
@Component(modules = {
AppModule.class,
ApiModule.class,
AppBindingModule.class,
AndroidSupportInjectionModule.class})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
UserComponent.Builder userBuilder();
UserManager getUserManager();
|
// Path: app/src/main/java/com/ragdroid/dahaka/DahakaApplication.java
// public class DahakaApplication extends Application implements HasActivityInjector {
//
// @Inject DispatchingAndroidInjector<Activity> activityInjector;
// @Inject UserManager userManager;
//
// public AppComponent getAppComponent() {
// return appComponent;
// }
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// DataBindingUtil.setDefaultComponent(buildDataBindingComponent());
// createComponent();
// }
//
// protected void createComponent() {
// appComponent = DaggerAppComponent.builder().application(this).build();
// appComponent.inject(this);
// }
//
// private DataBindingComponent buildDataBindingComponent() {
// return DaggerAppDataBindingComponent.builder().application(this).build();
// }
//
// @Override
// public AndroidInjector<Activity> activityInjector() {
// return userManager.activityInjector();
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
// @Module(subcomponents = UserComponent.class)
// public abstract class AppBindingModule {
//
// @ContributesAndroidInjector(modules = LoginModule.class)
// @ActivityScope
// abstract LoginActivity loginActivity();
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/api/ApiModule.java
// @Module
// public class ApiModule {
//
//
// private static final long CACHE_SIZE = 10 * 1024 * 1024; //10 MB
//
// @Provides
// @Singleton
// public static HttpLoggingInterceptor getLoggingInterceptor() {
// HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// return loggingInterceptor;
// }
//
//
// @Provides
// @Singleton
// static Gson provideGson() {
// GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
// return gsonBuilder.create();
// }
//
// @Provides
// @Singleton
// static Cache provideOkhttpCache(Application application) {
// return new Cache(application.getCacheDir(), CACHE_SIZE);
// }
//
// @Provides
// @Singleton
// static Interceptor provideCacheOverrideInterceptor() {
// return chain -> {
// int maxStale = 60 * 60 * 24 * 7; // tolerate 1-week stale
// return chain.proceed(chain.request())
// .newBuilder()
// .header("Cache-Control", "public, only-if-cached, max-age=" + maxStale)
// .build();
// };
// }
//
// @Provides
// @Singleton
// static OkHttpClient provideOkHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache,
// Interceptor cacheOverrideInterceptor) {
// OkHttpClient.Builder builder = new OkHttpClient.Builder()
// .cache(cache)
// .addInterceptor(loggingInterceptor)
// .connectTimeout(60, TimeUnit.SECONDS)
// .readTimeout(60, TimeUnit.SECONDS)
// .writeTimeout(60, TimeUnit.SECONDS)
// .addNetworkInterceptor(cacheOverrideInterceptor);
// return builder
// .build();
//
// }
//
//
// @Provides
// @Singleton
// static Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
// return new Retrofit.Builder()
// .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(gson))
// .baseUrl(getBaseUrl())
// .client(okHttpClient)
// .build();
// }
//
// protected static String getBaseUrl() {
// return "http://pokeapi.co/api/v2/";
// }
//
// @Provides
// @Singleton
// public static PokemonService providePokemonService(Retrofit retrofit) {
// return retrofit.create(PokemonService.class);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/app/AppComponent.java
import android.app.Application;
import com.ragdroid.dahaka.DahakaApplication;
import com.ragdroid.dahaka.activity.AppBindingModule;
import com.ragdroid.dahaka.api.ApiModule;
import com.ragdroid.dahaka.user.UserComponent;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import dagger.android.support.AndroidSupportInjectionModule;
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 13/08/17.
*/
@Singleton
@Component(modules = {
AppModule.class,
ApiModule.class,
AppBindingModule.class,
AndroidSupportInjectionModule.class})
public interface AppComponent extends AndroidInjector<DaggerApplication> {
UserComponent.Builder userBuilder();
UserManager getUserManager();
|
void inject(DahakaApplication instance);
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/activity/home/profile/ProfileContract.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
//
// void onViewAdded(T view);
//
// void onViewRemoved();
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseView.java
// public interface BaseView {
//
// void showMessage(String message);
//
// void finishView();
//
// }
|
import com.ragdroid.dahaka.mvp.BasePresenter;
import com.ragdroid.dahaka.mvp.BaseView;
|
package com.ragdroid.dahaka.activity.home.profile;
/**
* Created by garimajain on 13/08/17.
*/
public interface ProfileContract {
interface View extends BaseView {
void showModel(ProfileModel model);
}
|
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
//
// void onViewAdded(T view);
//
// void onViewRemoved();
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseView.java
// public interface BaseView {
//
// void showMessage(String message);
//
// void finishView();
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/profile/ProfileContract.java
import com.ragdroid.dahaka.mvp.BasePresenter;
import com.ragdroid.dahaka.mvp.BaseView;
package com.ragdroid.dahaka.activity.home.profile;
/**
* Created by garimajain on 13/08/17.
*/
public interface ProfileContract {
interface View extends BaseView {
void showModel(ProfileModel model);
}
|
interface Presenter extends BasePresenter<View> {
|
ragdroid/Dahaka
|
app/src/androidTest/java/com/ragdroid/dahaka/activity/login/LoginActivityTest.java
|
// Path: app/src/androidTest/java/com/ragdroid/dahaka/DahakaTestApplication.java
// public class DahakaTestApplication extends DahakaApplication {
//
// public TestComponent getTestComponent() {
// return testComponent;
// }
//
// private TestComponent testComponent;
//
// @Override
// protected void createComponent() {
// testComponent = DaggerTestComponent.builder().application(this).build();
// testComponent.inject(this);
// }
//
// }
//
// Path: app/src/androidTest/java/com/ragdroid/dahaka/app/TestComponent.java
// @Singleton
// @Component(modules = {
// MockAppModule.class,
// MockApiModule.class,
// TestAppBindingModule.class,
// AndroidSupportInjectionModule.class})
// public interface TestComponent extends AppComponent {
//
// void inject(DahakaTestApplication instance);
//
// void inject(LoginActivityTest loginActivityTest);
//
// @Component.Builder
// interface Builder {
//
// TestComponent build();
//
// @BindsInstance
// Builder application(Application application);
// }
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/PokemonService.java
// @UserScope
// public interface PokemonService {
//
// /**
// * fetch pokemon user
// * @param id
// * @return
// */
// @Headers("Content-Type: application/json")
// @GET("pokemon/{name}")
// Single<Pokemon> getPokemon(@Path("name") String id);
//
// }
|
import android.app.Instrumentation;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ragdroid.dahaka.DahakaTestApplication;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.app.TestComponent;
import com.ragdroid.dahaka.user.PokemonService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import io.reactivex.Single;
import io.reactivex.schedulers.TestScheduler;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.when;
|
package com.ragdroid.dahaka.activity.login;
/**
* Created by garimajain on 28/08/17.
*/
@RunWith(AndroidJUnit4.class)
public class LoginActivityTest {
@Inject
|
// Path: app/src/androidTest/java/com/ragdroid/dahaka/DahakaTestApplication.java
// public class DahakaTestApplication extends DahakaApplication {
//
// public TestComponent getTestComponent() {
// return testComponent;
// }
//
// private TestComponent testComponent;
//
// @Override
// protected void createComponent() {
// testComponent = DaggerTestComponent.builder().application(this).build();
// testComponent.inject(this);
// }
//
// }
//
// Path: app/src/androidTest/java/com/ragdroid/dahaka/app/TestComponent.java
// @Singleton
// @Component(modules = {
// MockAppModule.class,
// MockApiModule.class,
// TestAppBindingModule.class,
// AndroidSupportInjectionModule.class})
// public interface TestComponent extends AppComponent {
//
// void inject(DahakaTestApplication instance);
//
// void inject(LoginActivityTest loginActivityTest);
//
// @Component.Builder
// interface Builder {
//
// TestComponent build();
//
// @BindsInstance
// Builder application(Application application);
// }
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/PokemonService.java
// @UserScope
// public interface PokemonService {
//
// /**
// * fetch pokemon user
// * @param id
// * @return
// */
// @Headers("Content-Type: application/json")
// @GET("pokemon/{name}")
// Single<Pokemon> getPokemon(@Path("name") String id);
//
// }
// Path: app/src/androidTest/java/com/ragdroid/dahaka/activity/login/LoginActivityTest.java
import android.app.Instrumentation;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ragdroid.dahaka.DahakaTestApplication;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.app.TestComponent;
import com.ragdroid.dahaka.user.PokemonService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import io.reactivex.Single;
import io.reactivex.schedulers.TestScheduler;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.when;
package com.ragdroid.dahaka.activity.login;
/**
* Created by garimajain on 28/08/17.
*/
@RunWith(AndroidJUnit4.class)
public class LoginActivityTest {
@Inject
|
PokemonService service;
|
ragdroid/Dahaka
|
app/src/androidTest/java/com/ragdroid/dahaka/activity/login/LoginActivityTest.java
|
// Path: app/src/androidTest/java/com/ragdroid/dahaka/DahakaTestApplication.java
// public class DahakaTestApplication extends DahakaApplication {
//
// public TestComponent getTestComponent() {
// return testComponent;
// }
//
// private TestComponent testComponent;
//
// @Override
// protected void createComponent() {
// testComponent = DaggerTestComponent.builder().application(this).build();
// testComponent.inject(this);
// }
//
// }
//
// Path: app/src/androidTest/java/com/ragdroid/dahaka/app/TestComponent.java
// @Singleton
// @Component(modules = {
// MockAppModule.class,
// MockApiModule.class,
// TestAppBindingModule.class,
// AndroidSupportInjectionModule.class})
// public interface TestComponent extends AppComponent {
//
// void inject(DahakaTestApplication instance);
//
// void inject(LoginActivityTest loginActivityTest);
//
// @Component.Builder
// interface Builder {
//
// TestComponent build();
//
// @BindsInstance
// Builder application(Application application);
// }
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/PokemonService.java
// @UserScope
// public interface PokemonService {
//
// /**
// * fetch pokemon user
// * @param id
// * @return
// */
// @Headers("Content-Type: application/json")
// @GET("pokemon/{name}")
// Single<Pokemon> getPokemon(@Path("name") String id);
//
// }
|
import android.app.Instrumentation;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ragdroid.dahaka.DahakaTestApplication;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.app.TestComponent;
import com.ragdroid.dahaka.user.PokemonService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import io.reactivex.Single;
import io.reactivex.schedulers.TestScheduler;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.when;
|
package com.ragdroid.dahaka.activity.login;
/**
* Created by garimajain on 28/08/17.
*/
@RunWith(AndroidJUnit4.class)
public class LoginActivityTest {
@Inject
PokemonService service;
@Inject
TestScheduler testScheduler;
@Rule
public ActivityTestRule<LoginActivity> activityRule = new ActivityTestRule<>(
LoginActivity.class, true);
@Before
public void setUp() throws Exception {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
|
// Path: app/src/androidTest/java/com/ragdroid/dahaka/DahakaTestApplication.java
// public class DahakaTestApplication extends DahakaApplication {
//
// public TestComponent getTestComponent() {
// return testComponent;
// }
//
// private TestComponent testComponent;
//
// @Override
// protected void createComponent() {
// testComponent = DaggerTestComponent.builder().application(this).build();
// testComponent.inject(this);
// }
//
// }
//
// Path: app/src/androidTest/java/com/ragdroid/dahaka/app/TestComponent.java
// @Singleton
// @Component(modules = {
// MockAppModule.class,
// MockApiModule.class,
// TestAppBindingModule.class,
// AndroidSupportInjectionModule.class})
// public interface TestComponent extends AppComponent {
//
// void inject(DahakaTestApplication instance);
//
// void inject(LoginActivityTest loginActivityTest);
//
// @Component.Builder
// interface Builder {
//
// TestComponent build();
//
// @BindsInstance
// Builder application(Application application);
// }
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/PokemonService.java
// @UserScope
// public interface PokemonService {
//
// /**
// * fetch pokemon user
// * @param id
// * @return
// */
// @Headers("Content-Type: application/json")
// @GET("pokemon/{name}")
// Single<Pokemon> getPokemon(@Path("name") String id);
//
// }
// Path: app/src/androidTest/java/com/ragdroid/dahaka/activity/login/LoginActivityTest.java
import android.app.Instrumentation;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ragdroid.dahaka.DahakaTestApplication;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.app.TestComponent;
import com.ragdroid.dahaka.user.PokemonService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import io.reactivex.Single;
import io.reactivex.schedulers.TestScheduler;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.when;
package com.ragdroid.dahaka.activity.login;
/**
* Created by garimajain on 28/08/17.
*/
@RunWith(AndroidJUnit4.class)
public class LoginActivityTest {
@Inject
PokemonService service;
@Inject
TestScheduler testScheduler;
@Rule
public ActivityTestRule<LoginActivity> activityRule = new ActivityTestRule<>(
LoginActivity.class, true);
@Before
public void setUp() throws Exception {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
|
DahakaTestApplication app
|
ragdroid/Dahaka
|
app/src/androidTest/java/com/ragdroid/dahaka/activity/login/LoginActivityTest.java
|
// Path: app/src/androidTest/java/com/ragdroid/dahaka/DahakaTestApplication.java
// public class DahakaTestApplication extends DahakaApplication {
//
// public TestComponent getTestComponent() {
// return testComponent;
// }
//
// private TestComponent testComponent;
//
// @Override
// protected void createComponent() {
// testComponent = DaggerTestComponent.builder().application(this).build();
// testComponent.inject(this);
// }
//
// }
//
// Path: app/src/androidTest/java/com/ragdroid/dahaka/app/TestComponent.java
// @Singleton
// @Component(modules = {
// MockAppModule.class,
// MockApiModule.class,
// TestAppBindingModule.class,
// AndroidSupportInjectionModule.class})
// public interface TestComponent extends AppComponent {
//
// void inject(DahakaTestApplication instance);
//
// void inject(LoginActivityTest loginActivityTest);
//
// @Component.Builder
// interface Builder {
//
// TestComponent build();
//
// @BindsInstance
// Builder application(Application application);
// }
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/PokemonService.java
// @UserScope
// public interface PokemonService {
//
// /**
// * fetch pokemon user
// * @param id
// * @return
// */
// @Headers("Content-Type: application/json")
// @GET("pokemon/{name}")
// Single<Pokemon> getPokemon(@Path("name") String id);
//
// }
|
import android.app.Instrumentation;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ragdroid.dahaka.DahakaTestApplication;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.app.TestComponent;
import com.ragdroid.dahaka.user.PokemonService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import io.reactivex.Single;
import io.reactivex.schedulers.TestScheduler;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.when;
|
package com.ragdroid.dahaka.activity.login;
/**
* Created by garimajain on 28/08/17.
*/
@RunWith(AndroidJUnit4.class)
public class LoginActivityTest {
@Inject
PokemonService service;
@Inject
TestScheduler testScheduler;
@Rule
public ActivityTestRule<LoginActivity> activityRule = new ActivityTestRule<>(
LoginActivity.class, true);
@Before
public void setUp() throws Exception {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
DahakaTestApplication app
= (DahakaTestApplication) instrumentation.getTargetContext().getApplicationContext();
|
// Path: app/src/androidTest/java/com/ragdroid/dahaka/DahakaTestApplication.java
// public class DahakaTestApplication extends DahakaApplication {
//
// public TestComponent getTestComponent() {
// return testComponent;
// }
//
// private TestComponent testComponent;
//
// @Override
// protected void createComponent() {
// testComponent = DaggerTestComponent.builder().application(this).build();
// testComponent.inject(this);
// }
//
// }
//
// Path: app/src/androidTest/java/com/ragdroid/dahaka/app/TestComponent.java
// @Singleton
// @Component(modules = {
// MockAppModule.class,
// MockApiModule.class,
// TestAppBindingModule.class,
// AndroidSupportInjectionModule.class})
// public interface TestComponent extends AppComponent {
//
// void inject(DahakaTestApplication instance);
//
// void inject(LoginActivityTest loginActivityTest);
//
// @Component.Builder
// interface Builder {
//
// TestComponent build();
//
// @BindsInstance
// Builder application(Application application);
// }
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/PokemonService.java
// @UserScope
// public interface PokemonService {
//
// /**
// * fetch pokemon user
// * @param id
// * @return
// */
// @Headers("Content-Type: application/json")
// @GET("pokemon/{name}")
// Single<Pokemon> getPokemon(@Path("name") String id);
//
// }
// Path: app/src/androidTest/java/com/ragdroid/dahaka/activity/login/LoginActivityTest.java
import android.app.Instrumentation;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.ragdroid.dahaka.DahakaTestApplication;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.app.TestComponent;
import com.ragdroid.dahaka.user.PokemonService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import io.reactivex.Single;
import io.reactivex.schedulers.TestScheduler;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.when;
package com.ragdroid.dahaka.activity.login;
/**
* Created by garimajain on 28/08/17.
*/
@RunWith(AndroidJUnit4.class)
public class LoginActivityTest {
@Inject
PokemonService service;
@Inject
TestScheduler testScheduler;
@Rule
public ActivityTestRule<LoginActivity> activityRule = new ActivityTestRule<>(
LoginActivity.class, true);
@Before
public void setUp() throws Exception {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
DahakaTestApplication app
= (DahakaTestApplication) instrumentation.getTargetContext().getApplicationContext();
|
TestComponent component = (TestComponent) app.getTestComponent();
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
// public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
//
// private ActivityLoginBinding binding;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setTitle(R.string.title_activity_login);
// binding.setPresenter(getPresenter());
// }
//
// @Override
// public void showHome() {
// Intent intent = new Intent(this, HomeActivity.class);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void setModel(LoginModel loginModel) {
// binding.setModel(loginModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginModule.java
// @Module
// public abstract class LoginModule {
//
// @Binds
// public abstract LoginContract.Presenter provideLoginPresenter(LoginPresenter loginPresenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
|
import com.ragdroid.dahaka.activity.login.LoginActivity;
import com.ragdroid.dahaka.activity.login.LoginModule;
import com.ragdroid.dahaka.user.UserComponent;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
|
package com.ragdroid.dahaka.activity;
/**
* Created by garimajain on 20/08/17.
*/
@Module(subcomponents = UserComponent.class)
public abstract class AppBindingModule {
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
// public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
//
// private ActivityLoginBinding binding;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setTitle(R.string.title_activity_login);
// binding.setPresenter(getPresenter());
// }
//
// @Override
// public void showHome() {
// Intent intent = new Intent(this, HomeActivity.class);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void setModel(LoginModel loginModel) {
// binding.setModel(loginModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginModule.java
// @Module
// public abstract class LoginModule {
//
// @Binds
// public abstract LoginContract.Presenter provideLoginPresenter(LoginPresenter loginPresenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
import com.ragdroid.dahaka.activity.login.LoginActivity;
import com.ragdroid.dahaka.activity.login.LoginModule;
import com.ragdroid.dahaka.user.UserComponent;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
package com.ragdroid.dahaka.activity;
/**
* Created by garimajain on 20/08/17.
*/
@Module(subcomponents = UserComponent.class)
public abstract class AppBindingModule {
|
@ContributesAndroidInjector(modules = LoginModule.class)
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
// public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
//
// private ActivityLoginBinding binding;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setTitle(R.string.title_activity_login);
// binding.setPresenter(getPresenter());
// }
//
// @Override
// public void showHome() {
// Intent intent = new Intent(this, HomeActivity.class);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void setModel(LoginModel loginModel) {
// binding.setModel(loginModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginModule.java
// @Module
// public abstract class LoginModule {
//
// @Binds
// public abstract LoginContract.Presenter provideLoginPresenter(LoginPresenter loginPresenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
|
import com.ragdroid.dahaka.activity.login.LoginActivity;
import com.ragdroid.dahaka.activity.login.LoginModule;
import com.ragdroid.dahaka.user.UserComponent;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
|
package com.ragdroid.dahaka.activity;
/**
* Created by garimajain on 20/08/17.
*/
@Module(subcomponents = UserComponent.class)
public abstract class AppBindingModule {
@ContributesAndroidInjector(modules = LoginModule.class)
@ActivityScope
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
// public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
//
// private ActivityLoginBinding binding;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setTitle(R.string.title_activity_login);
// binding.setPresenter(getPresenter());
// }
//
// @Override
// public void showHome() {
// Intent intent = new Intent(this, HomeActivity.class);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void setModel(LoginModel loginModel) {
// binding.setModel(loginModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginModule.java
// @Module
// public abstract class LoginModule {
//
// @Binds
// public abstract LoginContract.Presenter provideLoginPresenter(LoginPresenter loginPresenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserComponent.java
// @UserScope
// @Subcomponent(modules = {UserBindingModule.class, AndroidSupportInjectionModule.class})
// public interface UserComponent extends AndroidInjector<DaggerApplication> {
// void inject(UserManager userManager);
//
//
// @Subcomponent.Builder
// interface Builder {
//
// UserComponent build();
// @BindsInstance
// Builder pokeMon(Pokemon pokemon);
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/activity/AppBindingModule.java
import com.ragdroid.dahaka.activity.login.LoginActivity;
import com.ragdroid.dahaka.activity.login.LoginModule;
import com.ragdroid.dahaka.user.UserComponent;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
package com.ragdroid.dahaka.activity;
/**
* Created by garimajain on 20/08/17.
*/
@Module(subcomponents = UserComponent.class)
public abstract class AppBindingModule {
@ContributesAndroidInjector(modules = LoginModule.class)
@ActivityScope
|
abstract LoginActivity loginActivity();
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/moves/MovesFragment.java
// public class MovesFragment extends BaseFragment<MovesContract.Presenter> implements MovesContract.View {
//
// private FragmentMovesBinding dataBinding;
//
// @Inject
// public MovesFragment() {
// //required empty public constructor for Injection
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_moves, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(MovesModel statsModel) {
// dataBinding.setModel(statsModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/profile/ProfileFragment.java
// public class ProfileFragment extends BaseFragment<ProfileContract.Presenter> implements ProfileContract.View {
//
// @Inject
// public ProfileFragment() {
// // Required empty public constructor for Injection
// }
//
// private FragmentProfileBinding dataBinding;
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_profile, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(ProfileModel model) {
// dataBinding.setModel(model);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/stats/StatsFragment.java
// public class StatsFragment extends BaseFragment<StatsContract.Presenter> implements StatsContract.View {
//
// private FragmentStatsBinding dataBinding;
//
// @Inject
// public StatsFragment() {
// //required empty public constructor
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_stats, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(StatsModel statsModel) {
// dataBinding.setModel(statsModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/BaseUserActivity.java
// public abstract class BaseUserActivity<T extends BasePresenter> extends BaseActivity<T> {
//
// @Inject UserManager userManager;
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (!userManager.isLoggedIn()) {
// finishView();
// }
// }
//
// @Override
// protected void androidInject() {
// AndroidInjection.inject(this);
// }
//
// protected void logoutUser() {
// userManager.logOut();
// finishView();
// }
//
//
// }
|
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.view.Menu;
import android.view.MenuItem;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.activity.home.moves.MovesFragment;
import com.ragdroid.dahaka.activity.home.profile.ProfileFragment;
import com.ragdroid.dahaka.activity.home.stats.StatsFragment;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.databinding.ActivityHomeBinding;
import com.ragdroid.dahaka.user.BaseUserActivity;
import javax.inject.Inject;
|
package com.ragdroid.dahaka.activity.home;
public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
@Inject ProfileFragment profileFragment;
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/moves/MovesFragment.java
// public class MovesFragment extends BaseFragment<MovesContract.Presenter> implements MovesContract.View {
//
// private FragmentMovesBinding dataBinding;
//
// @Inject
// public MovesFragment() {
// //required empty public constructor for Injection
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_moves, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(MovesModel statsModel) {
// dataBinding.setModel(statsModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/profile/ProfileFragment.java
// public class ProfileFragment extends BaseFragment<ProfileContract.Presenter> implements ProfileContract.View {
//
// @Inject
// public ProfileFragment() {
// // Required empty public constructor for Injection
// }
//
// private FragmentProfileBinding dataBinding;
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_profile, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(ProfileModel model) {
// dataBinding.setModel(model);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/stats/StatsFragment.java
// public class StatsFragment extends BaseFragment<StatsContract.Presenter> implements StatsContract.View {
//
// private FragmentStatsBinding dataBinding;
//
// @Inject
// public StatsFragment() {
// //required empty public constructor
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_stats, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(StatsModel statsModel) {
// dataBinding.setModel(statsModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/BaseUserActivity.java
// public abstract class BaseUserActivity<T extends BasePresenter> extends BaseActivity<T> {
//
// @Inject UserManager userManager;
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (!userManager.isLoggedIn()) {
// finishView();
// }
// }
//
// @Override
// protected void androidInject() {
// AndroidInjection.inject(this);
// }
//
// protected void logoutUser() {
// userManager.logOut();
// finishView();
// }
//
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.view.Menu;
import android.view.MenuItem;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.activity.home.moves.MovesFragment;
import com.ragdroid.dahaka.activity.home.profile.ProfileFragment;
import com.ragdroid.dahaka.activity.home.stats.StatsFragment;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.databinding.ActivityHomeBinding;
import com.ragdroid.dahaka.user.BaseUserActivity;
import javax.inject.Inject;
package com.ragdroid.dahaka.activity.home;
public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
@Inject ProfileFragment profileFragment;
|
@Inject StatsFragment statsFragment;
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/moves/MovesFragment.java
// public class MovesFragment extends BaseFragment<MovesContract.Presenter> implements MovesContract.View {
//
// private FragmentMovesBinding dataBinding;
//
// @Inject
// public MovesFragment() {
// //required empty public constructor for Injection
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_moves, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(MovesModel statsModel) {
// dataBinding.setModel(statsModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/profile/ProfileFragment.java
// public class ProfileFragment extends BaseFragment<ProfileContract.Presenter> implements ProfileContract.View {
//
// @Inject
// public ProfileFragment() {
// // Required empty public constructor for Injection
// }
//
// private FragmentProfileBinding dataBinding;
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_profile, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(ProfileModel model) {
// dataBinding.setModel(model);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/stats/StatsFragment.java
// public class StatsFragment extends BaseFragment<StatsContract.Presenter> implements StatsContract.View {
//
// private FragmentStatsBinding dataBinding;
//
// @Inject
// public StatsFragment() {
// //required empty public constructor
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_stats, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(StatsModel statsModel) {
// dataBinding.setModel(statsModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/BaseUserActivity.java
// public abstract class BaseUserActivity<T extends BasePresenter> extends BaseActivity<T> {
//
// @Inject UserManager userManager;
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (!userManager.isLoggedIn()) {
// finishView();
// }
// }
//
// @Override
// protected void androidInject() {
// AndroidInjection.inject(this);
// }
//
// protected void logoutUser() {
// userManager.logOut();
// finishView();
// }
//
//
// }
|
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.view.Menu;
import android.view.MenuItem;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.activity.home.moves.MovesFragment;
import com.ragdroid.dahaka.activity.home.profile.ProfileFragment;
import com.ragdroid.dahaka.activity.home.stats.StatsFragment;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.databinding.ActivityHomeBinding;
import com.ragdroid.dahaka.user.BaseUserActivity;
import javax.inject.Inject;
|
package com.ragdroid.dahaka.activity.home;
public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
@Inject ProfileFragment profileFragment;
@Inject StatsFragment statsFragment;
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/moves/MovesFragment.java
// public class MovesFragment extends BaseFragment<MovesContract.Presenter> implements MovesContract.View {
//
// private FragmentMovesBinding dataBinding;
//
// @Inject
// public MovesFragment() {
// //required empty public constructor for Injection
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_moves, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(MovesModel statsModel) {
// dataBinding.setModel(statsModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/profile/ProfileFragment.java
// public class ProfileFragment extends BaseFragment<ProfileContract.Presenter> implements ProfileContract.View {
//
// @Inject
// public ProfileFragment() {
// // Required empty public constructor for Injection
// }
//
// private FragmentProfileBinding dataBinding;
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_profile, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(ProfileModel model) {
// dataBinding.setModel(model);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/stats/StatsFragment.java
// public class StatsFragment extends BaseFragment<StatsContract.Presenter> implements StatsContract.View {
//
// private FragmentStatsBinding dataBinding;
//
// @Inject
// public StatsFragment() {
// //required empty public constructor
// }
//
// @Nullable
// @Override
// public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
// View view = inflater.inflate(R.layout.fragment_stats, container, false);
// dataBinding = DataBindingUtil.bind(view);
// return view;
// }
//
// @Override
// public void showModel(StatsModel statsModel) {
// dataBinding.setModel(statsModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/user/BaseUserActivity.java
// public abstract class BaseUserActivity<T extends BasePresenter> extends BaseActivity<T> {
//
// @Inject UserManager userManager;
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (!userManager.isLoggedIn()) {
// finishView();
// }
// }
//
// @Override
// protected void androidInject() {
// AndroidInjection.inject(this);
// }
//
// protected void logoutUser() {
// userManager.logOut();
// finishView();
// }
//
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.view.Menu;
import android.view.MenuItem;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.activity.home.moves.MovesFragment;
import com.ragdroid.dahaka.activity.home.profile.ProfileFragment;
import com.ragdroid.dahaka.activity.home.stats.StatsFragment;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.databinding.ActivityHomeBinding;
import com.ragdroid.dahaka.user.BaseUserActivity;
import javax.inject.Inject;
package com.ragdroid.dahaka.activity.home;
public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
@Inject ProfileFragment profileFragment;
@Inject StatsFragment statsFragment;
|
@Inject MovesFragment movesFragment;
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
// public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
//
//
// @Inject ProfileFragment profileFragment;
// @Inject StatsFragment statsFragment;
// @Inject MovesFragment movesFragment;
//
// private ActivityHomeBinding viewDataBinding;
//
// private BottomNavigationView.OnNavigationItemSelectedListener navigationListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// int itemId = item.getItemId();
// if (viewDataBinding.bottomNavigation.getSelectedItemId() == itemId) {
// //do nothing if reselected
// return true;
// }
// return openFragment(itemId);
// }
//
// };
//
// private boolean openFragment(int itemId) {
// Fragment fragment = null;
// switch (itemId) {
// case R.id.action_profile:
// fragment = profileFragment;
// break;
// case R.id.action_moves:
// fragment = movesFragment;
// break;
// case R.id.action_stats:
// fragment = statsFragment;
// break;
// }
//
// if (fragment != null) {
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.fragment_container, fragment)
// .commit();
// return true;
// }
// return false;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
// viewDataBinding.bottomNavigation.setOnNavigationItemSelectedListener(navigationListener);
// viewDataBinding.bottomNavigation.setSelectedItemId(R.id.action_profile);
// openFragment(R.id.action_profile);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_home, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == R.id.action_log_out) {
// logoutUser();
// return true;
// } else if (item.getItemId() == R.id.action_items) {
// openItemsActivity();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void openItemsActivity() {
// Intent intent = new Intent(this, ItemsActivity.class);
// startActivity(intent);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseActivity.java
// public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements BaseView,
// HasSupportFragmentInjector {
//
// public T getPresenter() {
// return presenter;
// }
//
// @Inject DispatchingAndroidInjector<Fragment> injector;
//
// @Inject
// T presenter;
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// androidInject();
// super.onCreate(savedInstanceState);
// presenter.onViewAdded(this);
// }
//
// protected void androidInject() {
// AndroidInjection.inject(this);
// }
//
// @Override
// public void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// @Override
// protected void onDestroy() {
// presenter.onViewRemoved();
// super.onDestroy();
// }
//
// @Override
// public void finishView() {
// startActivity(new Intent(this, LoginActivity.class));
// finish();
// }
// @Override
// public AndroidInjector<Fragment> supportFragmentInjector() {
// return injector;
// }
//
// }
|
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.activity.home.HomeActivity;
import com.ragdroid.dahaka.databinding.ActivityLoginBinding;
import com.ragdroid.dahaka.mvp.BaseActivity;
|
package com.ragdroid.dahaka.activity.login;
public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
private ActivityLoginBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
super.onCreate(savedInstanceState);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.title_activity_login);
binding.setPresenter(getPresenter());
}
@Override
public void showHome() {
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
// public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
//
//
// @Inject ProfileFragment profileFragment;
// @Inject StatsFragment statsFragment;
// @Inject MovesFragment movesFragment;
//
// private ActivityHomeBinding viewDataBinding;
//
// private BottomNavigationView.OnNavigationItemSelectedListener navigationListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// int itemId = item.getItemId();
// if (viewDataBinding.bottomNavigation.getSelectedItemId() == itemId) {
// //do nothing if reselected
// return true;
// }
// return openFragment(itemId);
// }
//
// };
//
// private boolean openFragment(int itemId) {
// Fragment fragment = null;
// switch (itemId) {
// case R.id.action_profile:
// fragment = profileFragment;
// break;
// case R.id.action_moves:
// fragment = movesFragment;
// break;
// case R.id.action_stats:
// fragment = statsFragment;
// break;
// }
//
// if (fragment != null) {
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.fragment_container, fragment)
// .commit();
// return true;
// }
// return false;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
// viewDataBinding.bottomNavigation.setOnNavigationItemSelectedListener(navigationListener);
// viewDataBinding.bottomNavigation.setSelectedItemId(R.id.action_profile);
// openFragment(R.id.action_profile);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_home, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == R.id.action_log_out) {
// logoutUser();
// return true;
// } else if (item.getItemId() == R.id.action_items) {
// openItemsActivity();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void openItemsActivity() {
// Intent intent = new Intent(this, ItemsActivity.class);
// startActivity(intent);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseActivity.java
// public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements BaseView,
// HasSupportFragmentInjector {
//
// public T getPresenter() {
// return presenter;
// }
//
// @Inject DispatchingAndroidInjector<Fragment> injector;
//
// @Inject
// T presenter;
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// androidInject();
// super.onCreate(savedInstanceState);
// presenter.onViewAdded(this);
// }
//
// protected void androidInject() {
// AndroidInjection.inject(this);
// }
//
// @Override
// public void showMessage(String message) {
// Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
// }
//
// @Override
// protected void onDestroy() {
// presenter.onViewRemoved();
// super.onDestroy();
// }
//
// @Override
// public void finishView() {
// startActivity(new Intent(this, LoginActivity.class));
// finish();
// }
// @Override
// public AndroidInjector<Fragment> supportFragmentInjector() {
// return injector;
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import com.ragdroid.dahaka.R;
import com.ragdroid.dahaka.activity.home.HomeActivity;
import com.ragdroid.dahaka.databinding.ActivityLoginBinding;
import com.ragdroid.dahaka.mvp.BaseActivity;
package com.ragdroid.dahaka.activity.login;
public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
private ActivityLoginBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
super.onCreate(savedInstanceState);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.title_activity_login);
binding.setPresenter(getPresenter());
}
@Override
public void showHome() {
|
Intent intent = new Intent(this, HomeActivity.class);
|
ragdroid/Dahaka
|
app/src/androidTest/java/com/ragdroid/dahaka/app/TestRunner.java
|
// Path: app/src/androidTest/java/com/ragdroid/dahaka/DahakaTestApplication.java
// public class DahakaTestApplication extends DahakaApplication {
//
// public TestComponent getTestComponent() {
// return testComponent;
// }
//
// private TestComponent testComponent;
//
// @Override
// protected void createComponent() {
// testComponent = DaggerTestComponent.builder().application(this).build();
// testComponent.inject(this);
// }
//
// }
|
import android.app.Application;
import android.content.Context;
import android.support.test.runner.AndroidJUnitRunner;
import com.ragdroid.dahaka.DahakaTestApplication;
|
package com.ragdroid.dahaka.app;
public class TestRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
|
// Path: app/src/androidTest/java/com/ragdroid/dahaka/DahakaTestApplication.java
// public class DahakaTestApplication extends DahakaApplication {
//
// public TestComponent getTestComponent() {
// return testComponent;
// }
//
// private TestComponent testComponent;
//
// @Override
// protected void createComponent() {
// testComponent = DaggerTestComponent.builder().application(this).build();
// testComponent.inject(this);
// }
//
// }
// Path: app/src/androidTest/java/com/ragdroid/dahaka/app/TestRunner.java
import android.app.Application;
import android.content.Context;
import android.support.test.runner.AndroidJUnitRunner;
import com.ragdroid.dahaka.DahakaTestApplication;
package com.ragdroid.dahaka.app;
public class TestRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context context)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
|
return super.newApplication(cl, DahakaTestApplication.class.getName(), context);
|
ragdroid/Dahaka
|
app/src/androidTest/java/com/ragdroid/dahaka/app/TestAppBindingModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
// public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
//
// private ActivityLoginBinding binding;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setTitle(R.string.title_activity_login);
// binding.setPresenter(getPresenter());
// }
//
// @Override
// public void showHome() {
// Intent intent = new Intent(this, HomeActivity.class);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void setModel(LoginModel loginModel) {
// binding.setModel(loginModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginModule.java
// @Module
// public abstract class LoginModule {
//
// @Binds
// public abstract LoginContract.Presenter provideLoginPresenter(LoginPresenter loginPresenter);
//
// }
|
import android.app.Activity;
import com.ragdroid.dahaka.activity.ActivityScope;
import com.ragdroid.dahaka.activity.login.LoginActivity;
import com.ragdroid.dahaka.activity.login.LoginModule;
import dagger.Binds;
import dagger.Module;
import dagger.Subcomponent;
import dagger.android.ActivityKey;
import dagger.android.AndroidInjector;
import dagger.multibindings.IntoMap;
|
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 31/08/17.
*/
@Module(subcomponents = TestAppBindingModule.LoginActivitySubcomponent.class)
public abstract class TestAppBindingModule {
private TestAppBindingModule() {}
@Binds
@IntoMap
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
// public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
//
// private ActivityLoginBinding binding;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setTitle(R.string.title_activity_login);
// binding.setPresenter(getPresenter());
// }
//
// @Override
// public void showHome() {
// Intent intent = new Intent(this, HomeActivity.class);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void setModel(LoginModel loginModel) {
// binding.setModel(loginModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginModule.java
// @Module
// public abstract class LoginModule {
//
// @Binds
// public abstract LoginContract.Presenter provideLoginPresenter(LoginPresenter loginPresenter);
//
// }
// Path: app/src/androidTest/java/com/ragdroid/dahaka/app/TestAppBindingModule.java
import android.app.Activity;
import com.ragdroid.dahaka.activity.ActivityScope;
import com.ragdroid.dahaka.activity.login.LoginActivity;
import com.ragdroid.dahaka.activity.login.LoginModule;
import dagger.Binds;
import dagger.Module;
import dagger.Subcomponent;
import dagger.android.ActivityKey;
import dagger.android.AndroidInjector;
import dagger.multibindings.IntoMap;
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 31/08/17.
*/
@Module(subcomponents = TestAppBindingModule.LoginActivitySubcomponent.class)
public abstract class TestAppBindingModule {
private TestAppBindingModule() {}
@Binds
@IntoMap
|
@ActivityKey(LoginActivity.class)
|
ragdroid/Dahaka
|
app/src/androidTest/java/com/ragdroid/dahaka/app/TestAppBindingModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
// public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
//
// private ActivityLoginBinding binding;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setTitle(R.string.title_activity_login);
// binding.setPresenter(getPresenter());
// }
//
// @Override
// public void showHome() {
// Intent intent = new Intent(this, HomeActivity.class);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void setModel(LoginModel loginModel) {
// binding.setModel(loginModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginModule.java
// @Module
// public abstract class LoginModule {
//
// @Binds
// public abstract LoginContract.Presenter provideLoginPresenter(LoginPresenter loginPresenter);
//
// }
|
import android.app.Activity;
import com.ragdroid.dahaka.activity.ActivityScope;
import com.ragdroid.dahaka.activity.login.LoginActivity;
import com.ragdroid.dahaka.activity.login.LoginModule;
import dagger.Binds;
import dagger.Module;
import dagger.Subcomponent;
import dagger.android.ActivityKey;
import dagger.android.AndroidInjector;
import dagger.multibindings.IntoMap;
|
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 31/08/17.
*/
@Module(subcomponents = TestAppBindingModule.LoginActivitySubcomponent.class)
public abstract class TestAppBindingModule {
private TestAppBindingModule() {}
@Binds
@IntoMap
@ActivityKey(LoginActivity.class)
abstract AndroidInjector.Factory<? extends Activity> bindAndroidInjectorFactory(
LoginActivitySubcomponent.Builder builder);
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginActivity.java
// public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {
//
// private ActivityLoginBinding binding;
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setTitle(R.string.title_activity_login);
// binding.setPresenter(getPresenter());
// }
//
// @Override
// public void showHome() {
// Intent intent = new Intent(this, HomeActivity.class);
// startActivity(intent);
// finish();
// }
//
// @Override
// public void setModel(LoginModel loginModel) {
// binding.setModel(loginModel);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/login/LoginModule.java
// @Module
// public abstract class LoginModule {
//
// @Binds
// public abstract LoginContract.Presenter provideLoginPresenter(LoginPresenter loginPresenter);
//
// }
// Path: app/src/androidTest/java/com/ragdroid/dahaka/app/TestAppBindingModule.java
import android.app.Activity;
import com.ragdroid.dahaka.activity.ActivityScope;
import com.ragdroid.dahaka.activity.login.LoginActivity;
import com.ragdroid.dahaka.activity.login.LoginModule;
import dagger.Binds;
import dagger.Module;
import dagger.Subcomponent;
import dagger.android.ActivityKey;
import dagger.android.AndroidInjector;
import dagger.multibindings.IntoMap;
package com.ragdroid.dahaka.app;
/**
* Created by garimajain on 31/08/17.
*/
@Module(subcomponents = TestAppBindingModule.LoginActivitySubcomponent.class)
public abstract class TestAppBindingModule {
private TestAppBindingModule() {}
@Binds
@IntoMap
@ActivityKey(LoginActivity.class)
abstract AndroidInjector.Factory<? extends Activity> bindAndroidInjectorFactory(
LoginActivitySubcomponent.Builder builder);
|
@Subcomponent(modules = LoginModule.class)
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsContract.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
//
// void onViewAdded(T view);
//
// void onViewRemoved();
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseView.java
// public interface BaseView {
//
// void showMessage(String message);
//
// void finishView();
//
// }
|
import com.ragdroid.dahaka.mvp.BasePresenter;
import com.ragdroid.dahaka.mvp.BaseView;
|
package com.ragdroid.dahaka.activity.items;
/**
* Created by garimajain on 13/08/17.
*/
public interface ItemsContract {
interface View extends BaseView {
void showModel(ItemsModel model);
}
|
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BasePresenter.java
// public interface BasePresenter<T extends BaseView> {
//
// void onViewAdded(T view);
//
// void onViewRemoved();
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/mvp/BaseView.java
// public interface BaseView {
//
// void showMessage(String message);
//
// void finishView();
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsContract.java
import com.ragdroid.dahaka.mvp.BasePresenter;
import com.ragdroid.dahaka.mvp.BaseView;
package com.ragdroid.dahaka.activity.items;
/**
* Created by garimajain on 13/08/17.
*/
public interface ItemsContract {
interface View extends BaseView {
void showModel(ItemsModel model);
}
|
interface Presenter extends BasePresenter<View> {
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/user/UserBindingModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
// public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
//
//
// @Inject ProfileFragment profileFragment;
// @Inject StatsFragment statsFragment;
// @Inject MovesFragment movesFragment;
//
// private ActivityHomeBinding viewDataBinding;
//
// private BottomNavigationView.OnNavigationItemSelectedListener navigationListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// int itemId = item.getItemId();
// if (viewDataBinding.bottomNavigation.getSelectedItemId() == itemId) {
// //do nothing if reselected
// return true;
// }
// return openFragment(itemId);
// }
//
// };
//
// private boolean openFragment(int itemId) {
// Fragment fragment = null;
// switch (itemId) {
// case R.id.action_profile:
// fragment = profileFragment;
// break;
// case R.id.action_moves:
// fragment = movesFragment;
// break;
// case R.id.action_stats:
// fragment = statsFragment;
// break;
// }
//
// if (fragment != null) {
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.fragment_container, fragment)
// .commit();
// return true;
// }
// return false;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
// viewDataBinding.bottomNavigation.setOnNavigationItemSelectedListener(navigationListener);
// viewDataBinding.bottomNavigation.setSelectedItemId(R.id.action_profile);
// openFragment(R.id.action_profile);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_home, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == R.id.action_log_out) {
// logoutUser();
// return true;
// } else if (item.getItemId() == R.id.action_items) {
// openItemsActivity();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void openItemsActivity() {
// Intent intent = new Intent(this, ItemsActivity.class);
// startActivity(intent);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeModule.java
// @Module
// public abstract class HomeModule {
//
// @ContributesAndroidInjector
// abstract ProfileFragment profileFragment();
//
// @ContributesAndroidInjector
// abstract MovesFragment movesFragment();
//
// @ContributesAndroidInjector
// abstract StatsFragment statisticsFragment();
//
//
// @Binds
// public abstract HomeContract.Presenter provideHomePresenter(HomePresenter presenter);
//
// @Binds
// public abstract ProfileContract.Presenter provideProfilePresenter(ProfilePresenter presenter);
//
// @Binds
// public abstract StatsContract.Presenter provideStatsPresenter(StatsPresenter presenter);
//
// @Binds
// public abstract MovesContract.Presenter provideMovesPresenter(MovesPresenter presenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsModule.java
// @Module
// public class ItemsModule {
//
// @Provides
// static ItemsContract.Presenter provideHomePresenter(ItemsPresenter presenter) {
// return presenter;
// }
//
// @Provides
// static ItemsAdapter provideItemsAdapter() {
// return new ItemsAdapter();
// }
//
// @Provides
// static LinearLayoutManager provideLayoutManager(ItemsActivity activity) {
// return new LinearLayoutManager(activity);
// }
//
// @Provides
// static DividerItemDecoration provideDividerItemDecoration(ItemsActivity activity) {
// return new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL);
// }
//
// }
|
import com.ragdroid.dahaka.activity.home.HomeActivity;
import com.ragdroid.dahaka.activity.home.HomeModule;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.activity.items.ItemsModule;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import dagger.android.support.AndroidSupportInjectionModule;
|
package com.ragdroid.dahaka.user;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class UserBindingModule {
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
// public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
//
//
// @Inject ProfileFragment profileFragment;
// @Inject StatsFragment statsFragment;
// @Inject MovesFragment movesFragment;
//
// private ActivityHomeBinding viewDataBinding;
//
// private BottomNavigationView.OnNavigationItemSelectedListener navigationListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// int itemId = item.getItemId();
// if (viewDataBinding.bottomNavigation.getSelectedItemId() == itemId) {
// //do nothing if reselected
// return true;
// }
// return openFragment(itemId);
// }
//
// };
//
// private boolean openFragment(int itemId) {
// Fragment fragment = null;
// switch (itemId) {
// case R.id.action_profile:
// fragment = profileFragment;
// break;
// case R.id.action_moves:
// fragment = movesFragment;
// break;
// case R.id.action_stats:
// fragment = statsFragment;
// break;
// }
//
// if (fragment != null) {
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.fragment_container, fragment)
// .commit();
// return true;
// }
// return false;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
// viewDataBinding.bottomNavigation.setOnNavigationItemSelectedListener(navigationListener);
// viewDataBinding.bottomNavigation.setSelectedItemId(R.id.action_profile);
// openFragment(R.id.action_profile);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_home, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == R.id.action_log_out) {
// logoutUser();
// return true;
// } else if (item.getItemId() == R.id.action_items) {
// openItemsActivity();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void openItemsActivity() {
// Intent intent = new Intent(this, ItemsActivity.class);
// startActivity(intent);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeModule.java
// @Module
// public abstract class HomeModule {
//
// @ContributesAndroidInjector
// abstract ProfileFragment profileFragment();
//
// @ContributesAndroidInjector
// abstract MovesFragment movesFragment();
//
// @ContributesAndroidInjector
// abstract StatsFragment statisticsFragment();
//
//
// @Binds
// public abstract HomeContract.Presenter provideHomePresenter(HomePresenter presenter);
//
// @Binds
// public abstract ProfileContract.Presenter provideProfilePresenter(ProfilePresenter presenter);
//
// @Binds
// public abstract StatsContract.Presenter provideStatsPresenter(StatsPresenter presenter);
//
// @Binds
// public abstract MovesContract.Presenter provideMovesPresenter(MovesPresenter presenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsModule.java
// @Module
// public class ItemsModule {
//
// @Provides
// static ItemsContract.Presenter provideHomePresenter(ItemsPresenter presenter) {
// return presenter;
// }
//
// @Provides
// static ItemsAdapter provideItemsAdapter() {
// return new ItemsAdapter();
// }
//
// @Provides
// static LinearLayoutManager provideLayoutManager(ItemsActivity activity) {
// return new LinearLayoutManager(activity);
// }
//
// @Provides
// static DividerItemDecoration provideDividerItemDecoration(ItemsActivity activity) {
// return new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL);
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserBindingModule.java
import com.ragdroid.dahaka.activity.home.HomeActivity;
import com.ragdroid.dahaka.activity.home.HomeModule;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.activity.items.ItemsModule;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import dagger.android.support.AndroidSupportInjectionModule;
package com.ragdroid.dahaka.user;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class UserBindingModule {
|
@ContributesAndroidInjector(modules = {HomeModule.class, AndroidSupportInjectionModule.class})
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/user/UserBindingModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
// public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
//
//
// @Inject ProfileFragment profileFragment;
// @Inject StatsFragment statsFragment;
// @Inject MovesFragment movesFragment;
//
// private ActivityHomeBinding viewDataBinding;
//
// private BottomNavigationView.OnNavigationItemSelectedListener navigationListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// int itemId = item.getItemId();
// if (viewDataBinding.bottomNavigation.getSelectedItemId() == itemId) {
// //do nothing if reselected
// return true;
// }
// return openFragment(itemId);
// }
//
// };
//
// private boolean openFragment(int itemId) {
// Fragment fragment = null;
// switch (itemId) {
// case R.id.action_profile:
// fragment = profileFragment;
// break;
// case R.id.action_moves:
// fragment = movesFragment;
// break;
// case R.id.action_stats:
// fragment = statsFragment;
// break;
// }
//
// if (fragment != null) {
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.fragment_container, fragment)
// .commit();
// return true;
// }
// return false;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
// viewDataBinding.bottomNavigation.setOnNavigationItemSelectedListener(navigationListener);
// viewDataBinding.bottomNavigation.setSelectedItemId(R.id.action_profile);
// openFragment(R.id.action_profile);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_home, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == R.id.action_log_out) {
// logoutUser();
// return true;
// } else if (item.getItemId() == R.id.action_items) {
// openItemsActivity();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void openItemsActivity() {
// Intent intent = new Intent(this, ItemsActivity.class);
// startActivity(intent);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeModule.java
// @Module
// public abstract class HomeModule {
//
// @ContributesAndroidInjector
// abstract ProfileFragment profileFragment();
//
// @ContributesAndroidInjector
// abstract MovesFragment movesFragment();
//
// @ContributesAndroidInjector
// abstract StatsFragment statisticsFragment();
//
//
// @Binds
// public abstract HomeContract.Presenter provideHomePresenter(HomePresenter presenter);
//
// @Binds
// public abstract ProfileContract.Presenter provideProfilePresenter(ProfilePresenter presenter);
//
// @Binds
// public abstract StatsContract.Presenter provideStatsPresenter(StatsPresenter presenter);
//
// @Binds
// public abstract MovesContract.Presenter provideMovesPresenter(MovesPresenter presenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsModule.java
// @Module
// public class ItemsModule {
//
// @Provides
// static ItemsContract.Presenter provideHomePresenter(ItemsPresenter presenter) {
// return presenter;
// }
//
// @Provides
// static ItemsAdapter provideItemsAdapter() {
// return new ItemsAdapter();
// }
//
// @Provides
// static LinearLayoutManager provideLayoutManager(ItemsActivity activity) {
// return new LinearLayoutManager(activity);
// }
//
// @Provides
// static DividerItemDecoration provideDividerItemDecoration(ItemsActivity activity) {
// return new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL);
// }
//
// }
|
import com.ragdroid.dahaka.activity.home.HomeActivity;
import com.ragdroid.dahaka.activity.home.HomeModule;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.activity.items.ItemsModule;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import dagger.android.support.AndroidSupportInjectionModule;
|
package com.ragdroid.dahaka.user;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class UserBindingModule {
@ContributesAndroidInjector(modules = {HomeModule.class, AndroidSupportInjectionModule.class})
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
// public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
//
//
// @Inject ProfileFragment profileFragment;
// @Inject StatsFragment statsFragment;
// @Inject MovesFragment movesFragment;
//
// private ActivityHomeBinding viewDataBinding;
//
// private BottomNavigationView.OnNavigationItemSelectedListener navigationListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// int itemId = item.getItemId();
// if (viewDataBinding.bottomNavigation.getSelectedItemId() == itemId) {
// //do nothing if reselected
// return true;
// }
// return openFragment(itemId);
// }
//
// };
//
// private boolean openFragment(int itemId) {
// Fragment fragment = null;
// switch (itemId) {
// case R.id.action_profile:
// fragment = profileFragment;
// break;
// case R.id.action_moves:
// fragment = movesFragment;
// break;
// case R.id.action_stats:
// fragment = statsFragment;
// break;
// }
//
// if (fragment != null) {
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.fragment_container, fragment)
// .commit();
// return true;
// }
// return false;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
// viewDataBinding.bottomNavigation.setOnNavigationItemSelectedListener(navigationListener);
// viewDataBinding.bottomNavigation.setSelectedItemId(R.id.action_profile);
// openFragment(R.id.action_profile);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_home, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == R.id.action_log_out) {
// logoutUser();
// return true;
// } else if (item.getItemId() == R.id.action_items) {
// openItemsActivity();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void openItemsActivity() {
// Intent intent = new Intent(this, ItemsActivity.class);
// startActivity(intent);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeModule.java
// @Module
// public abstract class HomeModule {
//
// @ContributesAndroidInjector
// abstract ProfileFragment profileFragment();
//
// @ContributesAndroidInjector
// abstract MovesFragment movesFragment();
//
// @ContributesAndroidInjector
// abstract StatsFragment statisticsFragment();
//
//
// @Binds
// public abstract HomeContract.Presenter provideHomePresenter(HomePresenter presenter);
//
// @Binds
// public abstract ProfileContract.Presenter provideProfilePresenter(ProfilePresenter presenter);
//
// @Binds
// public abstract StatsContract.Presenter provideStatsPresenter(StatsPresenter presenter);
//
// @Binds
// public abstract MovesContract.Presenter provideMovesPresenter(MovesPresenter presenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsModule.java
// @Module
// public class ItemsModule {
//
// @Provides
// static ItemsContract.Presenter provideHomePresenter(ItemsPresenter presenter) {
// return presenter;
// }
//
// @Provides
// static ItemsAdapter provideItemsAdapter() {
// return new ItemsAdapter();
// }
//
// @Provides
// static LinearLayoutManager provideLayoutManager(ItemsActivity activity) {
// return new LinearLayoutManager(activity);
// }
//
// @Provides
// static DividerItemDecoration provideDividerItemDecoration(ItemsActivity activity) {
// return new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL);
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserBindingModule.java
import com.ragdroid.dahaka.activity.home.HomeActivity;
import com.ragdroid.dahaka.activity.home.HomeModule;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.activity.items.ItemsModule;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import dagger.android.support.AndroidSupportInjectionModule;
package com.ragdroid.dahaka.user;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class UserBindingModule {
@ContributesAndroidInjector(modules = {HomeModule.class, AndroidSupportInjectionModule.class})
|
abstract HomeActivity homeActivity();
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/user/UserBindingModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
// public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
//
//
// @Inject ProfileFragment profileFragment;
// @Inject StatsFragment statsFragment;
// @Inject MovesFragment movesFragment;
//
// private ActivityHomeBinding viewDataBinding;
//
// private BottomNavigationView.OnNavigationItemSelectedListener navigationListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// int itemId = item.getItemId();
// if (viewDataBinding.bottomNavigation.getSelectedItemId() == itemId) {
// //do nothing if reselected
// return true;
// }
// return openFragment(itemId);
// }
//
// };
//
// private boolean openFragment(int itemId) {
// Fragment fragment = null;
// switch (itemId) {
// case R.id.action_profile:
// fragment = profileFragment;
// break;
// case R.id.action_moves:
// fragment = movesFragment;
// break;
// case R.id.action_stats:
// fragment = statsFragment;
// break;
// }
//
// if (fragment != null) {
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.fragment_container, fragment)
// .commit();
// return true;
// }
// return false;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
// viewDataBinding.bottomNavigation.setOnNavigationItemSelectedListener(navigationListener);
// viewDataBinding.bottomNavigation.setSelectedItemId(R.id.action_profile);
// openFragment(R.id.action_profile);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_home, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == R.id.action_log_out) {
// logoutUser();
// return true;
// } else if (item.getItemId() == R.id.action_items) {
// openItemsActivity();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void openItemsActivity() {
// Intent intent = new Intent(this, ItemsActivity.class);
// startActivity(intent);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeModule.java
// @Module
// public abstract class HomeModule {
//
// @ContributesAndroidInjector
// abstract ProfileFragment profileFragment();
//
// @ContributesAndroidInjector
// abstract MovesFragment movesFragment();
//
// @ContributesAndroidInjector
// abstract StatsFragment statisticsFragment();
//
//
// @Binds
// public abstract HomeContract.Presenter provideHomePresenter(HomePresenter presenter);
//
// @Binds
// public abstract ProfileContract.Presenter provideProfilePresenter(ProfilePresenter presenter);
//
// @Binds
// public abstract StatsContract.Presenter provideStatsPresenter(StatsPresenter presenter);
//
// @Binds
// public abstract MovesContract.Presenter provideMovesPresenter(MovesPresenter presenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsModule.java
// @Module
// public class ItemsModule {
//
// @Provides
// static ItemsContract.Presenter provideHomePresenter(ItemsPresenter presenter) {
// return presenter;
// }
//
// @Provides
// static ItemsAdapter provideItemsAdapter() {
// return new ItemsAdapter();
// }
//
// @Provides
// static LinearLayoutManager provideLayoutManager(ItemsActivity activity) {
// return new LinearLayoutManager(activity);
// }
//
// @Provides
// static DividerItemDecoration provideDividerItemDecoration(ItemsActivity activity) {
// return new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL);
// }
//
// }
|
import com.ragdroid.dahaka.activity.home.HomeActivity;
import com.ragdroid.dahaka.activity.home.HomeModule;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.activity.items.ItemsModule;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import dagger.android.support.AndroidSupportInjectionModule;
|
package com.ragdroid.dahaka.user;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class UserBindingModule {
@ContributesAndroidInjector(modules = {HomeModule.class, AndroidSupportInjectionModule.class})
abstract HomeActivity homeActivity();
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
// public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
//
//
// @Inject ProfileFragment profileFragment;
// @Inject StatsFragment statsFragment;
// @Inject MovesFragment movesFragment;
//
// private ActivityHomeBinding viewDataBinding;
//
// private BottomNavigationView.OnNavigationItemSelectedListener navigationListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// int itemId = item.getItemId();
// if (viewDataBinding.bottomNavigation.getSelectedItemId() == itemId) {
// //do nothing if reselected
// return true;
// }
// return openFragment(itemId);
// }
//
// };
//
// private boolean openFragment(int itemId) {
// Fragment fragment = null;
// switch (itemId) {
// case R.id.action_profile:
// fragment = profileFragment;
// break;
// case R.id.action_moves:
// fragment = movesFragment;
// break;
// case R.id.action_stats:
// fragment = statsFragment;
// break;
// }
//
// if (fragment != null) {
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.fragment_container, fragment)
// .commit();
// return true;
// }
// return false;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
// viewDataBinding.bottomNavigation.setOnNavigationItemSelectedListener(navigationListener);
// viewDataBinding.bottomNavigation.setSelectedItemId(R.id.action_profile);
// openFragment(R.id.action_profile);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_home, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == R.id.action_log_out) {
// logoutUser();
// return true;
// } else if (item.getItemId() == R.id.action_items) {
// openItemsActivity();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void openItemsActivity() {
// Intent intent = new Intent(this, ItemsActivity.class);
// startActivity(intent);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeModule.java
// @Module
// public abstract class HomeModule {
//
// @ContributesAndroidInjector
// abstract ProfileFragment profileFragment();
//
// @ContributesAndroidInjector
// abstract MovesFragment movesFragment();
//
// @ContributesAndroidInjector
// abstract StatsFragment statisticsFragment();
//
//
// @Binds
// public abstract HomeContract.Presenter provideHomePresenter(HomePresenter presenter);
//
// @Binds
// public abstract ProfileContract.Presenter provideProfilePresenter(ProfilePresenter presenter);
//
// @Binds
// public abstract StatsContract.Presenter provideStatsPresenter(StatsPresenter presenter);
//
// @Binds
// public abstract MovesContract.Presenter provideMovesPresenter(MovesPresenter presenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsModule.java
// @Module
// public class ItemsModule {
//
// @Provides
// static ItemsContract.Presenter provideHomePresenter(ItemsPresenter presenter) {
// return presenter;
// }
//
// @Provides
// static ItemsAdapter provideItemsAdapter() {
// return new ItemsAdapter();
// }
//
// @Provides
// static LinearLayoutManager provideLayoutManager(ItemsActivity activity) {
// return new LinearLayoutManager(activity);
// }
//
// @Provides
// static DividerItemDecoration provideDividerItemDecoration(ItemsActivity activity) {
// return new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL);
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserBindingModule.java
import com.ragdroid.dahaka.activity.home.HomeActivity;
import com.ragdroid.dahaka.activity.home.HomeModule;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.activity.items.ItemsModule;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import dagger.android.support.AndroidSupportInjectionModule;
package com.ragdroid.dahaka.user;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class UserBindingModule {
@ContributesAndroidInjector(modules = {HomeModule.class, AndroidSupportInjectionModule.class})
abstract HomeActivity homeActivity();
|
@ContributesAndroidInjector(modules = {ItemsModule.class})
|
ragdroid/Dahaka
|
app/src/main/java/com/ragdroid/dahaka/user/UserBindingModule.java
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
// public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
//
//
// @Inject ProfileFragment profileFragment;
// @Inject StatsFragment statsFragment;
// @Inject MovesFragment movesFragment;
//
// private ActivityHomeBinding viewDataBinding;
//
// private BottomNavigationView.OnNavigationItemSelectedListener navigationListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// int itemId = item.getItemId();
// if (viewDataBinding.bottomNavigation.getSelectedItemId() == itemId) {
// //do nothing if reselected
// return true;
// }
// return openFragment(itemId);
// }
//
// };
//
// private boolean openFragment(int itemId) {
// Fragment fragment = null;
// switch (itemId) {
// case R.id.action_profile:
// fragment = profileFragment;
// break;
// case R.id.action_moves:
// fragment = movesFragment;
// break;
// case R.id.action_stats:
// fragment = statsFragment;
// break;
// }
//
// if (fragment != null) {
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.fragment_container, fragment)
// .commit();
// return true;
// }
// return false;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
// viewDataBinding.bottomNavigation.setOnNavigationItemSelectedListener(navigationListener);
// viewDataBinding.bottomNavigation.setSelectedItemId(R.id.action_profile);
// openFragment(R.id.action_profile);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_home, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == R.id.action_log_out) {
// logoutUser();
// return true;
// } else if (item.getItemId() == R.id.action_items) {
// openItemsActivity();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void openItemsActivity() {
// Intent intent = new Intent(this, ItemsActivity.class);
// startActivity(intent);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeModule.java
// @Module
// public abstract class HomeModule {
//
// @ContributesAndroidInjector
// abstract ProfileFragment profileFragment();
//
// @ContributesAndroidInjector
// abstract MovesFragment movesFragment();
//
// @ContributesAndroidInjector
// abstract StatsFragment statisticsFragment();
//
//
// @Binds
// public abstract HomeContract.Presenter provideHomePresenter(HomePresenter presenter);
//
// @Binds
// public abstract ProfileContract.Presenter provideProfilePresenter(ProfilePresenter presenter);
//
// @Binds
// public abstract StatsContract.Presenter provideStatsPresenter(StatsPresenter presenter);
//
// @Binds
// public abstract MovesContract.Presenter provideMovesPresenter(MovesPresenter presenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsModule.java
// @Module
// public class ItemsModule {
//
// @Provides
// static ItemsContract.Presenter provideHomePresenter(ItemsPresenter presenter) {
// return presenter;
// }
//
// @Provides
// static ItemsAdapter provideItemsAdapter() {
// return new ItemsAdapter();
// }
//
// @Provides
// static LinearLayoutManager provideLayoutManager(ItemsActivity activity) {
// return new LinearLayoutManager(activity);
// }
//
// @Provides
// static DividerItemDecoration provideDividerItemDecoration(ItemsActivity activity) {
// return new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL);
// }
//
// }
|
import com.ragdroid.dahaka.activity.home.HomeActivity;
import com.ragdroid.dahaka.activity.home.HomeModule;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.activity.items.ItemsModule;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import dagger.android.support.AndroidSupportInjectionModule;
|
package com.ragdroid.dahaka.user;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class UserBindingModule {
@ContributesAndroidInjector(modules = {HomeModule.class, AndroidSupportInjectionModule.class})
abstract HomeActivity homeActivity();
@ContributesAndroidInjector(modules = {ItemsModule.class})
|
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeActivity.java
// public class HomeActivity extends BaseUserActivity<HomeContract.Presenter> {
//
//
// @Inject ProfileFragment profileFragment;
// @Inject StatsFragment statsFragment;
// @Inject MovesFragment movesFragment;
//
// private ActivityHomeBinding viewDataBinding;
//
// private BottomNavigationView.OnNavigationItemSelectedListener navigationListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// int itemId = item.getItemId();
// if (viewDataBinding.bottomNavigation.getSelectedItemId() == itemId) {
// //do nothing if reselected
// return true;
// }
// return openFragment(itemId);
// }
//
// };
//
// private boolean openFragment(int itemId) {
// Fragment fragment = null;
// switch (itemId) {
// case R.id.action_profile:
// fragment = profileFragment;
// break;
// case R.id.action_moves:
// fragment = movesFragment;
// break;
// case R.id.action_stats:
// fragment = statsFragment;
// break;
// }
//
// if (fragment != null) {
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.fragment_container, fragment)
// .commit();
// return true;
// }
// return false;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
// viewDataBinding.bottomNavigation.setOnNavigationItemSelectedListener(navigationListener);
// viewDataBinding.bottomNavigation.setSelectedItemId(R.id.action_profile);
// openFragment(R.id.action_profile);
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_home, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// if (item.getItemId() == R.id.action_log_out) {
// logoutUser();
// return true;
// } else if (item.getItemId() == R.id.action_items) {
// openItemsActivity();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// private void openItemsActivity() {
// Intent intent = new Intent(this, ItemsActivity.class);
// startActivity(intent);
// }
//
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/home/HomeModule.java
// @Module
// public abstract class HomeModule {
//
// @ContributesAndroidInjector
// abstract ProfileFragment profileFragment();
//
// @ContributesAndroidInjector
// abstract MovesFragment movesFragment();
//
// @ContributesAndroidInjector
// abstract StatsFragment statisticsFragment();
//
//
// @Binds
// public abstract HomeContract.Presenter provideHomePresenter(HomePresenter presenter);
//
// @Binds
// public abstract ProfileContract.Presenter provideProfilePresenter(ProfilePresenter presenter);
//
// @Binds
// public abstract StatsContract.Presenter provideStatsPresenter(StatsPresenter presenter);
//
// @Binds
// public abstract MovesContract.Presenter provideMovesPresenter(MovesPresenter presenter);
//
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsActivity.java
// public class ItemsActivity extends BaseUserActivity<ItemsContract.Presenter> implements ItemsContract.View {
//
// @Inject ItemsAdapter adapter;
// @Inject LinearLayoutManager linearLayoutManager;
// @Inject DividerItemDecoration dividerItemDecoration;
// private ActivityItemsBinding binding;
//
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// binding = DataBindingUtil.setContentView(this, R.layout.activity_items);
// super.onCreate(savedInstanceState);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
// toolbar.setNavigationOnClickListener(view -> finish());
// }
//
// @Override
// public void showModel(ItemsModel model) {
// binding.itemsRecyclerView.setAdapter(adapter);
// binding.itemsRecyclerView.addItemDecoration(dividerItemDecoration);
// binding.itemsRecyclerView.setLayoutManager(linearLayoutManager);
// adapter.updateList(model.items);
// }
// }
//
// Path: app/src/main/java/com/ragdroid/dahaka/activity/items/ItemsModule.java
// @Module
// public class ItemsModule {
//
// @Provides
// static ItemsContract.Presenter provideHomePresenter(ItemsPresenter presenter) {
// return presenter;
// }
//
// @Provides
// static ItemsAdapter provideItemsAdapter() {
// return new ItemsAdapter();
// }
//
// @Provides
// static LinearLayoutManager provideLayoutManager(ItemsActivity activity) {
// return new LinearLayoutManager(activity);
// }
//
// @Provides
// static DividerItemDecoration provideDividerItemDecoration(ItemsActivity activity) {
// return new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL);
// }
//
// }
// Path: app/src/main/java/com/ragdroid/dahaka/user/UserBindingModule.java
import com.ragdroid.dahaka.activity.home.HomeActivity;
import com.ragdroid.dahaka.activity.home.HomeModule;
import com.ragdroid.dahaka.activity.items.ItemsActivity;
import com.ragdroid.dahaka.activity.items.ItemsModule;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
import dagger.android.support.AndroidSupportInjectionModule;
package com.ragdroid.dahaka.user;
/**
* Created by garimajain on 13/08/17.
*/
@Module
public abstract class UserBindingModule {
@ContributesAndroidInjector(modules = {HomeModule.class, AndroidSupportInjectionModule.class})
abstract HomeActivity homeActivity();
@ContributesAndroidInjector(modules = {ItemsModule.class})
|
abstract ItemsActivity itemsActivity();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.