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
|
|---|---|---|---|---|---|---|
SW-Team/java-TelegramBot
|
src/milk/telegram/type/callback/CallbackQuery.java
|
// Path: src/milk/telegram/type/Identifier.java
// public interface Identifier<T>{
//
// T getId();
//
// }
//
// Path: src/milk/telegram/type/message/Message.java
// public class Message implements Identifier<Integer>{
//
// private final int date;
// private final int message_id;
//
// private final User from;
// private final Chat chat;
//
// private final Message reply_message;
//
// private final User forward_from;
// private final Chat forward_from_chat;
//
// private final JSONObject object;
//
// protected Message(JSONObject object){
// this.object = object;
//
// this.date = object.getInt("date");
// this.message_id = object.getInt("message_id");
// this.chat = Chat.create(object.getJSONObject("chat"));
//
// this.from = User.create(object.optJSONObject("from"));
// this.reply_message = Message.create(object.optJSONObject("reply_to_message"));
//
// this.forward_from = User.create(object.optJSONObject("forward_from"));
// this.forward_from_chat = Chat.create(object.optJSONObject("forward_from_chat"));
// }
//
// public static Message create(JSONObject object){
// if(object == null){
// return null;
// }else if(object.has("result")){
// object = object.optJSONObject("result");
// if(object == null || object.length() < 1){
// return null;
// }
// }
//
// if(object.has("game")){
// return new GameMessage(object);
// }else if(object.has("audio")){
// return new AudioMessage(object);
// }else if(object.has("contact")){
// return new ContactMessage(object);
// }else if(object.has("document")){
// return new DocumentMessage(object);
// }else if(object.has("location")){
// return new LocationMessage(object);
// }else if(object.has("photo")){
// return new PhotoMessage(object);
// }else if(object.has("sticker")){
// return new StickerMessage(object);
// }else if(object.has("text")){
// return new TextMessage(object);
// }else if(object.has("venue")){
// return new VenueMessage(object);
// }else if(object.has("video")){
// return new VideoMessage(object);
// }else if(object.has("voice")){
// return new VoiceMessage(object);
// }
// return new Message(object);
// }
//
// public Integer getId(){
// return this.message_id;
// }
//
// public int getDate(){
// return this.date;
// }
//
// public User getFrom(){
// return this.from;
// }
//
// public Chat getChat(){
// return this.chat;
// }
//
// public boolean isReplyMessage(){
// return this.reply_message != null;
// }
//
// public boolean isForwardMessage(){
// return this.forward_from != null || this.forward_from_chat != null;
// }
//
// public Message getReplyMessage(){
// return this.reply_message;
// }
//
// public User getForwardFrom(){
// return forward_from;
// }
//
// public Chat getForwardChat(){
// return forward_from_chat;
// }
//
// public String getName(){
// return "메시지";
// }
//
// public JSONObject toJSONObject(){
// return object;
// }
//
// @Override
// public String toString(){
// return this.getName();
// }
//
// }
//
// Path: src/milk/telegram/type/user/User.java
// public class User implements Identifier<Integer>, Usernamed{
//
// private int id;
//
// private String last;
// private String first;
// private String username;
//
// private User(JSONObject object){
// this.id = object.getInt("id");
// this.last = object.optString("last_name", null);
// this.first = object.optString("first_name", null);
// this.username = object.optString("username", null);
// }
//
// public static User create(JSONObject object){
// if(object == null){
// return null;
// }else if(object.has("result")){
// object = object.optJSONObject("result");
// if(object.length() < 1){
// return null;
// }
// }
// return new User(object);
// }
//
// public Integer getId(){
// return this.id;
// }
//
// public String getFirstName(){
// return this.first;
// }
//
// public String getLastName(){
// return this.last;
// }
//
// public String getUsername(){
// return this.username;
// }
//
// public String getFullName(){
// return (this.getLastName() == null ? "" : this.getLastName() + " ") + this.getFirstName();
// }
//
// }
|
import milk.telegram.type.Identifier;
import milk.telegram.type.message.Message;
import milk.telegram.type.user.User;
import org.json.JSONObject;
|
package milk.telegram.type.callback;
public class CallbackQuery implements Identifier<String>{
private final String id;
private final User from;
|
// Path: src/milk/telegram/type/Identifier.java
// public interface Identifier<T>{
//
// T getId();
//
// }
//
// Path: src/milk/telegram/type/message/Message.java
// public class Message implements Identifier<Integer>{
//
// private final int date;
// private final int message_id;
//
// private final User from;
// private final Chat chat;
//
// private final Message reply_message;
//
// private final User forward_from;
// private final Chat forward_from_chat;
//
// private final JSONObject object;
//
// protected Message(JSONObject object){
// this.object = object;
//
// this.date = object.getInt("date");
// this.message_id = object.getInt("message_id");
// this.chat = Chat.create(object.getJSONObject("chat"));
//
// this.from = User.create(object.optJSONObject("from"));
// this.reply_message = Message.create(object.optJSONObject("reply_to_message"));
//
// this.forward_from = User.create(object.optJSONObject("forward_from"));
// this.forward_from_chat = Chat.create(object.optJSONObject("forward_from_chat"));
// }
//
// public static Message create(JSONObject object){
// if(object == null){
// return null;
// }else if(object.has("result")){
// object = object.optJSONObject("result");
// if(object == null || object.length() < 1){
// return null;
// }
// }
//
// if(object.has("game")){
// return new GameMessage(object);
// }else if(object.has("audio")){
// return new AudioMessage(object);
// }else if(object.has("contact")){
// return new ContactMessage(object);
// }else if(object.has("document")){
// return new DocumentMessage(object);
// }else if(object.has("location")){
// return new LocationMessage(object);
// }else if(object.has("photo")){
// return new PhotoMessage(object);
// }else if(object.has("sticker")){
// return new StickerMessage(object);
// }else if(object.has("text")){
// return new TextMessage(object);
// }else if(object.has("venue")){
// return new VenueMessage(object);
// }else if(object.has("video")){
// return new VideoMessage(object);
// }else if(object.has("voice")){
// return new VoiceMessage(object);
// }
// return new Message(object);
// }
//
// public Integer getId(){
// return this.message_id;
// }
//
// public int getDate(){
// return this.date;
// }
//
// public User getFrom(){
// return this.from;
// }
//
// public Chat getChat(){
// return this.chat;
// }
//
// public boolean isReplyMessage(){
// return this.reply_message != null;
// }
//
// public boolean isForwardMessage(){
// return this.forward_from != null || this.forward_from_chat != null;
// }
//
// public Message getReplyMessage(){
// return this.reply_message;
// }
//
// public User getForwardFrom(){
// return forward_from;
// }
//
// public Chat getForwardChat(){
// return forward_from_chat;
// }
//
// public String getName(){
// return "메시지";
// }
//
// public JSONObject toJSONObject(){
// return object;
// }
//
// @Override
// public String toString(){
// return this.getName();
// }
//
// }
//
// Path: src/milk/telegram/type/user/User.java
// public class User implements Identifier<Integer>, Usernamed{
//
// private int id;
//
// private String last;
// private String first;
// private String username;
//
// private User(JSONObject object){
// this.id = object.getInt("id");
// this.last = object.optString("last_name", null);
// this.first = object.optString("first_name", null);
// this.username = object.optString("username", null);
// }
//
// public static User create(JSONObject object){
// if(object == null){
// return null;
// }else if(object.has("result")){
// object = object.optJSONObject("result");
// if(object.length() < 1){
// return null;
// }
// }
// return new User(object);
// }
//
// public Integer getId(){
// return this.id;
// }
//
// public String getFirstName(){
// return this.first;
// }
//
// public String getLastName(){
// return this.last;
// }
//
// public String getUsername(){
// return this.username;
// }
//
// public String getFullName(){
// return (this.getLastName() == null ? "" : this.getLastName() + " ") + this.getFirstName();
// }
//
// }
// Path: src/milk/telegram/type/callback/CallbackQuery.java
import milk.telegram.type.Identifier;
import milk.telegram.type.message.Message;
import milk.telegram.type.user.User;
import org.json.JSONObject;
package milk.telegram.type.callback;
public class CallbackQuery implements Identifier<String>{
private final String id;
private final User from;
|
private final Message message;
|
SW-Team/java-TelegramBot
|
src/milk/telegram/type/file/Document.java
|
// Path: src/milk/telegram/type/file/photo/PhotoSize.java
// public class PhotoSize implements Identifier<String>{
//
// private final String id;
//
// private final int width;
// private final int height;
//
// private final Integer size;
//
// private PhotoSize(JSONObject object){
// this.id = object.getString("file_id");
// this.width = object.getInt("width");
// this.height = object.getInt("height");
// this.size = object.has("file_size") ? object.getInt("file_size") : null;
// }
//
// public static PhotoSize create(JSONObject object){
// if(object == null){
// return null;
// }
// return new PhotoSize(object);
// }
//
// public String getId(){
// return id;
// }
//
// public int getWidth(){
// return this.width;
// }
//
// public int getHeight(){
// return this.height;
// }
//
// public Integer getSize(){
// return size;
// }
//
// }
//
// Path: src/milk/telegram/type/Identifier.java
// public interface Identifier<T>{
//
// T getId();
//
// }
|
import milk.telegram.type.file.photo.PhotoSize;
import milk.telegram.type.Identifier;
import org.json.JSONObject;
|
package milk.telegram.type.file;
public class Document implements Identifier<String>{
private final String file_id;
private final String file_name;
private final String mime_type;
|
// Path: src/milk/telegram/type/file/photo/PhotoSize.java
// public class PhotoSize implements Identifier<String>{
//
// private final String id;
//
// private final int width;
// private final int height;
//
// private final Integer size;
//
// private PhotoSize(JSONObject object){
// this.id = object.getString("file_id");
// this.width = object.getInt("width");
// this.height = object.getInt("height");
// this.size = object.has("file_size") ? object.getInt("file_size") : null;
// }
//
// public static PhotoSize create(JSONObject object){
// if(object == null){
// return null;
// }
// return new PhotoSize(object);
// }
//
// public String getId(){
// return id;
// }
//
// public int getWidth(){
// return this.width;
// }
//
// public int getHeight(){
// return this.height;
// }
//
// public Integer getSize(){
// return size;
// }
//
// }
//
// Path: src/milk/telegram/type/Identifier.java
// public interface Identifier<T>{
//
// T getId();
//
// }
// Path: src/milk/telegram/type/file/Document.java
import milk.telegram.type.file.photo.PhotoSize;
import milk.telegram.type.Identifier;
import org.json.JSONObject;
package milk.telegram.type.file;
public class Document implements Identifier<String>{
private final String file_id;
private final String file_name;
private final String mime_type;
|
private final PhotoSize thumb;
|
SW-Team/java-TelegramBot
|
src/milk/telegram/type/reply/InlineKeyboardMarkup.java
|
// Path: src/milk/telegram/type/inline/InlineKeyboardButton.java
// public class InlineKeyboardButton extends JSONObject{
//
// public InlineKeyboardButton setText(String text){
// this.put("text", text);
// return this;
// }
//
// public InlineKeyboardButton setUrl(String url){
// this.put("url", url);
// return this;
// }
//
// public InlineKeyboardButton setCallbackGame(Object callback_game){
// this.put("callback_game", callback_game);
// return this;
// }
//
// public InlineKeyboardButton setCallbackData(String callback_data){
// this.put("callback_data", callback_data);
// return this;
// }
//
// public InlineKeyboardButton setSwitchInlineQuery(String switch_inline_query){
// this.put("switch_inline_query", switch_inline_query);
// return this;
// }
//
// public InlineKeyboardButton setSwitchInlineQueryCurrentChat(String switch_inline_query_current_chat){
// this.put("switch_inline_query_current_chat", switch_inline_query_current_chat);
// return this;
// }
//
// }
|
import milk.telegram.type.inline.InlineKeyboardButton;
import org.json.JSONArray;
|
package milk.telegram.type.reply;
public class InlineKeyboardMarkup extends ReplyMarkup{
public InlineKeyboardMarkup(){
this.put("inline_keyboard", new JSONArray());
}
|
// Path: src/milk/telegram/type/inline/InlineKeyboardButton.java
// public class InlineKeyboardButton extends JSONObject{
//
// public InlineKeyboardButton setText(String text){
// this.put("text", text);
// return this;
// }
//
// public InlineKeyboardButton setUrl(String url){
// this.put("url", url);
// return this;
// }
//
// public InlineKeyboardButton setCallbackGame(Object callback_game){
// this.put("callback_game", callback_game);
// return this;
// }
//
// public InlineKeyboardButton setCallbackData(String callback_data){
// this.put("callback_data", callback_data);
// return this;
// }
//
// public InlineKeyboardButton setSwitchInlineQuery(String switch_inline_query){
// this.put("switch_inline_query", switch_inline_query);
// return this;
// }
//
// public InlineKeyboardButton setSwitchInlineQueryCurrentChat(String switch_inline_query_current_chat){
// this.put("switch_inline_query_current_chat", switch_inline_query_current_chat);
// return this;
// }
//
// }
// Path: src/milk/telegram/type/reply/InlineKeyboardMarkup.java
import milk.telegram.type.inline.InlineKeyboardButton;
import org.json.JSONArray;
package milk.telegram.type.reply;
public class InlineKeyboardMarkup extends ReplyMarkup{
public InlineKeyboardMarkup(){
this.put("inline_keyboard", new JSONArray());
}
|
public InlineKeyboardButton getButton(int column, int row){
|
SW-Team/java-TelegramBot
|
src/milk/telegram/type/reply/ReplyKeyboardMarkup.java
|
// Path: src/milk/telegram/type/callback/KeyboardButton.java
// public class KeyboardButton extends JSONObject{
//
// public KeyboardButton setText(String text){
// this.put("text", text);
// return this;
// }
//
// public KeyboardButton setRequestContact(boolean request_contact){
// this.put("request_contact", request_contact);
// return this;
// }
//
// public KeyboardButton setRequestLocation(boolean request_location){
// this.put("request_location", request_location);
// return this;
// }
//
// }
|
import milk.telegram.type.callback.KeyboardButton;
import org.json.JSONArray;
|
package milk.telegram.type.reply;
public class ReplyKeyboardMarkup extends ReplyMarkup{
public ReplyKeyboardMarkup(){
this.put("keyboard", new JSONArray());
}
public Boolean getSelective(){
return this.optBoolean("selective");
}
public Boolean getResizeKeyboard(){
return this.optBoolean("resize_keyboard");
}
public Boolean getOneTimeKeyboard(){
return this.optBoolean("one_time_keyboard");
}
|
// Path: src/milk/telegram/type/callback/KeyboardButton.java
// public class KeyboardButton extends JSONObject{
//
// public KeyboardButton setText(String text){
// this.put("text", text);
// return this;
// }
//
// public KeyboardButton setRequestContact(boolean request_contact){
// this.put("request_contact", request_contact);
// return this;
// }
//
// public KeyboardButton setRequestLocation(boolean request_location){
// this.put("request_location", request_location);
// return this;
// }
//
// }
// Path: src/milk/telegram/type/reply/ReplyKeyboardMarkup.java
import milk.telegram.type.callback.KeyboardButton;
import org.json.JSONArray;
package milk.telegram.type.reply;
public class ReplyKeyboardMarkup extends ReplyMarkup{
public ReplyKeyboardMarkup(){
this.put("keyboard", new JSONArray());
}
public Boolean getSelective(){
return this.optBoolean("selective");
}
public Boolean getResizeKeyboard(){
return this.optBoolean("resize_keyboard");
}
public Boolean getOneTimeKeyboard(){
return this.optBoolean("one_time_keyboard");
}
|
public KeyboardButton getButton(int column, int row){
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/ui/base/BasePresenter.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/CompositeDisposableHelper.java
// public class CompositeDisposableHelper {
//
// public CompositeDisposable disposables;
// public BaseSchedulerProvider schedulerProvider;
//
// @Inject public CompositeDisposableHelper(CompositeDisposable disposables,
// BaseSchedulerProvider schedulerProvider) {
// this.disposables = disposables;
// this.schedulerProvider = schedulerProvider;
// }
//
// private final ObservableTransformer schedulersTransformer = new ObservableTransformer() {
// @Override public ObservableSource apply(Observable upstream) {
// return upstream.subscribeOn(schedulerProvider.io()).observeOn(schedulerProvider.ui());
// }
// };
//
// public <T> ObservableTransformer<T, T> applySchedulers() {
// return (ObservableTransformer<T, T>) schedulersTransformer;
// }
//
// public void addDisposable(Disposable disposable) {
// disposables.add(disposable);
// }
//
// public void dispose() {
// if (!disposables.isDisposed()) {
// disposables.dispose();
// }
// }
//
// public BaseSchedulerProvider getSchedulerProvider() {
// return schedulerProvider;
// }
// }
|
import android.support.annotation.NonNull;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.data.remote.helper.CompositeDisposableHelper;
|
package mk.petrovski.weathergurumvp.ui.base;
/**
* Base class that implements the Presenter interface and provides a base implementation for
* attachView() and detachView(). It also handles keeping a reference to the mvpView that
* can be accessed from the children classes by calling getMvpView().
*/
public class BasePresenter<V extends BaseMvpView> implements Presenter<V> {
CompositeDisposableHelper compositeDisposableHelper;
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/CompositeDisposableHelper.java
// public class CompositeDisposableHelper {
//
// public CompositeDisposable disposables;
// public BaseSchedulerProvider schedulerProvider;
//
// @Inject public CompositeDisposableHelper(CompositeDisposable disposables,
// BaseSchedulerProvider schedulerProvider) {
// this.disposables = disposables;
// this.schedulerProvider = schedulerProvider;
// }
//
// private final ObservableTransformer schedulersTransformer = new ObservableTransformer() {
// @Override public ObservableSource apply(Observable upstream) {
// return upstream.subscribeOn(schedulerProvider.io()).observeOn(schedulerProvider.ui());
// }
// };
//
// public <T> ObservableTransformer<T, T> applySchedulers() {
// return (ObservableTransformer<T, T>) schedulersTransformer;
// }
//
// public void addDisposable(Disposable disposable) {
// disposables.add(disposable);
// }
//
// public void dispose() {
// if (!disposables.isDisposed()) {
// disposables.dispose();
// }
// }
//
// public BaseSchedulerProvider getSchedulerProvider() {
// return schedulerProvider;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/base/BasePresenter.java
import android.support.annotation.NonNull;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.data.remote.helper.CompositeDisposableHelper;
package mk.petrovski.weathergurumvp.ui.base;
/**
* Base class that implements the Presenter interface and provides a base implementation for
* attachView() and detachView(). It also handles keeping a reference to the mvpView that
* can be accessed from the children classes by calling getMvpView().
*/
public class BasePresenter<V extends BaseMvpView> implements Presenter<V> {
CompositeDisposableHelper compositeDisposableHelper;
|
DataManager dataManager;
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/HourlyModel.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/ValueModel.java
// public class ValueModel {
// private String value;
//
// public ValueModel(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
|
import java.util.List;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.ValueModel;
|
package mk.petrovski.weathergurumvp.data.remote.model.weather_models;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
public class HourlyModel {
private String chanceoffog;
private String chanceoffrost;
private String chanceofhightemp;
private String chanceofovercast;
private String chanceofrain;
private String chanceofremdry;
private String chanceofsnow;
private String chanceofsunshine;
private String chanceofthunder;
private String chanceofwindy;
private String cloudcover;
private String DewPointC;
private String DewPointF;
private String FeelsLikeC;
private String FeelsLikeF;
private String HeatIndexC;
private String HeatIndexF;
private String humidity;
private String precipMM;
private String pressure;
private String tempC;
private String tempF;
private String time;
private String visibility;
private String weatherCode;
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/ValueModel.java
// public class ValueModel {
// private String value;
//
// public ValueModel(String value) {
// this.value = value;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/HourlyModel.java
import java.util.List;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.ValueModel;
package mk.petrovski.weathergurumvp.data.remote.model.weather_models;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
public class HourlyModel {
private String chanceoffog;
private String chanceoffrost;
private String chanceofhightemp;
private String chanceofovercast;
private String chanceofrain;
private String chanceofremdry;
private String chanceofsnow;
private String chanceofsunshine;
private String chanceofthunder;
private String chanceofwindy;
private String cloudcover;
private String DewPointC;
private String DewPointF;
private String FeelsLikeC;
private String FeelsLikeF;
private String HeatIndexC;
private String HeatIndexF;
private String humidity;
private String precipMM;
private String pressure;
private String tempC;
private String tempF;
private String time;
private String visibility;
private String weatherCode;
|
private List<ValueModel> weatherDesc;
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/injection/component/ApplicationComponent.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/WeatherGuruApplication.java
// public class WeatherGuruApplication extends Application {
//
// @Inject CalligraphyConfig calligraphyConfig;
//
// public static ApplicationComponent applicationComponent;
//
// @Override public void onCreate() {
// super.onCreate();
//
// applicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(this))
// .contextModule(new ContextModule(this))
// .databaseModule(new DatabaseModule())
// .networkModule(new NetworkModule())
// .build();
//
// applicationComponent.inject(this);
//
// CalligraphyConfig.initDefault(calligraphyConfig);
// Timber.plant(new Timber.DebugTree());
// }
//
// public static ApplicationComponent getApplicationComponent() {
// return applicationComponent;
// }
//
// public void setApplicationComponent(ApplicationComponent applicationComponent) {
// WeatherGuruApplication.applicationComponent = applicationComponent;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/ApplicationModule.java
// @Module(includes = {
// ContextModule.class, PreferencesModule.class, NetworkModule.class, DatabaseModule.class
// }) public class ApplicationModule {
//
// private final Application application;
//
// public ApplicationModule(Application application) {
// this.application = application;
// }
//
// @Provides Application getApplication() {
// return application;
// }
//
// @Provides @WeatherGuruApplicationScope CalligraphyConfig getCalligraphyConfig() {
// return new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Roboto-Regular.ttf")
// .setFontAttrId(R.attr.fontPath)
// .build();
// }
//
// @Provides @WeatherGuruApplicationScope AppDataManager getAppDataManager(
// @ApplicationContext Context context, PreferencesHelper preferencesHelper, DbHelper dbHelper,
// ApiHelper apiHelper) {
// return new AppDataManager(context, dbHelper, preferencesHelper, apiHelper);
// }
//
// @Provides @WeatherGuruApplicationScope DataManager getDataManager(AppDataManager appDataManager) {
// return appDataManager;
// }
// }
|
import android.content.Context;
import dagger.Component;
import mk.petrovski.weathergurumvp.WeatherGuruApplication;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.injection.module.ApplicationModule;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
|
package mk.petrovski.weathergurumvp.injection.component;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
@WeatherGuruApplicationScope @Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/WeatherGuruApplication.java
// public class WeatherGuruApplication extends Application {
//
// @Inject CalligraphyConfig calligraphyConfig;
//
// public static ApplicationComponent applicationComponent;
//
// @Override public void onCreate() {
// super.onCreate();
//
// applicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(this))
// .contextModule(new ContextModule(this))
// .databaseModule(new DatabaseModule())
// .networkModule(new NetworkModule())
// .build();
//
// applicationComponent.inject(this);
//
// CalligraphyConfig.initDefault(calligraphyConfig);
// Timber.plant(new Timber.DebugTree());
// }
//
// public static ApplicationComponent getApplicationComponent() {
// return applicationComponent;
// }
//
// public void setApplicationComponent(ApplicationComponent applicationComponent) {
// WeatherGuruApplication.applicationComponent = applicationComponent;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/ApplicationModule.java
// @Module(includes = {
// ContextModule.class, PreferencesModule.class, NetworkModule.class, DatabaseModule.class
// }) public class ApplicationModule {
//
// private final Application application;
//
// public ApplicationModule(Application application) {
// this.application = application;
// }
//
// @Provides Application getApplication() {
// return application;
// }
//
// @Provides @WeatherGuruApplicationScope CalligraphyConfig getCalligraphyConfig() {
// return new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Roboto-Regular.ttf")
// .setFontAttrId(R.attr.fontPath)
// .build();
// }
//
// @Provides @WeatherGuruApplicationScope AppDataManager getAppDataManager(
// @ApplicationContext Context context, PreferencesHelper preferencesHelper, DbHelper dbHelper,
// ApiHelper apiHelper) {
// return new AppDataManager(context, dbHelper, preferencesHelper, apiHelper);
// }
//
// @Provides @WeatherGuruApplicationScope DataManager getDataManager(AppDataManager appDataManager) {
// return appDataManager;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/component/ApplicationComponent.java
import android.content.Context;
import dagger.Component;
import mk.petrovski.weathergurumvp.WeatherGuruApplication;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.injection.module.ApplicationModule;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
package mk.petrovski.weathergurumvp.injection.component;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
@WeatherGuruApplicationScope @Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
|
void inject(WeatherGuruApplication application);
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/injection/component/ApplicationComponent.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/WeatherGuruApplication.java
// public class WeatherGuruApplication extends Application {
//
// @Inject CalligraphyConfig calligraphyConfig;
//
// public static ApplicationComponent applicationComponent;
//
// @Override public void onCreate() {
// super.onCreate();
//
// applicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(this))
// .contextModule(new ContextModule(this))
// .databaseModule(new DatabaseModule())
// .networkModule(new NetworkModule())
// .build();
//
// applicationComponent.inject(this);
//
// CalligraphyConfig.initDefault(calligraphyConfig);
// Timber.plant(new Timber.DebugTree());
// }
//
// public static ApplicationComponent getApplicationComponent() {
// return applicationComponent;
// }
//
// public void setApplicationComponent(ApplicationComponent applicationComponent) {
// WeatherGuruApplication.applicationComponent = applicationComponent;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/ApplicationModule.java
// @Module(includes = {
// ContextModule.class, PreferencesModule.class, NetworkModule.class, DatabaseModule.class
// }) public class ApplicationModule {
//
// private final Application application;
//
// public ApplicationModule(Application application) {
// this.application = application;
// }
//
// @Provides Application getApplication() {
// return application;
// }
//
// @Provides @WeatherGuruApplicationScope CalligraphyConfig getCalligraphyConfig() {
// return new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Roboto-Regular.ttf")
// .setFontAttrId(R.attr.fontPath)
// .build();
// }
//
// @Provides @WeatherGuruApplicationScope AppDataManager getAppDataManager(
// @ApplicationContext Context context, PreferencesHelper preferencesHelper, DbHelper dbHelper,
// ApiHelper apiHelper) {
// return new AppDataManager(context, dbHelper, preferencesHelper, apiHelper);
// }
//
// @Provides @WeatherGuruApplicationScope DataManager getDataManager(AppDataManager appDataManager) {
// return appDataManager;
// }
// }
|
import android.content.Context;
import dagger.Component;
import mk.petrovski.weathergurumvp.WeatherGuruApplication;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.injection.module.ApplicationModule;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
|
package mk.petrovski.weathergurumvp.injection.component;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
@WeatherGuruApplicationScope @Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
void inject(WeatherGuruApplication application);
@ApplicationContext Context context();
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/WeatherGuruApplication.java
// public class WeatherGuruApplication extends Application {
//
// @Inject CalligraphyConfig calligraphyConfig;
//
// public static ApplicationComponent applicationComponent;
//
// @Override public void onCreate() {
// super.onCreate();
//
// applicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(this))
// .contextModule(new ContextModule(this))
// .databaseModule(new DatabaseModule())
// .networkModule(new NetworkModule())
// .build();
//
// applicationComponent.inject(this);
//
// CalligraphyConfig.initDefault(calligraphyConfig);
// Timber.plant(new Timber.DebugTree());
// }
//
// public static ApplicationComponent getApplicationComponent() {
// return applicationComponent;
// }
//
// public void setApplicationComponent(ApplicationComponent applicationComponent) {
// WeatherGuruApplication.applicationComponent = applicationComponent;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/ApplicationModule.java
// @Module(includes = {
// ContextModule.class, PreferencesModule.class, NetworkModule.class, DatabaseModule.class
// }) public class ApplicationModule {
//
// private final Application application;
//
// public ApplicationModule(Application application) {
// this.application = application;
// }
//
// @Provides Application getApplication() {
// return application;
// }
//
// @Provides @WeatherGuruApplicationScope CalligraphyConfig getCalligraphyConfig() {
// return new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Roboto-Regular.ttf")
// .setFontAttrId(R.attr.fontPath)
// .build();
// }
//
// @Provides @WeatherGuruApplicationScope AppDataManager getAppDataManager(
// @ApplicationContext Context context, PreferencesHelper preferencesHelper, DbHelper dbHelper,
// ApiHelper apiHelper) {
// return new AppDataManager(context, dbHelper, preferencesHelper, apiHelper);
// }
//
// @Provides @WeatherGuruApplicationScope DataManager getDataManager(AppDataManager appDataManager) {
// return appDataManager;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/component/ApplicationComponent.java
import android.content.Context;
import dagger.Component;
import mk.petrovski.weathergurumvp.WeatherGuruApplication;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.injection.module.ApplicationModule;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
package mk.petrovski.weathergurumvp.injection.component;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
@WeatherGuruApplicationScope @Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
void inject(WeatherGuruApplication application);
@ApplicationContext Context context();
|
DataManager getDataManager();
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiInterface.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
|
import io.reactivex.Observable;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
import retrofit2.http.GET;
import retrofit2.http.Query;
|
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
public interface ApiInterface {
@GET(ApiConsts.LOCATION_SEARCH_API_URL) Observable<SearchApiResponseModel> getLocations(
@Query("query") String query, @Query("key") String key, @Query("format") String format);
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiInterface.java
import io.reactivex.Observable;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
import retrofit2.http.GET;
import retrofit2.http.Query;
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
public interface ApiInterface {
@GET(ApiConsts.LOCATION_SEARCH_API_URL) Observable<SearchApiResponseModel> getLocations(
@Query("query") String query, @Query("key") String key, @Query("format") String format);
|
@GET(ApiConsts.WEATHER_API_URL) Observable<WeatherResponseModel> checkWeather(
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/BaseViewSubscriber.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/InternetConnectionException.java
// public class InternetConnectionException extends Throwable {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/base/BaseMvpView.java
// public interface BaseMvpView {
//
// void showLoading();
//
// void hideLoading();
//
// void onError(@StringRes int resId);
//
// void onError(String message);
//
// boolean isNetworkConnected();
//
// void hideKeyboard();
// }
|
import io.reactivex.observers.DisposableObserver;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.helper.error.InternetConnectionException;
import mk.petrovski.weathergurumvp.ui.base.BaseMvpView;
|
package mk.petrovski.weathergurumvp.data.remote.helper;
/**
* Created by Nikola Petrovski on 2/22/2017.
*/
/**
* Default DisposableObserver base class to be used whenever you want default error handling
*/
public class BaseViewSubscriber<V extends BaseMvpView, T> extends DisposableObserver<T> {
private V view;
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/InternetConnectionException.java
// public class InternetConnectionException extends Throwable {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/base/BaseMvpView.java
// public interface BaseMvpView {
//
// void showLoading();
//
// void hideLoading();
//
// void onError(@StringRes int resId);
//
// void onError(String message);
//
// boolean isNetworkConnected();
//
// void hideKeyboard();
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/BaseViewSubscriber.java
import io.reactivex.observers.DisposableObserver;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.helper.error.InternetConnectionException;
import mk.petrovski.weathergurumvp.ui.base.BaseMvpView;
package mk.petrovski.weathergurumvp.data.remote.helper;
/**
* Created by Nikola Petrovski on 2/22/2017.
*/
/**
* Default DisposableObserver base class to be used whenever you want default error handling
*/
public class BaseViewSubscriber<V extends BaseMvpView, T> extends DisposableObserver<T> {
private V view;
|
private ErrorHandlerHelper errorHandlerHelper;
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/BaseViewSubscriber.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/InternetConnectionException.java
// public class InternetConnectionException extends Throwable {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/base/BaseMvpView.java
// public interface BaseMvpView {
//
// void showLoading();
//
// void hideLoading();
//
// void onError(@StringRes int resId);
//
// void onError(String message);
//
// boolean isNetworkConnected();
//
// void hideKeyboard();
// }
|
import io.reactivex.observers.DisposableObserver;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.helper.error.InternetConnectionException;
import mk.petrovski.weathergurumvp.ui.base.BaseMvpView;
|
package mk.petrovski.weathergurumvp.data.remote.helper;
/**
* Created by Nikola Petrovski on 2/22/2017.
*/
/**
* Default DisposableObserver base class to be used whenever you want default error handling
*/
public class BaseViewSubscriber<V extends BaseMvpView, T> extends DisposableObserver<T> {
private V view;
private ErrorHandlerHelper errorHandlerHelper;
public BaseViewSubscriber(V view, ErrorHandlerHelper errorHandlerHelper) {
this.view = view;
this.errorHandlerHelper = errorHandlerHelper;
}
public V getView() {
return view;
}
public boolean shouldShowError() {
return true;
}
protected boolean shouldShowLoading() {
return true;
}
@Override public void onStart() {
if (!view.isNetworkConnected()) {
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/InternetConnectionException.java
// public class InternetConnectionException extends Throwable {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/base/BaseMvpView.java
// public interface BaseMvpView {
//
// void showLoading();
//
// void hideLoading();
//
// void onError(@StringRes int resId);
//
// void onError(String message);
//
// boolean isNetworkConnected();
//
// void hideKeyboard();
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/BaseViewSubscriber.java
import io.reactivex.observers.DisposableObserver;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.helper.error.InternetConnectionException;
import mk.petrovski.weathergurumvp.ui.base.BaseMvpView;
package mk.petrovski.weathergurumvp.data.remote.helper;
/**
* Created by Nikola Petrovski on 2/22/2017.
*/
/**
* Default DisposableObserver base class to be used whenever you want default error handling
*/
public class BaseViewSubscriber<V extends BaseMvpView, T> extends DisposableObserver<T> {
private V view;
private ErrorHandlerHelper errorHandlerHelper;
public BaseViewSubscriber(V view, ErrorHandlerHelper errorHandlerHelper) {
this.view = view;
this.errorHandlerHelper = errorHandlerHelper;
}
public V getView() {
return view;
}
public boolean shouldShowError() {
return true;
}
protected boolean shouldShowLoading() {
return true;
}
@Override public void onStart() {
if (!view.isNetworkConnected()) {
|
onError(new InternetConnectionException());
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherModel.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/utils/DateUtils.java
// public class DateUtils {
//
// /**
// * Check if some date is the current day
// */
// private static boolean isToday(String date) {
// return DateTimeComparator.getDateOnlyInstance().compare(new DateTime(), new DateTime(date))
// == 0;
// }
//
// /**
// * Get name day for some date. If is current day return 'Today'
// */
// //TODO should be in the string.xml
// public static String getDayName(String date) {
// if (isToday(date)) {
// return "Today";
// } else {
// return new DateTime(date).toString(DateTimeFormat.forPattern("EEEE"));
// }
// }
//
// /**
// * Get short month name
// */
// public static String getMonthName(String date) {
// return new DateTime(date).toString(DateTimeFormat.forPattern("dd MMM"));
// }
// }
|
import java.util.List;
import mk.petrovski.weathergurumvp.utils.DateUtils;
|
package mk.petrovski.weathergurumvp.data.remote.model.weather_models;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
public class WeatherModel {
private List<AstronomyModel> astronomy;
private String date;
private List<HourlyModel> hourly;
private String maxtempC;
private String maxtempF;
private String mintempC;
private String mintempF;
private String uvIndex;
public String getShortMonthDate() {
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/utils/DateUtils.java
// public class DateUtils {
//
// /**
// * Check if some date is the current day
// */
// private static boolean isToday(String date) {
// return DateTimeComparator.getDateOnlyInstance().compare(new DateTime(), new DateTime(date))
// == 0;
// }
//
// /**
// * Get name day for some date. If is current day return 'Today'
// */
// //TODO should be in the string.xml
// public static String getDayName(String date) {
// if (isToday(date)) {
// return "Today";
// } else {
// return new DateTime(date).toString(DateTimeFormat.forPattern("EEEE"));
// }
// }
//
// /**
// * Get short month name
// */
// public static String getMonthName(String date) {
// return new DateTime(date).toString(DateTimeFormat.forPattern("dd MMM"));
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherModel.java
import java.util.List;
import mk.petrovski.weathergurumvp.utils.DateUtils;
package mk.petrovski.weathergurumvp.data.remote.model.weather_models;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
public class WeatherModel {
private List<AstronomyModel> astronomy;
private String date;
private List<HourlyModel> hourly;
private String maxtempC;
private String maxtempF;
private String mintempC;
private String mintempF;
private String uvIndex;
public String getShortMonthDate() {
|
return DateUtils.getMonthName(date);
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/injection/module/RxModule.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/CompositeDisposableHelper.java
// public class CompositeDisposableHelper {
//
// public CompositeDisposable disposables;
// public BaseSchedulerProvider schedulerProvider;
//
// @Inject public CompositeDisposableHelper(CompositeDisposable disposables,
// BaseSchedulerProvider schedulerProvider) {
// this.disposables = disposables;
// this.schedulerProvider = schedulerProvider;
// }
//
// private final ObservableTransformer schedulersTransformer = new ObservableTransformer() {
// @Override public ObservableSource apply(Observable upstream) {
// return upstream.subscribeOn(schedulerProvider.io()).observeOn(schedulerProvider.ui());
// }
// };
//
// public <T> ObservableTransformer<T, T> applySchedulers() {
// return (ObservableTransformer<T, T>) schedulersTransformer;
// }
//
// public void addDisposable(Disposable disposable) {
// disposables.add(disposable);
// }
//
// public void dispose() {
// if (!disposables.isDisposed()) {
// disposables.dispose();
// }
// }
//
// public BaseSchedulerProvider getSchedulerProvider() {
// return schedulerProvider;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/utils/reactive/SchedulerProvider.java
// public class SchedulerProvider implements BaseSchedulerProvider {
//
// @Inject public SchedulerProvider() {
// }
//
// @NonNull @Override public Scheduler io() {
// return Schedulers.io();
// }
//
// @NonNull @Override public Scheduler ui() {
// return AndroidSchedulers.mainThread();
// }
//
// @NonNull @Override public Scheduler computation() {
// return Schedulers.computation();
// }
// }
|
import dagger.Module;
import dagger.Provides;
import io.reactivex.disposables.CompositeDisposable;
import mk.petrovski.weathergurumvp.data.remote.helper.CompositeDisposableHelper;
import mk.petrovski.weathergurumvp.utils.reactive.SchedulerProvider;
|
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
@Module public class RxModule {
@Provides CompositeDisposable getCompositeDisposable() {
return new CompositeDisposable();
}
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/CompositeDisposableHelper.java
// public class CompositeDisposableHelper {
//
// public CompositeDisposable disposables;
// public BaseSchedulerProvider schedulerProvider;
//
// @Inject public CompositeDisposableHelper(CompositeDisposable disposables,
// BaseSchedulerProvider schedulerProvider) {
// this.disposables = disposables;
// this.schedulerProvider = schedulerProvider;
// }
//
// private final ObservableTransformer schedulersTransformer = new ObservableTransformer() {
// @Override public ObservableSource apply(Observable upstream) {
// return upstream.subscribeOn(schedulerProvider.io()).observeOn(schedulerProvider.ui());
// }
// };
//
// public <T> ObservableTransformer<T, T> applySchedulers() {
// return (ObservableTransformer<T, T>) schedulersTransformer;
// }
//
// public void addDisposable(Disposable disposable) {
// disposables.add(disposable);
// }
//
// public void dispose() {
// if (!disposables.isDisposed()) {
// disposables.dispose();
// }
// }
//
// public BaseSchedulerProvider getSchedulerProvider() {
// return schedulerProvider;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/utils/reactive/SchedulerProvider.java
// public class SchedulerProvider implements BaseSchedulerProvider {
//
// @Inject public SchedulerProvider() {
// }
//
// @NonNull @Override public Scheduler io() {
// return Schedulers.io();
// }
//
// @NonNull @Override public Scheduler ui() {
// return AndroidSchedulers.mainThread();
// }
//
// @NonNull @Override public Scheduler computation() {
// return Schedulers.computation();
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/RxModule.java
import dagger.Module;
import dagger.Provides;
import io.reactivex.disposables.CompositeDisposable;
import mk.petrovski.weathergurumvp.data.remote.helper.CompositeDisposableHelper;
import mk.petrovski.weathergurumvp.utils.reactive.SchedulerProvider;
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
@Module public class RxModule {
@Provides CompositeDisposable getCompositeDisposable() {
return new CompositeDisposable();
}
|
@Provides SchedulerProvider getSchedulerProvider() {
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/injection/module/RxModule.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/CompositeDisposableHelper.java
// public class CompositeDisposableHelper {
//
// public CompositeDisposable disposables;
// public BaseSchedulerProvider schedulerProvider;
//
// @Inject public CompositeDisposableHelper(CompositeDisposable disposables,
// BaseSchedulerProvider schedulerProvider) {
// this.disposables = disposables;
// this.schedulerProvider = schedulerProvider;
// }
//
// private final ObservableTransformer schedulersTransformer = new ObservableTransformer() {
// @Override public ObservableSource apply(Observable upstream) {
// return upstream.subscribeOn(schedulerProvider.io()).observeOn(schedulerProvider.ui());
// }
// };
//
// public <T> ObservableTransformer<T, T> applySchedulers() {
// return (ObservableTransformer<T, T>) schedulersTransformer;
// }
//
// public void addDisposable(Disposable disposable) {
// disposables.add(disposable);
// }
//
// public void dispose() {
// if (!disposables.isDisposed()) {
// disposables.dispose();
// }
// }
//
// public BaseSchedulerProvider getSchedulerProvider() {
// return schedulerProvider;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/utils/reactive/SchedulerProvider.java
// public class SchedulerProvider implements BaseSchedulerProvider {
//
// @Inject public SchedulerProvider() {
// }
//
// @NonNull @Override public Scheduler io() {
// return Schedulers.io();
// }
//
// @NonNull @Override public Scheduler ui() {
// return AndroidSchedulers.mainThread();
// }
//
// @NonNull @Override public Scheduler computation() {
// return Schedulers.computation();
// }
// }
|
import dagger.Module;
import dagger.Provides;
import io.reactivex.disposables.CompositeDisposable;
import mk.petrovski.weathergurumvp.data.remote.helper.CompositeDisposableHelper;
import mk.petrovski.weathergurumvp.utils.reactive.SchedulerProvider;
|
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
@Module public class RxModule {
@Provides CompositeDisposable getCompositeDisposable() {
return new CompositeDisposable();
}
@Provides SchedulerProvider getSchedulerProvider() {
return new SchedulerProvider();
}
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/CompositeDisposableHelper.java
// public class CompositeDisposableHelper {
//
// public CompositeDisposable disposables;
// public BaseSchedulerProvider schedulerProvider;
//
// @Inject public CompositeDisposableHelper(CompositeDisposable disposables,
// BaseSchedulerProvider schedulerProvider) {
// this.disposables = disposables;
// this.schedulerProvider = schedulerProvider;
// }
//
// private final ObservableTransformer schedulersTransformer = new ObservableTransformer() {
// @Override public ObservableSource apply(Observable upstream) {
// return upstream.subscribeOn(schedulerProvider.io()).observeOn(schedulerProvider.ui());
// }
// };
//
// public <T> ObservableTransformer<T, T> applySchedulers() {
// return (ObservableTransformer<T, T>) schedulersTransformer;
// }
//
// public void addDisposable(Disposable disposable) {
// disposables.add(disposable);
// }
//
// public void dispose() {
// if (!disposables.isDisposed()) {
// disposables.dispose();
// }
// }
//
// public BaseSchedulerProvider getSchedulerProvider() {
// return schedulerProvider;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/utils/reactive/SchedulerProvider.java
// public class SchedulerProvider implements BaseSchedulerProvider {
//
// @Inject public SchedulerProvider() {
// }
//
// @NonNull @Override public Scheduler io() {
// return Schedulers.io();
// }
//
// @NonNull @Override public Scheduler ui() {
// return AndroidSchedulers.mainThread();
// }
//
// @NonNull @Override public Scheduler computation() {
// return Schedulers.computation();
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/RxModule.java
import dagger.Module;
import dagger.Provides;
import io.reactivex.disposables.CompositeDisposable;
import mk.petrovski.weathergurumvp.data.remote.helper.CompositeDisposableHelper;
import mk.petrovski.weathergurumvp.utils.reactive.SchedulerProvider;
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
@Module public class RxModule {
@Provides CompositeDisposable getCompositeDisposable() {
return new CompositeDisposable();
}
@Provides SchedulerProvider getSchedulerProvider() {
return new SchedulerProvider();
}
|
@Provides CompositeDisposableHelper getCompositeDisposableHelper(
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiHelper.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
|
import io.reactivex.Observable;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
|
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
public interface ApiHelper {
Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude);
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiHelper.java
import io.reactivex.Observable;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
public interface ApiHelper {
Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude);
|
Observable<SearchApiResponseModel> locationsApiRequest(String query);
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiHelper.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
|
import io.reactivex.Observable;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
|
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
public interface ApiHelper {
Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude);
Observable<SearchApiResponseModel> locationsApiRequest(String query);
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiHelper.java
import io.reactivex.Observable;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
public interface ApiHelper {
Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude);
Observable<SearchApiResponseModel> locationsApiRequest(String query);
|
ErrorHandlerHelper getErrorHandlerHelper();
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/injection/module/ApplicationModule.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/AppDataManager.java
// public class AppDataManager implements DataManager {
//
// private final Context context;
// private final DbHelper dbHelper;
// private final PreferencesHelper applicationPreferences;
// private final ApiHelper apiHelper;
//
// @Inject
// public AppDataManager(Context context, DbHelper dbHelper,
// PreferencesHelper applicationPreferences, ApiHelper apiHelper) {
// this.context = context;
// this.dbHelper = dbHelper;
// this.applicationPreferences = applicationPreferences;
// this.apiHelper = apiHelper;
// }
//
// @Override public void setLoggedIn() {
// applicationPreferences.setLoggedIn();
// }
//
// @Override public boolean isLoggedIn() {
// return applicationPreferences.isLoggedIn();
// }
//
// @Override public void setUserName(String userName) {
// applicationPreferences.setUserName(userName);
// }
//
// @Override public String getUserName() {
// return applicationPreferences.getUserName();
// }
//
// @Override public Observable<Long> addNewCity(LocationModel locationModel) {
// return dbHelper.addNewCity(locationModel);
// }
//
// @Override public Observable<Long> addDefaultCity() {
// return dbHelper.addDefaultCity();
// }
//
// @Override public Observable<List<CityDetailsModel>> getAllCities() {
// return dbHelper.getAllCities();
// }
//
// @Override public Observable<Boolean> deleteCity(CityDetailsModel city) {
// return dbHelper.deleteCity(city);
// }
//
// @Override public Observable<CityDetailsModel> getSelectedCity() {
// return dbHelper.getSelectedCity();
// }
//
// @Override public Observable<CityDetailsModel> getCityById(Long id) {
// return dbHelper.getCityById(id);
// }
//
// @Override public Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected) {
// return dbHelper.selectCity(city, isSelected);
// }
//
// @Override public Observable<Boolean> selectFirstCity() {
// return dbHelper.selectFirstCity();
// }
//
// @Override public CityDetailsModel getSelectedCityModel() {
// return dbHelper.getSelectedCityModel();
// }
//
// @Override public Long getCitiesCount() {
// return dbHelper.getCitiesCount();
// }
//
// @Override public Boolean isCityExist(String weatherUrl) {
// return dbHelper.isCityExist(weatherUrl);
// }
//
// @Override
// public Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude) {
// return apiHelper.weatherApiRequest(latitude, longitude);
// }
//
// @Override public Observable<SearchApiResponseModel> locationsApiRequest(String query) {
// return apiHelper.locationsApiRequest(query);
// }
//
// @Override public ErrorHandlerHelper getErrorHandlerHelper() {
// return apiHelper.getErrorHandlerHelper();
// }
//
// @Override public void setErrorHandler(ErrorHandlerHelper errorHandler) {
// apiHelper.setErrorHandler(errorHandler);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/db/DbHelper.java
// public interface DbHelper {
//
// Observable<Long> addNewCity(LocationModel locationModel);
//
// Observable<Long> addDefaultCity();
//
// Observable<List<CityDetailsModel>> getAllCities();
//
// Observable<Boolean> deleteCity(CityDetailsModel city);
//
// Observable<CityDetailsModel> getSelectedCity();
//
// Observable<CityDetailsModel> getCityById(Long id);
//
// Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected);
//
// Observable<Boolean> selectFirstCity();
//
// CityDetailsModel getSelectedCityModel();
//
// Long getCitiesCount();
//
// Boolean isCityExist(String weatherUrl);
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/PreferencesHelper.java
// public interface PreferencesHelper {
//
// void setLoggedIn();
//
// boolean isLoggedIn();
//
// void setUserName(String userName);
//
// String getUserName();
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiHelper.java
// public interface ApiHelper {
//
// Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude);
//
// Observable<SearchApiResponseModel> locationsApiRequest(String query);
//
// ErrorHandlerHelper getErrorHandlerHelper();
//
// void setErrorHandler(ErrorHandlerHelper errorHandler);
// }
|
import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import mk.petrovski.weathergurumvp.R;
import mk.petrovski.weathergurumvp.data.AppDataManager;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.data.local.db.DbHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.PreferencesHelper;
import mk.petrovski.weathergurumvp.data.remote.ApiHelper;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
|
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
@Module(includes = {
ContextModule.class, PreferencesModule.class, NetworkModule.class, DatabaseModule.class
}) public class ApplicationModule {
private final Application application;
public ApplicationModule(Application application) {
this.application = application;
}
@Provides Application getApplication() {
return application;
}
@Provides @WeatherGuruApplicationScope CalligraphyConfig getCalligraphyConfig() {
return new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Roboto-Regular.ttf")
.setFontAttrId(R.attr.fontPath)
.build();
}
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/AppDataManager.java
// public class AppDataManager implements DataManager {
//
// private final Context context;
// private final DbHelper dbHelper;
// private final PreferencesHelper applicationPreferences;
// private final ApiHelper apiHelper;
//
// @Inject
// public AppDataManager(Context context, DbHelper dbHelper,
// PreferencesHelper applicationPreferences, ApiHelper apiHelper) {
// this.context = context;
// this.dbHelper = dbHelper;
// this.applicationPreferences = applicationPreferences;
// this.apiHelper = apiHelper;
// }
//
// @Override public void setLoggedIn() {
// applicationPreferences.setLoggedIn();
// }
//
// @Override public boolean isLoggedIn() {
// return applicationPreferences.isLoggedIn();
// }
//
// @Override public void setUserName(String userName) {
// applicationPreferences.setUserName(userName);
// }
//
// @Override public String getUserName() {
// return applicationPreferences.getUserName();
// }
//
// @Override public Observable<Long> addNewCity(LocationModel locationModel) {
// return dbHelper.addNewCity(locationModel);
// }
//
// @Override public Observable<Long> addDefaultCity() {
// return dbHelper.addDefaultCity();
// }
//
// @Override public Observable<List<CityDetailsModel>> getAllCities() {
// return dbHelper.getAllCities();
// }
//
// @Override public Observable<Boolean> deleteCity(CityDetailsModel city) {
// return dbHelper.deleteCity(city);
// }
//
// @Override public Observable<CityDetailsModel> getSelectedCity() {
// return dbHelper.getSelectedCity();
// }
//
// @Override public Observable<CityDetailsModel> getCityById(Long id) {
// return dbHelper.getCityById(id);
// }
//
// @Override public Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected) {
// return dbHelper.selectCity(city, isSelected);
// }
//
// @Override public Observable<Boolean> selectFirstCity() {
// return dbHelper.selectFirstCity();
// }
//
// @Override public CityDetailsModel getSelectedCityModel() {
// return dbHelper.getSelectedCityModel();
// }
//
// @Override public Long getCitiesCount() {
// return dbHelper.getCitiesCount();
// }
//
// @Override public Boolean isCityExist(String weatherUrl) {
// return dbHelper.isCityExist(weatherUrl);
// }
//
// @Override
// public Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude) {
// return apiHelper.weatherApiRequest(latitude, longitude);
// }
//
// @Override public Observable<SearchApiResponseModel> locationsApiRequest(String query) {
// return apiHelper.locationsApiRequest(query);
// }
//
// @Override public ErrorHandlerHelper getErrorHandlerHelper() {
// return apiHelper.getErrorHandlerHelper();
// }
//
// @Override public void setErrorHandler(ErrorHandlerHelper errorHandler) {
// apiHelper.setErrorHandler(errorHandler);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/db/DbHelper.java
// public interface DbHelper {
//
// Observable<Long> addNewCity(LocationModel locationModel);
//
// Observable<Long> addDefaultCity();
//
// Observable<List<CityDetailsModel>> getAllCities();
//
// Observable<Boolean> deleteCity(CityDetailsModel city);
//
// Observable<CityDetailsModel> getSelectedCity();
//
// Observable<CityDetailsModel> getCityById(Long id);
//
// Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected);
//
// Observable<Boolean> selectFirstCity();
//
// CityDetailsModel getSelectedCityModel();
//
// Long getCitiesCount();
//
// Boolean isCityExist(String weatherUrl);
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/PreferencesHelper.java
// public interface PreferencesHelper {
//
// void setLoggedIn();
//
// boolean isLoggedIn();
//
// void setUserName(String userName);
//
// String getUserName();
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiHelper.java
// public interface ApiHelper {
//
// Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude);
//
// Observable<SearchApiResponseModel> locationsApiRequest(String query);
//
// ErrorHandlerHelper getErrorHandlerHelper();
//
// void setErrorHandler(ErrorHandlerHelper errorHandler);
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/ApplicationModule.java
import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import mk.petrovski.weathergurumvp.R;
import mk.petrovski.weathergurumvp.data.AppDataManager;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.data.local.db.DbHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.PreferencesHelper;
import mk.petrovski.weathergurumvp.data.remote.ApiHelper;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
@Module(includes = {
ContextModule.class, PreferencesModule.class, NetworkModule.class, DatabaseModule.class
}) public class ApplicationModule {
private final Application application;
public ApplicationModule(Application application) {
this.application = application;
}
@Provides Application getApplication() {
return application;
}
@Provides @WeatherGuruApplicationScope CalligraphyConfig getCalligraphyConfig() {
return new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Roboto-Regular.ttf")
.setFontAttrId(R.attr.fontPath)
.build();
}
|
@Provides @WeatherGuruApplicationScope AppDataManager getAppDataManager(
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/injection/module/ApplicationModule.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/AppDataManager.java
// public class AppDataManager implements DataManager {
//
// private final Context context;
// private final DbHelper dbHelper;
// private final PreferencesHelper applicationPreferences;
// private final ApiHelper apiHelper;
//
// @Inject
// public AppDataManager(Context context, DbHelper dbHelper,
// PreferencesHelper applicationPreferences, ApiHelper apiHelper) {
// this.context = context;
// this.dbHelper = dbHelper;
// this.applicationPreferences = applicationPreferences;
// this.apiHelper = apiHelper;
// }
//
// @Override public void setLoggedIn() {
// applicationPreferences.setLoggedIn();
// }
//
// @Override public boolean isLoggedIn() {
// return applicationPreferences.isLoggedIn();
// }
//
// @Override public void setUserName(String userName) {
// applicationPreferences.setUserName(userName);
// }
//
// @Override public String getUserName() {
// return applicationPreferences.getUserName();
// }
//
// @Override public Observable<Long> addNewCity(LocationModel locationModel) {
// return dbHelper.addNewCity(locationModel);
// }
//
// @Override public Observable<Long> addDefaultCity() {
// return dbHelper.addDefaultCity();
// }
//
// @Override public Observable<List<CityDetailsModel>> getAllCities() {
// return dbHelper.getAllCities();
// }
//
// @Override public Observable<Boolean> deleteCity(CityDetailsModel city) {
// return dbHelper.deleteCity(city);
// }
//
// @Override public Observable<CityDetailsModel> getSelectedCity() {
// return dbHelper.getSelectedCity();
// }
//
// @Override public Observable<CityDetailsModel> getCityById(Long id) {
// return dbHelper.getCityById(id);
// }
//
// @Override public Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected) {
// return dbHelper.selectCity(city, isSelected);
// }
//
// @Override public Observable<Boolean> selectFirstCity() {
// return dbHelper.selectFirstCity();
// }
//
// @Override public CityDetailsModel getSelectedCityModel() {
// return dbHelper.getSelectedCityModel();
// }
//
// @Override public Long getCitiesCount() {
// return dbHelper.getCitiesCount();
// }
//
// @Override public Boolean isCityExist(String weatherUrl) {
// return dbHelper.isCityExist(weatherUrl);
// }
//
// @Override
// public Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude) {
// return apiHelper.weatherApiRequest(latitude, longitude);
// }
//
// @Override public Observable<SearchApiResponseModel> locationsApiRequest(String query) {
// return apiHelper.locationsApiRequest(query);
// }
//
// @Override public ErrorHandlerHelper getErrorHandlerHelper() {
// return apiHelper.getErrorHandlerHelper();
// }
//
// @Override public void setErrorHandler(ErrorHandlerHelper errorHandler) {
// apiHelper.setErrorHandler(errorHandler);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/db/DbHelper.java
// public interface DbHelper {
//
// Observable<Long> addNewCity(LocationModel locationModel);
//
// Observable<Long> addDefaultCity();
//
// Observable<List<CityDetailsModel>> getAllCities();
//
// Observable<Boolean> deleteCity(CityDetailsModel city);
//
// Observable<CityDetailsModel> getSelectedCity();
//
// Observable<CityDetailsModel> getCityById(Long id);
//
// Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected);
//
// Observable<Boolean> selectFirstCity();
//
// CityDetailsModel getSelectedCityModel();
//
// Long getCitiesCount();
//
// Boolean isCityExist(String weatherUrl);
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/PreferencesHelper.java
// public interface PreferencesHelper {
//
// void setLoggedIn();
//
// boolean isLoggedIn();
//
// void setUserName(String userName);
//
// String getUserName();
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiHelper.java
// public interface ApiHelper {
//
// Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude);
//
// Observable<SearchApiResponseModel> locationsApiRequest(String query);
//
// ErrorHandlerHelper getErrorHandlerHelper();
//
// void setErrorHandler(ErrorHandlerHelper errorHandler);
// }
|
import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import mk.petrovski.weathergurumvp.R;
import mk.petrovski.weathergurumvp.data.AppDataManager;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.data.local.db.DbHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.PreferencesHelper;
import mk.petrovski.weathergurumvp.data.remote.ApiHelper;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
|
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
@Module(includes = {
ContextModule.class, PreferencesModule.class, NetworkModule.class, DatabaseModule.class
}) public class ApplicationModule {
private final Application application;
public ApplicationModule(Application application) {
this.application = application;
}
@Provides Application getApplication() {
return application;
}
@Provides @WeatherGuruApplicationScope CalligraphyConfig getCalligraphyConfig() {
return new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Roboto-Regular.ttf")
.setFontAttrId(R.attr.fontPath)
.build();
}
@Provides @WeatherGuruApplicationScope AppDataManager getAppDataManager(
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/AppDataManager.java
// public class AppDataManager implements DataManager {
//
// private final Context context;
// private final DbHelper dbHelper;
// private final PreferencesHelper applicationPreferences;
// private final ApiHelper apiHelper;
//
// @Inject
// public AppDataManager(Context context, DbHelper dbHelper,
// PreferencesHelper applicationPreferences, ApiHelper apiHelper) {
// this.context = context;
// this.dbHelper = dbHelper;
// this.applicationPreferences = applicationPreferences;
// this.apiHelper = apiHelper;
// }
//
// @Override public void setLoggedIn() {
// applicationPreferences.setLoggedIn();
// }
//
// @Override public boolean isLoggedIn() {
// return applicationPreferences.isLoggedIn();
// }
//
// @Override public void setUserName(String userName) {
// applicationPreferences.setUserName(userName);
// }
//
// @Override public String getUserName() {
// return applicationPreferences.getUserName();
// }
//
// @Override public Observable<Long> addNewCity(LocationModel locationModel) {
// return dbHelper.addNewCity(locationModel);
// }
//
// @Override public Observable<Long> addDefaultCity() {
// return dbHelper.addDefaultCity();
// }
//
// @Override public Observable<List<CityDetailsModel>> getAllCities() {
// return dbHelper.getAllCities();
// }
//
// @Override public Observable<Boolean> deleteCity(CityDetailsModel city) {
// return dbHelper.deleteCity(city);
// }
//
// @Override public Observable<CityDetailsModel> getSelectedCity() {
// return dbHelper.getSelectedCity();
// }
//
// @Override public Observable<CityDetailsModel> getCityById(Long id) {
// return dbHelper.getCityById(id);
// }
//
// @Override public Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected) {
// return dbHelper.selectCity(city, isSelected);
// }
//
// @Override public Observable<Boolean> selectFirstCity() {
// return dbHelper.selectFirstCity();
// }
//
// @Override public CityDetailsModel getSelectedCityModel() {
// return dbHelper.getSelectedCityModel();
// }
//
// @Override public Long getCitiesCount() {
// return dbHelper.getCitiesCount();
// }
//
// @Override public Boolean isCityExist(String weatherUrl) {
// return dbHelper.isCityExist(weatherUrl);
// }
//
// @Override
// public Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude) {
// return apiHelper.weatherApiRequest(latitude, longitude);
// }
//
// @Override public Observable<SearchApiResponseModel> locationsApiRequest(String query) {
// return apiHelper.locationsApiRequest(query);
// }
//
// @Override public ErrorHandlerHelper getErrorHandlerHelper() {
// return apiHelper.getErrorHandlerHelper();
// }
//
// @Override public void setErrorHandler(ErrorHandlerHelper errorHandler) {
// apiHelper.setErrorHandler(errorHandler);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/db/DbHelper.java
// public interface DbHelper {
//
// Observable<Long> addNewCity(LocationModel locationModel);
//
// Observable<Long> addDefaultCity();
//
// Observable<List<CityDetailsModel>> getAllCities();
//
// Observable<Boolean> deleteCity(CityDetailsModel city);
//
// Observable<CityDetailsModel> getSelectedCity();
//
// Observable<CityDetailsModel> getCityById(Long id);
//
// Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected);
//
// Observable<Boolean> selectFirstCity();
//
// CityDetailsModel getSelectedCityModel();
//
// Long getCitiesCount();
//
// Boolean isCityExist(String weatherUrl);
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/PreferencesHelper.java
// public interface PreferencesHelper {
//
// void setLoggedIn();
//
// boolean isLoggedIn();
//
// void setUserName(String userName);
//
// String getUserName();
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiHelper.java
// public interface ApiHelper {
//
// Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude);
//
// Observable<SearchApiResponseModel> locationsApiRequest(String query);
//
// ErrorHandlerHelper getErrorHandlerHelper();
//
// void setErrorHandler(ErrorHandlerHelper errorHandler);
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/ApplicationModule.java
import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import mk.petrovski.weathergurumvp.R;
import mk.petrovski.weathergurumvp.data.AppDataManager;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.data.local.db.DbHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.PreferencesHelper;
import mk.petrovski.weathergurumvp.data.remote.ApiHelper;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
@Module(includes = {
ContextModule.class, PreferencesModule.class, NetworkModule.class, DatabaseModule.class
}) public class ApplicationModule {
private final Application application;
public ApplicationModule(Application application) {
this.application = application;
}
@Provides Application getApplication() {
return application;
}
@Provides @WeatherGuruApplicationScope CalligraphyConfig getCalligraphyConfig() {
return new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Roboto-Regular.ttf")
.setFontAttrId(R.attr.fontPath)
.build();
}
@Provides @WeatherGuruApplicationScope AppDataManager getAppDataManager(
|
@ApplicationContext Context context, PreferencesHelper preferencesHelper, DbHelper dbHelper,
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/injection/module/ApplicationModule.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/AppDataManager.java
// public class AppDataManager implements DataManager {
//
// private final Context context;
// private final DbHelper dbHelper;
// private final PreferencesHelper applicationPreferences;
// private final ApiHelper apiHelper;
//
// @Inject
// public AppDataManager(Context context, DbHelper dbHelper,
// PreferencesHelper applicationPreferences, ApiHelper apiHelper) {
// this.context = context;
// this.dbHelper = dbHelper;
// this.applicationPreferences = applicationPreferences;
// this.apiHelper = apiHelper;
// }
//
// @Override public void setLoggedIn() {
// applicationPreferences.setLoggedIn();
// }
//
// @Override public boolean isLoggedIn() {
// return applicationPreferences.isLoggedIn();
// }
//
// @Override public void setUserName(String userName) {
// applicationPreferences.setUserName(userName);
// }
//
// @Override public String getUserName() {
// return applicationPreferences.getUserName();
// }
//
// @Override public Observable<Long> addNewCity(LocationModel locationModel) {
// return dbHelper.addNewCity(locationModel);
// }
//
// @Override public Observable<Long> addDefaultCity() {
// return dbHelper.addDefaultCity();
// }
//
// @Override public Observable<List<CityDetailsModel>> getAllCities() {
// return dbHelper.getAllCities();
// }
//
// @Override public Observable<Boolean> deleteCity(CityDetailsModel city) {
// return dbHelper.deleteCity(city);
// }
//
// @Override public Observable<CityDetailsModel> getSelectedCity() {
// return dbHelper.getSelectedCity();
// }
//
// @Override public Observable<CityDetailsModel> getCityById(Long id) {
// return dbHelper.getCityById(id);
// }
//
// @Override public Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected) {
// return dbHelper.selectCity(city, isSelected);
// }
//
// @Override public Observable<Boolean> selectFirstCity() {
// return dbHelper.selectFirstCity();
// }
//
// @Override public CityDetailsModel getSelectedCityModel() {
// return dbHelper.getSelectedCityModel();
// }
//
// @Override public Long getCitiesCount() {
// return dbHelper.getCitiesCount();
// }
//
// @Override public Boolean isCityExist(String weatherUrl) {
// return dbHelper.isCityExist(weatherUrl);
// }
//
// @Override
// public Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude) {
// return apiHelper.weatherApiRequest(latitude, longitude);
// }
//
// @Override public Observable<SearchApiResponseModel> locationsApiRequest(String query) {
// return apiHelper.locationsApiRequest(query);
// }
//
// @Override public ErrorHandlerHelper getErrorHandlerHelper() {
// return apiHelper.getErrorHandlerHelper();
// }
//
// @Override public void setErrorHandler(ErrorHandlerHelper errorHandler) {
// apiHelper.setErrorHandler(errorHandler);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/db/DbHelper.java
// public interface DbHelper {
//
// Observable<Long> addNewCity(LocationModel locationModel);
//
// Observable<Long> addDefaultCity();
//
// Observable<List<CityDetailsModel>> getAllCities();
//
// Observable<Boolean> deleteCity(CityDetailsModel city);
//
// Observable<CityDetailsModel> getSelectedCity();
//
// Observable<CityDetailsModel> getCityById(Long id);
//
// Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected);
//
// Observable<Boolean> selectFirstCity();
//
// CityDetailsModel getSelectedCityModel();
//
// Long getCitiesCount();
//
// Boolean isCityExist(String weatherUrl);
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/PreferencesHelper.java
// public interface PreferencesHelper {
//
// void setLoggedIn();
//
// boolean isLoggedIn();
//
// void setUserName(String userName);
//
// String getUserName();
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiHelper.java
// public interface ApiHelper {
//
// Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude);
//
// Observable<SearchApiResponseModel> locationsApiRequest(String query);
//
// ErrorHandlerHelper getErrorHandlerHelper();
//
// void setErrorHandler(ErrorHandlerHelper errorHandler);
// }
|
import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import mk.petrovski.weathergurumvp.R;
import mk.petrovski.weathergurumvp.data.AppDataManager;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.data.local.db.DbHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.PreferencesHelper;
import mk.petrovski.weathergurumvp.data.remote.ApiHelper;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
|
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
@Module(includes = {
ContextModule.class, PreferencesModule.class, NetworkModule.class, DatabaseModule.class
}) public class ApplicationModule {
private final Application application;
public ApplicationModule(Application application) {
this.application = application;
}
@Provides Application getApplication() {
return application;
}
@Provides @WeatherGuruApplicationScope CalligraphyConfig getCalligraphyConfig() {
return new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Roboto-Regular.ttf")
.setFontAttrId(R.attr.fontPath)
.build();
}
@Provides @WeatherGuruApplicationScope AppDataManager getAppDataManager(
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/AppDataManager.java
// public class AppDataManager implements DataManager {
//
// private final Context context;
// private final DbHelper dbHelper;
// private final PreferencesHelper applicationPreferences;
// private final ApiHelper apiHelper;
//
// @Inject
// public AppDataManager(Context context, DbHelper dbHelper,
// PreferencesHelper applicationPreferences, ApiHelper apiHelper) {
// this.context = context;
// this.dbHelper = dbHelper;
// this.applicationPreferences = applicationPreferences;
// this.apiHelper = apiHelper;
// }
//
// @Override public void setLoggedIn() {
// applicationPreferences.setLoggedIn();
// }
//
// @Override public boolean isLoggedIn() {
// return applicationPreferences.isLoggedIn();
// }
//
// @Override public void setUserName(String userName) {
// applicationPreferences.setUserName(userName);
// }
//
// @Override public String getUserName() {
// return applicationPreferences.getUserName();
// }
//
// @Override public Observable<Long> addNewCity(LocationModel locationModel) {
// return dbHelper.addNewCity(locationModel);
// }
//
// @Override public Observable<Long> addDefaultCity() {
// return dbHelper.addDefaultCity();
// }
//
// @Override public Observable<List<CityDetailsModel>> getAllCities() {
// return dbHelper.getAllCities();
// }
//
// @Override public Observable<Boolean> deleteCity(CityDetailsModel city) {
// return dbHelper.deleteCity(city);
// }
//
// @Override public Observable<CityDetailsModel> getSelectedCity() {
// return dbHelper.getSelectedCity();
// }
//
// @Override public Observable<CityDetailsModel> getCityById(Long id) {
// return dbHelper.getCityById(id);
// }
//
// @Override public Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected) {
// return dbHelper.selectCity(city, isSelected);
// }
//
// @Override public Observable<Boolean> selectFirstCity() {
// return dbHelper.selectFirstCity();
// }
//
// @Override public CityDetailsModel getSelectedCityModel() {
// return dbHelper.getSelectedCityModel();
// }
//
// @Override public Long getCitiesCount() {
// return dbHelper.getCitiesCount();
// }
//
// @Override public Boolean isCityExist(String weatherUrl) {
// return dbHelper.isCityExist(weatherUrl);
// }
//
// @Override
// public Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude) {
// return apiHelper.weatherApiRequest(latitude, longitude);
// }
//
// @Override public Observable<SearchApiResponseModel> locationsApiRequest(String query) {
// return apiHelper.locationsApiRequest(query);
// }
//
// @Override public ErrorHandlerHelper getErrorHandlerHelper() {
// return apiHelper.getErrorHandlerHelper();
// }
//
// @Override public void setErrorHandler(ErrorHandlerHelper errorHandler) {
// apiHelper.setErrorHandler(errorHandler);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/DataManager.java
// public interface DataManager extends PreferencesHelper, DbHelper, ApiHelper {
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/db/DbHelper.java
// public interface DbHelper {
//
// Observable<Long> addNewCity(LocationModel locationModel);
//
// Observable<Long> addDefaultCity();
//
// Observable<List<CityDetailsModel>> getAllCities();
//
// Observable<Boolean> deleteCity(CityDetailsModel city);
//
// Observable<CityDetailsModel> getSelectedCity();
//
// Observable<CityDetailsModel> getCityById(Long id);
//
// Observable<Boolean> selectCity(CityDetailsModel city, boolean isSelected);
//
// Observable<Boolean> selectFirstCity();
//
// CityDetailsModel getSelectedCityModel();
//
// Long getCitiesCount();
//
// Boolean isCityExist(String weatherUrl);
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/PreferencesHelper.java
// public interface PreferencesHelper {
//
// void setLoggedIn();
//
// boolean isLoggedIn();
//
// void setUserName(String userName);
//
// String getUserName();
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/ApiHelper.java
// public interface ApiHelper {
//
// Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude);
//
// Observable<SearchApiResponseModel> locationsApiRequest(String query);
//
// ErrorHandlerHelper getErrorHandlerHelper();
//
// void setErrorHandler(ErrorHandlerHelper errorHandler);
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/ApplicationModule.java
import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import mk.petrovski.weathergurumvp.R;
import mk.petrovski.weathergurumvp.data.AppDataManager;
import mk.petrovski.weathergurumvp.data.DataManager;
import mk.petrovski.weathergurumvp.data.local.db.DbHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.PreferencesHelper;
import mk.petrovski.weathergurumvp.data.remote.ApiHelper;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 2/13/2017.
*/
@Module(includes = {
ContextModule.class, PreferencesModule.class, NetworkModule.class, DatabaseModule.class
}) public class ApplicationModule {
private final Application application;
public ApplicationModule(Application application) {
this.application = application;
}
@Provides Application getApplication() {
return application;
}
@Provides @WeatherGuruApplicationScope CalligraphyConfig getCalligraphyConfig() {
return new CalligraphyConfig.Builder().setDefaultFontPath("fonts/Roboto-Regular.ttf")
.setFontAttrId(R.attr.fontPath)
.build();
}
@Provides @WeatherGuruApplicationScope AppDataManager getAppDataManager(
|
@ApplicationContext Context context, PreferencesHelper preferencesHelper, DbHelper dbHelper,
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/local/db/AppDbHelper.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/LocationModel.java
// public class LocationModel {
// private List<ValueModel> areaName;
// private List<ValueModel> country;
// private String latitude;
// private String longitude;
// private String population;
// private List<ValueModel> region;
// private List<ValueModel> weatherUrl;
// private int id;
// private boolean isSelected;
//
// public LocationModel() {
// }
//
// public LocationModel(String areaName, String country, String latitude, String longitude,
// String population, String region, String weatherUrl, boolean isSelected) {
// this.areaName = getValueModelFromString(areaName);
// this.country = getValueModelFromString(country);
// this.latitude = latitude;
// this.longitude = longitude;
// this.population = population;
// this.region = getValueModelFromString(region);
// this.weatherUrl = getValueModelFromString(weatherUrl);
// this.isSelected = isSelected;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public boolean isSelected() {
// return isSelected;
// }
//
// public void setIsSelected(boolean isSelected) {
// this.isSelected = isSelected;
// }
//
// public String getAreaName() {
// return areaName.get(0).getValue();
// }
//
// public void setAreaName(String areaName) {
// this.areaName = getValueModelFromString(areaName);
// }
//
// public String getCountry() {
// return country.get(0).getValue();
// }
//
// public void setCountry(String country) {
// this.country = getValueModelFromString(country);
// }
//
// public String getLatitude() {
// return latitude;
// }
//
// public void setLatitude(String latitude) {
// this.latitude = latitude;
// }
//
// public String getLongitude() {
// return longitude;
// }
//
// public void setLongitude(String longitude) {
// this.longitude = longitude;
// }
//
// public String getPopulation() {
// return population;
// }
//
// public void setPopulation(String population) {
// this.population = population;
// }
//
// public String getRegion() {
// return region.get(0).getValue();
// }
//
// public void setRegion(String region) {
// this.region = getValueModelFromString(region);
// }
//
// public String getWeatherUrl() {
// return weatherUrl.get(0).getValue();
// }
//
// public void setWeatherUrl(String weatherUrl) {
// this.weatherUrl = getValueModelFromString(weatherUrl);
// }
//
// private List<ValueModel> getValueModelFromString(String value) {
// List<ValueModel> valueList = new ArrayList<>();
// valueList.add(new ValueModel(value));
// return valueList;
// }
// }
|
import io.reactivex.Observable;
import java.util.List;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.LocationModel;
|
package mk.petrovski.weathergurumvp.data.local.db;
/**
* Created by Nikola Petrovski on 2/20/2017.
*/
public class AppDbHelper implements DbHelper {
DaoSession daoSession;
@Inject public AppDbHelper(DaoSession daoSession) {
this.daoSession = daoSession;
}
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/LocationModel.java
// public class LocationModel {
// private List<ValueModel> areaName;
// private List<ValueModel> country;
// private String latitude;
// private String longitude;
// private String population;
// private List<ValueModel> region;
// private List<ValueModel> weatherUrl;
// private int id;
// private boolean isSelected;
//
// public LocationModel() {
// }
//
// public LocationModel(String areaName, String country, String latitude, String longitude,
// String population, String region, String weatherUrl, boolean isSelected) {
// this.areaName = getValueModelFromString(areaName);
// this.country = getValueModelFromString(country);
// this.latitude = latitude;
// this.longitude = longitude;
// this.population = population;
// this.region = getValueModelFromString(region);
// this.weatherUrl = getValueModelFromString(weatherUrl);
// this.isSelected = isSelected;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public boolean isSelected() {
// return isSelected;
// }
//
// public void setIsSelected(boolean isSelected) {
// this.isSelected = isSelected;
// }
//
// public String getAreaName() {
// return areaName.get(0).getValue();
// }
//
// public void setAreaName(String areaName) {
// this.areaName = getValueModelFromString(areaName);
// }
//
// public String getCountry() {
// return country.get(0).getValue();
// }
//
// public void setCountry(String country) {
// this.country = getValueModelFromString(country);
// }
//
// public String getLatitude() {
// return latitude;
// }
//
// public void setLatitude(String latitude) {
// this.latitude = latitude;
// }
//
// public String getLongitude() {
// return longitude;
// }
//
// public void setLongitude(String longitude) {
// this.longitude = longitude;
// }
//
// public String getPopulation() {
// return population;
// }
//
// public void setPopulation(String population) {
// this.population = population;
// }
//
// public String getRegion() {
// return region.get(0).getValue();
// }
//
// public void setRegion(String region) {
// this.region = getValueModelFromString(region);
// }
//
// public String getWeatherUrl() {
// return weatherUrl.get(0).getValue();
// }
//
// public void setWeatherUrl(String weatherUrl) {
// this.weatherUrl = getValueModelFromString(weatherUrl);
// }
//
// private List<ValueModel> getValueModelFromString(String value) {
// List<ValueModel> valueList = new ArrayList<>();
// valueList.add(new ValueModel(value));
// return valueList;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/db/AppDbHelper.java
import io.reactivex.Observable;
import java.util.List;
import java.util.concurrent.Callable;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.LocationModel;
package mk.petrovski.weathergurumvp.data.local.db;
/**
* Created by Nikola Petrovski on 2/20/2017.
*/
public class AppDbHelper implements DbHelper {
DaoSession daoSession;
@Inject public AppDbHelper(DaoSession daoSession) {
this.daoSession = daoSession;
}
|
@Override public Observable<Long> addNewCity(final LocationModel location) {
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/error_models/DataResponseModel.java
// public class DataResponseModel {
// private ErrorModel data;
//
// public ErrorModel getData() {
// return data;
// }
//
// public void setData(ErrorModel data) {
// this.data = data;
// }
// }
|
import android.accounts.NetworkErrorException;
import android.content.Context;
import android.support.annotation.NonNull;
import com.google.gson.JsonSyntaxException;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import java.io.IOException;
import java.lang.annotation.Annotation;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.R;
import mk.petrovski.weathergurumvp.data.remote.model.error_models.DataResponseModel;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
|
package mk.petrovski.weathergurumvp.data.remote.helper.error;
/**
* Created by Nikola Petrovski on 2/22/2017.
*/
public class ErrorHandlerHelper {
Context context;
Retrofit retrofit;
@Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
this.context = context;
this.retrofit = retrofit;
}
public String getProperErrorMessage(Throwable throwable) {
Throwable properException = getProperException(throwable);
if (properException instanceof ServerException) {
return context.getString(R.string.error_server);
} else if (properException instanceof ServerNotAvailableException) {
return context.getString(R.string.error_server_not_available);
} else if (properException instanceof InternetConnectionException) {
return context.getString(R.string.error_connection);
} else if (properException instanceof NotFoundException) {
return context.getString(R.string.error_not_found);
} else if (properException instanceof UnauthorizedException) {
return context.getString(R.string.error_unauthorized);
} else if (properException instanceof ParsedResponseException) {
return throwable.getMessage();
} else {
return String.format(context.getString(R.string.error_default), throwable.getMessage());
}
}
public Throwable getProperException(Throwable throwable) {
if (throwable instanceof HttpException) {
HttpException httpException = (HttpException) throwable;
Response response = httpException.response();
// try to parse the error
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/error_models/DataResponseModel.java
// public class DataResponseModel {
// private ErrorModel data;
//
// public ErrorModel getData() {
// return data;
// }
//
// public void setData(ErrorModel data) {
// this.data = data;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
import android.accounts.NetworkErrorException;
import android.content.Context;
import android.support.annotation.NonNull;
import com.google.gson.JsonSyntaxException;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import java.io.IOException;
import java.lang.annotation.Annotation;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.R;
import mk.petrovski.weathergurumvp.data.remote.model.error_models.DataResponseModel;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Response;
import retrofit2.Retrofit;
package mk.petrovski.weathergurumvp.data.remote.helper.error;
/**
* Created by Nikola Petrovski on 2/22/2017.
*/
public class ErrorHandlerHelper {
Context context;
Retrofit retrofit;
@Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
this.context = context;
this.retrofit = retrofit;
}
public String getProperErrorMessage(Throwable throwable) {
Throwable properException = getProperException(throwable);
if (properException instanceof ServerException) {
return context.getString(R.string.error_server);
} else if (properException instanceof ServerNotAvailableException) {
return context.getString(R.string.error_server_not_available);
} else if (properException instanceof InternetConnectionException) {
return context.getString(R.string.error_connection);
} else if (properException instanceof NotFoundException) {
return context.getString(R.string.error_not_found);
} else if (properException instanceof UnauthorizedException) {
return context.getString(R.string.error_unauthorized);
} else if (properException instanceof ParsedResponseException) {
return throwable.getMessage();
} else {
return String.format(context.getString(R.string.error_default), throwable.getMessage());
}
}
public Throwable getProperException(Throwable throwable) {
if (throwable instanceof HttpException) {
HttpException httpException = (HttpException) throwable;
Response response = httpException.response();
// try to parse the error
|
Converter<ResponseBody, DataResponseModel> converter =
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/AppApiHelper.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
|
import io.reactivex.Observable;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.BuildConfig;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
|
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
public class AppApiHelper implements ApiHelper {
ApiInterface apiInterface;
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/AppApiHelper.java
import io.reactivex.Observable;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.BuildConfig;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
public class AppApiHelper implements ApiHelper {
ApiInterface apiInterface;
|
ErrorHandlerHelper errorHandlerHelper;
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/AppApiHelper.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
|
import io.reactivex.Observable;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.BuildConfig;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
|
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
public class AppApiHelper implements ApiHelper {
ApiInterface apiInterface;
ErrorHandlerHelper errorHandlerHelper;
final String format = "json";
final String key = BuildConfig.WWO_API_KEY;
@Inject public AppApiHelper(ApiInterface apiInterface, ErrorHandlerHelper errorHandlerHelper) {
this.apiInterface = apiInterface;
this.errorHandlerHelper = errorHandlerHelper;
}
@Override public ErrorHandlerHelper getErrorHandlerHelper() {
return errorHandlerHelper;
}
@Override public void setErrorHandler(ErrorHandlerHelper errorHandler) {
this.errorHandlerHelper = errorHandler;
}
@Override
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/AppApiHelper.java
import io.reactivex.Observable;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.BuildConfig;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
public class AppApiHelper implements ApiHelper {
ApiInterface apiInterface;
ErrorHandlerHelper errorHandlerHelper;
final String format = "json";
final String key = BuildConfig.WWO_API_KEY;
@Inject public AppApiHelper(ApiInterface apiInterface, ErrorHandlerHelper errorHandlerHelper) {
this.apiInterface = apiInterface;
this.errorHandlerHelper = errorHandlerHelper;
}
@Override public ErrorHandlerHelper getErrorHandlerHelper() {
return errorHandlerHelper;
}
@Override public void setErrorHandler(ErrorHandlerHelper errorHandler) {
this.errorHandlerHelper = errorHandler;
}
@Override
|
public Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude) {
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/AppApiHelper.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
|
import io.reactivex.Observable;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.BuildConfig;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
|
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
public class AppApiHelper implements ApiHelper {
ApiInterface apiInterface;
ErrorHandlerHelper errorHandlerHelper;
final String format = "json";
final String key = BuildConfig.WWO_API_KEY;
@Inject public AppApiHelper(ApiInterface apiInterface, ErrorHandlerHelper errorHandlerHelper) {
this.apiInterface = apiInterface;
this.errorHandlerHelper = errorHandlerHelper;
}
@Override public ErrorHandlerHelper getErrorHandlerHelper() {
return errorHandlerHelper;
}
@Override public void setErrorHandler(ErrorHandlerHelper errorHandler) {
this.errorHandlerHelper = errorHandler;
}
@Override
public Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude) {
String days = "5";
String tp = "24";
String cc = "no";
String location = String.format("%s,%s", latitude, longitude);
return apiInterface.checkWeather(location, key, format, days, tp, cc);
}
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/error/ErrorHandlerHelper.java
// public class ErrorHandlerHelper {
//
// Context context;
// Retrofit retrofit;
//
// @Inject public ErrorHandlerHelper(Context context, Retrofit retrofit) {
// this.context = context;
// this.retrofit = retrofit;
// }
//
// public String getProperErrorMessage(Throwable throwable) {
// Throwable properException = getProperException(throwable);
//
// if (properException instanceof ServerException) {
// return context.getString(R.string.error_server);
// } else if (properException instanceof ServerNotAvailableException) {
// return context.getString(R.string.error_server_not_available);
// } else if (properException instanceof InternetConnectionException) {
// return context.getString(R.string.error_connection);
// } else if (properException instanceof NotFoundException) {
// return context.getString(R.string.error_not_found);
// } else if (properException instanceof UnauthorizedException) {
// return context.getString(R.string.error_unauthorized);
// } else if (properException instanceof ParsedResponseException) {
// return throwable.getMessage();
// } else {
// return String.format(context.getString(R.string.error_default), throwable.getMessage());
// }
// }
//
// public Throwable getProperException(Throwable throwable) {
// if (throwable instanceof HttpException) {
// HttpException httpException = (HttpException) throwable;
// Response response = httpException.response();
//
// // try to parse the error
// Converter<ResponseBody, DataResponseModel> converter =
// retrofit.responseBodyConverter(DataResponseModel.class, new Annotation[0]);
// DataResponseModel error = null;
// try {
// error = converter.convert(response.errorBody());
// } catch (IOException | JsonSyntaxException e) {
// e.printStackTrace();
// }
//
// if (error == null || error.getData() == null || error.getData().getError() == null) {
// return getThrowable(response.message(), response.code(), throwable);
// } else {
// return new ParsedResponseException(error.getData().getError().get(0).getMsg());
// }
// } else if (throwable instanceof IOException) {
// return new InternetConnectionException();
// } else if (throwable instanceof NetworkErrorException) {
// return new InternetConnectionException();
// }
// return throwable;
// }
//
// @NonNull private Throwable getThrowable(String message, int code, Throwable throwable) {
// Throwable exception;
// switch (code) {
// case 404:
// exception = new NotFoundException();
// break;
// case 401:
// exception = new UncheckedException(message);
// break;
// case 500:
// exception = new ServerNotAvailableException();
// break;
// case 501:
// case 502:
// case 503:
// case 504:
// exception = new ServerException(throwable);
// break;
// default:
// exception = new UncheckedException(message);
// break;
// }
// return exception;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/location_models/SearchApiResponseModel.java
// public class SearchApiResponseModel extends DataResponseModel {
// private ResultModel search_api;
//
// public ResultModel getSearch_api() {
// return search_api;
// }
//
// public void setSearch_api(ResultModel search_api) {
// this.search_api = search_api;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/model/weather_models/WeatherResponseModel.java
// public class WeatherResponseModel {
// private DataModel data;
//
// public DataModel getData() {
// return data;
// }
//
// public void setData(DataModel data) {
// this.data = data;
// }
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/AppApiHelper.java
import io.reactivex.Observable;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.BuildConfig;
import mk.petrovski.weathergurumvp.data.remote.helper.error.ErrorHandlerHelper;
import mk.petrovski.weathergurumvp.data.remote.model.location_models.SearchApiResponseModel;
import mk.petrovski.weathergurumvp.data.remote.model.weather_models.WeatherResponseModel;
package mk.petrovski.weathergurumvp.data.remote;
/**
* Created by Nikola Petrovski on 2/23/2017.
*/
public class AppApiHelper implements ApiHelper {
ApiInterface apiInterface;
ErrorHandlerHelper errorHandlerHelper;
final String format = "json";
final String key = BuildConfig.WWO_API_KEY;
@Inject public AppApiHelper(ApiInterface apiInterface, ErrorHandlerHelper errorHandlerHelper) {
this.apiInterface = apiInterface;
this.errorHandlerHelper = errorHandlerHelper;
}
@Override public ErrorHandlerHelper getErrorHandlerHelper() {
return errorHandlerHelper;
}
@Override public void setErrorHandler(ErrorHandlerHelper errorHandler) {
this.errorHandlerHelper = errorHandler;
}
@Override
public Observable<WeatherResponseModel> weatherApiRequest(String latitude, String longitude) {
String days = "5";
String tp = "24";
String cc = "no";
String location = String.format("%s,%s", latitude, longitude);
return apiInterface.checkWeather(location, key, format, days, tp, cc);
}
|
@Override public Observable<SearchApiResponseModel> locationsApiRequest(String query) {
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/CompositeDisposableHelper.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/utils/reactive/BaseSchedulerProvider.java
// public interface BaseSchedulerProvider {
//
// @NonNull Scheduler io();
//
// @NonNull Scheduler ui();
//
// @NonNull Scheduler computation();
// }
|
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.schedulers.TestScheduler;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.utils.reactive.BaseSchedulerProvider;
|
package mk.petrovski.weathergurumvp.data.remote.helper;
/**
* Created by Nikola Petrovski on 2/22/2017.
*/
public class CompositeDisposableHelper {
public CompositeDisposable disposables;
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/utils/reactive/BaseSchedulerProvider.java
// public interface BaseSchedulerProvider {
//
// @NonNull Scheduler io();
//
// @NonNull Scheduler ui();
//
// @NonNull Scheduler computation();
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/remote/helper/CompositeDisposableHelper.java
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.schedulers.TestScheduler;
import javax.inject.Inject;
import mk.petrovski.weathergurumvp.utils.reactive.BaseSchedulerProvider;
package mk.petrovski.weathergurumvp.data.remote.helper;
/**
* Created by Nikola Petrovski on 2/22/2017.
*/
public class CompositeDisposableHelper {
public CompositeDisposable disposables;
|
public BaseSchedulerProvider schedulerProvider;
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/utils/AppUtils.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/base/BaseActivity.java
// public abstract class BaseActivity extends AppCompatActivity implements BaseMvpView {
//
// private ActivityFragmentComponent activityFragmentComponent;
// private Unbinder unbinder;
// private ProgressDialog progressDialog;
//
// @Override protected void attachBaseContext(Context newBase) {
// super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
// }
//
// @Override public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// activityFragmentComponent = DaggerActivityFragmentComponent.builder()
// .activityFragmentModule(new ActivityFragmentModule(this))
// .applicationComponent(WeatherGuruApplication.getApplicationComponent())
// .build();
// }
//
// public void showBackButton(boolean shouldShow) {
// if (getSupportActionBar() != null) {
// Drawable backArrow = ContextCompat.getDrawable(this, R.drawable.abc_ic_ab_back_material);
// backArrow.setColorFilter(ContextCompat.getColor(this, android.R.color.white),
// PorterDuff.Mode.SRC_ATOP);
// getSupportActionBar().setHomeAsUpIndicator(backArrow);
// getSupportActionBar().setHomeButtonEnabled(shouldShow);
// getSupportActionBar().setDisplayHomeAsUpEnabled(shouldShow);
// }
// }
//
// public ActivityFragmentComponent getActivityFragmentComponent() {
// return activityFragmentComponent;
// }
//
// @Override public void showLoading() {
// hideLoading();
// progressDialog = AppUtils.showLoadingDialog(this);
// }
//
// @Override public void hideLoading() {
// if (progressDialog != null && progressDialog.isShowing()) {
// progressDialog.cancel();
// }
// }
//
// @Override public void onError(@StringRes int resId) {
// Toast.makeText(this, getString(resId), Toast.LENGTH_LONG).show();
// }
//
// @Override public void onError(String message) {
// Toast.makeText(this, message, Toast.LENGTH_LONG).show();
// }
//
// @Override public boolean isNetworkConnected() {
// return AppUtils.isNetworkAvailable(getApplicationContext());
// }
//
// @Override public void hideKeyboard() {
// AppUtils.hideKeyboard(this);
// }
//
// public void setUnBinder(Unbinder unBinder) {
// unbinder = unBinder;
// }
//
// @Override protected void onDestroy() {
// if (unbinder != null) {
// unbinder.unbind();
// }
// super.onDestroy();
// }
//
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case android.R.id.home:
// onBackPressed();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// protected abstract void init();
// }
|
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.inputmethod.InputMethodManager;
import mk.petrovski.weathergurumvp.R;
import mk.petrovski.weathergurumvp.ui.base.BaseActivity;
|
package mk.petrovski.weathergurumvp.utils;
/**
* Created by Nikola Petrovski on 2/14/2017.
*/
public class AppUtils {
/**
* Check for internet connection
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
/**
* Show loading progress
*/
public static ProgressDialog showLoadingDialog(Context context) {
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.show();
if (progressDialog.getWindow() != null) {
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
progressDialog.setContentView(R.layout.dialog_progress);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(true);
progressDialog.setCanceledOnTouchOutside(false);
return progressDialog;
}
/**
* Hide keyboard
*/
public static void hideKeyboard(Context context) {
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (((Activity) context).getCurrentFocus() != null) {
try {
inputManager.hideSoftInputFromWindow(
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/base/BaseActivity.java
// public abstract class BaseActivity extends AppCompatActivity implements BaseMvpView {
//
// private ActivityFragmentComponent activityFragmentComponent;
// private Unbinder unbinder;
// private ProgressDialog progressDialog;
//
// @Override protected void attachBaseContext(Context newBase) {
// super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
// }
//
// @Override public void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// activityFragmentComponent = DaggerActivityFragmentComponent.builder()
// .activityFragmentModule(new ActivityFragmentModule(this))
// .applicationComponent(WeatherGuruApplication.getApplicationComponent())
// .build();
// }
//
// public void showBackButton(boolean shouldShow) {
// if (getSupportActionBar() != null) {
// Drawable backArrow = ContextCompat.getDrawable(this, R.drawable.abc_ic_ab_back_material);
// backArrow.setColorFilter(ContextCompat.getColor(this, android.R.color.white),
// PorterDuff.Mode.SRC_ATOP);
// getSupportActionBar().setHomeAsUpIndicator(backArrow);
// getSupportActionBar().setHomeButtonEnabled(shouldShow);
// getSupportActionBar().setDisplayHomeAsUpEnabled(shouldShow);
// }
// }
//
// public ActivityFragmentComponent getActivityFragmentComponent() {
// return activityFragmentComponent;
// }
//
// @Override public void showLoading() {
// hideLoading();
// progressDialog = AppUtils.showLoadingDialog(this);
// }
//
// @Override public void hideLoading() {
// if (progressDialog != null && progressDialog.isShowing()) {
// progressDialog.cancel();
// }
// }
//
// @Override public void onError(@StringRes int resId) {
// Toast.makeText(this, getString(resId), Toast.LENGTH_LONG).show();
// }
//
// @Override public void onError(String message) {
// Toast.makeText(this, message, Toast.LENGTH_LONG).show();
// }
//
// @Override public boolean isNetworkConnected() {
// return AppUtils.isNetworkAvailable(getApplicationContext());
// }
//
// @Override public void hideKeyboard() {
// AppUtils.hideKeyboard(this);
// }
//
// public void setUnBinder(Unbinder unBinder) {
// unbinder = unBinder;
// }
//
// @Override protected void onDestroy() {
// if (unbinder != null) {
// unbinder.unbind();
// }
// super.onDestroy();
// }
//
// @Override public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case android.R.id.home:
// onBackPressed();
// return true;
// }
// return super.onOptionsItemSelected(item);
// }
//
// protected abstract void init();
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/utils/AppUtils.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.inputmethod.InputMethodManager;
import mk.petrovski.weathergurumvp.R;
import mk.petrovski.weathergurumvp.ui.base.BaseActivity;
package mk.petrovski.weathergurumvp.utils;
/**
* Created by Nikola Petrovski on 2/14/2017.
*/
public class AppUtils {
/**
* Check for internet connection
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
/**
* Show loading progress
*/
public static ProgressDialog showLoadingDialog(Context context) {
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.show();
if (progressDialog.getWindow() != null) {
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
progressDialog.setContentView(R.layout.dialog_progress);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(true);
progressDialog.setCanceledOnTouchOutside(false);
return progressDialog;
}
/**
* Hide keyboard
*/
public static void hideKeyboard(Context context) {
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (((Activity) context).getCurrentFocus() != null) {
try {
inputManager.hideSoftInputFromWindow(
|
((BaseActivity) context).getCurrentFocus().getWindowToken(), 0);
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/ui/base/BaseFragment.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/component/ActivityFragmentComponent.java
// @ActivityScope
// @Component(dependencies = ApplicationComponent.class, modules = ActivityFragmentModule.class)
// public interface ActivityFragmentComponent {
//
// void inject(MainActivity mainActivity);
//
// void inject(DayFragment dayFragment);
//
// void inject(DayDetailActivity dayDetailActivity);
//
// void inject(ManageCityActivity manageCityActivity);
//
// void inject(WelcomeActivity welcomeActivity);
// }
|
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import butterknife.Unbinder;
import mk.petrovski.weathergurumvp.injection.component.ActivityFragmentComponent;
|
@Override public void onError(@StringRes int resId) {
if (baseActivity != null) {
baseActivity.onError(resId);
}
}
@Override public void onError(String message) {
if (baseActivity != null) {
baseActivity.onError(message);
}
}
@Override public boolean isNetworkConnected() {
return baseActivity != null && baseActivity.isNetworkConnected();
}
@Override public void onDetach() {
baseActivity = null;
super.onDetach();
}
@Override public void hideKeyboard() {
if (baseActivity != null) {
baseActivity.hideKeyboard();
}
}
protected abstract void init();
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/component/ActivityFragmentComponent.java
// @ActivityScope
// @Component(dependencies = ApplicationComponent.class, modules = ActivityFragmentModule.class)
// public interface ActivityFragmentComponent {
//
// void inject(MainActivity mainActivity);
//
// void inject(DayFragment dayFragment);
//
// void inject(DayDetailActivity dayDetailActivity);
//
// void inject(ManageCityActivity manageCityActivity);
//
// void inject(WelcomeActivity welcomeActivity);
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/base/BaseFragment.java
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import butterknife.Unbinder;
import mk.petrovski.weathergurumvp.injection.component.ActivityFragmentComponent;
@Override public void onError(@StringRes int resId) {
if (baseActivity != null) {
baseActivity.onError(resId);
}
}
@Override public void onError(String message) {
if (baseActivity != null) {
baseActivity.onError(message);
}
}
@Override public boolean isNetworkConnected() {
return baseActivity != null && baseActivity.isNetworkConnected();
}
@Override public void onDetach() {
baseActivity = null;
super.onDetach();
}
@Override public void hideKeyboard() {
if (baseActivity != null) {
baseActivity.hideKeyboard();
}
}
protected abstract void init();
|
public ActivityFragmentComponent getActivityFragmentComponent() {
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/test/java/mk/petrovski/weathergurumvp/data/PreferencesHelperTest.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/AppPreferencesHelper.java
// public class AppPreferencesHelper implements PreferencesHelper {
//
// private static final String PREF_KEY_IS_LOGGED_IN = "PREF_KEY_IS_LOGGED_IN";
// private static final String PREF_KEY_USER_NAME = "PREF_KEY_USER_NAME_VALUE";
//
// private CommonPreferencesHelper commonPreferencesHelper;
//
// @Inject public AppPreferencesHelper(CommonPreferencesHelper commonPreferencesHelper) {
// this.commonPreferencesHelper = commonPreferencesHelper;
// }
//
// @Override public void setLoggedIn() {
// commonPreferencesHelper.setBooleanToPrefs(PREF_KEY_IS_LOGGED_IN, true);
// }
//
// @Override public boolean isLoggedIn() {
// return commonPreferencesHelper.getBooleanFromPrefs(PREF_KEY_IS_LOGGED_IN);
// }
//
// @Override public void setUserName(String userName) {
// commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_NAME, userName);
// }
//
// @Override public String getUserName() {
// return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_NAME);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/CommonPreferencesHelper.java
// public class CommonPreferencesHelper implements BasePreferencesHelper {
//
// //shared prefs name
// private static final String NAME_PREF = "weather_guru_prefs";
//
// private final SharedPreferences preferences;
//
// @Inject public CommonPreferencesHelper(Context context) {
// preferences = context.getSharedPreferences(NAME_PREF, Context.MODE_PRIVATE);
// }
//
// /**
// * Method for getting boolean value from prefs
// *
// * @return boolean value
// */
// @Override public boolean getBooleanFromPrefs(String key) {
// return preferences.getBoolean(key, false);
// }
//
// /**
// * Method for setting boolean value from prefs
// */
// @Override public void setBooleanToPrefs(String key, boolean value) {
// preferences.edit().putBoolean(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key) {
// return preferences.getString(key, "");
// }
//
// /**
// * Method for setting string value from prefs
// */
// @Override public void setStringToPrefs(String key, String value) {
// preferences.edit().putString(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs with default value
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key, String defaultValue) {
// return preferences.getString(key, defaultValue);
// }
//
// /**
// * Method for setting long value from prefs
// */
// @Override public void setLongToPrefs(String key, long value) {
// preferences.edit().putLong(key, value).apply();
// }
//
// /**
// * Method for getting long value from prefs
// *
// * @return long value
// */
// @Override public long getLongFromPrefs(String key) {
// return preferences.getLong(key, 0);
// }
//
// /**
// * Method for getting int value from prefs
// *
// * @return integer value
// */
// @Override public int getIntFromPrefs(String key) {
// return preferences.getInt(key, 0);
// }
//
// /**
// * Method for setting int value from prefs
// */
// @Override public void setIntToPrefs(String key, int value) {
// preferences.edit().putInt(key, value).apply();
// }
// }
|
import mk.petrovski.weathergurumvp.BuildConfig;
import mk.petrovski.weathergurumvp.data.local.preferences.AppPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.CommonPreferencesHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
|
package mk.petrovski.weathergurumvp.data;
/**
* Created by Nikola Petrovski on 4/3/2017.
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 25)
public class PreferencesHelperTest {
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/AppPreferencesHelper.java
// public class AppPreferencesHelper implements PreferencesHelper {
//
// private static final String PREF_KEY_IS_LOGGED_IN = "PREF_KEY_IS_LOGGED_IN";
// private static final String PREF_KEY_USER_NAME = "PREF_KEY_USER_NAME_VALUE";
//
// private CommonPreferencesHelper commonPreferencesHelper;
//
// @Inject public AppPreferencesHelper(CommonPreferencesHelper commonPreferencesHelper) {
// this.commonPreferencesHelper = commonPreferencesHelper;
// }
//
// @Override public void setLoggedIn() {
// commonPreferencesHelper.setBooleanToPrefs(PREF_KEY_IS_LOGGED_IN, true);
// }
//
// @Override public boolean isLoggedIn() {
// return commonPreferencesHelper.getBooleanFromPrefs(PREF_KEY_IS_LOGGED_IN);
// }
//
// @Override public void setUserName(String userName) {
// commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_NAME, userName);
// }
//
// @Override public String getUserName() {
// return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_NAME);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/CommonPreferencesHelper.java
// public class CommonPreferencesHelper implements BasePreferencesHelper {
//
// //shared prefs name
// private static final String NAME_PREF = "weather_guru_prefs";
//
// private final SharedPreferences preferences;
//
// @Inject public CommonPreferencesHelper(Context context) {
// preferences = context.getSharedPreferences(NAME_PREF, Context.MODE_PRIVATE);
// }
//
// /**
// * Method for getting boolean value from prefs
// *
// * @return boolean value
// */
// @Override public boolean getBooleanFromPrefs(String key) {
// return preferences.getBoolean(key, false);
// }
//
// /**
// * Method for setting boolean value from prefs
// */
// @Override public void setBooleanToPrefs(String key, boolean value) {
// preferences.edit().putBoolean(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key) {
// return preferences.getString(key, "");
// }
//
// /**
// * Method for setting string value from prefs
// */
// @Override public void setStringToPrefs(String key, String value) {
// preferences.edit().putString(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs with default value
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key, String defaultValue) {
// return preferences.getString(key, defaultValue);
// }
//
// /**
// * Method for setting long value from prefs
// */
// @Override public void setLongToPrefs(String key, long value) {
// preferences.edit().putLong(key, value).apply();
// }
//
// /**
// * Method for getting long value from prefs
// *
// * @return long value
// */
// @Override public long getLongFromPrefs(String key) {
// return preferences.getLong(key, 0);
// }
//
// /**
// * Method for getting int value from prefs
// *
// * @return integer value
// */
// @Override public int getIntFromPrefs(String key) {
// return preferences.getInt(key, 0);
// }
//
// /**
// * Method for setting int value from prefs
// */
// @Override public void setIntToPrefs(String key, int value) {
// preferences.edit().putInt(key, value).apply();
// }
// }
// Path: app/src/test/java/mk/petrovski/weathergurumvp/data/PreferencesHelperTest.java
import mk.petrovski.weathergurumvp.BuildConfig;
import mk.petrovski.weathergurumvp.data.local.preferences.AppPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.CommonPreferencesHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package mk.petrovski.weathergurumvp.data;
/**
* Created by Nikola Petrovski on 4/3/2017.
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 25)
public class PreferencesHelperTest {
|
private AppPreferencesHelper appPreferencesHelper;
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/test/java/mk/petrovski/weathergurumvp/data/PreferencesHelperTest.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/AppPreferencesHelper.java
// public class AppPreferencesHelper implements PreferencesHelper {
//
// private static final String PREF_KEY_IS_LOGGED_IN = "PREF_KEY_IS_LOGGED_IN";
// private static final String PREF_KEY_USER_NAME = "PREF_KEY_USER_NAME_VALUE";
//
// private CommonPreferencesHelper commonPreferencesHelper;
//
// @Inject public AppPreferencesHelper(CommonPreferencesHelper commonPreferencesHelper) {
// this.commonPreferencesHelper = commonPreferencesHelper;
// }
//
// @Override public void setLoggedIn() {
// commonPreferencesHelper.setBooleanToPrefs(PREF_KEY_IS_LOGGED_IN, true);
// }
//
// @Override public boolean isLoggedIn() {
// return commonPreferencesHelper.getBooleanFromPrefs(PREF_KEY_IS_LOGGED_IN);
// }
//
// @Override public void setUserName(String userName) {
// commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_NAME, userName);
// }
//
// @Override public String getUserName() {
// return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_NAME);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/CommonPreferencesHelper.java
// public class CommonPreferencesHelper implements BasePreferencesHelper {
//
// //shared prefs name
// private static final String NAME_PREF = "weather_guru_prefs";
//
// private final SharedPreferences preferences;
//
// @Inject public CommonPreferencesHelper(Context context) {
// preferences = context.getSharedPreferences(NAME_PREF, Context.MODE_PRIVATE);
// }
//
// /**
// * Method for getting boolean value from prefs
// *
// * @return boolean value
// */
// @Override public boolean getBooleanFromPrefs(String key) {
// return preferences.getBoolean(key, false);
// }
//
// /**
// * Method for setting boolean value from prefs
// */
// @Override public void setBooleanToPrefs(String key, boolean value) {
// preferences.edit().putBoolean(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key) {
// return preferences.getString(key, "");
// }
//
// /**
// * Method for setting string value from prefs
// */
// @Override public void setStringToPrefs(String key, String value) {
// preferences.edit().putString(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs with default value
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key, String defaultValue) {
// return preferences.getString(key, defaultValue);
// }
//
// /**
// * Method for setting long value from prefs
// */
// @Override public void setLongToPrefs(String key, long value) {
// preferences.edit().putLong(key, value).apply();
// }
//
// /**
// * Method for getting long value from prefs
// *
// * @return long value
// */
// @Override public long getLongFromPrefs(String key) {
// return preferences.getLong(key, 0);
// }
//
// /**
// * Method for getting int value from prefs
// *
// * @return integer value
// */
// @Override public int getIntFromPrefs(String key) {
// return preferences.getInt(key, 0);
// }
//
// /**
// * Method for setting int value from prefs
// */
// @Override public void setIntToPrefs(String key, int value) {
// preferences.edit().putInt(key, value).apply();
// }
// }
|
import mk.petrovski.weathergurumvp.BuildConfig;
import mk.petrovski.weathergurumvp.data.local.preferences.AppPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.CommonPreferencesHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
|
package mk.petrovski.weathergurumvp.data;
/**
* Created by Nikola Petrovski on 4/3/2017.
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 25)
public class PreferencesHelperTest {
private AppPreferencesHelper appPreferencesHelper;
@Before public void setUp(){
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/AppPreferencesHelper.java
// public class AppPreferencesHelper implements PreferencesHelper {
//
// private static final String PREF_KEY_IS_LOGGED_IN = "PREF_KEY_IS_LOGGED_IN";
// private static final String PREF_KEY_USER_NAME = "PREF_KEY_USER_NAME_VALUE";
//
// private CommonPreferencesHelper commonPreferencesHelper;
//
// @Inject public AppPreferencesHelper(CommonPreferencesHelper commonPreferencesHelper) {
// this.commonPreferencesHelper = commonPreferencesHelper;
// }
//
// @Override public void setLoggedIn() {
// commonPreferencesHelper.setBooleanToPrefs(PREF_KEY_IS_LOGGED_IN, true);
// }
//
// @Override public boolean isLoggedIn() {
// return commonPreferencesHelper.getBooleanFromPrefs(PREF_KEY_IS_LOGGED_IN);
// }
//
// @Override public void setUserName(String userName) {
// commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_NAME, userName);
// }
//
// @Override public String getUserName() {
// return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_NAME);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/CommonPreferencesHelper.java
// public class CommonPreferencesHelper implements BasePreferencesHelper {
//
// //shared prefs name
// private static final String NAME_PREF = "weather_guru_prefs";
//
// private final SharedPreferences preferences;
//
// @Inject public CommonPreferencesHelper(Context context) {
// preferences = context.getSharedPreferences(NAME_PREF, Context.MODE_PRIVATE);
// }
//
// /**
// * Method for getting boolean value from prefs
// *
// * @return boolean value
// */
// @Override public boolean getBooleanFromPrefs(String key) {
// return preferences.getBoolean(key, false);
// }
//
// /**
// * Method for setting boolean value from prefs
// */
// @Override public void setBooleanToPrefs(String key, boolean value) {
// preferences.edit().putBoolean(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key) {
// return preferences.getString(key, "");
// }
//
// /**
// * Method for setting string value from prefs
// */
// @Override public void setStringToPrefs(String key, String value) {
// preferences.edit().putString(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs with default value
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key, String defaultValue) {
// return preferences.getString(key, defaultValue);
// }
//
// /**
// * Method for setting long value from prefs
// */
// @Override public void setLongToPrefs(String key, long value) {
// preferences.edit().putLong(key, value).apply();
// }
//
// /**
// * Method for getting long value from prefs
// *
// * @return long value
// */
// @Override public long getLongFromPrefs(String key) {
// return preferences.getLong(key, 0);
// }
//
// /**
// * Method for getting int value from prefs
// *
// * @return integer value
// */
// @Override public int getIntFromPrefs(String key) {
// return preferences.getInt(key, 0);
// }
//
// /**
// * Method for setting int value from prefs
// */
// @Override public void setIntToPrefs(String key, int value) {
// preferences.edit().putInt(key, value).apply();
// }
// }
// Path: app/src/test/java/mk/petrovski/weathergurumvp/data/PreferencesHelperTest.java
import mk.petrovski.weathergurumvp.BuildConfig;
import mk.petrovski.weathergurumvp.data.local.preferences.AppPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.CommonPreferencesHelper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package mk.petrovski.weathergurumvp.data;
/**
* Created by Nikola Petrovski on 4/3/2017.
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 25)
public class PreferencesHelperTest {
private AppPreferencesHelper appPreferencesHelper;
@Before public void setUp(){
|
CommonPreferencesHelper commonPreferencesHelper = new CommonPreferencesHelper(
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/injection/module/PreferencesModule.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/AppPreferencesHelper.java
// public class AppPreferencesHelper implements PreferencesHelper {
//
// private static final String PREF_KEY_IS_LOGGED_IN = "PREF_KEY_IS_LOGGED_IN";
// private static final String PREF_KEY_USER_NAME = "PREF_KEY_USER_NAME_VALUE";
//
// private CommonPreferencesHelper commonPreferencesHelper;
//
// @Inject public AppPreferencesHelper(CommonPreferencesHelper commonPreferencesHelper) {
// this.commonPreferencesHelper = commonPreferencesHelper;
// }
//
// @Override public void setLoggedIn() {
// commonPreferencesHelper.setBooleanToPrefs(PREF_KEY_IS_LOGGED_IN, true);
// }
//
// @Override public boolean isLoggedIn() {
// return commonPreferencesHelper.getBooleanFromPrefs(PREF_KEY_IS_LOGGED_IN);
// }
//
// @Override public void setUserName(String userName) {
// commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_NAME, userName);
// }
//
// @Override public String getUserName() {
// return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_NAME);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/CommonPreferencesHelper.java
// public class CommonPreferencesHelper implements BasePreferencesHelper {
//
// //shared prefs name
// private static final String NAME_PREF = "weather_guru_prefs";
//
// private final SharedPreferences preferences;
//
// @Inject public CommonPreferencesHelper(Context context) {
// preferences = context.getSharedPreferences(NAME_PREF, Context.MODE_PRIVATE);
// }
//
// /**
// * Method for getting boolean value from prefs
// *
// * @return boolean value
// */
// @Override public boolean getBooleanFromPrefs(String key) {
// return preferences.getBoolean(key, false);
// }
//
// /**
// * Method for setting boolean value from prefs
// */
// @Override public void setBooleanToPrefs(String key, boolean value) {
// preferences.edit().putBoolean(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key) {
// return preferences.getString(key, "");
// }
//
// /**
// * Method for setting string value from prefs
// */
// @Override public void setStringToPrefs(String key, String value) {
// preferences.edit().putString(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs with default value
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key, String defaultValue) {
// return preferences.getString(key, defaultValue);
// }
//
// /**
// * Method for setting long value from prefs
// */
// @Override public void setLongToPrefs(String key, long value) {
// preferences.edit().putLong(key, value).apply();
// }
//
// /**
// * Method for getting long value from prefs
// *
// * @return long value
// */
// @Override public long getLongFromPrefs(String key) {
// return preferences.getLong(key, 0);
// }
//
// /**
// * Method for getting int value from prefs
// *
// * @return integer value
// */
// @Override public int getIntFromPrefs(String key) {
// return preferences.getInt(key, 0);
// }
//
// /**
// * Method for setting int value from prefs
// */
// @Override public void setIntToPrefs(String key, int value) {
// preferences.edit().putInt(key, value).apply();
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/PreferencesHelper.java
// public interface PreferencesHelper {
//
// void setLoggedIn();
//
// boolean isLoggedIn();
//
// void setUserName(String userName);
//
// String getUserName();
// }
|
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import mk.petrovski.weathergurumvp.data.local.preferences.AppPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.CommonPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.PreferencesHelper;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
|
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 3/1/2017.
*/
@Module(includes = ContextModule.class) public class PreferencesModule {
@Provides @WeatherGuruApplicationScope CommonPreferencesHelper getPreferencesHelper(
@ApplicationContext Context context) {
return new CommonPreferencesHelper(context);
}
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/AppPreferencesHelper.java
// public class AppPreferencesHelper implements PreferencesHelper {
//
// private static final String PREF_KEY_IS_LOGGED_IN = "PREF_KEY_IS_LOGGED_IN";
// private static final String PREF_KEY_USER_NAME = "PREF_KEY_USER_NAME_VALUE";
//
// private CommonPreferencesHelper commonPreferencesHelper;
//
// @Inject public AppPreferencesHelper(CommonPreferencesHelper commonPreferencesHelper) {
// this.commonPreferencesHelper = commonPreferencesHelper;
// }
//
// @Override public void setLoggedIn() {
// commonPreferencesHelper.setBooleanToPrefs(PREF_KEY_IS_LOGGED_IN, true);
// }
//
// @Override public boolean isLoggedIn() {
// return commonPreferencesHelper.getBooleanFromPrefs(PREF_KEY_IS_LOGGED_IN);
// }
//
// @Override public void setUserName(String userName) {
// commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_NAME, userName);
// }
//
// @Override public String getUserName() {
// return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_NAME);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/CommonPreferencesHelper.java
// public class CommonPreferencesHelper implements BasePreferencesHelper {
//
// //shared prefs name
// private static final String NAME_PREF = "weather_guru_prefs";
//
// private final SharedPreferences preferences;
//
// @Inject public CommonPreferencesHelper(Context context) {
// preferences = context.getSharedPreferences(NAME_PREF, Context.MODE_PRIVATE);
// }
//
// /**
// * Method for getting boolean value from prefs
// *
// * @return boolean value
// */
// @Override public boolean getBooleanFromPrefs(String key) {
// return preferences.getBoolean(key, false);
// }
//
// /**
// * Method for setting boolean value from prefs
// */
// @Override public void setBooleanToPrefs(String key, boolean value) {
// preferences.edit().putBoolean(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key) {
// return preferences.getString(key, "");
// }
//
// /**
// * Method for setting string value from prefs
// */
// @Override public void setStringToPrefs(String key, String value) {
// preferences.edit().putString(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs with default value
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key, String defaultValue) {
// return preferences.getString(key, defaultValue);
// }
//
// /**
// * Method for setting long value from prefs
// */
// @Override public void setLongToPrefs(String key, long value) {
// preferences.edit().putLong(key, value).apply();
// }
//
// /**
// * Method for getting long value from prefs
// *
// * @return long value
// */
// @Override public long getLongFromPrefs(String key) {
// return preferences.getLong(key, 0);
// }
//
// /**
// * Method for getting int value from prefs
// *
// * @return integer value
// */
// @Override public int getIntFromPrefs(String key) {
// return preferences.getInt(key, 0);
// }
//
// /**
// * Method for setting int value from prefs
// */
// @Override public void setIntToPrefs(String key, int value) {
// preferences.edit().putInt(key, value).apply();
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/PreferencesHelper.java
// public interface PreferencesHelper {
//
// void setLoggedIn();
//
// boolean isLoggedIn();
//
// void setUserName(String userName);
//
// String getUserName();
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/PreferencesModule.java
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import mk.petrovski.weathergurumvp.data.local.preferences.AppPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.CommonPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.PreferencesHelper;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 3/1/2017.
*/
@Module(includes = ContextModule.class) public class PreferencesModule {
@Provides @WeatherGuruApplicationScope CommonPreferencesHelper getPreferencesHelper(
@ApplicationContext Context context) {
return new CommonPreferencesHelper(context);
}
|
@Provides @WeatherGuruApplicationScope PreferencesHelper getApplicationPreferences(
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/injection/module/PreferencesModule.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/AppPreferencesHelper.java
// public class AppPreferencesHelper implements PreferencesHelper {
//
// private static final String PREF_KEY_IS_LOGGED_IN = "PREF_KEY_IS_LOGGED_IN";
// private static final String PREF_KEY_USER_NAME = "PREF_KEY_USER_NAME_VALUE";
//
// private CommonPreferencesHelper commonPreferencesHelper;
//
// @Inject public AppPreferencesHelper(CommonPreferencesHelper commonPreferencesHelper) {
// this.commonPreferencesHelper = commonPreferencesHelper;
// }
//
// @Override public void setLoggedIn() {
// commonPreferencesHelper.setBooleanToPrefs(PREF_KEY_IS_LOGGED_IN, true);
// }
//
// @Override public boolean isLoggedIn() {
// return commonPreferencesHelper.getBooleanFromPrefs(PREF_KEY_IS_LOGGED_IN);
// }
//
// @Override public void setUserName(String userName) {
// commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_NAME, userName);
// }
//
// @Override public String getUserName() {
// return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_NAME);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/CommonPreferencesHelper.java
// public class CommonPreferencesHelper implements BasePreferencesHelper {
//
// //shared prefs name
// private static final String NAME_PREF = "weather_guru_prefs";
//
// private final SharedPreferences preferences;
//
// @Inject public CommonPreferencesHelper(Context context) {
// preferences = context.getSharedPreferences(NAME_PREF, Context.MODE_PRIVATE);
// }
//
// /**
// * Method for getting boolean value from prefs
// *
// * @return boolean value
// */
// @Override public boolean getBooleanFromPrefs(String key) {
// return preferences.getBoolean(key, false);
// }
//
// /**
// * Method for setting boolean value from prefs
// */
// @Override public void setBooleanToPrefs(String key, boolean value) {
// preferences.edit().putBoolean(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key) {
// return preferences.getString(key, "");
// }
//
// /**
// * Method for setting string value from prefs
// */
// @Override public void setStringToPrefs(String key, String value) {
// preferences.edit().putString(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs with default value
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key, String defaultValue) {
// return preferences.getString(key, defaultValue);
// }
//
// /**
// * Method for setting long value from prefs
// */
// @Override public void setLongToPrefs(String key, long value) {
// preferences.edit().putLong(key, value).apply();
// }
//
// /**
// * Method for getting long value from prefs
// *
// * @return long value
// */
// @Override public long getLongFromPrefs(String key) {
// return preferences.getLong(key, 0);
// }
//
// /**
// * Method for getting int value from prefs
// *
// * @return integer value
// */
// @Override public int getIntFromPrefs(String key) {
// return preferences.getInt(key, 0);
// }
//
// /**
// * Method for setting int value from prefs
// */
// @Override public void setIntToPrefs(String key, int value) {
// preferences.edit().putInt(key, value).apply();
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/PreferencesHelper.java
// public interface PreferencesHelper {
//
// void setLoggedIn();
//
// boolean isLoggedIn();
//
// void setUserName(String userName);
//
// String getUserName();
// }
|
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import mk.petrovski.weathergurumvp.data.local.preferences.AppPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.CommonPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.PreferencesHelper;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
|
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 3/1/2017.
*/
@Module(includes = ContextModule.class) public class PreferencesModule {
@Provides @WeatherGuruApplicationScope CommonPreferencesHelper getPreferencesHelper(
@ApplicationContext Context context) {
return new CommonPreferencesHelper(context);
}
@Provides @WeatherGuruApplicationScope PreferencesHelper getApplicationPreferences(
CommonPreferencesHelper commonPreferencesHelper) {
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/AppPreferencesHelper.java
// public class AppPreferencesHelper implements PreferencesHelper {
//
// private static final String PREF_KEY_IS_LOGGED_IN = "PREF_KEY_IS_LOGGED_IN";
// private static final String PREF_KEY_USER_NAME = "PREF_KEY_USER_NAME_VALUE";
//
// private CommonPreferencesHelper commonPreferencesHelper;
//
// @Inject public AppPreferencesHelper(CommonPreferencesHelper commonPreferencesHelper) {
// this.commonPreferencesHelper = commonPreferencesHelper;
// }
//
// @Override public void setLoggedIn() {
// commonPreferencesHelper.setBooleanToPrefs(PREF_KEY_IS_LOGGED_IN, true);
// }
//
// @Override public boolean isLoggedIn() {
// return commonPreferencesHelper.getBooleanFromPrefs(PREF_KEY_IS_LOGGED_IN);
// }
//
// @Override public void setUserName(String userName) {
// commonPreferencesHelper.setStringToPrefs(PREF_KEY_USER_NAME, userName);
// }
//
// @Override public String getUserName() {
// return commonPreferencesHelper.getStringFromPrefs(PREF_KEY_USER_NAME);
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/CommonPreferencesHelper.java
// public class CommonPreferencesHelper implements BasePreferencesHelper {
//
// //shared prefs name
// private static final String NAME_PREF = "weather_guru_prefs";
//
// private final SharedPreferences preferences;
//
// @Inject public CommonPreferencesHelper(Context context) {
// preferences = context.getSharedPreferences(NAME_PREF, Context.MODE_PRIVATE);
// }
//
// /**
// * Method for getting boolean value from prefs
// *
// * @return boolean value
// */
// @Override public boolean getBooleanFromPrefs(String key) {
// return preferences.getBoolean(key, false);
// }
//
// /**
// * Method for setting boolean value from prefs
// */
// @Override public void setBooleanToPrefs(String key, boolean value) {
// preferences.edit().putBoolean(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key) {
// return preferences.getString(key, "");
// }
//
// /**
// * Method for setting string value from prefs
// */
// @Override public void setStringToPrefs(String key, String value) {
// preferences.edit().putString(key, value).apply();
// }
//
// /**
// * Method for getting string value from prefs with default value
// *
// * @return string value
// */
// @Override public String getStringFromPrefs(String key, String defaultValue) {
// return preferences.getString(key, defaultValue);
// }
//
// /**
// * Method for setting long value from prefs
// */
// @Override public void setLongToPrefs(String key, long value) {
// preferences.edit().putLong(key, value).apply();
// }
//
// /**
// * Method for getting long value from prefs
// *
// * @return long value
// */
// @Override public long getLongFromPrefs(String key) {
// return preferences.getLong(key, 0);
// }
//
// /**
// * Method for getting int value from prefs
// *
// * @return integer value
// */
// @Override public int getIntFromPrefs(String key) {
// return preferences.getInt(key, 0);
// }
//
// /**
// * Method for setting int value from prefs
// */
// @Override public void setIntToPrefs(String key, int value) {
// preferences.edit().putInt(key, value).apply();
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/preferences/PreferencesHelper.java
// public interface PreferencesHelper {
//
// void setLoggedIn();
//
// boolean isLoggedIn();
//
// void setUserName(String userName);
//
// String getUserName();
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/injection/module/PreferencesModule.java
import android.content.Context;
import dagger.Module;
import dagger.Provides;
import mk.petrovski.weathergurumvp.data.local.preferences.AppPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.CommonPreferencesHelper;
import mk.petrovski.weathergurumvp.data.local.preferences.PreferencesHelper;
import mk.petrovski.weathergurumvp.injection.qualifier.ApplicationContext;
import mk.petrovski.weathergurumvp.injection.scope.WeatherGuruApplicationScope;
package mk.petrovski.weathergurumvp.injection.module;
/**
* Created by Nikola Petrovski on 3/1/2017.
*/
@Module(includes = ContextModule.class) public class PreferencesModule {
@Provides @WeatherGuruApplicationScope CommonPreferencesHelper getPreferencesHelper(
@ApplicationContext Context context) {
return new CommonPreferencesHelper(context);
}
@Provides @WeatherGuruApplicationScope PreferencesHelper getApplicationPreferences(
CommonPreferencesHelper commonPreferencesHelper) {
|
return new AppPreferencesHelper(commonPreferencesHelper);
|
nikacotAndroid/Weather-Guru-MVP
|
app/src/main/java/mk/petrovski/weathergurumvp/ui/main/MainMvpPresenter.java
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/db/CityDetailsModel.java
// @Entity(nameInDb = "city") public class CityDetailsModel {
//
// @Id(autoincrement = true) private Long id;
//
// private String areaName;
// private String country;
// private String latitude;
// private String longitude;
// private String population;
// private String region;
// private String weatherUrl;
// private Boolean isSelected;
//
// @Generated(hash = 959524249)
// public CityDetailsModel(Long id, String areaName, String country, String latitude,
// String longitude, String population, String region, String weatherUrl, Boolean isSelected) {
// this.id = id;
// this.areaName = areaName;
// this.country = country;
// this.latitude = latitude;
// this.longitude = longitude;
// this.population = population;
// this.region = region;
// this.weatherUrl = weatherUrl;
// this.isSelected = isSelected;
// }
//
// @Generated(hash = 696392665) public CityDetailsModel() {
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getAreaName() {
// return areaName;
// }
//
// public void setAreaName(String areaName) {
// this.areaName = areaName;
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getLatitude() {
// return latitude;
// }
//
// public void setLatitude(String latitude) {
// this.latitude = latitude;
// }
//
// public String getLongitude() {
// return longitude;
// }
//
// public void setLongitude(String longitude) {
// this.longitude = longitude;
// }
//
// public String getPopulation() {
// return population;
// }
//
// public void setPopulation(String population) {
// this.population = population;
// }
//
// public String getRegion() {
// return region;
// }
//
// public void setRegion(String region) {
// this.region = region;
// }
//
// public String getWeatherUrl() {
// return weatherUrl;
// }
//
// public void setWeatherUrl(String weatherUrl) {
// this.weatherUrl = weatherUrl;
// }
//
// public Boolean getSelected() {
// return isSelected;
// }
//
// public void setSelected(Boolean selected) {
// isSelected = selected;
// }
//
// public Boolean getIsSelected() {
// return this.isSelected;
// }
//
// public void setIsSelected(Boolean isSelected) {
// this.isSelected = isSelected;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/base/Presenter.java
// public interface Presenter<V extends BaseMvpView> {
//
// /**
// * Called when the view is attached to the presenter. Presenters should normally not use this
// * method since it's only used to link the view to the presenter which is done by the
// * BasePresenter.
// *
// * @param mvpView the view
// */
// void attachView(@NonNull V mvpView);
//
// /**
// * Called when the view is detached from the presenter. Presenters should normally not use this
// * method since it's only used to unlink the view from the presenter which is done by the
// * BasePresenter.
// */
// void detachView();
// }
|
import mk.petrovski.weathergurumvp.data.local.db.CityDetailsModel;
import mk.petrovski.weathergurumvp.ui.base.Presenter;
|
package mk.petrovski.weathergurumvp.ui.main;
/**
* Created by Nikola Petrovski on 2/14/2017.
*/
public interface MainMvpPresenter<V extends MainMvpView> extends Presenter<V> {
void setDrawerCities();
void setUserInfo();
|
// Path: app/src/main/java/mk/petrovski/weathergurumvp/data/local/db/CityDetailsModel.java
// @Entity(nameInDb = "city") public class CityDetailsModel {
//
// @Id(autoincrement = true) private Long id;
//
// private String areaName;
// private String country;
// private String latitude;
// private String longitude;
// private String population;
// private String region;
// private String weatherUrl;
// private Boolean isSelected;
//
// @Generated(hash = 959524249)
// public CityDetailsModel(Long id, String areaName, String country, String latitude,
// String longitude, String population, String region, String weatherUrl, Boolean isSelected) {
// this.id = id;
// this.areaName = areaName;
// this.country = country;
// this.latitude = latitude;
// this.longitude = longitude;
// this.population = population;
// this.region = region;
// this.weatherUrl = weatherUrl;
// this.isSelected = isSelected;
// }
//
// @Generated(hash = 696392665) public CityDetailsModel() {
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getAreaName() {
// return areaName;
// }
//
// public void setAreaName(String areaName) {
// this.areaName = areaName;
// }
//
// public String getCountry() {
// return country;
// }
//
// public void setCountry(String country) {
// this.country = country;
// }
//
// public String getLatitude() {
// return latitude;
// }
//
// public void setLatitude(String latitude) {
// this.latitude = latitude;
// }
//
// public String getLongitude() {
// return longitude;
// }
//
// public void setLongitude(String longitude) {
// this.longitude = longitude;
// }
//
// public String getPopulation() {
// return population;
// }
//
// public void setPopulation(String population) {
// this.population = population;
// }
//
// public String getRegion() {
// return region;
// }
//
// public void setRegion(String region) {
// this.region = region;
// }
//
// public String getWeatherUrl() {
// return weatherUrl;
// }
//
// public void setWeatherUrl(String weatherUrl) {
// this.weatherUrl = weatherUrl;
// }
//
// public Boolean getSelected() {
// return isSelected;
// }
//
// public void setSelected(Boolean selected) {
// isSelected = selected;
// }
//
// public Boolean getIsSelected() {
// return this.isSelected;
// }
//
// public void setIsSelected(Boolean isSelected) {
// this.isSelected = isSelected;
// }
// }
//
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/base/Presenter.java
// public interface Presenter<V extends BaseMvpView> {
//
// /**
// * Called when the view is attached to the presenter. Presenters should normally not use this
// * method since it's only used to link the view to the presenter which is done by the
// * BasePresenter.
// *
// * @param mvpView the view
// */
// void attachView(@NonNull V mvpView);
//
// /**
// * Called when the view is detached from the presenter. Presenters should normally not use this
// * method since it's only used to unlink the view from the presenter which is done by the
// * BasePresenter.
// */
// void detachView();
// }
// Path: app/src/main/java/mk/petrovski/weathergurumvp/ui/main/MainMvpPresenter.java
import mk.petrovski.weathergurumvp.data.local.db.CityDetailsModel;
import mk.petrovski.weathergurumvp.ui.base.Presenter;
package mk.petrovski.weathergurumvp.ui.main;
/**
* Created by Nikola Petrovski on 2/14/2017.
*/
public interface MainMvpPresenter<V extends MainMvpView> extends Presenter<V> {
void setDrawerCities();
void setUserInfo();
|
void selectCity(CityDetailsModel city);
|
at-attentec/at.attentec
|
at.attentec.com/android/at.attentec.client/src/com/attentec/StatusDialogCreator.java
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/Status.java
// class StatusIterator implements Iterator<Status> {
// //Start on online instead of offline since it is weird to set you own status to offline when you are online.
// private int current = STATUS_ONLINE;
// private Status status;
//
// /**
// * Create an iterator.
// * @param myStatus the status that should be cloned for iterating through.
// */
// public StatusIterator(final Status myStatus) {
// try {
// status = myStatus.clone();
// } catch (CloneNotSupportedException e) {
// Log.e(TAG, "StatusIterator can't clone MyStatus:" + e.getMessage());
// }
// }
//
// /**
// * Checks if there are any more status type to fetch.
// * @return true if has next
// */
// public boolean hasNext() {
// return current <= Status.STATUS_AWAY;
// }
//
// /**
// * Get the next status.
// * @return next status
// */
// public Status next() {
// if (hasNext()) {
// status.updateStatus(current++, "");
// return status;
// } else {
// return null;
// }
// }
//
// /**
// * Is not implemented.
// */
// public void remove() {
// //DO nothing
// }
// }
|
import com.attentec.Status.StatusIterator;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
|
/***
* Copyright (c) 2010 Attentec AB, http://www.attentec.se
*
* 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.attentec;
/**
* Creates Status dialog.
* @author David Granqvist
* @author Malte Lenz
* @author Johannes Nordkvist
*
*/
public class StatusDialogCreator {
/** Tag used for logging. */
private static final String TAG = "Attentec->StatusDialogCreator";
private Context mContext;
private Status mStatus;
/**
* Constructor for creating status dialog.
* @param ctx the contect
* @param myStatus The my status object that should be changed.
*/
public StatusDialogCreator(final Context ctx, final Status myStatus) {
mContext = ctx;
mStatus = myStatus;
}
/**
* Create the dialog that should be shown and return it.
* @return the dialog
*/
public final Dialog getDialog() {
Dialog dialog;
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
Resources mRes = mContext.getResources();
builder.setIcon(android.R.color.transparent);
builder.setTitle(mRes.getString(R.string.my_status));
builder.setNegativeButton(mContext.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int whichButton) {
dialog.cancel();
}
});
final ArrayList<Status> items = new ArrayList<Status>();
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/Status.java
// class StatusIterator implements Iterator<Status> {
// //Start on online instead of offline since it is weird to set you own status to offline when you are online.
// private int current = STATUS_ONLINE;
// private Status status;
//
// /**
// * Create an iterator.
// * @param myStatus the status that should be cloned for iterating through.
// */
// public StatusIterator(final Status myStatus) {
// try {
// status = myStatus.clone();
// } catch (CloneNotSupportedException e) {
// Log.e(TAG, "StatusIterator can't clone MyStatus:" + e.getMessage());
// }
// }
//
// /**
// * Checks if there are any more status type to fetch.
// * @return true if has next
// */
// public boolean hasNext() {
// return current <= Status.STATUS_AWAY;
// }
//
// /**
// * Get the next status.
// * @return next status
// */
// public Status next() {
// if (hasNext()) {
// status.updateStatus(current++, "");
// return status;
// } else {
// return null;
// }
// }
//
// /**
// * Is not implemented.
// */
// public void remove() {
// //DO nothing
// }
// }
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/StatusDialogCreator.java
import com.attentec.Status.StatusIterator;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/***
* Copyright (c) 2010 Attentec AB, http://www.attentec.se
*
* 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.attentec;
/**
* Creates Status dialog.
* @author David Granqvist
* @author Malte Lenz
* @author Johannes Nordkvist
*
*/
public class StatusDialogCreator {
/** Tag used for logging. */
private static final String TAG = "Attentec->StatusDialogCreator";
private Context mContext;
private Status mStatus;
/**
* Constructor for creating status dialog.
* @param ctx the contect
* @param myStatus The my status object that should be changed.
*/
public StatusDialogCreator(final Context ctx, final Status myStatus) {
mContext = ctx;
mStatus = myStatus;
}
/**
* Create the dialog that should be shown and return it.
* @return the dialog
*/
public final Dialog getDialog() {
Dialog dialog;
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
Resources mRes = mContext.getResources();
builder.setIcon(android.R.color.transparent);
builder.setTitle(mRes.getString(R.string.my_status));
builder.setNegativeButton(mContext.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int whichButton) {
dialog.cancel();
}
});
final ArrayList<Status> items = new ArrayList<Status>();
|
StatusIterator statusIterator = mStatus.getIterator();
|
at-attentec/at.attentec
|
at.attentec.com/android/at.attentec.client/src/com/attentec/Status.java
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/Login.java
// public static class LoginException extends Exception {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * No message constructor.
// */
// public LoginException() {
//
// }
//
// /**
// * Message constructor.
// * @param description description of exception
// */
// public LoginException(final String description) {
// super(description);
// }
// }
|
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.attentec.Login.LoginException;
|
// save the status in preferences
sp.edit().putString(STATUS_CUSTOM_MESSAGE, mCustomMessage).putInt(STATUS, mStatus).commit();
//Sent to server
return sendToServer(sp, ctx);
}
/**
* Send status to server.
* @param sp Shared Preferences where username and phonekey are stored.
* @param ctx calling context
* @return true on success
*/
public final boolean sendToServer(final SharedPreferences sp, final Context ctx) {
//Save to server.
//get logindata for server contact
String username = sp.getString("username", "");
String phoneKey = sp.getString("phone_key", "");
Hashtable<String, List<NameValuePair>> postdata = ServerContact.getLogin(username, phoneKey);
//add location to POST data
List<NameValuePair> statusData = new ArrayList<NameValuePair>();
statusData.add(new BasicNameValuePair("status", this.getStatusAsString()));
statusData.add(new BasicNameValuePair("status_custom_message", this.mCustomMessage));
postdata.put("status", statusData);
//send location to server
String url = "/app/app_update_user_info.json";
try {
ServerContact.postJSON(postdata, url, ctx);
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/Login.java
// public static class LoginException extends Exception {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * No message constructor.
// */
// public LoginException() {
//
// }
//
// /**
// * Message constructor.
// * @param description description of exception
// */
// public LoginException(final String description) {
// super(description);
// }
// }
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/Status.java
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.attentec.Login.LoginException;
// save the status in preferences
sp.edit().putString(STATUS_CUSTOM_MESSAGE, mCustomMessage).putInt(STATUS, mStatus).commit();
//Sent to server
return sendToServer(sp, ctx);
}
/**
* Send status to server.
* @param sp Shared Preferences where username and phonekey are stored.
* @param ctx calling context
* @return true on success
*/
public final boolean sendToServer(final SharedPreferences sp, final Context ctx) {
//Save to server.
//get logindata for server contact
String username = sp.getString("username", "");
String phoneKey = sp.getString("phone_key", "");
Hashtable<String, List<NameValuePair>> postdata = ServerContact.getLogin(username, phoneKey);
//add location to POST data
List<NameValuePair> statusData = new ArrayList<NameValuePair>();
statusData.add(new BasicNameValuePair("status", this.getStatusAsString()));
statusData.add(new BasicNameValuePair("status_custom_message", this.mCustomMessage));
postdata.put("status", statusData);
//send location to server
String url = "/app/app_update_user_info.json";
try {
ServerContact.postJSON(postdata, url, ctx);
|
} catch (LoginException e) {
|
at-attentec/at.attentec
|
at.attentec.com/android/at.attentec.client/src/com/attentec/CloseToYou.java
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/AttentecService.java
// public interface ServiceUpdateUIListener {
// /** Tell UI to update. */
// void updateUI();
//
// /** End UI Activity. */
// void endActivity();
// }
|
import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.util.Date;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import com.attentec.AttentecService.ServiceUpdateUIListener;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
|
/***
* Copyright (c) 2010 Attentec AB, http://www.attentec.se
*
* 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.attentec;
/**
* Shows a map with contacts at their location, with
* clickable markers for easy contact.
*
* @author David Granqvist
* @author Malte Lenz
* @author Johannes Nordkvist
*
*/
public class CloseToYou extends MapActivity {
/**
* Tag used for logging.
*/
private static final String TAG = "Attentec";
/** Minimum distance to show on screen, so defines a limit on max zoom-in. */
private static final int MAX_ZOOM = 3000;
/** Maximum distance to show on screen. */
private static final int MIN_ZOOM = 3000000;
// Declares map and its controller.
/** Instance of the map view. */
private MapView mapView;
/** Instance of the map controller. */
private MapController mc;
/** Database adapter. */
private DatabaseAdapter dbh;
/** Overlay that should show my location. */
private MyLocationOverlay mlo;
/** Database cursor for handling locations. */
private Cursor locationcursor;
/** Used to show contact info dialog. */
private long dialogid;
/** Used to show contact info dialog. */
private ContactDialogCreator cdc;
/** Resources . */
private Resources res;
/** Maximum latitude that should be showed on the map. */
private int maxLat = Integer.MIN_VALUE;
/** Maximum longitude that should be showed on the map. */
private int maxLng = Integer.MIN_VALUE;
/** Minimum latitude that should be showed on the map. */
private int minLat = Integer.MAX_VALUE;
/** Minimum longitude that should be showed on the map. */
private int minLng = Integer.MAX_VALUE;
/** Vertical padding for map bounds. */
private final Float vpadding = 0.1f;
/** Bottom padding for map bounds. */
private final Float hpaddingBottom = 0.1f;
/** Top padding for map bounds. */
private final Float hpaddingTop = 0.4f;
/** Used for converting to GeoPoint integer. */
private static final int ONE_MILLION = 1000000;
/** Minimum length for contact info (email/phone). */
private static final int MINIMUM_ACCEPTED_CONTACT_INFO_LENGTH = 4;
private ContactItemizedOverlay itemizedOverlay;
/* Called when the activity is first created. */
@Override
public final void onCreate(final Bundle savedInstanceState) {
Log.d(TAG, "CloseToYou onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.closetoyou);
res = getResources();
//Setup database connection
dbh = new DatabaseAdapter(this);
dbh.open();
locationcursor = dbh.getLocations();
locationcursor.moveToFirst();
startManagingCursor(locationcursor);
//Setup the map
mapView = (MapView) findViewById(R.id.mapView);
//Create ContactItemizedOverlay for mapView
itemizedOverlay = new ContactItemizedOverlay(new ColorDrawable(), mapView);
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mapView.setSatellite(true);
mc = mapView.getController();
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/AttentecService.java
// public interface ServiceUpdateUIListener {
// /** Tell UI to update. */
// void updateUI();
//
// /** End UI Activity. */
// void endActivity();
// }
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/CloseToYou.java
import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.util.Date;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import com.attentec.AttentecService.ServiceUpdateUIListener;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
/***
* Copyright (c) 2010 Attentec AB, http://www.attentec.se
*
* 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.attentec;
/**
* Shows a map with contacts at their location, with
* clickable markers for easy contact.
*
* @author David Granqvist
* @author Malte Lenz
* @author Johannes Nordkvist
*
*/
public class CloseToYou extends MapActivity {
/**
* Tag used for logging.
*/
private static final String TAG = "Attentec";
/** Minimum distance to show on screen, so defines a limit on max zoom-in. */
private static final int MAX_ZOOM = 3000;
/** Maximum distance to show on screen. */
private static final int MIN_ZOOM = 3000000;
// Declares map and its controller.
/** Instance of the map view. */
private MapView mapView;
/** Instance of the map controller. */
private MapController mc;
/** Database adapter. */
private DatabaseAdapter dbh;
/** Overlay that should show my location. */
private MyLocationOverlay mlo;
/** Database cursor for handling locations. */
private Cursor locationcursor;
/** Used to show contact info dialog. */
private long dialogid;
/** Used to show contact info dialog. */
private ContactDialogCreator cdc;
/** Resources . */
private Resources res;
/** Maximum latitude that should be showed on the map. */
private int maxLat = Integer.MIN_VALUE;
/** Maximum longitude that should be showed on the map. */
private int maxLng = Integer.MIN_VALUE;
/** Minimum latitude that should be showed on the map. */
private int minLat = Integer.MAX_VALUE;
/** Minimum longitude that should be showed on the map. */
private int minLng = Integer.MAX_VALUE;
/** Vertical padding for map bounds. */
private final Float vpadding = 0.1f;
/** Bottom padding for map bounds. */
private final Float hpaddingBottom = 0.1f;
/** Top padding for map bounds. */
private final Float hpaddingTop = 0.4f;
/** Used for converting to GeoPoint integer. */
private static final int ONE_MILLION = 1000000;
/** Minimum length for contact info (email/phone). */
private static final int MINIMUM_ACCEPTED_CONTACT_INFO_LENGTH = 4;
private ContactItemizedOverlay itemizedOverlay;
/* Called when the activity is first created. */
@Override
public final void onCreate(final Bundle savedInstanceState) {
Log.d(TAG, "CloseToYou onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.closetoyou);
res = getResources();
//Setup database connection
dbh = new DatabaseAdapter(this);
dbh.open();
locationcursor = dbh.getLocations();
locationcursor.moveToFirst();
startManagingCursor(locationcursor);
//Setup the map
mapView = (MapView) findViewById(R.id.mapView);
//Create ContactItemizedOverlay for mapView
itemizedOverlay = new ContactItemizedOverlay(new ColorDrawable(), mapView);
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
mapView.setSatellite(true);
mc = mapView.getController();
|
AttentecService.setCloseToYouUpdateListener(new ServiceUpdateUIListener() {
|
at-attentec/at.attentec
|
at.attentec.com/android/at.attentec.client/src/com/attentec/ContactsActivity.java
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/AttentecService.java
// public interface ServiceUpdateUIListener {
// /** Tell UI to update. */
// void updateUI();
//
// /** End UI Activity. */
// void endActivity();
// }
|
import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.attentec.AttentecService.ServiceUpdateUIListener;
|
});
statusBarCustomMessageBlock.setOnClickListener(new OnClickListener() {
public void onClick(final View view) {
showSetCustomStatus();
}
});
//Setup database
dbh = new DatabaseAdapter(this);
dbh.open();
contactCursor = dbh.getContent(orderMode);
startManagingCursor(contactCursor);
//Now create a new list adapter bound to the cursor.
adapter = createAdapter();
setListAdapter(adapter);
ListView contactlist = (ListView) findViewById(android.R.id.list);
contactlist.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, final View v, final int position, final long id) {
showContact(id);
}
});
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/AttentecService.java
// public interface ServiceUpdateUIListener {
// /** Tell UI to update. */
// void updateUI();
//
// /** End UI Activity. */
// void endActivity();
// }
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/ContactsActivity.java
import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.attentec.AttentecService.ServiceUpdateUIListener;
});
statusBarCustomMessageBlock.setOnClickListener(new OnClickListener() {
public void onClick(final View view) {
showSetCustomStatus();
}
});
//Setup database
dbh = new DatabaseAdapter(this);
dbh.open();
contactCursor = dbh.getContent(orderMode);
startManagingCursor(contactCursor);
//Now create a new list adapter bound to the cursor.
adapter = createAdapter();
setListAdapter(adapter);
ListView contactlist = (ListView) findViewById(android.R.id.list);
contactlist.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, final View v, final int position, final long id) {
showContact(id);
}
});
|
AttentecService.setContactsUpdateListener(new ServiceUpdateUIListener() {
|
at-attentec/at.attentec
|
at.attentec.com/android/at.attentec.client/src/com/attentec/AttentecService.java
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/LocationHelper.java
// public abstract static class LocationResult {
// /**
// * Call back with the found location.
// * @param location found location
// */
// public abstract void gotLocation(Location location);
// }
//
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/Login.java
// public static class LoginException extends Exception {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * No message constructor.
// */
// public LoginException() {
//
// }
//
// /**
// * Message constructor.
// * @param description description of exception
// */
// public LoginException(final String description) {
// super(description);
// }
// }
|
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.location.Location;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import com.attentec.LocationHelper.LocationResult;
import com.attentec.Login.LoginException;
|
Log.d(TAG, "Old locUpEn: " + previousLocationUpdateEnabled + " new locUpEn: " + PreferencesHelper.getLocationUpdateEnabled(ctx));
if (PreferencesHelper.getLocationUpdateEnabled(ctx) != previousLocationUpdateEnabled) {
//remove the old notifications
mNM.cancelAll();
//show the new one
showNotification();
}
previousLocationUpdateEnabled = PreferencesHelper.getLocationUpdateEnabled(ctx);
}
/**
* Stop all recurring tasks and location updates.
*/
private void shutdownService() {
//close database connection
dbh.close();
//stop the syncing of contacts and location fetches
locationTimer.cancel();
ownLocationTimer.cancel();
contactsTimer.cancel();
//remove all notifications
mNM.cancelAll();
isAlive = false;
Intent serviceStoppedIntent = new Intent(COM_ATTENTEC_SERVICE_CHANGED_STATUS);
sendBroadcast(serviceStoppedIntent);
}
/**
* Callback connector for new location from GPS.
*/
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/LocationHelper.java
// public abstract static class LocationResult {
// /**
// * Call back with the found location.
// * @param location found location
// */
// public abstract void gotLocation(Location location);
// }
//
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/Login.java
// public static class LoginException extends Exception {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * No message constructor.
// */
// public LoginException() {
//
// }
//
// /**
// * Message constructor.
// * @param description description of exception
// */
// public LoginException(final String description) {
// super(description);
// }
// }
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/AttentecService.java
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.location.Location;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import com.attentec.LocationHelper.LocationResult;
import com.attentec.Login.LoginException;
Log.d(TAG, "Old locUpEn: " + previousLocationUpdateEnabled + " new locUpEn: " + PreferencesHelper.getLocationUpdateEnabled(ctx));
if (PreferencesHelper.getLocationUpdateEnabled(ctx) != previousLocationUpdateEnabled) {
//remove the old notifications
mNM.cancelAll();
//show the new one
showNotification();
}
previousLocationUpdateEnabled = PreferencesHelper.getLocationUpdateEnabled(ctx);
}
/**
* Stop all recurring tasks and location updates.
*/
private void shutdownService() {
//close database connection
dbh.close();
//stop the syncing of contacts and location fetches
locationTimer.cancel();
ownLocationTimer.cancel();
contactsTimer.cancel();
//remove all notifications
mNM.cancelAll();
isAlive = false;
Intent serviceStoppedIntent = new Intent(COM_ATTENTEC_SERVICE_CHANGED_STATUS);
sendBroadcast(serviceStoppedIntent);
}
/**
* Callback connector for new location from GPS.
*/
|
private LocationResult locationResult = new LocationResult() {
|
at-attentec/at.attentec
|
at.attentec.com/android/at.attentec.client/src/com/attentec/AttentecService.java
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/LocationHelper.java
// public abstract static class LocationResult {
// /**
// * Call back with the found location.
// * @param location found location
// */
// public abstract void gotLocation(Location location);
// }
//
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/Login.java
// public static class LoginException extends Exception {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * No message constructor.
// */
// public LoginException() {
//
// }
//
// /**
// * Message constructor.
// * @param description description of exception
// */
// public LoginException(final String description) {
// super(description);
// }
// }
|
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.location.Location;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import com.attentec.LocationHelper.LocationResult;
import com.attentec.Login.LoginException;
|
Date d = new Date();
SharedPreferences.Editor editor = sp.edit();
editor.putFloat("latitude", lat.floatValue());
editor.putFloat("longitude", lng.floatValue());
editor.putLong("location_updated_at", d.getTime() / DevelopmentSettings.MILLISECONDS_IN_SECOND);
editor.commit();
//check if we need to update the server
if (d.getTime() - lastUpdatedToServer < PreferencesHelper.getLocationsUpdateInterval(ctx) / 2) {
Log.d(TAG, "Not updating location to server, to soon since last time: " + (d.getTime() - lastUpdatedToServer));
return;
}
Log.d(TAG, "Updating location to server");
//get logindata for server contact
Hashtable<String, List<NameValuePair>> postdata = ServerContact.getLogin(username, phoneKey);
//add location to POST data
List<NameValuePair> locationdata = new ArrayList<NameValuePair>();
locationdata.add(new BasicNameValuePair("latitude", lat.toString()));
locationdata.add(new BasicNameValuePair("longitude", lng.toString()));
postdata.put("location", locationdata);
//send location to server
String url = "/app/app_update_user_info.json";
try {
ServerContact.postJSON(postdata, url, ctx);
|
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/LocationHelper.java
// public abstract static class LocationResult {
// /**
// * Call back with the found location.
// * @param location found location
// */
// public abstract void gotLocation(Location location);
// }
//
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/Login.java
// public static class LoginException extends Exception {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * No message constructor.
// */
// public LoginException() {
//
// }
//
// /**
// * Message constructor.
// * @param description description of exception
// */
// public LoginException(final String description) {
// super(description);
// }
// }
// Path: at.attentec.com/android/at.attentec.client/src/com/attentec/AttentecService.java
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.location.Location;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import com.attentec.LocationHelper.LocationResult;
import com.attentec.Login.LoginException;
Date d = new Date();
SharedPreferences.Editor editor = sp.edit();
editor.putFloat("latitude", lat.floatValue());
editor.putFloat("longitude", lng.floatValue());
editor.putLong("location_updated_at", d.getTime() / DevelopmentSettings.MILLISECONDS_IN_SECOND);
editor.commit();
//check if we need to update the server
if (d.getTime() - lastUpdatedToServer < PreferencesHelper.getLocationsUpdateInterval(ctx) / 2) {
Log.d(TAG, "Not updating location to server, to soon since last time: " + (d.getTime() - lastUpdatedToServer));
return;
}
Log.d(TAG, "Updating location to server");
//get logindata for server contact
Hashtable<String, List<NameValuePair>> postdata = ServerContact.getLogin(username, phoneKey);
//add location to POST data
List<NameValuePair> locationdata = new ArrayList<NameValuePair>();
locationdata.add(new BasicNameValuePair("latitude", lat.toString()));
locationdata.add(new BasicNameValuePair("longitude", lng.toString()));
postdata.put("location", locationdata);
//send location to server
String url = "/app/app_update_user_info.json";
try {
ServerContact.postJSON(postdata, url, ctx);
|
} catch (LoginException e) {
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/ui/toolWindow/details/CommentAction.java
|
// Path: src/com/jetbrains/crucible/model/Comment.java
// public class Comment {
//
// @NotNull private final User myAuthor;
// @NotNull private final String myMessage;
// private boolean myDraft;
//
// private String myLine;
// private String myReviewItemId;
// private String myPermId;
// private String myRevision;
// private Date myCreateDate = new Date();
// private final List<Comment> myReplies = new ArrayList<Comment>();
// private String myParentCommentId;
//
// public Comment(@NotNull final User commentAuthor, @NotNull final String message, boolean draft) {
// myAuthor = commentAuthor;
// myMessage = message;
// myDraft = draft;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public User getAuthor() {
// return myAuthor;
// }
//
// public Date getCreateDate() {
// return new Date(myCreateDate.getTime());
// }
//
// public void setCreateDate(Date createDate) {
// if (createDate != null) {
// myCreateDate = new Date(createDate.getTime());
// }
// }
//
// @Override
// public String toString() {
// return getMessage();
// }
//
// public String getLine() {
// return myLine;
// }
//
// public void setLine(String line) {
// myLine = line;
// }
//
// public String getReviewItemId() {
// return myReviewItemId;
// }
//
// public void setReviewItemId(String reviewItemId) {
// myReviewItemId = reviewItemId;
// }
//
// public String getRevision() {
// return myRevision;
// }
//
// public void setRevision(String revision) {
// myRevision = revision;
// }
//
// public void addReply(Comment reply) {
// myReplies.add(reply);
// }
//
// public List<Comment> getReplies() {
// return myReplies;
// }
//
// public void setParentCommentId(String parentCommentId) {
// myParentCommentId = parentCommentId;
// }
//
// public String getParentCommentId() {
// return myParentCommentId;
// }
//
// public String getPermId() {
// return myPermId;
// }
//
// public void setPermId(String id) {
// myPermId = id;
// }
//
// public boolean isDraft() {
// return myDraft;
// }
//
// public void setDraft(boolean draft) {
// myDraft = draft;
// }
// }
//
// Path: src/com/jetbrains/crucible/model/Review.java
// public class Review extends BasicReview {
// private final List<Comment> myGeneralComments = new ArrayList<Comment>();
// private final List<Comment> myComments = new ArrayList<Comment>();
//
// private final Set<ReviewItem> myItems = new HashSet<ReviewItem>();
//
// public Review(@NotNull final String id, @NotNull final User author,
// @Nullable final User moderator) {
// super(id, author, moderator);
// }
//
// public void addGeneralComment(@NotNull Comment generalComment) {
// myGeneralComments.add(generalComment);
// }
//
// public void addComment(@NotNull Comment comment) {
// myComments.add(comment);
// }
//
// @NotNull
// public List<Comment> getGeneralComments() {
// return myGeneralComments;
// }
//
// @NotNull
// public List<Comment> getComments() {
// return myComments;
// }
//
// @NotNull
// public Set<ReviewItem> getReviewItems() {
// return myItems;
// }
//
// public void addReviewItem(@NotNull final ReviewItem item) {
// myItems.add(item);
// }
//
// @Nullable
// public String getPathById(@NotNull final String id) {
// for (ReviewItem item : myItems) {
// if (item.getId().equals(id))
// return item.getPath();
// }
// return null;
// }
//
// @Nullable
// public String getIdByPath(@NotNull final String path, Project project) {
// final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();
//
// for (ReviewItem item : myItems) {
// final String repo = item.getRepo();
// final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();
// String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));
// if (FileUtil.pathsEqual(relativePath, item.getPath())) {
// return item.getId();
// }
// }
// return null;
// }
//
// public boolean isInPatch(@NotNull Comment comment) {
// final String reviewItemId = comment.getReviewItemId();
// return null != ContainerUtil.find(myItems, new Condition<ReviewItem>() {
// @Override
// public boolean value(ReviewItem item) {
// return item.getId().equalsIgnoreCase(reviewItemId) && item.isPatch();
// }
// });
// }
// }
|
import com.intellij.openapi.project.Project;
import com.jetbrains.crucible.model.Comment;
import com.jetbrains.crucible.model.Review;
import org.jetbrains.annotations.NotNull;
|
package com.jetbrains.crucible.ui.toolWindow.details;
/**
* @author Kirill Likhodedov
*/
public abstract class CommentAction {
@NotNull protected final Project myProject;
|
// Path: src/com/jetbrains/crucible/model/Comment.java
// public class Comment {
//
// @NotNull private final User myAuthor;
// @NotNull private final String myMessage;
// private boolean myDraft;
//
// private String myLine;
// private String myReviewItemId;
// private String myPermId;
// private String myRevision;
// private Date myCreateDate = new Date();
// private final List<Comment> myReplies = new ArrayList<Comment>();
// private String myParentCommentId;
//
// public Comment(@NotNull final User commentAuthor, @NotNull final String message, boolean draft) {
// myAuthor = commentAuthor;
// myMessage = message;
// myDraft = draft;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public User getAuthor() {
// return myAuthor;
// }
//
// public Date getCreateDate() {
// return new Date(myCreateDate.getTime());
// }
//
// public void setCreateDate(Date createDate) {
// if (createDate != null) {
// myCreateDate = new Date(createDate.getTime());
// }
// }
//
// @Override
// public String toString() {
// return getMessage();
// }
//
// public String getLine() {
// return myLine;
// }
//
// public void setLine(String line) {
// myLine = line;
// }
//
// public String getReviewItemId() {
// return myReviewItemId;
// }
//
// public void setReviewItemId(String reviewItemId) {
// myReviewItemId = reviewItemId;
// }
//
// public String getRevision() {
// return myRevision;
// }
//
// public void setRevision(String revision) {
// myRevision = revision;
// }
//
// public void addReply(Comment reply) {
// myReplies.add(reply);
// }
//
// public List<Comment> getReplies() {
// return myReplies;
// }
//
// public void setParentCommentId(String parentCommentId) {
// myParentCommentId = parentCommentId;
// }
//
// public String getParentCommentId() {
// return myParentCommentId;
// }
//
// public String getPermId() {
// return myPermId;
// }
//
// public void setPermId(String id) {
// myPermId = id;
// }
//
// public boolean isDraft() {
// return myDraft;
// }
//
// public void setDraft(boolean draft) {
// myDraft = draft;
// }
// }
//
// Path: src/com/jetbrains/crucible/model/Review.java
// public class Review extends BasicReview {
// private final List<Comment> myGeneralComments = new ArrayList<Comment>();
// private final List<Comment> myComments = new ArrayList<Comment>();
//
// private final Set<ReviewItem> myItems = new HashSet<ReviewItem>();
//
// public Review(@NotNull final String id, @NotNull final User author,
// @Nullable final User moderator) {
// super(id, author, moderator);
// }
//
// public void addGeneralComment(@NotNull Comment generalComment) {
// myGeneralComments.add(generalComment);
// }
//
// public void addComment(@NotNull Comment comment) {
// myComments.add(comment);
// }
//
// @NotNull
// public List<Comment> getGeneralComments() {
// return myGeneralComments;
// }
//
// @NotNull
// public List<Comment> getComments() {
// return myComments;
// }
//
// @NotNull
// public Set<ReviewItem> getReviewItems() {
// return myItems;
// }
//
// public void addReviewItem(@NotNull final ReviewItem item) {
// myItems.add(item);
// }
//
// @Nullable
// public String getPathById(@NotNull final String id) {
// for (ReviewItem item : myItems) {
// if (item.getId().equals(id))
// return item.getPath();
// }
// return null;
// }
//
// @Nullable
// public String getIdByPath(@NotNull final String path, Project project) {
// final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();
//
// for (ReviewItem item : myItems) {
// final String repo = item.getRepo();
// final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();
// String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));
// if (FileUtil.pathsEqual(relativePath, item.getPath())) {
// return item.getId();
// }
// }
// return null;
// }
//
// public boolean isInPatch(@NotNull Comment comment) {
// final String reviewItemId = comment.getReviewItemId();
// return null != ContainerUtil.find(myItems, new Condition<ReviewItem>() {
// @Override
// public boolean value(ReviewItem item) {
// return item.getId().equalsIgnoreCase(reviewItemId) && item.isPatch();
// }
// });
// }
// }
// Path: src/com/jetbrains/crucible/ui/toolWindow/details/CommentAction.java
import com.intellij.openapi.project.Project;
import com.jetbrains.crucible.model.Comment;
import com.jetbrains.crucible.model.Review;
import org.jetbrains.annotations.NotNull;
package com.jetbrains.crucible.ui.toolWindow.details;
/**
* @author Kirill Likhodedov
*/
public abstract class CommentAction {
@NotNull protected final Project myProject;
|
@NotNull protected final Review myReview;
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/ui/toolWindow/details/CommentAction.java
|
// Path: src/com/jetbrains/crucible/model/Comment.java
// public class Comment {
//
// @NotNull private final User myAuthor;
// @NotNull private final String myMessage;
// private boolean myDraft;
//
// private String myLine;
// private String myReviewItemId;
// private String myPermId;
// private String myRevision;
// private Date myCreateDate = new Date();
// private final List<Comment> myReplies = new ArrayList<Comment>();
// private String myParentCommentId;
//
// public Comment(@NotNull final User commentAuthor, @NotNull final String message, boolean draft) {
// myAuthor = commentAuthor;
// myMessage = message;
// myDraft = draft;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public User getAuthor() {
// return myAuthor;
// }
//
// public Date getCreateDate() {
// return new Date(myCreateDate.getTime());
// }
//
// public void setCreateDate(Date createDate) {
// if (createDate != null) {
// myCreateDate = new Date(createDate.getTime());
// }
// }
//
// @Override
// public String toString() {
// return getMessage();
// }
//
// public String getLine() {
// return myLine;
// }
//
// public void setLine(String line) {
// myLine = line;
// }
//
// public String getReviewItemId() {
// return myReviewItemId;
// }
//
// public void setReviewItemId(String reviewItemId) {
// myReviewItemId = reviewItemId;
// }
//
// public String getRevision() {
// return myRevision;
// }
//
// public void setRevision(String revision) {
// myRevision = revision;
// }
//
// public void addReply(Comment reply) {
// myReplies.add(reply);
// }
//
// public List<Comment> getReplies() {
// return myReplies;
// }
//
// public void setParentCommentId(String parentCommentId) {
// myParentCommentId = parentCommentId;
// }
//
// public String getParentCommentId() {
// return myParentCommentId;
// }
//
// public String getPermId() {
// return myPermId;
// }
//
// public void setPermId(String id) {
// myPermId = id;
// }
//
// public boolean isDraft() {
// return myDraft;
// }
//
// public void setDraft(boolean draft) {
// myDraft = draft;
// }
// }
//
// Path: src/com/jetbrains/crucible/model/Review.java
// public class Review extends BasicReview {
// private final List<Comment> myGeneralComments = new ArrayList<Comment>();
// private final List<Comment> myComments = new ArrayList<Comment>();
//
// private final Set<ReviewItem> myItems = new HashSet<ReviewItem>();
//
// public Review(@NotNull final String id, @NotNull final User author,
// @Nullable final User moderator) {
// super(id, author, moderator);
// }
//
// public void addGeneralComment(@NotNull Comment generalComment) {
// myGeneralComments.add(generalComment);
// }
//
// public void addComment(@NotNull Comment comment) {
// myComments.add(comment);
// }
//
// @NotNull
// public List<Comment> getGeneralComments() {
// return myGeneralComments;
// }
//
// @NotNull
// public List<Comment> getComments() {
// return myComments;
// }
//
// @NotNull
// public Set<ReviewItem> getReviewItems() {
// return myItems;
// }
//
// public void addReviewItem(@NotNull final ReviewItem item) {
// myItems.add(item);
// }
//
// @Nullable
// public String getPathById(@NotNull final String id) {
// for (ReviewItem item : myItems) {
// if (item.getId().equals(id))
// return item.getPath();
// }
// return null;
// }
//
// @Nullable
// public String getIdByPath(@NotNull final String path, Project project) {
// final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();
//
// for (ReviewItem item : myItems) {
// final String repo = item.getRepo();
// final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();
// String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));
// if (FileUtil.pathsEqual(relativePath, item.getPath())) {
// return item.getId();
// }
// }
// return null;
// }
//
// public boolean isInPatch(@NotNull Comment comment) {
// final String reviewItemId = comment.getReviewItemId();
// return null != ContainerUtil.find(myItems, new Condition<ReviewItem>() {
// @Override
// public boolean value(ReviewItem item) {
// return item.getId().equalsIgnoreCase(reviewItemId) && item.isPatch();
// }
// });
// }
// }
|
import com.intellij.openapi.project.Project;
import com.jetbrains.crucible.model.Comment;
import com.jetbrains.crucible.model.Review;
import org.jetbrains.annotations.NotNull;
|
package com.jetbrains.crucible.ui.toolWindow.details;
/**
* @author Kirill Likhodedov
*/
public abstract class CommentAction {
@NotNull protected final Project myProject;
@NotNull protected final Review myReview;
|
// Path: src/com/jetbrains/crucible/model/Comment.java
// public class Comment {
//
// @NotNull private final User myAuthor;
// @NotNull private final String myMessage;
// private boolean myDraft;
//
// private String myLine;
// private String myReviewItemId;
// private String myPermId;
// private String myRevision;
// private Date myCreateDate = new Date();
// private final List<Comment> myReplies = new ArrayList<Comment>();
// private String myParentCommentId;
//
// public Comment(@NotNull final User commentAuthor, @NotNull final String message, boolean draft) {
// myAuthor = commentAuthor;
// myMessage = message;
// myDraft = draft;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public User getAuthor() {
// return myAuthor;
// }
//
// public Date getCreateDate() {
// return new Date(myCreateDate.getTime());
// }
//
// public void setCreateDate(Date createDate) {
// if (createDate != null) {
// myCreateDate = new Date(createDate.getTime());
// }
// }
//
// @Override
// public String toString() {
// return getMessage();
// }
//
// public String getLine() {
// return myLine;
// }
//
// public void setLine(String line) {
// myLine = line;
// }
//
// public String getReviewItemId() {
// return myReviewItemId;
// }
//
// public void setReviewItemId(String reviewItemId) {
// myReviewItemId = reviewItemId;
// }
//
// public String getRevision() {
// return myRevision;
// }
//
// public void setRevision(String revision) {
// myRevision = revision;
// }
//
// public void addReply(Comment reply) {
// myReplies.add(reply);
// }
//
// public List<Comment> getReplies() {
// return myReplies;
// }
//
// public void setParentCommentId(String parentCommentId) {
// myParentCommentId = parentCommentId;
// }
//
// public String getParentCommentId() {
// return myParentCommentId;
// }
//
// public String getPermId() {
// return myPermId;
// }
//
// public void setPermId(String id) {
// myPermId = id;
// }
//
// public boolean isDraft() {
// return myDraft;
// }
//
// public void setDraft(boolean draft) {
// myDraft = draft;
// }
// }
//
// Path: src/com/jetbrains/crucible/model/Review.java
// public class Review extends BasicReview {
// private final List<Comment> myGeneralComments = new ArrayList<Comment>();
// private final List<Comment> myComments = new ArrayList<Comment>();
//
// private final Set<ReviewItem> myItems = new HashSet<ReviewItem>();
//
// public Review(@NotNull final String id, @NotNull final User author,
// @Nullable final User moderator) {
// super(id, author, moderator);
// }
//
// public void addGeneralComment(@NotNull Comment generalComment) {
// myGeneralComments.add(generalComment);
// }
//
// public void addComment(@NotNull Comment comment) {
// myComments.add(comment);
// }
//
// @NotNull
// public List<Comment> getGeneralComments() {
// return myGeneralComments;
// }
//
// @NotNull
// public List<Comment> getComments() {
// return myComments;
// }
//
// @NotNull
// public Set<ReviewItem> getReviewItems() {
// return myItems;
// }
//
// public void addReviewItem(@NotNull final ReviewItem item) {
// myItems.add(item);
// }
//
// @Nullable
// public String getPathById(@NotNull final String id) {
// for (ReviewItem item : myItems) {
// if (item.getId().equals(id))
// return item.getPath();
// }
// return null;
// }
//
// @Nullable
// public String getIdByPath(@NotNull final String path, Project project) {
// final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();
//
// for (ReviewItem item : myItems) {
// final String repo = item.getRepo();
// final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();
// String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));
// if (FileUtil.pathsEqual(relativePath, item.getPath())) {
// return item.getId();
// }
// }
// return null;
// }
//
// public boolean isInPatch(@NotNull Comment comment) {
// final String reviewItemId = comment.getReviewItemId();
// return null != ContainerUtil.find(myItems, new Condition<ReviewItem>() {
// @Override
// public boolean value(ReviewItem item) {
// return item.getId().equalsIgnoreCase(reviewItemId) && item.isPatch();
// }
// });
// }
// }
// Path: src/com/jetbrains/crucible/ui/toolWindow/details/CommentAction.java
import com.intellij.openapi.project.Project;
import com.jetbrains.crucible.model.Comment;
import com.jetbrains.crucible.model.Review;
import org.jetbrains.annotations.NotNull;
package com.jetbrains.crucible.ui.toolWindow.details;
/**
* @author Kirill Likhodedov
*/
public abstract class CommentAction {
@NotNull protected final Project myProject;
@NotNull protected final Review myReview;
|
@NotNull protected final Comment myComment;
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/ui/toolWindow/details/GeneralCommentsTree.java
|
// Path: src/com/jetbrains/crucible/model/Comment.java
// public class Comment {
//
// @NotNull private final User myAuthor;
// @NotNull private final String myMessage;
// private boolean myDraft;
//
// private String myLine;
// private String myReviewItemId;
// private String myPermId;
// private String myRevision;
// private Date myCreateDate = new Date();
// private final List<Comment> myReplies = new ArrayList<Comment>();
// private String myParentCommentId;
//
// public Comment(@NotNull final User commentAuthor, @NotNull final String message, boolean draft) {
// myAuthor = commentAuthor;
// myMessage = message;
// myDraft = draft;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public User getAuthor() {
// return myAuthor;
// }
//
// public Date getCreateDate() {
// return new Date(myCreateDate.getTime());
// }
//
// public void setCreateDate(Date createDate) {
// if (createDate != null) {
// myCreateDate = new Date(createDate.getTime());
// }
// }
//
// @Override
// public String toString() {
// return getMessage();
// }
//
// public String getLine() {
// return myLine;
// }
//
// public void setLine(String line) {
// myLine = line;
// }
//
// public String getReviewItemId() {
// return myReviewItemId;
// }
//
// public void setReviewItemId(String reviewItemId) {
// myReviewItemId = reviewItemId;
// }
//
// public String getRevision() {
// return myRevision;
// }
//
// public void setRevision(String revision) {
// myRevision = revision;
// }
//
// public void addReply(Comment reply) {
// myReplies.add(reply);
// }
//
// public List<Comment> getReplies() {
// return myReplies;
// }
//
// public void setParentCommentId(String parentCommentId) {
// myParentCommentId = parentCommentId;
// }
//
// public String getParentCommentId() {
// return myParentCommentId;
// }
//
// public String getPermId() {
// return myPermId;
// }
//
// public void setPermId(String id) {
// myPermId = id;
// }
//
// public boolean isDraft() {
// return myDraft;
// }
//
// public void setDraft(boolean draft) {
// myDraft = draft;
// }
// }
//
// Path: src/com/jetbrains/crucible/model/Review.java
// public class Review extends BasicReview {
// private final List<Comment> myGeneralComments = new ArrayList<Comment>();
// private final List<Comment> myComments = new ArrayList<Comment>();
//
// private final Set<ReviewItem> myItems = new HashSet<ReviewItem>();
//
// public Review(@NotNull final String id, @NotNull final User author,
// @Nullable final User moderator) {
// super(id, author, moderator);
// }
//
// public void addGeneralComment(@NotNull Comment generalComment) {
// myGeneralComments.add(generalComment);
// }
//
// public void addComment(@NotNull Comment comment) {
// myComments.add(comment);
// }
//
// @NotNull
// public List<Comment> getGeneralComments() {
// return myGeneralComments;
// }
//
// @NotNull
// public List<Comment> getComments() {
// return myComments;
// }
//
// @NotNull
// public Set<ReviewItem> getReviewItems() {
// return myItems;
// }
//
// public void addReviewItem(@NotNull final ReviewItem item) {
// myItems.add(item);
// }
//
// @Nullable
// public String getPathById(@NotNull final String id) {
// for (ReviewItem item : myItems) {
// if (item.getId().equals(id))
// return item.getPath();
// }
// return null;
// }
//
// @Nullable
// public String getIdByPath(@NotNull final String path, Project project) {
// final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();
//
// for (ReviewItem item : myItems) {
// final String repo = item.getRepo();
// final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();
// String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));
// if (FileUtil.pathsEqual(relativePath, item.getPath())) {
// return item.getId();
// }
// }
// return null;
// }
//
// public boolean isInPatch(@NotNull Comment comment) {
// final String reviewItemId = comment.getReviewItemId();
// return null != ContainerUtil.find(myItems, new Condition<ReviewItem>() {
// @Override
// public boolean value(ReviewItem item) {
// return item.getId().equalsIgnoreCase(reviewItemId) && item.isPatch();
// }
// });
// }
// }
|
import com.intellij.openapi.project.Project;
import com.jetbrains.crucible.model.Comment;
import com.jetbrains.crucible.model.Review;
import org.jetbrains.annotations.NotNull;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
|
package com.jetbrains.crucible.ui.toolWindow.details;
/**
* @author Kirill Likhodedov
*/
public class GeneralCommentsTree extends CommentsTree {
public GeneralCommentsTree(@NotNull Project project, @NotNull Review review, @NotNull DefaultTreeModel model) {
super(project, review, model, null, null);
}
@NotNull
public static CommentsTree create(@NotNull Project project, @NotNull final Review review) {
DefaultTreeModel model = createModel(review);
GeneralCommentsTree tree = new GeneralCommentsTree(project, review, model);
tree.setRootVisible(false);
return tree;
}
private static DefaultTreeModel createModel(Review review) {
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
DefaultTreeModel model = new DefaultTreeModel(rootNode);
|
// Path: src/com/jetbrains/crucible/model/Comment.java
// public class Comment {
//
// @NotNull private final User myAuthor;
// @NotNull private final String myMessage;
// private boolean myDraft;
//
// private String myLine;
// private String myReviewItemId;
// private String myPermId;
// private String myRevision;
// private Date myCreateDate = new Date();
// private final List<Comment> myReplies = new ArrayList<Comment>();
// private String myParentCommentId;
//
// public Comment(@NotNull final User commentAuthor, @NotNull final String message, boolean draft) {
// myAuthor = commentAuthor;
// myMessage = message;
// myDraft = draft;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public User getAuthor() {
// return myAuthor;
// }
//
// public Date getCreateDate() {
// return new Date(myCreateDate.getTime());
// }
//
// public void setCreateDate(Date createDate) {
// if (createDate != null) {
// myCreateDate = new Date(createDate.getTime());
// }
// }
//
// @Override
// public String toString() {
// return getMessage();
// }
//
// public String getLine() {
// return myLine;
// }
//
// public void setLine(String line) {
// myLine = line;
// }
//
// public String getReviewItemId() {
// return myReviewItemId;
// }
//
// public void setReviewItemId(String reviewItemId) {
// myReviewItemId = reviewItemId;
// }
//
// public String getRevision() {
// return myRevision;
// }
//
// public void setRevision(String revision) {
// myRevision = revision;
// }
//
// public void addReply(Comment reply) {
// myReplies.add(reply);
// }
//
// public List<Comment> getReplies() {
// return myReplies;
// }
//
// public void setParentCommentId(String parentCommentId) {
// myParentCommentId = parentCommentId;
// }
//
// public String getParentCommentId() {
// return myParentCommentId;
// }
//
// public String getPermId() {
// return myPermId;
// }
//
// public void setPermId(String id) {
// myPermId = id;
// }
//
// public boolean isDraft() {
// return myDraft;
// }
//
// public void setDraft(boolean draft) {
// myDraft = draft;
// }
// }
//
// Path: src/com/jetbrains/crucible/model/Review.java
// public class Review extends BasicReview {
// private final List<Comment> myGeneralComments = new ArrayList<Comment>();
// private final List<Comment> myComments = new ArrayList<Comment>();
//
// private final Set<ReviewItem> myItems = new HashSet<ReviewItem>();
//
// public Review(@NotNull final String id, @NotNull final User author,
// @Nullable final User moderator) {
// super(id, author, moderator);
// }
//
// public void addGeneralComment(@NotNull Comment generalComment) {
// myGeneralComments.add(generalComment);
// }
//
// public void addComment(@NotNull Comment comment) {
// myComments.add(comment);
// }
//
// @NotNull
// public List<Comment> getGeneralComments() {
// return myGeneralComments;
// }
//
// @NotNull
// public List<Comment> getComments() {
// return myComments;
// }
//
// @NotNull
// public Set<ReviewItem> getReviewItems() {
// return myItems;
// }
//
// public void addReviewItem(@NotNull final ReviewItem item) {
// myItems.add(item);
// }
//
// @Nullable
// public String getPathById(@NotNull final String id) {
// for (ReviewItem item : myItems) {
// if (item.getId().equals(id))
// return item.getPath();
// }
// return null;
// }
//
// @Nullable
// public String getIdByPath(@NotNull final String path, Project project) {
// final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();
//
// for (ReviewItem item : myItems) {
// final String repo = item.getRepo();
// final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();
// String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));
// if (FileUtil.pathsEqual(relativePath, item.getPath())) {
// return item.getId();
// }
// }
// return null;
// }
//
// public boolean isInPatch(@NotNull Comment comment) {
// final String reviewItemId = comment.getReviewItemId();
// return null != ContainerUtil.find(myItems, new Condition<ReviewItem>() {
// @Override
// public boolean value(ReviewItem item) {
// return item.getId().equalsIgnoreCase(reviewItemId) && item.isPatch();
// }
// });
// }
// }
// Path: src/com/jetbrains/crucible/ui/toolWindow/details/GeneralCommentsTree.java
import com.intellij.openapi.project.Project;
import com.jetbrains.crucible.model.Comment;
import com.jetbrains.crucible.model.Review;
import org.jetbrains.annotations.NotNull;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
package com.jetbrains.crucible.ui.toolWindow.details;
/**
* @author Kirill Likhodedov
*/
public class GeneralCommentsTree extends CommentsTree {
public GeneralCommentsTree(@NotNull Project project, @NotNull Review review, @NotNull DefaultTreeModel model) {
super(project, review, model, null, null);
}
@NotNull
public static CommentsTree create(@NotNull Project project, @NotNull final Review review) {
DefaultTreeModel model = createModel(review);
GeneralCommentsTree tree = new GeneralCommentsTree(project, review, model);
tree.setRootVisible(false);
return tree;
}
private static DefaultTreeModel createModel(Review review) {
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode();
DefaultTreeModel model = new DefaultTreeModel(rootNode);
|
for (Comment comment : review.getGeneralComments()) {
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/ui/toolWindow/CrucibleToolWindowFactory.java
|
// Path: src/com/jetbrains/crucible/utils/CrucibleBundle.java
// public class CrucibleBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "com.jetbrains.crucible.utils.CrucibleBundle";
//
// private CrucibleBundle() {}
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE)String key, Object... params) {
// return AbstractBundle.message(getBundle(), key, params);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) bundle = ourBundle.get();
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
|
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.jetbrains.crucible.utils.CrucibleBundle;
|
package com.jetbrains.crucible.ui.toolWindow;
/**
* User: ktisha
*/
public class CrucibleToolWindowFactory implements ToolWindowFactory, DumbAware {
@Override
public void createToolWindowContent(Project project, ToolWindow toolWindow) {
final ContentManager contentManager = toolWindow.getContentManager();
final CruciblePanel cruciblePanel = new CruciblePanel(project);
final Content content = ContentFactory.SERVICE.getInstance().
|
// Path: src/com/jetbrains/crucible/utils/CrucibleBundle.java
// public class CrucibleBundle {
// private static Reference<ResourceBundle> ourBundle;
//
// @NonNls
// private static final String BUNDLE = "com.jetbrains.crucible.utils.CrucibleBundle";
//
// private CrucibleBundle() {}
//
// public static String message(@PropertyKey(resourceBundle = BUNDLE)String key, Object... params) {
// return AbstractBundle.message(getBundle(), key, params);
// }
//
// private static ResourceBundle getBundle() {
// ResourceBundle bundle = null;
// if (ourBundle != null) bundle = ourBundle.get();
// if (bundle == null) {
// bundle = ResourceBundle.getBundle(BUNDLE);
// ourBundle = new SoftReference<ResourceBundle>(bundle);
// }
// return bundle;
// }
// }
// Path: src/com/jetbrains/crucible/ui/toolWindow/CrucibleToolWindowFactory.java
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.jetbrains.crucible.utils.CrucibleBundle;
package com.jetbrains.crucible.ui.toolWindow;
/**
* User: ktisha
*/
public class CrucibleToolWindowFactory implements ToolWindowFactory, DumbAware {
@Override
public void createToolWindowContent(Project project, ToolWindow toolWindow) {
final ContentManager contentManager = toolWindow.getContentManager();
final CruciblePanel cruciblePanel = new CruciblePanel(project);
final Content content = ContentFactory.SERVICE.getInstance().
|
createContent(cruciblePanel, CrucibleBundle.message("crucible.main.name"), false);
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/connection/CrucibleSession.java
|
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiLoginException.java
// public class CrucibleApiLoginException extends CrucibleApiException {
//
// public CrucibleApiLoginException(String message) {
// super(message);
// }
//
// public CrucibleApiLoginException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
|
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiLoginException;
import com.jetbrains.crucible.model.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
|
package com.jetbrains.crucible.connection;
/**
* User : ktisha
*/
public interface CrucibleSession {
String REVIEW_SERVICE = "/rest-service/reviews-v1";
String REVIEW_ITEMS = "/reviewitems";
String DETAIL_REVIEW_INFO = "/details";
String VERSION = "/versionInfo";
String AUTH_SERVICE = "/rest-service/auth-v1";
String LOGIN = "/login";
String FILTERED_REVIEWS = "/filter";
String COMMENTS = "/comments";
String REPLIES = "/replies";
String REPOSITORIES = "/rest-service/repositories-v1";
String COMPLETE = "/complete";
String PUBLISH = "/publish";
|
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiLoginException.java
// public class CrucibleApiLoginException extends CrucibleApiException {
//
// public CrucibleApiLoginException(String message) {
// super(message);
// }
//
// public CrucibleApiLoginException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
// Path: src/com/jetbrains/crucible/connection/CrucibleSession.java
import com.intellij.openapi.vfs.VirtualFile;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiLoginException;
import com.jetbrains.crucible.model.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
package com.jetbrains.crucible.connection;
/**
* User : ktisha
*/
public interface CrucibleSession {
String REVIEW_SERVICE = "/rest-service/reviews-v1";
String REVIEW_ITEMS = "/reviewitems";
String DETAIL_REVIEW_INFO = "/details";
String VERSION = "/versionInfo";
String AUTH_SERVICE = "/rest-service/auth-v1";
String LOGIN = "/login";
String FILTERED_REVIEWS = "/filter";
String COMMENTS = "/comments";
String REPLIES = "/replies";
String REPOSITORIES = "/rest-service/repositories-v1";
String COMPLETE = "/complete";
String PUBLISH = "/publish";
|
void login() throws CrucibleApiLoginException;
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/model/Review.java
|
// Path: src/com/jetbrains/crucible/connection/CrucibleManager.java
// public class CrucibleManager {
// private final Project myProject;
// private final Map<String, CrucibleSession> mySessions = new HashMap<String, CrucibleSession>();
//
// private static final Logger LOG = Logger.getInstance(CrucibleManager.class.getName());
//
// // implicitly constructed by pico container
// @SuppressWarnings("UnusedDeclaration")
// private CrucibleManager(@NotNull final Project project) {
// myProject = project;
// }
//
// public static CrucibleManager getInstance(@NotNull final Project project) {
// return ServiceManager.getService(project, CrucibleManager.class);
// }
//
// @Nullable
// public List<BasicReview> getReviewsForFilter(@NotNull final CrucibleFilter filter) {
// try {
// final CrucibleSession session = getSession();
// if (session != null) {
// return session.getReviewsForFilter(filter);
// }
// }
// catch (IOException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
// }
// catch (CrucibleApiException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
// }
// return null;
// }
//
// @Nullable
// public Review getDetailsForReview(@NotNull final String permId) {
// try {
// final CrucibleSession session = getSession();
// if (session != null) {
// return session.getDetailsForReview(permId);
// }
// }
// catch (CrucibleApiException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
//
// }
// catch (IOException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
// }
// return null;
// }
//
// @Nullable
// public Comment postComment(@NotNull final Comment comment, boolean isGeneral, String reviewId) {
// try {
// final CrucibleSession session = getSession();
// if (session != null) {
// return session.postComment(comment, isGeneral, reviewId);
// }
// }
// catch (CrucibleApiException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
// }
// return null;
// }
//
// public void completeReview(String reviewId) {
// try {
// final CrucibleSession session = getSession();
// if (session != null) {
// session.completeReview(reviewId);
// }
// }
// catch (CrucibleApiException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
// }
// }
//
// @Nullable
// public CrucibleSession getSession() throws CrucibleApiException {
// final CrucibleSettings crucibleSettings = CrucibleSettings.getInstance();
// final String serverUrl = crucibleSettings.SERVER_URL;
// final String username = crucibleSettings.USERNAME;
// if (StringUtil.isEmptyOrSpaces(serverUrl) || StringUtil.isEmptyOrSpaces(username)) {
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.define.host.username"), MessageType.ERROR);
// return null;
// }
// try {
// new URL(serverUrl);
// }
// catch (MalformedURLException e) {
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.wrong.host"), MessageType.ERROR);
// return null;
// }
// String key = serverUrl + username + crucibleSettings.getPassword();
// CrucibleSession session = mySessions.get(key);
// if (session == null) {
// session = new CrucibleSessionImpl(myProject);
// session.login();
// mySessions.put(key, session);
// try {
// session.fillRepoHash();
// }
// catch (IOException e) {
// LOG.warn(e.getMessage());
// }
// }
// return session;
// }
//
// public Map<String,VirtualFile> getRepoHash() {
// try {
// final CrucibleSession session = getSession();
// if (session != null) {
// return session.getRepoHash();
// }
// }
// catch (CrucibleApiException e) {
// LOG.warn(e.getMessage());
// }
// return Collections.emptyMap();
// }
//
// public void publishComment(@NotNull Review review, @NotNull Comment comment) throws IOException, CrucibleApiException {
// CrucibleSession session = getSession();
// if (session != null) {
// session.publishComment(review, comment);
// }
// }
// }
|
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.crucible.connection.CrucibleManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
|
@NotNull
public List<Comment> getGeneralComments() {
return myGeneralComments;
}
@NotNull
public List<Comment> getComments() {
return myComments;
}
@NotNull
public Set<ReviewItem> getReviewItems() {
return myItems;
}
public void addReviewItem(@NotNull final ReviewItem item) {
myItems.add(item);
}
@Nullable
public String getPathById(@NotNull final String id) {
for (ReviewItem item : myItems) {
if (item.getId().equals(id))
return item.getPath();
}
return null;
}
@Nullable
public String getIdByPath(@NotNull final String path, Project project) {
|
// Path: src/com/jetbrains/crucible/connection/CrucibleManager.java
// public class CrucibleManager {
// private final Project myProject;
// private final Map<String, CrucibleSession> mySessions = new HashMap<String, CrucibleSession>();
//
// private static final Logger LOG = Logger.getInstance(CrucibleManager.class.getName());
//
// // implicitly constructed by pico container
// @SuppressWarnings("UnusedDeclaration")
// private CrucibleManager(@NotNull final Project project) {
// myProject = project;
// }
//
// public static CrucibleManager getInstance(@NotNull final Project project) {
// return ServiceManager.getService(project, CrucibleManager.class);
// }
//
// @Nullable
// public List<BasicReview> getReviewsForFilter(@NotNull final CrucibleFilter filter) {
// try {
// final CrucibleSession session = getSession();
// if (session != null) {
// return session.getReviewsForFilter(filter);
// }
// }
// catch (IOException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
// }
// catch (CrucibleApiException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
// }
// return null;
// }
//
// @Nullable
// public Review getDetailsForReview(@NotNull final String permId) {
// try {
// final CrucibleSession session = getSession();
// if (session != null) {
// return session.getDetailsForReview(permId);
// }
// }
// catch (CrucibleApiException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
//
// }
// catch (IOException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
// }
// return null;
// }
//
// @Nullable
// public Comment postComment(@NotNull final Comment comment, boolean isGeneral, String reviewId) {
// try {
// final CrucibleSession session = getSession();
// if (session != null) {
// return session.postComment(comment, isGeneral, reviewId);
// }
// }
// catch (CrucibleApiException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
// }
// return null;
// }
//
// public void completeReview(String reviewId) {
// try {
// final CrucibleSession session = getSession();
// if (session != null) {
// session.completeReview(reviewId);
// }
// }
// catch (CrucibleApiException e) {
// LOG.warn(e.getMessage());
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.connection.error.message.$0", e.getMessage()), MessageType.ERROR);
// }
// }
//
// @Nullable
// public CrucibleSession getSession() throws CrucibleApiException {
// final CrucibleSettings crucibleSettings = CrucibleSettings.getInstance();
// final String serverUrl = crucibleSettings.SERVER_URL;
// final String username = crucibleSettings.USERNAME;
// if (StringUtil.isEmptyOrSpaces(serverUrl) || StringUtil.isEmptyOrSpaces(username)) {
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.define.host.username"), MessageType.ERROR);
// return null;
// }
// try {
// new URL(serverUrl);
// }
// catch (MalformedURLException e) {
// UiUtils.showBalloon(myProject, CrucibleBundle.message("crucible.wrong.host"), MessageType.ERROR);
// return null;
// }
// String key = serverUrl + username + crucibleSettings.getPassword();
// CrucibleSession session = mySessions.get(key);
// if (session == null) {
// session = new CrucibleSessionImpl(myProject);
// session.login();
// mySessions.put(key, session);
// try {
// session.fillRepoHash();
// }
// catch (IOException e) {
// LOG.warn(e.getMessage());
// }
// }
// return session;
// }
//
// public Map<String,VirtualFile> getRepoHash() {
// try {
// final CrucibleSession session = getSession();
// if (session != null) {
// return session.getRepoHash();
// }
// }
// catch (CrucibleApiException e) {
// LOG.warn(e.getMessage());
// }
// return Collections.emptyMap();
// }
//
// public void publishComment(@NotNull Review review, @NotNull Comment comment) throws IOException, CrucibleApiException {
// CrucibleSession session = getSession();
// if (session != null) {
// session.publishComment(review, comment);
// }
// }
// }
// Path: src/com/jetbrains/crucible/model/Review.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import com.jetbrains.crucible.connection.CrucibleManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
@NotNull
public List<Comment> getGeneralComments() {
return myGeneralComments;
}
@NotNull
public List<Comment> getComments() {
return myComments;
}
@NotNull
public Set<ReviewItem> getReviewItems() {
return myItems;
}
public void addReviewItem(@NotNull final ReviewItem item) {
myItems.add(item);
}
@Nullable
public String getPathById(@NotNull final String id) {
for (ReviewItem item : myItems) {
if (item.getId().equals(id))
return item.getPath();
}
return null;
}
@Nullable
public String getIdByPath(@NotNull final String path, Project project) {
|
final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/configuration/CrucibleConfigurable.java
|
// Path: src/com/jetbrains/crucible/connection/CrucibleTestConnectionTask.java
// public class CrucibleTestConnectionTask extends Task.Modal {
// private static final int CHECK_CANCEL_INTERVAL = 500;
// private static final Logger LOG = Logger.getInstance(CrucibleTestConnectionTask.class.getName());
//
// public CrucibleTestConnectionTask(@Nullable Project project) {
// super(project, "Testing Connection", true);
// setCancelText("Stop");
// }
//
// @Override
// public void run(@NotNull ProgressIndicator indicator) {
// indicator.setText("Connecting...");
// indicator.setFraction(0);
// indicator.setIndeterminate(true);
//
// final CrucibleTestConnector connector = new CrucibleTestConnector(myProject);
// connector.run();
//
// while (connector.getConnectionState() == CrucibleTestConnector.ConnectionState.NOT_FINISHED) {
// try {
// if (indicator.isCanceled()) {
// connector.setInterrupted();
// break;
// }
// else {
// Thread.sleep(CHECK_CANCEL_INTERVAL);
// }
// }
// catch (InterruptedException e) {
// LOG.info(e.getMessage());
// }
// }
//
// CrucibleTestConnector.ConnectionState state = connector.getConnectionState();
// switch (state) {
// case FAILED:
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// Messages.showDialog(myProject, "Reason: " + connector.getErrorMessage(), "Connection Failed", new String[]{"Ok"}, 0, null);
// }
// });
// break;
// case INTERRUPTED:
// LOG.debug("'Test Connection' canceled");
// break;
// case SUCCEEDED:
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// Messages.showDialog(myProject, "Connected successfully", "Connection OK", new String[]{"Ok"}, 0, null);
// }
// });
// break;
// default: //NOT_FINISHED:
// LOG.warn("Unexpected 'Test Connection' state: "
// + connector.getConnectionState().toString());
// }
// }
// }
|
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.text.StringUtil;
import com.jetbrains.crucible.connection.CrucibleTestConnectionTask;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
|
package com.jetbrains.crucible.configuration;
/**
* User: ktisha
*/
public class CrucibleConfigurable implements SearchableConfigurable {
private JPanel myMainPanel;
private JTextField myServerField;
private JTextField myUsernameField;
private JPasswordField myPasswordField;
private JButton myTestButton;
private final CrucibleSettings myCrucibleSettings;
private static final String DEFAULT_PASSWORD_TEXT = "************";
private boolean myPasswordModified;
public CrucibleConfigurable() {
myCrucibleSettings = CrucibleSettings.getInstance();
myTestButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveSettings();
|
// Path: src/com/jetbrains/crucible/connection/CrucibleTestConnectionTask.java
// public class CrucibleTestConnectionTask extends Task.Modal {
// private static final int CHECK_CANCEL_INTERVAL = 500;
// private static final Logger LOG = Logger.getInstance(CrucibleTestConnectionTask.class.getName());
//
// public CrucibleTestConnectionTask(@Nullable Project project) {
// super(project, "Testing Connection", true);
// setCancelText("Stop");
// }
//
// @Override
// public void run(@NotNull ProgressIndicator indicator) {
// indicator.setText("Connecting...");
// indicator.setFraction(0);
// indicator.setIndeterminate(true);
//
// final CrucibleTestConnector connector = new CrucibleTestConnector(myProject);
// connector.run();
//
// while (connector.getConnectionState() == CrucibleTestConnector.ConnectionState.NOT_FINISHED) {
// try {
// if (indicator.isCanceled()) {
// connector.setInterrupted();
// break;
// }
// else {
// Thread.sleep(CHECK_CANCEL_INTERVAL);
// }
// }
// catch (InterruptedException e) {
// LOG.info(e.getMessage());
// }
// }
//
// CrucibleTestConnector.ConnectionState state = connector.getConnectionState();
// switch (state) {
// case FAILED:
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// Messages.showDialog(myProject, "Reason: " + connector.getErrorMessage(), "Connection Failed", new String[]{"Ok"}, 0, null);
// }
// });
// break;
// case INTERRUPTED:
// LOG.debug("'Test Connection' canceled");
// break;
// case SUCCEEDED:
// EventQueue.invokeLater(new Runnable() {
// public void run() {
// Messages.showDialog(myProject, "Connected successfully", "Connection OK", new String[]{"Ok"}, 0, null);
// }
// });
// break;
// default: //NOT_FINISHED:
// LOG.warn("Unexpected 'Test Connection' state: "
// + connector.getConnectionState().toString());
// }
// }
// }
// Path: src/com/jetbrains/crucible/configuration/CrucibleConfigurable.java
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.text.StringUtil;
import com.jetbrains.crucible.connection.CrucibleTestConnectionTask;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
package com.jetbrains.crucible.configuration;
/**
* User: ktisha
*/
public class CrucibleConfigurable implements SearchableConfigurable {
private JPanel myMainPanel;
private JTextField myServerField;
private JTextField myUsernameField;
private JPasswordField myPasswordField;
private JButton myTestButton;
private final CrucibleSettings myCrucibleSettings;
private static final String DEFAULT_PASSWORD_TEXT = "************";
private boolean myPasswordModified;
public CrucibleConfigurable() {
myCrucibleSettings = CrucibleSettings.getInstance();
myTestButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveSettings();
|
final Task.Modal testConnectionTask = new CrucibleTestConnectionTask(ProjectManager.getInstance().getDefaultProject());
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/model/ReviewItem.java
|
// Path: src/com/jetbrains/crucible/vcs/VcsUtils.java
// public class VcsUtils {
//
// private VcsUtils() {
// }
//
// @Nullable
// public static CommittedChangeList loadRevisions(@NotNull final Project project, final VcsRevisionNumber number, final FilePath filePath) {
// final CommittedChangeList[] list = new CommittedChangeList[1];
// final ThrowableRunnable<VcsException> runnable = () -> {
// final AbstractVcs vcs = VcsUtil.getVcsFor(project, filePath);
//
// if (vcs == null) {
// return;
// }
//
// list[0] = vcs.loadRevisions(filePath.getVirtualFile(), number);
// };
//
// final boolean success = VcsSynchronousProgressWrapper.wrap(runnable, project, "Load Revision Contents");
//
// return success ? list[0] : null;
// }
// }
|
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.jetbrains.crucible.vcs.VcsUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
|
package com.jetbrains.crucible.model;
/**
*
* User : ktisha
*/
public class ReviewItem {
private String myId;
private String myPath;
private String myRepo;
private Set<String> myRevisions = new HashSet<String>();
public ReviewItem(@NotNull final String id, @NotNull final String path, @Nullable final String repo) {
myId = id;
myPath = path;
myRepo = repo;
}
@NotNull
public List<CommittedChangeList> loadChangeLists(@NotNull Project project, @NotNull AbstractVcs vcsFor,
@NotNull Set<String> loadedRevisions, FilePath path) throws VcsException {
final Set<String> revisions = getRevisions();
List<CommittedChangeList> changeLists = new ArrayList<CommittedChangeList>();
for (String revision : revisions) {
if (!loadedRevisions.contains(revision)) {
final VcsRevisionNumber revisionNumber = vcsFor.parseRevisionNumber(revision);
if (revisionNumber != null) {
|
// Path: src/com/jetbrains/crucible/vcs/VcsUtils.java
// public class VcsUtils {
//
// private VcsUtils() {
// }
//
// @Nullable
// public static CommittedChangeList loadRevisions(@NotNull final Project project, final VcsRevisionNumber number, final FilePath filePath) {
// final CommittedChangeList[] list = new CommittedChangeList[1];
// final ThrowableRunnable<VcsException> runnable = () -> {
// final AbstractVcs vcs = VcsUtil.getVcsFor(project, filePath);
//
// if (vcs == null) {
// return;
// }
//
// list[0] = vcs.loadRevisions(filePath.getVirtualFile(), number);
// };
//
// final boolean success = VcsSynchronousProgressWrapper.wrap(runnable, project, "Load Revision Contents");
//
// return success ? list[0] : null;
// }
// }
// Path: src/com/jetbrains/crucible/model/ReviewItem.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.jetbrains.crucible.vcs.VcsUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
package com.jetbrains.crucible.model;
/**
*
* User : ktisha
*/
public class ReviewItem {
private String myId;
private String myPath;
private String myRepo;
private Set<String> myRevisions = new HashSet<String>();
public ReviewItem(@NotNull final String id, @NotNull final String path, @Nullable final String repo) {
myId = id;
myPath = path;
myRepo = repo;
}
@NotNull
public List<CommittedChangeList> loadChangeLists(@NotNull Project project, @NotNull AbstractVcs vcsFor,
@NotNull Set<String> loadedRevisions, FilePath path) throws VcsException {
final Set<String> revisions = getRevisions();
List<CommittedChangeList> changeLists = new ArrayList<CommittedChangeList>();
for (String revision : revisions) {
if (!loadedRevisions.contains(revision)) {
final VcsRevisionNumber revisionNumber = vcsFor.parseRevisionNumber(revision);
if (revisionNumber != null) {
|
final CommittedChangeList changeList = VcsUtils.loadRevisions(project, revisionNumber, path);
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/connection/CrucibleSessionImpl.java
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiLoginException.java
// public class CrucibleApiLoginException extends CrucibleApiException {
//
// public CrucibleApiLoginException(String message) {
// super(message);
// }
//
// public CrucibleApiLoginException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/UiUtils.java
// public class UiUtils {
// private UiUtils() {
// }
//
// public static void showBalloon(@NotNull final Project project, @NotNull final String message,
// @NotNull final MessageType messageType) {
// final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
// if (frame == null) return;
// final JComponent component = frame.getRootPane();
// if (component == null) return;
// final Rectangle rect = component.getVisibleRect();
// final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
// final RelativePoint point = new RelativePoint(component, p);
//
// final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().
// createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
// messageType.getPopupBackground(), null);
// balloonBuilder.setShowCallout(false).setCloseButtonEnabled(true)
// .createBalloon().show(point, Balloon.Position.atLeft);
// }
// }
|
import com.google.gson.*;
import com.intellij.dvcs.repo.VcsRepositoryManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.SLRUCache;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiLoginException;
import com.jetbrains.crucible.model.*;
import com.jetbrains.crucible.ui.UiUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
|
@NotNull
@Override
public String createValue(String relativeUrl) {
return doDownloadFile(relativeUrl);
}
private String doDownloadFile(String relativeUrl) {
String url = getHostUrl() + relativeUrl;
final GetMethod method = new GetMethod(url);
try {
executeHttpMethod(method);
return method.getResponseBodyAsString();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
};
public CrucibleSessionImpl(@NotNull final Project project) {
myProject = project;
initSSLCertPolicy();
}
private void initSSLCertPolicy() {
EasySSLProtocolSocketFactory secureProtocolSocketFactory = new EasySSLProtocolSocketFactory();
Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)secureProtocolSocketFactory, 443));
}
@Override
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiLoginException.java
// public class CrucibleApiLoginException extends CrucibleApiException {
//
// public CrucibleApiLoginException(String message) {
// super(message);
// }
//
// public CrucibleApiLoginException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/UiUtils.java
// public class UiUtils {
// private UiUtils() {
// }
//
// public static void showBalloon(@NotNull final Project project, @NotNull final String message,
// @NotNull final MessageType messageType) {
// final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
// if (frame == null) return;
// final JComponent component = frame.getRootPane();
// if (component == null) return;
// final Rectangle rect = component.getVisibleRect();
// final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
// final RelativePoint point = new RelativePoint(component, p);
//
// final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().
// createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
// messageType.getPopupBackground(), null);
// balloonBuilder.setShowCallout(false).setCloseButtonEnabled(true)
// .createBalloon().show(point, Balloon.Position.atLeft);
// }
// }
// Path: src/com/jetbrains/crucible/connection/CrucibleSessionImpl.java
import com.google.gson.*;
import com.intellij.dvcs.repo.VcsRepositoryManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.SLRUCache;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiLoginException;
import com.jetbrains.crucible.model.*;
import com.jetbrains.crucible.ui.UiUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
@NotNull
@Override
public String createValue(String relativeUrl) {
return doDownloadFile(relativeUrl);
}
private String doDownloadFile(String relativeUrl) {
String url = getHostUrl() + relativeUrl;
final GetMethod method = new GetMethod(url);
try {
executeHttpMethod(method);
return method.getResponseBodyAsString();
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
};
public CrucibleSessionImpl(@NotNull final Project project) {
myProject = project;
initSSLCertPolicy();
}
private void initSSLCertPolicy() {
EasySSLProtocolSocketFactory secureProtocolSocketFactory = new EasySSLProtocolSocketFactory();
Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)secureProtocolSocketFactory, 443));
}
@Override
|
public void login() throws CrucibleApiLoginException {
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/connection/CrucibleSessionImpl.java
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiLoginException.java
// public class CrucibleApiLoginException extends CrucibleApiException {
//
// public CrucibleApiLoginException(String message) {
// super(message);
// }
//
// public CrucibleApiLoginException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/UiUtils.java
// public class UiUtils {
// private UiUtils() {
// }
//
// public static void showBalloon(@NotNull final Project project, @NotNull final String message,
// @NotNull final MessageType messageType) {
// final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
// if (frame == null) return;
// final JComponent component = frame.getRootPane();
// if (component == null) return;
// final Rectangle rect = component.getVisibleRect();
// final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
// final RelativePoint point = new RelativePoint(component, p);
//
// final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().
// createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
// messageType.getPopupBackground(), null);
// balloonBuilder.setShowCallout(false).setCloseButtonEnabled(true)
// .createBalloon().show(point, Balloon.Position.atLeft);
// }
// }
|
import com.google.gson.*;
import com.intellij.dvcs.repo.VcsRepositoryManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.SLRUCache;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiLoginException;
import com.jetbrains.crucible.model.*;
import com.jetbrains.crucible.ui.UiUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
|
public CrucibleSessionImpl(@NotNull final Project project) {
myProject = project;
initSSLCertPolicy();
}
private void initSSLCertPolicy() {
EasySSLProtocolSocketFactory secureProtocolSocketFactory = new EasySSLProtocolSocketFactory();
Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)secureProtocolSocketFactory, 443));
}
@Override
public void login() throws CrucibleApiLoginException {
try {
final String username = getUsername();
final String password = getPassword();
if (username == null || password == null) {
throw new CrucibleApiLoginException("Username or Password is empty");
}
final String loginUrl = getLoginUrl(username, password);
final JsonObject jsonObject = buildJsonResponse(loginUrl);
final JsonElement authToken = jsonObject.get("token");
final String errorMessage = getExceptionMessages(jsonObject);
if (authToken == null || errorMessage != null) {
throw new CrucibleApiLoginException(errorMessage != null ? errorMessage : "Unknown error");
}
}
catch (IOException e) {
throw new CrucibleApiLoginException(getHostUrl() + ":" + e.getMessage(), e);
}
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiLoginException.java
// public class CrucibleApiLoginException extends CrucibleApiException {
//
// public CrucibleApiLoginException(String message) {
// super(message);
// }
//
// public CrucibleApiLoginException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/UiUtils.java
// public class UiUtils {
// private UiUtils() {
// }
//
// public static void showBalloon(@NotNull final Project project, @NotNull final String message,
// @NotNull final MessageType messageType) {
// final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
// if (frame == null) return;
// final JComponent component = frame.getRootPane();
// if (component == null) return;
// final Rectangle rect = component.getVisibleRect();
// final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
// final RelativePoint point = new RelativePoint(component, p);
//
// final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().
// createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
// messageType.getPopupBackground(), null);
// balloonBuilder.setShowCallout(false).setCloseButtonEnabled(true)
// .createBalloon().show(point, Balloon.Position.atLeft);
// }
// }
// Path: src/com/jetbrains/crucible/connection/CrucibleSessionImpl.java
import com.google.gson.*;
import com.intellij.dvcs.repo.VcsRepositoryManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.SLRUCache;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiLoginException;
import com.jetbrains.crucible.model.*;
import com.jetbrains.crucible.ui.UiUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
public CrucibleSessionImpl(@NotNull final Project project) {
myProject = project;
initSSLCertPolicy();
}
private void initSSLCertPolicy() {
EasySSLProtocolSocketFactory secureProtocolSocketFactory = new EasySSLProtocolSocketFactory();
Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)secureProtocolSocketFactory, 443));
}
@Override
public void login() throws CrucibleApiLoginException {
try {
final String username = getUsername();
final String password = getPassword();
if (username == null || password == null) {
throw new CrucibleApiLoginException("Username or Password is empty");
}
final String loginUrl = getLoginUrl(username, password);
final JsonObject jsonObject = buildJsonResponse(loginUrl);
final JsonElement authToken = jsonObject.get("token");
final String errorMessage = getExceptionMessages(jsonObject);
if (authToken == null || errorMessage != null) {
throw new CrucibleApiLoginException(errorMessage != null ? errorMessage : "Unknown error");
}
}
catch (IOException e) {
throw new CrucibleApiLoginException(getHostUrl() + ":" + e.getMessage(), e);
}
|
catch (CrucibleApiException e) {
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/connection/CrucibleSessionImpl.java
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiLoginException.java
// public class CrucibleApiLoginException extends CrucibleApiException {
//
// public CrucibleApiLoginException(String message) {
// super(message);
// }
//
// public CrucibleApiLoginException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/UiUtils.java
// public class UiUtils {
// private UiUtils() {
// }
//
// public static void showBalloon(@NotNull final Project project, @NotNull final String message,
// @NotNull final MessageType messageType) {
// final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
// if (frame == null) return;
// final JComponent component = frame.getRootPane();
// if (component == null) return;
// final Rectangle rect = component.getVisibleRect();
// final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
// final RelativePoint point = new RelativePoint(component, p);
//
// final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().
// createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
// messageType.getPopupBackground(), null);
// balloonBuilder.setShowCallout(false).setCloseButtonEnabled(true)
// .createBalloon().show(point, Balloon.Position.atLeft);
// }
// }
|
import com.google.gson.*;
import com.intellij.dvcs.repo.VcsRepositoryManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.SLRUCache;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiLoginException;
import com.jetbrains.crucible.model.*;
import com.jetbrains.crucible.ui.UiUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
|
final HttpClient client = new HttpClient();
HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host)
params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host)
client.executeMethod(method);
}
protected JsonObject buildJsonResponseForPost(@NotNull final String urlString,
@NotNull final RequestEntity requestEntity) throws IOException {
final PostMethod method = new PostMethod(urlString);
method.setRequestEntity(requestEntity);
executeHttpMethod(method);
final String response = method.getResponseBodyAsString();
try {
return JsonParser.parseString(response).getAsJsonObject();
}
catch (JsonSyntaxException ex) {
LOG.error("Malformed Json");
LOG.error(response);
}
return new JsonObject();
}
protected void adjustHttpHeader(@NotNull final HttpMethod method) {
method.addRequestHeader(new Header("Authorization", getAuthHeaderValue()));
method.addRequestHeader(new Header("accept", "application/json"));
}
protected String getUsername() {
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiLoginException.java
// public class CrucibleApiLoginException extends CrucibleApiException {
//
// public CrucibleApiLoginException(String message) {
// super(message);
// }
//
// public CrucibleApiLoginException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/UiUtils.java
// public class UiUtils {
// private UiUtils() {
// }
//
// public static void showBalloon(@NotNull final Project project, @NotNull final String message,
// @NotNull final MessageType messageType) {
// final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
// if (frame == null) return;
// final JComponent component = frame.getRootPane();
// if (component == null) return;
// final Rectangle rect = component.getVisibleRect();
// final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
// final RelativePoint point = new RelativePoint(component, p);
//
// final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().
// createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
// messageType.getPopupBackground(), null);
// balloonBuilder.setShowCallout(false).setCloseButtonEnabled(true)
// .createBalloon().show(point, Balloon.Position.atLeft);
// }
// }
// Path: src/com/jetbrains/crucible/connection/CrucibleSessionImpl.java
import com.google.gson.*;
import com.intellij.dvcs.repo.VcsRepositoryManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.SLRUCache;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiLoginException;
import com.jetbrains.crucible.model.*;
import com.jetbrains.crucible.ui.UiUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
final HttpClient client = new HttpClient();
HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
params.setConnectionTimeout(CONNECTION_TIMEOUT); //set connection timeout (how long it takes to connect to remote host)
params.setSoTimeout(CONNECTION_TIMEOUT); //set socket timeout (how long it takes to retrieve data from remote host)
client.executeMethod(method);
}
protected JsonObject buildJsonResponseForPost(@NotNull final String urlString,
@NotNull final RequestEntity requestEntity) throws IOException {
final PostMethod method = new PostMethod(urlString);
method.setRequestEntity(requestEntity);
executeHttpMethod(method);
final String response = method.getResponseBodyAsString();
try {
return JsonParser.parseString(response).getAsJsonObject();
}
catch (JsonSyntaxException ex) {
LOG.error("Malformed Json");
LOG.error(response);
}
return new JsonObject();
}
protected void adjustHttpHeader(@NotNull final HttpMethod method) {
method.addRequestHeader(new Header("Authorization", getAuthHeaderValue()));
method.addRequestHeader(new Header("accept", "application/json"));
}
protected String getUsername() {
|
return CrucibleSettings.getInstance().USERNAME;
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/connection/CrucibleSessionImpl.java
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiLoginException.java
// public class CrucibleApiLoginException extends CrucibleApiException {
//
// public CrucibleApiLoginException(String message) {
// super(message);
// }
//
// public CrucibleApiLoginException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/UiUtils.java
// public class UiUtils {
// private UiUtils() {
// }
//
// public static void showBalloon(@NotNull final Project project, @NotNull final String message,
// @NotNull final MessageType messageType) {
// final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
// if (frame == null) return;
// final JComponent component = frame.getRootPane();
// if (component == null) return;
// final Rectangle rect = component.getVisibleRect();
// final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
// final RelativePoint point = new RelativePoint(component, p);
//
// final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().
// createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
// messageType.getPopupBackground(), null);
// balloonBuilder.setShowCallout(false).setCloseButtonEnabled(true)
// .createBalloon().show(point, Balloon.Position.atLeft);
// }
// }
|
import com.google.gson.*;
import com.intellij.dvcs.repo.VcsRepositoryManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.SLRUCache;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiLoginException;
import com.jetbrains.crucible.model.*;
import com.jetbrains.crucible.ui.UiUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
|
}
return null;
}
@Nullable
public Comment postComment(@NotNull final Comment comment, boolean isGeneral,
@NotNull final String reviewId) {
String url = getHostUrl() + REVIEW_SERVICE + "/" + reviewId;
final String parentCommentId = comment.getParentCommentId();
final boolean isVersioned = !isGeneral;
boolean reply = comment.getParentCommentId() != null;
if (isVersioned && !reply) {
url += REVIEW_ITEMS + "/" + comment.getReviewItemId();
}
url += COMMENTS;
if (reply) {
url += "/" + parentCommentId + REPLIES;
}
try {
final RequestEntity request = CrucibleApi.createCommentRequest(comment, !isVersioned);
final JsonObject jsonObject = buildJsonResponseForPost(url, request);
final String errorMessage = getExceptionMessages(jsonObject);
if (errorMessage != null) {
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiLoginException.java
// public class CrucibleApiLoginException extends CrucibleApiException {
//
// public CrucibleApiLoginException(String message) {
// super(message);
// }
//
// public CrucibleApiLoginException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/UiUtils.java
// public class UiUtils {
// private UiUtils() {
// }
//
// public static void showBalloon(@NotNull final Project project, @NotNull final String message,
// @NotNull final MessageType messageType) {
// final JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project);
// if (frame == null) return;
// final JComponent component = frame.getRootPane();
// if (component == null) return;
// final Rectangle rect = component.getVisibleRect();
// final Point p = new Point(rect.x + rect.width - 10, rect.y + 10);
// final RelativePoint point = new RelativePoint(component, p);
//
// final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().
// createHtmlTextBalloonBuilder(message, messageType.getDefaultIcon(),
// messageType.getPopupBackground(), null);
// balloonBuilder.setShowCallout(false).setCloseButtonEnabled(true)
// .createBalloon().show(point, Balloon.Position.atLeft);
// }
// }
// Path: src/com/jetbrains/crucible/connection/CrucibleSessionImpl.java
import com.google.gson.*;
import com.intellij.dvcs.repo.VcsRepositoryManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.SLRUCache;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiLoginException;
import com.jetbrains.crucible.model.*;
import com.jetbrains.crucible.ui.UiUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
}
return null;
}
@Nullable
public Comment postComment(@NotNull final Comment comment, boolean isGeneral,
@NotNull final String reviewId) {
String url = getHostUrl() + REVIEW_SERVICE + "/" + reviewId;
final String parentCommentId = comment.getParentCommentId();
final boolean isVersioned = !isGeneral;
boolean reply = comment.getParentCommentId() != null;
if (isVersioned && !reply) {
url += REVIEW_ITEMS + "/" + comment.getReviewItemId();
}
url += COMMENTS;
if (reply) {
url += "/" + parentCommentId + REPLIES;
}
try {
final RequestEntity request = CrucibleApi.createCommentRequest(comment, !isVersioned);
final JsonObject jsonObject = buildJsonResponseForPost(url, request);
final String errorMessage = getExceptionMessages(jsonObject);
if (errorMessage != null) {
|
UiUtils.showBalloon(myProject, "Sorry, comment wasn't added:\n" + errorMessage, MessageType.ERROR);
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/ui/toolWindow/details/VersionedCommentsTree.java
|
// Path: src/com/jetbrains/crucible/model/Comment.java
// public class Comment {
//
// @NotNull private final User myAuthor;
// @NotNull private final String myMessage;
// private boolean myDraft;
//
// private String myLine;
// private String myReviewItemId;
// private String myPermId;
// private String myRevision;
// private Date myCreateDate = new Date();
// private final List<Comment> myReplies = new ArrayList<Comment>();
// private String myParentCommentId;
//
// public Comment(@NotNull final User commentAuthor, @NotNull final String message, boolean draft) {
// myAuthor = commentAuthor;
// myMessage = message;
// myDraft = draft;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public User getAuthor() {
// return myAuthor;
// }
//
// public Date getCreateDate() {
// return new Date(myCreateDate.getTime());
// }
//
// public void setCreateDate(Date createDate) {
// if (createDate != null) {
// myCreateDate = new Date(createDate.getTime());
// }
// }
//
// @Override
// public String toString() {
// return getMessage();
// }
//
// public String getLine() {
// return myLine;
// }
//
// public void setLine(String line) {
// myLine = line;
// }
//
// public String getReviewItemId() {
// return myReviewItemId;
// }
//
// public void setReviewItemId(String reviewItemId) {
// myReviewItemId = reviewItemId;
// }
//
// public String getRevision() {
// return myRevision;
// }
//
// public void setRevision(String revision) {
// myRevision = revision;
// }
//
// public void addReply(Comment reply) {
// myReplies.add(reply);
// }
//
// public List<Comment> getReplies() {
// return myReplies;
// }
//
// public void setParentCommentId(String parentCommentId) {
// myParentCommentId = parentCommentId;
// }
//
// public String getParentCommentId() {
// return myParentCommentId;
// }
//
// public String getPermId() {
// return myPermId;
// }
//
// public void setPermId(String id) {
// myPermId = id;
// }
//
// public boolean isDraft() {
// return myDraft;
// }
//
// public void setDraft(boolean draft) {
// myDraft = draft;
// }
// }
//
// Path: src/com/jetbrains/crucible/model/Review.java
// public class Review extends BasicReview {
// private final List<Comment> myGeneralComments = new ArrayList<Comment>();
// private final List<Comment> myComments = new ArrayList<Comment>();
//
// private final Set<ReviewItem> myItems = new HashSet<ReviewItem>();
//
// public Review(@NotNull final String id, @NotNull final User author,
// @Nullable final User moderator) {
// super(id, author, moderator);
// }
//
// public void addGeneralComment(@NotNull Comment generalComment) {
// myGeneralComments.add(generalComment);
// }
//
// public void addComment(@NotNull Comment comment) {
// myComments.add(comment);
// }
//
// @NotNull
// public List<Comment> getGeneralComments() {
// return myGeneralComments;
// }
//
// @NotNull
// public List<Comment> getComments() {
// return myComments;
// }
//
// @NotNull
// public Set<ReviewItem> getReviewItems() {
// return myItems;
// }
//
// public void addReviewItem(@NotNull final ReviewItem item) {
// myItems.add(item);
// }
//
// @Nullable
// public String getPathById(@NotNull final String id) {
// for (ReviewItem item : myItems) {
// if (item.getId().equals(id))
// return item.getPath();
// }
// return null;
// }
//
// @Nullable
// public String getIdByPath(@NotNull final String path, Project project) {
// final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();
//
// for (ReviewItem item : myItems) {
// final String repo = item.getRepo();
// final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();
// String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));
// if (FileUtil.pathsEqual(relativePath, item.getPath())) {
// return item.getId();
// }
// }
// return null;
// }
//
// public boolean isInPatch(@NotNull Comment comment) {
// final String reviewItemId = comment.getReviewItemId();
// return null != ContainerUtil.find(myItems, new Condition<ReviewItem>() {
// @Override
// public boolean value(ReviewItem item) {
// return item.getId().equalsIgnoreCase(reviewItemId) && item.isPatch();
// }
// });
// }
// }
|
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import com.jetbrains.crucible.model.Comment;
import com.jetbrains.crucible.model.Review;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
|
package com.jetbrains.crucible.ui.toolWindow.details;
/**
* @author Kirill Likhodedov
*/
public class VersionedCommentsTree extends CommentsTree {
private VersionedCommentsTree(@NotNull Project project, @NotNull Review review, @NotNull DefaultTreeModel model,
@Nullable Editor editor, @Nullable FilePath filePath) {
super(project, review, model, editor, filePath);
}
@NotNull
|
// Path: src/com/jetbrains/crucible/model/Comment.java
// public class Comment {
//
// @NotNull private final User myAuthor;
// @NotNull private final String myMessage;
// private boolean myDraft;
//
// private String myLine;
// private String myReviewItemId;
// private String myPermId;
// private String myRevision;
// private Date myCreateDate = new Date();
// private final List<Comment> myReplies = new ArrayList<Comment>();
// private String myParentCommentId;
//
// public Comment(@NotNull final User commentAuthor, @NotNull final String message, boolean draft) {
// myAuthor = commentAuthor;
// myMessage = message;
// myDraft = draft;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public User getAuthor() {
// return myAuthor;
// }
//
// public Date getCreateDate() {
// return new Date(myCreateDate.getTime());
// }
//
// public void setCreateDate(Date createDate) {
// if (createDate != null) {
// myCreateDate = new Date(createDate.getTime());
// }
// }
//
// @Override
// public String toString() {
// return getMessage();
// }
//
// public String getLine() {
// return myLine;
// }
//
// public void setLine(String line) {
// myLine = line;
// }
//
// public String getReviewItemId() {
// return myReviewItemId;
// }
//
// public void setReviewItemId(String reviewItemId) {
// myReviewItemId = reviewItemId;
// }
//
// public String getRevision() {
// return myRevision;
// }
//
// public void setRevision(String revision) {
// myRevision = revision;
// }
//
// public void addReply(Comment reply) {
// myReplies.add(reply);
// }
//
// public List<Comment> getReplies() {
// return myReplies;
// }
//
// public void setParentCommentId(String parentCommentId) {
// myParentCommentId = parentCommentId;
// }
//
// public String getParentCommentId() {
// return myParentCommentId;
// }
//
// public String getPermId() {
// return myPermId;
// }
//
// public void setPermId(String id) {
// myPermId = id;
// }
//
// public boolean isDraft() {
// return myDraft;
// }
//
// public void setDraft(boolean draft) {
// myDraft = draft;
// }
// }
//
// Path: src/com/jetbrains/crucible/model/Review.java
// public class Review extends BasicReview {
// private final List<Comment> myGeneralComments = new ArrayList<Comment>();
// private final List<Comment> myComments = new ArrayList<Comment>();
//
// private final Set<ReviewItem> myItems = new HashSet<ReviewItem>();
//
// public Review(@NotNull final String id, @NotNull final User author,
// @Nullable final User moderator) {
// super(id, author, moderator);
// }
//
// public void addGeneralComment(@NotNull Comment generalComment) {
// myGeneralComments.add(generalComment);
// }
//
// public void addComment(@NotNull Comment comment) {
// myComments.add(comment);
// }
//
// @NotNull
// public List<Comment> getGeneralComments() {
// return myGeneralComments;
// }
//
// @NotNull
// public List<Comment> getComments() {
// return myComments;
// }
//
// @NotNull
// public Set<ReviewItem> getReviewItems() {
// return myItems;
// }
//
// public void addReviewItem(@NotNull final ReviewItem item) {
// myItems.add(item);
// }
//
// @Nullable
// public String getPathById(@NotNull final String id) {
// for (ReviewItem item : myItems) {
// if (item.getId().equals(id))
// return item.getPath();
// }
// return null;
// }
//
// @Nullable
// public String getIdByPath(@NotNull final String path, Project project) {
// final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();
//
// for (ReviewItem item : myItems) {
// final String repo = item.getRepo();
// final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();
// String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));
// if (FileUtil.pathsEqual(relativePath, item.getPath())) {
// return item.getId();
// }
// }
// return null;
// }
//
// public boolean isInPatch(@NotNull Comment comment) {
// final String reviewItemId = comment.getReviewItemId();
// return null != ContainerUtil.find(myItems, new Condition<ReviewItem>() {
// @Override
// public boolean value(ReviewItem item) {
// return item.getId().equalsIgnoreCase(reviewItemId) && item.isPatch();
// }
// });
// }
// }
// Path: src/com/jetbrains/crucible/ui/toolWindow/details/VersionedCommentsTree.java
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import com.jetbrains.crucible.model.Comment;
import com.jetbrains.crucible.model.Review;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
package com.jetbrains.crucible.ui.toolWindow.details;
/**
* @author Kirill Likhodedov
*/
public class VersionedCommentsTree extends CommentsTree {
private VersionedCommentsTree(@NotNull Project project, @NotNull Review review, @NotNull DefaultTreeModel model,
@Nullable Editor editor, @Nullable FilePath filePath) {
super(project, review, model, editor, filePath);
}
@NotNull
|
public static CommentsTree create(@NotNull Project project, @NotNull Review review, @NotNull Comment comment,
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/ui/toolWindow/tree/CrucibleFilterNode.java
|
// Path: src/com/jetbrains/crucible/model/CrucibleFilter.java
// public enum CrucibleFilter {
// // Inbox
// ToReview("toReview", "To Review"), //Reviews on which the current user is an uncompleted reviewer.
// ReadyToClose("toSummarize", "Ready To Close"), //Completed reviews which are ready for the current user to summarize.
// InDraft("drafts", "In Draft"), //Draft reviews created by the current user.
// RequireApprovalReview("requireMyApproval", "Review Required My Approval"), //Reviews waiting to be approved by the current user.
//
// // Outbox
// OutForReview("outForReview", "Out For Review"), //Reviews with uncompleted reviewers, on which the current reviewer is the moderator.
// Completed("completed", "Completed"), //Open reviews where the current user is a completed reviewer.
//
// // Archive
// Closed("closed", "Closed"), //Closed reviews created by the current user.
// Abandoned("trash", "Abandoned"); //Abandoned reviews created by the current user.
//
// private final String myFilterUrl;
// private final String myFilterName;
//
// CrucibleFilter(@NotNull final String filterUrl, @NotNull final String filterName) {
// myFilterUrl = filterUrl;
// myFilterName = filterName;
// }
//
// @NotNull
// public String getFilterUrl() {
// return myFilterUrl;
// }
//
// @NotNull
// public String getFilterName() {
// return myFilterName;
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/toolWindow/CrucibleReviewModel.java
// public class CrucibleReviewModel extends DefaultTableModel {
// private final Project myProject;
//
// public CrucibleReviewModel(Project project) {
// myProject = project;
// }
//
// @Override
// public Class<?> getColumnClass(int columnIndex) {
// if (columnIndex == 4) return Date.class;
// return String.class;
// }
//
// @Override
// public int getColumnCount() {
// return 5;
// }
//
// @Override
// public String getColumnName(int column) {
// switch (column) {
// case 0:
// return CrucibleBundle.message("crucible.id");
// case 1:
// return CrucibleBundle.message("crucible.description");
// case 2:
// return CrucibleBundle.message("crucible.state");
// case 3:
// return CrucibleBundle.message("crucible.author");
// case 4:
// return CrucibleBundle.message("crucible.date");
// }
// return super.getColumnName(column);
// }
//
// @Override
// public boolean isCellEditable(int row, int column) {
// return false;
// }
//
// public void updateModel(@NotNull final CrucibleFilter filter) {
// setRowCount(0);
// final CrucibleManager manager = CrucibleManager.getInstance(myProject);
// final List<BasicReview> reviews;
// reviews = manager.getReviewsForFilter(filter);
// if (reviews != null) {
// for (BasicReview review : reviews) {
// addRow(new Object[]{review.getPermaId(), review.getDescription(), review.getState(),
// review.getAuthor().getUserName(), review.getCreateDate()});
//
// }
// }
// }
// }
|
import com.intellij.ui.treeStructure.SimpleNode;
import com.intellij.ui.treeStructure.SimpleTree;
import com.jetbrains.crucible.model.CrucibleFilter;
import com.jetbrains.crucible.ui.toolWindow.CrucibleReviewModel;
import org.jetbrains.annotations.NotNull;
|
package com.jetbrains.crucible.ui.toolWindow.tree;
/**
* Created by Dmitry on 14.12.2014.
*/
public class CrucibleFilterNode extends SimpleNode {
private final CrucibleReviewModel myReviewModel;
|
// Path: src/com/jetbrains/crucible/model/CrucibleFilter.java
// public enum CrucibleFilter {
// // Inbox
// ToReview("toReview", "To Review"), //Reviews on which the current user is an uncompleted reviewer.
// ReadyToClose("toSummarize", "Ready To Close"), //Completed reviews which are ready for the current user to summarize.
// InDraft("drafts", "In Draft"), //Draft reviews created by the current user.
// RequireApprovalReview("requireMyApproval", "Review Required My Approval"), //Reviews waiting to be approved by the current user.
//
// // Outbox
// OutForReview("outForReview", "Out For Review"), //Reviews with uncompleted reviewers, on which the current reviewer is the moderator.
// Completed("completed", "Completed"), //Open reviews where the current user is a completed reviewer.
//
// // Archive
// Closed("closed", "Closed"), //Closed reviews created by the current user.
// Abandoned("trash", "Abandoned"); //Abandoned reviews created by the current user.
//
// private final String myFilterUrl;
// private final String myFilterName;
//
// CrucibleFilter(@NotNull final String filterUrl, @NotNull final String filterName) {
// myFilterUrl = filterUrl;
// myFilterName = filterName;
// }
//
// @NotNull
// public String getFilterUrl() {
// return myFilterUrl;
// }
//
// @NotNull
// public String getFilterName() {
// return myFilterName;
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/toolWindow/CrucibleReviewModel.java
// public class CrucibleReviewModel extends DefaultTableModel {
// private final Project myProject;
//
// public CrucibleReviewModel(Project project) {
// myProject = project;
// }
//
// @Override
// public Class<?> getColumnClass(int columnIndex) {
// if (columnIndex == 4) return Date.class;
// return String.class;
// }
//
// @Override
// public int getColumnCount() {
// return 5;
// }
//
// @Override
// public String getColumnName(int column) {
// switch (column) {
// case 0:
// return CrucibleBundle.message("crucible.id");
// case 1:
// return CrucibleBundle.message("crucible.description");
// case 2:
// return CrucibleBundle.message("crucible.state");
// case 3:
// return CrucibleBundle.message("crucible.author");
// case 4:
// return CrucibleBundle.message("crucible.date");
// }
// return super.getColumnName(column);
// }
//
// @Override
// public boolean isCellEditable(int row, int column) {
// return false;
// }
//
// public void updateModel(@NotNull final CrucibleFilter filter) {
// setRowCount(0);
// final CrucibleManager manager = CrucibleManager.getInstance(myProject);
// final List<BasicReview> reviews;
// reviews = manager.getReviewsForFilter(filter);
// if (reviews != null) {
// for (BasicReview review : reviews) {
// addRow(new Object[]{review.getPermaId(), review.getDescription(), review.getState(),
// review.getAuthor().getUserName(), review.getCreateDate()});
//
// }
// }
// }
// }
// Path: src/com/jetbrains/crucible/ui/toolWindow/tree/CrucibleFilterNode.java
import com.intellij.ui.treeStructure.SimpleNode;
import com.intellij.ui.treeStructure.SimpleTree;
import com.jetbrains.crucible.model.CrucibleFilter;
import com.jetbrains.crucible.ui.toolWindow.CrucibleReviewModel;
import org.jetbrains.annotations.NotNull;
package com.jetbrains.crucible.ui.toolWindow.tree;
/**
* Created by Dmitry on 14.12.2014.
*/
public class CrucibleFilterNode extends SimpleNode {
private final CrucibleReviewModel myReviewModel;
|
private final CrucibleFilter myFilter;
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/connection/CrucibleTestConnector.java
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
|
import com.intellij.openapi.project.Project;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import org.jetbrains.annotations.Nullable;
import java.net.MalformedURLException;
import java.net.URL;
|
package com.jetbrains.crucible.connection;
/**
* User : ktisha
*/
public class CrucibleTestConnector {
public enum ConnectionState {
NOT_FINISHED,
SUCCEEDED,
FAILED,
INTERRUPTED,
}
private ConnectionState myConnectionState = ConnectionState.NOT_FINISHED;
private Exception myException;
private final Project myProject;
public CrucibleTestConnector(Project project) {
myProject = project;
}
public ConnectionState getConnectionState() {
return myConnectionState;
}
public void run() {
try {
testConnect();
if (myConnectionState != ConnectionState.INTERRUPTED && myConnectionState != ConnectionState.FAILED) {
myConnectionState = ConnectionState.SUCCEEDED;
}
}
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
// Path: src/com/jetbrains/crucible/connection/CrucibleTestConnector.java
import com.intellij.openapi.project.Project;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import org.jetbrains.annotations.Nullable;
import java.net.MalformedURLException;
import java.net.URL;
package com.jetbrains.crucible.connection;
/**
* User : ktisha
*/
public class CrucibleTestConnector {
public enum ConnectionState {
NOT_FINISHED,
SUCCEEDED,
FAILED,
INTERRUPTED,
}
private ConnectionState myConnectionState = ConnectionState.NOT_FINISHED;
private Exception myException;
private final Project myProject;
public CrucibleTestConnector(Project project) {
myProject = project;
}
public ConnectionState getConnectionState() {
return myConnectionState;
}
public void run() {
try {
testConnect();
if (myConnectionState != ConnectionState.INTERRUPTED && myConnectionState != ConnectionState.FAILED) {
myConnectionState = ConnectionState.SUCCEEDED;
}
}
|
catch (CrucibleApiException e) {
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/connection/CrucibleTestConnector.java
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
|
import com.intellij.openapi.project.Project;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import org.jetbrains.annotations.Nullable;
import java.net.MalformedURLException;
import java.net.URL;
|
public ConnectionState getConnectionState() {
return myConnectionState;
}
public void run() {
try {
testConnect();
if (myConnectionState != ConnectionState.INTERRUPTED && myConnectionState != ConnectionState.FAILED) {
myConnectionState = ConnectionState.SUCCEEDED;
}
}
catch (CrucibleApiException e) {
if (myConnectionState != ConnectionState.INTERRUPTED) {
myConnectionState = ConnectionState.FAILED;
myException = e;
}
}
}
public void setInterrupted() {
myConnectionState = ConnectionState.INTERRUPTED;
}
@Nullable
public String getErrorMessage() {
return myException == null ? null : myException.getMessage();
}
public void testConnect() throws CrucibleApiException {
final CrucibleSession session = new CrucibleSessionImpl(myProject);
|
// Path: src/com/jetbrains/crucible/configuration/CrucibleSettings.java
// @State(name = "CrucibleSettings",
// storages = {
// @Storage(file = "$APP_CONFIG$" + "/crucibleConnector.xml")
// }
// )
// public class CrucibleSettings implements PersistentStateComponent<CrucibleSettings> {
// public String SERVER_URL = "";
// public String USERNAME = "";
//
// @Override
// public CrucibleSettings getState() {
// return this;
// }
//
// @Override
// public void loadState(CrucibleSettings state) {
// XmlSerializerUtil.copyBean(state, this);
// }
//
// public static CrucibleSettings getInstance() {
// return ServiceManager.getService(CrucibleSettings.class);
// }
//
// public static final String CRUCIBLE_SETTINGS_PASSWORD_KEY = "CRUCIBLE_SETTINGS_PASSWORD_KEY";
// private static final Logger LOG = Logger.getInstance(CrucibleConfigurable.class.getName());
//
// public void savePassword(String pass) {
// PasswordSafe.getInstance().set(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY), new Credentials(USERNAME, pass));
// }
//
// @Nullable
// public String getPassword() {
// final Credentials credentials = PasswordSafe.getInstance().get(new CredentialAttributes(CRUCIBLE_SETTINGS_PASSWORD_KEY));
//
// return credentials != null ? credentials.getPasswordAsString() : null;
// }
// }
//
// Path: src/com/jetbrains/crucible/connection/exceptions/CrucibleApiException.java
// public class CrucibleApiException extends Exception {
//
// public CrucibleApiException(String message) {
// super(message);
// }
//
// public CrucibleApiException(String message, Throwable throwable) {
// super(message, throwable);
// }
// }
// Path: src/com/jetbrains/crucible/connection/CrucibleTestConnector.java
import com.intellij.openapi.project.Project;
import com.jetbrains.crucible.configuration.CrucibleSettings;
import com.jetbrains.crucible.connection.exceptions.CrucibleApiException;
import org.jetbrains.annotations.Nullable;
import java.net.MalformedURLException;
import java.net.URL;
public ConnectionState getConnectionState() {
return myConnectionState;
}
public void run() {
try {
testConnect();
if (myConnectionState != ConnectionState.INTERRUPTED && myConnectionState != ConnectionState.FAILED) {
myConnectionState = ConnectionState.SUCCEEDED;
}
}
catch (CrucibleApiException e) {
if (myConnectionState != ConnectionState.INTERRUPTED) {
myConnectionState = ConnectionState.FAILED;
myException = e;
}
}
}
public void setInterrupted() {
myConnectionState = ConnectionState.INTERRUPTED;
}
@Nullable
public String getErrorMessage() {
return myException == null ? null : myException.getMessage();
}
public void testConnect() throws CrucibleApiException {
final CrucibleSession session = new CrucibleSessionImpl(myProject);
|
final String url = CrucibleSettings.getInstance().SERVER_URL;
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/ui/toolWindow/tree/CrucibleRootNode.java
|
// Path: src/com/jetbrains/crucible/model/CrucibleFilter.java
// public enum CrucibleFilter {
// // Inbox
// ToReview("toReview", "To Review"), //Reviews on which the current user is an uncompleted reviewer.
// ReadyToClose("toSummarize", "Ready To Close"), //Completed reviews which are ready for the current user to summarize.
// InDraft("drafts", "In Draft"), //Draft reviews created by the current user.
// RequireApprovalReview("requireMyApproval", "Review Required My Approval"), //Reviews waiting to be approved by the current user.
//
// // Outbox
// OutForReview("outForReview", "Out For Review"), //Reviews with uncompleted reviewers, on which the current reviewer is the moderator.
// Completed("completed", "Completed"), //Open reviews where the current user is a completed reviewer.
//
// // Archive
// Closed("closed", "Closed"), //Closed reviews created by the current user.
// Abandoned("trash", "Abandoned"); //Abandoned reviews created by the current user.
//
// private final String myFilterUrl;
// private final String myFilterName;
//
// CrucibleFilter(@NotNull final String filterUrl, @NotNull final String filterName) {
// myFilterUrl = filterUrl;
// myFilterName = filterName;
// }
//
// @NotNull
// public String getFilterUrl() {
// return myFilterUrl;
// }
//
// @NotNull
// public String getFilterName() {
// return myFilterName;
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/toolWindow/CrucibleReviewModel.java
// public class CrucibleReviewModel extends DefaultTableModel {
// private final Project myProject;
//
// public CrucibleReviewModel(Project project) {
// myProject = project;
// }
//
// @Override
// public Class<?> getColumnClass(int columnIndex) {
// if (columnIndex == 4) return Date.class;
// return String.class;
// }
//
// @Override
// public int getColumnCount() {
// return 5;
// }
//
// @Override
// public String getColumnName(int column) {
// switch (column) {
// case 0:
// return CrucibleBundle.message("crucible.id");
// case 1:
// return CrucibleBundle.message("crucible.description");
// case 2:
// return CrucibleBundle.message("crucible.state");
// case 3:
// return CrucibleBundle.message("crucible.author");
// case 4:
// return CrucibleBundle.message("crucible.date");
// }
// return super.getColumnName(column);
// }
//
// @Override
// public boolean isCellEditable(int row, int column) {
// return false;
// }
//
// public void updateModel(@NotNull final CrucibleFilter filter) {
// setRowCount(0);
// final CrucibleManager manager = CrucibleManager.getInstance(myProject);
// final List<BasicReview> reviews;
// reviews = manager.getReviewsForFilter(filter);
// if (reviews != null) {
// for (BasicReview review : reviews) {
// addRow(new Object[]{review.getPermaId(), review.getDescription(), review.getState(),
// review.getAuthor().getUserName(), review.getCreateDate()});
//
// }
// }
// }
// }
|
import com.intellij.ui.treeStructure.SimpleNode;
import com.jetbrains.crucible.model.CrucibleFilter;
import com.jetbrains.crucible.ui.toolWindow.CrucibleReviewModel;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
|
package com.jetbrains.crucible.ui.toolWindow.tree;
/**
* User : ktisha
*/
public class CrucibleRootNode extends SimpleNode {
private static final String NAME = "All My Reviews";
|
// Path: src/com/jetbrains/crucible/model/CrucibleFilter.java
// public enum CrucibleFilter {
// // Inbox
// ToReview("toReview", "To Review"), //Reviews on which the current user is an uncompleted reviewer.
// ReadyToClose("toSummarize", "Ready To Close"), //Completed reviews which are ready for the current user to summarize.
// InDraft("drafts", "In Draft"), //Draft reviews created by the current user.
// RequireApprovalReview("requireMyApproval", "Review Required My Approval"), //Reviews waiting to be approved by the current user.
//
// // Outbox
// OutForReview("outForReview", "Out For Review"), //Reviews with uncompleted reviewers, on which the current reviewer is the moderator.
// Completed("completed", "Completed"), //Open reviews where the current user is a completed reviewer.
//
// // Archive
// Closed("closed", "Closed"), //Closed reviews created by the current user.
// Abandoned("trash", "Abandoned"); //Abandoned reviews created by the current user.
//
// private final String myFilterUrl;
// private final String myFilterName;
//
// CrucibleFilter(@NotNull final String filterUrl, @NotNull final String filterName) {
// myFilterUrl = filterUrl;
// myFilterName = filterName;
// }
//
// @NotNull
// public String getFilterUrl() {
// return myFilterUrl;
// }
//
// @NotNull
// public String getFilterName() {
// return myFilterName;
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/toolWindow/CrucibleReviewModel.java
// public class CrucibleReviewModel extends DefaultTableModel {
// private final Project myProject;
//
// public CrucibleReviewModel(Project project) {
// myProject = project;
// }
//
// @Override
// public Class<?> getColumnClass(int columnIndex) {
// if (columnIndex == 4) return Date.class;
// return String.class;
// }
//
// @Override
// public int getColumnCount() {
// return 5;
// }
//
// @Override
// public String getColumnName(int column) {
// switch (column) {
// case 0:
// return CrucibleBundle.message("crucible.id");
// case 1:
// return CrucibleBundle.message("crucible.description");
// case 2:
// return CrucibleBundle.message("crucible.state");
// case 3:
// return CrucibleBundle.message("crucible.author");
// case 4:
// return CrucibleBundle.message("crucible.date");
// }
// return super.getColumnName(column);
// }
//
// @Override
// public boolean isCellEditable(int row, int column) {
// return false;
// }
//
// public void updateModel(@NotNull final CrucibleFilter filter) {
// setRowCount(0);
// final CrucibleManager manager = CrucibleManager.getInstance(myProject);
// final List<BasicReview> reviews;
// reviews = manager.getReviewsForFilter(filter);
// if (reviews != null) {
// for (BasicReview review : reviews) {
// addRow(new Object[]{review.getPermaId(), review.getDescription(), review.getState(),
// review.getAuthor().getUserName(), review.getCreateDate()});
//
// }
// }
// }
// }
// Path: src/com/jetbrains/crucible/ui/toolWindow/tree/CrucibleRootNode.java
import com.intellij.ui.treeStructure.SimpleNode;
import com.jetbrains.crucible.model.CrucibleFilter;
import com.jetbrains.crucible.ui.toolWindow.CrucibleReviewModel;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
package com.jetbrains.crucible.ui.toolWindow.tree;
/**
* User : ktisha
*/
public class CrucibleRootNode extends SimpleNode {
private static final String NAME = "All My Reviews";
|
private final CrucibleReviewModel myReviewModel;
|
ktisha/Crucible4IDEA
|
src/com/jetbrains/crucible/ui/toolWindow/tree/CrucibleRootNode.java
|
// Path: src/com/jetbrains/crucible/model/CrucibleFilter.java
// public enum CrucibleFilter {
// // Inbox
// ToReview("toReview", "To Review"), //Reviews on which the current user is an uncompleted reviewer.
// ReadyToClose("toSummarize", "Ready To Close"), //Completed reviews which are ready for the current user to summarize.
// InDraft("drafts", "In Draft"), //Draft reviews created by the current user.
// RequireApprovalReview("requireMyApproval", "Review Required My Approval"), //Reviews waiting to be approved by the current user.
//
// // Outbox
// OutForReview("outForReview", "Out For Review"), //Reviews with uncompleted reviewers, on which the current reviewer is the moderator.
// Completed("completed", "Completed"), //Open reviews where the current user is a completed reviewer.
//
// // Archive
// Closed("closed", "Closed"), //Closed reviews created by the current user.
// Abandoned("trash", "Abandoned"); //Abandoned reviews created by the current user.
//
// private final String myFilterUrl;
// private final String myFilterName;
//
// CrucibleFilter(@NotNull final String filterUrl, @NotNull final String filterName) {
// myFilterUrl = filterUrl;
// myFilterName = filterName;
// }
//
// @NotNull
// public String getFilterUrl() {
// return myFilterUrl;
// }
//
// @NotNull
// public String getFilterName() {
// return myFilterName;
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/toolWindow/CrucibleReviewModel.java
// public class CrucibleReviewModel extends DefaultTableModel {
// private final Project myProject;
//
// public CrucibleReviewModel(Project project) {
// myProject = project;
// }
//
// @Override
// public Class<?> getColumnClass(int columnIndex) {
// if (columnIndex == 4) return Date.class;
// return String.class;
// }
//
// @Override
// public int getColumnCount() {
// return 5;
// }
//
// @Override
// public String getColumnName(int column) {
// switch (column) {
// case 0:
// return CrucibleBundle.message("crucible.id");
// case 1:
// return CrucibleBundle.message("crucible.description");
// case 2:
// return CrucibleBundle.message("crucible.state");
// case 3:
// return CrucibleBundle.message("crucible.author");
// case 4:
// return CrucibleBundle.message("crucible.date");
// }
// return super.getColumnName(column);
// }
//
// @Override
// public boolean isCellEditable(int row, int column) {
// return false;
// }
//
// public void updateModel(@NotNull final CrucibleFilter filter) {
// setRowCount(0);
// final CrucibleManager manager = CrucibleManager.getInstance(myProject);
// final List<BasicReview> reviews;
// reviews = manager.getReviewsForFilter(filter);
// if (reviews != null) {
// for (BasicReview review : reviews) {
// addRow(new Object[]{review.getPermaId(), review.getDescription(), review.getState(),
// review.getAuthor().getUserName(), review.getCreateDate()});
//
// }
// }
// }
// }
|
import com.intellij.ui.treeStructure.SimpleNode;
import com.jetbrains.crucible.model.CrucibleFilter;
import com.jetbrains.crucible.ui.toolWindow.CrucibleReviewModel;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
|
package com.jetbrains.crucible.ui.toolWindow.tree;
/**
* User : ktisha
*/
public class CrucibleRootNode extends SimpleNode {
private static final String NAME = "All My Reviews";
private final CrucibleReviewModel myReviewModel;
private final List<SimpleNode> myChildren = new ArrayList<SimpleNode>();
public CrucibleRootNode(@NotNull final CrucibleReviewModel reviewModel) {
myReviewModel = reviewModel;
addChildren();
}
@NotNull
public String toString() {
return NAME;
}
@Override
public SimpleNode[] getChildren() {
if (myChildren.isEmpty()) {
addChildren();
}
return myChildren.toArray(new SimpleNode[myChildren.size()]);
}
private void addChildren() {
|
// Path: src/com/jetbrains/crucible/model/CrucibleFilter.java
// public enum CrucibleFilter {
// // Inbox
// ToReview("toReview", "To Review"), //Reviews on which the current user is an uncompleted reviewer.
// ReadyToClose("toSummarize", "Ready To Close"), //Completed reviews which are ready for the current user to summarize.
// InDraft("drafts", "In Draft"), //Draft reviews created by the current user.
// RequireApprovalReview("requireMyApproval", "Review Required My Approval"), //Reviews waiting to be approved by the current user.
//
// // Outbox
// OutForReview("outForReview", "Out For Review"), //Reviews with uncompleted reviewers, on which the current reviewer is the moderator.
// Completed("completed", "Completed"), //Open reviews where the current user is a completed reviewer.
//
// // Archive
// Closed("closed", "Closed"), //Closed reviews created by the current user.
// Abandoned("trash", "Abandoned"); //Abandoned reviews created by the current user.
//
// private final String myFilterUrl;
// private final String myFilterName;
//
// CrucibleFilter(@NotNull final String filterUrl, @NotNull final String filterName) {
// myFilterUrl = filterUrl;
// myFilterName = filterName;
// }
//
// @NotNull
// public String getFilterUrl() {
// return myFilterUrl;
// }
//
// @NotNull
// public String getFilterName() {
// return myFilterName;
// }
// }
//
// Path: src/com/jetbrains/crucible/ui/toolWindow/CrucibleReviewModel.java
// public class CrucibleReviewModel extends DefaultTableModel {
// private final Project myProject;
//
// public CrucibleReviewModel(Project project) {
// myProject = project;
// }
//
// @Override
// public Class<?> getColumnClass(int columnIndex) {
// if (columnIndex == 4) return Date.class;
// return String.class;
// }
//
// @Override
// public int getColumnCount() {
// return 5;
// }
//
// @Override
// public String getColumnName(int column) {
// switch (column) {
// case 0:
// return CrucibleBundle.message("crucible.id");
// case 1:
// return CrucibleBundle.message("crucible.description");
// case 2:
// return CrucibleBundle.message("crucible.state");
// case 3:
// return CrucibleBundle.message("crucible.author");
// case 4:
// return CrucibleBundle.message("crucible.date");
// }
// return super.getColumnName(column);
// }
//
// @Override
// public boolean isCellEditable(int row, int column) {
// return false;
// }
//
// public void updateModel(@NotNull final CrucibleFilter filter) {
// setRowCount(0);
// final CrucibleManager manager = CrucibleManager.getInstance(myProject);
// final List<BasicReview> reviews;
// reviews = manager.getReviewsForFilter(filter);
// if (reviews != null) {
// for (BasicReview review : reviews) {
// addRow(new Object[]{review.getPermaId(), review.getDescription(), review.getState(),
// review.getAuthor().getUserName(), review.getCreateDate()});
//
// }
// }
// }
// }
// Path: src/com/jetbrains/crucible/ui/toolWindow/tree/CrucibleRootNode.java
import com.intellij.ui.treeStructure.SimpleNode;
import com.jetbrains.crucible.model.CrucibleFilter;
import com.jetbrains.crucible.ui.toolWindow.CrucibleReviewModel;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
package com.jetbrains.crucible.ui.toolWindow.tree;
/**
* User : ktisha
*/
public class CrucibleRootNode extends SimpleNode {
private static final String NAME = "All My Reviews";
private final CrucibleReviewModel myReviewModel;
private final List<SimpleNode> myChildren = new ArrayList<SimpleNode>();
public CrucibleRootNode(@NotNull final CrucibleReviewModel reviewModel) {
myReviewModel = reviewModel;
addChildren();
}
@NotNull
public String toString() {
return NAME;
}
@Override
public SimpleNode[] getChildren() {
if (myChildren.isEmpty()) {
addChildren();
}
return myChildren.toArray(new SimpleNode[myChildren.size()]);
}
private void addChildren() {
|
for (CrucibleFilter filter : CrucibleFilter.values()) {
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/tinyhttpd/interceptor/InterceptorChainImpl.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
// public interface Request {
//
// HttpMethod method();
//
// String url();
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// String getParam(String name);
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
// public interface Response {
//
// HttpStatus status();
//
// void setStatus(HttpStatus status);
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// /**
// * 添加头部
// *
// * @param key {@link com.vincan.medialoader.tinyhttpd.HttpHeaders.Names}
// * @param value
// */
// void addHeader(String key, String value);
//
// void write(byte[] bytes) throws IOException;
//
// void write(byte[] bytes, int offset, int length) throws IOException;
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/ResponseException.java
// public final class ResponseException extends Exception {
//
// private final HttpStatus status;
//
// public ResponseException(HttpStatus status) {
// super(status.desc);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message) {
// super(message);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message, Exception e) {
// super(message, e);
// this.status = status;
// }
//
// public HttpStatus getStatus() {
// return this.status;
// }
// }
|
import com.vincan.medialoader.tinyhttpd.request.Request;
import com.vincan.medialoader.tinyhttpd.response.Response;
import com.vincan.medialoader.tinyhttpd.response.ResponseException;
import java.io.IOException;
import java.util.List;
|
package com.vincan.medialoader.tinyhttpd.interceptor;
/**
* 拦截器链实现
*
* @author vincanyang
*/
public class InterceptorChainImpl implements Interceptor.Chain {
private List<Interceptor> mInterceptors;
private int mIndex;
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
// public interface Request {
//
// HttpMethod method();
//
// String url();
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// String getParam(String name);
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
// public interface Response {
//
// HttpStatus status();
//
// void setStatus(HttpStatus status);
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// /**
// * 添加头部
// *
// * @param key {@link com.vincan.medialoader.tinyhttpd.HttpHeaders.Names}
// * @param value
// */
// void addHeader(String key, String value);
//
// void write(byte[] bytes) throws IOException;
//
// void write(byte[] bytes, int offset, int length) throws IOException;
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/ResponseException.java
// public final class ResponseException extends Exception {
//
// private final HttpStatus status;
//
// public ResponseException(HttpStatus status) {
// super(status.desc);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message) {
// super(message);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message, Exception e) {
// super(message, e);
// this.status = status;
// }
//
// public HttpStatus getStatus() {
// return this.status;
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/interceptor/InterceptorChainImpl.java
import com.vincan.medialoader.tinyhttpd.request.Request;
import com.vincan.medialoader.tinyhttpd.response.Response;
import com.vincan.medialoader.tinyhttpd.response.ResponseException;
import java.io.IOException;
import java.util.List;
package com.vincan.medialoader.tinyhttpd.interceptor;
/**
* 拦截器链实现
*
* @author vincanyang
*/
public class InterceptorChainImpl implements Interceptor.Chain {
private List<Interceptor> mInterceptors;
private int mIndex;
|
private Request mRequest;
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/tinyhttpd/interceptor/InterceptorChainImpl.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
// public interface Request {
//
// HttpMethod method();
//
// String url();
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// String getParam(String name);
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
// public interface Response {
//
// HttpStatus status();
//
// void setStatus(HttpStatus status);
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// /**
// * 添加头部
// *
// * @param key {@link com.vincan.medialoader.tinyhttpd.HttpHeaders.Names}
// * @param value
// */
// void addHeader(String key, String value);
//
// void write(byte[] bytes) throws IOException;
//
// void write(byte[] bytes, int offset, int length) throws IOException;
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/ResponseException.java
// public final class ResponseException extends Exception {
//
// private final HttpStatus status;
//
// public ResponseException(HttpStatus status) {
// super(status.desc);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message) {
// super(message);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message, Exception e) {
// super(message, e);
// this.status = status;
// }
//
// public HttpStatus getStatus() {
// return this.status;
// }
// }
|
import com.vincan.medialoader.tinyhttpd.request.Request;
import com.vincan.medialoader.tinyhttpd.response.Response;
import com.vincan.medialoader.tinyhttpd.response.ResponseException;
import java.io.IOException;
import java.util.List;
|
package com.vincan.medialoader.tinyhttpd.interceptor;
/**
* 拦截器链实现
*
* @author vincanyang
*/
public class InterceptorChainImpl implements Interceptor.Chain {
private List<Interceptor> mInterceptors;
private int mIndex;
private Request mRequest;
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
// public interface Request {
//
// HttpMethod method();
//
// String url();
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// String getParam(String name);
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
// public interface Response {
//
// HttpStatus status();
//
// void setStatus(HttpStatus status);
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// /**
// * 添加头部
// *
// * @param key {@link com.vincan.medialoader.tinyhttpd.HttpHeaders.Names}
// * @param value
// */
// void addHeader(String key, String value);
//
// void write(byte[] bytes) throws IOException;
//
// void write(byte[] bytes, int offset, int length) throws IOException;
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/ResponseException.java
// public final class ResponseException extends Exception {
//
// private final HttpStatus status;
//
// public ResponseException(HttpStatus status) {
// super(status.desc);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message) {
// super(message);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message, Exception e) {
// super(message, e);
// this.status = status;
// }
//
// public HttpStatus getStatus() {
// return this.status;
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/interceptor/InterceptorChainImpl.java
import com.vincan.medialoader.tinyhttpd.request.Request;
import com.vincan.medialoader.tinyhttpd.response.Response;
import com.vincan.medialoader.tinyhttpd.response.ResponseException;
import java.io.IOException;
import java.util.List;
package com.vincan.medialoader.tinyhttpd.interceptor;
/**
* 拦截器链实现
*
* @author vincanyang
*/
public class InterceptorChainImpl implements Interceptor.Chain {
private List<Interceptor> mInterceptors;
private int mIndex;
private Request mRequest;
|
private Response mResponse;
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/tinyhttpd/interceptor/InterceptorChainImpl.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
// public interface Request {
//
// HttpMethod method();
//
// String url();
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// String getParam(String name);
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
// public interface Response {
//
// HttpStatus status();
//
// void setStatus(HttpStatus status);
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// /**
// * 添加头部
// *
// * @param key {@link com.vincan.medialoader.tinyhttpd.HttpHeaders.Names}
// * @param value
// */
// void addHeader(String key, String value);
//
// void write(byte[] bytes) throws IOException;
//
// void write(byte[] bytes, int offset, int length) throws IOException;
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/ResponseException.java
// public final class ResponseException extends Exception {
//
// private final HttpStatus status;
//
// public ResponseException(HttpStatus status) {
// super(status.desc);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message) {
// super(message);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message, Exception e) {
// super(message, e);
// this.status = status;
// }
//
// public HttpStatus getStatus() {
// return this.status;
// }
// }
|
import com.vincan.medialoader.tinyhttpd.request.Request;
import com.vincan.medialoader.tinyhttpd.response.Response;
import com.vincan.medialoader.tinyhttpd.response.ResponseException;
import java.io.IOException;
import java.util.List;
|
package com.vincan.medialoader.tinyhttpd.interceptor;
/**
* 拦截器链实现
*
* @author vincanyang
*/
public class InterceptorChainImpl implements Interceptor.Chain {
private List<Interceptor> mInterceptors;
private int mIndex;
private Request mRequest;
private Response mResponse;
public InterceptorChainImpl(List<Interceptor> interceptors, int index, Request request, Response response) {
mInterceptors = interceptors;
mIndex = index;
mRequest = request;
mResponse = response;
}
@Override
public Request request() {
return mRequest;
}
@Override
public Response response() {
return mResponse;
}
@Override
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
// public interface Request {
//
// HttpMethod method();
//
// String url();
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// String getParam(String name);
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
// public interface Response {
//
// HttpStatus status();
//
// void setStatus(HttpStatus status);
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// /**
// * 添加头部
// *
// * @param key {@link com.vincan.medialoader.tinyhttpd.HttpHeaders.Names}
// * @param value
// */
// void addHeader(String key, String value);
//
// void write(byte[] bytes) throws IOException;
//
// void write(byte[] bytes, int offset, int length) throws IOException;
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/ResponseException.java
// public final class ResponseException extends Exception {
//
// private final HttpStatus status;
//
// public ResponseException(HttpStatus status) {
// super(status.desc);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message) {
// super(message);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message, Exception e) {
// super(message, e);
// this.status = status;
// }
//
// public HttpStatus getStatus() {
// return this.status;
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/interceptor/InterceptorChainImpl.java
import com.vincan.medialoader.tinyhttpd.request.Request;
import com.vincan.medialoader.tinyhttpd.response.Response;
import com.vincan.medialoader.tinyhttpd.response.ResponseException;
import java.io.IOException;
import java.util.List;
package com.vincan.medialoader.tinyhttpd.interceptor;
/**
* 拦截器链实现
*
* @author vincanyang
*/
public class InterceptorChainImpl implements Interceptor.Chain {
private List<Interceptor> mInterceptors;
private int mIndex;
private Request mRequest;
private Response mResponse;
public InterceptorChainImpl(List<Interceptor> interceptors, int index, Request request, Response response) {
mInterceptors = interceptors;
mIndex = index;
mRequest = request;
mResponse = response;
}
@Override
public Request request() {
return mRequest;
}
@Override
public Response response() {
return mResponse;
}
@Override
|
public void proceed(Request request, Response response) throws ResponseException, IOException {
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/utils/Util.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpConstants.java
// public final class HttpConstants {
//
// public final static String CRLF = "\r\n";
//
// public final static String SP = " ";
//
// public final static String COLON = ":";
//
// public static final String CHARSET_DEFAULT = "UTF-8";
//
// public static final String PARAM_SIGN = "sign";
//
// public static final String PARAM_TIMESTAMP = "timestamp";
//
// private HttpConstants() {
// // Unused
// }
// }
|
import android.text.TextUtils;
import android.util.Base64;
import android.webkit.MimeTypeMap;
import com.vincan.medialoader.tinyhttpd.HttpConstants;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
|
throw new NullPointerException(object.getClass().getSimpleName() + " cann't be null");
}
}
return object;
}
public static String encode(String url) {
try {
return URLEncoder.encode(url, CHARSET_DEFAULT);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Encoding not supported", e);
}
}
public static String decode(String url) {
try {
return URLDecoder.decode(url, CHARSET_DEFAULT);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Decoding not supported", e);
}
}
public static String createUrl(String host, int port, String path) {
return String.format(Locale.US, "http://%s:%d/%s", host, port, Util.encode(path));
}
public static String createUrl(String host, int port, String path, String secret) {
String timestamp = String.valueOf(System.currentTimeMillis());
String sign = getHmacSha1(path + timestamp, secret);
StringBuilder sb = new StringBuilder("http://%s:%d/%s");
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpConstants.java
// public final class HttpConstants {
//
// public final static String CRLF = "\r\n";
//
// public final static String SP = " ";
//
// public final static String COLON = ":";
//
// public static final String CHARSET_DEFAULT = "UTF-8";
//
// public static final String PARAM_SIGN = "sign";
//
// public static final String PARAM_TIMESTAMP = "timestamp";
//
// private HttpConstants() {
// // Unused
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/utils/Util.java
import android.text.TextUtils;
import android.util.Base64;
import android.webkit.MimeTypeMap;
import com.vincan.medialoader.tinyhttpd.HttpConstants;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
throw new NullPointerException(object.getClass().getSimpleName() + " cann't be null");
}
}
return object;
}
public static String encode(String url) {
try {
return URLEncoder.encode(url, CHARSET_DEFAULT);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Encoding not supported", e);
}
}
public static String decode(String url) {
try {
return URLDecoder.decode(url, CHARSET_DEFAULT);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Decoding not supported", e);
}
}
public static String createUrl(String host, int port, String path) {
return String.format(Locale.US, "http://%s:%d/%s", host, port, Util.encode(path));
}
public static String createUrl(String host, int port, String path, String secret) {
String timestamp = String.valueOf(System.currentTimeMillis());
String sign = getHmacSha1(path + timestamp, secret);
StringBuilder sb = new StringBuilder("http://%s:%d/%s");
|
sb.append("?").append(HttpConstants.PARAM_SIGN).append("=%s");
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/data/file/BufferRAFileDataSource.java
|
// Path: library/src/main/java/com/vincan/medialoader/data/file/cleanup/DiskLruCache.java
// public interface DiskLruCache {
//
// void save(String url, File file);
//
// File get(String url);
//
// void remove(String url);
//
// void close();
//
// void clear();
// }
|
import com.vincan.medialoader.data.file.cleanup.DiskLruCache;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
|
package com.vincan.medialoader.data.file;
/**
* {@link BufferedRandomAccessFile}实现
*
* @author vincanyang
*/
public class BufferRAFileDataSource extends BaseFileDataSource {
private static final String TEMP_POSTFIX = ".tmp";
private BufferedRandomAccessFile mRandomAccessFile;
|
// Path: library/src/main/java/com/vincan/medialoader/data/file/cleanup/DiskLruCache.java
// public interface DiskLruCache {
//
// void save(String url, File file);
//
// File get(String url);
//
// void remove(String url);
//
// void close();
//
// void clear();
// }
// Path: library/src/main/java/com/vincan/medialoader/data/file/BufferRAFileDataSource.java
import com.vincan.medialoader.data.file.cleanup.DiskLruCache;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
package com.vincan.medialoader.data.file;
/**
* {@link BufferedRandomAccessFile}实现
*
* @author vincanyang
*/
public class BufferRAFileDataSource extends BaseFileDataSource {
private static final String TEMP_POSTFIX = ".tmp";
private BufferedRandomAccessFile mRandomAccessFile;
|
public BufferRAFileDataSource(File file, DiskLruCache diskLruStorage) throws IOException {
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/tinyhttpd/codec/HttpResponseEncoder.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpConstants.java
// public final class HttpConstants {
//
// public final static String CRLF = "\r\n";
//
// public final static String SP = " ";
//
// public final static String COLON = ":";
//
// public static final String CHARSET_DEFAULT = "UTF-8";
//
// public static final String PARAM_SIGN = "sign";
//
// public static final String PARAM_TIMESTAMP = "timestamp";
//
// private HttpConstants() {
// // Unused
// }
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/HttpResponse.java
// public final class HttpResponse implements Response {
//
// private HttpHeaders mHeaders = new HttpHeaders();
//
// private final HttpVersion mHttpVersion = HttpVersion.HTTP_1_1;
//
// private HttpStatus mStatus = HttpStatus.OK;
//
// private final SocketChannel mChannel;
//
// private ByteBuffer mResponseByteBuffer = ByteBuffer.allocate(Util.DEFAULT_BUFFER_SIZE);
//
// public HttpResponse(SocketChannel channel) {
// mChannel = channel;
// }
//
// @Override
// public void setStatus(HttpStatus status) {
// mStatus = status;
// }
//
// @Override
// public void addHeader(String key, String value) {
// mHeaders.put(key, value);
// }
//
// @Override
// public void write(byte[] bytes) throws IOException {
// write(bytes, 0, bytes.length);
// }
//
// @Override
// public void write(byte[] bytes, int offset, int length) throws IOException {
// mResponseByteBuffer.put(bytes, offset, length);
// mResponseByteBuffer.flip();
// while (mResponseByteBuffer.hasRemaining()) {//XXX 巨坑:ByteBuffer会缓存,可能不会全部写入channel
// mChannel.write(mResponseByteBuffer);
// }
// mResponseByteBuffer.clear();
// }
//
// @Override
// public HttpStatus status() {
// return mStatus;
// }
//
// @Override
// public HttpVersion protocol() {
// return mHttpVersion;
// }
//
// @Override
// public HttpHeaders headers() {
// return mHeaders;
// }
//
// @Override
// public String toString() {
// return "HttpResponse{" +
// "httpVersion=" + mHttpVersion +
// ", status=" + mStatus +
// '}';
// }
// }
|
import com.vincan.medialoader.tinyhttpd.HttpConstants;
import com.vincan.medialoader.tinyhttpd.response.HttpResponse;
import java.io.IOException;
import java.util.Map;
|
package com.vincan.medialoader.tinyhttpd.codec;
/**
* {@link HttpResponse}的编码器
*
* @author vincanyang
*/
public class HttpResponseEncoder implements ResponseEncoder<HttpResponse> {
@Override
public byte[] encode(HttpResponse response) throws IOException {
StringBuilder sb = new StringBuilder();
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpConstants.java
// public final class HttpConstants {
//
// public final static String CRLF = "\r\n";
//
// public final static String SP = " ";
//
// public final static String COLON = ":";
//
// public static final String CHARSET_DEFAULT = "UTF-8";
//
// public static final String PARAM_SIGN = "sign";
//
// public static final String PARAM_TIMESTAMP = "timestamp";
//
// private HttpConstants() {
// // Unused
// }
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/HttpResponse.java
// public final class HttpResponse implements Response {
//
// private HttpHeaders mHeaders = new HttpHeaders();
//
// private final HttpVersion mHttpVersion = HttpVersion.HTTP_1_1;
//
// private HttpStatus mStatus = HttpStatus.OK;
//
// private final SocketChannel mChannel;
//
// private ByteBuffer mResponseByteBuffer = ByteBuffer.allocate(Util.DEFAULT_BUFFER_SIZE);
//
// public HttpResponse(SocketChannel channel) {
// mChannel = channel;
// }
//
// @Override
// public void setStatus(HttpStatus status) {
// mStatus = status;
// }
//
// @Override
// public void addHeader(String key, String value) {
// mHeaders.put(key, value);
// }
//
// @Override
// public void write(byte[] bytes) throws IOException {
// write(bytes, 0, bytes.length);
// }
//
// @Override
// public void write(byte[] bytes, int offset, int length) throws IOException {
// mResponseByteBuffer.put(bytes, offset, length);
// mResponseByteBuffer.flip();
// while (mResponseByteBuffer.hasRemaining()) {//XXX 巨坑:ByteBuffer会缓存,可能不会全部写入channel
// mChannel.write(mResponseByteBuffer);
// }
// mResponseByteBuffer.clear();
// }
//
// @Override
// public HttpStatus status() {
// return mStatus;
// }
//
// @Override
// public HttpVersion protocol() {
// return mHttpVersion;
// }
//
// @Override
// public HttpHeaders headers() {
// return mHeaders;
// }
//
// @Override
// public String toString() {
// return "HttpResponse{" +
// "httpVersion=" + mHttpVersion +
// ", status=" + mStatus +
// '}';
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/codec/HttpResponseEncoder.java
import com.vincan.medialoader.tinyhttpd.HttpConstants;
import com.vincan.medialoader.tinyhttpd.response.HttpResponse;
import java.io.IOException;
import java.util.Map;
package com.vincan.medialoader.tinyhttpd.codec;
/**
* {@link HttpResponse}的编码器
*
* @author vincanyang
*/
public class HttpResponseEncoder implements ResponseEncoder<HttpResponse> {
@Override
public byte[] encode(HttpResponse response) throws IOException {
StringBuilder sb = new StringBuilder();
|
sb.append(response.protocol().toString()).append(HttpConstants.SP).append(response.status().toString());
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/data/file/RandomAcessFileDataSource.java
|
// Path: library/src/main/java/com/vincan/medialoader/data/file/cleanup/DiskLruCache.java
// public interface DiskLruCache {
//
// void save(String url, File file);
//
// File get(String url);
//
// void remove(String url);
//
// void close();
//
// void clear();
// }
//
// Path: library/src/main/java/com/vincan/medialoader/utils/LogUtil.java
// public final class LogUtil {
//
// private static final String LOG_FORMAT = "%1$s\n%2$s";
// private static volatile boolean writeDebugLogs = false;
// private static volatile boolean writeLogs = true;
//
// private LogUtil() {
// }
//
// /**
// * 进行打开或者关闭调试日志打印功能
// */
// public static void writeDebugLogs(boolean writeDebugLogs) {
// LogUtil.writeDebugLogs = writeDebugLogs;
// }
//
// /**
// * 打开或者关闭所有日志打印功能
// */
// public static void writeLogs(boolean writeLogs) {
// LogUtil.writeLogs = writeLogs;
// }
//
// public static void d(String message, Object... args) {
// if (writeDebugLogs) {
// log(Log.DEBUG, null, message, args);
// }
// }
//
// public static void i(String message, Object... args) {
// log(Log.INFO, null, message, args);
// }
//
// public static void w(String message, Object... args) {
// log(Log.WARN, null, message, args);
// }
//
// public static void e(Throwable ex) {
// log(Log.ERROR, ex, null);
// }
//
// public static void e(String message, Object... args) {
// log(Log.ERROR, null, message, args);
// }
//
// public static void e(Throwable ex, String message, Object... args) {
// log(Log.ERROR, ex, message, args);
// }
//
// /**
// * 日志格式转换 以及输出
// *
// * @param priority
// * @param ex
// * @param message
// * @param args
// */
// private static void log(int priority, Throwable ex, String message, Object... args) {
// if (!writeLogs) {
// return;
// }
// if (args.length > 0) {
// message = String.format(message, args);
// }
// String log;
// if (ex == null) {
// log = message;
// } else {
// String logMessage = message == null ? ex.getMessage() : message;
// String logBody = Log.getStackTraceString(ex);
// log = String.format(LOG_FORMAT, logMessage, logBody);
// }
// Log.println(priority, MediaLoader.TAG, log);
// }
// }
|
import com.vincan.medialoader.data.file.cleanup.DiskLruCache;
import com.vincan.medialoader.utils.LogUtil;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
|
package com.vincan.medialoader.data.file;
/**
* {@link RandomAccessFile}实现
*
* @author vincanyang
*/
public class RandomAcessFileDataSource extends BaseFileDataSource {
private static final String TEMP_POSTFIX = ".tmp";
private RandomAccessFile mRandomAccessFile;
|
// Path: library/src/main/java/com/vincan/medialoader/data/file/cleanup/DiskLruCache.java
// public interface DiskLruCache {
//
// void save(String url, File file);
//
// File get(String url);
//
// void remove(String url);
//
// void close();
//
// void clear();
// }
//
// Path: library/src/main/java/com/vincan/medialoader/utils/LogUtil.java
// public final class LogUtil {
//
// private static final String LOG_FORMAT = "%1$s\n%2$s";
// private static volatile boolean writeDebugLogs = false;
// private static volatile boolean writeLogs = true;
//
// private LogUtil() {
// }
//
// /**
// * 进行打开或者关闭调试日志打印功能
// */
// public static void writeDebugLogs(boolean writeDebugLogs) {
// LogUtil.writeDebugLogs = writeDebugLogs;
// }
//
// /**
// * 打开或者关闭所有日志打印功能
// */
// public static void writeLogs(boolean writeLogs) {
// LogUtil.writeLogs = writeLogs;
// }
//
// public static void d(String message, Object... args) {
// if (writeDebugLogs) {
// log(Log.DEBUG, null, message, args);
// }
// }
//
// public static void i(String message, Object... args) {
// log(Log.INFO, null, message, args);
// }
//
// public static void w(String message, Object... args) {
// log(Log.WARN, null, message, args);
// }
//
// public static void e(Throwable ex) {
// log(Log.ERROR, ex, null);
// }
//
// public static void e(String message, Object... args) {
// log(Log.ERROR, null, message, args);
// }
//
// public static void e(Throwable ex, String message, Object... args) {
// log(Log.ERROR, ex, message, args);
// }
//
// /**
// * 日志格式转换 以及输出
// *
// * @param priority
// * @param ex
// * @param message
// * @param args
// */
// private static void log(int priority, Throwable ex, String message, Object... args) {
// if (!writeLogs) {
// return;
// }
// if (args.length > 0) {
// message = String.format(message, args);
// }
// String log;
// if (ex == null) {
// log = message;
// } else {
// String logMessage = message == null ? ex.getMessage() : message;
// String logBody = Log.getStackTraceString(ex);
// log = String.format(LOG_FORMAT, logMessage, logBody);
// }
// Log.println(priority, MediaLoader.TAG, log);
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/data/file/RandomAcessFileDataSource.java
import com.vincan.medialoader.data.file.cleanup.DiskLruCache;
import com.vincan.medialoader.utils.LogUtil;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
package com.vincan.medialoader.data.file;
/**
* {@link RandomAccessFile}实现
*
* @author vincanyang
*/
public class RandomAcessFileDataSource extends BaseFileDataSource {
private static final String TEMP_POSTFIX = ".tmp";
private RandomAccessFile mRandomAccessFile;
|
public RandomAcessFileDataSource(File file, DiskLruCache diskLruStorage) {
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/data/file/RandomAcessFileDataSource.java
|
// Path: library/src/main/java/com/vincan/medialoader/data/file/cleanup/DiskLruCache.java
// public interface DiskLruCache {
//
// void save(String url, File file);
//
// File get(String url);
//
// void remove(String url);
//
// void close();
//
// void clear();
// }
//
// Path: library/src/main/java/com/vincan/medialoader/utils/LogUtil.java
// public final class LogUtil {
//
// private static final String LOG_FORMAT = "%1$s\n%2$s";
// private static volatile boolean writeDebugLogs = false;
// private static volatile boolean writeLogs = true;
//
// private LogUtil() {
// }
//
// /**
// * 进行打开或者关闭调试日志打印功能
// */
// public static void writeDebugLogs(boolean writeDebugLogs) {
// LogUtil.writeDebugLogs = writeDebugLogs;
// }
//
// /**
// * 打开或者关闭所有日志打印功能
// */
// public static void writeLogs(boolean writeLogs) {
// LogUtil.writeLogs = writeLogs;
// }
//
// public static void d(String message, Object... args) {
// if (writeDebugLogs) {
// log(Log.DEBUG, null, message, args);
// }
// }
//
// public static void i(String message, Object... args) {
// log(Log.INFO, null, message, args);
// }
//
// public static void w(String message, Object... args) {
// log(Log.WARN, null, message, args);
// }
//
// public static void e(Throwable ex) {
// log(Log.ERROR, ex, null);
// }
//
// public static void e(String message, Object... args) {
// log(Log.ERROR, null, message, args);
// }
//
// public static void e(Throwable ex, String message, Object... args) {
// log(Log.ERROR, ex, message, args);
// }
//
// /**
// * 日志格式转换 以及输出
// *
// * @param priority
// * @param ex
// * @param message
// * @param args
// */
// private static void log(int priority, Throwable ex, String message, Object... args) {
// if (!writeLogs) {
// return;
// }
// if (args.length > 0) {
// message = String.format(message, args);
// }
// String log;
// if (ex == null) {
// log = message;
// } else {
// String logMessage = message == null ? ex.getMessage() : message;
// String logBody = Log.getStackTraceString(ex);
// log = String.format(LOG_FORMAT, logMessage, logBody);
// }
// Log.println(priority, MediaLoader.TAG, log);
// }
// }
|
import com.vincan.medialoader.data.file.cleanup.DiskLruCache;
import com.vincan.medialoader.utils.LogUtil;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
|
package com.vincan.medialoader.data.file;
/**
* {@link RandomAccessFile}实现
*
* @author vincanyang
*/
public class RandomAcessFileDataSource extends BaseFileDataSource {
private static final String TEMP_POSTFIX = ".tmp";
private RandomAccessFile mRandomAccessFile;
public RandomAcessFileDataSource(File file, DiskLruCache diskLruStorage) {
super(file, diskLruStorage);
try{
boolean completed = file.exists();
mOriginFile = completed ? file : new File(file.getParentFile(), file.getName() + TEMP_POSTFIX);
mRandomAccessFile = new RandomAccessFile(mOriginFile, completed ? "r" : "rw");
}catch (IOException e){
//should not happen
|
// Path: library/src/main/java/com/vincan/medialoader/data/file/cleanup/DiskLruCache.java
// public interface DiskLruCache {
//
// void save(String url, File file);
//
// File get(String url);
//
// void remove(String url);
//
// void close();
//
// void clear();
// }
//
// Path: library/src/main/java/com/vincan/medialoader/utils/LogUtil.java
// public final class LogUtil {
//
// private static final String LOG_FORMAT = "%1$s\n%2$s";
// private static volatile boolean writeDebugLogs = false;
// private static volatile boolean writeLogs = true;
//
// private LogUtil() {
// }
//
// /**
// * 进行打开或者关闭调试日志打印功能
// */
// public static void writeDebugLogs(boolean writeDebugLogs) {
// LogUtil.writeDebugLogs = writeDebugLogs;
// }
//
// /**
// * 打开或者关闭所有日志打印功能
// */
// public static void writeLogs(boolean writeLogs) {
// LogUtil.writeLogs = writeLogs;
// }
//
// public static void d(String message, Object... args) {
// if (writeDebugLogs) {
// log(Log.DEBUG, null, message, args);
// }
// }
//
// public static void i(String message, Object... args) {
// log(Log.INFO, null, message, args);
// }
//
// public static void w(String message, Object... args) {
// log(Log.WARN, null, message, args);
// }
//
// public static void e(Throwable ex) {
// log(Log.ERROR, ex, null);
// }
//
// public static void e(String message, Object... args) {
// log(Log.ERROR, null, message, args);
// }
//
// public static void e(Throwable ex, String message, Object... args) {
// log(Log.ERROR, ex, message, args);
// }
//
// /**
// * 日志格式转换 以及输出
// *
// * @param priority
// * @param ex
// * @param message
// * @param args
// */
// private static void log(int priority, Throwable ex, String message, Object... args) {
// if (!writeLogs) {
// return;
// }
// if (args.length > 0) {
// message = String.format(message, args);
// }
// String log;
// if (ex == null) {
// log = message;
// } else {
// String logMessage = message == null ? ex.getMessage() : message;
// String logBody = Log.getStackTraceString(ex);
// log = String.format(LOG_FORMAT, logMessage, logBody);
// }
// Log.println(priority, MediaLoader.TAG, log);
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/data/file/RandomAcessFileDataSource.java
import com.vincan.medialoader.data.file.cleanup.DiskLruCache;
import com.vincan.medialoader.utils.LogUtil;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
package com.vincan.medialoader.data.file;
/**
* {@link RandomAccessFile}实现
*
* @author vincanyang
*/
public class RandomAcessFileDataSource extends BaseFileDataSource {
private static final String TEMP_POSTFIX = ".tmp";
private RandomAccessFile mRandomAccessFile;
public RandomAcessFileDataSource(File file, DiskLruCache diskLruStorage) {
super(file, diskLruStorage);
try{
boolean completed = file.exists();
mOriginFile = completed ? file : new File(file.getParentFile(), file.getName() + TEMP_POSTFIX);
mRandomAccessFile = new RandomAccessFile(mOriginFile, completed ? "r" : "rw");
}catch (IOException e){
//should not happen
|
LogUtil.e(e);
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/data/file/naming/Md5FileNameCreator.java
|
// Path: library/src/main/java/com/vincan/medialoader/utils/Util.java
// public final class Util {
//
// public static final String LOCALHOST = "127.0.0.1";//不建议使用localhost,因为需要访问网络
//
// public static final int DEFAULT_BUFFER_SIZE = 8192;//8 * 1024
//
// public static final String CHARSET_DEFAULT = "UTF-8";
//
// private static final int MAX_EXTENSION_LENGTH = 4;
//
// private Util() {
//
// }
//
// public static <T> T notEmpty(T object) {
// if (object instanceof String) {
// if (TextUtils.isEmpty((String) object)) {
// throw new NullPointerException(object.getClass().getSimpleName() + " cann't be empty");
// }
// } else {
// if (object == null) {
// throw new NullPointerException(object.getClass().getSimpleName() + " cann't be null");
// }
// }
// return object;
// }
//
// public static String encode(String url) {
// try {
// return URLEncoder.encode(url, CHARSET_DEFAULT);
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("Encoding not supported", e);
// }
// }
//
// public static String decode(String url) {
// try {
// return URLDecoder.decode(url, CHARSET_DEFAULT);
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("Decoding not supported", e);
// }
// }
//
// public static String createUrl(String host, int port, String path) {
// return String.format(Locale.US, "http://%s:%d/%s", host, port, Util.encode(path));
// }
//
// public static String createUrl(String host, int port, String path, String secret) {
// String timestamp = String.valueOf(System.currentTimeMillis());
// String sign = getHmacSha1(path + timestamp, secret);
// StringBuilder sb = new StringBuilder("http://%s:%d/%s");
// sb.append("?").append(HttpConstants.PARAM_SIGN).append("=%s");
// sb.append("&").append(HttpConstants.PARAM_TIMESTAMP).append("=%s");
// return String.format(Locale.US, sb.toString(), host, port, Util.encode(path), Util.encode(sign), Util.encode(timestamp));
// }
//
// public static String getHmacSha1(String s, String keyString) {
// String hmacSha1 = null;
// try {
// SecretKeySpec key = new SecretKeySpec((keyString).getBytes(), "HmacSHA1");
// Mac mac = Mac.getInstance("HmacSHA1");
// mac.init(key);
// byte[] bytes = mac.doFinal(s.getBytes());
// hmacSha1 = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
// } catch (InvalidKeyException | NoSuchAlgorithmException e) {
//
// }
// return hmacSha1;
// }
//
// public static String getMimeTypeFromUrl(String url) {
// String extension = MimeTypeMap.getFileExtensionFromUrl(url);
// return TextUtils.isEmpty(extension) ? "" : MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
// }
//
// public static String getExtensionFromUrl(String url) {
// int dotIndex = url.lastIndexOf('.');
// int slashIndex = url.lastIndexOf('/');
// return dotIndex != -1 && dotIndex > slashIndex && dotIndex + 2 + MAX_EXTENSION_LENGTH > url.length() ?
// url.substring(dotIndex + 1, url.length()) : "";
// }
//
// public static String getMD5(String string) {
// try {
// MessageDigest messageDigest = MessageDigest.getInstance("MD5");
// byte[] digestBytes = messageDigest.digest(string.getBytes());
// return bytesToHexString(digestBytes);
// } catch (NoSuchAlgorithmException e) {
// throw new IllegalStateException(e);
// }
// }
//
// private static String bytesToHexString(byte[] bytes) {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < bytes.length; i++) {
// sb.append(String.format("%02x", bytes[i]));// 以十六进制(x)输出,2为指定的输出字段的宽度.如果位数小于2,则左端补0
// }
// return sb.toString();
// }
// }
|
import android.text.TextUtils;
import com.vincan.medialoader.utils.Util;
|
package com.vincan.medialoader.data.file.naming;
/**
* 使用图片URL地址的 MD5编码来进行生成缓存的文件名称
*
* @author vincanyang
*/
public class Md5FileNameCreator implements FileNameCreator {
@Override
public String create(String url) {
|
// Path: library/src/main/java/com/vincan/medialoader/utils/Util.java
// public final class Util {
//
// public static final String LOCALHOST = "127.0.0.1";//不建议使用localhost,因为需要访问网络
//
// public static final int DEFAULT_BUFFER_SIZE = 8192;//8 * 1024
//
// public static final String CHARSET_DEFAULT = "UTF-8";
//
// private static final int MAX_EXTENSION_LENGTH = 4;
//
// private Util() {
//
// }
//
// public static <T> T notEmpty(T object) {
// if (object instanceof String) {
// if (TextUtils.isEmpty((String) object)) {
// throw new NullPointerException(object.getClass().getSimpleName() + " cann't be empty");
// }
// } else {
// if (object == null) {
// throw new NullPointerException(object.getClass().getSimpleName() + " cann't be null");
// }
// }
// return object;
// }
//
// public static String encode(String url) {
// try {
// return URLEncoder.encode(url, CHARSET_DEFAULT);
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("Encoding not supported", e);
// }
// }
//
// public static String decode(String url) {
// try {
// return URLDecoder.decode(url, CHARSET_DEFAULT);
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("Decoding not supported", e);
// }
// }
//
// public static String createUrl(String host, int port, String path) {
// return String.format(Locale.US, "http://%s:%d/%s", host, port, Util.encode(path));
// }
//
// public static String createUrl(String host, int port, String path, String secret) {
// String timestamp = String.valueOf(System.currentTimeMillis());
// String sign = getHmacSha1(path + timestamp, secret);
// StringBuilder sb = new StringBuilder("http://%s:%d/%s");
// sb.append("?").append(HttpConstants.PARAM_SIGN).append("=%s");
// sb.append("&").append(HttpConstants.PARAM_TIMESTAMP).append("=%s");
// return String.format(Locale.US, sb.toString(), host, port, Util.encode(path), Util.encode(sign), Util.encode(timestamp));
// }
//
// public static String getHmacSha1(String s, String keyString) {
// String hmacSha1 = null;
// try {
// SecretKeySpec key = new SecretKeySpec((keyString).getBytes(), "HmacSHA1");
// Mac mac = Mac.getInstance("HmacSHA1");
// mac.init(key);
// byte[] bytes = mac.doFinal(s.getBytes());
// hmacSha1 = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
// } catch (InvalidKeyException | NoSuchAlgorithmException e) {
//
// }
// return hmacSha1;
// }
//
// public static String getMimeTypeFromUrl(String url) {
// String extension = MimeTypeMap.getFileExtensionFromUrl(url);
// return TextUtils.isEmpty(extension) ? "" : MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
// }
//
// public static String getExtensionFromUrl(String url) {
// int dotIndex = url.lastIndexOf('.');
// int slashIndex = url.lastIndexOf('/');
// return dotIndex != -1 && dotIndex > slashIndex && dotIndex + 2 + MAX_EXTENSION_LENGTH > url.length() ?
// url.substring(dotIndex + 1, url.length()) : "";
// }
//
// public static String getMD5(String string) {
// try {
// MessageDigest messageDigest = MessageDigest.getInstance("MD5");
// byte[] digestBytes = messageDigest.digest(string.getBytes());
// return bytesToHexString(digestBytes);
// } catch (NoSuchAlgorithmException e) {
// throw new IllegalStateException(e);
// }
// }
//
// private static String bytesToHexString(byte[] bytes) {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < bytes.length; i++) {
// sb.append(String.format("%02x", bytes[i]));// 以十六进制(x)输出,2为指定的输出字段的宽度.如果位数小于2,则左端补0
// }
// return sb.toString();
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/data/file/naming/Md5FileNameCreator.java
import android.text.TextUtils;
import com.vincan.medialoader.utils.Util;
package com.vincan.medialoader.data.file.naming;
/**
* 使用图片URL地址的 MD5编码来进行生成缓存的文件名称
*
* @author vincanyang
*/
public class Md5FileNameCreator implements FileNameCreator {
@Override
public String create(String url) {
|
String extension = Util.getExtensionFromUrl(url);
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpHeaders.java
// public class HttpHeaders extends LinkedHashMap<String, String> {
//
// private static final Pattern HEADER_RANGE_PATTERN = Pattern.compile("bytes=(\\d*)-");
//
// public interface Names {
// String RANGE = "Range";
// String ACCEPT_RANGES = "Accept-Ranges";
// String CONTENT_LENGTH = "Content-Length";
// String CONTENT_RANGE = "Content-Range";
// String CONTENT_TYPE = "Content-Type";
// }
//
// public interface Values {
// String BYTES = "bytes";
// }
//
// private long mRangeOffset = Long.MIN_VALUE;
//
// public long getRangeOffset() {
// if (mRangeOffset == Long.MIN_VALUE) {
// String range = get(HttpHeaders.Names.RANGE);
// if (!TextUtils.isEmpty(range)) {
// Matcher matcher = HEADER_RANGE_PATTERN.matcher(range);
// if (matcher.find()) {
// String rangeValue = matcher.group(1);
// mRangeOffset = Long.parseLong(rangeValue);
// }
// }
// }
// return Math.max(mRangeOffset, 0);
// }
//
// public boolean isPartial() {
// return containsKey(HttpHeaders.Names.RANGE);
// }
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpVersion.java
// public enum HttpVersion {
//
// HTTP_1_0("HTTP/1.0"),
//
// HTTP_1_1("HTTP/1.1"),
//
// HTTP_2("H2");
//
// private final String version;
//
// HttpVersion(String version) {
// this.version = version;
// }
//
// public static HttpVersion get(String version) throws IOException {
// if (version.equals(HTTP_1_0.version)) {
// return HTTP_1_0;
// } else if (version.equals(HTTP_1_1.version)) {
// return HTTP_1_1;
// } else if (version.equals(HTTP_2.version)) {
// return HTTP_2;
// }
// throw new IOException("Unexpected version: " + version);
// }
//
// @Override
// public String toString() {
// return version;
// }
// }
|
import com.vincan.medialoader.tinyhttpd.HttpHeaders;
import com.vincan.medialoader.tinyhttpd.HttpVersion;
|
package com.vincan.medialoader.tinyhttpd.request;
/**
* 请求接口
*
* @author vincanyang
*/
public interface Request {
HttpMethod method();
String url();
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpHeaders.java
// public class HttpHeaders extends LinkedHashMap<String, String> {
//
// private static final Pattern HEADER_RANGE_PATTERN = Pattern.compile("bytes=(\\d*)-");
//
// public interface Names {
// String RANGE = "Range";
// String ACCEPT_RANGES = "Accept-Ranges";
// String CONTENT_LENGTH = "Content-Length";
// String CONTENT_RANGE = "Content-Range";
// String CONTENT_TYPE = "Content-Type";
// }
//
// public interface Values {
// String BYTES = "bytes";
// }
//
// private long mRangeOffset = Long.MIN_VALUE;
//
// public long getRangeOffset() {
// if (mRangeOffset == Long.MIN_VALUE) {
// String range = get(HttpHeaders.Names.RANGE);
// if (!TextUtils.isEmpty(range)) {
// Matcher matcher = HEADER_RANGE_PATTERN.matcher(range);
// if (matcher.find()) {
// String rangeValue = matcher.group(1);
// mRangeOffset = Long.parseLong(rangeValue);
// }
// }
// }
// return Math.max(mRangeOffset, 0);
// }
//
// public boolean isPartial() {
// return containsKey(HttpHeaders.Names.RANGE);
// }
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpVersion.java
// public enum HttpVersion {
//
// HTTP_1_0("HTTP/1.0"),
//
// HTTP_1_1("HTTP/1.1"),
//
// HTTP_2("H2");
//
// private final String version;
//
// HttpVersion(String version) {
// this.version = version;
// }
//
// public static HttpVersion get(String version) throws IOException {
// if (version.equals(HTTP_1_0.version)) {
// return HTTP_1_0;
// } else if (version.equals(HTTP_1_1.version)) {
// return HTTP_1_1;
// } else if (version.equals(HTTP_2.version)) {
// return HTTP_2;
// }
// throw new IOException("Unexpected version: " + version);
// }
//
// @Override
// public String toString() {
// return version;
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
import com.vincan.medialoader.tinyhttpd.HttpHeaders;
import com.vincan.medialoader.tinyhttpd.HttpVersion;
package com.vincan.medialoader.tinyhttpd.request;
/**
* 请求接口
*
* @author vincanyang
*/
public interface Request {
HttpMethod method();
String url();
|
HttpVersion protocol();
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpHeaders.java
// public class HttpHeaders extends LinkedHashMap<String, String> {
//
// private static final Pattern HEADER_RANGE_PATTERN = Pattern.compile("bytes=(\\d*)-");
//
// public interface Names {
// String RANGE = "Range";
// String ACCEPT_RANGES = "Accept-Ranges";
// String CONTENT_LENGTH = "Content-Length";
// String CONTENT_RANGE = "Content-Range";
// String CONTENT_TYPE = "Content-Type";
// }
//
// public interface Values {
// String BYTES = "bytes";
// }
//
// private long mRangeOffset = Long.MIN_VALUE;
//
// public long getRangeOffset() {
// if (mRangeOffset == Long.MIN_VALUE) {
// String range = get(HttpHeaders.Names.RANGE);
// if (!TextUtils.isEmpty(range)) {
// Matcher matcher = HEADER_RANGE_PATTERN.matcher(range);
// if (matcher.find()) {
// String rangeValue = matcher.group(1);
// mRangeOffset = Long.parseLong(rangeValue);
// }
// }
// }
// return Math.max(mRangeOffset, 0);
// }
//
// public boolean isPartial() {
// return containsKey(HttpHeaders.Names.RANGE);
// }
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpVersion.java
// public enum HttpVersion {
//
// HTTP_1_0("HTTP/1.0"),
//
// HTTP_1_1("HTTP/1.1"),
//
// HTTP_2("H2");
//
// private final String version;
//
// HttpVersion(String version) {
// this.version = version;
// }
//
// public static HttpVersion get(String version) throws IOException {
// if (version.equals(HTTP_1_0.version)) {
// return HTTP_1_0;
// } else if (version.equals(HTTP_1_1.version)) {
// return HTTP_1_1;
// } else if (version.equals(HTTP_2.version)) {
// return HTTP_2;
// }
// throw new IOException("Unexpected version: " + version);
// }
//
// @Override
// public String toString() {
// return version;
// }
// }
|
import com.vincan.medialoader.tinyhttpd.HttpHeaders;
import com.vincan.medialoader.tinyhttpd.HttpVersion;
|
package com.vincan.medialoader.tinyhttpd.request;
/**
* 请求接口
*
* @author vincanyang
*/
public interface Request {
HttpMethod method();
String url();
HttpVersion protocol();
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpHeaders.java
// public class HttpHeaders extends LinkedHashMap<String, String> {
//
// private static final Pattern HEADER_RANGE_PATTERN = Pattern.compile("bytes=(\\d*)-");
//
// public interface Names {
// String RANGE = "Range";
// String ACCEPT_RANGES = "Accept-Ranges";
// String CONTENT_LENGTH = "Content-Length";
// String CONTENT_RANGE = "Content-Range";
// String CONTENT_TYPE = "Content-Type";
// }
//
// public interface Values {
// String BYTES = "bytes";
// }
//
// private long mRangeOffset = Long.MIN_VALUE;
//
// public long getRangeOffset() {
// if (mRangeOffset == Long.MIN_VALUE) {
// String range = get(HttpHeaders.Names.RANGE);
// if (!TextUtils.isEmpty(range)) {
// Matcher matcher = HEADER_RANGE_PATTERN.matcher(range);
// if (matcher.find()) {
// String rangeValue = matcher.group(1);
// mRangeOffset = Long.parseLong(rangeValue);
// }
// }
// }
// return Math.max(mRangeOffset, 0);
// }
//
// public boolean isPartial() {
// return containsKey(HttpHeaders.Names.RANGE);
// }
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpVersion.java
// public enum HttpVersion {
//
// HTTP_1_0("HTTP/1.0"),
//
// HTTP_1_1("HTTP/1.1"),
//
// HTTP_2("H2");
//
// private final String version;
//
// HttpVersion(String version) {
// this.version = version;
// }
//
// public static HttpVersion get(String version) throws IOException {
// if (version.equals(HTTP_1_0.version)) {
// return HTTP_1_0;
// } else if (version.equals(HTTP_1_1.version)) {
// return HTTP_1_1;
// } else if (version.equals(HTTP_2.version)) {
// return HTTP_2;
// }
// throw new IOException("Unexpected version: " + version);
// }
//
// @Override
// public String toString() {
// return version;
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
import com.vincan.medialoader.tinyhttpd.HttpHeaders;
import com.vincan.medialoader.tinyhttpd.HttpVersion;
package com.vincan.medialoader.tinyhttpd.request;
/**
* 请求接口
*
* @author vincanyang
*/
public interface Request {
HttpMethod method();
String url();
HttpVersion protocol();
|
HttpHeaders headers();
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpVersion.java
// public enum HttpVersion {
//
// HTTP_1_0("HTTP/1.0"),
//
// HTTP_1_1("HTTP/1.1"),
//
// HTTP_2("H2");
//
// private final String version;
//
// HttpVersion(String version) {
// this.version = version;
// }
//
// public static HttpVersion get(String version) throws IOException {
// if (version.equals(HTTP_1_0.version)) {
// return HTTP_1_0;
// } else if (version.equals(HTTP_1_1.version)) {
// return HTTP_1_1;
// } else if (version.equals(HTTP_2.version)) {
// return HTTP_2;
// }
// throw new IOException("Unexpected version: " + version);
// }
//
// @Override
// public String toString() {
// return version;
// }
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpHeaders.java
// public class HttpHeaders extends LinkedHashMap<String, String> {
//
// private static final Pattern HEADER_RANGE_PATTERN = Pattern.compile("bytes=(\\d*)-");
//
// public interface Names {
// String RANGE = "Range";
// String ACCEPT_RANGES = "Accept-Ranges";
// String CONTENT_LENGTH = "Content-Length";
// String CONTENT_RANGE = "Content-Range";
// String CONTENT_TYPE = "Content-Type";
// }
//
// public interface Values {
// String BYTES = "bytes";
// }
//
// private long mRangeOffset = Long.MIN_VALUE;
//
// public long getRangeOffset() {
// if (mRangeOffset == Long.MIN_VALUE) {
// String range = get(HttpHeaders.Names.RANGE);
// if (!TextUtils.isEmpty(range)) {
// Matcher matcher = HEADER_RANGE_PATTERN.matcher(range);
// if (matcher.find()) {
// String rangeValue = matcher.group(1);
// mRangeOffset = Long.parseLong(rangeValue);
// }
// }
// }
// return Math.max(mRangeOffset, 0);
// }
//
// public boolean isPartial() {
// return containsKey(HttpHeaders.Names.RANGE);
// }
// }
|
import com.vincan.medialoader.tinyhttpd.HttpVersion;
import com.vincan.medialoader.tinyhttpd.HttpHeaders;
import java.io.IOException;
|
package com.vincan.medialoader.tinyhttpd.response;
/**
* 响应接口
*
* @author vincanyang
*/
public interface Response {
HttpStatus status();
void setStatus(HttpStatus status);
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpVersion.java
// public enum HttpVersion {
//
// HTTP_1_0("HTTP/1.0"),
//
// HTTP_1_1("HTTP/1.1"),
//
// HTTP_2("H2");
//
// private final String version;
//
// HttpVersion(String version) {
// this.version = version;
// }
//
// public static HttpVersion get(String version) throws IOException {
// if (version.equals(HTTP_1_0.version)) {
// return HTTP_1_0;
// } else if (version.equals(HTTP_1_1.version)) {
// return HTTP_1_1;
// } else if (version.equals(HTTP_2.version)) {
// return HTTP_2;
// }
// throw new IOException("Unexpected version: " + version);
// }
//
// @Override
// public String toString() {
// return version;
// }
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpHeaders.java
// public class HttpHeaders extends LinkedHashMap<String, String> {
//
// private static final Pattern HEADER_RANGE_PATTERN = Pattern.compile("bytes=(\\d*)-");
//
// public interface Names {
// String RANGE = "Range";
// String ACCEPT_RANGES = "Accept-Ranges";
// String CONTENT_LENGTH = "Content-Length";
// String CONTENT_RANGE = "Content-Range";
// String CONTENT_TYPE = "Content-Type";
// }
//
// public interface Values {
// String BYTES = "bytes";
// }
//
// private long mRangeOffset = Long.MIN_VALUE;
//
// public long getRangeOffset() {
// if (mRangeOffset == Long.MIN_VALUE) {
// String range = get(HttpHeaders.Names.RANGE);
// if (!TextUtils.isEmpty(range)) {
// Matcher matcher = HEADER_RANGE_PATTERN.matcher(range);
// if (matcher.find()) {
// String rangeValue = matcher.group(1);
// mRangeOffset = Long.parseLong(rangeValue);
// }
// }
// }
// return Math.max(mRangeOffset, 0);
// }
//
// public boolean isPartial() {
// return containsKey(HttpHeaders.Names.RANGE);
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
import com.vincan.medialoader.tinyhttpd.HttpVersion;
import com.vincan.medialoader.tinyhttpd.HttpHeaders;
import java.io.IOException;
package com.vincan.medialoader.tinyhttpd.response;
/**
* 响应接口
*
* @author vincanyang
*/
public interface Response {
HttpStatus status();
void setStatus(HttpStatus status);
|
HttpVersion protocol();
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpVersion.java
// public enum HttpVersion {
//
// HTTP_1_0("HTTP/1.0"),
//
// HTTP_1_1("HTTP/1.1"),
//
// HTTP_2("H2");
//
// private final String version;
//
// HttpVersion(String version) {
// this.version = version;
// }
//
// public static HttpVersion get(String version) throws IOException {
// if (version.equals(HTTP_1_0.version)) {
// return HTTP_1_0;
// } else if (version.equals(HTTP_1_1.version)) {
// return HTTP_1_1;
// } else if (version.equals(HTTP_2.version)) {
// return HTTP_2;
// }
// throw new IOException("Unexpected version: " + version);
// }
//
// @Override
// public String toString() {
// return version;
// }
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpHeaders.java
// public class HttpHeaders extends LinkedHashMap<String, String> {
//
// private static final Pattern HEADER_RANGE_PATTERN = Pattern.compile("bytes=(\\d*)-");
//
// public interface Names {
// String RANGE = "Range";
// String ACCEPT_RANGES = "Accept-Ranges";
// String CONTENT_LENGTH = "Content-Length";
// String CONTENT_RANGE = "Content-Range";
// String CONTENT_TYPE = "Content-Type";
// }
//
// public interface Values {
// String BYTES = "bytes";
// }
//
// private long mRangeOffset = Long.MIN_VALUE;
//
// public long getRangeOffset() {
// if (mRangeOffset == Long.MIN_VALUE) {
// String range = get(HttpHeaders.Names.RANGE);
// if (!TextUtils.isEmpty(range)) {
// Matcher matcher = HEADER_RANGE_PATTERN.matcher(range);
// if (matcher.find()) {
// String rangeValue = matcher.group(1);
// mRangeOffset = Long.parseLong(rangeValue);
// }
// }
// }
// return Math.max(mRangeOffset, 0);
// }
//
// public boolean isPartial() {
// return containsKey(HttpHeaders.Names.RANGE);
// }
// }
|
import com.vincan.medialoader.tinyhttpd.HttpVersion;
import com.vincan.medialoader.tinyhttpd.HttpHeaders;
import java.io.IOException;
|
package com.vincan.medialoader.tinyhttpd.response;
/**
* 响应接口
*
* @author vincanyang
*/
public interface Response {
HttpStatus status();
void setStatus(HttpStatus status);
HttpVersion protocol();
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpVersion.java
// public enum HttpVersion {
//
// HTTP_1_0("HTTP/1.0"),
//
// HTTP_1_1("HTTP/1.1"),
//
// HTTP_2("H2");
//
// private final String version;
//
// HttpVersion(String version) {
// this.version = version;
// }
//
// public static HttpVersion get(String version) throws IOException {
// if (version.equals(HTTP_1_0.version)) {
// return HTTP_1_0;
// } else if (version.equals(HTTP_1_1.version)) {
// return HTTP_1_1;
// } else if (version.equals(HTTP_2.version)) {
// return HTTP_2;
// }
// throw new IOException("Unexpected version: " + version);
// }
//
// @Override
// public String toString() {
// return version;
// }
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/HttpHeaders.java
// public class HttpHeaders extends LinkedHashMap<String, String> {
//
// private static final Pattern HEADER_RANGE_PATTERN = Pattern.compile("bytes=(\\d*)-");
//
// public interface Names {
// String RANGE = "Range";
// String ACCEPT_RANGES = "Accept-Ranges";
// String CONTENT_LENGTH = "Content-Length";
// String CONTENT_RANGE = "Content-Range";
// String CONTENT_TYPE = "Content-Type";
// }
//
// public interface Values {
// String BYTES = "bytes";
// }
//
// private long mRangeOffset = Long.MIN_VALUE;
//
// public long getRangeOffset() {
// if (mRangeOffset == Long.MIN_VALUE) {
// String range = get(HttpHeaders.Names.RANGE);
// if (!TextUtils.isEmpty(range)) {
// Matcher matcher = HEADER_RANGE_PATTERN.matcher(range);
// if (matcher.find()) {
// String rangeValue = matcher.group(1);
// mRangeOffset = Long.parseLong(rangeValue);
// }
// }
// }
// return Math.max(mRangeOffset, 0);
// }
//
// public boolean isPartial() {
// return containsKey(HttpHeaders.Names.RANGE);
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
import com.vincan.medialoader.tinyhttpd.HttpVersion;
import com.vincan.medialoader.tinyhttpd.HttpHeaders;
import java.io.IOException;
package com.vincan.medialoader.tinyhttpd.response;
/**
* 响应接口
*
* @author vincanyang
*/
public interface Response {
HttpStatus status();
void setStatus(HttpStatus status);
HttpVersion protocol();
|
HttpHeaders headers();
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/tinyhttpd/interceptor/Interceptor.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
// public interface Request {
//
// HttpMethod method();
//
// String url();
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// String getParam(String name);
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
// public interface Response {
//
// HttpStatus status();
//
// void setStatus(HttpStatus status);
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// /**
// * 添加头部
// *
// * @param key {@link com.vincan.medialoader.tinyhttpd.HttpHeaders.Names}
// * @param value
// */
// void addHeader(String key, String value);
//
// void write(byte[] bytes) throws IOException;
//
// void write(byte[] bytes, int offset, int length) throws IOException;
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/ResponseException.java
// public final class ResponseException extends Exception {
//
// private final HttpStatus status;
//
// public ResponseException(HttpStatus status) {
// super(status.desc);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message) {
// super(message);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message, Exception e) {
// super(message, e);
// this.status = status;
// }
//
// public HttpStatus getStatus() {
// return this.status;
// }
// }
|
import com.vincan.medialoader.tinyhttpd.request.Request;
import com.vincan.medialoader.tinyhttpd.response.Response;
import com.vincan.medialoader.tinyhttpd.response.ResponseException;
import java.io.IOException;
|
package com.vincan.medialoader.tinyhttpd.interceptor;
/**
* 拦截器
*
* @author wencanyang
*/
public interface Interceptor {
void intercept(Chain chain) throws ResponseException, IOException;
/**
* 拦截器链
*/
interface Chain {
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
// public interface Request {
//
// HttpMethod method();
//
// String url();
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// String getParam(String name);
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
// public interface Response {
//
// HttpStatus status();
//
// void setStatus(HttpStatus status);
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// /**
// * 添加头部
// *
// * @param key {@link com.vincan.medialoader.tinyhttpd.HttpHeaders.Names}
// * @param value
// */
// void addHeader(String key, String value);
//
// void write(byte[] bytes) throws IOException;
//
// void write(byte[] bytes, int offset, int length) throws IOException;
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/ResponseException.java
// public final class ResponseException extends Exception {
//
// private final HttpStatus status;
//
// public ResponseException(HttpStatus status) {
// super(status.desc);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message) {
// super(message);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message, Exception e) {
// super(message, e);
// this.status = status;
// }
//
// public HttpStatus getStatus() {
// return this.status;
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/interceptor/Interceptor.java
import com.vincan.medialoader.tinyhttpd.request.Request;
import com.vincan.medialoader.tinyhttpd.response.Response;
import com.vincan.medialoader.tinyhttpd.response.ResponseException;
import java.io.IOException;
package com.vincan.medialoader.tinyhttpd.interceptor;
/**
* 拦截器
*
* @author wencanyang
*/
public interface Interceptor {
void intercept(Chain chain) throws ResponseException, IOException;
/**
* 拦截器链
*/
interface Chain {
|
Request request();
|
yangwencan2002/MediaLoader
|
library/src/main/java/com/vincan/medialoader/tinyhttpd/interceptor/Interceptor.java
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
// public interface Request {
//
// HttpMethod method();
//
// String url();
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// String getParam(String name);
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
// public interface Response {
//
// HttpStatus status();
//
// void setStatus(HttpStatus status);
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// /**
// * 添加头部
// *
// * @param key {@link com.vincan.medialoader.tinyhttpd.HttpHeaders.Names}
// * @param value
// */
// void addHeader(String key, String value);
//
// void write(byte[] bytes) throws IOException;
//
// void write(byte[] bytes, int offset, int length) throws IOException;
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/ResponseException.java
// public final class ResponseException extends Exception {
//
// private final HttpStatus status;
//
// public ResponseException(HttpStatus status) {
// super(status.desc);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message) {
// super(message);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message, Exception e) {
// super(message, e);
// this.status = status;
// }
//
// public HttpStatus getStatus() {
// return this.status;
// }
// }
|
import com.vincan.medialoader.tinyhttpd.request.Request;
import com.vincan.medialoader.tinyhttpd.response.Response;
import com.vincan.medialoader.tinyhttpd.response.ResponseException;
import java.io.IOException;
|
package com.vincan.medialoader.tinyhttpd.interceptor;
/**
* 拦截器
*
* @author wencanyang
*/
public interface Interceptor {
void intercept(Chain chain) throws ResponseException, IOException;
/**
* 拦截器链
*/
interface Chain {
Request request();
|
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/request/Request.java
// public interface Request {
//
// HttpMethod method();
//
// String url();
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// String getParam(String name);
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/Response.java
// public interface Response {
//
// HttpStatus status();
//
// void setStatus(HttpStatus status);
//
// HttpVersion protocol();
//
// HttpHeaders headers();
//
// /**
// * 添加头部
// *
// * @param key {@link com.vincan.medialoader.tinyhttpd.HttpHeaders.Names}
// * @param value
// */
// void addHeader(String key, String value);
//
// void write(byte[] bytes) throws IOException;
//
// void write(byte[] bytes, int offset, int length) throws IOException;
// }
//
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/response/ResponseException.java
// public final class ResponseException extends Exception {
//
// private final HttpStatus status;
//
// public ResponseException(HttpStatus status) {
// super(status.desc);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message) {
// super(message);
// this.status = status;
// }
//
// public ResponseException(HttpStatus status, String message, Exception e) {
// super(message, e);
// this.status = status;
// }
//
// public HttpStatus getStatus() {
// return this.status;
// }
// }
// Path: library/src/main/java/com/vincan/medialoader/tinyhttpd/interceptor/Interceptor.java
import com.vincan.medialoader.tinyhttpd.request.Request;
import com.vincan.medialoader.tinyhttpd.response.Response;
import com.vincan.medialoader.tinyhttpd.response.ResponseException;
import java.io.IOException;
package com.vincan.medialoader.tinyhttpd.interceptor;
/**
* 拦截器
*
* @author wencanyang
*/
public interface Interceptor {
void intercept(Chain chain) throws ResponseException, IOException;
/**
* 拦截器链
*/
interface Chain {
Request request();
|
Response response();
|
yangwencan2002/MediaLoader
|
library/src/test/java/com/vincan/medialoader/data/file/naming/FileNameCreatorTest.java
|
// Path: library/src/main/java/com/vincan/medialoader/utils/Util.java
// public final class Util {
//
// public static final String LOCALHOST = "127.0.0.1";//不建议使用localhost,因为需要访问网络
//
// public static final int DEFAULT_BUFFER_SIZE = 8192;//8 * 1024
//
// public static final String CHARSET_DEFAULT = "UTF-8";
//
// private static final int MAX_EXTENSION_LENGTH = 4;
//
// private Util() {
//
// }
//
// public static <T> T notEmpty(T object) {
// if (object instanceof String) {
// if (TextUtils.isEmpty((String) object)) {
// throw new NullPointerException(object.getClass().getSimpleName() + " cann't be empty");
// }
// } else {
// if (object == null) {
// throw new NullPointerException(object.getClass().getSimpleName() + " cann't be null");
// }
// }
// return object;
// }
//
// public static String encode(String url) {
// try {
// return URLEncoder.encode(url, CHARSET_DEFAULT);
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("Encoding not supported", e);
// }
// }
//
// public static String decode(String url) {
// try {
// return URLDecoder.decode(url, CHARSET_DEFAULT);
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("Decoding not supported", e);
// }
// }
//
// public static String createUrl(String host, int port, String path) {
// return String.format(Locale.US, "http://%s:%d/%s", host, port, Util.encode(path));
// }
//
// public static String createUrl(String host, int port, String path, String secret) {
// String timestamp = String.valueOf(System.currentTimeMillis());
// String sign = getHmacSha1(path + timestamp, secret);
// StringBuilder sb = new StringBuilder("http://%s:%d/%s");
// sb.append("?").append(HttpConstants.PARAM_SIGN).append("=%s");
// sb.append("&").append(HttpConstants.PARAM_TIMESTAMP).append("=%s");
// return String.format(Locale.US, sb.toString(), host, port, Util.encode(path), Util.encode(sign), Util.encode(timestamp));
// }
//
// public static String getHmacSha1(String s, String keyString) {
// String hmacSha1 = null;
// try {
// SecretKeySpec key = new SecretKeySpec((keyString).getBytes(), "HmacSHA1");
// Mac mac = Mac.getInstance("HmacSHA1");
// mac.init(key);
// byte[] bytes = mac.doFinal(s.getBytes());
// hmacSha1 = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
// } catch (InvalidKeyException | NoSuchAlgorithmException e) {
//
// }
// return hmacSha1;
// }
//
// public static String getMimeTypeFromUrl(String url) {
// String extension = MimeTypeMap.getFileExtensionFromUrl(url);
// return TextUtils.isEmpty(extension) ? "" : MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
// }
//
// public static String getExtensionFromUrl(String url) {
// int dotIndex = url.lastIndexOf('.');
// int slashIndex = url.lastIndexOf('/');
// return dotIndex != -1 && dotIndex > slashIndex && dotIndex + 2 + MAX_EXTENSION_LENGTH > url.length() ?
// url.substring(dotIndex + 1, url.length()) : "";
// }
//
// public static String getMD5(String string) {
// try {
// MessageDigest messageDigest = MessageDigest.getInstance("MD5");
// byte[] digestBytes = messageDigest.digest(string.getBytes());
// return bytesToHexString(digestBytes);
// } catch (NoSuchAlgorithmException e) {
// throw new IllegalStateException(e);
// }
// }
//
// private static String bytesToHexString(byte[] bytes) {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < bytes.length; i++) {
// sb.append(String.format("%02x", bytes[i]));// 以十六进制(x)输出,2为指定的输出字段的宽度.如果位数小于2,则左端补0
// }
// return sb.toString();
// }
// }
|
import com.vincan.medialoader.BuildConfig;
import com.vincan.medialoader.utils.Util;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
|
package com.vincan.medialoader.data.file.naming;
/**
* {@link FileNameCreator}
*
* @author vincanyang
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class FileNameCreatorTest {
@Test(expected = NullPointerException.class)
public void testAssertNullUrl() throws Exception {
FileNameCreator fileNameCreator = new Md5FileNameCreator();
fileNameCreator.create(null);
fail("Url should be not null");
}
@Test
public void testMd5Name() throws Exception {
String url = "http://www.vincan.com/videos/video.mp4";
FileNameCreator nameGenerator = new Md5FileNameCreator();
String actual = nameGenerator.create(url);
|
// Path: library/src/main/java/com/vincan/medialoader/utils/Util.java
// public final class Util {
//
// public static final String LOCALHOST = "127.0.0.1";//不建议使用localhost,因为需要访问网络
//
// public static final int DEFAULT_BUFFER_SIZE = 8192;//8 * 1024
//
// public static final String CHARSET_DEFAULT = "UTF-8";
//
// private static final int MAX_EXTENSION_LENGTH = 4;
//
// private Util() {
//
// }
//
// public static <T> T notEmpty(T object) {
// if (object instanceof String) {
// if (TextUtils.isEmpty((String) object)) {
// throw new NullPointerException(object.getClass().getSimpleName() + " cann't be empty");
// }
// } else {
// if (object == null) {
// throw new NullPointerException(object.getClass().getSimpleName() + " cann't be null");
// }
// }
// return object;
// }
//
// public static String encode(String url) {
// try {
// return URLEncoder.encode(url, CHARSET_DEFAULT);
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("Encoding not supported", e);
// }
// }
//
// public static String decode(String url) {
// try {
// return URLDecoder.decode(url, CHARSET_DEFAULT);
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException("Decoding not supported", e);
// }
// }
//
// public static String createUrl(String host, int port, String path) {
// return String.format(Locale.US, "http://%s:%d/%s", host, port, Util.encode(path));
// }
//
// public static String createUrl(String host, int port, String path, String secret) {
// String timestamp = String.valueOf(System.currentTimeMillis());
// String sign = getHmacSha1(path + timestamp, secret);
// StringBuilder sb = new StringBuilder("http://%s:%d/%s");
// sb.append("?").append(HttpConstants.PARAM_SIGN).append("=%s");
// sb.append("&").append(HttpConstants.PARAM_TIMESTAMP).append("=%s");
// return String.format(Locale.US, sb.toString(), host, port, Util.encode(path), Util.encode(sign), Util.encode(timestamp));
// }
//
// public static String getHmacSha1(String s, String keyString) {
// String hmacSha1 = null;
// try {
// SecretKeySpec key = new SecretKeySpec((keyString).getBytes(), "HmacSHA1");
// Mac mac = Mac.getInstance("HmacSHA1");
// mac.init(key);
// byte[] bytes = mac.doFinal(s.getBytes());
// hmacSha1 = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
// } catch (InvalidKeyException | NoSuchAlgorithmException e) {
//
// }
// return hmacSha1;
// }
//
// public static String getMimeTypeFromUrl(String url) {
// String extension = MimeTypeMap.getFileExtensionFromUrl(url);
// return TextUtils.isEmpty(extension) ? "" : MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
// }
//
// public static String getExtensionFromUrl(String url) {
// int dotIndex = url.lastIndexOf('.');
// int slashIndex = url.lastIndexOf('/');
// return dotIndex != -1 && dotIndex > slashIndex && dotIndex + 2 + MAX_EXTENSION_LENGTH > url.length() ?
// url.substring(dotIndex + 1, url.length()) : "";
// }
//
// public static String getMD5(String string) {
// try {
// MessageDigest messageDigest = MessageDigest.getInstance("MD5");
// byte[] digestBytes = messageDigest.digest(string.getBytes());
// return bytesToHexString(digestBytes);
// } catch (NoSuchAlgorithmException e) {
// throw new IllegalStateException(e);
// }
// }
//
// private static String bytesToHexString(byte[] bytes) {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < bytes.length; i++) {
// sb.append(String.format("%02x", bytes[i]));// 以十六进制(x)输出,2为指定的输出字段的宽度.如果位数小于2,则左端补0
// }
// return sb.toString();
// }
// }
// Path: library/src/test/java/com/vincan/medialoader/data/file/naming/FileNameCreatorTest.java
import com.vincan.medialoader.BuildConfig;
import com.vincan.medialoader.utils.Util;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
package com.vincan.medialoader.data.file.naming;
/**
* {@link FileNameCreator}
*
* @author vincanyang
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class FileNameCreatorTest {
@Test(expected = NullPointerException.class)
public void testAssertNullUrl() throws Exception {
FileNameCreator fileNameCreator = new Md5FileNameCreator();
fileNameCreator.create(null);
fail("Url should be not null");
}
@Test
public void testMd5Name() throws Exception {
String url = "http://www.vincan.com/videos/video.mp4";
FileNameCreator nameGenerator = new Md5FileNameCreator();
String actual = nameGenerator.create(url);
|
String expected = Util.getMD5(url) + ".mp4";
|
hageldave/ImagingKit
|
ImagingKit_Core/src/main/java/hageldave/imagingkit/core/Img.java
|
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/util/ImagingKitUtils.java
// public final class ImagingKitUtils {
//
// // not to be instantiated
// private ImagingKitUtils() {}
//
//
// /**
// * Clamps a value to the range [0,255].
// * Returns 0 for values less than 0, 255 for values greater than 255,
// * and the value it self when in range.
// * @param val value to be clamped
// * @return value clamped to [0,255]
// */
// public static final int clamp_0_255(int val){
// return Math.max(0, Math.min(val, 255));
// }
//
// /**
// * Clamps a value to the range [0.0, 1.0].
// * Returns 0.0 for values less than 0, 1.0 for values greater than 1.0,
// * and the value it self when in range.
// * @param val value to be clamped
// * @return value clamped to [0.0, 1.0]
// */
// public static double clamp_0_1(double val){
// return Math.max(0.0, Math.min(val, 1.0));
// }
//
// /**
// * Throws an {@link IllegalArgumentException} when the specified area
// * is not within the bounds of the specified image, or if the area
// * is not positive.
// * This is used for parameter evaluation.
// *
// * @param xStart left boundary of the area
// * @param yStart top boundary of the area
// * @param width of the area
// * @param height of the area
// * @param img the area has to fit in.
// * @throws IllegalArgumentException when area not in image bounds or not area not positive
// */
// public static void requireAreaInImageBounds(final int xStart, final int yStart, final int width, final int height, ImgBase<?> img){
// if( width <= 0 || height <= 0 ||
// xStart < 0 || yStart < 0 ||
// xStart+width > img.getWidth() || yStart+height > img.getHeight() )
// {
// throw new IllegalArgumentException(String.format(
// "provided area [%d,%d][%d,%d] is not within bounds of the image [%d,%d]",
// xStart,yStart,width,height, img.getWidth(), img.getHeight()));
// }
// }
//
// }
|
import java.util.Spliterator;
import java.util.function.Consumer;
import hageldave.imagingkit.core.util.ImagingKitUtils;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.util.Arrays;
|
* @since 1.0
*/
public Pixel getPixel(int x, int y){
return new Pixel(this, x,y);
}
/**
* Copies specified area of this Img to the specified destination Img
* at specified destination coordinates. If destination Img is null a new
* Img with the areas size will be created and the destination coordinates
* will be ignored so that the Img will contain all the values of the area.
* <p>
* The specified area has to be within the bounds of this image or
* otherwise an IllegalArgumentException will be thrown. Only the
* intersecting part of the area and the destination image is copied which
* allows for an out of bounds destination area origin.
*
* @param x area origin in this image (x-coordinate)
* @param y area origin in this image (y-coordinate)
* @param w width of area
* @param h height of area
* @param dest destination Img
* @param destX area origin in destination Img (x-coordinate)
* @param destY area origin in destination Img (y-coordinate)
* @return the destination Img
* @throws IllegalArgumentException if the specified area is not within
* the bounds of this Img or if the size of the area is not positive.
* @since 1.0
*/
public Img copyArea(int x, int y, int w, int h, Img dest, int destX, int destY){
|
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/util/ImagingKitUtils.java
// public final class ImagingKitUtils {
//
// // not to be instantiated
// private ImagingKitUtils() {}
//
//
// /**
// * Clamps a value to the range [0,255].
// * Returns 0 for values less than 0, 255 for values greater than 255,
// * and the value it self when in range.
// * @param val value to be clamped
// * @return value clamped to [0,255]
// */
// public static final int clamp_0_255(int val){
// return Math.max(0, Math.min(val, 255));
// }
//
// /**
// * Clamps a value to the range [0.0, 1.0].
// * Returns 0.0 for values less than 0, 1.0 for values greater than 1.0,
// * and the value it self when in range.
// * @param val value to be clamped
// * @return value clamped to [0.0, 1.0]
// */
// public static double clamp_0_1(double val){
// return Math.max(0.0, Math.min(val, 1.0));
// }
//
// /**
// * Throws an {@link IllegalArgumentException} when the specified area
// * is not within the bounds of the specified image, or if the area
// * is not positive.
// * This is used for parameter evaluation.
// *
// * @param xStart left boundary of the area
// * @param yStart top boundary of the area
// * @param width of the area
// * @param height of the area
// * @param img the area has to fit in.
// * @throws IllegalArgumentException when area not in image bounds or not area not positive
// */
// public static void requireAreaInImageBounds(final int xStart, final int yStart, final int width, final int height, ImgBase<?> img){
// if( width <= 0 || height <= 0 ||
// xStart < 0 || yStart < 0 ||
// xStart+width > img.getWidth() || yStart+height > img.getHeight() )
// {
// throw new IllegalArgumentException(String.format(
// "provided area [%d,%d][%d,%d] is not within bounds of the image [%d,%d]",
// xStart,yStart,width,height, img.getWidth(), img.getHeight()));
// }
// }
//
// }
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/Img.java
import java.util.Spliterator;
import java.util.function.Consumer;
import hageldave.imagingkit.core.util.ImagingKitUtils;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.util.Arrays;
* @since 1.0
*/
public Pixel getPixel(int x, int y){
return new Pixel(this, x,y);
}
/**
* Copies specified area of this Img to the specified destination Img
* at specified destination coordinates. If destination Img is null a new
* Img with the areas size will be created and the destination coordinates
* will be ignored so that the Img will contain all the values of the area.
* <p>
* The specified area has to be within the bounds of this image or
* otherwise an IllegalArgumentException will be thrown. Only the
* intersecting part of the area and the destination image is copied which
* allows for an out of bounds destination area origin.
*
* @param x area origin in this image (x-coordinate)
* @param y area origin in this image (y-coordinate)
* @param w width of area
* @param h height of area
* @param dest destination Img
* @param destX area origin in destination Img (x-coordinate)
* @param destY area origin in destination Img (y-coordinate)
* @return the destination Img
* @throws IllegalArgumentException if the specified area is not within
* the bounds of this Img or if the size of the area is not positive.
* @since 1.0
*/
public Img copyArea(int x, int y, int w, int h, Img dest, int destX, int destY){
|
ImagingKitUtils.requireAreaInImageBounds(x, y, w, h, this);
|
hageldave/ImagingKit
|
ImagingKit_Core/src/main/java/hageldave/imagingkit/core/PixelConvertingSpliterator.java
|
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/util/ImagingKitUtils.java
// public static double clamp_0_1(double val){
// return Math.max(0.0, Math.min(val, 1.0));
// }
|
import static hageldave.imagingkit.core.util.ImagingKitUtils.clamp_0_1;
import java.util.Objects;
import java.util.Spliterator;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
|
* @param pixelSpliterator the {@code Spliterator<Pixel>} to which the
* returned spliterator delegates to.
* @return a spliterator with float[] elements consisting of normalized RGB channels.
*
* @since 1.4
*/
public static PixelConvertingSpliterator<PixelBase, double[]> getDoubletArrayElementSpliterator(
Spliterator<? extends PixelBase> pixelSpliterator){
PixelConvertingSpliterator<PixelBase, double[]> arraySpliterator = new PixelConvertingSpliterator<>(
pixelSpliterator, getDoubleArrayConverter());
return arraySpliterator;
}
/**
* @return Exemplary PixelConverter that converts to double[].
*/
public static PixelConverter<PixelBase, double[]> getDoubleArrayConverter(){
return new PixelConverter<PixelBase, double[]>() {
@Override
public void convertPixelToElement(PixelBase px, double[] array) {
array[0]=px.r_asDouble();
array[1]=px.g_asDouble();
array[2]=px.b_asDouble();
}
@Override
public void convertElementToPixel(double[] array, PixelBase px) {
px.setRGB_fromDouble_preserveAlpha(
// clamp values between zero and one
|
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/util/ImagingKitUtils.java
// public static double clamp_0_1(double val){
// return Math.max(0.0, Math.min(val, 1.0));
// }
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/PixelConvertingSpliterator.java
import static hageldave.imagingkit.core.util.ImagingKitUtils.clamp_0_1;
import java.util.Objects;
import java.util.Spliterator;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
* @param pixelSpliterator the {@code Spliterator<Pixel>} to which the
* returned spliterator delegates to.
* @return a spliterator with float[] elements consisting of normalized RGB channels.
*
* @since 1.4
*/
public static PixelConvertingSpliterator<PixelBase, double[]> getDoubletArrayElementSpliterator(
Spliterator<? extends PixelBase> pixelSpliterator){
PixelConvertingSpliterator<PixelBase, double[]> arraySpliterator = new PixelConvertingSpliterator<>(
pixelSpliterator, getDoubleArrayConverter());
return arraySpliterator;
}
/**
* @return Exemplary PixelConverter that converts to double[].
*/
public static PixelConverter<PixelBase, double[]> getDoubleArrayConverter(){
return new PixelConverter<PixelBase, double[]>() {
@Override
public void convertPixelToElement(PixelBase px, double[] array) {
array[0]=px.r_asDouble();
array[1]=px.g_asDouble();
array[2]=px.b_asDouble();
}
@Override
public void convertElementToPixel(double[] array, PixelBase px) {
px.setRGB_fromDouble_preserveAlpha(
// clamp values between zero and one
|
clamp_0_1(array[0]),
|
hageldave/ImagingKit
|
ImagingKit_Core/src/test/java/hageldave/imagingkit/core/util/BufferedImageFactoryTest.java
|
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/util/BufferedImageFactory.java
// public class BufferedImageFactory {
//
// private BufferedImageFactory(){}
//
// /**
// * shortcut for get(img, BufferedImage.TYPE_INT_ARGB).
// * @param img to be copied to BufferedImage of type INT_ARGB
// * @return a BufferedImage copy of the provided Image
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(Image img){
// return get(img, BufferedImage.TYPE_INT_ARGB);
// }
//
// /**
// * Creates a new BufferedImage of the specified imgType and same size as
// * the provided image and draws the provided Image onto the new BufferedImage.
// * @param img to be copied to BufferedImage
// * @param imgType of the BufferedImage. See
// * {@link BufferedImage#BufferedImage(int, int, int)} for details on the
// * available imgTypes.
// * @return a BufferedImage copy of the provided Image
// * @since 1.0
// */
// public static BufferedImage get(Image img, int imgType){
// Function<Integer, ImageObserver> obs = flags->{
// return (image, infoflags, x, y, width, height)->(infoflags & flags)!=flags;
// };
// BufferedImage bimg = new BufferedImage(
// img.getWidth(obs.apply(ImageObserver.WIDTH)),
// img.getHeight(obs.apply(ImageObserver.HEIGHT)),
// imgType);
// Graphics2D gr2D = bimg.createGraphics();
// gr2D.drawImage(img, 0, 0, obs.apply(ImageObserver.ALLBITS));
//
// gr2D.dispose();
//
// return bimg;
// }
//
// /**
// * Instancing method for BufferedImage of type {@link BufferedImage#TYPE_INT_ARGB}
// * @param d dimension of the created BufferedImage
// * @return a new BufferedImage of specified dimension and type TYPE_INT_ARGB
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(Dimension d){
// return getINT_ARGB(d.width, d.height);
// }
//
// /**
// * Instancing method for BufferedImage of type {@link BufferedImage#TYPE_INT_ARGB}
// * @param width of the created BufferedImage
// * @param height of the created BufferedImage
// * @return a new BufferedImage of specified dimension and type TYPE_INT_ARGB
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(int width, int height){
// return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// }
// }
|
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import static org.junit.Assert.*;
import org.junit.Test;
import hageldave.imagingkit.core.util.BufferedImageFactory;
|
package hageldave.imagingkit.core.util;
public class BufferedImageFactoryTest {
@Test
public void testAll() {
|
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/util/BufferedImageFactory.java
// public class BufferedImageFactory {
//
// private BufferedImageFactory(){}
//
// /**
// * shortcut for get(img, BufferedImage.TYPE_INT_ARGB).
// * @param img to be copied to BufferedImage of type INT_ARGB
// * @return a BufferedImage copy of the provided Image
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(Image img){
// return get(img, BufferedImage.TYPE_INT_ARGB);
// }
//
// /**
// * Creates a new BufferedImage of the specified imgType and same size as
// * the provided image and draws the provided Image onto the new BufferedImage.
// * @param img to be copied to BufferedImage
// * @param imgType of the BufferedImage. See
// * {@link BufferedImage#BufferedImage(int, int, int)} for details on the
// * available imgTypes.
// * @return a BufferedImage copy of the provided Image
// * @since 1.0
// */
// public static BufferedImage get(Image img, int imgType){
// Function<Integer, ImageObserver> obs = flags->{
// return (image, infoflags, x, y, width, height)->(infoflags & flags)!=flags;
// };
// BufferedImage bimg = new BufferedImage(
// img.getWidth(obs.apply(ImageObserver.WIDTH)),
// img.getHeight(obs.apply(ImageObserver.HEIGHT)),
// imgType);
// Graphics2D gr2D = bimg.createGraphics();
// gr2D.drawImage(img, 0, 0, obs.apply(ImageObserver.ALLBITS));
//
// gr2D.dispose();
//
// return bimg;
// }
//
// /**
// * Instancing method for BufferedImage of type {@link BufferedImage#TYPE_INT_ARGB}
// * @param d dimension of the created BufferedImage
// * @return a new BufferedImage of specified dimension and type TYPE_INT_ARGB
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(Dimension d){
// return getINT_ARGB(d.width, d.height);
// }
//
// /**
// * Instancing method for BufferedImage of type {@link BufferedImage#TYPE_INT_ARGB}
// * @param width of the created BufferedImage
// * @param height of the created BufferedImage
// * @return a new BufferedImage of specified dimension and type TYPE_INT_ARGB
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(int width, int height){
// return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// }
// }
// Path: ImagingKit_Core/src/test/java/hageldave/imagingkit/core/util/BufferedImageFactoryTest.java
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import static org.junit.Assert.*;
import org.junit.Test;
import hageldave.imagingkit.core.util.BufferedImageFactory;
package hageldave.imagingkit.core.util;
public class BufferedImageFactoryTest {
@Test
public void testAll() {
|
BufferedImage bimg = BufferedImageFactory.getINT_ARGB(1, 2);
|
hageldave/ImagingKit
|
ImagingKit_Core/src/test/java/hageldave/imagingkit/core/ImgTest.java
|
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/PixelConvertingSpliterator.java
// public static interface PixelConverter<P extends PixelBase, T> {
// /**
// * Allocates a new element for the PixelConvertingSpliterator
// * (will be called once per split)
// * @return element, probably in uninitialized state
// */
// public T allocateElement();
//
// /**
// * converts the specified pixel to the specified element
// * (initiliazation of previously allocated element).
// * <br><b>NOT ALLOCATION, ONLY SETUP OF THE ELEMENT</b>
// * @param px to used for setting up the element
// * @param element to be set up
// */
// public void convertPixelToElement(P px, T element);
//
// /**
// * converts the specified element back to the specified pixel
// * (set pixel value according to element).
// * <br><b>NOT ALLOCATION, ONLY SETTING THE PIXEL VALUE ACCORDINGLY</b>
// * @param element to be used for setting the pixel value
// * @param px to be set
// */
// public void convertElementToPixel(T element, P px);
//
// /**
// * Creates a new PixelConverter from the specified functions.
// * @param allocator a supplier that allocates a new object of the element type (see {@link #allocateElement()})
// * @param pixelToElement a consumer that sets the contents of the element according to a pixel (see {@link #convertPixelToElement(PixelBase, Object)})
// * @param elementToPixel a consumer that sets the content of a pixel according to the element (see {@link #convertElementToPixel(Object, PixelBase)})
// * @return a new PixelConverter
// */
// public static <P extends PixelBase, T> PixelConverter<P,T> fromFunctions(
// Supplier<T> allocator,
// BiConsumer<P,T> pixelToElement,
// BiConsumer<T,P> elementToPixel)
// {
// Objects.requireNonNull(allocator);
// BiConsumer<P,T> px_2_el = pixelToElement==null ? (px,e)->{}:pixelToElement;
// BiConsumer<T,P> el_2_px = elementToPixel==null ? (e,px)->{}:elementToPixel;
//
// return new PixelConverter<P,T>(){
// @Override
// public T allocateElement() {return allocator.get();}
// @Override
// public void convertPixelToElement(P px, T element) {px_2_el.accept(px, element);}
// @Override
// public void convertElementToPixel(T element, P px) {el_2_px.accept(element, px);}
//
// };
// }
// }
|
import static org.junit.Assert.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Spliterator;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import org.junit.Test;
import hageldave.imagingkit.core.PixelConvertingSpliterator.PixelConverter;
|
assertEquals((x+1)%2, img.getValue(x, y));
}
img.fill(0);
img.stream(100,200,1000,1000).filter(px->{return px.getX() % 2 == 0;}).forEach(px->{px.setValue(1);});
for(int y = 0; y < 2000; y++)
for(int x = 0; x < 3000; x++){
if(x < 100 || y < 200 || x >=100+1000 || y >= 200+1000){
assertEquals(0, img.getValue(x, y));
} else {
assertEquals((x+1)%2, img.getValue(x, y));
}
}
img.fill(0);
img.stream(true, 100,200,1000,1000).filter(px->{return px.getX() % 2 == 0;}).forEach(px->{px.setValue(1);});
for(int y = 0; y < 2000; y++)
for(int x = 0; x < 3000; x++){
if(x < 100 || y < 200 || x >=100+1000 || y >= 200+1000){
assertEquals(0, img.getValue(x, y));
} else {
assertEquals((x+1)%2, img.getValue(x, y));
}
}
}
// forEach/stream with manipulator/converter
{
PixelManipulator<PixelBase,Color[]> colorManip = new PixelManipulator<PixelBase,Color[]>() {
@Override
|
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/PixelConvertingSpliterator.java
// public static interface PixelConverter<P extends PixelBase, T> {
// /**
// * Allocates a new element for the PixelConvertingSpliterator
// * (will be called once per split)
// * @return element, probably in uninitialized state
// */
// public T allocateElement();
//
// /**
// * converts the specified pixel to the specified element
// * (initiliazation of previously allocated element).
// * <br><b>NOT ALLOCATION, ONLY SETUP OF THE ELEMENT</b>
// * @param px to used for setting up the element
// * @param element to be set up
// */
// public void convertPixelToElement(P px, T element);
//
// /**
// * converts the specified element back to the specified pixel
// * (set pixel value according to element).
// * <br><b>NOT ALLOCATION, ONLY SETTING THE PIXEL VALUE ACCORDINGLY</b>
// * @param element to be used for setting the pixel value
// * @param px to be set
// */
// public void convertElementToPixel(T element, P px);
//
// /**
// * Creates a new PixelConverter from the specified functions.
// * @param allocator a supplier that allocates a new object of the element type (see {@link #allocateElement()})
// * @param pixelToElement a consumer that sets the contents of the element according to a pixel (see {@link #convertPixelToElement(PixelBase, Object)})
// * @param elementToPixel a consumer that sets the content of a pixel according to the element (see {@link #convertElementToPixel(Object, PixelBase)})
// * @return a new PixelConverter
// */
// public static <P extends PixelBase, T> PixelConverter<P,T> fromFunctions(
// Supplier<T> allocator,
// BiConsumer<P,T> pixelToElement,
// BiConsumer<T,P> elementToPixel)
// {
// Objects.requireNonNull(allocator);
// BiConsumer<P,T> px_2_el = pixelToElement==null ? (px,e)->{}:pixelToElement;
// BiConsumer<T,P> el_2_px = elementToPixel==null ? (e,px)->{}:elementToPixel;
//
// return new PixelConverter<P,T>(){
// @Override
// public T allocateElement() {return allocator.get();}
// @Override
// public void convertPixelToElement(P px, T element) {px_2_el.accept(px, element);}
// @Override
// public void convertElementToPixel(T element, P px) {el_2_px.accept(element, px);}
//
// };
// }
// }
// Path: ImagingKit_Core/src/test/java/hageldave/imagingkit/core/ImgTest.java
import static org.junit.Assert.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Spliterator;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import org.junit.Test;
import hageldave.imagingkit.core.PixelConvertingSpliterator.PixelConverter;
assertEquals((x+1)%2, img.getValue(x, y));
}
img.fill(0);
img.stream(100,200,1000,1000).filter(px->{return px.getX() % 2 == 0;}).forEach(px->{px.setValue(1);});
for(int y = 0; y < 2000; y++)
for(int x = 0; x < 3000; x++){
if(x < 100 || y < 200 || x >=100+1000 || y >= 200+1000){
assertEquals(0, img.getValue(x, y));
} else {
assertEquals((x+1)%2, img.getValue(x, y));
}
}
img.fill(0);
img.stream(true, 100,200,1000,1000).filter(px->{return px.getX() % 2 == 0;}).forEach(px->{px.setValue(1);});
for(int y = 0; y < 2000; y++)
for(int x = 0; x < 3000; x++){
if(x < 100 || y < 200 || x >=100+1000 || y >= 200+1000){
assertEquals(0, img.getValue(x, y));
} else {
assertEquals((x+1)%2, img.getValue(x, y));
}
}
}
// forEach/stream with manipulator/converter
{
PixelManipulator<PixelBase,Color[]> colorManip = new PixelManipulator<PixelBase,Color[]>() {
@Override
|
public PixelConverter<PixelBase, Color[]> getConverter() {
|
hageldave/ImagingKit
|
ImagingKit_Core/src/main/java/hageldave/imagingkit/core/io/ImageSaver.java
|
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/util/BufferedImageFactory.java
// public class BufferedImageFactory {
//
// private BufferedImageFactory(){}
//
// /**
// * shortcut for get(img, BufferedImage.TYPE_INT_ARGB).
// * @param img to be copied to BufferedImage of type INT_ARGB
// * @return a BufferedImage copy of the provided Image
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(Image img){
// return get(img, BufferedImage.TYPE_INT_ARGB);
// }
//
// /**
// * Creates a new BufferedImage of the specified imgType and same size as
// * the provided image and draws the provided Image onto the new BufferedImage.
// * @param img to be copied to BufferedImage
// * @param imgType of the BufferedImage. See
// * {@link BufferedImage#BufferedImage(int, int, int)} for details on the
// * available imgTypes.
// * @return a BufferedImage copy of the provided Image
// * @since 1.0
// */
// public static BufferedImage get(Image img, int imgType){
// Function<Integer, ImageObserver> obs = flags->{
// return (image, infoflags, x, y, width, height)->(infoflags & flags)!=flags;
// };
// BufferedImage bimg = new BufferedImage(
// img.getWidth(obs.apply(ImageObserver.WIDTH)),
// img.getHeight(obs.apply(ImageObserver.HEIGHT)),
// imgType);
// Graphics2D gr2D = bimg.createGraphics();
// gr2D.drawImage(img, 0, 0, obs.apply(ImageObserver.ALLBITS));
//
// gr2D.dispose();
//
// return bimg;
// }
//
// /**
// * Instancing method for BufferedImage of type {@link BufferedImage#TYPE_INT_ARGB}
// * @param d dimension of the created BufferedImage
// * @return a new BufferedImage of specified dimension and type TYPE_INT_ARGB
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(Dimension d){
// return getINT_ARGB(d.width, d.height);
// }
//
// /**
// * Instancing method for BufferedImage of type {@link BufferedImage#TYPE_INT_ARGB}
// * @param width of the created BufferedImage
// * @param height of the created BufferedImage
// * @return a new BufferedImage of specified dimension and type TYPE_INT_ARGB
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(int width, int height){
// return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// }
// }
|
import javax.imageio.ImageIO;
import hageldave.imagingkit.core.util.BufferedImageFactory;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
|
/*
* Copyright 2017 David Haegele
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package hageldave.imagingkit.core.io;
/**
* Class providing convenience methods for saving Images to file.
* @author hageldave
* @since 1.0
*/
public class ImageSaver {
private ImageSaver(){}
/**
* @return {@link ImageIO#getWriterFileSuffixes()}
* @since 1.0
*/
public static String[] getSaveableImageFileFormats(){
return ImageIO.getWriterFileSuffixes();
}
/**
* returns if specified image format supports rgb values only. This means
* argb values probably need conversion beforehand.
* @param imgFormat the file format e.g. jpg or png
* @return true if format only supports rgb values
* @since 1.0
*/
public static boolean isFormatRGBOnly(String imgFormat){
switch (imgFormat.toLowerCase()) {
/* fall through */
case "jpg":
case "jpeg":
case "bmp":
return true;
default:
return false;
}
}
public static boolean isFormatBWOnly(String imgFormat){
switch (imgFormat.toLowerCase()) {
case "wbmp":
return true;
default:
return false;
}
}
/**
* Saves specified Image to file of specified img file format.
* <p>
* Some image file formats may require image type conversion before
* saving. This method converts to type INT_RGB for jpg, jpeg and bmp,
* and to type BYTE_BINARY for wbmp.
* <p>
* The provided {@link OutputStream} will not be closed, this is the
* responsibility of the caller.
* @param image to be saved
* @param os {@link OutputStream} to write image to.
* @param imgFileFormat image file format. Consult {@link #getSaveableImageFileFormats()}
* to get the supported img file formats of your system.
* @throws ImageSaverException if an IOException occurred during
* the process or no appropriate writer could be found for specified format.
* @since 1.1
*/
public static void saveImage(Image image, OutputStream os, String imgFileFormat){
final RenderedImage rImg;
if( isFormatRGBOnly(imgFileFormat) && !isBufferedImageOfType(image, BufferedImage.TYPE_INT_RGB) ){
|
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/util/BufferedImageFactory.java
// public class BufferedImageFactory {
//
// private BufferedImageFactory(){}
//
// /**
// * shortcut for get(img, BufferedImage.TYPE_INT_ARGB).
// * @param img to be copied to BufferedImage of type INT_ARGB
// * @return a BufferedImage copy of the provided Image
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(Image img){
// return get(img, BufferedImage.TYPE_INT_ARGB);
// }
//
// /**
// * Creates a new BufferedImage of the specified imgType and same size as
// * the provided image and draws the provided Image onto the new BufferedImage.
// * @param img to be copied to BufferedImage
// * @param imgType of the BufferedImage. See
// * {@link BufferedImage#BufferedImage(int, int, int)} for details on the
// * available imgTypes.
// * @return a BufferedImage copy of the provided Image
// * @since 1.0
// */
// public static BufferedImage get(Image img, int imgType){
// Function<Integer, ImageObserver> obs = flags->{
// return (image, infoflags, x, y, width, height)->(infoflags & flags)!=flags;
// };
// BufferedImage bimg = new BufferedImage(
// img.getWidth(obs.apply(ImageObserver.WIDTH)),
// img.getHeight(obs.apply(ImageObserver.HEIGHT)),
// imgType);
// Graphics2D gr2D = bimg.createGraphics();
// gr2D.drawImage(img, 0, 0, obs.apply(ImageObserver.ALLBITS));
//
// gr2D.dispose();
//
// return bimg;
// }
//
// /**
// * Instancing method for BufferedImage of type {@link BufferedImage#TYPE_INT_ARGB}
// * @param d dimension of the created BufferedImage
// * @return a new BufferedImage of specified dimension and type TYPE_INT_ARGB
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(Dimension d){
// return getINT_ARGB(d.width, d.height);
// }
//
// /**
// * Instancing method for BufferedImage of type {@link BufferedImage#TYPE_INT_ARGB}
// * @param width of the created BufferedImage
// * @param height of the created BufferedImage
// * @return a new BufferedImage of specified dimension and type TYPE_INT_ARGB
// * @since 1.0
// */
// public static BufferedImage getINT_ARGB(int width, int height){
// return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// }
// }
// Path: ImagingKit_Core/src/main/java/hageldave/imagingkit/core/io/ImageSaver.java
import javax.imageio.ImageIO;
import hageldave.imagingkit.core.util.BufferedImageFactory;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/*
* Copyright 2017 David Haegele
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package hageldave.imagingkit.core.io;
/**
* Class providing convenience methods for saving Images to file.
* @author hageldave
* @since 1.0
*/
public class ImageSaver {
private ImageSaver(){}
/**
* @return {@link ImageIO#getWriterFileSuffixes()}
* @since 1.0
*/
public static String[] getSaveableImageFileFormats(){
return ImageIO.getWriterFileSuffixes();
}
/**
* returns if specified image format supports rgb values only. This means
* argb values probably need conversion beforehand.
* @param imgFormat the file format e.g. jpg or png
* @return true if format only supports rgb values
* @since 1.0
*/
public static boolean isFormatRGBOnly(String imgFormat){
switch (imgFormat.toLowerCase()) {
/* fall through */
case "jpg":
case "jpeg":
case "bmp":
return true;
default:
return false;
}
}
public static boolean isFormatBWOnly(String imgFormat){
switch (imgFormat.toLowerCase()) {
case "wbmp":
return true;
default:
return false;
}
}
/**
* Saves specified Image to file of specified img file format.
* <p>
* Some image file formats may require image type conversion before
* saving. This method converts to type INT_RGB for jpg, jpeg and bmp,
* and to type BYTE_BINARY for wbmp.
* <p>
* The provided {@link OutputStream} will not be closed, this is the
* responsibility of the caller.
* @param image to be saved
* @param os {@link OutputStream} to write image to.
* @param imgFileFormat image file format. Consult {@link #getSaveableImageFileFormats()}
* to get the supported img file formats of your system.
* @throws ImageSaverException if an IOException occurred during
* the process or no appropriate writer could be found for specified format.
* @since 1.1
*/
public static void saveImage(Image image, OutputStream os, String imgFileFormat){
final RenderedImage rImg;
if( isFormatRGBOnly(imgFileFormat) && !isBufferedImageOfType(image, BufferedImage.TYPE_INT_RGB) ){
|
rImg = BufferedImageFactory.get(image, BufferedImage.TYPE_INT_RGB);
|
jawher/moulder-j
|
src/test/java/moulder/moulds/PrependerTest.java
|
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
|
import moulder.Value;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import org.mockito.InOrder;
import java.io.StringReader;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import static org.mockito.Mockito.*;
|
package moulder.moulds;
public class PrependerTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
|
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
// Path: src/test/java/moulder/moulds/PrependerTest.java
import moulder.Value;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import org.mockito.InOrder;
import java.io.StringReader;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import static org.mockito.Mockito.*;
package moulder.moulds;
public class PrependerTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
|
Value<Iterable<Node>> content = mock(Value.class);
|
jawher/moulder-j
|
src/main/java/moulder/values/ValueFieldExtractor.java
|
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
|
import moulder.Value;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
|
package moulder.values;
public class ValueFieldExtractor<T, S> extends ValueTransformer<S, T> {
private Method m;
|
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
// Path: src/main/java/moulder/values/ValueFieldExtractor.java
import moulder.Value;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
package moulder.values;
public class ValueFieldExtractor<T, S> extends ValueTransformer<S, T> {
private Method m;
|
public ValueFieldExtractor(Value<S> delegate, String field,
|
jawher/moulder-j
|
src/main/java/moulder/moulds/ChildAppender.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/HtmlValue.java
// public class HtmlValue implements Value<Iterable<Node>> {
// private Value<String> html;
//
// public HtmlValue(String html) {
// this(new SimpleValue<String>(html));
// }
//
// public HtmlValue(Value<String> html) {
// super();
// this.html = html;
// }
//
// public Iterable<Node> get() {
// List<Node> nodes = Jsoup.parseBodyFragment(html.get()).body()
// .childNodes();
// List<Node> copy = new ArrayList<Node>(nodes);
// return copy;
// }
//
// }
|
import moulder.Moulder;
import moulder.Value;
import moulder.values.HtmlValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.List;
|
package moulder.moulds;
/**
* A moulder that appends content to its input element's children
*
* @author jawher
*
*/
public class ChildAppender implements Moulder {
private Value<Iterable<Node>> content;
/**
*
* @param content
* the nodes that are to be appended to the input element's
* children.
*/
public ChildAppender(Value<Iterable<Node>> content) {
super();
this.content = content;
}
/**
* a convenience version of the {@link #ChildAppender(moulder.Value)} constructor
* that parses the supplied <code>html</code> string.
*
* @param html
*/
public ChildAppender(String html) {
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/HtmlValue.java
// public class HtmlValue implements Value<Iterable<Node>> {
// private Value<String> html;
//
// public HtmlValue(String html) {
// this(new SimpleValue<String>(html));
// }
//
// public HtmlValue(Value<String> html) {
// super();
// this.html = html;
// }
//
// public Iterable<Node> get() {
// List<Node> nodes = Jsoup.parseBodyFragment(html.get()).body()
// .childNodes();
// List<Node> copy = new ArrayList<Node>(nodes);
// return copy;
// }
//
// }
// Path: src/main/java/moulder/moulds/ChildAppender.java
import moulder.Moulder;
import moulder.Value;
import moulder.values.HtmlValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.List;
package moulder.moulds;
/**
* A moulder that appends content to its input element's children
*
* @author jawher
*
*/
public class ChildAppender implements Moulder {
private Value<Iterable<Node>> content;
/**
*
* @param content
* the nodes that are to be appended to the input element's
* children.
*/
public ChildAppender(Value<Iterable<Node>> content) {
super();
this.content = content;
}
/**
* a convenience version of the {@link #ChildAppender(moulder.Value)} constructor
* that parses the supplied <code>html</code> string.
*
* @param html
*/
public ChildAppender(String html) {
|
this(new HtmlValue(html));
|
jawher/moulder-j
|
src/test/java/moulder/moulds/ForEachTest.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/values/SeqValue.java
// public class SeqValue<T> implements Value<T> {
// private Iterator<T> values;
//
// public SeqValue(Iterator<T> values) {
// super();
// this.values = values;
// }
//
// public SeqValue(Iterable<T> values) {
// this.values = values.iterator();
// }
//
// public SeqValue(T... values) {
// this.values = Arrays.asList(values).iterator();
// }
//
// public T get() {
// return values.hasNext() ? values.next() : null;
// }
//
// public SeqValue<T> cycle() {
// return new SeqValue<T>(new CyclingIterator<T>(values));
// }
//
// private static final class CyclingIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private final List<S> values = new ArrayList<S>();
// private boolean cycled = false;
//
// public CyclingIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// S res = it.next();
// if (!cycled) {
// values.add(res);
// }
// return res;
// } else {
// cycled = true;
// it = values.iterator();
// return next();
// }
// }
//
// public void remove() {
//
// }
//
// }
//
// public SeqValue<T> repeatLast() {
// return new SeqValue<T>(new RepeatLastIterator<T>(values));
// }
//
// private static final class RepeatLastIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private S last;
//
// public RepeatLastIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// last = it.next();
// }
// return last;
// }
//
// public void remove() {
//
// }
//
// }
// }
//
// Path: src/main/java/moulder/values/SimpleBox.java
// public class SimpleBox<T> implements Value<T> {
//
// private T value;
//
// public SimpleBox() {
// this.value = null;
// }
//
// public SimpleBox(T value) {
// this.value = value;
// }
//
// public void set(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
|
import moulder.Moulder;
import moulder.values.SeqValue;
import moulder.values.SimpleBox;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
|
package moulder.moulds;
public class ForEachTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
List<Integer> list = Arrays.asList(4, 2);
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/values/SeqValue.java
// public class SeqValue<T> implements Value<T> {
// private Iterator<T> values;
//
// public SeqValue(Iterator<T> values) {
// super();
// this.values = values;
// }
//
// public SeqValue(Iterable<T> values) {
// this.values = values.iterator();
// }
//
// public SeqValue(T... values) {
// this.values = Arrays.asList(values).iterator();
// }
//
// public T get() {
// return values.hasNext() ? values.next() : null;
// }
//
// public SeqValue<T> cycle() {
// return new SeqValue<T>(new CyclingIterator<T>(values));
// }
//
// private static final class CyclingIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private final List<S> values = new ArrayList<S>();
// private boolean cycled = false;
//
// public CyclingIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// S res = it.next();
// if (!cycled) {
// values.add(res);
// }
// return res;
// } else {
// cycled = true;
// it = values.iterator();
// return next();
// }
// }
//
// public void remove() {
//
// }
//
// }
//
// public SeqValue<T> repeatLast() {
// return new SeqValue<T>(new RepeatLastIterator<T>(values));
// }
//
// private static final class RepeatLastIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private S last;
//
// public RepeatLastIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// last = it.next();
// }
// return last;
// }
//
// public void remove() {
//
// }
//
// }
// }
//
// Path: src/main/java/moulder/values/SimpleBox.java
// public class SimpleBox<T> implements Value<T> {
//
// private T value;
//
// public SimpleBox() {
// this.value = null;
// }
//
// public SimpleBox(T value) {
// this.value = value;
// }
//
// public void set(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
// Path: src/test/java/moulder/moulds/ForEachTest.java
import moulder.Moulder;
import moulder.values.SeqValue;
import moulder.values.SimpleBox;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
package moulder.moulds;
public class ForEachTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
List<Integer> list = Arrays.asList(4, 2);
|
final SimpleBox<Integer> sb = new SimpleBox<Integer>();
|
jawher/moulder-j
|
src/test/java/moulder/moulds/ForEachTest.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/values/SeqValue.java
// public class SeqValue<T> implements Value<T> {
// private Iterator<T> values;
//
// public SeqValue(Iterator<T> values) {
// super();
// this.values = values;
// }
//
// public SeqValue(Iterable<T> values) {
// this.values = values.iterator();
// }
//
// public SeqValue(T... values) {
// this.values = Arrays.asList(values).iterator();
// }
//
// public T get() {
// return values.hasNext() ? values.next() : null;
// }
//
// public SeqValue<T> cycle() {
// return new SeqValue<T>(new CyclingIterator<T>(values));
// }
//
// private static final class CyclingIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private final List<S> values = new ArrayList<S>();
// private boolean cycled = false;
//
// public CyclingIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// S res = it.next();
// if (!cycled) {
// values.add(res);
// }
// return res;
// } else {
// cycled = true;
// it = values.iterator();
// return next();
// }
// }
//
// public void remove() {
//
// }
//
// }
//
// public SeqValue<T> repeatLast() {
// return new SeqValue<T>(new RepeatLastIterator<T>(values));
// }
//
// private static final class RepeatLastIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private S last;
//
// public RepeatLastIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// last = it.next();
// }
// return last;
// }
//
// public void remove() {
//
// }
//
// }
// }
//
// Path: src/main/java/moulder/values/SimpleBox.java
// public class SimpleBox<T> implements Value<T> {
//
// private T value;
//
// public SimpleBox() {
// this.value = null;
// }
//
// public SimpleBox(T value) {
// this.value = value;
// }
//
// public void set(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
|
import moulder.Moulder;
import moulder.values.SeqValue;
import moulder.values.SimpleBox;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
|
package moulder.moulds;
public class ForEachTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
List<Integer> list = Arrays.asList(4, 2);
final SimpleBox<Integer> sb = new SimpleBox<Integer>();
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/values/SeqValue.java
// public class SeqValue<T> implements Value<T> {
// private Iterator<T> values;
//
// public SeqValue(Iterator<T> values) {
// super();
// this.values = values;
// }
//
// public SeqValue(Iterable<T> values) {
// this.values = values.iterator();
// }
//
// public SeqValue(T... values) {
// this.values = Arrays.asList(values).iterator();
// }
//
// public T get() {
// return values.hasNext() ? values.next() : null;
// }
//
// public SeqValue<T> cycle() {
// return new SeqValue<T>(new CyclingIterator<T>(values));
// }
//
// private static final class CyclingIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private final List<S> values = new ArrayList<S>();
// private boolean cycled = false;
//
// public CyclingIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// S res = it.next();
// if (!cycled) {
// values.add(res);
// }
// return res;
// } else {
// cycled = true;
// it = values.iterator();
// return next();
// }
// }
//
// public void remove() {
//
// }
//
// }
//
// public SeqValue<T> repeatLast() {
// return new SeqValue<T>(new RepeatLastIterator<T>(values));
// }
//
// private static final class RepeatLastIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private S last;
//
// public RepeatLastIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// last = it.next();
// }
// return last;
// }
//
// public void remove() {
//
// }
//
// }
// }
//
// Path: src/main/java/moulder/values/SimpleBox.java
// public class SimpleBox<T> implements Value<T> {
//
// private T value;
//
// public SimpleBox() {
// this.value = null;
// }
//
// public SimpleBox(T value) {
// this.value = value;
// }
//
// public void set(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
// Path: src/test/java/moulder/moulds/ForEachTest.java
import moulder.Moulder;
import moulder.values.SeqValue;
import moulder.values.SimpleBox;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
package moulder.moulds;
public class ForEachTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
List<Integer> list = Arrays.asList(4, 2);
final SimpleBox<Integer> sb = new SimpleBox<Integer>();
|
ForEach<Integer> f = new ForEach<Integer>(sb, new SeqValue<Integer>(list), new Moulder() {
|
jawher/moulder-j
|
src/test/java/moulder/moulds/ForEachTest.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/values/SeqValue.java
// public class SeqValue<T> implements Value<T> {
// private Iterator<T> values;
//
// public SeqValue(Iterator<T> values) {
// super();
// this.values = values;
// }
//
// public SeqValue(Iterable<T> values) {
// this.values = values.iterator();
// }
//
// public SeqValue(T... values) {
// this.values = Arrays.asList(values).iterator();
// }
//
// public T get() {
// return values.hasNext() ? values.next() : null;
// }
//
// public SeqValue<T> cycle() {
// return new SeqValue<T>(new CyclingIterator<T>(values));
// }
//
// private static final class CyclingIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private final List<S> values = new ArrayList<S>();
// private boolean cycled = false;
//
// public CyclingIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// S res = it.next();
// if (!cycled) {
// values.add(res);
// }
// return res;
// } else {
// cycled = true;
// it = values.iterator();
// return next();
// }
// }
//
// public void remove() {
//
// }
//
// }
//
// public SeqValue<T> repeatLast() {
// return new SeqValue<T>(new RepeatLastIterator<T>(values));
// }
//
// private static final class RepeatLastIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private S last;
//
// public RepeatLastIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// last = it.next();
// }
// return last;
// }
//
// public void remove() {
//
// }
//
// }
// }
//
// Path: src/main/java/moulder/values/SimpleBox.java
// public class SimpleBox<T> implements Value<T> {
//
// private T value;
//
// public SimpleBox() {
// this.value = null;
// }
//
// public SimpleBox(T value) {
// this.value = value;
// }
//
// public void set(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
|
import moulder.Moulder;
import moulder.values.SeqValue;
import moulder.values.SimpleBox;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
|
package moulder.moulds;
public class ForEachTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
List<Integer> list = Arrays.asList(4, 2);
final SimpleBox<Integer> sb = new SimpleBox<Integer>();
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/values/SeqValue.java
// public class SeqValue<T> implements Value<T> {
// private Iterator<T> values;
//
// public SeqValue(Iterator<T> values) {
// super();
// this.values = values;
// }
//
// public SeqValue(Iterable<T> values) {
// this.values = values.iterator();
// }
//
// public SeqValue(T... values) {
// this.values = Arrays.asList(values).iterator();
// }
//
// public T get() {
// return values.hasNext() ? values.next() : null;
// }
//
// public SeqValue<T> cycle() {
// return new SeqValue<T>(new CyclingIterator<T>(values));
// }
//
// private static final class CyclingIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private final List<S> values = new ArrayList<S>();
// private boolean cycled = false;
//
// public CyclingIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// S res = it.next();
// if (!cycled) {
// values.add(res);
// }
// return res;
// } else {
// cycled = true;
// it = values.iterator();
// return next();
// }
// }
//
// public void remove() {
//
// }
//
// }
//
// public SeqValue<T> repeatLast() {
// return new SeqValue<T>(new RepeatLastIterator<T>(values));
// }
//
// private static final class RepeatLastIterator<S> implements Iterator<S> {
// private Iterator<S> it;
// private final boolean itHasValues;
// private S last;
//
// public RepeatLastIterator(Iterator<S> it) {
// this.it = it;
// itHasValues = it.hasNext();
// }
//
// public boolean hasNext() {
// return itHasValues;
// }
//
// public S next() {
// if (!itHasValues) {
// throw new NoSuchElementException();
// }
// if (it.hasNext()) {
// last = it.next();
// }
// return last;
// }
//
// public void remove() {
//
// }
//
// }
// }
//
// Path: src/main/java/moulder/values/SimpleBox.java
// public class SimpleBox<T> implements Value<T> {
//
// private T value;
//
// public SimpleBox() {
// this.value = null;
// }
//
// public SimpleBox(T value) {
// this.value = value;
// }
//
// public void set(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
// Path: src/test/java/moulder/moulds/ForEachTest.java
import moulder.Moulder;
import moulder.values.SeqValue;
import moulder.values.SimpleBox;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
package moulder.moulds;
public class ForEachTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
List<Integer> list = Arrays.asList(4, 2);
final SimpleBox<Integer> sb = new SimpleBox<Integer>();
|
ForEach<Integer> f = new ForEach<Integer>(sb, new SeqValue<Integer>(list), new Moulder() {
|
jawher/moulder-j
|
src/test/java/moulder/moulds/RemoveCssClassMoulderTest.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
|
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import java.io.StringReader;
import java.util.List;
import moulder.Moulder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
|
package moulder.moulds;
public class RemoveCssClassMoulderTest extends BaseMoulderTest {
@Test
public void noClass() throws Exception {
final String bodyHtml = "<tag>text</tag>";
final String cssClass = "ss";
final String expected = "<tag>text\n</tag>";
test(bodyHtml, cssClass, expected);
}
@Test
public void withSameClass() throws Exception {
final String bodyHtml = "<tag class=\"ss\">text</tag>";
final String cssClass = "ss";
final String expected = "<tag class=\"\">text\n</tag>";
test(bodyHtml, cssClass, expected);
}
@Test
public void withSimilarClass() throws Exception {
final String bodyHtml = "<tag class=\"sss ss ss1\">text</tag>";
final String cssClass = "ss";
final String expected = "<tag class=\"sss ss1\">text\n</tag>";
test(bodyHtml, cssClass, expected);
}
private void test(String bodyHtml, String cssClass, String expected) throws Exception {
Document document = Jsoup.parseBodyFragment(bodyHtml);
Element element = document.getElementsByTag("tag").first();
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
// Path: src/test/java/moulder/moulds/RemoveCssClassMoulderTest.java
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import java.io.StringReader;
import java.util.List;
import moulder.Moulder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
package moulder.moulds;
public class RemoveCssClassMoulderTest extends BaseMoulderTest {
@Test
public void noClass() throws Exception {
final String bodyHtml = "<tag>text</tag>";
final String cssClass = "ss";
final String expected = "<tag>text\n</tag>";
test(bodyHtml, cssClass, expected);
}
@Test
public void withSameClass() throws Exception {
final String bodyHtml = "<tag class=\"ss\">text</tag>";
final String cssClass = "ss";
final String expected = "<tag class=\"\">text\n</tag>";
test(bodyHtml, cssClass, expected);
}
@Test
public void withSimilarClass() throws Exception {
final String bodyHtml = "<tag class=\"sss ss ss1\">text</tag>";
final String cssClass = "ss";
final String expected = "<tag class=\"sss ss1\">text\n</tag>";
test(bodyHtml, cssClass, expected);
}
private void test(String bodyHtml, String cssClass, String expected) throws Exception {
Document document = Jsoup.parseBodyFragment(bodyHtml);
Element element = document.getElementsByTag("tag").first();
|
Moulder moulder = new RemoveCssClassMoulder(cssClass);
|
jawher/moulder-j
|
src/main/java/moulder/moulds/AttrModifier.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/SimpleValue.java
// public class SimpleValue<T> implements Value<T> {
// private final T value;
//
// /**
// * @param value the value to be returned by {@link #get()}
// */
// public SimpleValue(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
|
import moulder.Moulder;
import moulder.Value;
import moulder.values.SimpleValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.List;
|
package moulder.moulds;
/**
* A moulder that adds/modifies/removes an attribute to its input element
*
* @author jawher
*
*/
public class AttrModifier implements Moulder {
private Value<String> attr;
private Value<String> value;
/**
*
* @param attr
* a value that returns the attribute name
* @param value
* a value that returns the attribute's value. If null is
* supplied, or if <code>value</code> generates a null value, the
* attribute is removed from the input element
*/
public AttrModifier(Value<String> attr, Value<String> value) {
this.attr = attr;
this.value = value;
}
/**
* A variant of {@link #AttrModifier(Value, Value)} that wraps the
* <code>attr</code> argument in a {@link SimpleValue}
*
* @param attr
* @param value
*/
public AttrModifier(String attr, Value<String> value) {
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/SimpleValue.java
// public class SimpleValue<T> implements Value<T> {
// private final T value;
//
// /**
// * @param value the value to be returned by {@link #get()}
// */
// public SimpleValue(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
// Path: src/main/java/moulder/moulds/AttrModifier.java
import moulder.Moulder;
import moulder.Value;
import moulder.values.SimpleValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.List;
package moulder.moulds;
/**
* A moulder that adds/modifies/removes an attribute to its input element
*
* @author jawher
*
*/
public class AttrModifier implements Moulder {
private Value<String> attr;
private Value<String> value;
/**
*
* @param attr
* a value that returns the attribute name
* @param value
* a value that returns the attribute's value. If null is
* supplied, or if <code>value</code> generates a null value, the
* attribute is removed from the input element
*/
public AttrModifier(Value<String> attr, Value<String> value) {
this.attr = attr;
this.value = value;
}
/**
* A variant of {@link #AttrModifier(Value, Value)} that wraps the
* <code>attr</code> argument in a {@link SimpleValue}
*
* @param attr
* @param value
*/
public AttrModifier(String attr, Value<String> value) {
|
this(new SimpleValue<String>(attr), value);
|
jawher/moulder-j
|
src/main/java/moulder/moulds/AddCssClassMoulder.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/SimpleValue.java
// public class SimpleValue<T> implements Value<T> {
// private final T value;
//
// /**
// * @param value the value to be returned by {@link #get()}
// */
// public SimpleValue(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
|
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import moulder.Moulder;
import moulder.Value;
import moulder.values.SimpleValue;
|
package moulder.moulds;
/**
* Moulder, which adds a CSS class if it's not already present.
*/
public class AddCssClassMoulder implements Moulder {
private final Value<String> value;
/**
* @param value
* a value that returns the CSS class
*/
public AddCssClassMoulder(Value<String> value) {
this.value = value;
}
/**
* @param cssClass
* the CSS class
*/
public AddCssClassMoulder(String cssClass) {
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/SimpleValue.java
// public class SimpleValue<T> implements Value<T> {
// private final T value;
//
// /**
// * @param value the value to be returned by {@link #get()}
// */
// public SimpleValue(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
// Path: src/main/java/moulder/moulds/AddCssClassMoulder.java
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import moulder.Moulder;
import moulder.Value;
import moulder.values.SimpleValue;
package moulder.moulds;
/**
* Moulder, which adds a CSS class if it's not already present.
*/
public class AddCssClassMoulder implements Moulder {
private final Value<String> value;
/**
* @param value
* a value that returns the CSS class
*/
public AddCssClassMoulder(Value<String> value) {
this.value = value;
}
/**
* @param cssClass
* the CSS class
*/
public AddCssClassMoulder(String cssClass) {
|
this(new SimpleValue<String>(cssClass));
|
jawher/moulder-j
|
src/main/java/moulder/moulds/Replacer.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/HtmlValue.java
// public class HtmlValue implements Value<Iterable<Node>> {
// private Value<String> html;
//
// public HtmlValue(String html) {
// this(new SimpleValue<String>(html));
// }
//
// public HtmlValue(Value<String> html) {
// super();
// this.html = html;
// }
//
// public Iterable<Node> get() {
// List<Node> nodes = Jsoup.parseBodyFragment(html.get()).body()
// .childNodes();
// List<Node> copy = new ArrayList<Node>(nodes);
// return copy;
// }
//
// }
|
import moulder.Moulder;
import moulder.Value;
import moulder.values.HtmlValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.List;
|
package moulder.moulds;
/**
* A moulder that replaces its input element with the supplied content
*
* @author jawher
*/
public class Replacer implements Moulder {
private Value<Iterable<Node>> content;
/**
* @param content the nodes to replace the input element with
*/
public Replacer(Value<Iterable<Node>> content) {
super();
this.content = content;
}
/**
* a convenience version of the {@link #Replacer(moulder.Value)} constructor that
* parses the supplied <code>html</code> string.
*
* @param html
*/
public Replacer(String html) {
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/HtmlValue.java
// public class HtmlValue implements Value<Iterable<Node>> {
// private Value<String> html;
//
// public HtmlValue(String html) {
// this(new SimpleValue<String>(html));
// }
//
// public HtmlValue(Value<String> html) {
// super();
// this.html = html;
// }
//
// public Iterable<Node> get() {
// List<Node> nodes = Jsoup.parseBodyFragment(html.get()).body()
// .childNodes();
// List<Node> copy = new ArrayList<Node>(nodes);
// return copy;
// }
//
// }
// Path: src/main/java/moulder/moulds/Replacer.java
import moulder.Moulder;
import moulder.Value;
import moulder.values.HtmlValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.List;
package moulder.moulds;
/**
* A moulder that replaces its input element with the supplied content
*
* @author jawher
*/
public class Replacer implements Moulder {
private Value<Iterable<Node>> content;
/**
* @param content the nodes to replace the input element with
*/
public Replacer(Value<Iterable<Node>> content) {
super();
this.content = content;
}
/**
* a convenience version of the {@link #Replacer(moulder.Value)} constructor that
* parses the supplied <code>html</code> string.
*
* @param html
*/
public Replacer(String html) {
|
this(new HtmlValue(html));
|
jawher/moulder-j
|
src/main/java/moulder/moulds/SubMoulder.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/MoulderChain.java
// public class MoulderChain {
// private final List<Moulder> moulders;
//
// public MoulderChain(List<Moulder> moulders) {
// this.moulders = moulders;
// }
//
// public MoulderChain add(Moulder... moulders) {
// return add(Arrays.asList(moulders));
// }
//
// public MoulderChain add(List<Moulder> moulders) {
// this.moulders.addAll(moulders);
// return null;
// }
//
// }
//
// Path: src/main/java/moulder/Registry.java
// public class Registry {
//
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// private final List<TemplatorConfig> cfg = new ArrayList<TemplatorConfig>();
//
// /**
// * Registers a number of moulders to be applied to its input element's
// * children returned by the supplied selector
// *
// * @param selector
// * to selected the input element's children to be processed
// * @param templators
// * the moulders to apply on the selected children
// */
// public void register(String selector, List<Moulder> templators) {
// cfg.add(new TemplatorConfig(selector, templators));
// }
//
// /**
// * Return the registered selector/moulders pairs
// *
// * @return
// */
// public List<TemplatorConfig> getConfig() {
// return cfg;
// }
// }
//
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/JsoupHelper.java
// public class JsoupHelper {
//
// public static Element copy(Element e) {
// Element res = new Element(Tag.valueOf(e.tagName()), e.baseUri());
// for (Attribute a: e.attributes()) {
// res.attr(a.getKey(), a.getValue());
// }
// res.html(e.html());
// return res;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Moulder;
import moulder.MoulderChain;
import moulder.Registry;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.JsoupHelper;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
|
package moulder.moulds;
/**
* A moulder that can be configured to select children of its input element an
* apply other moulders on them
*
* @author jawher
*/
public class SubMoulder implements Moulder {
private final Registry registry = new Registry();
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param moulders the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param templators the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/MoulderChain.java
// public class MoulderChain {
// private final List<Moulder> moulders;
//
// public MoulderChain(List<Moulder> moulders) {
// this.moulders = moulders;
// }
//
// public MoulderChain add(Moulder... moulders) {
// return add(Arrays.asList(moulders));
// }
//
// public MoulderChain add(List<Moulder> moulders) {
// this.moulders.addAll(moulders);
// return null;
// }
//
// }
//
// Path: src/main/java/moulder/Registry.java
// public class Registry {
//
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// private final List<TemplatorConfig> cfg = new ArrayList<TemplatorConfig>();
//
// /**
// * Registers a number of moulders to be applied to its input element's
// * children returned by the supplied selector
// *
// * @param selector
// * to selected the input element's children to be processed
// * @param templators
// * the moulders to apply on the selected children
// */
// public void register(String selector, List<Moulder> templators) {
// cfg.add(new TemplatorConfig(selector, templators));
// }
//
// /**
// * Return the registered selector/moulders pairs
// *
// * @return
// */
// public List<TemplatorConfig> getConfig() {
// return cfg;
// }
// }
//
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/JsoupHelper.java
// public class JsoupHelper {
//
// public static Element copy(Element e) {
// Element res = new Element(Tag.valueOf(e.tagName()), e.baseUri());
// for (Attribute a: e.attributes()) {
// res.attr(a.getKey(), a.getValue());
// }
// res.html(e.html());
// return res;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
// Path: src/main/java/moulder/moulds/SubMoulder.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Moulder;
import moulder.MoulderChain;
import moulder.Registry;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.JsoupHelper;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
package moulder.moulds;
/**
* A moulder that can be configured to select children of its input element an
* apply other moulders on them
*
* @author jawher
*/
public class SubMoulder implements Moulder {
private final Registry registry = new Registry();
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param moulders the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param templators the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
|
public MoulderChain select(String selector) {
|
jawher/moulder-j
|
src/main/java/moulder/moulds/SubMoulder.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/MoulderChain.java
// public class MoulderChain {
// private final List<Moulder> moulders;
//
// public MoulderChain(List<Moulder> moulders) {
// this.moulders = moulders;
// }
//
// public MoulderChain add(Moulder... moulders) {
// return add(Arrays.asList(moulders));
// }
//
// public MoulderChain add(List<Moulder> moulders) {
// this.moulders.addAll(moulders);
// return null;
// }
//
// }
//
// Path: src/main/java/moulder/Registry.java
// public class Registry {
//
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// private final List<TemplatorConfig> cfg = new ArrayList<TemplatorConfig>();
//
// /**
// * Registers a number of moulders to be applied to its input element's
// * children returned by the supplied selector
// *
// * @param selector
// * to selected the input element's children to be processed
// * @param templators
// * the moulders to apply on the selected children
// */
// public void register(String selector, List<Moulder> templators) {
// cfg.add(new TemplatorConfig(selector, templators));
// }
//
// /**
// * Return the registered selector/moulders pairs
// *
// * @return
// */
// public List<TemplatorConfig> getConfig() {
// return cfg;
// }
// }
//
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/JsoupHelper.java
// public class JsoupHelper {
//
// public static Element copy(Element e) {
// Element res = new Element(Tag.valueOf(e.tagName()), e.baseUri());
// for (Attribute a: e.attributes()) {
// res.attr(a.getKey(), a.getValue());
// }
// res.html(e.html());
// return res;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Moulder;
import moulder.MoulderChain;
import moulder.Registry;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.JsoupHelper;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
|
package moulder.moulds;
/**
* A moulder that can be configured to select children of its input element an
* apply other moulders on them
*
* @author jawher
*/
public class SubMoulder implements Moulder {
private final Registry registry = new Registry();
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param moulders the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param templators the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
public MoulderChain select(String selector) {
List<Moulder> moulders = new ArrayList<Moulder>();
register(selector, moulders);
return new MoulderChain(moulders);
}
public List<Node> process(Element element) {
final Document doc = new Document(element.baseUri());
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/MoulderChain.java
// public class MoulderChain {
// private final List<Moulder> moulders;
//
// public MoulderChain(List<Moulder> moulders) {
// this.moulders = moulders;
// }
//
// public MoulderChain add(Moulder... moulders) {
// return add(Arrays.asList(moulders));
// }
//
// public MoulderChain add(List<Moulder> moulders) {
// this.moulders.addAll(moulders);
// return null;
// }
//
// }
//
// Path: src/main/java/moulder/Registry.java
// public class Registry {
//
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// private final List<TemplatorConfig> cfg = new ArrayList<TemplatorConfig>();
//
// /**
// * Registers a number of moulders to be applied to its input element's
// * children returned by the supplied selector
// *
// * @param selector
// * to selected the input element's children to be processed
// * @param templators
// * the moulders to apply on the selected children
// */
// public void register(String selector, List<Moulder> templators) {
// cfg.add(new TemplatorConfig(selector, templators));
// }
//
// /**
// * Return the registered selector/moulders pairs
// *
// * @return
// */
// public List<TemplatorConfig> getConfig() {
// return cfg;
// }
// }
//
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/JsoupHelper.java
// public class JsoupHelper {
//
// public static Element copy(Element e) {
// Element res = new Element(Tag.valueOf(e.tagName()), e.baseUri());
// for (Attribute a: e.attributes()) {
// res.attr(a.getKey(), a.getValue());
// }
// res.html(e.html());
// return res;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
// Path: src/main/java/moulder/moulds/SubMoulder.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Moulder;
import moulder.MoulderChain;
import moulder.Registry;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.JsoupHelper;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
package moulder.moulds;
/**
* A moulder that can be configured to select children of its input element an
* apply other moulders on them
*
* @author jawher
*/
public class SubMoulder implements Moulder {
private final Registry registry = new Registry();
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param moulders the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param templators the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
public MoulderChain select(String selector) {
List<Moulder> moulders = new ArrayList<Moulder>();
register(selector, moulders);
return new MoulderChain(moulders);
}
public List<Node> process(Element element) {
final Document doc = new Document(element.baseUri());
|
final Element copy = JsoupHelper.copy(element);
|
jawher/moulder-j
|
src/main/java/moulder/moulds/SubMoulder.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/MoulderChain.java
// public class MoulderChain {
// private final List<Moulder> moulders;
//
// public MoulderChain(List<Moulder> moulders) {
// this.moulders = moulders;
// }
//
// public MoulderChain add(Moulder... moulders) {
// return add(Arrays.asList(moulders));
// }
//
// public MoulderChain add(List<Moulder> moulders) {
// this.moulders.addAll(moulders);
// return null;
// }
//
// }
//
// Path: src/main/java/moulder/Registry.java
// public class Registry {
//
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// private final List<TemplatorConfig> cfg = new ArrayList<TemplatorConfig>();
//
// /**
// * Registers a number of moulders to be applied to its input element's
// * children returned by the supplied selector
// *
// * @param selector
// * to selected the input element's children to be processed
// * @param templators
// * the moulders to apply on the selected children
// */
// public void register(String selector, List<Moulder> templators) {
// cfg.add(new TemplatorConfig(selector, templators));
// }
//
// /**
// * Return the registered selector/moulders pairs
// *
// * @return
// */
// public List<TemplatorConfig> getConfig() {
// return cfg;
// }
// }
//
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/JsoupHelper.java
// public class JsoupHelper {
//
// public static Element copy(Element e) {
// Element res = new Element(Tag.valueOf(e.tagName()), e.baseUri());
// for (Attribute a: e.attributes()) {
// res.attr(a.getKey(), a.getValue());
// }
// res.html(e.html());
// return res;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Moulder;
import moulder.MoulderChain;
import moulder.Registry;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.JsoupHelper;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
|
package moulder.moulds;
/**
* A moulder that can be configured to select children of its input element an
* apply other moulders on them
*
* @author jawher
*/
public class SubMoulder implements Moulder {
private final Registry registry = new Registry();
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param moulders the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param templators the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
public MoulderChain select(String selector) {
List<Moulder> moulders = new ArrayList<Moulder>();
register(selector, moulders);
return new MoulderChain(moulders);
}
public List<Node> process(Element element) {
final Document doc = new Document(element.baseUri());
final Element copy = JsoupHelper.copy(element);
doc.appendChild(copy);
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/MoulderChain.java
// public class MoulderChain {
// private final List<Moulder> moulders;
//
// public MoulderChain(List<Moulder> moulders) {
// this.moulders = moulders;
// }
//
// public MoulderChain add(Moulder... moulders) {
// return add(Arrays.asList(moulders));
// }
//
// public MoulderChain add(List<Moulder> moulders) {
// this.moulders.addAll(moulders);
// return null;
// }
//
// }
//
// Path: src/main/java/moulder/Registry.java
// public class Registry {
//
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// private final List<TemplatorConfig> cfg = new ArrayList<TemplatorConfig>();
//
// /**
// * Registers a number of moulders to be applied to its input element's
// * children returned by the supplied selector
// *
// * @param selector
// * to selected the input element's children to be processed
// * @param templators
// * the moulders to apply on the selected children
// */
// public void register(String selector, List<Moulder> templators) {
// cfg.add(new TemplatorConfig(selector, templators));
// }
//
// /**
// * Return the registered selector/moulders pairs
// *
// * @return
// */
// public List<TemplatorConfig> getConfig() {
// return cfg;
// }
// }
//
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/JsoupHelper.java
// public class JsoupHelper {
//
// public static Element copy(Element e) {
// Element res = new Element(Tag.valueOf(e.tagName()), e.baseUri());
// for (Attribute a: e.attributes()) {
// res.attr(a.getKey(), a.getValue());
// }
// res.html(e.html());
// return res;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
// Path: src/main/java/moulder/moulds/SubMoulder.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Moulder;
import moulder.MoulderChain;
import moulder.Registry;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.JsoupHelper;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
package moulder.moulds;
/**
* A moulder that can be configured to select children of its input element an
* apply other moulders on them
*
* @author jawher
*/
public class SubMoulder implements Moulder {
private final Registry registry = new Registry();
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param moulders the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param templators the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
public MoulderChain select(String selector) {
List<Moulder> moulders = new ArrayList<Moulder>();
register(selector, moulders);
return new MoulderChain(moulders);
}
public List<Node> process(Element element) {
final Document doc = new Document(element.baseUri());
final Element copy = JsoupHelper.copy(element);
doc.appendChild(copy);
|
for (TemplatorConfig c : registry.getConfig()) {
|
jawher/moulder-j
|
src/main/java/moulder/moulds/SubMoulder.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/MoulderChain.java
// public class MoulderChain {
// private final List<Moulder> moulders;
//
// public MoulderChain(List<Moulder> moulders) {
// this.moulders = moulders;
// }
//
// public MoulderChain add(Moulder... moulders) {
// return add(Arrays.asList(moulders));
// }
//
// public MoulderChain add(List<Moulder> moulders) {
// this.moulders.addAll(moulders);
// return null;
// }
//
// }
//
// Path: src/main/java/moulder/Registry.java
// public class Registry {
//
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// private final List<TemplatorConfig> cfg = new ArrayList<TemplatorConfig>();
//
// /**
// * Registers a number of moulders to be applied to its input element's
// * children returned by the supplied selector
// *
// * @param selector
// * to selected the input element's children to be processed
// * @param templators
// * the moulders to apply on the selected children
// */
// public void register(String selector, List<Moulder> templators) {
// cfg.add(new TemplatorConfig(selector, templators));
// }
//
// /**
// * Return the registered selector/moulders pairs
// *
// * @return
// */
// public List<TemplatorConfig> getConfig() {
// return cfg;
// }
// }
//
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/JsoupHelper.java
// public class JsoupHelper {
//
// public static Element copy(Element e) {
// Element res = new Element(Tag.valueOf(e.tagName()), e.baseUri());
// for (Attribute a: e.attributes()) {
// res.attr(a.getKey(), a.getValue());
// }
// res.html(e.html());
// return res;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Moulder;
import moulder.MoulderChain;
import moulder.Registry;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.JsoupHelper;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
|
package moulder.moulds;
/**
* A moulder that can be configured to select children of its input element an
* apply other moulders on them
*
* @author jawher
*/
public class SubMoulder implements Moulder {
private final Registry registry = new Registry();
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param moulders the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param templators the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
public MoulderChain select(String selector) {
List<Moulder> moulders = new ArrayList<Moulder>();
register(selector, moulders);
return new MoulderChain(moulders);
}
public List<Node> process(Element element) {
final Document doc = new Document(element.baseUri());
final Element copy = JsoupHelper.copy(element);
doc.appendChild(copy);
for (TemplatorConfig c : registry.getConfig()) {
Elements elements = copy.select(c.selector);
for (Element e : elements) {
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/MoulderChain.java
// public class MoulderChain {
// private final List<Moulder> moulders;
//
// public MoulderChain(List<Moulder> moulders) {
// this.moulders = moulders;
// }
//
// public MoulderChain add(Moulder... moulders) {
// return add(Arrays.asList(moulders));
// }
//
// public MoulderChain add(List<Moulder> moulders) {
// this.moulders.addAll(moulders);
// return null;
// }
//
// }
//
// Path: src/main/java/moulder/Registry.java
// public class Registry {
//
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// private final List<TemplatorConfig> cfg = new ArrayList<TemplatorConfig>();
//
// /**
// * Registers a number of moulders to be applied to its input element's
// * children returned by the supplied selector
// *
// * @param selector
// * to selected the input element's children to be processed
// * @param templators
// * the moulders to apply on the selected children
// */
// public void register(String selector, List<Moulder> templators) {
// cfg.add(new TemplatorConfig(selector, templators));
// }
//
// /**
// * Return the registered selector/moulders pairs
// *
// * @return
// */
// public List<TemplatorConfig> getConfig() {
// return cfg;
// }
// }
//
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/JsoupHelper.java
// public class JsoupHelper {
//
// public static Element copy(Element e) {
// Element res = new Element(Tag.valueOf(e.tagName()), e.baseUri());
// for (Attribute a: e.attributes()) {
// res.attr(a.getKey(), a.getValue());
// }
// res.html(e.html());
// return res;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
// Path: src/main/java/moulder/moulds/SubMoulder.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Moulder;
import moulder.MoulderChain;
import moulder.Registry;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.JsoupHelper;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
package moulder.moulds;
/**
* A moulder that can be configured to select children of its input element an
* apply other moulders on them
*
* @author jawher
*/
public class SubMoulder implements Moulder {
private final Registry registry = new Registry();
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param moulders the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
/**
* Registers a number of moulders to be applied to its input element's
* children returned by the supplied selector
*
* @param selector to selected the input element's children to be processed
* @param templators the moulders to apply on the selected children
* @return its self, so that calls to register can be chained
*/
public SubMoulder register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
public MoulderChain select(String selector) {
List<Moulder> moulders = new ArrayList<Moulder>();
register(selector, moulders);
return new MoulderChain(moulders);
}
public List<Node> process(Element element) {
final Document doc = new Document(element.baseUri());
final Element copy = JsoupHelper.copy(element);
doc.appendChild(copy);
for (TemplatorConfig c : registry.getConfig()) {
Elements elements = copy.select(c.selector);
for (Element e : elements) {
|
Collection<Node> oes = MouldersApplier.applyMoulders(c.templators, Arrays.<Node>asList(e));
|
jawher/moulder-j
|
src/test/java/moulder/moulds/ReplacerTest.java
|
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
|
import moulder.Value;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import org.mockito.InOrder;
import java.io.StringReader;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import static org.mockito.Mockito.*;
|
package moulder.moulds;
public class ReplacerTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
|
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
// Path: src/test/java/moulder/moulds/ReplacerTest.java
import moulder.Value;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import org.mockito.InOrder;
import java.io.StringReader;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import static org.mockito.Mockito.*;
package moulder.moulds;
public class ReplacerTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
|
Value<Iterable<Node>> content = mock(Value.class);
|
jawher/moulder-j
|
src/main/java/moulder/moulds/ChildPrepender.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/HtmlValue.java
// public class HtmlValue implements Value<Iterable<Node>> {
// private Value<String> html;
//
// public HtmlValue(String html) {
// this(new SimpleValue<String>(html));
// }
//
// public HtmlValue(Value<String> html) {
// super();
// this.html = html;
// }
//
// public Iterable<Node> get() {
// List<Node> nodes = Jsoup.parseBodyFragment(html.get()).body()
// .childNodes();
// List<Node> copy = new ArrayList<Node>(nodes);
// return copy;
// }
//
// }
|
import moulder.Moulder;
import moulder.Value;
import moulder.values.HtmlValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
|
package moulder.moulds;
/**
* A moulder that prepends content to its input element's children
*
* @author jawher
*
*/
public class ChildPrepender implements Moulder {
private Value<Iterable<Node>> content;
/**
*
* @param content
* the nodes that are to be prepended to the input element's
* children.
*/
public ChildPrepender(Value<Iterable<Node>> content) {
super();
this.content = content;
}
/**
* a convenience version of the {@link #ChildPrepender(moulder.Value)} constructor
* that parses the supplied <code>html</code> string.
*
* @param html
*/
public ChildPrepender(String html) {
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/HtmlValue.java
// public class HtmlValue implements Value<Iterable<Node>> {
// private Value<String> html;
//
// public HtmlValue(String html) {
// this(new SimpleValue<String>(html));
// }
//
// public HtmlValue(Value<String> html) {
// super();
// this.html = html;
// }
//
// public Iterable<Node> get() {
// List<Node> nodes = Jsoup.parseBodyFragment(html.get()).body()
// .childNodes();
// List<Node> copy = new ArrayList<Node>(nodes);
// return copy;
// }
//
// }
// Path: src/main/java/moulder/moulds/ChildPrepender.java
import moulder.Moulder;
import moulder.Value;
import moulder.values.HtmlValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
package moulder.moulds;
/**
* A moulder that prepends content to its input element's children
*
* @author jawher
*
*/
public class ChildPrepender implements Moulder {
private Value<Iterable<Node>> content;
/**
*
* @param content
* the nodes that are to be prepended to the input element's
* children.
*/
public ChildPrepender(Value<Iterable<Node>> content) {
super();
this.content = content;
}
/**
* a convenience version of the {@link #ChildPrepender(moulder.Value)} constructor
* that parses the supplied <code>html</code> string.
*
* @param html
*/
public ChildPrepender(String html) {
|
this(new HtmlValue(html));
|
jawher/moulder-j
|
src/test/java/moulder/moulds/SubMoulderTest.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
|
import moulder.Moulder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
|
package moulder.moulds;
public class SubMoulderTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
Document document = Jsoup
.parseBodyFragment("<html><body><outer a='v'><a>test</a></outer></body></html>");
Element element = document.getElementsByTag("outer").first();
Element subElement = document.getElementsByTag("a").first();
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
// Path: src/test/java/moulder/moulds/SubMoulderTest.java
import moulder.Moulder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
package moulder.moulds;
public class SubMoulderTest extends BaseMoulderTest {
@Test
public void test() throws Exception {
Document document = Jsoup
.parseBodyFragment("<html><body><outer a='v'><a>test</a></outer></body></html>");
Element element = document.getElementsByTag("outer").first();
Element subElement = document.getElementsByTag("a").first();
|
Moulder moulder = mock(Moulder.class);
|
jawher/moulder-j
|
src/main/java/moulder/moulds/IfMoulder.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/SimpleValue.java
// public class SimpleValue<T> implements Value<T> {
// private final T value;
//
// /**
// * @param value the value to be returned by {@link #get()}
// */
// public SimpleValue(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
|
import moulder.Moulder;
import moulder.Value;
import moulder.values.SimpleValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.List;
|
package moulder.moulds;
/**
* A moulder that depending on a boolean value will invoke one of two other
* moulder
*
* @author jawher
*
*/
public class IfMoulder implements Moulder {
private Value<Boolean> condition;
private Moulder thenMoulder;
private Moulder elseMoulder;
/**
*
* @param condition
* A value that returns a boolean value. <code>thenMoulder</code>
* will be used to process the input element if
* <code>condition</code> evaluates to true, else
* <code>elseMoulder</code>
* @param thenMoulder
* @param elseMoulder
*/
public IfMoulder(Value<Boolean> condition, Moulder thenMoulder,
Moulder elseMoulder) {
super();
this.condition = condition;
this.thenMoulder = thenMoulder;
this.elseMoulder = elseMoulder;
}
/**
* A variant of {@link #IfMoulder(moulder.Value, Moulder, Moulder)} that wraps the
* <code>condition</code> argument in a {@link SimpleValue}
*
* @param condition
* @param thenMoulder
* @param elseMoulder
*/
public IfMoulder(boolean condition, Moulder thenMoulder, Moulder elseMoulder) {
super();
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/SimpleValue.java
// public class SimpleValue<T> implements Value<T> {
// private final T value;
//
// /**
// * @param value the value to be returned by {@link #get()}
// */
// public SimpleValue(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
// Path: src/main/java/moulder/moulds/IfMoulder.java
import moulder.Moulder;
import moulder.Value;
import moulder.values.SimpleValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.List;
package moulder.moulds;
/**
* A moulder that depending on a boolean value will invoke one of two other
* moulder
*
* @author jawher
*
*/
public class IfMoulder implements Moulder {
private Value<Boolean> condition;
private Moulder thenMoulder;
private Moulder elseMoulder;
/**
*
* @param condition
* A value that returns a boolean value. <code>thenMoulder</code>
* will be used to process the input element if
* <code>condition</code> evaluates to true, else
* <code>elseMoulder</code>
* @param thenMoulder
* @param elseMoulder
*/
public IfMoulder(Value<Boolean> condition, Moulder thenMoulder,
Moulder elseMoulder) {
super();
this.condition = condition;
this.thenMoulder = thenMoulder;
this.elseMoulder = elseMoulder;
}
/**
* A variant of {@link #IfMoulder(moulder.Value, Moulder, Moulder)} that wraps the
* <code>condition</code> argument in a {@link SimpleValue}
*
* @param condition
* @param thenMoulder
* @param elseMoulder
*/
public IfMoulder(boolean condition, Moulder thenMoulder, Moulder elseMoulder) {
super();
|
this.condition = new SimpleValue<Boolean>(condition);
|
jawher/moulder-j
|
src/main/java/moulder/moulds/Appender.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/HtmlValue.java
// public class HtmlValue implements Value<Iterable<Node>> {
// private Value<String> html;
//
// public HtmlValue(String html) {
// this(new SimpleValue<String>(html));
// }
//
// public HtmlValue(Value<String> html) {
// super();
// this.html = html;
// }
//
// public Iterable<Node> get() {
// List<Node> nodes = Jsoup.parseBodyFragment(html.get()).body()
// .childNodes();
// List<Node> copy = new ArrayList<Node>(nodes);
// return copy;
// }
//
// }
|
import moulder.Moulder;
import moulder.Value;
import moulder.values.HtmlValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.List;
|
package moulder.moulds;
/**
* A moulder that appends content to its input element
*
* @author jawher
*
*/
public class Appender implements Moulder {
private Value<Iterable<Node>> content;
/**
*
* @param content
* the nodes that are to be appended after the input element.
*/
public Appender(Value<Iterable<Node>> content) {
super();
this.content = content;
}
/**
* a convenience version of the {@link #Appender(moulder.Value)} constructor that
* parses the supplied <code>html</code> string.
*
* @param html
*
*/
public Appender(String html) {
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/HtmlValue.java
// public class HtmlValue implements Value<Iterable<Node>> {
// private Value<String> html;
//
// public HtmlValue(String html) {
// this(new SimpleValue<String>(html));
// }
//
// public HtmlValue(Value<String> html) {
// super();
// this.html = html;
// }
//
// public Iterable<Node> get() {
// List<Node> nodes = Jsoup.parseBodyFragment(html.get()).body()
// .childNodes();
// List<Node> copy = new ArrayList<Node>(nodes);
// return copy;
// }
//
// }
// Path: src/main/java/moulder/moulds/Appender.java
import moulder.Moulder;
import moulder.Value;
import moulder.values.HtmlValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.List;
package moulder.moulds;
/**
* A moulder that appends content to its input element
*
* @author jawher
*
*/
public class Appender implements Moulder {
private Value<Iterable<Node>> content;
/**
*
* @param content
* the nodes that are to be appended after the input element.
*/
public Appender(Value<Iterable<Node>> content) {
super();
this.content = content;
}
/**
* a convenience version of the {@link #Appender(moulder.Value)} constructor that
* parses the supplied <code>html</code> string.
*
* @param html
*
*/
public Appender(String html) {
|
this(new HtmlValue(html));
|
jawher/moulder-j
|
src/main/java/moulder/moulds/Remover.java
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/SimpleValue.java
// public class SimpleValue<T> implements Value<T> {
// private final T value;
//
// /**
// * @param value the value to be returned by {@link #get()}
// */
// public SimpleValue(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
|
import moulder.Moulder;
import moulder.Value;
import moulder.values.SimpleValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
|
package moulder.moulds;
/**
* A moulder that removes its input element from the resuling document
*
* @author jawher
*/
public class Remover implements Moulder {
private final Value<Boolean> remove;
/**
* Creates a remover that removes its input element from the resulting
* document
*/
public Remover() {
|
// Path: src/main/java/moulder/Moulder.java
// public interface Moulder {
// /**
// * This is where a moulder can process the input element to generate its
// * result.
// *
// * @param element the element and its associated data to process
// * @return the list of nodes and their associated data that were generated
// * after processing the input element.
// */
// List<Node> process(Element element);
// }
//
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
//
// Path: src/main/java/moulder/values/SimpleValue.java
// public class SimpleValue<T> implements Value<T> {
// private final T value;
//
// /**
// * @param value the value to be returned by {@link #get()}
// */
// public SimpleValue(T value) {
// this.value = value;
// }
//
// public T get() {
// return value;
// }
// }
// Path: src/main/java/moulder/moulds/Remover.java
import moulder.Moulder;
import moulder.Value;
import moulder.values.SimpleValue;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
package moulder.moulds;
/**
* A moulder that removes its input element from the resuling document
*
* @author jawher
*/
public class Remover implements Moulder {
private final Value<Boolean> remove;
/**
* Creates a remover that removes its input element from the resulting
* document
*/
public Remover() {
|
this(new SimpleValue<Boolean>(true));
|
jawher/moulder-j
|
src/test/java/moulder/values/ValueTransformerTest.java
|
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
|
import moulder.Value;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
|
package moulder.values;
public class ValueTransformerTest {
@Test
public void testTransform() {
|
// Path: src/main/java/moulder/Value.java
// public interface Value<T> {
// /**
// *
// * @return the generated value
// */
// T get();
// }
// Path: src/test/java/moulder/values/ValueTransformerTest.java
import moulder.Value;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
package moulder.values;
public class ValueTransformerTest {
@Test
public void testTransform() {
|
Value<String> v = mock(Value.class);
|
jawher/moulder-j
|
src/main/java/moulder/MoulderShop.java
|
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
|
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
|
package moulder;
public class MoulderShop {
private final Registry registry = new Registry();
public MoulderChain select(String selector) {
List<Moulder> moulders = new ArrayList<Moulder>();
registry.register(selector, moulders);
return new MoulderChain(moulders);
}
public MoulderShop register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
public MoulderShop register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
public void process(Document doc) {
|
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
// Path: src/main/java/moulder/MoulderShop.java
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
package moulder;
public class MoulderShop {
private final Registry registry = new Registry();
public MoulderChain select(String selector) {
List<Moulder> moulders = new ArrayList<Moulder>();
registry.register(selector, moulders);
return new MoulderChain(moulders);
}
public MoulderShop register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
public MoulderShop register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
public void process(Document doc) {
|
for (TemplatorConfig c : registry.getConfig()) {
|
jawher/moulder-j
|
src/main/java/moulder/MoulderShop.java
|
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
|
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
|
package moulder;
public class MoulderShop {
private final Registry registry = new Registry();
public MoulderChain select(String selector) {
List<Moulder> moulders = new ArrayList<Moulder>();
registry.register(selector, moulders);
return new MoulderChain(moulders);
}
public MoulderShop register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
public MoulderShop register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
public void process(Document doc) {
for (TemplatorConfig c : registry.getConfig()) {
Elements elements = doc.select(c.selector);
for (Element e : elements) {
|
// Path: src/main/java/moulder/Registry.java
// public static final class TemplatorConfig {
// public final String selector;
// public final List<Moulder> templators;
//
// public TemplatorConfig(String selector, List<Moulder> templators) {
// this.selector = selector;
// this.templators = templators;
// }
// }
//
// Path: src/main/java/moulder/moulds/helpers/MouldersApplier.java
// public class MouldersApplier {
// public static Collection<Node> applyMoulder(Moulder moulder, Collection<Node> nodes) {
// List<Node> res = new ArrayList<Node>();
// for(Node node: nodes) {
// if(node instanceof Element) {
// res.addAll(moulder.process((Element) node));
// } else {
// res.add(node);
// }
// }
// return res;
// }
// public static Collection<Node> applyMoulders(Collection<Moulder> moulders, Collection<Node> nodes) {
// if(moulders.isEmpty()) {
// return nodes;
// } else {
// Collection<Node> workingSet = new ArrayList<Node>(nodes);
// for(Moulder moulder: moulders) {
// workingSet = applyMoulder(moulder, workingSet);
// }
// return workingSet;
// }
// }
// }
// Path: src/main/java/moulder/MoulderShop.java
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import moulder.Registry.TemplatorConfig;
import moulder.moulds.helpers.MouldersApplier;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
package moulder;
public class MoulderShop {
private final Registry registry = new Registry();
public MoulderChain select(String selector) {
List<Moulder> moulders = new ArrayList<Moulder>();
registry.register(selector, moulders);
return new MoulderChain(moulders);
}
public MoulderShop register(String selector, Moulder... moulders) {
return register(selector, Arrays.asList(moulders));
}
public MoulderShop register(String selector, List<Moulder> templators) {
registry.register(selector, templators);
return this;
}
public void process(Document doc) {
for (TemplatorConfig c : registry.getConfig()) {
Elements elements = doc.select(c.selector);
for (Element e : elements) {
|
Collection<Node> oes = MouldersApplier.applyMoulders(c.templators, Arrays.<Node>asList(e));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.